-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathsql_utils.ts
385 lines (342 loc) Β· 11.1 KB
/
sql_utils.ts
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import type { DataSource, DataSourceOptions } from "typeorm";
import { PromptTemplate } from "@langchain/core/prompts";
import {
DEFAULT_SQL_DATABASE_PROMPT,
SQL_SAP_HANA_PROMPT,
SQL_MSSQL_PROMPT,
SQL_MYSQL_PROMPT,
SQL_POSTGRES_PROMPT,
SQL_SQLITE_PROMPT,
SQL_ORACLE_PROMPT,
} from "../chains/sql_db/sql_db_prompt.js";
interface RawResultTableAndColumn {
table_name: string;
column_name: string;
data_type: string | undefined;
is_nullable: string;
}
export interface SqlDatabaseParams {
includesTables?: Array<string>;
ignoreTables?: Array<string>;
sampleRowsInTableInfo?: number;
customDescription?: Record<string, string>;
}
export interface SqlDatabaseOptionsParams extends SqlDatabaseParams {
appDataSourceOptions: DataSourceOptions;
}
export interface SqlDatabaseDataSourceParams extends SqlDatabaseParams {
appDataSource: DataSource;
}
export type SerializedSqlDatabase = SqlDatabaseOptionsParams & {
_type: string;
};
export interface SqlTable {
tableName: string;
columns: SqlColumn[];
}
export interface SqlColumn {
columnName: string;
dataType?: string;
isNullable?: boolean;
}
export const verifyListTablesExistInDatabase = (
tablesFromDatabase: Array<SqlTable>,
listTables: Array<string>,
errorPrefixMsg: string
): void => {
const onlyTableNames: Array<string> = tablesFromDatabase.map(
(table: SqlTable) => table.tableName
);
if (listTables.length > 0) {
for (const tableName of listTables) {
if (!onlyTableNames.includes(tableName)) {
throw new Error(
`${errorPrefixMsg} the table ${tableName} was not found in the database`
);
}
}
}
};
export const verifyIncludeTablesExistInDatabase = (
tablesFromDatabase: Array<SqlTable>,
includeTables: Array<string>
): void => {
verifyListTablesExistInDatabase(
tablesFromDatabase,
includeTables,
"Include tables not found in database:"
);
};
export const verifyIgnoreTablesExistInDatabase = (
tablesFromDatabase: Array<SqlTable>,
ignoreTables: Array<string>
): void => {
verifyListTablesExistInDatabase(
tablesFromDatabase,
ignoreTables,
"Ignore tables not found in database:"
);
};
const formatToSqlTable = (
rawResultsTableAndColumn: Array<RawResultTableAndColumn>
): Array<SqlTable> => {
const sqlTable: Array<SqlTable> = [];
for (const oneResult of rawResultsTableAndColumn) {
const sqlColumn = {
columnName: oneResult.column_name,
dataType: oneResult.data_type,
isNullable: oneResult.is_nullable === "YES",
};
const currentTable = sqlTable.find(
(oneTable) => oneTable.tableName === oneResult.table_name
);
if (currentTable) {
currentTable.columns.push(sqlColumn);
} else {
const newTable = {
tableName: oneResult.table_name,
columns: [sqlColumn],
};
sqlTable.push(newTable);
}
}
return sqlTable;
};
export const getTableAndColumnsName = async (
appDataSource: DataSource
): Promise<Array<SqlTable>> => {
let sql;
if (appDataSource.options.type === "postgres") {
const schema = appDataSource.options?.schema ?? "public";
sql = `SELECT
t.table_name,
c.*
FROM
information_schema.tables t
JOIN information_schema.columns c
ON t.table_name = c.table_name
WHERE
t.table_schema = '${schema}'
AND c.table_schema = '${schema}'
ORDER BY
t.table_name,
c.ordinal_position;`;
const rep = await appDataSource.query(sql);
return formatToSqlTable(rep);
}
if (
appDataSource.options.type === "sqlite" ||
appDataSource.options.type === "sqljs"
) {
sql =
"SELECT \n" +
" m.name AS table_name,\n" +
" p.name AS column_name,\n" +
" p.type AS data_type,\n" +
" CASE \n" +
" WHEN p.\"notnull\" = 0 THEN 'YES' \n" +
" ELSE 'NO' \n" +
" END AS is_nullable \n" +
"FROM \n" +
" sqlite_master m \n" +
"JOIN \n" +
" pragma_table_info(m.name) p \n" +
"WHERE \n" +
" m.type = 'table' AND \n" +
" m.name NOT LIKE 'sqlite_%';\n";
const rep = await appDataSource.query(sql);
return formatToSqlTable(rep);
}
if (
appDataSource.options.type === "mysql" ||
appDataSource.options.type === "aurora-mysql"
) {
sql =
"SELECT " +
"TABLE_NAME AS table_name, " +
"COLUMN_NAME AS column_name, " +
"DATA_TYPE AS data_type, " +
"IS_NULLABLE AS is_nullable " +
"FROM INFORMATION_SCHEMA.COLUMNS " +
`WHERE TABLE_SCHEMA = '${appDataSource.options.database}';`;
const rep = await appDataSource.query(sql);
return formatToSqlTable(rep);
}
if (appDataSource.options.type === "mssql") {
const schema = appDataSource.options?.schema;
const sql = `SELECT
TABLE_NAME AS table_name,
COLUMN_NAME AS column_name,
DATA_TYPE AS data_type,
IS_NULLABLE AS is_nullable
FROM INFORMATION_SCHEMA.COLUMNS
${schema && `WHERE TABLE_SCHEMA = '${schema}'`}
ORDER BY TABLE_NAME, ORDINAL_POSITION;`;
const rep = await appDataSource.query(sql);
return formatToSqlTable(rep);
}
if (appDataSource.options.type === "sap") {
const schema = appDataSource.options?.schema ?? "public";
sql = `SELECT
TABLE_NAME,
COLUMN_NAME,
DATA_TYPE_NAME AS data_type,
CASE WHEN IS_NULLABLE='TRUE' THEN 'YES' ELSE 'NO' END AS is_nullable
FROM TABLE_COLUMNS
WHERE SCHEMA_NAME='${schema}'`;
const rep: Array<{ [key: string]: string }> = await appDataSource.query(
sql
);
const repLowerCase: Array<RawResultTableAndColumn> = [];
rep.forEach((_rep) =>
repLowerCase.push({
table_name: _rep.TABLE_NAME,
column_name: _rep.COLUMN_NAME,
data_type: _rep.DATA_TYPE,
is_nullable: _rep.IS_NULLABLE,
})
);
return formatToSqlTable(repLowerCase);
}
if (appDataSource.options.type === "oracle") {
const schemaName = appDataSource.options.schema;
const sql = `
SELECT
TABLE_NAME AS "table_name",
COLUMN_NAME AS "column_name",
DATA_TYPE AS "data_type",
NULLABLE AS "is_nullable"
FROM ALL_TAB_COLS
WHERE
OWNER = UPPER('${schemaName}')`;
const rep = await appDataSource.query(sql);
return formatToSqlTable(rep);
}
throw new Error("Database type not implemented yet");
};
const formatSqlResponseToSimpleTableString = (rawResult: unknown): string => {
if (!rawResult || !Array.isArray(rawResult) || rawResult.length === 0) {
return "";
}
let globalString = "";
for (const oneRow of rawResult) {
globalString += `${Object.values(oneRow).reduce(
(completeString, columnValue) => `${completeString} ${columnValue}`,
""
)}\n`;
}
return globalString;
};
export const generateTableInfoFromTables = async (
tables: Array<SqlTable> | undefined,
appDataSource: DataSource,
nbSampleRow: number,
customDescription?: Record<string, string>
): Promise<string> => {
if (!tables) {
return "";
}
let globalString = "";
for (const currentTable of tables) {
// Add the custom info of the table
const tableCustomDescription =
customDescription &&
Object.keys(customDescription).includes(currentTable.tableName)
? `${customDescription[currentTable.tableName]}\n`
: "";
// Add the creation of the table in SQL
let schema = null;
if (appDataSource.options.type === "postgres") {
schema = appDataSource.options?.schema ?? "public";
} else if (appDataSource.options.type === "mssql") {
schema = appDataSource.options?.schema;
} else if (appDataSource.options.type === "sap") {
schema =
appDataSource.options?.schema ??
appDataSource.options?.username ??
"public";
} else if (appDataSource.options.type === "oracle") {
schema = appDataSource.options.schema;
}
let sqlCreateTableQuery = schema
? `CREATE TABLE "${schema}"."${currentTable.tableName}" (\n`
: `CREATE TABLE ${currentTable.tableName} (\n`;
for (const [key, currentColumn] of currentTable.columns.entries()) {
if (key > 0) {
sqlCreateTableQuery += ", ";
}
sqlCreateTableQuery += `${currentColumn.columnName} ${
currentColumn.dataType
} ${currentColumn.isNullable ? "" : "NOT NULL"}`;
}
sqlCreateTableQuery += ") \n";
let sqlSelectInfoQuery;
if (appDataSource.options.type === "mysql") {
// We use backticks to quote the table names and thus allow for example spaces in table names
sqlSelectInfoQuery = `SELECT * FROM \`${currentTable.tableName}\` LIMIT ${nbSampleRow};\n`;
} else if (appDataSource.options.type === "postgres") {
const schema = appDataSource.options?.schema ?? "public";
sqlSelectInfoQuery = `SELECT * FROM "${schema}"."${currentTable.tableName}" LIMIT ${nbSampleRow};\n`;
} else if (appDataSource.options.type === "mssql") {
const schema = appDataSource.options?.schema;
sqlSelectInfoQuery = schema
? `SELECT TOP ${nbSampleRow} * FROM ${schema}.[${currentTable.tableName}];\n`
: `SELECT TOP ${nbSampleRow} * FROM [${currentTable.tableName}];\n`;
} else if (appDataSource.options.type === "sap") {
const schema =
appDataSource.options?.schema ??
appDataSource.options?.username ??
"public";
sqlSelectInfoQuery = `SELECT * FROM "${schema}"."${currentTable.tableName}" LIMIT ${nbSampleRow};\n`;
} else if (appDataSource.options.type === "oracle") {
sqlSelectInfoQuery = `SELECT * FROM "${schema}"."${currentTable.tableName}" WHERE ROWNUM <= '${nbSampleRow}'`;
} else {
sqlSelectInfoQuery = `SELECT * FROM "${currentTable.tableName}" LIMIT ${nbSampleRow};\n`;
}
const columnNamesConcatString = `${currentTable.columns.reduce(
(completeString, column) => `${completeString} ${column.columnName}`,
""
)}\n`;
let sample = "";
try {
const infoObjectResult = nbSampleRow
? await appDataSource.query(sqlSelectInfoQuery)
: null;
sample = formatSqlResponseToSimpleTableString(infoObjectResult);
} catch (error) {
// If the request fails we catch it and only display a log message
console.log(error);
}
globalString = globalString.concat(
tableCustomDescription +
sqlCreateTableQuery +
sqlSelectInfoQuery +
columnNamesConcatString +
sample
);
}
return globalString;
};
export const getPromptTemplateFromDataSource = (
appDataSource: DataSource
): PromptTemplate => {
if (appDataSource.options.type === "postgres") {
return SQL_POSTGRES_PROMPT;
}
if (appDataSource.options.type === "sqlite") {
return SQL_SQLITE_PROMPT;
}
if (appDataSource.options.type === "mysql") {
return SQL_MYSQL_PROMPT;
}
if (appDataSource.options.type === "mssql") {
return SQL_MSSQL_PROMPT;
}
if (appDataSource.options.type === "sap") {
return SQL_SAP_HANA_PROMPT;
}
if (appDataSource.options.type === "oracle") {
return SQL_ORACLE_PROMPT;
}
return DEFAULT_SQL_DATABASE_PROMPT;
};