|
| 1 | +/* |
| 2 | + * Copyright 2025 Google LLC |
| 3 | + * |
| 4 | + * Permission is hereby granted, free of charge, to any person obtaining |
| 5 | + * a copy of this software and associated documentation files |
| 6 | + * (the "Software"), to deal in the Software without restriction, |
| 7 | + * including without limitation the rights to use, copy, modify, merge, |
| 8 | + * publish, distribute, sublicense, and/or sell copies of the Software, |
| 9 | + * and to permit persons to whom the Software is furnished to do so, |
| 10 | + * subject to the following conditions: |
| 11 | + * |
| 12 | + * The above copyright notice and this permission notice shall be |
| 13 | + * included in all copies or substantial portions of the Software. |
| 14 | + * |
| 15 | + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 16 | + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| 17 | + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. |
| 18 | + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY |
| 19 | + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, |
| 20 | + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE |
| 21 | + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 22 | + */ |
| 23 | + |
| 24 | +import crypto from 'crypto'; |
| 25 | +import type { |
| 26 | + ConnectionConfig, |
| 27 | + QueryDataRow, |
| 28 | + QueryOptionsReader, |
| 29 | + RunSQLOptions, |
| 30 | +} from '@malloydata/malloy'; |
| 31 | +import {DuckDBCommon} from './duckdb_common'; |
| 32 | +import {PythonBridgeClient} from './python_bridge_client'; |
| 33 | +import type {Table} from 'apache-arrow'; |
| 34 | + |
| 35 | +export interface GizmoSQLConnectionOptions extends ConnectionConfig { |
| 36 | + gizmosqlUri: string; |
| 37 | + gizmosqlUsername: string; |
| 38 | + gizmosqlPassword: string; |
| 39 | + gizmosqlCatalog?: string; |
| 40 | + pythonPath?: string; |
| 41 | +} |
| 42 | + |
| 43 | +export class GizmoSQLConnection extends DuckDBCommon { |
| 44 | + public readonly name: string; |
| 45 | + private client: PythonBridgeClient | null = null; |
| 46 | + private uri: string; |
| 47 | + private username: string; |
| 48 | + private password: string; |
| 49 | + private catalog: string; |
| 50 | + private pythonPath?: string; |
| 51 | + private isSetup: Promise<void> | undefined; |
| 52 | + private setupError: Error | undefined; |
| 53 | + |
| 54 | + constructor( |
| 55 | + options: GizmoSQLConnectionOptions, |
| 56 | + queryOptions?: QueryOptionsReader |
| 57 | + ) { |
| 58 | + super(queryOptions); |
| 59 | + this.name = options.name; |
| 60 | + this.uri = options.gizmosqlUri; |
| 61 | + this.username = options.gizmosqlUsername; |
| 62 | + this.password = options.gizmosqlPassword; |
| 63 | + this.catalog = options.gizmosqlCatalog || 'main'; |
| 64 | + this.pythonPath = options.pythonPath; |
| 65 | + } |
| 66 | + |
| 67 | + private async getClient(): Promise<PythonBridgeClient> { |
| 68 | + if (!this.client) { |
| 69 | + this.client = new PythonBridgeClient({ |
| 70 | + uri: this.uri, |
| 71 | + username: this.username, |
| 72 | + password: this.password, |
| 73 | + catalog: this.catalog, |
| 74 | + pythonPath: this.pythonPath, |
| 75 | + }); |
| 76 | + |
| 77 | + await this.client.connect(); |
| 78 | + } |
| 79 | + return this.client; |
| 80 | + } |
| 81 | + |
| 82 | + protected async setup(): Promise<void> { |
| 83 | + if (this.setupError) { |
| 84 | + throw this.setupError; |
| 85 | + } |
| 86 | + |
| 87 | + const doSetup = async () => { |
| 88 | + try { |
| 89 | + await this.getClient(); |
| 90 | + } catch (error) { |
| 91 | + this.setupError = error as Error; |
| 92 | + throw error; |
| 93 | + } |
| 94 | + }; |
| 95 | + |
| 96 | + if (!this.isSetup) { |
| 97 | + this.isSetup = doSetup(); |
| 98 | + } |
| 99 | + await this.isSetup; |
| 100 | + } |
| 101 | + |
| 102 | + protected async runDuckDBQuery( |
| 103 | + sql: string |
| 104 | + ): Promise<{rows: QueryDataRow[]; totalRows: number}> { |
| 105 | + const client = await this.getClient(); |
| 106 | + |
| 107 | + try { |
| 108 | + const table: Table = await client.query(sql); |
| 109 | + |
| 110 | + // Convert Arrow Table to QueryDataRow[] |
| 111 | + const rows: QueryDataRow[] = []; |
| 112 | + for (let i = 0; i < table.numRows; i++) { |
| 113 | + const row: QueryDataRow = {}; |
| 114 | + for (const field of table.schema.fields) { |
| 115 | + const column = table.getChild(field.name); |
| 116 | + if (column) { |
| 117 | + row[field.name] = column.get(i); |
| 118 | + } |
| 119 | + } |
| 120 | + rows.push(row); |
| 121 | + } |
| 122 | + |
| 123 | + return {rows, totalRows: rows.length}; |
| 124 | + } catch (error) { |
| 125 | + const message = error instanceof Error ? error.message : String(error); |
| 126 | + throw new Error(`GizmoSQL query failed: ${message}`); |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + public async *runSQLStream( |
| 131 | + sql: string, |
| 132 | + {rowLimit, abortSignal}: RunSQLOptions = {} |
| 133 | + ): AsyncIterableIterator<QueryDataRow> { |
| 134 | + const defaultOptions = this.readQueryOptions(); |
| 135 | + rowLimit ??= defaultOptions.rowLimit; |
| 136 | + await this.setup(); |
| 137 | + |
| 138 | + const statements = sql.split('-- hack: split on this'); |
| 139 | + |
| 140 | + while (statements.length > 1) { |
| 141 | + await this.runDuckDBQuery(statements[0]); |
| 142 | + statements.shift(); |
| 143 | + } |
| 144 | + |
| 145 | + const result = await this.runDuckDBQuery(statements[0]); |
| 146 | + let index = 0; |
| 147 | + |
| 148 | + for (const row of result.rows) { |
| 149 | + if ( |
| 150 | + (rowLimit !== undefined && index >= rowLimit) || |
| 151 | + abortSignal?.aborted |
| 152 | + ) { |
| 153 | + break; |
| 154 | + } |
| 155 | + index++; |
| 156 | + yield row; |
| 157 | + } |
| 158 | + } |
| 159 | + |
| 160 | + async createHash(sqlCommand: string): Promise<string> { |
| 161 | + return crypto.createHash('md5').update(sqlCommand).digest('hex'); |
| 162 | + } |
| 163 | + |
| 164 | + public async close(): Promise<void> { |
| 165 | + if (this.client) { |
| 166 | + this.client.close(); |
| 167 | + this.client = null; |
| 168 | + } |
| 169 | + } |
| 170 | +} |
0 commit comments