diff --git a/src/adapter.ts b/src/adapter.ts index b1752ef..400c91d 100644 --- a/src/adapter.ts +++ b/src/adapter.ts @@ -93,17 +93,27 @@ class BunSQLiteQueryable implements SqlQueryable { } } - private getTableFromQuery(sql: string): string | null { - // Simple regex to extract table name from SELECT queries - // This handles common cases like SELECT ... FROM table, SELECT ... FROM "table", etc. - const match = sql.match(/\bFROM\s+(?:`([^`]+)`|"([^"]+)"|(\w+))/i); - return match ? (match[1] || match[2] || match[3]) : null; + private getTableFromQuery(sql: string): { schema?: string; table: string } | null { + // Extract table name from SELECT queries, handling qualified names like schema.table + // Match patterns like: `schema`.`table`, "schema"."table", schema.table, `table`, "table", table + const match = sql.match(/\bFROM\s+(?:(?:`([^`]+)`|"([^"]+)"|(\w+))\.)?(?:`([^`]+)`|"([^"]+)"|(\w+))/i); + if (match) { + const schema = match[1] || match[2] || match[3]; + const table = match[4] || match[5] || match[6]; + return schema ? { schema, table } : { table }; + } + return null; } - private async getColumnTypes(tableName: string, columnNames: string[]): Promise> { + private async getColumnTypes(tableInfo: { schema?: string; table: string }, columnNames: string[]): Promise> { try { - const tableInfoStmt = this.db.query(`PRAGMA table_info(${tableName})`); - const tableInfo = tableInfoStmt.all() as Array<{ + // Build PRAGMA query with optional schema qualifier + const pragmaQuery = tableInfo.schema + ? `PRAGMA ${tableInfo.schema}.table_info(${tableInfo.table})` + : `PRAGMA table_info(${tableInfo.table})`; + + const tableInfoStmt = this.db.query(pragmaQuery); + const tableInfoResult = tableInfoStmt.all() as Array<{ cid: number; name: string; type: string; @@ -114,14 +124,14 @@ class BunSQLiteQueryable implements SqlQueryable { // Create a map of column names to types const typeMap = new Map(); - tableInfo.forEach(col => { + tableInfoResult.forEach(col => { typeMap.set(col.name, col.type); }); // Return types in the same order as columnNames return columnNames.map(name => typeMap.get(name) || null); } catch (e) { - debug("Failed to get column types for table %s: %O", tableName, e); + debug("Failed to get column types for table %s: %O", tableInfo, e); // Fall back to null types if we can't get schema info return columnNames.map(() => null); } @@ -145,9 +155,9 @@ class BunSQLiteQueryable implements SqlQueryable { // Try to get proper column types from table schema let declaredTypes: Array; - const tableName = this.getTableFromQuery(query.sql); - if (tableName) { - declaredTypes = await this.getColumnTypes(tableName, columns); + const tableInfo = this.getTableFromQuery(query.sql); + if (tableInfo) { + declaredTypes = await this.getColumnTypes(tableInfo, columns); } else { declaredTypes = columns.map((col: any) => null); }