|
| 1 | +import { DatabaseSchemasCollection, DeploymentsCollection } from './schema.ts' |
| 2 | +import { DB_SCHEMA_REFRESH_MS } from './lib/env.ts' |
| 3 | +import { log } from './lib/log.ts' |
| 4 | + |
| 5 | +async function runSQL( |
| 6 | + endpoint: string, |
| 7 | + token: string, |
| 8 | + query: string, |
| 9 | + params?: unknown, |
| 10 | +) { |
| 11 | + const res = await fetch(endpoint, { |
| 12 | + method: 'POST', |
| 13 | + headers: { |
| 14 | + 'Content-Type': 'application/json', |
| 15 | + Authorization: `Bearer ${token}`, |
| 16 | + }, |
| 17 | + body: JSON.stringify({ query, params }), |
| 18 | + }) |
| 19 | + if (!res.ok) throw Error(`sql endpoint error ${res.status}`) |
| 20 | + const data = await res.json() |
| 21 | + |
| 22 | + return data |
| 23 | +} |
| 24 | + |
| 25 | +// Dialect detection attempts (run first successful) |
| 26 | +const DETECTION_QUERIES: { name: string; sql: string; matcher: RegExp }[] = [ |
| 27 | + { |
| 28 | + name: 'sqlite', |
| 29 | + sql: 'SELECT sqlite_version() as v', |
| 30 | + matcher: /\d+\.\d+\.\d+/, |
| 31 | + }, |
| 32 | +] |
| 33 | + |
| 34 | +async function detectDialect(endpoint: string, token: string): Promise<string> { |
| 35 | + for (const d of DETECTION_QUERIES) { |
| 36 | + try { |
| 37 | + const rows = await runSQL(endpoint, token, d.sql) |
| 38 | + log.debug('dialect-detection', { dialect: d.name, rows }) |
| 39 | + if (rows.length) { |
| 40 | + const text = JSON.stringify(rows[0]) |
| 41 | + if (d.matcher.test(text)) return d.name |
| 42 | + } |
| 43 | + } catch { /* ignore */ } |
| 44 | + } |
| 45 | + return 'unknown' |
| 46 | +} |
| 47 | + |
| 48 | +// Introspection queries per dialect returning columns list |
| 49 | +// Standardized output fields: table_schema (nullable), table_name, column_name, data_type, ordinal_position |
| 50 | +const INTROSPECTION: Record<string, string> = { |
| 51 | + sqlite: |
| 52 | + `SELECT NULL AS table_schema, m.name AS table_name, p.name AS column_name, p.type AS data_type, p.cid + 1 AS ordinal_position FROM sqlite_master m JOIN pragma_table_info(m.name) p WHERE m.type = 'table' AND m.name NOT LIKE 'sqlite_%' ORDER BY m.name, p.cid`, |
| 53 | + unknown: |
| 54 | + `SELECT table_schema, table_name, column_name, data_type, ordinal_position FROM information_schema.columns ORDER BY table_schema, table_name, ordinal_position`, |
| 55 | +} |
| 56 | + |
| 57 | +async function fetchSchema(endpoint: string, token: string, dialect: string) { |
| 58 | + const sql = INTROSPECTION[dialect] ?? INTROSPECTION.unknown |
| 59 | + return await runSQL(endpoint, token, sql) |
| 60 | +} |
| 61 | + |
| 62 | +type ColumnInfo = { name: string; type: string; ordinal: number } |
| 63 | +type TableInfo = { |
| 64 | + schema: string | undefined |
| 65 | + table: string |
| 66 | + columns: ColumnInfo[] |
| 67 | +} |
| 68 | + |
| 69 | +export async function refreshOneSchema( |
| 70 | + dep: ReturnType<typeof DeploymentsCollection.get>, |
| 71 | +) { |
| 72 | + if (!dep || !dep.databaseEnabled || !dep.sqlEndpoint || !dep.sqlToken) return |
| 73 | + try { |
| 74 | + const dialect = await detectDialect(dep.sqlEndpoint, dep.sqlToken) |
| 75 | + const rows = await fetchSchema(dep.sqlEndpoint, dep.sqlToken, dialect) |
| 76 | + // group rows |
| 77 | + const tableMap = new Map<string, TableInfo>() |
| 78 | + for (const r of rows) { |
| 79 | + const schema = (r.table_schema as string) || undefined |
| 80 | + const table = r.table_name as string |
| 81 | + if (!table) continue |
| 82 | + const key = (schema ? schema + '.' : '') + table |
| 83 | + if (!tableMap.has(key)) tableMap.set(key, { schema, table, columns: [] }) |
| 84 | + tableMap.get(key)!.columns.push({ |
| 85 | + name: String(r.column_name), |
| 86 | + type: String(r.data_type || ''), |
| 87 | + ordinal: Number(r.ordinal_position || 0), |
| 88 | + }) |
| 89 | + } |
| 90 | + const tables = [...tableMap.values()].map((t) => ({ |
| 91 | + ...t, |
| 92 | + columns: t.columns.sort((a, b) => a.ordinal - b.ordinal), |
| 93 | + })) |
| 94 | + const payload = { |
| 95 | + deploymentUrl: dep.url, |
| 96 | + dialect, |
| 97 | + refreshedAt: new Date().toISOString(), |
| 98 | + tables: tables, |
| 99 | + } |
| 100 | + const existing = DatabaseSchemasCollection.get(dep.url) |
| 101 | + if (existing) { |
| 102 | + await DatabaseSchemasCollection.update(dep.url, payload) |
| 103 | + } else { |
| 104 | + await DatabaseSchemasCollection.insert(payload) |
| 105 | + } |
| 106 | + log.info('schema-refreshed', { |
| 107 | + deployment: dep.url, |
| 108 | + dialect, |
| 109 | + tables: tables.length, |
| 110 | + }) |
| 111 | + } catch (err) { |
| 112 | + log.error('schema-refresh-failed', { deployment: dep.url, err }) |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +export async function refreshAllSchemas() { |
| 117 | + for (const dep of DeploymentsCollection.values()) { |
| 118 | + await refreshOneSchema(dep) |
| 119 | + } |
| 120 | +} |
| 121 | + |
| 122 | +let intervalHandle: number | undefined |
| 123 | +export function startSchemaRefreshLoop() { |
| 124 | + if (intervalHandle) return |
| 125 | + // initial kick (non-blocking) |
| 126 | + refreshAllSchemas() |
| 127 | + intervalHandle = setInterval(() => { |
| 128 | + refreshAllSchemas() |
| 129 | + }, DB_SCHEMA_REFRESH_MS) as unknown as number |
| 130 | + log.info('schema-refresh-loop-started', { everyMs: DB_SCHEMA_REFRESH_MS }) |
| 131 | +} |
0 commit comments