├── .github ├── codeql │ └── config.yml ├── dependabot.yml └── workflows │ ├── main.yml │ ├── docs.yml │ ├── release.yml │ ├── it-tests.yml │ └── codeql-analysis.yml ├── .prettierignore ├── .dir-locals.el ├── .yarnrc.yml ├── tsconfig.build.json ├── .vscode ├── extensions.json └── settings.json ├── .prettierrc.json ├── .editorconfig ├── .gitignore ├── jest.config.ts ├── eslint.config.ts ├── package.json ├── README.md ├── tests └── it │ ├── trino.yml │ └── client.spec.ts ├── tsconfig.json ├── LICENSE └── src └── index.ts /.github/codeql/config.yml: -------------------------------------------------------------------------------- 1 | name: "CodeQL config" 2 | 3 | paths: 4 | - src 5 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | **/.git 2 | **/.svn 3 | **/.hg 4 | **/node_modules 5 | **/.yarn 6 | -------------------------------------------------------------------------------- /.dir-locals.el: -------------------------------------------------------------------------------- 1 | ((typescript-mode . ((jest-test-command-string "yarn %s jest %s %s")))) 2 | -------------------------------------------------------------------------------- /.yarnrc.yml: -------------------------------------------------------------------------------- 1 | nodeLinker: node-modules 2 | 3 | yarnPath: .yarn/releases/yarn-3.2.1.cjs 4 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["tests/**/*.ts", "dist"] 4 | } 5 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "dbaeumer.vscode-eslint", 4 | "esbenp.prettier-vscode" 5 | ] 6 | } -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "bracketSpacing": false, 3 | "singleQuote": true, 4 | "trailingComma": "es5", 5 | "arrowParens": "avoid" 6 | } 7 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "search.exclude": { 3 | "**/.yarn": true, 4 | }, 5 | "typescript.enablePromptUseWorkspaceTsdk": true, 6 | "jest.jestCommandLine": "yarn test:it" 7 | } -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | 7 | [*.{js,json,yml}] 8 | charset = utf-8 9 | indent_style = space 10 | indent_size = 2 11 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | # Maintain dependencies for GitHub Actions 4 | - package-ecosystem: "github-actions" 5 | directory: "/" 6 | schedule: 7 | interval: "daily" 8 | # Maintain dependencies for npm 9 | - package-ecosystem: "npm" 10 | directory: "/" 11 | schedule: 12 | interval: "daily" 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .idea 3 | 4 | .log 5 | dist 6 | docs 7 | *.tmp 8 | 9 | .yarn/* 10 | !.yarn/patches 11 | !.yarn/plugins 12 | !.yarn/releases 13 | !.yarn/sdks 14 | !.yarn/versions 15 | 16 | # Swap the comments on the following lines if you don't wish to use zero-installs 17 | # Documentation here: https://yarnpkg.com/features/zero-installs 18 | #!.yarn/cache 19 | .pnp.* 20 | 21 | node_modules 22 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Main 2 | 3 | on: [pull_request, push] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - name: Checkout 10 | uses: actions/checkout@v5 11 | - name: Install Dependencies 12 | run: yarn install --frozen-lockfile 13 | - name: Lint 14 | run: yarn test:lint 15 | - name: Build 16 | run: yarn build 17 | -------------------------------------------------------------------------------- /jest.config.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * For a detailed explanation regarding each configuration property, visit: 3 | * https://jestjs.io/docs/configuration 4 | */ 5 | 6 | import type {Config} from 'jest'; 7 | 8 | const config: Config = { 9 | clearMocks: true, 10 | coverageProvider: 'v8', 11 | moduleFileExtensions: ['js', 'ts'], 12 | preset: 'ts-jest', 13 | testEnvironment: 'node', 14 | verbose: true, 15 | }; 16 | 17 | export default config; 18 | -------------------------------------------------------------------------------- /.github/workflows/docs.yml: -------------------------------------------------------------------------------- 1 | name: Build docs and Upload to GitHub Pages 2 | on: 3 | push: 4 | branches: 5 | - main 6 | permissions: 7 | contents: write 8 | jobs: 9 | build-and-deploy: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Checkout 13 | uses: actions/checkout@v5 14 | - name: Install Dependencies 15 | run: yarn install --frozen-lockfile 16 | - name: Build 17 | run: yarn typedoc --out docs src/index.ts 18 | - name: Deploy 19 | uses: JamesIves/github-pages-deploy-action@v4 20 | with: 21 | branch: gh-pages 22 | folder: docs 23 | -------------------------------------------------------------------------------- /eslint.config.ts: -------------------------------------------------------------------------------- 1 | import eslint from '@eslint/js'; 2 | import tseslint from 'typescript-eslint'; 3 | import jest from 'eslint-plugin-jest'; 4 | 5 | export default tseslint.config( 6 | { 7 | ignores: ['dist'], 8 | }, 9 | jest.configs['flat/recommended'], 10 | eslint.configs.recommended, 11 | ...tseslint.configs.recommended, 12 | { 13 | rules: { 14 | '@typescript-eslint/no-explicit-any': ['warn'], 15 | 'no-unused-vars': 'off', 16 | '@typescript-eslint/no-unused-vars': [ 17 | 'warn', 18 | { 19 | argsIgnorePattern: '^_', 20 | varsIgnorePattern: '^_', 21 | caughtErrorsIgnorePattern: '^_', 22 | }, 23 | ], 24 | }, 25 | } 26 | ); 27 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Publish Package to npmjs 2 | on: 3 | release: 4 | types: [created] 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v5 10 | # Setup .npmrc file to publish to npm 11 | - uses: actions/setup-node@v6 12 | with: 13 | node-version: "16.x" 14 | registry-url: "https://registry.npmjs.org" 15 | - name: Install Dependencies 16 | run: yarn install --frozen-lockfile 17 | # Writes token to .yarnrc.yml 18 | - name: Setup NPM auth token 19 | run: | 20 | echo npmAuthToken: "${NODE_AUTH_TOKEN}" >> ./.yarnrc.yml 21 | env: 22 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} 23 | - run: yarn publish 24 | -------------------------------------------------------------------------------- /.github/workflows/it-tests.yml: -------------------------------------------------------------------------------- 1 | name: IT tests 2 | on: 3 | push: 4 | branches: 5 | - main 6 | jobs: 7 | it-tests: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - name: Checkout 11 | uses: actions/checkout@v5 12 | - name: Install Dependencies 13 | run: yarn install --frozen-lockfile 14 | - name: Create k8s Kind Cluster 15 | uses: helm/kind-action@v1.13.0 16 | with: 17 | cluster_name: trino 18 | - name: Deploy trino 19 | run: kubectl apply -f tests/it/trino.yml 20 | - name: Wait for pods to be ready 21 | run: kubectl wait --for=condition=ready pods -n trino-system --all --timeout=120s 22 | - name: Test 23 | run: | 24 | kubectl -n trino-system port-forward svc/trino 8080:8080 > /dev/null & 25 | sleep 10 # give it a little bit more time to start 26 | yarn test:it --testTimeout=60000 27 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.9", 3 | "name": "trino-client", 4 | "description": "Trino client library", 5 | "author": { 6 | "name": "Trino Javascript contributors", 7 | "email": "general@trino.io", 8 | "url": "https://github.com/trinodb/trino-js-client/graphs/contributors" 9 | }, 10 | "keywords": [ 11 | "trino", 12 | "trinodb", 13 | "client" 14 | ], 15 | "repository": { 16 | "type": "git", 17 | "url": "https://github.com/trinodb/trino-js-client.git" 18 | }, 19 | "homepage": "https://trinodb.github.io/trino-js-client", 20 | "bugs": { 21 | "url": "https://github.com/trinodb/trino-js-client/issues" 22 | }, 23 | "main": "dist/index.js", 24 | "types": "dist/index.d.ts", 25 | "packageManager": "yarn@3.2.1", 26 | "license": "Apache-2.0", 27 | "files": [ 28 | "dist" 29 | ], 30 | "devDependencies": { 31 | "@eslint/js": "9.25.1", 32 | "@types/eslint__js": "^8.42.3", 33 | "@types/jest": "^30.0.0", 34 | "@types/node": "^24.2.0", 35 | "eslint": "9.39.1", 36 | "eslint-plugin-jest": "^29.0.1", 37 | "jest": "^30.0.5", 38 | "jiti": "^2.4.0", 39 | "prettier": "^3.0.0", 40 | "ts-jest": "^29.2.5", 41 | "ts-node": "^10.9.2", 42 | "typedoc": "^0.28.3", 43 | "typescript": "^5.6.3", 44 | "typescript-eslint": "^8.14.0" 45 | }, 46 | "dependencies": { 47 | "axios": "1.13.2" 48 | }, 49 | "scripts": { 50 | "build": "tsc --project tsconfig.build.json", 51 | "test:it": "jest --testPathPatterns tests/it", 52 | "test:lint": "eslint . --flag unstable_ts_config", 53 | "publish": "yarn build && yarn npm publish" 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: ["main"] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: ["main"] 20 | schedule: 21 | - cron: "32 10 * * 0" 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: ["typescript"] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] 37 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support 38 | 39 | steps: 40 | - name: Checkout repository 41 | uses: actions/checkout@v5 42 | 43 | # Initializes the CodeQL tools for scanning. 44 | - name: Initialize CodeQL 45 | uses: github/codeql-action/init@v4 46 | with: 47 | languages: ${{ matrix.language }} 48 | # If you wish to specify custom queries, you can do so here or in a config file. 49 | # By default, queries listed here will override any specified in a config file. 50 | # Prefix the list here with "+" to use these queries and those in the config file. 51 | 52 | # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs 53 | # queries: security-extended,security-and-quality 54 | 55 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 56 | # If this step fails, then you should remove it and run the build manually (see below) 57 | - name: Autobuild 58 | uses: github/codeql-action/autobuild@v4 59 | 60 | # ℹ️ Command-line programs to run using the OS shell. 61 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun 62 | 63 | # If the Autobuild fails above, remove it and uncomment the following three lines. 64 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. 65 | 66 | # - run: | 67 | # echo "Run, Build Application using script" 68 | # ./location_of_script_within_repo/buildscript.sh 69 | 70 | - name: Perform CodeQL Analysis 71 | uses: github/codeql-action/analyze@v4 72 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # trino-js-client 2 | 3 | A [Trino](https://trino.io) client for [Node.js](https://nodejs.org/). 4 | 5 | Join us on [Trino Slack](https://trino.io/slack) in 6 | [#core-dev](https://trinodb.slack.com/archives/C07ABNN828M) to discuss and help 7 | this project. 8 | 9 | [![@latest](https://img.shields.io/npm/v/trino-client.svg)](https://www.npmjs.com/package/trino-client) 10 | ![it-tests](https://github.com/trinodb/trino-js-client/actions/workflows/it-tests.yml/badge.svg) 11 | ![license](https://img.shields.io/github/license/trinodb/trino-js-client) 12 | 13 | ## Features 14 | 15 | - Connections over HTTP or HTTPS 16 | - Supports HTTP Basic Authentication 17 | - Per-query user information for access control 18 | 19 | ## Requirements 20 | 21 | - Node 12 or newer. 22 | - Trino 0.16x or newer. 23 | 24 | ## Install 25 | 26 | `npm install trino-client` or `yarn add trino-client` 27 | 28 | ## Usage 29 | 30 | For additional info on all available methods and types [have a look at the 31 | `API` documentation](https://trinodb.github.io/trino-js-client/). 32 | 33 | ### Create a Trino client 34 | 35 | ```typescript 36 | const trino: Trino = Trino.create({ 37 | server: 'http://localhost:8080', 38 | catalog: 'tpcds', 39 | schema: 'sf100000', 40 | auth: new BasicAuth('test'), 41 | }); 42 | ``` 43 | 44 | ### Submit a query 45 | 46 | ```typescript 47 | const iter: Iterator = await trino.query( 48 | 'select * from customer limit 100' 49 | ); 50 | ``` 51 | 52 | ### Iterate through the query results 53 | 54 | ```typescript 55 | for await (const queryResult of iter) { 56 | console.log(queryResult.data); 57 | } 58 | ``` 59 | 60 | ### Alternative: map and aggregate the data 61 | 62 | ```typescript 63 | const data: QueryData[] = await iter 64 | .map(r => r.data ?? []) 65 | .fold([], (row, acc) => [...acc, ...row]); 66 | ``` 67 | 68 | ## Examples 69 | 70 | More usage examples can be found in the 71 | [integration tests](https://github.com/trinodb/trino-js-client/blob/main/tests/it/client.spec.ts). 72 | 73 | ## Build 74 | 75 | Use the following commands to build the project locally with your modifications, 76 | and in preparation to contribute a pull request. 77 | 78 | Requirements: 79 | 80 | * yarn 81 | 82 | Install dependencies: 83 | 84 | ```shell 85 | yarn install --frozen-lockfile 86 | ``` 87 | 88 | Lint the source code: 89 | 90 | ```shell 91 | yarn test:lint 92 | ``` 93 | 94 | Build: 95 | 96 | ```shell 97 | yarn build 98 | ``` 99 | 100 | A successful build run does not produce any message on the terminal. 101 | 102 | ## Integration test 103 | 104 | Integration tests run against a Trino server running on your workstation. 105 | 106 | Requirements: 107 | 108 | * [kind](https://kind.sigs.k8s.io/ ) 109 | * [kubectl](https://kubernetes.io/docs/reference/kubectl/) 110 | 111 | Create a cluster: 112 | 113 | ```shell 114 | kind create cluster 115 | ``` 116 | 117 | Deploy Trino: 118 | 119 | ```shell 120 | kubectl apply -f tests/it/trino.yml 121 | ``` 122 | 123 | Wait for pods to be ready: 124 | 125 | ```shell 126 | kubectl wait --for=condition=ready pods -n trino-system --all --timeout=120s 127 | ``` 128 | 129 | Ensure Trino is running and available on port `8080`. Run the following 130 | command in a separate terminal: 131 | 132 | ```shell 133 | kubectl -n trino-system port-forward svc/trino 8080:8080 134 | ``` 135 | 136 | Run tests: 137 | 138 | ```shell 139 | yarn test:it --testTimeout=60000 140 | ``` 141 | 142 | Output should look similar to the following: 143 | 144 | ```text 145 | PASS tests/it/client.spec.ts 146 | trino 147 | ✓ exhaust query results (1567 ms) 148 | ✓ close running query (200 ms) 149 | ✓ cancel running query (17 ms) 150 | ✓ get query info (1 ms) 151 | ✓ client extra header propagation 152 | ✓ query request header propagation (88 ms) 153 | ✓ QueryResult has error info 154 | ✓ QueryInfo has failure info (1 ms) 155 | ✓ prepare statement (98 ms) 156 | ✓ multiple prepare statement (432 ms) 157 | 158 | Test Suites: 1 passed, 1 total 159 | Tests: 10 passed, 10 total 160 | Snapshots: 0 total 161 | Time: 3.457 s 162 | Ran all test suites matching /tests\/it/i. 163 | ``` 164 | 165 | Remove the cluster: 166 | 167 | ```shell 168 | kind delete cluster 169 | ``` 170 | 171 | ## Contributing 172 | 173 | Follow the [Trino contribution guidelines](https://trino.io/development/process) 174 | and contact us on Slack and GitHub. 175 | 176 | Copyright 177 | [Trino JS Client contributors](https://github.com/trinodb/trino-js-client/graphs/contributors) 2022-present 178 | 179 | ## Releasing 180 | 181 | Releases are automated with GitHub Actions and only require a pull request 182 | that updates the version in `package.json`. For example, see 183 | [PR 723](https://github.com/trinodb/trino-js-client/pull/723) 184 | -------------------------------------------------------------------------------- /tests/it/trino.yml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: trino-system 5 | --- 6 | apiVersion: v1 7 | kind: ServiceAccount 8 | metadata: 9 | name: trino 10 | namespace: trino-system 11 | --- 12 | apiVersion: v1 13 | kind: ConfigMap 14 | metadata: 15 | name: trino-catalog 16 | namespace: trino-system 17 | labels: 18 | app: trino 19 | role: catalogs 20 | data: 21 | tpch.properties: | 22 | connector.name=tpch 23 | tpch.splits-per-node=4 24 | tpcds.properties: | 25 | connector.name=tpcds 26 | tpcds.splits-per-node=4 27 | --- 28 | apiVersion: v1 29 | kind: ConfigMap 30 | metadata: 31 | name: trino-coordinator 32 | namespace: trino-system 33 | labels: 34 | app: trino 35 | component: coordinator 36 | data: 37 | node.properties: | 38 | node.environment=dev 39 | node.data-dir=/data/trino 40 | plugin.dir=/usr/lib/trino/plugin 41 | 42 | jvm.config: | 43 | -server 44 | -Xmx2G 45 | -XX:+UseG1GC 46 | -XX:+UnlockDiagnosticVMOptions 47 | -XX:G1NumCollectionsKeepPinned=10000000 48 | 49 | config.properties: | 50 | coordinator=true 51 | node-scheduler.include-coordinator=false 52 | http-server.http.port=8080 53 | discovery.type=airlift_discovery 54 | discovery-server.enabled=true 55 | discovery.uri=http://localhost:8080 56 | 57 | log.properties: | 58 | io.trino=INFO 59 | --- 60 | apiVersion: v1 61 | kind: ConfigMap 62 | metadata: 63 | name: trino-worker 64 | namespace: trino-system 65 | labels: 66 | app: trino 67 | component: worker 68 | data: 69 | node.properties: | 70 | node.environment=dev 71 | node.data-dir=/data/trino 72 | plugin.dir=/usr/lib/trino/plugin 73 | 74 | jvm.config: | 75 | -server 76 | -Xmx2G 77 | -XX:+UseG1GC 78 | -XX:+UnlockDiagnosticVMOptions 79 | -XX:G1NumCollectionsKeepPinned=10000000 80 | 81 | config.properties: | 82 | coordinator=false 83 | http-server.http.port=8080 84 | discovery.type=airlift_discovery 85 | discovery.uri=http://trino:8080 86 | 87 | log.properties: | 88 | io.trino=INFO 89 | --- 90 | apiVersion: apps/v1 91 | kind: Deployment 92 | metadata: 93 | name: trino-coordinator 94 | namespace: trino-system 95 | labels: 96 | app: trino 97 | component: coordinator 98 | spec: 99 | selector: 100 | matchLabels: 101 | app: trino 102 | component: coordinator 103 | template: 104 | metadata: 105 | labels: 106 | app: trino 107 | component: coordinator 108 | spec: 109 | serviceAccountName: trino 110 | securityContext: 111 | fsGroup: 9999 112 | volumes: 113 | - name: config-volume 114 | configMap: 115 | name: trino-coordinator 116 | - name: catalog-volume 117 | configMap: 118 | name: trino-catalog 119 | containers: 120 | - name: trino-coordinator 121 | image: "trinodb/trino:latest" 122 | imagePullPolicy: IfNotPresent 123 | volumeMounts: 124 | - mountPath: /etc/trino 125 | name: config-volume 126 | - mountPath: /etc/trino/catalog 127 | name: catalog-volume 128 | ports: 129 | - name: http 130 | containerPort: 8080 131 | protocol: TCP 132 | livenessProbe: 133 | httpGet: 134 | path: /v1/info 135 | port: http 136 | readinessProbe: 137 | httpGet: 138 | path: /v1/info 139 | port: http 140 | resources: 141 | requests: 142 | cpu: "100m" 143 | memory: 512Mi 144 | --- 145 | apiVersion: apps/v1 146 | kind: Deployment 147 | metadata: 148 | name: trino-worker 149 | namespace: trino-system 150 | labels: 151 | app: trino 152 | component: worker 153 | spec: 154 | replicas: 1 155 | selector: 156 | matchLabels: 157 | app: trino 158 | component: worker 159 | template: 160 | metadata: 161 | labels: 162 | app: trino 163 | component: worker 164 | spec: 165 | serviceAccountName: trino 166 | volumes: 167 | - name: config-volume 168 | configMap: 169 | name: trino-worker 170 | - name: catalog-volume 171 | configMap: 172 | name: trino-catalog 173 | securityContext: 174 | fsGroup: 9999 175 | containers: 176 | - name: trino-worker 177 | image: "trinodb/trino:latest" 178 | imagePullPolicy: IfNotPresent 179 | volumeMounts: 180 | - mountPath: /etc/trino 181 | name: config-volume 182 | - mountPath: /etc/trino/catalog 183 | name: catalog-volume 184 | ports: 185 | - name: http 186 | containerPort: 8080 187 | protocol: TCP 188 | livenessProbe: 189 | httpGet: 190 | path: /v1/info 191 | port: http 192 | readinessProbe: 193 | httpGet: 194 | path: /v1/info 195 | port: http 196 | resources: 197 | requests: 198 | cpu: "100m" 199 | memory: 512Mi 200 | --- 201 | apiVersion: v1 202 | kind: Service 203 | metadata: 204 | name: trino 205 | namespace: trino-system 206 | labels: 207 | app: trino 208 | spec: 209 | type: ClusterIP 210 | ports: 211 | - port: 8080 212 | targetPort: http 213 | protocol: TCP 214 | name: http 215 | selector: 216 | app: trino 217 | component: coordinator 218 | -------------------------------------------------------------------------------- /tests/it/client.spec.ts: -------------------------------------------------------------------------------- 1 | import {BasicAuth, QueryData, Trino} from '../../src'; 2 | 3 | const allCustomerQuery = 'select * from customer'; 4 | const limit = 1; 5 | const singleCustomerQuery = `select * from customer limit ${limit}`; 6 | const useSchemaQuery = 'use tpcds.sf100000'; 7 | const prepareListCustomerQuery = 8 | 'prepare list_customers from select * from customer limit ?'; 9 | const listCustomersQuery = `execute list_customers using ${limit}`; 10 | const prepareListSalesQuery = 11 | 'prepare list_sales from select * from web_sales limit ?'; 12 | const listSalesQuery = `execute list_sales using ${limit}`; 13 | 14 | describe('trino', () => { 15 | test.concurrent('exhaust query results', async () => { 16 | const trino = Trino.create({ 17 | catalog: 'tpcds', 18 | schema: 'sf100000', 19 | auth: new BasicAuth('test'), 20 | }); 21 | 22 | const iter = await trino.query(singleCustomerQuery); 23 | const data = await iter 24 | .map(r => r.data ?? []) 25 | .fold([], (row, acc) => [...acc, ...row]); 26 | 27 | expect(data).toHaveLength(limit); 28 | }); 29 | 30 | test.concurrent('close running query', async () => { 31 | const trino = Trino.create({ 32 | catalog: 'tpcds', 33 | schema: 'sf100000', 34 | auth: new BasicAuth('test'), 35 | }); 36 | const query = await trino.query(allCustomerQuery); 37 | const qr = await query.next(); 38 | await trino.cancel(qr.value.id); 39 | 40 | const info = await trino.queryInfo(qr.value.id); 41 | 42 | expect(info.state).toBe('FAILED'); 43 | }); 44 | 45 | test.concurrent('cancel running query', async () => { 46 | const trino = Trino.create({ 47 | catalog: 'tpcds', 48 | schema: 'sf100000', 49 | auth: new BasicAuth('test'), 50 | }); 51 | const query = await trino.query(allCustomerQuery); 52 | const qr = await query.next(); 53 | 54 | await trino.cancel(qr.value.id); 55 | const info = await trino.queryInfo(qr.value.id); 56 | 57 | expect(info.state).toBe('FAILED'); 58 | }); 59 | 60 | test.concurrent('get query info', async () => { 61 | const trino = Trino.create({ 62 | catalog: 'tpcds', 63 | schema: 'sf100000', 64 | auth: new BasicAuth('test'), 65 | }); 66 | const query = await trino.query(singleCustomerQuery); 67 | const qr = await query.next(); 68 | await trino.cancel(qr.value.id); 69 | 70 | const info = await trino.queryInfo(qr.value.id); 71 | expect(info.query).toBe(singleCustomerQuery); 72 | }); 73 | 74 | test.concurrent('client extra header propagation', async () => { 75 | const source = 'new-client'; 76 | const trino = Trino.create({ 77 | catalog: 'tpcds', 78 | schema: 'sf100000', 79 | auth: new BasicAuth('test'), 80 | extraHeaders: {'X-Trino-Source': source}, 81 | }); 82 | 83 | const query = await trino.query(singleCustomerQuery); 84 | const qr = await query.next(); 85 | 86 | const info: any = await trino.queryInfo(qr.value.id); 87 | expect(info.session.source).toBe(source); 88 | }); 89 | 90 | test.concurrent('query request header propagation', async () => { 91 | const trino = Trino.create({catalog: 'tpcds', auth: new BasicAuth('test')}); 92 | const query = await trino.query(useSchemaQuery); 93 | await query.next(); 94 | 95 | const sqr = await trino.query(singleCustomerQuery); 96 | const qr = await sqr.next(); 97 | await trino.cancel(qr.value.id); 98 | 99 | const info = await trino.queryInfo(qr.value.id); 100 | expect(info.query).toBe(singleCustomerQuery); 101 | }); 102 | 103 | test.concurrent('QueryResult has error info', async () => { 104 | const trino = Trino.create({ 105 | catalog: 'tpcds', 106 | schema: 'sf100000', 107 | auth: new BasicAuth('test'), 108 | }); 109 | const sqr = await trino.query('select * from foobar where id = -1'); 110 | const qr = await sqr.next(); 111 | expect(qr.value.error).toBeDefined(); 112 | expect(qr.value.error?.message).toBe( 113 | "line 1:15: Table 'tpcds.sf100000.foobar' does not exist" 114 | ); 115 | 116 | await trino.cancel(qr.value.id); 117 | }); 118 | 119 | test.concurrent('QueryInfo has failure info', async () => { 120 | const trino = Trino.create({ 121 | catalog: 'tpcds', 122 | schema: 'sf100000', 123 | auth: new BasicAuth('test'), 124 | }); 125 | 126 | const sqr = await trino.query('select * from foobar where id = -1'); 127 | const qr = await sqr.next(); 128 | await trino.cancel(qr.value.id); 129 | 130 | const info = await trino.queryInfo(qr.value.id); 131 | expect(info.state).toBe('FAILED'); 132 | expect(info.failureInfo?.message).toBe( 133 | "line 1:15: Table 'tpcds.sf100000.foobar' does not exist" 134 | ); 135 | }); 136 | 137 | test.concurrent('prepare statement', async () => { 138 | const trino = Trino.create({ 139 | catalog: 'tpcds', 140 | schema: 'sf100000', 141 | auth: new BasicAuth('test'), 142 | }); 143 | 144 | await trino.query(prepareListCustomerQuery).then(qr => qr.next()); 145 | 146 | const iter = await trino.query(listCustomersQuery); 147 | const data = await iter.fold([], (row, acc) => [ 148 | ...acc, 149 | ...(row.data ?? []), 150 | ]); 151 | expect(data).toHaveLength(limit); 152 | }); 153 | 154 | test.concurrent('multiple prepare statement', async () => { 155 | const trino = Trino.create({ 156 | catalog: 'tpcds', 157 | schema: 'sf100000', 158 | auth: new BasicAuth('test'), 159 | }); 160 | 161 | await trino.query(prepareListCustomerQuery).then(qr => qr.next()); 162 | await trino.query(prepareListSalesQuery).then(qr => qr.next()); 163 | 164 | const customersIter = await trino.query(listCustomersQuery); 165 | const customers = await customersIter.fold([], (row, acc) => [ 166 | ...acc, 167 | ...(row.data ?? []), 168 | ]); 169 | expect(customers).toHaveLength(limit); 170 | 171 | const salesIter = await trino.query(listSalesQuery); 172 | const sales = await salesIter.fold([], (row, acc) => [ 173 | ...acc, 174 | ...(row.data ?? []), 175 | ]); 176 | expect(sales).toHaveLength(limit); 177 | }); 178 | }); 179 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, 15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | // "jsx": "preserve", /* Specify what JSX code is generated. */ 17 | // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ 22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ 26 | 27 | /* Modules */ 28 | "module": "commonjs" /* Specify what module code is generated. */, 29 | "rootDir": "./src" /* Specify the root folder within your source files. */, 30 | // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ 31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ 35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ 38 | // "resolveJsonModule": true, /* Enable importing .json files. */ 39 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ 40 | 41 | /* JavaScript Support */ 42 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ 43 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 44 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ 45 | 46 | /* Emit */ 47 | "declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */, 48 | // "declarationMap": true /* Create sourcemaps for d.ts files. */, 49 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 50 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 51 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ 52 | "outDir": "dist" /* Specify an output folder for all emitted files. */, 53 | // "removeComments": true, /* Disable emitting comments. */ 54 | // "noEmit": true, /* Disable emitting files from a compilation. */ 55 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 56 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ 57 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 58 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 59 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 60 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 61 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 62 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 63 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 64 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ 65 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ 66 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 67 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ 68 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 69 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 70 | 71 | /* Interop Constraints */ 72 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 73 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 74 | "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, 75 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 76 | "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, 77 | 78 | /* Type Checking */ 79 | "strict": true /* Enable all strict type-checking options. */, 80 | "noImplicitAny": true /* Enable error reporting for expressions and declarations with an implied 'any' type. */, 81 | "strictNullChecks": true /* When type checking, take into account 'null' and 'undefined'. */, 82 | "strictFunctionTypes": true /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */, 83 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ 84 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 85 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ 86 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ 87 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 88 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ 89 | "noUnusedParameters": true /* Raise an error when a function parameter isn't read. */, 90 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 91 | "noImplicitReturns": true /* Enable error reporting for codepaths that do not explicitly return in a function. */, 92 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 93 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ 94 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 95 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ 96 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 97 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 98 | 99 | /* Completeness */ 100 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 101 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 102 | }, 103 | "include": ["src"] 104 | } 105 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Licensed under the Apache License, Version 2.0 (the "License"); 190 | you may not use this file except in compliance with the License. 191 | You may obtain a copy of the License at 192 | 193 | http://www.apache.org/licenses/LICENSE-2.0 194 | 195 | Unless required by applicable law or agreed to in writing, software 196 | distributed under the License is distributed on an "AS IS" BASIS, 197 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 198 | See the License for the specific language governing permissions and 199 | limitations under the License. 200 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import axios, {AxiosRequestConfig, RawAxiosRequestHeaders} from 'axios'; 2 | import * as https from 'https'; 3 | import * as tls from 'tls'; 4 | 5 | const DEFAULT_SERVER = 'http://localhost:8080'; 6 | const DEFAULT_SOURCE = 'trino-js-client'; 7 | const DEFAULT_USER = process.env.USER; 8 | 9 | // Trino headers 10 | const TRINO_HEADER_PREFIX = 'X-Trino-'; 11 | const TRINO_PREPARED_STATEMENT_HEADER = 12 | TRINO_HEADER_PREFIX + 'Prepared-Statement'; 13 | const TRINO_ADDED_PREPARE_HEADER = TRINO_HEADER_PREFIX + 'Added-Prepare'; 14 | const TRINO_USER_HEADER = TRINO_HEADER_PREFIX + 'User'; 15 | const TRINO_SOURCE_HEADER = TRINO_HEADER_PREFIX + 'Source'; 16 | const TRINO_CATALOG_HEADER = TRINO_HEADER_PREFIX + 'Catalog'; 17 | const TRINO_SCHEMA_HEADER = TRINO_HEADER_PREFIX + 'Schema'; 18 | const TRINO_SESSION_HEADER = TRINO_HEADER_PREFIX + 'Session'; 19 | const TRINO_SET_CATALOG_HEADER = TRINO_HEADER_PREFIX + 'Set-Catalog'; 20 | const TRINO_SET_SCHEMA_HEADER = TRINO_HEADER_PREFIX + 'Set-Schema'; 21 | const TRINO_SET_PATH_HEADER = TRINO_HEADER_PREFIX + 'Set-Path'; 22 | const TRINO_SET_SESSION_HEADER = TRINO_HEADER_PREFIX + 'Set-Session'; 23 | const TRINO_CLEAR_SESSION_HEADER = TRINO_HEADER_PREFIX + 'Clear-Session'; 24 | const TRINO_SET_ROLE_HEADER = TRINO_HEADER_PREFIX + 'Set-Role'; 25 | const TRINO_EXTRA_CREDENTIAL_HEADER = TRINO_HEADER_PREFIX + 'Extra-Credential'; 26 | 27 | export type AuthType = string; 28 | 29 | export interface Auth { 30 | readonly type: AuthType; 31 | } 32 | 33 | export class BasicAuth implements Auth { 34 | readonly type: AuthType = 'basic'; 35 | constructor(readonly username: string, readonly password?: string) {} 36 | } 37 | 38 | export type Session = {[key: string]: string}; 39 | 40 | export type ExtraCredential = {[key: string]: string}; 41 | 42 | const encodeAsString = (obj: {[key: string]: string}) => { 43 | return Object.entries(obj) 44 | .map(([key, value]) => `${key}=${value}`) 45 | .join(','); 46 | }; 47 | 48 | export type RequestHeaders = { 49 | [key: string]: string; 50 | } 51 | 52 | export type SecureContextOptions = tls.SecureContextOptions & { 53 | readonly rejectUnauthorized?: boolean; 54 | }; 55 | 56 | export type ConnectionOptions = { 57 | readonly server?: string; 58 | readonly source?: string; 59 | readonly catalog?: string; 60 | readonly schema?: string; 61 | readonly auth?: Auth; 62 | readonly session?: Session; 63 | readonly extraCredential?: ExtraCredential; 64 | readonly ssl?: SecureContextOptions; 65 | readonly extraHeaders?: RequestHeaders; 66 | }; 67 | 68 | export type QueryStage = { 69 | stageId: string; 70 | state: string; 71 | done: boolean; 72 | nodes: number; 73 | totalSplits: number; 74 | queuedSplits: number; 75 | runningSplits: number; 76 | completedSplits: number; 77 | cpuTimeMillis: number; 78 | wallTimeMillis: number; 79 | processedRows: number; 80 | processedBytes: number; 81 | physicalInputBytes: number; 82 | failedTasks: number; 83 | coordinatorOnly: boolean; 84 | subStages: QueryStage[]; 85 | }; 86 | 87 | export type QueryStats = { 88 | state: string; 89 | queued: boolean; 90 | scheduled: boolean; 91 | nodes: number; 92 | totalSplits: number; 93 | queuedSplits: number; 94 | runningSplits: number; 95 | completedSplits: number; 96 | cpuTimeMillis: number; 97 | wallTimeMillis: number; 98 | queuedTimeMillis: number; 99 | elapsedTimeMillis: number; 100 | processedRows: number; 101 | processedBytes: number; 102 | physicalInputBytes: number; 103 | peakMemoryBytes: number; 104 | spilledBytes: number; 105 | rootStage: QueryStage; 106 | progressPercentage: number; 107 | }; 108 | 109 | export type Columns = {name: string; type: string}[]; 110 | 111 | export type QueryData = any[]; 112 | 113 | export type QueryFailureInfo = { 114 | type: string; 115 | message: string; 116 | suppressed: string[]; 117 | stack: string[]; 118 | }; 119 | 120 | export type QueryError = { 121 | message: string; 122 | errorCode: number; 123 | errorName: string; 124 | errorType: string; 125 | failureInfo: QueryFailureInfo; 126 | }; 127 | 128 | export type QueryResult = { 129 | id: string; 130 | infoUri?: string; 131 | nextUri?: string; 132 | columns?: Columns; 133 | data?: QueryData[]; 134 | stats?: QueryStats; 135 | warnings?: string[]; 136 | error?: QueryError; 137 | }; 138 | 139 | export type QueryInfo = { 140 | queryId: string; 141 | state: string; 142 | query: string; 143 | failureInfo?: QueryFailureInfo; 144 | }; 145 | 146 | export type Query = { 147 | query: string; 148 | catalog?: string; 149 | schema?: string; 150 | user?: string; 151 | session?: Session; 152 | extraCredential?: ExtraCredential; 153 | extraHeaders?: RequestHeaders; 154 | }; 155 | 156 | /** 157 | * It takes a Headers object and returns a new object with the same keys, but only the values that are 158 | * truthy 159 | * @param {RawAxiosRequestHeaders} headers - RawAxiosRequestHeaders - The headers object to be sanitized. 160 | * @returns An object with the key-value pairs of the headers object, but only if the value is truthy. 161 | */ 162 | const cleanHeaders = (headers: RawAxiosRequestHeaders) => { 163 | const sanitizedHeaders: RawAxiosRequestHeaders = {}; 164 | for (const [key, value] of Object.entries(headers)) { 165 | if (value) { 166 | sanitizedHeaders[key] = value; 167 | } 168 | } 169 | return sanitizedHeaders; 170 | }; 171 | 172 | /* It's a wrapper around the Axios library that adds some Trino specific headers to the requests */ 173 | class Client { 174 | private constructor( 175 | private readonly clientConfig: AxiosRequestConfig, 176 | private readonly options: ConnectionOptions 177 | ) {} 178 | 179 | static create(options: ConnectionOptions): Client { 180 | const agent = new https.Agent(options.ssl ?? {}); 181 | 182 | const clientConfig: AxiosRequestConfig = { 183 | baseURL: options.server ?? DEFAULT_SERVER, 184 | httpsAgent: agent, 185 | }; 186 | 187 | const headers: RawAxiosRequestHeaders = { 188 | [TRINO_USER_HEADER]: DEFAULT_USER, 189 | [TRINO_SOURCE_HEADER]: options.source ?? DEFAULT_SOURCE, 190 | [TRINO_CATALOG_HEADER]: options.catalog, 191 | [TRINO_SCHEMA_HEADER]: options.schema, 192 | [TRINO_SESSION_HEADER]: encodeAsString(options.session ?? {}), 193 | [TRINO_EXTRA_CREDENTIAL_HEADER]: encodeAsString( 194 | options.extraCredential ?? {} 195 | ), 196 | ...(options.extraHeaders ?? {}), 197 | }; 198 | 199 | if (options.auth && options.auth.type === 'basic') { 200 | const basic: BasicAuth = options.auth; 201 | clientConfig.auth = { 202 | username: basic.username, 203 | password: basic.password ?? '', 204 | }; 205 | 206 | headers[TRINO_USER_HEADER] = basic.username; 207 | } 208 | 209 | clientConfig.headers = cleanHeaders(headers); 210 | 211 | return new Client(clientConfig, options); 212 | } 213 | 214 | /** 215 | * Generic method to send a request to the server. 216 | * @param cfg - AxiosRequestConfig 217 | * @returns The response data. 218 | */ 219 | async request(cfg: AxiosRequestConfig): Promise { 220 | return axios 221 | .create(this.clientConfig) 222 | .request(cfg) 223 | .then(response => { 224 | const reqHeaders: RawAxiosRequestHeaders = 225 | this.clientConfig.headers ?? {}; 226 | const respHeaders = response.headers; 227 | reqHeaders[TRINO_CATALOG_HEADER] = 228 | respHeaders[TRINO_SET_CATALOG_HEADER.toLowerCase()] ?? 229 | reqHeaders[TRINO_CATALOG_HEADER] ?? 230 | this.options.catalog; 231 | reqHeaders[TRINO_SCHEMA_HEADER] = 232 | respHeaders[TRINO_SET_SCHEMA_HEADER.toLowerCase()] ?? 233 | reqHeaders[TRINO_SCHEMA_HEADER] ?? 234 | this.options.schema; 235 | reqHeaders[TRINO_SESSION_HEADER] = 236 | respHeaders[TRINO_SET_SESSION_HEADER.toLowerCase()] ?? 237 | reqHeaders[TRINO_SESSION_HEADER] ?? 238 | encodeAsString(this.options.session ?? {}); 239 | 240 | if (TRINO_CLEAR_SESSION_HEADER.toLowerCase() in respHeaders) { 241 | reqHeaders[TRINO_SESSION_HEADER] = undefined; 242 | } 243 | 244 | if (TRINO_ADDED_PREPARE_HEADER.toLowerCase() in respHeaders) { 245 | const prep = reqHeaders[TRINO_PREPARED_STATEMENT_HEADER]; 246 | 247 | reqHeaders[TRINO_PREPARED_STATEMENT_HEADER] = 248 | (prep ? prep + ',' : '') + 249 | respHeaders[TRINO_ADDED_PREPARE_HEADER.toLowerCase()]; 250 | } 251 | 252 | this.clientConfig.headers = cleanHeaders(reqHeaders); 253 | 254 | return response.data; 255 | }); 256 | } 257 | 258 | /** 259 | * It takes a query object and returns a promise that resolves to a query result object 260 | * @param {Query | string} query - The query to execute. 261 | * @returns A promise that resolves to a QueryResult object. 262 | */ 263 | async query(query: Query | string): Promise> { 264 | const req = typeof query === 'string' ? {query} : query; 265 | const headers: RawAxiosRequestHeaders = { 266 | [TRINO_USER_HEADER]: req.user, 267 | [TRINO_CATALOG_HEADER]: req.catalog, 268 | [TRINO_SCHEMA_HEADER]: req.schema, 269 | [TRINO_SESSION_HEADER]: encodeAsString(req.session ?? {}), 270 | [TRINO_EXTRA_CREDENTIAL_HEADER]: encodeAsString( 271 | req.extraCredential ?? {} 272 | ), 273 | ...(req.extraHeaders ?? {}) 274 | }; 275 | const requestConfig = { 276 | method: 'POST', 277 | url: '/v1/statement', 278 | data: req.query, 279 | headers: cleanHeaders(headers), 280 | }; 281 | return this.request(requestConfig).then( 282 | result => new Iterator(new QueryIterator(this, result)) 283 | ); 284 | } 285 | 286 | /** 287 | * It returns the query info for a given queryId. 288 | * @param {string} queryId - The query ID of the query you want to get information about. 289 | * @returns The query info 290 | */ 291 | async queryInfo(queryId: string): Promise { 292 | return this.request({url: `/v1/query/${queryId}`, method: 'GET'}); 293 | } 294 | 295 | /** 296 | * It cancels a query. 297 | * @param {string} queryId - The queryId of the query to cancel. 298 | * @returns The result of the query. 299 | */ 300 | async cancel(queryId: string): Promise { 301 | return this.request({url: `/v1/query/${queryId}`, method: 'DELETE'}).then( 302 | _ => {id: queryId} 303 | ); 304 | } 305 | } 306 | 307 | export class Iterator implements AsyncIterableIterator { 308 | constructor(private readonly iter: AsyncIterableIterator) {} 309 | 310 | [Symbol.asyncIterator](): AsyncIterableIterator { 311 | return this; 312 | } 313 | 314 | next(): Promise> { 315 | return this.iter.next(); 316 | } 317 | 318 | /** 319 | * Calls a defined callback function on each QueryResult, and returns an array that contains the results. 320 | * @param fn A function that accepts a QueryResult. map calls the fn function one time for each QueryResult. 321 | */ 322 | map(fn: (t: T) => B): Iterator { 323 | const that: AsyncIterableIterator = this.iter; 324 | const asyncIterableIterator: AsyncIterableIterator = { 325 | [Symbol.asyncIterator]: () => asyncIterableIterator, 326 | async next() { 327 | return that.next().then(result => { 328 | return >{ 329 | value: fn(result.value), 330 | done: result.done, 331 | }; 332 | }); 333 | }, 334 | }; 335 | return new Iterator(asyncIterableIterator); 336 | } 337 | 338 | /** 339 | * Performs the specified action for each element. 340 | * @param fn A function that accepts a QueryResult. forEach calls the fn function one time for each QueryResult. 341 | */ 342 | async forEach(fn: (value: T) => void): Promise { 343 | for await (const value of this) { 344 | fn(value); 345 | } 346 | } 347 | 348 | /** 349 | * Calls a defined callback function on each QueryResult. The return value of the callback function is the accumulated 350 | * result, and is provided as an argument in the next call to the callback function. 351 | * @param acc The initial value of the accumulator. 352 | * @param fn A function that accepts a QueryResult and accumulator, and returns an accumulator. 353 | */ 354 | async fold(acc: B, fn: (value: T, acc: B) => B): Promise { 355 | await this.forEach(value => (acc = fn(value, acc))); 356 | return acc; 357 | } 358 | } 359 | 360 | /** 361 | * Iterator for the query result data. 362 | */ 363 | export class QueryIterator implements AsyncIterableIterator { 364 | constructor( 365 | private readonly client: Client, 366 | private queryResult: QueryResult 367 | ) {} 368 | 369 | [Symbol.asyncIterator](): AsyncIterableIterator { 370 | return this; 371 | } 372 | 373 | /** 374 | * It returns true if the queryResult object has a nextUri property, and false otherwise 375 | * @returns A boolean value. 376 | */ 377 | hasNext(): boolean { 378 | return !!this.queryResult.nextUri; 379 | } 380 | 381 | /** 382 | * Retrieves the next QueryResult available. If there's no nextUri then there are no more 383 | * results and the query reached a completion state, successful or failure. 384 | * @returns The next set of results. 385 | */ 386 | async next(): Promise> { 387 | if (!this.hasNext()) { 388 | return Promise.resolve({value: this.queryResult, done: true}); 389 | } 390 | 391 | this.queryResult = await this.client.request({ 392 | url: this.queryResult.nextUri, 393 | }); 394 | 395 | const data = this.queryResult.data ?? []; 396 | if (data.length === 0) { 397 | if (this.hasNext()) { 398 | return this.next(); 399 | } 400 | } 401 | 402 | return Promise.resolve({value: this.queryResult, done: false}); 403 | } 404 | } 405 | 406 | /** 407 | * Trino is a client for the Trino REST API. 408 | */ 409 | export class Trino { 410 | private constructor(private readonly client: Client) {} 411 | 412 | static create(options: ConnectionOptions): Trino { 413 | return new Trino(Client.create(options)); 414 | } 415 | 416 | /** 417 | * Submittes a query for execution and returns a QueryIterator object that can be used to iterate over the query results. 418 | * @param query - The query to execute. 419 | * @returns A QueryIterator object. 420 | */ 421 | async query(query: Query | string): Promise> { 422 | return this.client.query(query); 423 | } 424 | 425 | /** 426 | * Retrieves the query info for a given queryId. 427 | * @param queryId - The query to execute. 428 | * @returns The query info 429 | */ 430 | async queryInfo(queryId: string): Promise { 431 | return this.client.queryInfo(queryId); 432 | } 433 | 434 | /** 435 | * It cancels a query. 436 | * @param {string} queryId - The queryId of the query to cancel. 437 | * @returns The result of the query. 438 | */ 439 | async cancel(queryId: string): Promise { 440 | return this.client.cancel(queryId); 441 | } 442 | } 443 | --------------------------------------------------------------------------------