-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql.ts
More file actions
357 lines (326 loc) · 10.3 KB
/
sql.ts
File metadata and controls
357 lines (326 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import {
DatabaseSchemasCollection,
Deployment,
DeploymentsCollection,
} from '/api/schema.ts'
import { DB_SCHEMA_REFRESH_MS } from '/api/lib/env.ts'
import {
applyReadTransformers,
applyWriteTransformers,
getProjectFunctions,
} from '/api/lib/functions.ts'
export class SQLQueryError extends Error {
constructor(message: string, body: string) {
super(message)
this.type = 'unexpected'
this.sqlMessage = 'unexpected error'
try {
const errorDetails = JSON.parse(body)
const errorTypes = ['service-error', 'bad-query', 'timeout']
if (errorTypes.includes(errorDetails.type)) this.type = errorDetails.type
if (typeof errorDetails.sqlMessage === 'string') {
this.sqlMessage = errorDetails.sqlMessage
}
} catch {
this.sqlMessage = body
}
}
type: 'service-error' | 'bad-query' | 'unexpected' | 'timeout'
sqlMessage: string
}
export async function runSQL(
endpoint: string,
token: string,
query: string,
params?: unknown,
) {
const res = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ query, params }),
})
const body = await res.text()
if (res.ok) return JSON.parse(body)
throw new SQLQueryError(`sql endpoint error ${res.status}`, body)
}
// Dialect detection attempts (run first successful)
const DETECTION_QUERIES: { name: string; sql: string; matcher: RegExp }[] = [
{
name: 'sqlite',
sql: 'SELECT sqlite_version() as v',
matcher: /\d+\.\d+\.\d+/,
},
]
async function detectDialect(endpoint: string, token: string): Promise<string> {
for (const d of DETECTION_QUERIES) {
try {
const rows = await runSQL(endpoint, token, d.sql)
console.debug('dialect-detection', { dialect: d.name, rows })
if (rows.length) {
const text = JSON.stringify(rows[0])
if (d.matcher.test(text)) return d.name
}
} catch { /* ignore */ }
}
return 'unknown'
}
// Introspection queries per dialect returning columns list
// Standardized output fields: table_schema (nullable), table_name, column_name, data_type, ordinal_position
const INTROSPECTION: Record<string, string> = {
sqlite:
`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`,
unknown:
`SELECT table_schema, table_name, column_name, data_type, ordinal_position FROM information_schema.columns ORDER BY table_schema, table_name, ordinal_position`,
}
async function fetchSchema(endpoint: string, token: string, dialect: string) {
const sql = INTROSPECTION[dialect] ?? INTROSPECTION.unknown
try {
return await runSQL(endpoint, token, sql)
} catch { /* ignore */ }
}
export type ColumnInfo = { name: string; type: string; ordinal: number }
type TableInfo = {
schema: string | undefined
table: string
columns: ColumnInfo[]
columnsMap: Map<string, ColumnInfo>
}
export async function refreshOneSchema(
dep: ReturnType<typeof DeploymentsCollection.get>,
) {
if (!dep || !dep.databaseEnabled || !dep.sqlEndpoint || !dep.sqlToken) return
try {
const dialect = await detectDialect(dep.sqlEndpoint, dep.sqlToken)
const rows = await fetchSchema(dep.sqlEndpoint, dep.sqlToken, dialect)
// group rows
const tableMap = new Map<string, TableInfo>()
for (const r of rows) {
const schema = (r.table_schema as string) || undefined
const table = r.table_name as string
if (!table) continue
const key = (schema ? schema + '.' : '') + table
if (!tableMap.has(key)) {
tableMap.set(key, { schema, table, columns: [], columnsMap: new Map() })
}
tableMap.get(key)!.columns.push({
name: String(r.column_name),
type: String(r.data_type || ''),
ordinal: Number(r.ordinal_position || 0),
})
}
const tables = [...tableMap.values()].map((t) => ({
...t,
columns: t.columns.sort((a, b) => a.ordinal - b.ordinal),
columnsMap: t.columns.reduce((obj, col) => {
obj[col.name] = col
return obj
}, {} as Record<string, ColumnInfo>),
}))
const payload = {
deploymentUrl: dep.url,
dialect,
refreshedAt: new Date().toISOString(),
tables: tables,
}
const existing = DatabaseSchemasCollection.get(dep.url)
if (existing) {
await DatabaseSchemasCollection.update(dep.url, payload)
} else {
await DatabaseSchemasCollection.insert(payload)
}
console.info('schema-refreshed', {
deployment: dep.url,
dialect,
tables: tables.length,
})
} catch (err) {
console.error('schema-refresh-failed', { deployment: dep.url, err })
}
}
export async function refreshAllSchemas() {
for (const dep of DeploymentsCollection.values()) {
await refreshOneSchema(dep)
}
}
let intervalHandle: number | undefined
export function startSchemaRefreshLoop() {
if (intervalHandle) return
// initial kick (non-blocking)
refreshAllSchemas()
intervalHandle = setInterval(() => {
refreshAllSchemas()
}, DB_SCHEMA_REFRESH_MS) as unknown as number
console.info('schema-refresh-loop-started', { everyMs: DB_SCHEMA_REFRESH_MS })
}
type FetchTablesParams = {
deployment: Deployment
table: string
filter: { key: string; comparator: string; value: string }[]
sort: { key: string; order: 'ASC' | 'DESC' }[]
limit: number
offset: number
search: string
}
const constructWhereClause = (
params: FetchTablesParams,
columnsMap: Map<string, ColumnInfo>,
) => {
const whereClauses: string[] = []
if (params.filter.length) {
for (const filter of params.filter) {
const { key, comparator, value } = filter
const column = columnsMap.get(key)
if (!column) {
throw Error(`Invalid filter column: ${key}`)
}
const safeValue = value.replace(/'/g, "''")
whereClauses.push(`${key} ${comparator} '${safeValue}'`)
}
}
if (params.search) {
const searchClauses = columnsMap.values().map((col) => {
return `${col.name} LIKE '%${params.search.replace(/'/g, "''")}%'`
}).toArray()
if (searchClauses.length) {
whereClauses.push(`(${searchClauses.join(' OR ')})`)
}
}
return whereClauses.length ? 'WHERE ' + whereClauses.join(' AND ') : ''
}
const constructOrderByClause = (
params: FetchTablesParams,
columnsMap: Map<string, ColumnInfo>,
) => {
if (!params.sort.length) return ''
const orderClauses: string[] = []
for (const sort of params.sort) {
const { key, order } = sort
const column = columnsMap.get(key)
if (!column) {
throw Error(`Invalid sort column: ${key}`)
}
orderClauses.push(`${key} ${order}`)
}
return orderClauses.length ? 'ORDER BY ' + orderClauses.join(', ') : ''
}
export const fetchTablesData = async (
params: FetchTablesParams,
columnsMap: Map<string, ColumnInfo>,
) => {
const { sqlEndpoint, sqlToken } = params.deployment
if (!sqlToken || !sqlEndpoint) {
throw Error('Missing SQL endpoint or token')
}
const projectFunctions = getProjectFunctions(params.deployment.projectId)
const whereClause = constructWhereClause(params, columnsMap)
const orderByClause = constructOrderByClause(params, columnsMap)
let limitOffsetClause = ''
const limit = Math.floor(params.limit)
if (params.limit && limit > 0) {
limitOffsetClause += `LIMIT ${limit}`
const offset = Math.floor(params.offset)
if (params.offset && offset >= 0) {
limitOffsetClause += ` OFFSET ${offset}`
}
}
const query =
`SELECT * FROM ${params.table} ${whereClause} ${orderByClause} ${limitOffsetClause}`
const countQuery =
`SELECT COUNT(*) as count FROM ${params.table} ${whereClause}`
const rows = await runSQL(sqlEndpoint, sqlToken, query)
// Apply read transformer pipeline
const transformedRows = await applyReadTransformers(
rows,
params.deployment.projectId,
params.deployment.url,
params.table,
projectFunctions,
)
return {
rows: transformedRows,
totalRows: limit > 0
? ((await runSQL(sqlEndpoint, sqlToken, countQuery))[0].count) as number
: rows.length,
}
}
export const insertTableData = async (
deployment: Deployment,
table: string,
data: Record<string, unknown>,
) => {
const { sqlEndpoint, sqlToken } = deployment
if (!sqlToken || !sqlEndpoint) {
throw Error('Missing SQL endpoint or token')
}
const projectFunctions = getProjectFunctions(deployment.projectId)
const transformedData = await applyWriteTransformers(
data,
deployment.projectId,
deployment.url,
table,
projectFunctions,
)
const columns = Object.keys(transformedData)
const values = Object.values(transformedData).map((v) => {
if (v === null) return 'NULL'
if (typeof v === 'string') return `'${v.replaceAll("'", "''")}'`
return String(v)
})
const query = `INSERT INTO ${table} (${columns.join(', ')}) VALUES (${
values.join(', ')
})`
const rows = await runSQL(sqlEndpoint, sqlToken, query)
// Apply read transformer pipeline
return await applyReadTransformers(
rows,
deployment.projectId,
deployment.url,
table,
projectFunctions,
)
}
export const updateTableData = async (
deployment: Deployment,
table: string,
pk: { key: string; value: unknown },
data: Record<string, unknown>,
) => {
const { sqlEndpoint, sqlToken } = deployment
if (!sqlToken || !sqlEndpoint) {
throw Error('Missing SQL endpoint or token')
}
const projectFunctions = getProjectFunctions(deployment.projectId)
const transformedData = await applyWriteTransformers(
data,
deployment.projectId,
deployment.url,
table,
projectFunctions,
)
const sets = Object.entries(transformedData).map(([k, v]) => {
const val = v === null
? 'NULL'
: typeof v === 'string'
? `'${v.replaceAll("'", "''")}'`
: String(v)
return `${k} = ${val}`
})
const pkVal = typeof pk.value === 'string'
? `'${String(pk.value).replaceAll("'", "''")}'`
: String(pk.value)
const query = `UPDATE ${table} SET ${
sets.join(', ')
} WHERE ${pk.key} = ${pkVal}`
const rows = await runSQL(sqlEndpoint, sqlToken, query)
// Apply read transformer pipeline
return await applyReadTransformers(
rows,
deployment.projectId,
deployment.url,
table,
projectFunctions,
)
}