@dbml/connector 7.0.0 → 7.0.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +0 -0
  2. package/README.md +0 -0
  3. package/__tests__/connector.test.ts +0 -0
  4. package/__tests__/connectors/mssql/connection.json +0 -0
  5. package/__tests__/connectors/mssql/expect-out-files/schema.json +0 -0
  6. package/__tests__/connectors/mysql/connection.json +0 -0
  7. package/__tests__/connectors/mysql/expect-out-files/schema.json +0 -0
  8. package/__tests__/connectors/oracle/connection.json +0 -0
  9. package/__tests__/connectors/oracle/expect-out-files/schema.json +0 -0
  10. package/__tests__/connectors/postgres/connection.json +0 -0
  11. package/__tests__/connectors/postgres/expect-out-files/schema.json +0 -0
  12. package/__tests__/testHelpers.ts +0 -0
  13. package/dist/connectors/bigquery/index.d.ts +0 -0
  14. package/dist/connectors/connector.d.ts +0 -0
  15. package/dist/connectors/mssql/index.d.ts +0 -0
  16. package/dist/connectors/mysql/index.d.ts +0 -0
  17. package/dist/connectors/oracle/constraints.d.ts +0 -0
  18. package/dist/connectors/oracle/index.d.ts +0 -0
  19. package/dist/connectors/oracle/indexes.d.ts +0 -0
  20. package/dist/connectors/oracle/refs.d.ts +0 -0
  21. package/dist/connectors/oracle/tables.d.ts +0 -0
  22. package/dist/connectors/oracle/utils.d.ts +0 -0
  23. package/dist/connectors/postgres/index.d.ts +0 -0
  24. package/dist/connectors/snowflake/index.d.ts +0 -0
  25. package/dist/connectors/types.d.ts +0 -0
  26. package/dist/index.d.ts +0 -0
  27. package/dist/index.js +517 -517
  28. package/dist/index.mjs +1555 -1555
  29. package/dist/utils/credential-loader.d.ts +0 -0
  30. package/dist/utils/helpers.d.ts +0 -0
  31. package/dist/utils/parseSchema.d.ts +0 -0
  32. package/eslint.config.ts +1 -9
  33. package/package.json +3 -3
  34. package/src/connectors/bigquery/index.ts +0 -0
  35. package/src/connectors/connector.ts +4 -4
  36. package/src/connectors/mssql/index.ts +0 -0
  37. package/src/connectors/mysql/index.ts +2 -2
  38. package/src/connectors/oracle/constraints.ts +0 -0
  39. package/src/connectors/oracle/index.ts +3 -3
  40. package/src/connectors/oracle/indexes.ts +0 -0
  41. package/src/connectors/oracle/refs.ts +0 -0
  42. package/src/connectors/oracle/tables.ts +0 -0
  43. package/src/connectors/oracle/utils.ts +0 -0
  44. package/src/connectors/postgres/index.ts +0 -0
  45. package/src/connectors/snowflake/index.ts +1 -1
  46. package/src/connectors/types.ts +0 -0
  47. package/src/ddl_samples/bigquery.sql +0 -0
  48. package/src/ddl_samples/snowflake.sql +0 -0
  49. package/src/index.ts +0 -0
  50. package/src/utils/credential-loader.ts +0 -0
  51. package/src/utils/helpers.ts +0 -0
  52. package/src/utils/parseSchema.ts +0 -0
  53. package/tsconfig.json +0 -0
  54. package/vite.config.ts +0 -0
package/dist/index.mjs CHANGED
@@ -1,9 +1,9 @@
1
- import { Client } from "pg";
2
- import sql from "mssql";
3
- import snowflake from "snowflake-sdk";
4
1
  import { BigQuery } from "@google-cloud/bigquery";
5
2
  import { readFile } from "fs/promises";
3
+ import sql from "mssql";
6
4
  import oracledb, { getConnection } from "oracledb";
5
+ import { Client } from "pg";
6
+ import snowflake from "snowflake-sdk";
7
7
  var __defProp = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __getOwnPropNames = Object.getOwnPropertyNames, __hasOwnProp = Object.prototype.hasOwnProperty, __esmMin = (e, t) => () => (e && (t = e(e = 0)), t), __commonJSMin = (e, t) => () => (t || e((t = { exports: {} }).exports, t), t.exports), __export = (e, t) => {
8
8
  let n = {};
9
9
  for (var r in e) __defProp(n, r, {
@@ -20,7 +20,258 @@ var __defProp = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyD
20
20
  }, __toCommonJS = (e) => __hasOwnProp.call(e, "module.exports") ? e["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: !0 }), e), __require = /* @__PURE__ */ ((e) => typeof require < "u" ? require : typeof Proxy < "u" ? new Proxy(e, { get: (e, t) => (typeof require < "u" ? require : e)[t] }) : e)(function(e) {
21
21
  if (typeof require < "u") return require.apply(this, arguments);
22
22
  throw Error("Calling `require` for \"" + e + "\" in an environment that doesn't expose the `require` function.");
23
- }), SCHEMAS_DELIMITER = "schemas=", haveSchemas = (e) => e.toLowerCase().includes(SCHEMAS_DELIMITER), getSchemasPart = (e) => e ? e.toLowerCase().split(SCHEMAS_DELIMITER)[1] : "", noSchemaResult = (e) => ({
23
+ });
24
+ async function loadCredentialFromFile(e) {
25
+ try {
26
+ return await readFile(e, { encoding: "utf8" });
27
+ } catch (e) {
28
+ throw e.name === "TypeError" || e.name === "Error" ? Error(`Load credential error: ${e.message}`) : e;
29
+ }
30
+ }
31
+ function parseBigQueryCredential(e) {
32
+ try {
33
+ let { project_id: t, client_email: n, private_key: r, datasets: i } = JSON.parse(e), a = { datasets: Array.isArray(i) ? i.filter((e) => typeof e == "string") : [] };
34
+ if (t !== void 0) {
35
+ if (typeof t != "string" || !t || !t.trim()) throw Error("project_id must be a non-empty string when provided");
36
+ a.projectId = t;
37
+ }
38
+ if (n !== void 0 || r !== void 0) {
39
+ if (!n || typeof n != "string" || !n.trim()) throw Error("client_email must be a non-empty string when credentials are provided");
40
+ if (!r || typeof r != "string" || !r.trim()) throw Error("private_key must be a non-empty string when credentials are provided");
41
+ a.credentials = {
42
+ clientEmail: n,
43
+ privateKey: r
44
+ };
45
+ }
46
+ return a;
47
+ } catch (e) {
48
+ throw e instanceof SyntaxError ? Error("Credentials must be in JSON format") : e;
49
+ }
50
+ }
51
+ function getIntersection(e, t) {
52
+ return e.filter((e) => t.includes(e));
53
+ }
54
+ function getTableSchemaKey(e, t) {
55
+ if (!t || !t.trim()) throw Error("Table name must be a non-empty string");
56
+ return e ? `${e}.${t}` : `${t}`;
57
+ }
58
+ function mergeTables(e, t) {
59
+ return e.concat(t);
60
+ }
61
+ function mergeFieldDictionary(e, t) {
62
+ let n = { ...e };
63
+ return Object.keys(t).forEach((e) => {
64
+ n[e] || (n[e] = []), n[e] = n[e].concat(t[e]);
65
+ }), n;
66
+ }
67
+ function mergeIndexDictionary(e, t) {
68
+ let n = { ...e };
69
+ return Object.keys(t).forEach((e) => {
70
+ n[e] || (n[e] = []), n[e] = n[e].concat(t[e]);
71
+ }), n;
72
+ }
73
+ function mergeTableConstraintDictionary(e, t) {
74
+ let n = { ...e };
75
+ return Object.keys(t).forEach((e) => {
76
+ n[e] || (n[e] = {}), n[e] = t[e];
77
+ }), n;
78
+ }
79
+ async function connectBigQuery(t) {
80
+ let n = {};
81
+ t?.projectId && (n.projectId = t.projectId), t?.credentials?.clientEmail && t?.credentials?.privateKey && (n.credentials = {
82
+ client_email: t.credentials.clientEmail,
83
+ private_key: t.credentials.privateKey
84
+ });
85
+ let r = new BigQuery(n);
86
+ try {
87
+ return await r.query("SELECT CURRENT_DATE() as today"), r;
88
+ } catch (e) {
89
+ throw e instanceof Error ? Error(`BigQuery connection error: ${e.message}`) : e;
90
+ }
91
+ }
92
+ function getDbDefault$1(e, t) {
93
+ return t === null ? null : t === "string" ? {
94
+ value: e.slice(1, -1).replaceAll("'", "'"),
95
+ type: t
96
+ } : {
97
+ value: e,
98
+ type: t
99
+ };
100
+ }
101
+ function generateField$5(e) {
102
+ let { columnName: t, isNullable: n, dataType: r, columnDefault: i, columnDefaultType: a, columnDescription: o } = e, s = getDbDefault$1(i, a);
103
+ return {
104
+ name: t,
105
+ not_null: n === "NO",
106
+ type: {
107
+ type_name: r,
108
+ schemaName: null
109
+ },
110
+ note: { value: o || "" },
111
+ dbdefault: s,
112
+ increment: !1
113
+ };
114
+ }
115
+ async function generateTablesAndFields$4(e, t, n) {
116
+ let r = `${t}.${n}`, i = `
117
+ with
118
+ table_comments as (
119
+ select table_schema, table_name, option_value as description
120
+ from ${r}.INFORMATION_SCHEMA.TABLE_OPTIONS
121
+ where option_name = 'description'
122
+ ),
123
+ column_comments as (
124
+ select column_name, table_schema, table_name, description
125
+ from ${r}.INFORMATION_SCHEMA.COLUMN_FIELD_PATHS
126
+ where column_name = field_path
127
+ )
128
+ select
129
+ t.table_schema as tableSchema,
130
+ t.table_name as tableName,
131
+ (select description from table_comments tc where tc.table_name = t.table_name and tc.table_schema = t.table_schema) as tableDescription,
132
+ (
133
+ select description
134
+ from column_comments cc
135
+ where cc.table_name = c.table_name and cc.table_schema = c.table_schema and cc.column_name = c.column_name
136
+ ) as columnDescription,
137
+ c.column_name as columnName,
138
+ c.is_nullable as isNullable,
139
+ c.data_type as dataType,
140
+ c.column_default as columnDefault,
141
+ CASE
142
+ WHEN SAFE_CAST(c.column_default AS FLOAT64) IS NOT NULL THEN 'number'
143
+ WHEN SAFE_CAST(c.column_default AS BOOLEAN) IS NOT NULL THEN 'boolean'
144
+ -- string value is enclosed in single quotes, double quotes
145
+ WHEN REGEXP_CONTAINS(c.column_default, r"^['\\"].*['\\"]$") THEN 'string'
146
+ WHEN c.column_default = "NULL" THEN NULL
147
+ ELSE 'expression'
148
+ END AS columnDefaultType
149
+ from ${r}.INFORMATION_SCHEMA.TABLES t
150
+ join ${r}.INFORMATION_SCHEMA.COLUMNS c
151
+ on
152
+ t.table_schema = c.table_schema
153
+ and t.table_name = c.table_name
154
+ where t.table_type = 'BASE TABLE'
155
+ order by t.creation_time, c.ordinal_position;
156
+ `, [a] = await e.query({ query: i }), o = {}, s = {};
157
+ return a.forEach((e) => {
158
+ let { tableSchema: t, tableName: n, tableComment: r } = e, i = getTableSchemaKey(t, n);
159
+ o[i] || (o[i] = {
160
+ name: n,
161
+ note: { value: r || "" },
162
+ schemaName: t
163
+ }), s[i] || (s[i] = []);
164
+ let a = generateField$5(e);
165
+ s[i].push(a);
166
+ }), {
167
+ tables: Object.values(o),
168
+ fieldMap: s
169
+ };
170
+ }
171
+ async function generateIndexes$3(e, t, n) {
172
+ let r = `${t}.${n}`, i = `
173
+ select
174
+ s.index_schema as indexSchema,
175
+ s.table_name as tableName,
176
+ s.index_name as indexName,
177
+ string_agg(sc.index_column_name, ', ') as indexColumnNames
178
+ from ${r}.INFORMATION_SCHEMA.SEARCH_INDEXES s
179
+ join ${r}.INFORMATION_SCHEMA.SEARCH_INDEX_COLUMNS sc
180
+ on
181
+ s.index_schema = sc.index_schema
182
+ and s.table_name = sc.table_name
183
+ and s.index_name = sc.index_name
184
+ where sc.index_column_name = sc.index_field_path
185
+ group by s.index_schema, s.table_name, s.index_name
186
+ order by s.table_name, s.index_name;
187
+ `, [a] = await e.query(i), o = {};
188
+ return a.forEach((e) => {
189
+ let { indexSchema: t, tableName: n, indexName: r, indexColumnNames: i } = e, a = {
190
+ name: r,
191
+ type: "",
192
+ columns: [...i.split(", ").map((e) => ({
193
+ type: "column",
194
+ value: e
195
+ }))]
196
+ }, s = getTableSchemaKey(t, n);
197
+ o[s] ? o[s].push(a) : o[s] = [a];
198
+ }), o;
199
+ }
200
+ async function generateTableConstraints(e, t, n) {
201
+ let r = `${t}.${n}`, i = `
202
+ select
203
+ tc.table_schema as tableSchema,
204
+ tc.table_name as tableName,
205
+ tc.constraint_name as constraintName,
206
+ string_agg(kcu.column_name, ', ') as columnNames,
207
+ count(kcu.column_name) as columnCount,
208
+ from ${r}.INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
209
+ join ${r}.INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
210
+ on
211
+ tc.table_schema = kcu.table_schema
212
+ and tc.table_name = kcu.table_name
213
+ and tc.constraint_name = kcu.constraint_name
214
+ where tc.constraint_type = 'PRIMARY KEY'
215
+ group by tc.table_schema, tc.table_name, tc.constraint_name
216
+ order by tc.table_name, tc.constraint_name;
217
+ `, [a] = await e.query(i), o = a.filter((e) => e.columnCount && e.columnCount === 1), s = a.filter((e) => e.columnCount && e.columnCount > 1), c = {};
218
+ o.forEach((e) => {
219
+ let { tableSchema: t, tableName: n, columnNames: r } = e, i = getTableSchemaKey(t, n);
220
+ c[i] || (c[i] = {}), c[i][r] || (c[i][r] = { checks: [] }), c[i][r].pk = !0;
221
+ });
222
+ let l = {};
223
+ return s.forEach((e) => {
224
+ let { tableSchema: t, tableName: n, constraintName: r, columnNames: i } = e, a = {
225
+ name: r,
226
+ type: "",
227
+ columns: [...i.split(", ").map((e) => ({
228
+ type: "column",
229
+ value: e
230
+ }))],
231
+ pk: !0
232
+ }, o = getTableSchemaKey(t, n);
233
+ l[o] ? l[o].push(a) : l[o] = [a];
234
+ }), {
235
+ inlinePrimaryKeyMap: c,
236
+ compositePrimaryKeyMap: l
237
+ };
238
+ }
239
+ async function validateDatasetIdList(e, t) {
240
+ let [n] = await e.getDatasets(), r = n.map((e) => e.id).filter((e) => e);
241
+ return t.length === 0 ? r : getIntersection(t, r);
242
+ }
243
+ async function fetchSchemaJsonByDataset(e, t, n) {
244
+ let r = await Promise.all([
245
+ generateTablesAndFields$4(e, t, n),
246
+ generateIndexes$3(e, t, n),
247
+ generateTableConstraints(e, t, n)
248
+ ]), { tables: i, fieldMap: a } = r[0], o = r[1], { inlinePrimaryKeyMap: s, compositePrimaryKeyMap: c } = r[2];
249
+ return {
250
+ tables: i,
251
+ fields: a,
252
+ refs: [],
253
+ enums: [],
254
+ indexes: mergeIndexDictionary(o, c),
255
+ tableConstraints: s,
256
+ checks: {}
257
+ };
258
+ }
259
+ async function fetchSchemaJson(e) {
260
+ let t = parseBigQueryCredential(await loadCredentialFromFile(e)), n = await connectBigQuery(t), r = await n.getProjectId(), i = (await validateDatasetIdList(n, t.datasets)).map((e) => fetchSchemaJsonByDataset(n, r, e));
261
+ return (await Promise.all(i)).reduce((e, t) => {
262
+ let { tables: n, fields: r, indexes: i, tableConstraints: a } = t;
263
+ return e.tables = mergeTables(e.tables, n), e.fields = mergeFieldDictionary(e.fields, r), e.indexes = mergeIndexDictionary(e.indexes, i), e.tableConstraints = mergeTableConstraintDictionary(e.tableConstraints, a), e;
264
+ }, {
265
+ tables: [],
266
+ fields: {},
267
+ tableConstraints: {},
268
+ indexes: {},
269
+ refs: [],
270
+ enums: [],
271
+ checks: {}
272
+ });
273
+ }
274
+ var SCHEMAS_DELIMITER = "schemas=", haveSchemas = (e) => e.toLowerCase().includes(SCHEMAS_DELIMITER), getSchemasPart = (e) => e ? e.toLowerCase().split(SCHEMAS_DELIMITER)[1] : "", noSchemaResult = (e) => ({
24
275
  connectionString: e,
25
276
  schemas: []
26
277
  });
@@ -39,260 +290,260 @@ const parseJdbcSchema = (e) => {
39
290
  schemas: parseSchema(getSchemasPart(n))
40
291
  };
41
292
  }, parseConnectionString$1 = (e, t) => haveSchemas(e) ? t === "jdbc" ? parseJdbcSchema(e) : parseOdbcSchema(e) : noSchemaResult(e), buildSchemaQuery = (e, t, n = "AND") => t.length === 0 ? "" : `${n} ${e} IN (${t.map((e) => `'${e}'`).join(", ")})`;
42
- var getValidatedClient$2 = async (t) => {
43
- let n = new Client(t);
293
+ var MSSQL_DATE_TYPES = [
294
+ "date",
295
+ "datetime",
296
+ "datetime2",
297
+ "smalldatetime",
298
+ "datetimeoffset",
299
+ "time"
300
+ ], getValidatedClient$2 = async (e) => {
301
+ let t = await sql.connect(e);
44
302
  try {
45
- return await n.connect(), await n.query("SELECT 1"), n;
303
+ return await t.request().query("SELECT 1"), t;
46
304
  } catch (e) {
47
- throw await n.end(), e instanceof Error ? Error(`PostgreSQL connection error: ${e}`) : e;
305
+ throw t.connected && await t.close(), e instanceof Error ? Error(`SQL connection error: ${e.message}`) : e;
48
306
  }
49
- }, convertQueryBoolean$2 = (e) => e === "YES", getFieldType$4 = (e, t, n, r, i) => e === "ARRAY" ? `${t.slice(1, t.length)}[]` : n ? `${t}(${n})` : r && i ? `${t}(${r},${i})` : t, getDbdefault$3 = (e, t, n) => {
50
- if (e === "ARRAY") return {
307
+ }, convertQueryBoolean$2 = (e) => e === "YES", getFieldType$4 = (e, t, n, r) => MSSQL_DATE_TYPES.includes(e) || e === "timestamp" || e === "bit" ? e : n ? r ? `${e}(${n},${r})` : `${e}(${n})` : [
308
+ "ntext",
309
+ "text",
310
+ "image"
311
+ ].includes(e) ? e : t < 0 ? e === "xml" ? e : `${e}(MAX)` : t > 0 ? `${e}(${e === "nchar" || e === "nvarchar" ? t / 2 : t})` : e, getDbdefault$3 = (e, t, n) => {
312
+ let r = t.slice(1, -1).replace(/\(([^()]+)\)/g, "$1");
313
+ return {
51
314
  type: n,
52
- value: `ARRAY[${t.slice(6, -1).split(",").map((e) => e.split("::")[0]).join(", ")}]`
53
- };
54
- if (n === "string") {
55
- let n = t.split("::")[0];
56
- return {
57
- type: e === "json" || e === "jsonb" ? "expression" : "string",
58
- value: n.slice(1, -1)
59
- };
60
- }
61
- return {
62
- type: n,
63
- value: t
315
+ value: n === "string" ? r.slice(1, -1) : r
64
316
  };
65
- }, generateField$5 = (e) => {
66
- let { column_name: t, data_type: n, character_maximum_length: r, numeric_precision: i, numeric_scale: a, udt_schema: o, udt_name: s, identity_increment: c, is_nullable: l, column_default: u, default_type: d, column_comment: f } = e, p = u && d !== "increment" ? getDbdefault$3(n, u, d) : null;
317
+ }, generateField$4 = (e) => {
318
+ let { column_name: t, data_type: n, character_maximum_length: r, numeric_precision: i, numeric_scale: a, identity_increment: o, is_nullable: s, column_default: c, default_type: l, column_comment: u } = e, d = c && l !== "increment" ? getDbdefault$3(n, c, l) : null;
67
319
  return {
68
320
  name: t,
69
- type: n === "USER-DEFINED" ? {
70
- type_name: s,
71
- schemaName: o
72
- } : {
73
- type_name: getFieldType$4(n, s, r, i, a),
321
+ type: {
322
+ type_name: getFieldType$4(n, r, i, a),
74
323
  schemaName: null
75
324
  },
76
- dbdefault: p,
77
- not_null: !convertQueryBoolean$2(l),
78
- increment: !!c || d === "increment",
79
- note: f ? { value: f } : { value: "" }
325
+ dbdefault: d,
326
+ not_null: !convertQueryBoolean$2(s),
327
+ increment: !!o,
328
+ note: u ? { value: u } : { value: "" }
80
329
  };
81
- }, generateTablesAndFields$4 = async (e, t) => {
330
+ }, generateTablesFields = async (e, t) => {
82
331
  let n = {}, r = `
83
- WITH
84
- comments AS (
85
- SELECT DISTINCT ON (pc.relname, pn.nspname, pa.attname)
86
- pc.relname AS table_name,
87
- pn.nspname AS table_schema,
88
- pa.attname AS column_name,
89
- pd.description
90
- FROM
91
- pg_description pd
92
- JOIN
93
- pg_class pc ON pd.objoid = pc.oid
94
- JOIN
95
- pg_namespace pn ON pc.relnamespace = pn.oid
96
- LEFT JOIN
97
- pg_attribute pa ON pd.objoid = pa.attrelid AND pd.objsubid = pa.attnum
98
- WHERE
99
- pc.relkind = 'r'
100
- AND pn.nspname NOT IN ('pg_catalog', 'information_schema')
101
- ),
102
- table_positions AS (
103
- SELECT
104
- pc.oid as table_ordinal_position,
105
- pc.relname as table_name,
106
- pn.nspname as table_schema
107
- FROM pg_class pc
108
- JOIN pg_namespace pn
109
- ON pc.relnamespace = pn.oid
110
- WHERE
111
- -- r is ordinary table
112
- -- see https://www.postgresql.org/docs/14/catalog-pg-class.html#:~:text=%3D%20temporary%20table-,relkind,-char
113
- pc.relkind = 'r'
114
- AND pn.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
115
- ${buildSchemaQuery("pn.nspname", t)}
116
- )
332
+ WITH tables_and_fields AS (
333
+ SELECT
334
+ t.object_id AS table_id,
335
+ s.name AS table_schema,
336
+ t.name AS table_name,
337
+ t.create_date as table_create_date,
338
+ c.name AS column_name,
339
+ c.column_id as column_id,
340
+ ty.name AS data_type,
341
+ c.max_length AS character_maximum_length,
342
+ c.precision AS numeric_precision,
343
+ c.scale AS numeric_scale,
344
+ c.is_identity AS identity_increment,
345
+ CASE
346
+ WHEN c.is_nullable = 1 THEN 'YES'
347
+ ELSE 'NO'
348
+ END AS is_nullable,
349
+ CASE
350
+ WHEN c.default_object_id = 0 THEN NULL
351
+ ELSE OBJECT_DEFINITION(c.default_object_id)
352
+ END AS column_default,
353
+ -- Fetching table comments
354
+ p.value AS table_comment,
355
+ ep.value AS column_comment
356
+ FROM
357
+ sys.tables t
358
+ JOIN sys.schemas s ON t.schema_id = s.schema_id
359
+ JOIN sys.columns c ON t.object_id = c.object_id
360
+ JOIN sys.types ty ON c.user_type_id = ty.user_type_id
361
+ LEFT JOIN sys.extended_properties p ON p.major_id = t.object_id
362
+ AND p.name like '%description%'
363
+ AND p.minor_id = 0 -- Ensure minor_id is 0 for table comments
364
+ LEFT JOIN sys.extended_properties ep ON ep.major_id = c.object_id
365
+ AND ep.minor_id = c.column_id
366
+ AND ep.name like '%description%'
367
+ WHERE
368
+ t.type = 'U' -- User-defined tables
369
+ )
117
370
  SELECT
118
- t.table_schema,
119
- t.table_name,
120
- c.column_name,
121
- c.data_type,
122
- c.character_maximum_length,
123
- c.numeric_precision,
124
- c.numeric_scale,
125
- c.udt_schema,
126
- c.udt_name,
127
- c.identity_increment,
128
- c.is_nullable,
129
- c.column_default,
130
- c.ordinal_position,
371
+ table_schema,
372
+ table_name,
373
+ column_name,
374
+ data_type,
375
+ character_maximum_length,
376
+ numeric_precision,
377
+ numeric_scale,
378
+ identity_increment,
379
+ is_nullable,
380
+ column_default,
381
+ table_comment,
382
+ column_comment,
131
383
  CASE
132
- WHEN c.column_default IS NULL THEN NULL
133
- WHEN c.column_default LIKE 'nextval(%' THEN 'increment'
134
- WHEN c.column_default LIKE '''%' THEN 'string'
135
- WHEN c.column_default = 'true' OR c.column_default = 'false' THEN 'boolean'
136
- WHEN c.column_default ~ '^-?[0-9]+(.[0-9]+)?$' THEN 'number'
384
+ WHEN column_default LIKE '((%))' THEN 'number'
385
+ WHEN column_default LIKE '(''%'')' THEN 'string'
137
386
  ELSE 'expression'
138
- END AS default_type,
139
- (SELECT description FROM comments WHERE table_name = t.table_name AND table_schema = t.table_schema AND column_name IS NULL LIMIT 1) AS table_comment,
140
- (SELECT description FROM comments WHERE table_name = t.table_name AND table_schema = t.table_schema AND column_name = c.column_name LIMIT 1) AS column_comment
387
+ END AS default_type
141
388
  FROM
142
- information_schema.columns c
143
- JOIN
144
- information_schema.tables t ON c.table_name = t.table_name AND c.table_schema = t.table_schema
145
- JOIN
146
- table_positions tp ON tp.table_name = t.table_name AND tp.table_schema = t.table_schema
389
+ tables_and_fields
147
390
  WHERE
148
- t.table_type = 'BASE TABLE'
149
- AND t.table_schema NOT IN ('pg_catalog', 'information_schema')
150
- ${buildSchemaQuery("t.table_schema", t)}
391
+ 1 = 1
392
+ ${buildSchemaQuery("table_schema", t)}
151
393
  ORDER BY
152
- t.table_schema,
153
- tp.table_ordinal_position,
154
- c.ordinal_position
155
- ;
156
- `, i = (await e.query(r)).rows.reduce((e, t) => {
394
+ table_schema,
395
+ table_create_date,
396
+ table_id,
397
+ column_id;
398
+ `, i = (await e.query(r)).recordset.reduce((e, t) => {
157
399
  let { table_schema: r, table_name: i, table_comment: a } = t, o = `${r}.${i}`;
158
400
  e[o] || (e[o] = {
159
401
  name: i,
160
402
  schemaName: r,
161
403
  note: a ? { value: a } : { value: "" }
162
404
  }), n[o] || (n[o] = []);
163
- let s = generateField$5(t);
405
+ let s = generateField$4(t);
164
406
  return n[o].push(s), e;
165
407
  }, {});
166
408
  return {
167
409
  tables: Object.values(i),
168
410
  fields: n
169
411
  };
170
- }, generateRawRefs$1 = async (e, t) => {
412
+ }, generateRefs = async (e, t) => {
171
413
  let n = [], r = `
172
414
  SELECT
173
- tc.table_schema,
174
- tc.table_name,
175
- tc.constraint_name as fk_constraint_name,
176
- STRING_AGG(DISTINCT kcu.column_name, ',') AS column_names,
177
- ccu.table_schema AS foreign_table_schema,
178
- ccu.table_name AS foreign_table_name,
179
- STRING_AGG(DISTINCT ccu.column_name, ',') AS foreign_column_names,
180
- tc.constraint_type,
181
- rc.delete_rule AS on_delete,
182
- rc.update_rule AS on_update
183
- FROM information_schema.table_constraints AS tc
184
- JOIN information_schema.key_column_usage AS kcu
185
- ON tc.constraint_name = kcu.constraint_name
186
- AND tc.table_schema = kcu.table_schema
187
- JOIN information_schema.constraint_column_usage AS ccu
188
- ON ccu.constraint_name = tc.constraint_name
189
- JOIN information_schema.referential_constraints AS rc
190
- ON tc.constraint_name = rc.constraint_name
191
- AND tc.table_schema = rc.constraint_schema
192
- WHERE tc.constraint_type = 'FOREIGN KEY'
193
- AND tc.table_schema NOT IN ('pg_catalog', 'information_schema')
194
- ${buildSchemaQuery("tc.table_schema", t)}
195
- GROUP BY
196
- tc.table_schema,
197
- tc.table_name,
198
- tc.constraint_name,
199
- ccu.table_schema,
200
- ccu.table_name,
201
- tc.constraint_type,
202
- rc.delete_rule,
203
- rc.update_rule
415
+ s.name AS table_schema,
416
+ t.name AS table_name,
417
+ fk.name AS fk_constraint_name,
418
+ STUFF((
419
+ SELECT ',' + c1.name
420
+ FROM sys.foreign_key_columns AS fkc
421
+ JOIN sys.columns AS c1 ON fkc.parent_object_id = c1.object_id AND fkc.parent_column_id = c1.column_id
422
+ WHERE fkc.constraint_object_id = fk.object_id
423
+ FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS column_names,
424
+ s2.name AS foreign_table_schema,
425
+ t2.name AS foreign_table_name,
426
+ STUFF((
427
+ SELECT ',' + c2.name
428
+ FROM sys.foreign_key_columns AS fkc
429
+ JOIN sys.columns AS c2 ON fkc.referenced_object_id = c2.object_id AND fkc.referenced_column_id = c2.column_id
430
+ WHERE fkc.constraint_object_id = fk.object_id
431
+ FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS foreign_column_names,
432
+ fk.type_desc AS constraint_type,
433
+ fk.delete_referential_action_desc AS on_delete,
434
+ fk.update_referential_action_desc AS on_update
435
+ FROM sys.foreign_keys AS fk
436
+ JOIN sys.tables AS t ON fk.parent_object_id = t.object_id
437
+ JOIN sys.schemas AS s ON t.schema_id = s.schema_id
438
+ JOIN sys.tables AS t2 ON fk.referenced_object_id = t2.object_id
439
+ JOIN sys.schemas AS s2 ON t2.schema_id = s2.schema_id
440
+ WHERE s.name NOT IN ('sys', 'information_schema')
441
+ ${buildSchemaQuery("s.name", t)}
204
442
  ORDER BY
205
- tc.table_schema,
206
- tc.table_name;
207
- `;
208
- return (await e.query(r)).rows.forEach((e) => {
209
- let { table_schema: t, fk_constraint_name: r, table_name: i, column_names: a, foreign_table_schema: o, foreign_table_name: s, foreign_column_names: c, on_delete: l, on_update: u } = e, d = {
210
- tableName: i,
211
- schemaName: t,
212
- fieldNames: a.split(","),
213
- relation: "*"
214
- }, f = {
215
- tableName: s,
216
- schemaName: o,
217
- fieldNames: c.split(","),
218
- relation: "1"
219
- };
220
- n.push({
443
+ s.name,
444
+ t.name;
445
+ `, i = await e.query(r), a = (e, t) => e.length === t.length ? e.every((e, n) => e.tableName === t[n].tableName && e.schemaName === t[n].schemaName && e.fieldNames.length === t[n].fieldNames.length && e.fieldNames.every((e, r) => e === t[n].fieldNames[r])) : !1;
446
+ return i.recordset.forEach((e) => {
447
+ let { table_schema: t, fk_constraint_name: r, table_name: i, column_names: o, foreign_table_schema: s, foreign_table_name: c, foreign_column_names: l, on_delete: u, on_update: d } = e, f = {
221
448
  name: r,
222
- endpoints: [d, f],
223
- onDelete: l === "NO ACTION" ? null : l,
224
- onUpdate: u === "NO ACTION" ? null : u
225
- });
449
+ endpoints: [{
450
+ tableName: i,
451
+ schemaName: t,
452
+ fieldNames: o.split(","),
453
+ relation: "*"
454
+ }, {
455
+ tableName: c,
456
+ schemaName: s,
457
+ fieldNames: l.split(","),
458
+ relation: "1"
459
+ }],
460
+ onDelete: u === "NO_ACTION" ? null : u,
461
+ onUpdate: d === "NO_ACTION" ? null : d
462
+ };
463
+ n.some((e) => a(e.endpoints, f.endpoints)) || n.push(f);
226
464
  }), n;
227
465
  }, generateIndexesAndConstraints$1 = async (e, t) => {
228
466
  let n = `
229
467
  WITH user_tables AS (
230
468
  SELECT
231
- schemaname AS tableschema,
232
- tablename
233
- FROM pg_tables
234
- WHERE schemaname NOT IN ('pg_catalog', 'information_schema') -- Exclude system schemas
235
- AND tablename NOT LIKE 'pg_%' -- Exclude PostgreSQL system tables
236
- AND tablename NOT LIKE 'sql_%' -- Exclude SQL standard tables
469
+ TABLE_SCHEMA,
470
+ TABLE_NAME
471
+ FROM
472
+ INFORMATION_SCHEMA.TABLES
473
+ WHERE
474
+ TABLE_TYPE = 'BASE TABLE' -- Ensure we are only getting base tables
475
+ AND TABLE_NAME NOT LIKE 'dt%'
476
+ AND TABLE_NAME NOT LIKE 'syscs%'
477
+ AND TABLE_NAME NOT LIKE 'sysss%'
478
+ AND TABLE_NAME NOT LIKE 'sysrs%'
479
+ AND TABLE_NAME NOT LIKE 'sysxlgc%'
237
480
  ),
238
481
  index_info AS (
239
482
  SELECT
240
- t.relnamespace::regnamespace::text AS table_schema,
241
- t.relname AS table_name,
242
- i.relname AS index_name,
243
- ix.indisunique AS is_unique,
244
- ix.indisprimary AS is_primary,
245
- am.amname AS index_type,
246
- array_to_string(array_agg(a.attname ORDER BY x.n), ', ') AS columns,
247
- pg_get_expr(ix.indexprs, ix.indrelid) AS expressions,
483
+ SCHEMA_NAME(t.schema_id) AS table_schema, -- Add schema information
484
+ OBJECT_NAME(i.object_id) AS table_name,
485
+ i.name AS index_name,
486
+ i.is_unique,
248
487
  CASE
249
- WHEN ix.indisprimary THEN 'PRIMARY KEY'
250
- WHEN ix.indisunique THEN 'UNIQUE'
488
+ WHEN i.type = 1 THEN 1
489
+ ELSE 0
490
+ END AS is_primary,
491
+ i.type_desc AS index_type,
492
+ STUFF((
493
+ SELECT
494
+ ', ' + c.name
495
+ FROM
496
+ sys.index_columns ic
497
+ JOIN sys.columns c ON ic.column_id = c.column_id AND ic.object_id = c.object_id
498
+ WHERE
499
+ ic.index_id = i.index_id
500
+ AND ic.object_id = i.object_id
501
+ AND OBJECT_NAME(ic.object_id) IN (SELECT TABLE_NAME FROM user_tables) -- Filter for user tables
502
+ ORDER BY
503
+ ic.key_ordinal
504
+ FOR XML PATH('')
505
+ ), 1, 2, '') AS columns,
506
+ CASE
507
+ WHEN i.type = 1 THEN 'PRIMARY KEY'
508
+ WHEN i.is_unique = 1 THEN 'UNIQUE'
251
509
  ELSE NULL
252
510
  END AS constraint_type
253
511
  FROM
254
- pg_class t
255
- JOIN pg_index ix ON t.oid = ix.indrelid
256
- JOIN pg_class i ON i.oid = ix.indexrelid
257
- LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
258
- JOIN pg_am am ON i.relam = am.oid
259
- LEFT JOIN generate_subscripts(ix.indkey, 1) AS x(n) ON a.attnum = ix.indkey[x.n]
512
+ sys.indexes i
513
+ JOIN sys.tables t ON i.object_id = t.object_id
260
514
  WHERE
261
- t.relkind = 'r'
262
- AND t.relname NOT LIKE 'pg_%'
263
- AND t.relname NOT LIKE 'sql_%'
264
- GROUP BY
265
- t.relnamespace, t.relname, i.relname, ix.indisunique, ix.indisprimary, am.amname, ix.indexprs, ix.indrelid
515
+ t.is_ms_shipped = 0
516
+ AND i.type <> 0
266
517
  )
267
518
  SELECT
268
- ut.tableschema AS table_schema,
269
- ut.tablename AS table_name,
519
+ ut.TABLE_SCHEMA AS table_schema,
520
+ ut.TABLE_NAME AS table_name,
270
521
  ii.index_name,
271
522
  ii.is_unique,
272
523
  ii.is_primary,
273
524
  ii.index_type,
274
- ii.columns AS index_columns,
275
- ii.expressions AS index_expressions,
276
- ii.constraint_type -- Retained constraint type here
525
+ ii.columns,
526
+ ii.constraint_type
277
527
  FROM
278
528
  user_tables ut
279
529
  LEFT JOIN
280
- index_info ii ON ut.tableschema = ii.table_schema AND ut.tablename = ii.table_name
281
- WHERE ii.columns IS NOT NULL
282
- ${buildSchemaQuery("ut.tableschema", t)}
530
+ index_info ii ON ut.TABLE_NAME = ii.table_name
531
+ AND ut.TABLE_SCHEMA = ii.table_schema
532
+ WHERE
533
+ ii.columns IS NOT NULL
534
+ ${buildSchemaQuery("ut.TABLE_SCHEMA", t)}
283
535
  ORDER BY
284
- ut.tablename,
536
+ ut.TABLE_NAME,
285
537
  ii.constraint_type,
286
- ii.index_name
287
- ;
288
- `, { outOfLineIndexes: r, inlineIndexes: i } = (await e.query(n)).rows.reduce((e, t) => {
289
- let { constraint_type: n, index_columns: r } = t;
290
- return r === "null" || r.trim() === "" || (r.split(",").length === 1 && (n === "PRIMARY KEY" || n === "UNIQUE") ? e.inlineIndexes.push(t) : e.outOfLineIndexes.push(t)), e;
538
+ ii.index_name;
539
+ `, { outOfLineIndexes: r, inlineIndexes: i } = (await e.query(n)).recordset.reduce((e, t) => {
540
+ let { constraint_type: n, columns: r } = t;
541
+ return r === "null" || r.trim() === "" || (n === "PRIMARY KEY" || n === "UNIQUE" ? e.inlineIndexes.push(t) : e.outOfLineIndexes.push(t)), e;
291
542
  }, {
292
- outOfLineIndexes: [],
293
- inlineIndexes: []
543
+ inlineIndexes: [],
544
+ outOfLineIndexes: []
294
545
  }), a = r.reduce((e, t) => {
295
- let { table_schema: n, table_name: r, index_name: i, index_type: a, index_columns: o, index_expressions: s, is_primary: c, is_unique: l } = t, u = o.split(",").map((e) => ({
546
+ let { table_schema: n, table_name: r, index_name: i, index_type: a, columns: o, expressions: s, is_unique: c, is_primary: l } = t, u = o.split(",").map((e) => ({
296
547
  type: "column",
297
548
  value: e.trim()
298
549
  })), d = s ? s.split(",").map((e) => ({
@@ -302,445 +553,124 @@ var getValidatedClient$2 = async (t) => {
302
553
  name: i,
303
554
  type: a,
304
555
  columns: [...u, ...d],
305
- pk: !!c,
306
- unique: !c && !!l
556
+ pk: !!l,
557
+ unique: !l && !!c
307
558
  }, p = `${n}.${r}`;
308
559
  return e[p] ? e[p].push(f) : e[p] = [f], e;
309
560
  }, {}), o = {};
310
561
  i.forEach((e) => {
311
- let { table_schema: t, table_name: n, index_columns: r, constraint_type: i } = e, a = `${t}.${n}`;
562
+ let { table_schema: t, table_name: n, columns: r, constraint_type: i } = e, a = `${t}.${n}`;
312
563
  o[a] || (o[a] = {}), r.split(",").map((e) => e.trim()).forEach((e) => {
313
564
  o[a][e] || (o[a][e] = { checks: [] }), i === "PRIMARY KEY" && (o[a][e].pk = !0), i === "UNIQUE" && !o[a][e].pk && (o[a][e].unique = !0);
314
565
  });
315
- }, {});
566
+ });
316
567
  let s = `
317
568
  SELECT
318
- n.nspname AS table_schema,
319
- c.relname AS table_name,
320
- MAX(a.attname) AS column_name,
321
- con.conname AS check_name,
322
- pg_get_constraintdef(con.oid) AS check_definition,
323
- CASE
324
- WHEN COUNT(*) = 1 THEN TRUE
325
- ELSE FALSE
326
- END AS is_column_constraint
569
+ OBJECT_SCHEMA_NAME(cc.parent_object_id) AS table_schema,
570
+ OBJECT_NAME(cc.parent_object_id) AS table_name,
571
+ c.name AS column_name,
572
+ cc.name AS check_name,
573
+ cc.definition AS check_expression
327
574
  FROM
328
- pg_catalog.pg_constraint AS con
329
- JOIN
330
- pg_catalog.pg_class AS c
331
- ON con.conrelid = c.oid
332
- LEFT JOIN
333
- pg_catalog.pg_namespace AS n
334
- ON c.relnamespace = n.oid
575
+ sys.check_constraints cc
335
576
  LEFT JOIN
336
- pg_catalog.pg_attribute AS a
337
- ON a.attrelid = c.oid AND a.attnum = ANY(con.conkey)
338
- WHERE con.contype = 'c' -- 'c' for CHECK constraints
339
- ${buildSchemaQuery("n.nspname", t)}
340
- GROUP BY
341
- con.conname,
342
- n.nspname,
343
- c.relname,
344
- con.oid
577
+ sys.columns c ON cc.parent_object_id = c.object_id AND cc.parent_column_id = c.column_id
578
+ WHERE 1 = 1
579
+ ${buildSchemaQuery("OBJECT_SCHEMA_NAME(cc.parent_object_id)", t)}
345
580
  `, c = await e.query(s), l = {};
346
- return c.rows.forEach((e) => {
347
- let { table_schema: t, table_name: n, check_name: r, check_definition: i, column_name: a, is_column_constraint: s } = e;
348
- if (typeof t != "string" || typeof n != "string" || typeof i != "string" || !i.match(/CHECK \(\(.*\)\)/) || s && typeof a != "string") return;
349
- let c = `${t}.${n}`;
350
- if (s) {
351
- o[c] || (o[c] = {}), o[c][a] || (o[c][a] = { checks: [] }), o[c][a].checks.push({
352
- name: r || void 0,
353
- expression: i.slice(8, -2)
581
+ return c.recordset.forEach((e) => {
582
+ let { table_schema: t, table_name: n, column_name: r, check_name: i, check_expression: a } = e, s = `${t}.${n}`;
583
+ if (a) {
584
+ if (r) {
585
+ o[s] || (o[s] = {}), o[s][r] || (o[s][r] = { checks: [] }), o[s][r].checks.push({
586
+ name: i,
587
+ expression: a.slice(1, -1)
588
+ });
589
+ return;
590
+ }
591
+ l[s] || (l[s] = []), l[s].push({
592
+ name: i,
593
+ expression: a.slice(1, -1)
354
594
  });
355
- return;
356
595
  }
357
- l[c] || (l[c] = []), l[c].push({
358
- name: r || void 0,
359
- expression: i.slice(8, -2)
360
- });
361
596
  }), {
362
597
  indexes: a,
363
598
  tableConstraints: o,
364
599
  checks: l
365
600
  };
366
- }, generateRawEnums = async (e, t) => {
367
- let n = `
368
- SELECT DISTINCT
369
- n.nspname AS schema_name,
370
- t.typname AS enum_type,
371
- e.enumlabel AS enum_value,
372
- e.enumsortorder AS sort_order
373
- FROM
374
- pg_enum e
375
- JOIN
376
- pg_type t ON e.enumtypid = t.oid
377
- JOIN
378
- pg_namespace n ON t.typnamespace = n.oid
379
- ${buildSchemaQuery("n.nspname", t, "WHERE")}
380
- ORDER BY
381
- schema_name,
382
- enum_type,
383
- sort_order;
384
- ;
385
- `, r = (await e.query(n)).rows.reduce((e, t) => {
386
- let { schema_name: n, enum_type: r, enum_value: i } = t, a = `${n}.${r}`;
387
- return e[a] || (e[a] = {
388
- name: r,
389
- schemaName: n,
390
- values: []
391
- }), e[a].values.push({ name: i }), e;
392
- }, {});
393
- return Object.values(r);
394
- }, fetchSchemaJson = async (e) => {
395
- let { connectionString: t, schemas: n } = parseConnectionString$1(e, "jdbc"), r = await getValidatedClient$2(t);
601
+ }, fetchSchemaJson$1 = async (e) => {
602
+ let { connectionString: t, schemas: n } = parseConnectionString$1(e, "odbc"), r = await getValidatedClient$2(t);
396
603
  try {
397
- let e = generateTablesAndFields$4(r, n), t = generateIndexesAndConstraints$1(r, n), i = generateRawRefs$1(r, n), a = generateRawEnums(r, n), o = await Promise.all([
604
+ let e = generateTablesFields(r, n), t = generateIndexesAndConstraints$1(r, n), i = generateRefs(r, n), a = await Promise.all([
398
605
  e,
399
606
  t,
400
- i,
401
- a
402
- ]), { tables: s, fields: c } = o[0], { indexes: l, tableConstraints: u, checks: d } = o[1];
607
+ i
608
+ ]), { tables: o, fields: s } = a[0], { indexes: c, tableConstraints: l, checks: u } = a[1];
403
609
  return {
404
- tables: s,
405
- fields: c,
406
- refs: o[2],
407
- enums: o[3],
408
- indexes: l,
409
- tableConstraints: u,
410
- checks: d
610
+ tables: o,
611
+ fields: s,
612
+ enums: [],
613
+ refs: a[2],
614
+ indexes: c,
615
+ tableConstraints: l,
616
+ checks: u
411
617
  };
412
618
  } finally {
413
- await r.end();
619
+ await r.close();
414
620
  }
415
- }, MSSQL_DATE_TYPES = [
416
- "date",
417
- "datetime",
418
- "datetime2",
419
- "smalldatetime",
420
- "datetimeoffset",
421
- "time"
422
- ], getValidatedClient$1 = async (e) => {
423
- let n = await sql.connect(e);
621
+ }, _freeGlobal_default = typeof global == "object" && global && global.Object === Object && global, freeSelf = typeof self == "object" && self && self.Object === Object && self, _Symbol_default = (_freeGlobal_default || freeSelf || Function("return this")()).Symbol, objectProto$1 = Object.prototype, hasOwnProperty$1 = objectProto$1.hasOwnProperty, nativeObjectToString$1 = objectProto$1.toString, symToStringTag$1 = _Symbol_default ? _Symbol_default.toStringTag : void 0;
622
+ function getRawTag(e) {
623
+ var t = hasOwnProperty$1.call(e, symToStringTag$1), n = e[symToStringTag$1];
424
624
  try {
425
- return await n.request().query("SELECT 1"), n;
426
- } catch (e) {
427
- throw n.connected && await n.close(), e instanceof Error ? Error(`SQL connection error: ${e.message}`) : e;
428
- }
429
- }, convertQueryBoolean$1 = (e) => e === "YES", getFieldType$3 = (e, t, n, r) => MSSQL_DATE_TYPES.includes(e) || e === "timestamp" || e === "bit" ? e : n ? r ? `${e}(${n},${r})` : `${e}(${n})` : [
430
- "ntext",
431
- "text",
432
- "image"
433
- ].includes(e) ? e : t < 0 ? e === "xml" ? e : `${e}(MAX)` : t > 0 ? `${e}(${e === "nchar" || e === "nvarchar" ? t / 2 : t})` : e, getDbdefault$2 = (e, t, n) => {
434
- let r = t.slice(1, -1).replace(/\(([^()]+)\)/g, "$1");
435
- return {
436
- type: n,
437
- value: n === "string" ? r.slice(1, -1) : r
438
- };
439
- }, generateField$4 = (e) => {
440
- let { column_name: t, data_type: n, character_maximum_length: r, numeric_precision: i, numeric_scale: a, identity_increment: o, is_nullable: s, column_default: c, default_type: l, column_comment: u } = e, d = c && l !== "increment" ? getDbdefault$2(n, c, l) : null;
441
- return {
442
- name: t,
443
- type: {
444
- type_name: getFieldType$3(n, r, i, a),
445
- schemaName: null
446
- },
447
- dbdefault: d,
448
- not_null: !convertQueryBoolean$1(s),
449
- increment: !!o,
450
- note: u ? { value: u } : { value: "" }
451
- };
452
- }, generateTablesFields = async (e, t) => {
453
- let n = {}, r = `
454
- WITH tables_and_fields AS (
455
- SELECT
456
- t.object_id AS table_id,
457
- s.name AS table_schema,
458
- t.name AS table_name,
459
- t.create_date as table_create_date,
460
- c.name AS column_name,
461
- c.column_id as column_id,
462
- ty.name AS data_type,
463
- c.max_length AS character_maximum_length,
464
- c.precision AS numeric_precision,
465
- c.scale AS numeric_scale,
466
- c.is_identity AS identity_increment,
467
- CASE
468
- WHEN c.is_nullable = 1 THEN 'YES'
469
- ELSE 'NO'
470
- END AS is_nullable,
471
- CASE
472
- WHEN c.default_object_id = 0 THEN NULL
473
- ELSE OBJECT_DEFINITION(c.default_object_id)
474
- END AS column_default,
475
- -- Fetching table comments
476
- p.value AS table_comment,
477
- ep.value AS column_comment
478
- FROM
479
- sys.tables t
480
- JOIN sys.schemas s ON t.schema_id = s.schema_id
481
- JOIN sys.columns c ON t.object_id = c.object_id
482
- JOIN sys.types ty ON c.user_type_id = ty.user_type_id
483
- LEFT JOIN sys.extended_properties p ON p.major_id = t.object_id
484
- AND p.name like '%description%'
485
- AND p.minor_id = 0 -- Ensure minor_id is 0 for table comments
486
- LEFT JOIN sys.extended_properties ep ON ep.major_id = c.object_id
487
- AND ep.minor_id = c.column_id
488
- AND ep.name like '%description%'
489
- WHERE
490
- t.type = 'U' -- User-defined tables
491
- )
492
- SELECT
493
- table_schema,
494
- table_name,
495
- column_name,
496
- data_type,
497
- character_maximum_length,
498
- numeric_precision,
499
- numeric_scale,
500
- identity_increment,
501
- is_nullable,
502
- column_default,
503
- table_comment,
504
- column_comment,
505
- CASE
506
- WHEN column_default LIKE '((%))' THEN 'number'
507
- WHEN column_default LIKE '(''%'')' THEN 'string'
508
- ELSE 'expression'
509
- END AS default_type
510
- FROM
511
- tables_and_fields
512
- WHERE
513
- 1 = 1
514
- ${buildSchemaQuery("table_schema", t)}
515
- ORDER BY
516
- table_schema,
517
- table_create_date,
518
- table_id,
519
- column_id;
520
- `, i = (await e.query(r)).recordset.reduce((e, t) => {
521
- let { table_schema: r, table_name: i, table_comment: a } = t, o = `${r}.${i}`;
522
- e[o] || (e[o] = {
523
- name: i,
524
- schemaName: r,
525
- note: a ? { value: a } : { value: "" }
526
- }), n[o] || (n[o] = []);
527
- let s = generateField$4(t);
528
- return n[o].push(s), e;
529
- }, {});
530
- return {
531
- tables: Object.values(i),
532
- fields: n
533
- };
534
- }, generateRefs = async (e, t) => {
535
- let n = [], r = `
536
- SELECT
537
- s.name AS table_schema,
538
- t.name AS table_name,
539
- fk.name AS fk_constraint_name,
540
- STUFF((
541
- SELECT ',' + c1.name
542
- FROM sys.foreign_key_columns AS fkc
543
- JOIN sys.columns AS c1 ON fkc.parent_object_id = c1.object_id AND fkc.parent_column_id = c1.column_id
544
- WHERE fkc.constraint_object_id = fk.object_id
545
- FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS column_names,
546
- s2.name AS foreign_table_schema,
547
- t2.name AS foreign_table_name,
548
- STUFF((
549
- SELECT ',' + c2.name
550
- FROM sys.foreign_key_columns AS fkc
551
- JOIN sys.columns AS c2 ON fkc.referenced_object_id = c2.object_id AND fkc.referenced_column_id = c2.column_id
552
- WHERE fkc.constraint_object_id = fk.object_id
553
- FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS foreign_column_names,
554
- fk.type_desc AS constraint_type,
555
- fk.delete_referential_action_desc AS on_delete,
556
- fk.update_referential_action_desc AS on_update
557
- FROM sys.foreign_keys AS fk
558
- JOIN sys.tables AS t ON fk.parent_object_id = t.object_id
559
- JOIN sys.schemas AS s ON t.schema_id = s.schema_id
560
- JOIN sys.tables AS t2 ON fk.referenced_object_id = t2.object_id
561
- JOIN sys.schemas AS s2 ON t2.schema_id = s2.schema_id
562
- WHERE s.name NOT IN ('sys', 'information_schema')
563
- ${buildSchemaQuery("s.name", t)}
564
- ORDER BY
565
- s.name,
566
- t.name;
567
- `, i = await e.query(r), a = (e, t) => e.length === t.length ? e.every((e, n) => e.tableName === t[n].tableName && e.schemaName === t[n].schemaName && e.fieldNames.length === t[n].fieldNames.length && e.fieldNames.every((e, r) => e === t[n].fieldNames[r])) : !1;
568
- return i.recordset.forEach((e) => {
569
- let { table_schema: t, fk_constraint_name: r, table_name: i, column_names: o, foreign_table_schema: s, foreign_table_name: c, foreign_column_names: l, on_delete: u, on_update: d } = e, f = {
570
- name: r,
571
- endpoints: [{
572
- tableName: i,
573
- schemaName: t,
574
- fieldNames: o.split(","),
575
- relation: "*"
576
- }, {
577
- tableName: c,
578
- schemaName: s,
579
- fieldNames: l.split(","),
580
- relation: "1"
581
- }],
582
- onDelete: u === "NO_ACTION" ? null : u,
583
- onUpdate: d === "NO_ACTION" ? null : d
584
- };
585
- n.some((e) => a(e.endpoints, f.endpoints)) || n.push(f);
586
- }), n;
587
- }, generateIndexesAndConstraints = async (e, t) => {
588
- let n = `
589
- WITH user_tables AS (
590
- SELECT
591
- TABLE_SCHEMA,
592
- TABLE_NAME
593
- FROM
594
- INFORMATION_SCHEMA.TABLES
595
- WHERE
596
- TABLE_TYPE = 'BASE TABLE' -- Ensure we are only getting base tables
597
- AND TABLE_NAME NOT LIKE 'dt%'
598
- AND TABLE_NAME NOT LIKE 'syscs%'
599
- AND TABLE_NAME NOT LIKE 'sysss%'
600
- AND TABLE_NAME NOT LIKE 'sysrs%'
601
- AND TABLE_NAME NOT LIKE 'sysxlgc%'
602
- ),
603
- index_info AS (
604
- SELECT
605
- SCHEMA_NAME(t.schema_id) AS table_schema, -- Add schema information
606
- OBJECT_NAME(i.object_id) AS table_name,
607
- i.name AS index_name,
608
- i.is_unique,
609
- CASE
610
- WHEN i.type = 1 THEN 1
611
- ELSE 0
612
- END AS is_primary,
613
- i.type_desc AS index_type,
614
- STUFF((
615
- SELECT
616
- ', ' + c.name
617
- FROM
618
- sys.index_columns ic
619
- JOIN sys.columns c ON ic.column_id = c.column_id AND ic.object_id = c.object_id
620
- WHERE
621
- ic.index_id = i.index_id
622
- AND ic.object_id = i.object_id
623
- AND OBJECT_NAME(ic.object_id) IN (SELECT TABLE_NAME FROM user_tables) -- Filter for user tables
624
- ORDER BY
625
- ic.key_ordinal
626
- FOR XML PATH('')
627
- ), 1, 2, '') AS columns,
628
- CASE
629
- WHEN i.type = 1 THEN 'PRIMARY KEY'
630
- WHEN i.is_unique = 1 THEN 'UNIQUE'
631
- ELSE NULL
632
- END AS constraint_type
633
- FROM
634
- sys.indexes i
635
- JOIN sys.tables t ON i.object_id = t.object_id
636
- WHERE
637
- t.is_ms_shipped = 0
638
- AND i.type <> 0
639
- )
640
- SELECT
641
- ut.TABLE_SCHEMA AS table_schema,
642
- ut.TABLE_NAME AS table_name,
643
- ii.index_name,
644
- ii.is_unique,
645
- ii.is_primary,
646
- ii.index_type,
647
- ii.columns,
648
- ii.constraint_type
649
- FROM
650
- user_tables ut
651
- LEFT JOIN
652
- index_info ii ON ut.TABLE_NAME = ii.table_name
653
- AND ut.TABLE_SCHEMA = ii.table_schema
654
- WHERE
655
- ii.columns IS NOT NULL
656
- ${buildSchemaQuery("ut.TABLE_SCHEMA", t)}
657
- ORDER BY
658
- ut.TABLE_NAME,
659
- ii.constraint_type,
660
- ii.index_name;
661
- `, { outOfLineIndexes: r, inlineIndexes: i } = (await e.query(n)).recordset.reduce((e, t) => {
662
- let { constraint_type: n, columns: r } = t;
663
- return r === "null" || r.trim() === "" || (n === "PRIMARY KEY" || n === "UNIQUE" ? e.inlineIndexes.push(t) : e.outOfLineIndexes.push(t)), e;
664
- }, {
665
- inlineIndexes: [],
666
- outOfLineIndexes: []
667
- }), a = r.reduce((e, t) => {
668
- let { table_schema: n, table_name: r, index_name: i, index_type: a, columns: o, expressions: s, is_unique: c, is_primary: l } = t, u = o.split(",").map((e) => ({
669
- type: "column",
670
- value: e.trim()
671
- })), d = s ? s.split(",").map((e) => ({
672
- type: "expression",
673
- value: e
674
- })) : [], f = {
675
- name: i,
676
- type: a,
677
- columns: [...u, ...d],
678
- pk: !!l,
679
- unique: !l && !!c
680
- }, p = `${n}.${r}`;
681
- return e[p] ? e[p].push(f) : e[p] = [f], e;
682
- }, {}), o = {};
683
- i.forEach((e) => {
684
- let { table_schema: t, table_name: n, columns: r, constraint_type: i } = e, a = `${t}.${n}`;
685
- o[a] || (o[a] = {}), r.split(",").map((e) => e.trim()).forEach((e) => {
686
- o[a][e] || (o[a][e] = { checks: [] }), i === "PRIMARY KEY" && (o[a][e].pk = !0), i === "UNIQUE" && !o[a][e].pk && (o[a][e].unique = !0);
687
- });
688
- });
689
- let s = `
690
- SELECT
691
- OBJECT_SCHEMA_NAME(cc.parent_object_id) AS table_schema,
692
- OBJECT_NAME(cc.parent_object_id) AS table_name,
693
- c.name AS column_name,
694
- cc.name AS check_name,
695
- cc.definition AS check_expression
696
- FROM
697
- sys.check_constraints cc
698
- LEFT JOIN
699
- sys.columns c ON cc.parent_object_id = c.object_id AND cc.parent_column_id = c.column_id
700
- WHERE 1 = 1
701
- ${buildSchemaQuery("OBJECT_SCHEMA_NAME(cc.parent_object_id)", t)}
702
- `, c = await e.query(s), l = {};
703
- return c.recordset.forEach((e) => {
704
- let { table_schema: t, table_name: n, column_name: r, check_name: i, check_expression: a } = e, s = `${t}.${n}`;
705
- if (a) {
706
- if (r) {
707
- o[s] || (o[s] = {}), o[s][r] || (o[s][r] = { checks: [] }), o[s][r].checks.push({
708
- name: i,
709
- expression: a.slice(1, -1)
710
- });
711
- return;
712
- }
713
- l[s] || (l[s] = []), l[s].push({
714
- name: i,
715
- expression: a.slice(1, -1)
716
- });
717
- }
718
- }), {
719
- indexes: a,
720
- tableConstraints: o,
721
- checks: l
722
- };
723
- }, fetchSchemaJson$1 = async (e) => {
724
- let { connectionString: t, schemas: n } = parseConnectionString$1(e, "odbc"), r = await getValidatedClient$1(t);
725
- try {
726
- let e = generateTablesFields(r, n), t = generateIndexesAndConstraints(r, n), i = generateRefs(r, n), a = await Promise.all([
727
- e,
728
- t,
729
- i
730
- ]), { tables: o, fields: s } = a[0], { indexes: c, tableConstraints: l, checks: u } = a[1];
731
- return {
732
- tables: o,
733
- fields: s,
734
- enums: [],
735
- refs: a[2],
736
- indexes: c,
737
- tableConstraints: l,
738
- checks: u
739
- };
740
- } finally {
741
- await r.close();
625
+ e[symToStringTag$1] = void 0;
626
+ var r = !0;
627
+ } catch {}
628
+ var i = nativeObjectToString$1.call(e);
629
+ return r && (t ? e[symToStringTag$1] = n : delete e[symToStringTag$1]), i;
630
+ }
631
+ var _getRawTag_default = getRawTag, nativeObjectToString = Object.prototype.toString;
632
+ function objectToString(e) {
633
+ return nativeObjectToString.call(e);
634
+ }
635
+ var _objectToString_default = objectToString, nullTag = "[object Null]", undefinedTag = "[object Undefined]", symToStringTag = _Symbol_default ? _Symbol_default.toStringTag : void 0;
636
+ function baseGetTag(e) {
637
+ return e == null ? e === void 0 ? undefinedTag : nullTag : symToStringTag && symToStringTag in Object(e) ? _getRawTag_default(e) : _objectToString_default(e);
638
+ }
639
+ var _baseGetTag_default = baseGetTag;
640
+ function isObjectLike(e) {
641
+ return typeof e == "object" && !!e;
642
+ }
643
+ var isObjectLike_default = isObjectLike, isArray_default = Array.isArray, argsTag = "[object Arguments]";
644
+ function baseIsArguments(e) {
645
+ return isObjectLike_default(e) && _baseGetTag_default(e) == argsTag;
646
+ }
647
+ var _baseIsArguments_default = baseIsArguments, objectProto = Object.prototype, hasOwnProperty = objectProto.hasOwnProperty, propertyIsEnumerable = objectProto.propertyIsEnumerable, isArguments_default = _baseIsArguments_default(function() {
648
+ return arguments;
649
+ }()) ? _baseIsArguments_default : function(e) {
650
+ return isObjectLike_default(e) && hasOwnProperty.call(e, "callee") && !propertyIsEnumerable.call(e, "callee");
651
+ };
652
+ function arrayPush(e, t) {
653
+ for (var n = -1, r = t.length, i = e.length; ++n < r;) e[i + n] = t[n];
654
+ return e;
655
+ }
656
+ var _arrayPush_default = arrayPush, spreadableSymbol = _Symbol_default ? _Symbol_default.isConcatSpreadable : void 0;
657
+ function isFlattenable(e) {
658
+ return isArray_default(e) || isArguments_default(e) || !!(spreadableSymbol && e && e[spreadableSymbol]);
659
+ }
660
+ var _isFlattenable_default = isFlattenable;
661
+ function baseFlatten(e, t, n, r, i) {
662
+ var a = -1, o = e.length;
663
+ for (n ||= _isFlattenable_default, i ||= []; ++a < o;) {
664
+ var s = e[a];
665
+ t > 0 && n(s) ? t > 1 ? baseFlatten(s, t - 1, n, r, i) : _arrayPush_default(i, s) : r || (i[i.length] = s);
742
666
  }
743
- }, require_SqlString = /* @__PURE__ */ __commonJSMin(((e) => {
667
+ return i;
668
+ }
669
+ var _baseFlatten_default = baseFlatten;
670
+ function flatten(e) {
671
+ return e != null && e.length ? _baseFlatten_default(e, 1) : [];
672
+ }
673
+ var flatten_default = flatten, require_SqlString = /* @__PURE__ */ __commonJSMin(((e) => {
744
674
  var t = e, n = /`/g, r = /\./g, i = /[\0\b\t\n\r\x1a\"\'\\]/g, a = {
745
675
  "\0": "\\0",
746
676
  "\b": "\\b",
@@ -9253,797 +9183,310 @@ var getValidatedClient$2 = async (t) => {
9253
9183
  });
9254
9184
  });
9255
9185
  }
9256
- releaseConnection(e) {
9257
- e instanceof l && e.release();
9258
- }
9259
- query(e, t) {
9260
- let n = this.pool, r = /* @__PURE__ */ Error();
9261
- if (typeof t == "function") throw Error("Callback function is not available with promise clients.");
9262
- return new this.Promise((a, o) => {
9263
- let s = i(a, o, r);
9264
- t === void 0 ? n.query(e, s) : n.query(e, t, s);
9265
- });
9266
- }
9267
- execute(e, t) {
9268
- let n = this.pool, r = /* @__PURE__ */ Error();
9269
- if (typeof t == "function") throw Error("Callback function is not available with promise clients.");
9270
- return new this.Promise((a, o) => {
9271
- let s = i(a, o, r);
9272
- t ? n.execute(e, t, s) : n.execute(e, s);
9273
- });
9274
- }
9275
- end() {
9276
- let e = this.pool, t = /* @__PURE__ */ Error();
9277
- return new this.Promise((n, r) => {
9278
- e.end((e) => {
9279
- e ? (t.message = e.message, t.code = e.code, t.errno = e.errno, t.sqlState = e.sqlState, t.sqlMessage = e.sqlMessage, r(t)) : n();
9280
- });
9281
- });
9282
- }
9283
- };
9284
- function d(e) {
9285
- let n = t.createPool(e), r = e.Promise || Promise;
9286
- if (!r) throw Error("no Promise implementation available.Use promise-enabled node version or pass userland Promise implementation as parameter, for example: { Promise: require('bluebird') }");
9287
- return new u(n, r);
9288
- }
9289
- (function(e) {
9290
- for (let n = 0; e && n < e.length; n++) {
9291
- let r = e[n];
9292
- typeof t.Pool.prototype[r] == "function" && u.prototype[r] === void 0 && (u.prototype[r] = (function(e) {
9293
- return function() {
9294
- return t.Pool.prototype[e].apply(this.pool, arguments);
9295
- };
9296
- })(r));
9297
- }
9298
- })([
9299
- "escape",
9300
- "escapeId",
9301
- "format"
9302
- ]);
9303
- var f = class e extends n {
9304
- constructor(e, t) {
9305
- super(), this.poolCluster = e, this.Promise = t || Promise, a(e, this, ["warn", "remove"]);
9306
- }
9307
- getConnection() {
9308
- let e = this.poolCluster;
9309
- return new this.Promise((t, n) => {
9310
- e.getConnection((e, r) => {
9311
- e ? n(e) : t(new l(r, this.Promise));
9312
- });
9313
- });
9186
+ releaseConnection(e) {
9187
+ e instanceof l && e.release();
9314
9188
  }
9315
9189
  query(e, t) {
9316
- let n = this.poolCluster, r = /* @__PURE__ */ Error();
9190
+ let n = this.pool, r = /* @__PURE__ */ Error();
9317
9191
  if (typeof t == "function") throw Error("Callback function is not available with promise clients.");
9318
9192
  return new this.Promise((a, o) => {
9319
9193
  let s = i(a, o, r);
9320
- n.query(e, t, s);
9194
+ t === void 0 ? n.query(e, s) : n.query(e, t, s);
9321
9195
  });
9322
9196
  }
9323
9197
  execute(e, t) {
9324
- let n = this.poolCluster, r = /* @__PURE__ */ Error();
9325
- if (typeof t == "function") throw Error("Callback function is not available with promise clients.");
9326
- return new this.Promise((a, o) => {
9327
- let s = i(a, o, r);
9328
- n.execute(e, t, s);
9329
- });
9330
- }
9331
- of(t, n) {
9332
- return new e(this.poolCluster.of(t, n), this.Promise);
9333
- }
9334
- end() {
9335
- let e = this.poolCluster, t = /* @__PURE__ */ Error();
9336
- return new this.Promise((n, r) => {
9337
- e.end((e) => {
9338
- e ? (t.message = e.message, t.code = e.code, t.errno = e.errno, t.sqlState = e.sqlState, t.sqlMessage = e.sqlMessage, r(t)) : n();
9339
- });
9340
- });
9341
- }
9342
- };
9343
- (function(e) {
9344
- for (let n = 0; e && n < e.length; n++) {
9345
- let r = e[n];
9346
- typeof t.PoolCluster.prototype[r] == "function" && f.prototype[r] === void 0 && (f.prototype[r] = (function(e) {
9347
- return function() {
9348
- return t.PoolCluster.prototype[e].apply(this.poolCluster, arguments);
9349
- };
9350
- })(r));
9351
- }
9352
- })(["add"]);
9353
- function p(e) {
9354
- let n = t.createPoolCluster(e), r = e && e.Promise || Promise;
9355
- if (!r) throw Error("no Promise implementation available.Use promise-enabled node version or pass userland Promise implementation as parameter, for example: { Promise: require('bluebird') }");
9356
- return new f(n, r);
9357
- }
9358
- e.createConnection = c, e.createPool = d, e.createPoolCluster = p, e.escape = t.escape, e.escapeId = t.escapeId, e.format = t.format, e.raw = t.raw, e.PromisePool = u, e.PromiseConnection = s, e.PromisePoolConnection = l, e.__defineGetter__("Types", () => require_types()), e.__defineGetter__("Charsets", () => require_charsets()), e.__defineGetter__("CharsetToEncoding", () => require_charset_encodings()), e.setMaxParserCache = function(e) {
9359
- r.setMaxCache(e);
9360
- }, e.clearParserCache = function() {
9361
- r.clearCache();
9362
- };
9363
- })), _freeGlobal_default = typeof global == "object" && global && global.Object === Object && global, freeSelf = typeof self == "object" && self && self.Object === Object && self, _Symbol_default = (_freeGlobal_default || freeSelf || Function("return this")()).Symbol, objectProto$1 = Object.prototype, hasOwnProperty$1 = objectProto$1.hasOwnProperty, nativeObjectToString$1 = objectProto$1.toString, symToStringTag$1 = _Symbol_default ? _Symbol_default.toStringTag : void 0;
9364
- function getRawTag(e) {
9365
- var t = hasOwnProperty$1.call(e, symToStringTag$1), n = e[symToStringTag$1];
9366
- try {
9367
- e[symToStringTag$1] = void 0;
9368
- var r = !0;
9369
- } catch {}
9370
- var i = nativeObjectToString$1.call(e);
9371
- return r && (t ? e[symToStringTag$1] = n : delete e[symToStringTag$1]), i;
9372
- }
9373
- var _getRawTag_default = getRawTag, nativeObjectToString = Object.prototype.toString;
9374
- function objectToString(e) {
9375
- return nativeObjectToString.call(e);
9376
- }
9377
- var _objectToString_default = objectToString, nullTag = "[object Null]", undefinedTag = "[object Undefined]", symToStringTag = _Symbol_default ? _Symbol_default.toStringTag : void 0;
9378
- function baseGetTag(e) {
9379
- return e == null ? e === void 0 ? undefinedTag : nullTag : symToStringTag && symToStringTag in Object(e) ? _getRawTag_default(e) : _objectToString_default(e);
9380
- }
9381
- var _baseGetTag_default = baseGetTag;
9382
- function isObjectLike(e) {
9383
- return typeof e == "object" && !!e;
9384
- }
9385
- var isObjectLike_default = isObjectLike, isArray_default = Array.isArray, argsTag = "[object Arguments]";
9386
- function baseIsArguments(e) {
9387
- return isObjectLike_default(e) && _baseGetTag_default(e) == argsTag;
9388
- }
9389
- var _baseIsArguments_default = baseIsArguments, objectProto = Object.prototype, hasOwnProperty = objectProto.hasOwnProperty, propertyIsEnumerable = objectProto.propertyIsEnumerable, isArguments_default = _baseIsArguments_default(function() {
9390
- return arguments;
9391
- }()) ? _baseIsArguments_default : function(e) {
9392
- return isObjectLike_default(e) && hasOwnProperty.call(e, "callee") && !propertyIsEnumerable.call(e, "callee");
9393
- };
9394
- function arrayPush(e, t) {
9395
- for (var n = -1, r = t.length, i = e.length; ++n < r;) e[i + n] = t[n];
9396
- return e;
9397
- }
9398
- var _arrayPush_default = arrayPush, spreadableSymbol = _Symbol_default ? _Symbol_default.isConcatSpreadable : void 0;
9399
- function isFlattenable(e) {
9400
- return isArray_default(e) || isArguments_default(e) || !!(spreadableSymbol && e && e[spreadableSymbol]);
9401
- }
9402
- var _isFlattenable_default = isFlattenable;
9403
- function baseFlatten(e, t, n, r, i) {
9404
- var a = -1, o = e.length;
9405
- for (n ||= _isFlattenable_default, i ||= []; ++a < o;) {
9406
- var s = e[a];
9407
- t > 0 && n(s) ? t > 1 ? baseFlatten(s, t - 1, n, r, i) : _arrayPush_default(i, s) : r || (i[i.length] = s);
9408
- }
9409
- return i;
9410
- }
9411
- var _baseFlatten_default = baseFlatten;
9412
- function flatten(e) {
9413
- return e != null && e.length ? _baseFlatten_default(e, 1) : [];
9414
- }
9415
- var flatten_default = flatten, import_promise = require_promise(), NUMBER_REGEX = "^-?[0-9]+(.[0-9]+)?$";
9416
- async function connectMySQL(e) {
9417
- let t = await (0, import_promise.createConnection)(e);
9418
- try {
9419
- return await t.connect(), await t.query("SELECT 1"), t;
9420
- } catch (e) {
9421
- throw await t.end(), e instanceof Error ? Error(`MySQL connection error: ${e.message}`) : e;
9422
- }
9423
- }
9424
- function getEnumName(e, t) {
9425
- return `${e}_${t}_enum`;
9426
- }
9427
- function getGenerationExpression(e, t) {
9428
- return e === "VIRTUAL GENERATED" ? `GENERATED ALWAYS AS (${t}) VIRTUAL` : e === "STORED GENERATED" ? `GENERATED ALWAYS AS (${t}) STORED` : e.includes("on update CURRENT_TIMESTAMP") ? "on update CURRENT_TIMESTAMP" : "";
9429
- }
9430
- function getDbDefault$1(e, t) {
9431
- return e === null ? null : {
9432
- value: e,
9433
- type: t
9434
- };
9435
- }
9436
- function getFieldType$2(e, t, n, r, i, a) {
9437
- if (r === "enum") return getEnumName(e, t);
9438
- let o = getGenerationExpression(i, a);
9439
- return o ? `${n} ${o}` : n;
9440
- }
9441
- function generateField$3(e) {
9442
- let { tableName: t, columnName: n, columnDefault: r, defaultValueType: i, columnIsNullable: a, columnType: o, columnDataType: s, columnComment: c, columnExtra: l, generationExpression: u } = e, d = getFieldType$2(t, n, o, s, l, u), f = getDbDefault$1(r, i);
9443
- return {
9444
- name: n,
9445
- type: {
9446
- type_name: d,
9447
- schemaName: null
9448
- },
9449
- dbdefault: f,
9450
- not_null: a !== "YES",
9451
- increment: l === "auto_increment",
9452
- note: { value: c || "" }
9453
- };
9454
- }
9455
- function getIndexColumn(e, t, n) {
9456
- return t ? {
9457
- value: t,
9458
- type: "expression"
9459
- } : n ? {
9460
- value: `${e}(${n})`,
9461
- type: "expression"
9462
- } : e ? {
9463
- value: e,
9464
- type: "column"
9465
- } : null;
9466
- }
9467
- async function generateTablesAndFields$3(e, t) {
9468
- let n = (await e.query("\n select\n t.table_name as tableName,\n t.table_comment as tableComment,\n c.column_name as columnName,\n c.column_default as columnDefault,\n case\n when c.column_default is null then 'boolean'\n when c.data_type = 'enum' then 'string'\n when c.column_default regexp ? then 'number'\n when c.extra like '%DEFAULT_GENERATED%' then 'expression'\n else 'string'\n end as defaultValueType,\n c.is_nullable as columnIsNullable,\n c.data_type as columnDataType,\n c.column_type as columnType,\n c.extra as columnExtra,\n c.column_comment as columnComment,\n c.generation_expression as generationExpression\n from information_schema.tables t\n join information_schema.columns c\n on t.table_schema = c.table_schema and t.table_name = c.table_name\n where\n t.table_schema = ? and t.table_type = 'BASE TABLE'\n order by\n t.table_name, c.ordinal_position;\n ", [NUMBER_REGEX, t]))[0], r = {}, i = {};
9469
- return n.forEach((e) => {
9470
- let { tableName: t, tableComment: n } = e, a = t;
9471
- r[a] || (r[a] = {
9472
- name: t,
9473
- note: { value: n || "" }
9474
- }), i[a] || (i[a] = []);
9475
- let o = generateField$3(e);
9476
- i[a].push(o);
9477
- }), {
9478
- tableList: Object.values(r),
9479
- fieldMap: i
9480
- };
9481
- }
9482
- async function generateEnums(e, t) {
9483
- return (await e.query("\n select\n t.table_name as tableName,\n c.column_name as columnName,\n TRIM(LEADING 'enum' FROM c.column_type) AS rawValues\n from information_schema.tables t\n join information_schema.columns c\n on t.table_schema = c.table_schema and t.table_name = c.table_name\n where\n t.table_schema = ? and t.table_type = 'BASE TABLE' and c.data_type = 'enum'\n order by\n t.table_name, c.ordinal_position;\n ", [t]))[0].map((e) => {
9484
- let { tableName: t, columnName: n, rawValues: r } = e, i = r.slice(1, -1).split(",").map((e) => ({ name: e.slice(1, -1) }));
9485
- return {
9486
- name: getEnumName(t, n),
9487
- values: i
9488
- };
9489
- });
9490
- }
9491
- async function generateIndexes$3(e, t) {
9492
- let n = (await e.query("\n with\n pk_fk_uniques as (\n select constraint_name, table_name\n from information_schema.table_constraints\n where table_schema = ?\n )\n select\n st.table_name as tableName,\n case\n when st.non_unique = 0 then true\n else false\n end as isIdxUnique,\n st.index_name as idxName,\n st.column_name as columnName,\n st.sub_part as idxSubPart,\n st.index_type as idxType,\n replace(st.expression, '`', '') as idxExpression\n from information_schema.statistics st\n where\n st.table_schema = ?\n and st.index_name not in (\n select constraint_name\n from pk_fk_uniques pfu\n where pfu.table_name = st.table_name\n )\n and st.index_type in ('BTREE', 'HASH')\n group by\n st.table_name, st.non_unique, st.index_name, st.column_name, st.sub_part, st.index_type, st.expression\n order by st.index_name;\n ", [t, t]))[0].reduce((e, t) => {
9493
- let { tableName: n, idxName: r, idxType: i, isIdxUnique: a, columnName: o, idxExpression: s, idxSubPart: c } = t, l = n;
9494
- e[l] || (e[l] = {}), e[l][r] || (e[l][r] = {
9495
- name: r,
9496
- type: i,
9497
- columns: [],
9498
- unique: !!a
9499
- });
9500
- let u = e[l][r], d = getIndexColumn(o, s, c);
9501
- return d && u.columns.push(d), e;
9502
- }, {}), r = {};
9503
- return Object.keys(n).forEach((e) => {
9504
- r[e] = flatten_default(Object.values(n[e]));
9505
- }), r;
9506
- }
9507
- async function generatePrimaryAndUniqueConstraint(e, t) {
9508
- let n = (await e.query("\n select\n tc.table_name as tableName,\n tc.constraint_name as constraintName,\n group_concat(kcu.column_name order by kcu.ordinal_position separator ',') as columnNames,\n count(kcu.column_name) as columnCount,\n tc.constraint_type as constraintType\n from information_schema.table_constraints tc\n join information_schema.key_column_usage kcu\n on\n tc.constraint_schema = kcu.constraint_schema\n and tc.constraint_name = kcu.constraint_name\n and tc.table_name = kcu.table_name\n where\n (tc.constraint_type = 'PRIMARY KEY' or tc.constraint_type = 'UNIQUE')\n and tc.table_schema = ?\n group by tc.table_name, tc.constraint_name, tc.constraint_type\n order by tc.table_name, tc.constraint_name;\n ", [t]))[0], r = n.filter((e) => e.columnCount === 1), i = n.filter((e) => e.columnCount > 1).reduce((e, t) => {
9509
- let { tableName: n, constraintName: r, columnNames: i, constraintType: a } = t, o = n;
9510
- e[o] || (e[o] = {}), e[o][r] || (e[o][r] = { name: r }), a === "PRIMARY KEY" && (e[o][r].pk = !0), a === "UNIQUE" && (e[o][r].unique = !0);
9511
- let s = i.split(",").map((e) => ({
9512
- type: "column",
9513
- value: e
9514
- }));
9515
- return e[o][r].columns = s, e;
9516
- }, {}), a = {};
9517
- return Object.keys(i).forEach((e) => {
9518
- a[e] = flatten_default(Object.values(i[e]));
9519
- }), {
9520
- compositeConstraintMap: a,
9521
- primaryAndUniqueConstraintMap: r.reduce((e, t) => {
9522
- let { tableName: n, columnNames: r, constraintType: i } = t, a = n;
9523
- return e[a] || (e[a] = {}), r.split(",").forEach((t) => {
9524
- e[a][t] || (e[a][t] = { checks: [] }), i === "PRIMARY KEY" && (e[a][t].pk = !0), i === "UNIQUE" && !e[a][t].pk && (e[a][t].unique = !0);
9525
- }), e;
9526
- }, {})
9527
- };
9528
- }
9529
- function extractColumnsFromCheckConstraint(e) {
9530
- return [...e.matchAll(/`(?:``|[^`])*`/g)].map((e) => e.toString().slice(1, -1));
9531
- }
9532
- async function generateCheckConstraints(e, t) {
9533
- let n = (await e.query("\n select\n cc.constraint_name as constraintName,\n tc.table_name as tableName,\n cc.check_clause as checkClause\n from information_schema.check_constraints cc\n join information_schema.table_constraints tc\n on cc.constraint_name = tc.constraint_name\n where cc.constraint_schema = ?\n ", [t]))[0], r = {}, i = {};
9534
- return n.forEach((e) => {
9535
- let { constraintName: t, tableName: n, checkClause: a } = e, o = n, s = extractColumnsFromCheckConstraint(a);
9536
- if (s.length === 1) {
9537
- let e = s[0];
9538
- i[o] || (i[o] = {}), i[o][e] || (i[o][e] = { checks: [] }), i[o][e].checks.push({
9539
- name: t,
9540
- expression: a.slice(1, -1)
9541
- });
9542
- return;
9543
- }
9544
- r[o] || (r[o] = []), r[o].push({
9545
- name: t,
9546
- expression: a.slice(1, -1)
9547
- });
9548
- }), {
9549
- checks: r,
9550
- tableConstraints: i
9551
- };
9552
- }
9553
- async function generateForeignKeys(e, t) {
9554
- return (await e.query("\n select\n rc.constraint_name as constraintName,\n rc.table_name as foreignTableName,\n group_concat(kcu.column_name order by kcu.ordinal_position separator ',') as foreignColumnNames,\n kcu.referenced_table_name as refTableName,\n group_concat(kcu.referenced_column_name order by kcu.ordinal_position separator ',') as refColumnNames,\n rc.update_rule as onUpdate,\n rc.delete_rule as onDelete\n from information_schema.referential_constraints rc\n join information_schema.key_column_usage kcu\n on\n rc.constraint_name = kcu.constraint_name\n and rc.table_name = kcu.table_name\n and rc.constraint_schema = kcu.table_schema\n where rc.constraint_schema = ?\n group by\n rc.constraint_name,\n rc.table_name,\n kcu.referenced_table_name,\n rc.update_rule,\n rc.delete_rule\n order by\n rc.table_name;\n ", [t]))[0].map((e) => {
9555
- let { constraintName: t, onDelete: n, onUpdate: r, foreignTableName: i, foreignColumnNames: a, refTableName: o, refColumnNames: s } = e;
9556
- return {
9557
- name: t,
9558
- endpoints: [{
9559
- tableName: i,
9560
- fieldNames: a.split(","),
9561
- relation: "*"
9562
- }, {
9563
- tableName: o,
9564
- fieldNames: s.split(","),
9565
- relation: "1"
9566
- }],
9567
- onDelete: n === "NO ACTION" ? null : n,
9568
- onUpdate: r === "NO ACTION" ? null : r
9569
- };
9570
- });
9571
- }
9572
- function combineIndexAndCompositeConstraint(e, t) {
9573
- let n = Object.assign(e, {});
9574
- return Object.keys(t).forEach((e) => {
9575
- let r = t[e];
9576
- if (!n[e]) {
9577
- n[e] = r;
9578
- return;
9198
+ let n = this.pool, r = /* @__PURE__ */ Error();
9199
+ if (typeof t == "function") throw Error("Callback function is not available with promise clients.");
9200
+ return new this.Promise((a, o) => {
9201
+ let s = i(a, o, r);
9202
+ t ? n.execute(e, t, s) : n.execute(e, s);
9203
+ });
9579
9204
  }
9580
- n[e].push(...r);
9581
- }), n;
9582
- }
9583
- async function fetchSchemaJson$2(e) {
9584
- let t = await connectMySQL(e), { database: n } = t.config;
9585
- if (!n) throw Error("Cannot get schema name from the connection");
9586
- try {
9587
- let [{ tableList: e, fieldMap: r }, i, a, { primaryAndUniqueConstraintMap: o, compositeConstraintMap: s }, c, { checks: l, tableConstraints: u }] = await Promise.all([
9588
- generateTablesAndFields$3(t, n),
9589
- generateEnums(t, n),
9590
- generateIndexes$3(t, n),
9591
- generatePrimaryAndUniqueConstraint(t, n),
9592
- generateForeignKeys(t, n),
9593
- generateCheckConstraints(t, n)
9594
- ]), d = combineIndexAndCompositeConstraint(a, s), f = { ...o };
9595
- return Object.keys(u).forEach((e) => {
9596
- f[e] || (f[e] = {}), Object.keys(u[e]).forEach((t) => {
9597
- f[e][t] || (f[e][t] = { checks: [] }), f[e][t].checks.push(...u[e][t].checks);
9205
+ end() {
9206
+ let e = this.pool, t = /* @__PURE__ */ Error();
9207
+ return new this.Promise((n, r) => {
9208
+ e.end((e) => {
9209
+ e ? (t.message = e.message, t.code = e.code, t.errno = e.errno, t.sqlState = e.sqlState, t.sqlMessage = e.sqlMessage, r(t)) : n();
9210
+ });
9598
9211
  });
9599
- }), {
9600
- tables: e,
9601
- fields: r,
9602
- refs: c,
9603
- enums: i,
9604
- indexes: d,
9605
- tableConstraints: f,
9606
- checks: l
9607
- };
9608
- } finally {
9609
- await t.end();
9610
- }
9611
- }
9612
- var parseConnectionString = (e) => {
9613
- let t = {}, n = /([^;=]+)=([^;]*)/g, r;
9614
- for (; (r = n.exec(e)) !== null;) t[r[1].trim()] = r[2].trim();
9615
- return t;
9616
- }, connect = async (e) => new Promise((t, n) => {
9617
- console.log("Attempting to connect..."), e.connect((e) => {
9618
- e ? n(e) : t();
9619
- });
9620
- }), executeQuery = (e, t) => new Promise((n, r) => {
9621
- console.log("Executing query..."), e.execute({
9622
- sqlText: t,
9623
- complete: (e, t, i) => {
9624
- e ? r(e) : (console.log("Query executed successfully."), i && n(i));
9625
9212
  }
9626
- });
9627
- }), isLogLevel = (e) => [
9628
- "ERROR",
9629
- "WARN",
9630
- "INFO",
9631
- "DEBUG",
9632
- "TRACE"
9633
- ].includes(e), connectToSnowflake = async (e) => {
9634
- let t = isLogLevel(e.LOG_LEVEL) ? e.LOG_LEVEL : "INFO", r = e.IS_DEBUG_MODE === "true";
9635
- snowflake.configure({
9636
- logLevel: t,
9637
- additionalLogToConsole: r
9638
- });
9639
- let i = {};
9640
- switch (e.AUTHENTICATOR) {
9641
- case "SNOWFLAKE_JWT":
9642
- i = {
9643
- privateKeyPath: e.PRIVATE_KEY_PATH,
9644
- privateKeyPass: e.PASSPHRASE
9645
- };
9646
- break;
9647
- case "SNOWFLAKE":
9648
- case void 0:
9649
- i = { password: e.PWD };
9650
- break;
9651
- default: throw Error("Unsupported authenticator");
9652
- }
9653
- let a = {
9654
- authenticator: e.AUTHENTICATOR,
9655
- account: e.SERVER,
9656
- username: e.UID,
9657
- database: e.DATABASE,
9658
- warehouse: e.WAREHOUSE,
9659
- sfRetryMaxLoginRetries: 3,
9660
- timeout: 1e4,
9661
- ...i
9662
- }, o = snowflake.createConnection(a);
9663
- return await connect(o), await executeQuery(o, "SELECT CURRENT_VERSION();"), o;
9664
- }, convertQueryBoolean = (e) => e === "YES", getFieldType$1 = (e, t, n, r) => t ? `${e}(${t})` : n && r ? `${e}(${n},${r})` : e, getDbdefault$1 = (e, t) => t === "string" ? {
9665
- type: t,
9666
- value: e.slice(1, -1)
9667
- } : {
9668
- type: t,
9669
- value: e
9670
- }, generateField$2 = (e) => {
9671
- let { COLUMN_NAME: t, DATA_TYPE: n, CHARACTER_MAXIMUM_LENGTH: r, NUMERIC_PRECISION: i, NUMERIC_SCALE: a, IDENTITY_INCREMENT: o, IS_NULLABLE: s, COLUMN_DEFAULT: c, DEFAULT_TYPE: l, COLUMN_COMMENT: u } = e, d = c ? getDbdefault$1(c, l) : null;
9672
- return {
9673
- name: t,
9674
- type: {
9675
- type_name: getFieldType$1(n, r, i, a),
9676
- schemaName: null
9677
- },
9678
- dbdefault: d,
9679
- not_null: !convertQueryBoolean(s),
9680
- increment: !!o,
9681
- note: u ? { value: u } : { value: "" }
9682
- };
9683
- }, generateTablesAndFields$2 = async (e, t) => {
9684
- let n = {}, r = (await executeQuery(e, `
9685
- SELECT
9686
- c.table_schema,
9687
- c.table_name,
9688
- c.column_name,
9689
- c.data_type,
9690
- c.character_maximum_length,
9691
- c.numeric_precision,
9692
- c.numeric_scale,
9693
- c.is_nullable,
9694
- c.column_default,
9695
- CASE
9696
- WHEN c.column_default IS NULL THEN NULL
9697
- WHEN c.column_default LIKE '''%' THEN 'string'
9698
- WHEN LOWER(c.column_default) = 'true' OR LOWER(c.column_default) = 'false' THEN 'boolean'
9699
- WHEN c.column_default REGEXP '^-?[0-9]+(\\.[0-9]+)?$' THEN 'number'
9700
- ELSE 'expression'
9701
- END AS default_type,
9702
- t.comment AS table_comment,
9703
- c.comment AS column_comment,
9704
- c.identity_increment
9705
- FROM
9706
- information_schema.columns c
9707
- JOIN information_schema.tables t
9708
- ON c.table_name = t.table_name
9709
- AND c.table_schema = t.table_schema
9710
- WHERE
9711
- t.table_type = 'BASE TABLE'
9712
- AND t.table_schema NOT IN ('INFORMATION_SCHEMA')
9713
- ${t.length > 0 ? `AND c.table_schema IN (${t.map((e) => `'${e}'`).join(",")})` : ""}
9714
- ORDER BY
9715
- c.table_schema,
9716
- t.created,
9717
- c.ordinal_position;
9718
- `)).reduce((e, t) => {
9719
- let { TABLE_SCHEMA: r, TABLE_NAME: i, TABLE_COMMENT: a } = t, o = `${r}.${i}`;
9720
- e[o] || (e[o] = {
9721
- name: i,
9722
- schemaName: r,
9723
- note: a ? { value: a } : { value: "" }
9724
- }), n[o] || (n[o] = []);
9725
- let s = generateField$2(t);
9726
- return n[o].push(s), e;
9727
- }, {});
9728
- return {
9729
- tables: Object.values(r),
9730
- fields: n
9731
9213
  };
9732
- }, createConstraintKeysMap = (e, t, n) => e.reduce((e, r) => {
9733
- let { schema_name: i, table_name: a, column_name: o, constraint_name: s } = r;
9734
- if (!(!(t.length > 0) || t.includes(i))) return e;
9735
- let c = `${i}.${a}.${s}`;
9736
- if (e[c]) {
9737
- let { columnNames: t } = e[c];
9738
- return t.push(o), e;
9214
+ function d(e) {
9215
+ let n = t.createPool(e), r = e.Promise || Promise;
9216
+ if (!r) throw Error("no Promise implementation available.Use promise-enabled node version or pass userland Promise implementation as parameter, for example: { Promise: require('bluebird') }");
9217
+ return new u(n, r);
9739
9218
  }
9740
- return e[c] = {
9741
- schemaName: i,
9742
- tableName: a,
9743
- constraintName: s,
9744
- columnNames: [o],
9745
- type: ""
9746
- }, e[c][n] = !0, e;
9747
- }, {}), generateIndexes$2 = async (e, t, n) => {
9748
- let r = `
9749
- SHOW PRIMARY KEYS IN DATABASE ${t};
9750
- `, i = `
9751
- SHOW UNIQUE KEYS IN DATABASE ${t};
9752
- `, a = await executeQuery(e, r), o = await executeQuery(e, i), s = createConstraintKeysMap(a, n, "primary"), c = createConstraintKeysMap(o, n, "unique"), { indexes: l, tableConstraints: u } = [Object.values(s), Object.values(c)].flat().reduce((e, t) => {
9753
- let { schemaName: n, tableName: r, constraintName: i, columnNames: a, type: o, primary: s, unique: c } = t, l = `${n}.${r}`;
9754
- if (a.length < 2) return e.tableConstraints[l] = { [a[0]]: {
9755
- pk: s,
9756
- unique: c,
9757
- checks: []
9758
- } }, e;
9759
- let u = {
9760
- name: i,
9761
- type: o,
9762
- unique: c,
9763
- pk: s,
9764
- columns: a.map((e) => ({
9765
- type: "column",
9766
- value: e
9767
- }))
9768
- };
9769
- return e.indexes[l] ? e.indexes[l].push(u) : e.indexes[l] = [u], e;
9770
- }, {
9771
- indexes: {},
9772
- tableConstraints: {}
9773
- });
9774
- return {
9775
- indexes: l,
9776
- tableConstraints: u
9777
- };
9778
- }, fetchSchemaJson$3 = async (e) => {
9779
- let t = parseConnectionString(e), n = await connectToSnowflake(t);
9780
- if (n instanceof Error) throw n;
9781
- let r = t.SCHEMAS ? parseSchema(t.SCHEMAS) : [], i = t.DATABASE, a = generateTablesAndFields$2(n, r), o = generateIndexes$2(n, i, r), s = await Promise.all([a, o]);
9782
- n.destroy((e) => {
9783
- if (e) throw e;
9784
- console.log("Connection destroyed successfully.");
9785
- });
9786
- let { tables: c, fields: l } = s[0], { indexes: u, tableConstraints: d } = s[1];
9787
- return {
9788
- tables: c,
9789
- fields: l,
9790
- refs: [],
9791
- enums: [],
9792
- indexes: u,
9793
- tableConstraints: d,
9794
- checks: {}
9219
+ (function(e) {
9220
+ for (let n = 0; e && n < e.length; n++) {
9221
+ let r = e[n];
9222
+ typeof t.Pool.prototype[r] == "function" && u.prototype[r] === void 0 && (u.prototype[r] = (function(e) {
9223
+ return function() {
9224
+ return t.Pool.prototype[e].apply(this.pool, arguments);
9225
+ };
9226
+ })(r));
9227
+ }
9228
+ })([
9229
+ "escape",
9230
+ "escapeId",
9231
+ "format"
9232
+ ]);
9233
+ var f = class e extends n {
9234
+ constructor(e, t) {
9235
+ super(), this.poolCluster = e, this.Promise = t || Promise, a(e, this, ["warn", "remove"]);
9236
+ }
9237
+ getConnection() {
9238
+ let e = this.poolCluster;
9239
+ return new this.Promise((t, n) => {
9240
+ e.getConnection((e, r) => {
9241
+ e ? n(e) : t(new l(r, this.Promise));
9242
+ });
9243
+ });
9244
+ }
9245
+ query(e, t) {
9246
+ let n = this.poolCluster, r = /* @__PURE__ */ Error();
9247
+ if (typeof t == "function") throw Error("Callback function is not available with promise clients.");
9248
+ return new this.Promise((a, o) => {
9249
+ let s = i(a, o, r);
9250
+ n.query(e, t, s);
9251
+ });
9252
+ }
9253
+ execute(e, t) {
9254
+ let n = this.poolCluster, r = /* @__PURE__ */ Error();
9255
+ if (typeof t == "function") throw Error("Callback function is not available with promise clients.");
9256
+ return new this.Promise((a, o) => {
9257
+ let s = i(a, o, r);
9258
+ n.execute(e, t, s);
9259
+ });
9260
+ }
9261
+ of(t, n) {
9262
+ return new e(this.poolCluster.of(t, n), this.Promise);
9263
+ }
9264
+ end() {
9265
+ let e = this.poolCluster, t = /* @__PURE__ */ Error();
9266
+ return new this.Promise((n, r) => {
9267
+ e.end((e) => {
9268
+ e ? (t.message = e.message, t.code = e.code, t.errno = e.errno, t.sqlState = e.sqlState, t.sqlMessage = e.sqlMessage, r(t)) : n();
9269
+ });
9270
+ });
9271
+ }
9795
9272
  };
9796
- };
9797
- async function loadCredentialFromFile(e) {
9798
- try {
9799
- return await readFile(e, { encoding: "utf8" });
9800
- } catch (e) {
9801
- throw e.name === "TypeError" || e.name === "Error" ? Error(`Load credential error: ${e.message}`) : e;
9273
+ (function(e) {
9274
+ for (let n = 0; e && n < e.length; n++) {
9275
+ let r = e[n];
9276
+ typeof t.PoolCluster.prototype[r] == "function" && f.prototype[r] === void 0 && (f.prototype[r] = (function(e) {
9277
+ return function() {
9278
+ return t.PoolCluster.prototype[e].apply(this.poolCluster, arguments);
9279
+ };
9280
+ })(r));
9281
+ }
9282
+ })(["add"]);
9283
+ function p(e) {
9284
+ let n = t.createPoolCluster(e), r = e && e.Promise || Promise;
9285
+ if (!r) throw Error("no Promise implementation available.Use promise-enabled node version or pass userland Promise implementation as parameter, for example: { Promise: require('bluebird') }");
9286
+ return new f(n, r);
9802
9287
  }
9803
- }
9804
- function parseBigQueryCredential(e) {
9288
+ e.createConnection = c, e.createPool = d, e.createPoolCluster = p, e.escape = t.escape, e.escapeId = t.escapeId, e.format = t.format, e.raw = t.raw, e.PromisePool = u, e.PromiseConnection = s, e.PromisePoolConnection = l, e.__defineGetter__("Types", () => require_types()), e.__defineGetter__("Charsets", () => require_charsets()), e.__defineGetter__("CharsetToEncoding", () => require_charset_encodings()), e.setMaxParserCache = function(e) {
9289
+ r.setMaxCache(e);
9290
+ }, e.clearParserCache = function() {
9291
+ r.clearCache();
9292
+ };
9293
+ })), import_promise = require_promise(), NUMBER_REGEX = "^-?[0-9]+(.[0-9]+)?$";
9294
+ async function connectMySQL(e) {
9295
+ let t = await (0, import_promise.createConnection)(e);
9805
9296
  try {
9806
- let { project_id: t, client_email: n, private_key: r, datasets: i } = JSON.parse(e), a = { datasets: Array.isArray(i) ? i.filter((e) => typeof e == "string") : [] };
9807
- if (t !== void 0) {
9808
- if (typeof t != "string" || !t || !t.trim()) throw Error("project_id must be a non-empty string when provided");
9809
- a.projectId = t;
9810
- }
9811
- if (n !== void 0 || r !== void 0) {
9812
- if (!n || typeof n != "string" || !n.trim()) throw Error("client_email must be a non-empty string when credentials are provided");
9813
- if (!r || typeof r != "string" || !r.trim()) throw Error("private_key must be a non-empty string when credentials are provided");
9814
- a.credentials = {
9815
- clientEmail: n,
9816
- privateKey: r
9817
- };
9818
- }
9819
- return a;
9297
+ return await t.connect(), await t.query("SELECT 1"), t;
9820
9298
  } catch (e) {
9821
- throw e instanceof SyntaxError ? Error("Credentials must be in JSON format") : e;
9299
+ throw await t.end(), e instanceof Error ? Error(`MySQL connection error: ${e.message}`) : e;
9822
9300
  }
9823
9301
  }
9824
- function getIntersection(e, t) {
9825
- return e.filter((e) => t.includes(e));
9826
- }
9827
- function getTableSchemaKey(e, t) {
9828
- if (!t || !t.trim()) throw Error("Table name must be a non-empty string");
9829
- return e ? `${e}.${t}` : `${t}`;
9830
- }
9831
- function mergeTables(e, t) {
9832
- return e.concat(t);
9833
- }
9834
- function mergeFieldDictionary(e, t) {
9835
- let n = { ...e };
9836
- return Object.keys(t).forEach((e) => {
9837
- n[e] || (n[e] = []), n[e] = n[e].concat(t[e]);
9838
- }), n;
9839
- }
9840
- function mergeIndexDictionary(e, t) {
9841
- let n = { ...e };
9842
- return Object.keys(t).forEach((e) => {
9843
- n[e] || (n[e] = []), n[e] = n[e].concat(t[e]);
9844
- }), n;
9845
- }
9846
- function mergeTableConstraintDictionary(e, t) {
9847
- let n = { ...e };
9848
- return Object.keys(t).forEach((e) => {
9849
- n[e] || (n[e] = {}), n[e] = t[e];
9850
- }), n;
9302
+ function getEnumName(e, t) {
9303
+ return `${e}_${t}_enum`;
9851
9304
  }
9852
- async function connectBigQuery(e) {
9853
- let t = {};
9854
- e?.projectId && (t.projectId = e.projectId), e?.credentials?.clientEmail && e?.credentials?.privateKey && (t.credentials = {
9855
- client_email: e.credentials.clientEmail,
9856
- private_key: e.credentials.privateKey
9857
- });
9858
- let n = new BigQuery(t);
9859
- try {
9860
- return await n.query("SELECT CURRENT_DATE() as today"), n;
9861
- } catch (e) {
9862
- throw e instanceof Error ? Error(`BigQuery connection error: ${e.message}`) : e;
9863
- }
9305
+ function getGenerationExpression(e, t) {
9306
+ return e === "VIRTUAL GENERATED" ? `GENERATED ALWAYS AS (${t}) VIRTUAL` : e === "STORED GENERATED" ? `GENERATED ALWAYS AS (${t}) STORED` : e.includes("on update CURRENT_TIMESTAMP") ? "on update CURRENT_TIMESTAMP" : "";
9864
9307
  }
9865
9308
  function getDbDefault(e, t) {
9866
- return t === null ? null : t === "string" ? {
9867
- value: e.slice(1, -1).replaceAll("'", "'"),
9868
- type: t
9869
- } : {
9309
+ return e === null ? null : {
9870
9310
  value: e,
9871
9311
  type: t
9872
9312
  };
9873
9313
  }
9874
- function generateField$1(e) {
9875
- let { columnName: t, isNullable: n, dataType: r, columnDefault: i, columnDefaultType: a, columnDescription: o } = e, s = getDbDefault(i, a);
9314
+ function getFieldType$3(e, t, n, r, i, a) {
9315
+ if (r === "enum") return getEnumName(e, t);
9316
+ let o = getGenerationExpression(i, a);
9317
+ return o ? `${n} ${o}` : n;
9318
+ }
9319
+ function generateField$3(e) {
9320
+ let { tableName: t, columnName: n, columnDefault: r, defaultValueType: i, columnIsNullable: a, columnType: o, columnDataType: s, columnComment: c, columnExtra: l, generationExpression: u } = e, d = getFieldType$3(t, n, o, s, l, u), f = getDbDefault(r, i);
9876
9321
  return {
9877
- name: t,
9878
- not_null: n === "NO",
9322
+ name: n,
9879
9323
  type: {
9880
- type_name: r,
9324
+ type_name: d,
9881
9325
  schemaName: null
9882
9326
  },
9883
- note: { value: o || "" },
9884
- dbdefault: s,
9885
- increment: !1
9327
+ dbdefault: f,
9328
+ not_null: a !== "YES",
9329
+ increment: l === "auto_increment",
9330
+ note: { value: c || "" }
9886
9331
  };
9887
9332
  }
9888
- async function generateTablesAndFields$1(e, t, n) {
9889
- let r = `${t}.${n}`, i = `
9890
- with
9891
- table_comments as (
9892
- select table_schema, table_name, option_value as description
9893
- from ${r}.INFORMATION_SCHEMA.TABLE_OPTIONS
9894
- where option_name = 'description'
9895
- ),
9896
- column_comments as (
9897
- select column_name, table_schema, table_name, description
9898
- from ${r}.INFORMATION_SCHEMA.COLUMN_FIELD_PATHS
9899
- where column_name = field_path
9900
- )
9901
- select
9902
- t.table_schema as tableSchema,
9903
- t.table_name as tableName,
9904
- (select description from table_comments tc where tc.table_name = t.table_name and tc.table_schema = t.table_schema) as tableDescription,
9905
- (
9906
- select description
9907
- from column_comments cc
9908
- where cc.table_name = c.table_name and cc.table_schema = c.table_schema and cc.column_name = c.column_name
9909
- ) as columnDescription,
9910
- c.column_name as columnName,
9911
- c.is_nullable as isNullable,
9912
- c.data_type as dataType,
9913
- c.column_default as columnDefault,
9914
- CASE
9915
- WHEN SAFE_CAST(c.column_default AS FLOAT64) IS NOT NULL THEN 'number'
9916
- WHEN SAFE_CAST(c.column_default AS BOOLEAN) IS NOT NULL THEN 'boolean'
9917
- -- string value is enclosed in single quotes, double quotes
9918
- WHEN REGEXP_CONTAINS(c.column_default, r"^['\\"].*['\\"]$") THEN 'string'
9919
- WHEN c.column_default = "NULL" THEN NULL
9920
- ELSE 'expression'
9921
- END AS columnDefaultType
9922
- from ${r}.INFORMATION_SCHEMA.TABLES t
9923
- join ${r}.INFORMATION_SCHEMA.COLUMNS c
9924
- on
9925
- t.table_schema = c.table_schema
9926
- and t.table_name = c.table_name
9927
- where t.table_type = 'BASE TABLE'
9928
- order by t.creation_time, c.ordinal_position;
9929
- `, [a] = await e.query({ query: i }), o = {}, s = {};
9930
- return a.forEach((e) => {
9931
- let { tableSchema: t, tableName: n, tableComment: r } = e, i = getTableSchemaKey(t, n);
9932
- o[i] || (o[i] = {
9933
- name: n,
9934
- note: { value: r || "" },
9935
- schemaName: t
9936
- }), s[i] || (s[i] = []);
9937
- let a = generateField$1(e);
9938
- s[i].push(a);
9333
+ function getIndexColumn(e, t, n) {
9334
+ return t ? {
9335
+ value: t,
9336
+ type: "expression"
9337
+ } : n ? {
9338
+ value: `${e}(${n})`,
9339
+ type: "expression"
9340
+ } : e ? {
9341
+ value: e,
9342
+ type: "column"
9343
+ } : null;
9344
+ }
9345
+ async function generateTablesAndFields$3(e, t) {
9346
+ let n = (await e.query("\n select\n t.table_name as tableName,\n t.table_comment as tableComment,\n c.column_name as columnName,\n c.column_default as columnDefault,\n case\n when c.column_default is null then 'boolean'\n when c.data_type = 'enum' then 'string'\n when c.column_default regexp ? then 'number'\n when c.extra like '%DEFAULT_GENERATED%' then 'expression'\n else 'string'\n end as defaultValueType,\n c.is_nullable as columnIsNullable,\n c.data_type as columnDataType,\n c.column_type as columnType,\n c.extra as columnExtra,\n c.column_comment as columnComment,\n c.generation_expression as generationExpression\n from information_schema.tables t\n join information_schema.columns c\n on t.table_schema = c.table_schema and t.table_name = c.table_name\n where\n t.table_schema = ? and t.table_type = 'BASE TABLE'\n order by\n t.table_name, c.ordinal_position;\n ", [NUMBER_REGEX, t]))[0], r = {}, i = {};
9347
+ return n.forEach((e) => {
9348
+ let { tableName: t, tableComment: n } = e, a = t;
9349
+ r[a] || (r[a] = {
9350
+ name: t,
9351
+ note: { value: n || "" }
9352
+ }), i[a] || (i[a] = []);
9353
+ let o = generateField$3(e);
9354
+ i[a].push(o);
9939
9355
  }), {
9940
- tables: Object.values(o),
9941
- fieldMap: s
9356
+ tableList: Object.values(r),
9357
+ fieldMap: i
9942
9358
  };
9943
9359
  }
9944
- async function generateIndexes$1(e, t, n) {
9945
- let r = `${t}.${n}`, i = `
9946
- select
9947
- s.index_schema as indexSchema,
9948
- s.table_name as tableName,
9949
- s.index_name as indexName,
9950
- string_agg(sc.index_column_name, ', ') as indexColumnNames
9951
- from ${r}.INFORMATION_SCHEMA.SEARCH_INDEXES s
9952
- join ${r}.INFORMATION_SCHEMA.SEARCH_INDEX_COLUMNS sc
9953
- on
9954
- s.index_schema = sc.index_schema
9955
- and s.table_name = sc.table_name
9956
- and s.index_name = sc.index_name
9957
- where sc.index_column_name = sc.index_field_path
9958
- group by s.index_schema, s.table_name, s.index_name
9959
- order by s.table_name, s.index_name;
9960
- `, [a] = await e.query(i), o = {};
9961
- return a.forEach((e) => {
9962
- let { indexSchema: t, tableName: n, indexName: r, indexColumnNames: i } = e, a = {
9963
- name: r,
9964
- type: "",
9965
- columns: [...i.split(", ").map((e) => ({
9966
- type: "column",
9967
- value: e
9968
- }))]
9969
- }, s = getTableSchemaKey(t, n);
9970
- o[s] ? o[s].push(a) : o[s] = [a];
9971
- }), o;
9972
- }
9973
- async function generateTableConstraints(e, t, n) {
9974
- let r = `${t}.${n}`, i = `
9975
- select
9976
- tc.table_schema as tableSchema,
9977
- tc.table_name as tableName,
9978
- tc.constraint_name as constraintName,
9979
- string_agg(kcu.column_name, ', ') as columnNames,
9980
- count(kcu.column_name) as columnCount,
9981
- from ${r}.INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
9982
- join ${r}.INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
9983
- on
9984
- tc.table_schema = kcu.table_schema
9985
- and tc.table_name = kcu.table_name
9986
- and tc.constraint_name = kcu.constraint_name
9987
- where tc.constraint_type = 'PRIMARY KEY'
9988
- group by tc.table_schema, tc.table_name, tc.constraint_name
9989
- order by tc.table_name, tc.constraint_name;
9990
- `, [a] = await e.query(i), o = a.filter((e) => e.columnCount && e.columnCount === 1), s = a.filter((e) => e.columnCount && e.columnCount > 1), c = {};
9991
- o.forEach((e) => {
9992
- let { tableSchema: t, tableName: n, columnNames: r } = e, i = getTableSchemaKey(t, n);
9993
- c[i] || (c[i] = {}), c[i][r] || (c[i][r] = { checks: [] }), c[i][r].pk = !0;
9360
+ async function generateEnums(e, t) {
9361
+ return (await e.query("\n select\n t.table_name as tableName,\n c.column_name as columnName,\n TRIM(LEADING 'enum' FROM c.column_type) AS rawValues\n from information_schema.tables t\n join information_schema.columns c\n on t.table_schema = c.table_schema and t.table_name = c.table_name\n where\n t.table_schema = ? and t.table_type = 'BASE TABLE' and c.data_type = 'enum'\n order by\n t.table_name, c.ordinal_position;\n ", [t]))[0].map((e) => {
9362
+ let { tableName: t, columnName: n, rawValues: r } = e, i = r.slice(1, -1).split(",").map((e) => ({ name: e.slice(1, -1) }));
9363
+ return {
9364
+ name: getEnumName(t, n),
9365
+ values: i
9366
+ };
9994
9367
  });
9995
- let l = {};
9996
- return s.forEach((e) => {
9997
- let { tableSchema: t, tableName: n, constraintName: r, columnNames: i } = e, a = {
9368
+ }
9369
+ async function generateIndexes$2(e, t) {
9370
+ let n = (await e.query("\n with\n pk_fk_uniques as (\n select constraint_name, table_name\n from information_schema.table_constraints\n where table_schema = ?\n )\n select\n st.table_name as tableName,\n case\n when st.non_unique = 0 then true\n else false\n end as isIdxUnique,\n st.index_name as idxName,\n st.column_name as columnName,\n st.sub_part as idxSubPart,\n st.index_type as idxType,\n replace(st.expression, '`', '') as idxExpression\n from information_schema.statistics st\n where\n st.table_schema = ?\n and st.index_name not in (\n select constraint_name\n from pk_fk_uniques pfu\n where pfu.table_name = st.table_name\n )\n and st.index_type in ('BTREE', 'HASH')\n group by\n st.table_name, st.non_unique, st.index_name, st.column_name, st.sub_part, st.index_type, st.expression\n order by st.index_name;\n ", [t, t]))[0].reduce((e, t) => {
9371
+ let { tableName: n, idxName: r, idxType: i, isIdxUnique: a, columnName: o, idxExpression: s, idxSubPart: c } = t, l = n;
9372
+ e[l] || (e[l] = {}), e[l][r] || (e[l][r] = {
9998
9373
  name: r,
9999
- type: "",
10000
- columns: [...i.split(", ").map((e) => ({
10001
- type: "column",
10002
- value: e
10003
- }))],
10004
- pk: !0
10005
- }, o = getTableSchemaKey(t, n);
10006
- l[o] ? l[o].push(a) : l[o] = [a];
9374
+ type: i,
9375
+ columns: [],
9376
+ unique: !!a
9377
+ });
9378
+ let u = e[l][r], d = getIndexColumn(o, s, c);
9379
+ return d && u.columns.push(d), e;
9380
+ }, {}), r = {};
9381
+ return Object.keys(n).forEach((e) => {
9382
+ r[e] = flatten_default(Object.values(n[e]));
9383
+ }), r;
9384
+ }
9385
+ async function generatePrimaryAndUniqueConstraint(e, t) {
9386
+ let n = (await e.query("\n select\n tc.table_name as tableName,\n tc.constraint_name as constraintName,\n group_concat(kcu.column_name order by kcu.ordinal_position separator ',') as columnNames,\n count(kcu.column_name) as columnCount,\n tc.constraint_type as constraintType\n from information_schema.table_constraints tc\n join information_schema.key_column_usage kcu\n on\n tc.constraint_schema = kcu.constraint_schema\n and tc.constraint_name = kcu.constraint_name\n and tc.table_name = kcu.table_name\n where\n (tc.constraint_type = 'PRIMARY KEY' or tc.constraint_type = 'UNIQUE')\n and tc.table_schema = ?\n group by tc.table_name, tc.constraint_name, tc.constraint_type\n order by tc.table_name, tc.constraint_name;\n ", [t]))[0], r = n.filter((e) => e.columnCount === 1), i = n.filter((e) => e.columnCount > 1).reduce((e, t) => {
9387
+ let { tableName: n, constraintName: r, columnNames: i, constraintType: a } = t, o = n;
9388
+ e[o] || (e[o] = {}), e[o][r] || (e[o][r] = { name: r }), a === "PRIMARY KEY" && (e[o][r].pk = !0), a === "UNIQUE" && (e[o][r].unique = !0);
9389
+ let s = i.split(",").map((e) => ({
9390
+ type: "column",
9391
+ value: e
9392
+ }));
9393
+ return e[o][r].columns = s, e;
9394
+ }, {}), a = {};
9395
+ return Object.keys(i).forEach((e) => {
9396
+ a[e] = flatten_default(Object.values(i[e]));
10007
9397
  }), {
10008
- inlinePrimaryKeyMap: c,
10009
- compositePrimaryKeyMap: l
9398
+ compositeConstraintMap: a,
9399
+ primaryAndUniqueConstraintMap: r.reduce((e, t) => {
9400
+ let { tableName: n, columnNames: r, constraintType: i } = t, a = n;
9401
+ return e[a] || (e[a] = {}), r.split(",").forEach((t) => {
9402
+ e[a][t] || (e[a][t] = { checks: [] }), i === "PRIMARY KEY" && (e[a][t].pk = !0), i === "UNIQUE" && !e[a][t].pk && (e[a][t].unique = !0);
9403
+ }), e;
9404
+ }, {})
10010
9405
  };
10011
9406
  }
10012
- async function validateDatasetIdList(e, t) {
10013
- let [n] = await e.getDatasets(), r = n.map((e) => e.id).filter((e) => e);
10014
- return t.length === 0 ? r : getIntersection(t, r);
9407
+ function extractColumnsFromCheckConstraint(e) {
9408
+ return [...e.matchAll(/`(?:``|[^`])*`/g)].map((e) => e.toString().slice(1, -1));
10015
9409
  }
10016
- async function fetchSchemaJsonByDataset(e, t, n) {
10017
- let r = await Promise.all([
10018
- generateTablesAndFields$1(e, t, n),
10019
- generateIndexes$1(e, t, n),
10020
- generateTableConstraints(e, t, n)
10021
- ]), { tables: i, fieldMap: a } = r[0], o = r[1], { inlinePrimaryKeyMap: s, compositePrimaryKeyMap: c } = r[2];
10022
- return {
10023
- tables: i,
10024
- fields: a,
10025
- refs: [],
10026
- enums: [],
10027
- indexes: mergeIndexDictionary(o, c),
10028
- tableConstraints: s,
10029
- checks: {}
9410
+ async function generateCheckConstraints(e, t) {
9411
+ let n = (await e.query("\n select\n cc.constraint_name as constraintName,\n tc.table_name as tableName,\n cc.check_clause as checkClause\n from information_schema.check_constraints cc\n join information_schema.table_constraints tc\n on cc.constraint_name = tc.constraint_name\n where cc.constraint_schema = ?\n ", [t]))[0], r = {}, i = {};
9412
+ return n.forEach((e) => {
9413
+ let { constraintName: t, tableName: n, checkClause: a } = e, o = n, s = extractColumnsFromCheckConstraint(a);
9414
+ if (s.length === 1) {
9415
+ let e = s[0];
9416
+ i[o] || (i[o] = {}), i[o][e] || (i[o][e] = { checks: [] }), i[o][e].checks.push({
9417
+ name: t,
9418
+ expression: a.slice(1, -1)
9419
+ });
9420
+ return;
9421
+ }
9422
+ r[o] || (r[o] = []), r[o].push({
9423
+ name: t,
9424
+ expression: a.slice(1, -1)
9425
+ });
9426
+ }), {
9427
+ checks: r,
9428
+ tableConstraints: i
10030
9429
  };
10031
9430
  }
10032
- async function fetchSchemaJson$4(e) {
10033
- let t = parseBigQueryCredential(await loadCredentialFromFile(e)), n = await connectBigQuery(t), r = await n.getProjectId(), i = (await validateDatasetIdList(n, t.datasets)).map((e) => fetchSchemaJsonByDataset(n, r, e));
10034
- return (await Promise.all(i)).reduce((e, t) => {
10035
- let { tables: n, fields: r, indexes: i, tableConstraints: a } = t;
10036
- return e.tables = mergeTables(e.tables, n), e.fields = mergeFieldDictionary(e.fields, r), e.indexes = mergeIndexDictionary(e.indexes, i), e.tableConstraints = mergeTableConstraintDictionary(e.tableConstraints, a), e;
10037
- }, {
10038
- tables: [],
10039
- fields: {},
10040
- tableConstraints: {},
10041
- indexes: {},
10042
- refs: [],
10043
- enums: [],
10044
- checks: {}
9431
+ async function generateForeignKeys(e, t) {
9432
+ return (await e.query("\n select\n rc.constraint_name as constraintName,\n rc.table_name as foreignTableName,\n group_concat(kcu.column_name order by kcu.ordinal_position separator ',') as foreignColumnNames,\n kcu.referenced_table_name as refTableName,\n group_concat(kcu.referenced_column_name order by kcu.ordinal_position separator ',') as refColumnNames,\n rc.update_rule as onUpdate,\n rc.delete_rule as onDelete\n from information_schema.referential_constraints rc\n join information_schema.key_column_usage kcu\n on\n rc.constraint_name = kcu.constraint_name\n and rc.table_name = kcu.table_name\n and rc.constraint_schema = kcu.table_schema\n where rc.constraint_schema = ?\n group by\n rc.constraint_name,\n rc.table_name,\n kcu.referenced_table_name,\n rc.update_rule,\n rc.delete_rule\n order by\n rc.table_name;\n ", [t]))[0].map((e) => {
9433
+ let { constraintName: t, onDelete: n, onUpdate: r, foreignTableName: i, foreignColumnNames: a, refTableName: o, refColumnNames: s } = e;
9434
+ return {
9435
+ name: t,
9436
+ endpoints: [{
9437
+ tableName: i,
9438
+ fieldNames: a.split(","),
9439
+ relation: "*"
9440
+ }, {
9441
+ tableName: o,
9442
+ fieldNames: s.split(","),
9443
+ relation: "1"
9444
+ }],
9445
+ onDelete: n === "NO ACTION" ? null : n,
9446
+ onUpdate: r === "NO ACTION" ? null : r
9447
+ };
10045
9448
  });
10046
9449
  }
9450
+ function combineIndexAndCompositeConstraint(e, t) {
9451
+ let n = Object.assign(e, {});
9452
+ return Object.keys(t).forEach((e) => {
9453
+ let r = t[e];
9454
+ if (!n[e]) {
9455
+ n[e] = r;
9456
+ return;
9457
+ }
9458
+ n[e].push(...r);
9459
+ }), n;
9460
+ }
9461
+ async function fetchSchemaJson$2(e) {
9462
+ let t = await connectMySQL(e), { database: n } = t.config;
9463
+ if (!n) throw Error("Cannot get schema name from the connection");
9464
+ try {
9465
+ let [{ tableList: e, fieldMap: r }, i, a, { primaryAndUniqueConstraintMap: o, compositeConstraintMap: s }, c, { checks: l, tableConstraints: u }] = await Promise.all([
9466
+ generateTablesAndFields$3(t, n),
9467
+ generateEnums(t, n),
9468
+ generateIndexes$2(t, n),
9469
+ generatePrimaryAndUniqueConstraint(t, n),
9470
+ generateForeignKeys(t, n),
9471
+ generateCheckConstraints(t, n)
9472
+ ]), d = combineIndexAndCompositeConstraint(a, s), f = { ...o };
9473
+ return Object.keys(u).forEach((e) => {
9474
+ f[e] || (f[e] = {}), Object.keys(u[e]).forEach((t) => {
9475
+ f[e][t] || (f[e][t] = { checks: [] }), f[e][t].checks.push(...u[e][t].checks);
9476
+ });
9477
+ }), {
9478
+ tables: e,
9479
+ fields: r,
9480
+ refs: c,
9481
+ enums: i,
9482
+ indexes: d,
9483
+ tableConstraints: f,
9484
+ checks: l
9485
+ };
9486
+ } finally {
9487
+ await t.end();
9488
+ }
9489
+ }
10047
9490
  const LIST_SEPARATOR = "@@@@@@@@", EXECUTE_OPTIONS = { outFormat: oracledb.OUT_FORMAT_OBJECT };
10048
9491
  function processEasyConnectString(e) {
10049
9492
  let { username: t, password: n, dbidentifier: r } = e.match(/^(?<username>[^/@:]+)\/(?<password>[^/@:]+)@(\/\/)?(?<dbidentifier>.+)$/)?.groups || {};
@@ -10054,7 +9497,185 @@ function processEasyConnectString(e) {
10054
9497
  dbidentifier: r
10055
9498
  };
10056
9499
  }
10057
- async function generateTablesAndFields(e) {
9500
+ async function generateConstraints(e) {
9501
+ let t = `
9502
+ WITH all_constraints AS (
9503
+ SELECT
9504
+ c.CONSTRAINT_NAME,
9505
+ c.TABLE_NAME,
9506
+ c.CONSTRAINT_TYPE,
9507
+ c.SEARCH_CONDITION_VC AS CHECK_EXPRESSION
9508
+ FROM USER_CONSTRAINTS c
9509
+ WHERE c.CONSTRAINT_TYPE IN ('P', 'U', 'C') -- P stands for primary key, U stands for unique and C stands for check
9510
+ AND (c.CONSTRAINT_TYPE != 'C' OR UPPER(c.SEARCH_CONDITION_VC) NOT LIKE '%IS NOT NULL')
9511
+ ),
9512
+ constraint_columns AS (
9513
+ SELECT
9514
+ cc.CONSTRAINT_NAME,
9515
+ LISTAGG(cc.COLUMN_NAME, '${LIST_SEPARATOR}') WITHIN GROUP (ORDER BY cc.POSITION) AS COLUMNS,
9516
+ COUNT(cc.COLUMN_NAME) AS COLUMN_COUNT
9517
+ FROM USER_CONS_COLUMNS cc
9518
+ GROUP BY cc.CONSTRAINT_NAME
9519
+ )
9520
+ SELECT
9521
+ ac.CONSTRAINT_NAME AS "constraint_name",
9522
+ ac.TABLE_NAME AS "table_name",
9523
+ cc.COLUMNS AS "columns",
9524
+ cc.COLUMN_COUNT AS "column_count",
9525
+ ac.CHECK_EXPRESSION AS "check_expression",
9526
+ ac.CONSTRAINT_TYPE AS "constraint_type"
9527
+ FROM all_constraints ac
9528
+ LEFT JOIN constraint_columns cc
9529
+ ON ac.CONSTRAINT_NAME = cc.CONSTRAINT_NAME
9530
+ LEFT JOIN USER_OBJECTS obj
9531
+ ON obj.OBJECT_NAME = ac.TABLE_NAME
9532
+ AND obj.OBJECT_TYPE = 'TABLE'
9533
+ ORDER BY
9534
+ obj.CREATED,
9535
+ obj.OBJECT_ID,
9536
+ ac.CONSTRAINT_NAME
9537
+ `, n = {}, r = {}, i = {};
9538
+ return (await e.execute(t, [], EXECUTE_OPTIONS)).rows?.forEach((e) => {
9539
+ let { constraint_name: t, table_name: a, columns: o, column_count: s, check_expression: c, constraint_type: l } = e, u = a, d = t || "", f = (o || "").split(LIST_SEPARATOR), p = s || 1, m = l, h = c || null;
9540
+ if (m === "C" && h && p > 1) {
9541
+ i[u] || (i[u] = []);
9542
+ let e = {
9543
+ name: d,
9544
+ expression: h
9545
+ };
9546
+ i[u].push(e);
9547
+ return;
9548
+ }
9549
+ if (m === "C" && h && p === 1 && f.length === 1) {
9550
+ r[u] || (r[u] = {});
9551
+ let e = f[0];
9552
+ r[u][e] || (r[u][e] = { checks: [] }), r[u][e].checks.push({
9553
+ name: d,
9554
+ expression: h
9555
+ });
9556
+ }
9557
+ if (["P", "U"].includes(m) && p === 1 && f.length === 1) {
9558
+ r[u] || (r[u] = {});
9559
+ let e = f[0];
9560
+ r[u][e] || (r[u][e] = { checks: [] }), r[u][e].pk ||= m === "P", r[u][e].unique ||= m === "U";
9561
+ }
9562
+ if (["P", "U"].includes(m) && p > 1) {
9563
+ r[u] || (r[u] = {}), n[u] || (n[u] = []);
9564
+ let e = {
9565
+ name: d,
9566
+ type: "",
9567
+ unique: !0,
9568
+ pk: m === "P",
9569
+ columns: f.map((e) => ({
9570
+ type: "column",
9571
+ value: e
9572
+ }))
9573
+ };
9574
+ n[u].push(e);
9575
+ }
9576
+ }), {
9577
+ indexes: n,
9578
+ tableConstraints: r,
9579
+ checks: i
9580
+ };
9581
+ }
9582
+ async function generateIndexes$1(e) {
9583
+ let t = await e.execute("\n SELECT\n i.INDEX_NAME AS \"index_name\",\n i.TABLE_NAME AS \"table_name\",\n CASE\n WHEN i.INDEX_TYPE LIKE '%NORMAL' THEN 'btree'\n ELSE LOWER(REGEXP_REPLACE(i.INDEX_TYPE, '^FUNCTION-BASED ', ''))\n END AS \"index_type\",\n CASE WHEN i.UNIQUENESS = 'UNIQUE' THEN 1 ELSE 0 END AS \"is_unique\",\n ic.COLUMN_NAME AS \"column_name\",\n ic.COLUMN_POSITION AS \"column_position\",\n ie.COLUMN_EXPRESSION AS \"column_expression\"\n FROM USER_INDEXES i\n LEFT JOIN USER_IND_COLUMNS ic\n ON i.INDEX_NAME = ic.INDEX_NAME\n LEFT JOIN USER_IND_EXPRESSIONS ie\n ON i.INDEX_NAME = ie.INDEX_NAME\n AND ic.COLUMN_POSITION = ie.COLUMN_POSITION\n LEFT JOIN USER_OBJECTS obj\n ON obj.OBJECT_NAME = i.TABLE_NAME\n AND obj.OBJECT_TYPE = 'TABLE'\n WHERE NOT EXISTS (\n SELECT 1\n FROM USER_CONSTRAINTS c\n WHERE c.INDEX_NAME = i.INDEX_NAME\n )\n ORDER BY obj.CREATED, obj.OBJECT_ID, i.INDEX_NAME, ic.COLUMN_POSITION\n ", [], EXECUTE_OPTIONS), n = {}, r = {};
9584
+ return t.rows?.forEach((e) => {
9585
+ let { index_name: t, table_name: n, index_type: i, is_unique: a, column_name: o, column_expression: s } = e, c = t, l = n, u = i, d = !!a;
9586
+ if (s) {
9587
+ r[c] || (r[c] = {
9588
+ table: l,
9589
+ type: u,
9590
+ unique: d,
9591
+ columns: []
9592
+ }), r[c].columns.push({
9593
+ type: "expression",
9594
+ value: s
9595
+ });
9596
+ return;
9597
+ }
9598
+ if (o) {
9599
+ r[c] || (r[c] = {
9600
+ table: l,
9601
+ type: u,
9602
+ unique: d,
9603
+ columns: []
9604
+ }), r[c].columns.push({
9605
+ type: "column",
9606
+ value: o
9607
+ });
9608
+ return;
9609
+ }
9610
+ }), Object.entries(r).forEach(([e, { table: t, type: r, unique: i, columns: a }]) => {
9611
+ let o = {
9612
+ name: e,
9613
+ type: r,
9614
+ unique: i,
9615
+ columns: a
9616
+ };
9617
+ n[t] || (n[t] = []), n[t].push(o);
9618
+ }), n;
9619
+ }
9620
+ async function generateRawRefs$1(e) {
9621
+ let t = [], n = `
9622
+ SELECT
9623
+ c.CONSTRAINT_NAME AS "fk_name",
9624
+ c.TABLE_NAME AS "child_table",
9625
+ LISTAGG(cc.COLUMN_NAME, '${LIST_SEPARATOR}') WITHIN GROUP (ORDER BY cc.POSITION) AS "child_columns",
9626
+ p.TABLE_NAME AS "parent_table",
9627
+ LISTAGG(pc.COLUMN_NAME, '${LIST_SEPARATOR}') WITHIN GROUP (ORDER BY pc.POSITION) AS "parent_columns",
9628
+ c.DELETE_RULE AS "delete_rule"
9629
+ FROM USER_CONSTRAINTS c
9630
+ JOIN USER_CONSTRAINTS p
9631
+ ON c.R_CONSTRAINT_NAME = p.CONSTRAINT_NAME
9632
+ JOIN USER_CONS_COLUMNS cc
9633
+ ON c.CONSTRAINT_NAME = cc.CONSTRAINT_NAME
9634
+ JOIN USER_CONS_COLUMNS pc
9635
+ ON p.CONSTRAINT_NAME = pc.CONSTRAINT_NAME
9636
+ AND cc.POSITION = pc.POSITION
9637
+ LEFT JOIN USER_OBJECTS obj_child
9638
+ ON obj_child.OBJECT_NAME = c.TABLE_NAME
9639
+ AND obj_child.OBJECT_TYPE = 'TABLE'
9640
+ LEFT JOIN USER_OBJECTS obj_parent
9641
+ ON obj_parent.OBJECT_NAME = p.TABLE_NAME
9642
+ AND obj_parent.OBJECT_TYPE = 'TABLE'
9643
+ WHERE c.CONSTRAINT_TYPE = 'R'
9644
+ GROUP BY
9645
+ c.CONSTRAINT_NAME,
9646
+ c.TABLE_NAME,
9647
+ p.TABLE_NAME,
9648
+ c.DELETE_RULE,
9649
+ obj_child.CREATED,
9650
+ obj_child.OBJECT_ID,
9651
+ obj_parent.CREATED,
9652
+ obj_parent.OBJECT_ID
9653
+ ORDER BY
9654
+ obj_child.CREATED,
9655
+ obj_child.OBJECT_ID,
9656
+ c.CONSTRAINT_NAME
9657
+ `;
9658
+ return (await e.execute(n, [], EXECUTE_OPTIONS)).rows?.forEach((e) => {
9659
+ let { fk_name: n, child_table: r, child_columns: i, parent_table: a, parent_columns: o, delete_rule: s } = e, c = {
9660
+ tableName: r,
9661
+ schemaName: "",
9662
+ fieldNames: i.split(LIST_SEPARATOR),
9663
+ relation: "*"
9664
+ }, l = {
9665
+ tableName: a,
9666
+ schemaName: "",
9667
+ fieldNames: o.split(LIST_SEPARATOR),
9668
+ relation: "1"
9669
+ };
9670
+ t.push({
9671
+ name: n,
9672
+ endpoints: [c, l],
9673
+ onDelete: s === "NO ACTION" ? null : s,
9674
+ onUpdate: null
9675
+ });
9676
+ }), t;
9677
+ }
9678
+ async function generateTablesAndFields$2(e) {
10058
9679
  let t = {}, n = (await e.execute("\n SELECT\n cols.TABLE_NAME AS \"table_name\",\n cols.COLUMN_NAME AS \"column_name\",\n cols.COLUMN_ID AS \"column_id\",\n cols.DATA_TYPE AS \"data_type\",\n cols.DATA_LENGTH AS \"data_length\",\n cols.DATA_PRECISION AS \"data_precision\",\n cols.DATA_SCALE AS \"data_scale\",\n CASE WHEN cols.IDENTITY_COLUMN = 'YES' THEN 1 ELSE 0 END AS \"identity_increment\",\n CASE WHEN cols.NULLABLE = 'Y' THEN 1 ELSE 0 END AS \"is_nullable\",\n cols.DATA_DEFAULT AS \"data_default\",\n tcoms.COMMENTS AS \"table_comment\",\n ccoms.COMMENTS AS \"column_comment\",\n obj.CREATED AS \"table_created\"\n FROM USER_TAB_COLUMNS cols\n LEFT JOIN USER_COL_COMMENTS ccoms\n ON ccoms.COLUMN_NAME = cols.COLUMN_NAME\n AND ccoms.TABLE_NAME = cols.TABLE_NAME\n LEFT JOIN USER_TAB_COMMENTS tcoms\n ON tcoms.TABLE_NAME = cols.TABLE_NAME\n LEFT JOIN USER_OBJECTS obj\n ON obj.OBJECT_NAME = cols.TABLE_NAME\n AND obj.OBJECT_TYPE = 'TABLE'\n ORDER BY obj.CREATED, obj.OBJECT_ID, cols.COLUMN_ID\n ", [], EXECUTE_OPTIONS)).rows?.reduce((e, n) => {
10059
9680
  let { table_name: r, table_comment: i } = n;
10060
9681
  e[r] || (e[r] = {
@@ -10062,7 +9683,7 @@ async function generateTablesAndFields(e) {
10062
9683
  schemaName: "",
10063
9684
  note: i ? { value: i } : { value: "" }
10064
9685
  }), t[r] || (t[r] = []);
10065
- let a = generateField(n);
9686
+ let a = generateField$2(n);
10066
9687
  return t[r].push(a), e;
10067
9688
  }, {}) || {};
10068
9689
  return {
@@ -10075,12 +9696,12 @@ function getDefaultType(e) {
10075
9696
  let t = e.trim();
10076
9697
  return /^'.*'$/.test(t) ? "string" : /^[0-9]+$/.test(t) || /^[0-9]*\.[0-9]*$/.test(t) ? "number" : "expression";
10077
9698
  }
10078
- function generateField(e) {
10079
- let { column_name: t, data_type: n, data_length: r, data_precision: i, data_scale: a, identity_increment: o, is_nullable: s, data_default: c, column_comment: l } = e, u = getDefaultType(c), d = c && !o ? getDbdefault(c, u) : null;
9699
+ function generateField$2(e) {
9700
+ let { column_name: t, data_type: n, data_length: r, data_precision: i, data_scale: a, identity_increment: o, is_nullable: s, data_default: c, column_comment: l } = e, u = getDefaultType(c), d = c && !o ? getDbdefault$2(c, u) : null;
10080
9701
  return {
10081
9702
  name: t,
10082
9703
  type: {
10083
- type_name: getFieldType(n, r, i, a),
9704
+ type_name: getFieldType$2(n, r, i, a),
10084
9705
  schemaName: null
10085
9706
  },
10086
9707
  dbdefault: d,
@@ -10089,7 +9710,7 @@ function generateField(e) {
10089
9710
  note: l ? { value: l } : { value: "" }
10090
9711
  };
10091
9712
  }
10092
- function getDbdefault(e, t) {
9713
+ function getDbdefault$2(e, t) {
10093
9714
  return e === null ? null : t === "string" ? {
10094
9715
  value: e.trim().slice(1, -1).replaceAll("''", "'"),
10095
9716
  type: t
@@ -10134,227 +9755,606 @@ function normalizeFieldType(e) {
10134
9755
  default: return t;
10135
9756
  }
10136
9757
  }
10137
- function getFieldType(e, t, n, r) {
9758
+ function getFieldType$2(e, t, n, r) {
10138
9759
  let i = normalizeFieldType(e);
10139
9760
  return i === TIMESTAMP_WITH_LOCAL_TIME_ZONE_DATA_TYPE ? r === null ? i : `timestamp (${r}) with local time zone` : i === TIMESTAMP_WITH_TIME_ZONE_DATA_TYPE ? r === null ? i : `timestamp (${r}) with time zone` : i === TIMESTAMP_DATA_TYPE ? r === null ? i : `timestamp (${r})` : i === INTERVAL_YEAR_DATA_TYPE ? n === null ? i : `interval year (${n}) to month` : i === INTERVAL_DAY_DATA_TYPE ? n !== null && r !== null ? `interval day (${n}) to second (${r})` : n === null ? r === null ? i : `interval day to second (${r})` : `interval day (${n}) to second` : SIZED_DATA_TYPES.has(i) ? t ? `${i}(${t})` : i : PRECISION_DATA_TYPES.has(i) ? n === null ? i : `${i}(${n})` : PRECISION_SCALED_DATA_TYPES.has(i) ? n !== null && r !== null ? `${i}(${n}, ${r})` : n === null ? i : `${i}(${n})` : i;
10140
9761
  }
10141
- async function generateRawRefs(e) {
10142
- let t = [], n = `
9762
+ var getValidatedClient$1 = async (e, t, n) => {
9763
+ let r = await getConnection({
9764
+ username: e,
9765
+ password: t,
9766
+ connectionString: n
9767
+ });
9768
+ try {
9769
+ return await r.execute("SELECT 1 FROM DUAL"), r;
9770
+ } catch (e) {
9771
+ throw await r.close(), e instanceof Error ? Error(`OracleSQL connection error: ${e.message}`) : e;
9772
+ }
9773
+ };
9774
+ async function fetchSchemaJson$3(e) {
9775
+ let { username: t, password: n, dbidentifier: r } = processEasyConnectString(e), i = await getValidatedClient$1(t, n, r), a = generateTablesAndFields$2(i), o = generateConstraints(i), s = generateRawRefs$1(i), c = generateIndexes$1(i), l = await Promise.all([
9776
+ a,
9777
+ o,
9778
+ s,
9779
+ c
9780
+ ]), { tables: u, fields: d } = l[0], { indexes: f, tableConstraints: p, checks: m } = l[1], h = l[2], g = l[3];
9781
+ return Object.keys(f).forEach((e) => {
9782
+ g[e] ? g[e].push(...f[e]) : g[e] = f[e];
9783
+ }), await i.close(), {
9784
+ tables: u,
9785
+ fields: d,
9786
+ refs: h,
9787
+ enums: [],
9788
+ indexes: g,
9789
+ tableConstraints: p,
9790
+ checks: m
9791
+ };
9792
+ }
9793
+ var getValidatedClient = async (e) => {
9794
+ let t = new Client(e);
9795
+ try {
9796
+ return await t.connect(), await t.query("SELECT 1"), t;
9797
+ } catch (e) {
9798
+ throw await t.end(), e instanceof Error ? Error(`PostgreSQL connection error: ${e}`) : e;
9799
+ }
9800
+ }, convertQueryBoolean$1 = (e) => e === "YES", getFieldType$1 = (e, t, n, r, i) => e === "ARRAY" ? `${t.slice(1, t.length)}[]` : n ? `${t}(${n})` : r && i ? `${t}(${r},${i})` : t, getDbdefault$1 = (e, t, n) => {
9801
+ if (e === "ARRAY") return {
9802
+ type: n,
9803
+ value: `ARRAY[${t.slice(6, -1).split(",").map((e) => e.split("::")[0]).join(", ")}]`
9804
+ };
9805
+ if (n === "string") {
9806
+ let n = t.split("::")[0];
9807
+ return {
9808
+ type: e === "json" || e === "jsonb" ? "expression" : "string",
9809
+ value: n.slice(1, -1)
9810
+ };
9811
+ }
9812
+ return {
9813
+ type: n,
9814
+ value: t
9815
+ };
9816
+ }, generateField$1 = (e) => {
9817
+ let { column_name: t, data_type: n, character_maximum_length: r, numeric_precision: i, numeric_scale: a, udt_schema: o, udt_name: s, identity_increment: c, is_nullable: l, column_default: u, default_type: d, column_comment: f } = e, p = u && d !== "increment" ? getDbdefault$1(n, u, d) : null;
9818
+ return {
9819
+ name: t,
9820
+ type: n === "USER-DEFINED" ? {
9821
+ type_name: s,
9822
+ schemaName: o
9823
+ } : {
9824
+ type_name: getFieldType$1(n, s, r, i, a),
9825
+ schemaName: null
9826
+ },
9827
+ dbdefault: p,
9828
+ not_null: !convertQueryBoolean$1(l),
9829
+ increment: !!c || d === "increment",
9830
+ note: f ? { value: f } : { value: "" }
9831
+ };
9832
+ }, generateTablesAndFields$1 = async (e, t) => {
9833
+ let n = {}, r = `
9834
+ WITH
9835
+ comments AS (
9836
+ SELECT DISTINCT ON (pc.relname, pn.nspname, pa.attname)
9837
+ pc.relname AS table_name,
9838
+ pn.nspname AS table_schema,
9839
+ pa.attname AS column_name,
9840
+ pd.description
9841
+ FROM
9842
+ pg_description pd
9843
+ JOIN
9844
+ pg_class pc ON pd.objoid = pc.oid
9845
+ JOIN
9846
+ pg_namespace pn ON pc.relnamespace = pn.oid
9847
+ LEFT JOIN
9848
+ pg_attribute pa ON pd.objoid = pa.attrelid AND pd.objsubid = pa.attnum
9849
+ WHERE
9850
+ pc.relkind = 'r'
9851
+ AND pn.nspname NOT IN ('pg_catalog', 'information_schema')
9852
+ ),
9853
+ table_positions AS (
9854
+ SELECT
9855
+ pc.oid as table_ordinal_position,
9856
+ pc.relname as table_name,
9857
+ pn.nspname as table_schema
9858
+ FROM pg_class pc
9859
+ JOIN pg_namespace pn
9860
+ ON pc.relnamespace = pn.oid
9861
+ WHERE
9862
+ -- r is ordinary table
9863
+ -- see https://www.postgresql.org/docs/14/catalog-pg-class.html#:~:text=%3D%20temporary%20table-,relkind,-char
9864
+ pc.relkind = 'r'
9865
+ AND pn.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
9866
+ ${buildSchemaQuery("pn.nspname", t)}
9867
+ )
10143
9868
  SELECT
10144
- c.CONSTRAINT_NAME AS "fk_name",
10145
- c.TABLE_NAME AS "child_table",
10146
- LISTAGG(cc.COLUMN_NAME, '${LIST_SEPARATOR}') WITHIN GROUP (ORDER BY cc.POSITION) AS "child_columns",
10147
- p.TABLE_NAME AS "parent_table",
10148
- LISTAGG(pc.COLUMN_NAME, '${LIST_SEPARATOR}') WITHIN GROUP (ORDER BY pc.POSITION) AS "parent_columns",
10149
- c.DELETE_RULE AS "delete_rule"
10150
- FROM USER_CONSTRAINTS c
10151
- JOIN USER_CONSTRAINTS p
10152
- ON c.R_CONSTRAINT_NAME = p.CONSTRAINT_NAME
10153
- JOIN USER_CONS_COLUMNS cc
10154
- ON c.CONSTRAINT_NAME = cc.CONSTRAINT_NAME
10155
- JOIN USER_CONS_COLUMNS pc
10156
- ON p.CONSTRAINT_NAME = pc.CONSTRAINT_NAME
10157
- AND cc.POSITION = pc.POSITION
10158
- LEFT JOIN USER_OBJECTS obj_child
10159
- ON obj_child.OBJECT_NAME = c.TABLE_NAME
10160
- AND obj_child.OBJECT_TYPE = 'TABLE'
10161
- LEFT JOIN USER_OBJECTS obj_parent
10162
- ON obj_parent.OBJECT_NAME = p.TABLE_NAME
10163
- AND obj_parent.OBJECT_TYPE = 'TABLE'
10164
- WHERE c.CONSTRAINT_TYPE = 'R'
9869
+ t.table_schema,
9870
+ t.table_name,
9871
+ c.column_name,
9872
+ c.data_type,
9873
+ c.character_maximum_length,
9874
+ c.numeric_precision,
9875
+ c.numeric_scale,
9876
+ c.udt_schema,
9877
+ c.udt_name,
9878
+ c.identity_increment,
9879
+ c.is_nullable,
9880
+ c.column_default,
9881
+ c.ordinal_position,
9882
+ CASE
9883
+ WHEN c.column_default IS NULL THEN NULL
9884
+ WHEN c.column_default LIKE 'nextval(%' THEN 'increment'
9885
+ WHEN c.column_default LIKE '''%' THEN 'string'
9886
+ WHEN c.column_default = 'true' OR c.column_default = 'false' THEN 'boolean'
9887
+ WHEN c.column_default ~ '^-?[0-9]+(.[0-9]+)?$' THEN 'number'
9888
+ ELSE 'expression'
9889
+ END AS default_type,
9890
+ (SELECT description FROM comments WHERE table_name = t.table_name AND table_schema = t.table_schema AND column_name IS NULL LIMIT 1) AS table_comment,
9891
+ (SELECT description FROM comments WHERE table_name = t.table_name AND table_schema = t.table_schema AND column_name = c.column_name LIMIT 1) AS column_comment
9892
+ FROM
9893
+ information_schema.columns c
9894
+ JOIN
9895
+ information_schema.tables t ON c.table_name = t.table_name AND c.table_schema = t.table_schema
9896
+ JOIN
9897
+ table_positions tp ON tp.table_name = t.table_name AND tp.table_schema = t.table_schema
9898
+ WHERE
9899
+ t.table_type = 'BASE TABLE'
9900
+ AND t.table_schema NOT IN ('pg_catalog', 'information_schema')
9901
+ ${buildSchemaQuery("t.table_schema", t)}
9902
+ ORDER BY
9903
+ t.table_schema,
9904
+ tp.table_ordinal_position,
9905
+ c.ordinal_position
9906
+ ;
9907
+ `, i = (await e.query(r)).rows.reduce((e, t) => {
9908
+ let { table_schema: r, table_name: i, table_comment: a } = t, o = `${r}.${i}`;
9909
+ e[o] || (e[o] = {
9910
+ name: i,
9911
+ schemaName: r,
9912
+ note: a ? { value: a } : { value: "" }
9913
+ }), n[o] || (n[o] = []);
9914
+ let s = generateField$1(t);
9915
+ return n[o].push(s), e;
9916
+ }, {});
9917
+ return {
9918
+ tables: Object.values(i),
9919
+ fields: n
9920
+ };
9921
+ }, generateRawRefs = async (e, t) => {
9922
+ let n = [], r = `
9923
+ SELECT
9924
+ tc.table_schema,
9925
+ tc.table_name,
9926
+ tc.constraint_name as fk_constraint_name,
9927
+ STRING_AGG(DISTINCT kcu.column_name, ',') AS column_names,
9928
+ ccu.table_schema AS foreign_table_schema,
9929
+ ccu.table_name AS foreign_table_name,
9930
+ STRING_AGG(DISTINCT ccu.column_name, ',') AS foreign_column_names,
9931
+ tc.constraint_type,
9932
+ rc.delete_rule AS on_delete,
9933
+ rc.update_rule AS on_update
9934
+ FROM information_schema.table_constraints AS tc
9935
+ JOIN information_schema.key_column_usage AS kcu
9936
+ ON tc.constraint_name = kcu.constraint_name
9937
+ AND tc.table_schema = kcu.table_schema
9938
+ JOIN information_schema.constraint_column_usage AS ccu
9939
+ ON ccu.constraint_name = tc.constraint_name
9940
+ JOIN information_schema.referential_constraints AS rc
9941
+ ON tc.constraint_name = rc.constraint_name
9942
+ AND tc.table_schema = rc.constraint_schema
9943
+ WHERE tc.constraint_type = 'FOREIGN KEY'
9944
+ AND tc.table_schema NOT IN ('pg_catalog', 'information_schema')
9945
+ ${buildSchemaQuery("tc.table_schema", t)}
10165
9946
  GROUP BY
10166
- c.CONSTRAINT_NAME,
10167
- c.TABLE_NAME,
10168
- p.TABLE_NAME,
10169
- c.DELETE_RULE,
10170
- obj_child.CREATED,
10171
- obj_child.OBJECT_ID,
10172
- obj_parent.CREATED,
10173
- obj_parent.OBJECT_ID
9947
+ tc.table_schema,
9948
+ tc.table_name,
9949
+ tc.constraint_name,
9950
+ ccu.table_schema,
9951
+ ccu.table_name,
9952
+ tc.constraint_type,
9953
+ rc.delete_rule,
9954
+ rc.update_rule
10174
9955
  ORDER BY
10175
- obj_child.CREATED,
10176
- obj_child.OBJECT_ID,
10177
- c.CONSTRAINT_NAME
9956
+ tc.table_schema,
9957
+ tc.table_name;
10178
9958
  `;
10179
- return (await e.execute(n, [], EXECUTE_OPTIONS)).rows?.forEach((e) => {
10180
- let { fk_name: n, child_table: r, child_columns: i, parent_table: a, parent_columns: o, delete_rule: s } = e, c = {
10181
- tableName: r,
10182
- schemaName: "",
10183
- fieldNames: i.split(LIST_SEPARATOR),
9959
+ return (await e.query(r)).rows.forEach((e) => {
9960
+ let { table_schema: t, fk_constraint_name: r, table_name: i, column_names: a, foreign_table_schema: o, foreign_table_name: s, foreign_column_names: c, on_delete: l, on_update: u } = e, d = {
9961
+ tableName: i,
9962
+ schemaName: t,
9963
+ fieldNames: a.split(","),
10184
9964
  relation: "*"
10185
- }, l = {
10186
- tableName: a,
10187
- schemaName: "",
10188
- fieldNames: o.split(LIST_SEPARATOR),
9965
+ }, f = {
9966
+ tableName: s,
9967
+ schemaName: o,
9968
+ fieldNames: c.split(","),
10189
9969
  relation: "1"
10190
9970
  };
10191
- t.push({
10192
- name: n,
10193
- endpoints: [c, l],
10194
- onDelete: s === "NO ACTION" ? null : s,
10195
- onUpdate: null
9971
+ n.push({
9972
+ name: r,
9973
+ endpoints: [d, f],
9974
+ onDelete: l === "NO ACTION" ? null : l,
9975
+ onUpdate: u === "NO ACTION" ? null : u
10196
9976
  });
10197
- }), t;
10198
- }
10199
- async function generateConstraints(e) {
10200
- let t = `
10201
- WITH all_constraints AS (
9977
+ }), n;
9978
+ }, generateIndexesAndConstraints = async (e, t) => {
9979
+ let n = `
9980
+ WITH user_tables AS (
10202
9981
  SELECT
10203
- c.CONSTRAINT_NAME,
10204
- c.TABLE_NAME,
10205
- c.CONSTRAINT_TYPE,
10206
- c.SEARCH_CONDITION_VC AS CHECK_EXPRESSION
10207
- FROM USER_CONSTRAINTS c
10208
- WHERE c.CONSTRAINT_TYPE IN ('P', 'U', 'C') -- P stands for primary key, U stands for unique and C stands for check
10209
- AND (c.CONSTRAINT_TYPE != 'C' OR UPPER(c.SEARCH_CONDITION_VC) NOT LIKE '%IS NOT NULL')
9982
+ schemaname AS tableschema,
9983
+ tablename
9984
+ FROM pg_tables
9985
+ WHERE schemaname NOT IN ('pg_catalog', 'information_schema') -- Exclude system schemas
9986
+ AND tablename NOT LIKE 'pg_%' -- Exclude PostgreSQL system tables
9987
+ AND tablename NOT LIKE 'sql_%' -- Exclude SQL standard tables
10210
9988
  ),
10211
- constraint_columns AS (
9989
+ index_info AS (
10212
9990
  SELECT
10213
- cc.CONSTRAINT_NAME,
10214
- LISTAGG(cc.COLUMN_NAME, '${LIST_SEPARATOR}') WITHIN GROUP (ORDER BY cc.POSITION) AS COLUMNS,
10215
- COUNT(cc.COLUMN_NAME) AS COLUMN_COUNT
10216
- FROM USER_CONS_COLUMNS cc
10217
- GROUP BY cc.CONSTRAINT_NAME
9991
+ t.relnamespace::regnamespace::text AS table_schema,
9992
+ t.relname AS table_name,
9993
+ i.relname AS index_name,
9994
+ ix.indisunique AS is_unique,
9995
+ ix.indisprimary AS is_primary,
9996
+ am.amname AS index_type,
9997
+ array_to_string(array_agg(a.attname ORDER BY x.n), ', ') AS columns,
9998
+ pg_get_expr(ix.indexprs, ix.indrelid) AS expressions,
9999
+ CASE
10000
+ WHEN ix.indisprimary THEN 'PRIMARY KEY'
10001
+ WHEN ix.indisunique THEN 'UNIQUE'
10002
+ ELSE NULL
10003
+ END AS constraint_type
10004
+ FROM
10005
+ pg_class t
10006
+ JOIN pg_index ix ON t.oid = ix.indrelid
10007
+ JOIN pg_class i ON i.oid = ix.indexrelid
10008
+ LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
10009
+ JOIN pg_am am ON i.relam = am.oid
10010
+ LEFT JOIN generate_subscripts(ix.indkey, 1) AS x(n) ON a.attnum = ix.indkey[x.n]
10011
+ WHERE
10012
+ t.relkind = 'r'
10013
+ AND t.relname NOT LIKE 'pg_%'
10014
+ AND t.relname NOT LIKE 'sql_%'
10015
+ GROUP BY
10016
+ t.relnamespace, t.relname, i.relname, ix.indisunique, ix.indisprimary, am.amname, ix.indexprs, ix.indrelid
10218
10017
  )
10219
10018
  SELECT
10220
- ac.CONSTRAINT_NAME AS "constraint_name",
10221
- ac.TABLE_NAME AS "table_name",
10222
- cc.COLUMNS AS "columns",
10223
- cc.COLUMN_COUNT AS "column_count",
10224
- ac.CHECK_EXPRESSION AS "check_expression",
10225
- ac.CONSTRAINT_TYPE AS "constraint_type"
10226
- FROM all_constraints ac
10227
- LEFT JOIN constraint_columns cc
10228
- ON ac.CONSTRAINT_NAME = cc.CONSTRAINT_NAME
10229
- LEFT JOIN USER_OBJECTS obj
10230
- ON obj.OBJECT_NAME = ac.TABLE_NAME
10231
- AND obj.OBJECT_TYPE = 'TABLE'
10019
+ ut.tableschema AS table_schema,
10020
+ ut.tablename AS table_name,
10021
+ ii.index_name,
10022
+ ii.is_unique,
10023
+ ii.is_primary,
10024
+ ii.index_type,
10025
+ ii.columns AS index_columns,
10026
+ ii.expressions AS index_expressions,
10027
+ ii.constraint_type -- Retained constraint type here
10028
+ FROM
10029
+ user_tables ut
10030
+ LEFT JOIN
10031
+ index_info ii ON ut.tableschema = ii.table_schema AND ut.tablename = ii.table_name
10032
+ WHERE ii.columns IS NOT NULL
10033
+ ${buildSchemaQuery("ut.tableschema", t)}
10232
10034
  ORDER BY
10233
- obj.CREATED,
10234
- obj.OBJECT_ID,
10235
- ac.CONSTRAINT_NAME
10236
- `, n = {}, r = {}, i = {};
10237
- return (await e.execute(t, [], EXECUTE_OPTIONS)).rows?.forEach((e) => {
10238
- let { constraint_name: t, table_name: a, columns: o, column_count: s, check_expression: c, constraint_type: l } = e, u = a, d = t || "", f = (o || "").split(LIST_SEPARATOR), p = s || 1, m = l, h = c || null;
10239
- if (m === "C" && h && p > 1) {
10240
- i[u] || (i[u] = []);
10241
- let e = {
10242
- name: d,
10243
- expression: h
10244
- };
10245
- i[u].push(e);
10246
- return;
10247
- }
10248
- if (m === "C" && h && p === 1 && f.length === 1) {
10249
- r[u] || (r[u] = {});
10250
- let e = f[0];
10251
- r[u][e] || (r[u][e] = { checks: [] }), r[u][e].checks.push({
10252
- name: d,
10253
- expression: h
10254
- });
10255
- }
10256
- if (["P", "U"].includes(m) && p === 1 && f.length === 1) {
10257
- r[u] || (r[u] = {});
10258
- let e = f[0];
10259
- r[u][e] || (r[u][e] = { checks: [] }), r[u][e].pk ||= m === "P", r[u][e].unique ||= m === "U";
10260
- }
10261
- if (["P", "U"].includes(m) && p > 1) {
10262
- r[u] || (r[u] = {}), n[u] || (n[u] = []);
10263
- let e = {
10264
- name: d,
10265
- type: "",
10266
- unique: !0,
10267
- pk: m === "P",
10268
- columns: f.map((e) => ({
10269
- type: "column",
10270
- value: e
10271
- }))
10272
- };
10273
- n[u].push(e);
10274
- }
10275
- }), {
10276
- indexes: n,
10277
- tableConstraints: r,
10278
- checks: i
10279
- };
10280
- }
10281
- async function generateIndexes(e) {
10282
- let t = await e.execute("\n SELECT\n i.INDEX_NAME AS \"index_name\",\n i.TABLE_NAME AS \"table_name\",\n CASE\n WHEN i.INDEX_TYPE LIKE '%NORMAL' THEN 'btree'\n ELSE LOWER(REGEXP_REPLACE(i.INDEX_TYPE, '^FUNCTION-BASED ', ''))\n END AS \"index_type\",\n CASE WHEN i.UNIQUENESS = 'UNIQUE' THEN 1 ELSE 0 END AS \"is_unique\",\n ic.COLUMN_NAME AS \"column_name\",\n ic.COLUMN_POSITION AS \"column_position\",\n ie.COLUMN_EXPRESSION AS \"column_expression\"\n FROM USER_INDEXES i\n LEFT JOIN USER_IND_COLUMNS ic\n ON i.INDEX_NAME = ic.INDEX_NAME\n LEFT JOIN USER_IND_EXPRESSIONS ie\n ON i.INDEX_NAME = ie.INDEX_NAME\n AND ic.COLUMN_POSITION = ie.COLUMN_POSITION\n LEFT JOIN USER_OBJECTS obj\n ON obj.OBJECT_NAME = i.TABLE_NAME\n AND obj.OBJECT_TYPE = 'TABLE'\n WHERE NOT EXISTS (\n SELECT 1\n FROM USER_CONSTRAINTS c\n WHERE c.INDEX_NAME = i.INDEX_NAME\n )\n ORDER BY obj.CREATED, obj.OBJECT_ID, i.INDEX_NAME, ic.COLUMN_POSITION\n ", [], EXECUTE_OPTIONS), n = {}, r = {};
10283
- return t.rows?.forEach((e) => {
10284
- let { index_name: t, table_name: n, index_type: i, is_unique: a, column_name: o, column_expression: s } = e, c = t, l = n, u = i, d = !!a;
10285
- if (s) {
10286
- r[c] || (r[c] = {
10287
- table: l,
10288
- type: u,
10289
- unique: d,
10290
- columns: []
10291
- }), r[c].columns.push({
10292
- type: "expression",
10293
- value: s
10294
- });
10295
- return;
10296
- }
10297
- if (o) {
10298
- r[c] || (r[c] = {
10299
- table: l,
10300
- type: u,
10301
- unique: d,
10302
- columns: []
10303
- }), r[c].columns.push({
10304
- type: "column",
10305
- value: o
10035
+ ut.tablename,
10036
+ ii.constraint_type,
10037
+ ii.index_name
10038
+ ;
10039
+ `, { outOfLineIndexes: r, inlineIndexes: i } = (await e.query(n)).rows.reduce((e, t) => {
10040
+ let { constraint_type: n, index_columns: r } = t;
10041
+ return r === "null" || r.trim() === "" || (r.split(",").length === 1 && (n === "PRIMARY KEY" || n === "UNIQUE") ? e.inlineIndexes.push(t) : e.outOfLineIndexes.push(t)), e;
10042
+ }, {
10043
+ outOfLineIndexes: [],
10044
+ inlineIndexes: []
10045
+ }), a = r.reduce((e, t) => {
10046
+ let { table_schema: n, table_name: r, index_name: i, index_type: a, index_columns: o, index_expressions: s, is_primary: c, is_unique: l } = t, u = o.split(",").map((e) => ({
10047
+ type: "column",
10048
+ value: e.trim()
10049
+ })), d = s ? s.split(",").map((e) => ({
10050
+ type: "expression",
10051
+ value: e
10052
+ })) : [], f = {
10053
+ name: i,
10054
+ type: a,
10055
+ columns: [...u, ...d],
10056
+ pk: !!c,
10057
+ unique: !c && !!l
10058
+ }, p = `${n}.${r}`;
10059
+ return e[p] ? e[p].push(f) : e[p] = [f], e;
10060
+ }, {}), o = {};
10061
+ i.forEach((e) => {
10062
+ let { table_schema: t, table_name: n, index_columns: r, constraint_type: i } = e, a = `${t}.${n}`;
10063
+ o[a] || (o[a] = {}), r.split(",").map((e) => e.trim()).forEach((e) => {
10064
+ o[a][e] || (o[a][e] = { checks: [] }), i === "PRIMARY KEY" && (o[a][e].pk = !0), i === "UNIQUE" && !o[a][e].pk && (o[a][e].unique = !0);
10065
+ });
10066
+ }, {});
10067
+ let s = `
10068
+ SELECT
10069
+ n.nspname AS table_schema,
10070
+ c.relname AS table_name,
10071
+ MAX(a.attname) AS column_name,
10072
+ con.conname AS check_name,
10073
+ pg_get_constraintdef(con.oid) AS check_definition,
10074
+ CASE
10075
+ WHEN COUNT(*) = 1 THEN TRUE
10076
+ ELSE FALSE
10077
+ END AS is_column_constraint
10078
+ FROM
10079
+ pg_catalog.pg_constraint AS con
10080
+ JOIN
10081
+ pg_catalog.pg_class AS c
10082
+ ON con.conrelid = c.oid
10083
+ LEFT JOIN
10084
+ pg_catalog.pg_namespace AS n
10085
+ ON c.relnamespace = n.oid
10086
+ LEFT JOIN
10087
+ pg_catalog.pg_attribute AS a
10088
+ ON a.attrelid = c.oid AND a.attnum = ANY(con.conkey)
10089
+ WHERE con.contype = 'c' -- 'c' for CHECK constraints
10090
+ ${buildSchemaQuery("n.nspname", t)}
10091
+ GROUP BY
10092
+ con.conname,
10093
+ n.nspname,
10094
+ c.relname,
10095
+ con.oid
10096
+ `, c = await e.query(s), l = {};
10097
+ return c.rows.forEach((e) => {
10098
+ let { table_schema: t, table_name: n, check_name: r, check_definition: i, column_name: a, is_column_constraint: s } = e;
10099
+ if (typeof t != "string" || typeof n != "string" || typeof i != "string" || !i.match(/CHECK \(\(.*\)\)/) || s && typeof a != "string") return;
10100
+ let c = `${t}.${n}`;
10101
+ if (s) {
10102
+ o[c] || (o[c] = {}), o[c][a] || (o[c][a] = { checks: [] }), o[c][a].checks.push({
10103
+ name: r || void 0,
10104
+ expression: i.slice(8, -2)
10306
10105
  });
10307
10106
  return;
10308
10107
  }
10309
- }), Object.entries(r).forEach(([e, { table: t, type: r, unique: i, columns: a }]) => {
10310
- let o = {
10311
- name: e,
10312
- type: r,
10313
- unique: i,
10314
- columns: a
10108
+ l[c] || (l[c] = []), l[c].push({
10109
+ name: r || void 0,
10110
+ expression: i.slice(8, -2)
10111
+ });
10112
+ }), {
10113
+ indexes: a,
10114
+ tableConstraints: o,
10115
+ checks: l
10116
+ };
10117
+ }, generateRawEnums = async (e, t) => {
10118
+ let n = `
10119
+ SELECT DISTINCT
10120
+ n.nspname AS schema_name,
10121
+ t.typname AS enum_type,
10122
+ e.enumlabel AS enum_value,
10123
+ e.enumsortorder AS sort_order
10124
+ FROM
10125
+ pg_enum e
10126
+ JOIN
10127
+ pg_type t ON e.enumtypid = t.oid
10128
+ JOIN
10129
+ pg_namespace n ON t.typnamespace = n.oid
10130
+ ${buildSchemaQuery("n.nspname", t, "WHERE")}
10131
+ ORDER BY
10132
+ schema_name,
10133
+ enum_type,
10134
+ sort_order;
10135
+ ;
10136
+ `, r = (await e.query(n)).rows.reduce((e, t) => {
10137
+ let { schema_name: n, enum_type: r, enum_value: i } = t, a = `${n}.${r}`;
10138
+ return e[a] || (e[a] = {
10139
+ name: r,
10140
+ schemaName: n,
10141
+ values: []
10142
+ }), e[a].values.push({ name: i }), e;
10143
+ }, {});
10144
+ return Object.values(r);
10145
+ }, fetchSchemaJson$4 = async (e) => {
10146
+ let { connectionString: t, schemas: n } = parseConnectionString$1(e, "jdbc"), r = await getValidatedClient(t);
10147
+ try {
10148
+ let e = generateTablesAndFields$1(r, n), t = generateIndexesAndConstraints(r, n), i = generateRawRefs(r, n), a = generateRawEnums(r, n), o = await Promise.all([
10149
+ e,
10150
+ t,
10151
+ i,
10152
+ a
10153
+ ]), { tables: s, fields: c } = o[0], { indexes: l, tableConstraints: u, checks: d } = o[1];
10154
+ return {
10155
+ tables: s,
10156
+ fields: c,
10157
+ refs: o[2],
10158
+ enums: o[3],
10159
+ indexes: l,
10160
+ tableConstraints: u,
10161
+ checks: d
10315
10162
  };
10316
- n[t] || (n[t] = []), n[t].push(o);
10317
- }), n;
10318
- }
10319
- var getValidatedClient = async (e, t, n) => {
10320
- let r = await getConnection({
10321
- username: e,
10322
- password: t,
10323
- connectionString: n
10163
+ } finally {
10164
+ await r.end();
10165
+ }
10166
+ }, parseConnectionString = (e) => {
10167
+ let t = {}, n = /([^;=]+)=([^;]*)/g, r;
10168
+ for (; (r = n.exec(e)) !== null;) t[r[1].trim()] = r[2].trim();
10169
+ return t;
10170
+ }, connect = async (e) => new Promise((t, n) => {
10171
+ console.log("Attempting to connect..."), e.connect((e) => {
10172
+ e ? n(e) : t();
10324
10173
  });
10325
- try {
10326
- return await r.execute("SELECT 1 FROM DUAL"), r;
10327
- } catch (e) {
10328
- throw await r.close(), e instanceof Error ? Error(`OracleSQL connection error: ${e.message}`) : e;
10174
+ }), executeQuery = (e, t) => new Promise((n, r) => {
10175
+ console.log("Executing query..."), e.execute({
10176
+ sqlText: t,
10177
+ complete: (e, t, i) => {
10178
+ e ? r(e) : (console.log("Query executed successfully."), i && n(i));
10179
+ }
10180
+ });
10181
+ }), isLogLevel = (e) => [
10182
+ "ERROR",
10183
+ "WARN",
10184
+ "INFO",
10185
+ "DEBUG",
10186
+ "TRACE"
10187
+ ].includes(e), connectToSnowflake = async (e) => {
10188
+ let t = isLogLevel(e.LOG_LEVEL) ? e.LOG_LEVEL : "INFO", n = e.IS_DEBUG_MODE === "true";
10189
+ snowflake.configure({
10190
+ logLevel: t,
10191
+ additionalLogToConsole: n
10192
+ });
10193
+ let r = {};
10194
+ switch (e.AUTHENTICATOR) {
10195
+ case "SNOWFLAKE_JWT":
10196
+ r = {
10197
+ privateKeyPath: e.PRIVATE_KEY_PATH,
10198
+ privateKeyPass: e.PASSPHRASE
10199
+ };
10200
+ break;
10201
+ case "SNOWFLAKE":
10202
+ case void 0:
10203
+ r = { password: e.PWD };
10204
+ break;
10205
+ default: throw Error("Unsupported authenticator");
10329
10206
  }
10330
- };
10331
- async function fetchSchemaJson$5(e) {
10332
- let { username: t, password: n, dbidentifier: r } = processEasyConnectString(e), i = await getValidatedClient(t, n, r), a = generateTablesAndFields(i), o = generateConstraints(i), s = generateRawRefs(i), c = generateIndexes(i), l = await Promise.all([
10333
- a,
10334
- o,
10335
- s,
10336
- c
10337
- ]), { tables: u, fields: d } = l[0], { indexes: f, tableConstraints: p, checks: m } = l[1], h = l[2], g = l[3];
10338
- return Object.keys(f).forEach((e) => {
10339
- g[e] ? g[e].push(...f[e]) : g[e] = f[e];
10340
- }), await i.close(), {
10341
- tables: u,
10342
- fields: d,
10343
- refs: h,
10207
+ let i = {
10208
+ authenticator: e.AUTHENTICATOR,
10209
+ account: e.SERVER,
10210
+ username: e.UID,
10211
+ database: e.DATABASE,
10212
+ warehouse: e.WAREHOUSE,
10213
+ sfRetryMaxLoginRetries: 3,
10214
+ timeout: 1e4,
10215
+ ...r
10216
+ }, a = snowflake.createConnection(i);
10217
+ return await connect(a), await executeQuery(a, "SELECT CURRENT_VERSION();"), a;
10218
+ }, convertQueryBoolean = (e) => e === "YES", getFieldType = (e, t, n, r) => t ? `${e}(${t})` : n && r ? `${e}(${n},${r})` : e, getDbdefault = (e, t) => t === "string" ? {
10219
+ type: t,
10220
+ value: e.slice(1, -1)
10221
+ } : {
10222
+ type: t,
10223
+ value: e
10224
+ }, generateField = (e) => {
10225
+ let { COLUMN_NAME: t, DATA_TYPE: n, CHARACTER_MAXIMUM_LENGTH: r, NUMERIC_PRECISION: i, NUMERIC_SCALE: a, IDENTITY_INCREMENT: o, IS_NULLABLE: s, COLUMN_DEFAULT: c, DEFAULT_TYPE: l, COLUMN_COMMENT: u } = e, d = c ? getDbdefault(c, l) : null;
10226
+ return {
10227
+ name: t,
10228
+ type: {
10229
+ type_name: getFieldType(n, r, i, a),
10230
+ schemaName: null
10231
+ },
10232
+ dbdefault: d,
10233
+ not_null: !convertQueryBoolean(s),
10234
+ increment: !!o,
10235
+ note: u ? { value: u } : { value: "" }
10236
+ };
10237
+ }, generateTablesAndFields = async (e, t) => {
10238
+ let n = {}, r = (await executeQuery(e, `
10239
+ SELECT
10240
+ c.table_schema,
10241
+ c.table_name,
10242
+ c.column_name,
10243
+ c.data_type,
10244
+ c.character_maximum_length,
10245
+ c.numeric_precision,
10246
+ c.numeric_scale,
10247
+ c.is_nullable,
10248
+ c.column_default,
10249
+ CASE
10250
+ WHEN c.column_default IS NULL THEN NULL
10251
+ WHEN c.column_default LIKE '''%' THEN 'string'
10252
+ WHEN LOWER(c.column_default) = 'true' OR LOWER(c.column_default) = 'false' THEN 'boolean'
10253
+ WHEN c.column_default REGEXP '^-?[0-9]+(\\.[0-9]+)?$' THEN 'number'
10254
+ ELSE 'expression'
10255
+ END AS default_type,
10256
+ t.comment AS table_comment,
10257
+ c.comment AS column_comment,
10258
+ c.identity_increment
10259
+ FROM
10260
+ information_schema.columns c
10261
+ JOIN information_schema.tables t
10262
+ ON c.table_name = t.table_name
10263
+ AND c.table_schema = t.table_schema
10264
+ WHERE
10265
+ t.table_type = 'BASE TABLE'
10266
+ AND t.table_schema NOT IN ('INFORMATION_SCHEMA')
10267
+ ${t.length > 0 ? `AND c.table_schema IN (${t.map((e) => `'${e}'`).join(",")})` : ""}
10268
+ ORDER BY
10269
+ c.table_schema,
10270
+ t.created,
10271
+ c.ordinal_position;
10272
+ `)).reduce((e, t) => {
10273
+ let { TABLE_SCHEMA: r, TABLE_NAME: i, TABLE_COMMENT: a } = t, o = `${r}.${i}`;
10274
+ e[o] || (e[o] = {
10275
+ name: i,
10276
+ schemaName: r,
10277
+ note: a ? { value: a } : { value: "" }
10278
+ }), n[o] || (n[o] = []);
10279
+ let s = generateField(t);
10280
+ return n[o].push(s), e;
10281
+ }, {});
10282
+ return {
10283
+ tables: Object.values(r),
10284
+ fields: n
10285
+ };
10286
+ }, createConstraintKeysMap = (e, t, n) => e.reduce((e, r) => {
10287
+ let { schema_name: i, table_name: a, column_name: o, constraint_name: s } = r;
10288
+ if (!(!(t.length > 0) || t.includes(i))) return e;
10289
+ let c = `${i}.${a}.${s}`;
10290
+ if (e[c]) {
10291
+ let { columnNames: t } = e[c];
10292
+ return t.push(o), e;
10293
+ }
10294
+ return e[c] = {
10295
+ schemaName: i,
10296
+ tableName: a,
10297
+ constraintName: s,
10298
+ columnNames: [o],
10299
+ type: ""
10300
+ }, e[c][n] = !0, e;
10301
+ }, {}), generateIndexes = async (e, t, n) => {
10302
+ let r = `
10303
+ SHOW PRIMARY KEYS IN DATABASE ${t};
10304
+ `, i = `
10305
+ SHOW UNIQUE KEYS IN DATABASE ${t};
10306
+ `, a = await executeQuery(e, r), o = await executeQuery(e, i), s = createConstraintKeysMap(a, n, "primary"), c = createConstraintKeysMap(o, n, "unique"), { indexes: l, tableConstraints: u } = [Object.values(s), Object.values(c)].flat().reduce((e, t) => {
10307
+ let { schemaName: n, tableName: r, constraintName: i, columnNames: a, type: o, primary: s, unique: c } = t, l = `${n}.${r}`;
10308
+ if (a.length < 2) return e.tableConstraints[l] = { [a[0]]: {
10309
+ pk: s,
10310
+ unique: c,
10311
+ checks: []
10312
+ } }, e;
10313
+ let u = {
10314
+ name: i,
10315
+ type: o,
10316
+ unique: c,
10317
+ pk: s,
10318
+ columns: a.map((e) => ({
10319
+ type: "column",
10320
+ value: e
10321
+ }))
10322
+ };
10323
+ return e.indexes[l] ? e.indexes[l].push(u) : e.indexes[l] = [u], e;
10324
+ }, {
10325
+ indexes: {},
10326
+ tableConstraints: {}
10327
+ });
10328
+ return {
10329
+ indexes: l,
10330
+ tableConstraints: u
10331
+ };
10332
+ }, fetchSchemaJson$5 = async (e) => {
10333
+ let t = parseConnectionString(e), n = await connectToSnowflake(t);
10334
+ if (n instanceof Error) throw n;
10335
+ let r = t.SCHEMAS ? parseSchema(t.SCHEMAS) : [], i = t.DATABASE, a = generateTablesAndFields(n, r), o = generateIndexes(n, i, r), s = await Promise.all([a, o]);
10336
+ n.destroy((e) => {
10337
+ if (e) throw e;
10338
+ console.log("Connection destroyed successfully.");
10339
+ });
10340
+ let { tables: c, fields: l } = s[0], { indexes: u, tableConstraints: d } = s[1];
10341
+ return {
10342
+ tables: c,
10343
+ fields: l,
10344
+ refs: [],
10344
10345
  enums: [],
10345
- indexes: g,
10346
- tableConstraints: p,
10347
- checks: m
10346
+ indexes: u,
10347
+ tableConstraints: d,
10348
+ checks: {}
10348
10349
  };
10349
- }
10350
- var connector_exports = /* @__PURE__ */ __export({ fetchSchemaJson: () => fetchSchemaJson$6 }, 1), fetchSchemaJson$6 = async (e, t) => {
10350
+ }, connector_exports = /* @__PURE__ */ __export({ fetchSchemaJson: () => fetchSchemaJson$6 }, 1), fetchSchemaJson$6 = async (e, t) => {
10351
10351
  switch (t) {
10352
- case "postgres": return fetchSchemaJson(e);
10352
+ case "postgres": return fetchSchemaJson$4(e);
10353
10353
  case "mssql": return fetchSchemaJson$1(e);
10354
10354
  case "mysql": return fetchSchemaJson$2(e);
10355
- case "snowflake": return fetchSchemaJson$3(e);
10356
- case "bigquery": return fetchSchemaJson$4(e);
10357
- case "oracle": return fetchSchemaJson$5(e);
10355
+ case "snowflake": return fetchSchemaJson$5(e);
10356
+ case "bigquery": return fetchSchemaJson(e);
10357
+ case "oracle": return fetchSchemaJson$3(e);
10358
10358
  default: throw Error(`Unsupported database type: ${t}`);
10359
10359
  }
10360
10360
  };