drizzle-kit 0.20.8 → 0.20.9

Sign up to get free protection for your applications and to get access to all the features.
package/utils-studio.js CHANGED
@@ -1098,1014 +1098,868 @@ var init_outputs = __esm({
1098
1098
  }
1099
1099
  });
1100
1100
 
1101
- // src/serializer/pgSerializer.ts
1102
- var import_pg_core, import_pg_core2, import_drizzle_orm, dialect, trimChar, fromDatabase, columnToDefault, defaultForColumn, toDrizzle;
1103
- var init_pgSerializer = __esm({
1104
- "src/serializer/pgSerializer.ts"() {
1105
- import_pg_core = require("drizzle-orm/pg-core");
1106
- import_pg_core2 = require("drizzle-orm/pg-core");
1101
+ // src/serializer/sqliteSerializer.ts
1102
+ function mapSqlToSqliteType(sqlType) {
1103
+ if ([
1104
+ "int",
1105
+ "integer",
1106
+ "integer auto_increment",
1107
+ "tinyint",
1108
+ "smallint",
1109
+ "mediumint",
1110
+ "bigint",
1111
+ "unsigned big int",
1112
+ "int2",
1113
+ "int8"
1114
+ ].includes(sqlType.toLowerCase())) {
1115
+ return "integer";
1116
+ } else if ([
1117
+ "character",
1118
+ "varchar",
1119
+ "vatying character",
1120
+ "nchar",
1121
+ "native character",
1122
+ "nvarchar",
1123
+ "text",
1124
+ "clob"
1125
+ ].some((it) => it.startsWith(sqlType.toLowerCase()))) {
1126
+ return "text";
1127
+ } else if (sqlType.toLowerCase() === "blob") {
1128
+ return "blob";
1129
+ } else if (["real", "double", "double precision", "float"].includes(
1130
+ sqlType.toLowerCase()
1131
+ )) {
1132
+ return "real";
1133
+ } else {
1134
+ return "numeric";
1135
+ }
1136
+ }
1137
+ var import_drizzle_orm, import_sqlite_core2, dialect, fromDatabase;
1138
+ var init_sqliteSerializer = __esm({
1139
+ "src/serializer/sqliteSerializer.ts"() {
1107
1140
  import_drizzle_orm = require("drizzle-orm");
1141
+ import_sqlite_core2 = require("drizzle-orm/sqlite-core");
1108
1142
  init_serializer();
1109
- init_source();
1110
1143
  init_outputs();
1111
- dialect = new import_pg_core.PgDialect();
1112
- trimChar = (str, char) => {
1113
- let start = 0;
1114
- let end = str.length;
1115
- while (start < end && str[start] === char)
1116
- ++start;
1117
- while (end > start && str[end - 1] === char)
1118
- --end;
1119
- return start > 0 || end < str.length ? str.substring(start, end) : str.toString();
1120
- };
1121
- fromDatabase = async (db, tablesFilter = (table) => true, schemaFilters, progressCallback) => {
1144
+ init_source();
1145
+ dialect = new import_sqlite_core2.SQLiteSyncDialect();
1146
+ fromDatabase = async (db, tablesFilter = (table) => true, progressCallback) => {
1122
1147
  const result = {};
1123
- const internals = { tables: {} };
1124
- const where = schemaFilters.map((t) => `table_schema = '${t}'`).join(" or ");
1125
- const allTables = await db.query(
1126
- `SELECT table_schema, table_name FROM information_schema.tables WHERE ${where};`
1148
+ const columns = await db.query(
1149
+ `SELECT
1150
+ m.name as "tableName", p.name as "columnName", p.type as "columnType", p."notnull" as "notNull", p.dflt_value as "defaultValue", p.pk as pk
1151
+ FROM sqlite_master AS m JOIN pragma_table_info(m.name) AS p
1152
+ WHERE m.type = 'table' and m.tbl_name != 'sqlite_sequence' and m.tbl_name != 'sqlite_stat1' and m.tbl_name != '_litestream_seq' and m.tbl_name != '_litestream_lock' and m.tbl_name != 'libsql_wasm_func_table';
1153
+ `
1127
1154
  );
1128
- const schemas = new Set(allTables.map((it) => it.table_schema));
1129
- schemas.delete("public");
1130
- const allSchemas = await db.query(`select s.nspname as table_schema
1131
- from pg_catalog.pg_namespace s
1132
- join pg_catalog.pg_user u on u.usesysid = s.nspowner
1133
- where nspname not in ('information_schema', 'pg_catalog', 'public')
1134
- and nspname not like 'pg_toast%'
1135
- and nspname not like 'pg_temp_%'
1136
- order by table_schema;`);
1137
- allSchemas.forEach((item) => {
1138
- if (schemaFilters.includes(item.table_schema)) {
1139
- schemas.add(item.table_schema);
1140
- }
1141
- });
1155
+ const tablesWithSeq = [];
1156
+ const seq = await db.query(
1157
+ `SELECT * FROM sqlite_master WHERE name != 'sqlite_sequence' and name != 'sqlite_stat1' and name != '_litestream_seq' and name != '_litestream_lock' and sql GLOB '*[ *' || CHAR(9) || CHAR(10) || CHAR(13) || ']AUTOINCREMENT[^'']*';`
1158
+ );
1159
+ for (const s of seq) {
1160
+ tablesWithSeq.push(s.name);
1161
+ }
1142
1162
  let columnsCount = 0;
1163
+ let tablesCount = /* @__PURE__ */ new Set();
1143
1164
  let indexesCount = 0;
1144
1165
  let foreignKeysCount = 0;
1145
- let tableCount = 0;
1146
- const all = allTables.map((row) => {
1147
- return new Promise(async (res, rej) => {
1148
- const tableName = row.table_name;
1149
- if (!tablesFilter(tableName))
1150
- return res("");
1151
- tableCount += 1;
1152
- const tableSchema = row.table_schema;
1153
- try {
1154
- const columnToReturn = {};
1155
- const indexToReturn = {};
1156
- const foreignKeysToReturn = {};
1157
- const primaryKeys = {};
1158
- const uniqueConstrains = {};
1159
- const tableResponse = await db.query(
1160
- `SELECT a.attrelid::regclass::text, a.attname, is_nullable, a.attndims as array_dimensions
1161
- , CASE WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[])
1162
- AND EXISTS (
1163
- SELECT FROM pg_attrdef ad
1164
- WHERE ad.adrelid = a.attrelid
1165
- AND ad.adnum = a.attnum
1166
- AND pg_get_expr(ad.adbin, ad.adrelid)
1167
- = 'nextval('''
1168
- || (pg_get_serial_sequence (a.attrelid::regclass::text
1169
- , a.attname))::regclass
1170
- || '''::regclass)'
1171
- )
1172
- THEN CASE a.atttypid
1173
- WHEN 'int'::regtype THEN 'serial'
1174
- WHEN 'int8'::regtype THEN 'bigserial'
1175
- WHEN 'int2'::regtype THEN 'smallserial'
1176
- END
1177
- ELSE format_type(a.atttypid, a.atttypmod)
1178
- END AS data_type, INFORMATION_SCHEMA.COLUMNS.table_name, INFORMATION_SCHEMA.COLUMNS.column_name, INFORMATION_SCHEMA.COLUMNS.column_default, INFORMATION_SCHEMA.COLUMNS.data_type as additional_dt
1179
- FROM pg_attribute a
1180
- JOIN INFORMATION_SCHEMA.COLUMNS ON INFORMATION_SCHEMA.COLUMNS.column_name = a.attname
1181
- WHERE a.attrelid = '"${tableSchema}"."${tableName}"'::regclass and INFORMATION_SCHEMA.COLUMNS.table_name = '${tableName}'
1182
- AND a.attnum > 0
1183
- AND NOT a.attisdropped
1184
- ORDER BY a.attnum;`
1185
- );
1186
- const tableConstraints = await db.query(
1187
- `SELECT c.column_name, c.data_type, constraint_type, constraint_name, constraint_schema
1188
- FROM information_schema.table_constraints tc
1189
- JOIN information_schema.constraint_column_usage AS ccu USING (constraint_schema, constraint_name)
1190
- JOIN information_schema.columns AS c ON c.table_schema = tc.constraint_schema
1191
- AND tc.table_name = c.table_name AND ccu.column_name = c.column_name
1192
- WHERE tc.table_name = '${tableName}' and constraint_schema = '${tableSchema}';`
1193
- );
1194
- columnsCount += tableResponse.length;
1195
- if (progressCallback) {
1196
- progressCallback("columns", columnsCount, "fetching");
1197
- }
1198
- const tableForeignKeys = await db.query(
1199
- `SELECT
1200
- tc.table_schema,
1201
- tc.constraint_name,
1202
- tc.table_name,
1203
- kcu.column_name,
1204
- ccu.table_schema AS foreign_table_schema,
1205
- ccu.table_name AS foreign_table_name,
1206
- ccu.column_name AS foreign_column_name,
1207
- rc.delete_rule, rc.update_rule
1208
- FROM
1209
- information_schema.table_constraints AS tc
1210
- JOIN information_schema.key_column_usage AS kcu
1211
- ON tc.constraint_name = kcu.constraint_name
1212
- AND tc.table_schema = kcu.table_schema
1213
- JOIN information_schema.constraint_column_usage AS ccu
1214
- ON ccu.constraint_name = tc.constraint_name
1215
- AND ccu.table_schema = tc.table_schema
1216
- JOIN information_schema.referential_constraints AS rc
1217
- ON ccu.constraint_name = rc.constraint_name
1218
- WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='${tableName}' and tc.table_schema='${tableSchema}';`
1219
- );
1220
- foreignKeysCount += tableForeignKeys.length;
1221
- if (progressCallback) {
1222
- progressCallback("fks", foreignKeysCount, "fetching");
1223
- }
1224
- for (const fk of tableForeignKeys) {
1225
- const columnFrom = fk.column_name;
1226
- const tableTo = fk.foreign_table_name;
1227
- const columnTo = fk.foreign_column_name;
1228
- const foreignKeyName = fk.constraint_name;
1229
- const onUpdate = fk.update_rule.toLowerCase();
1230
- const onDelete = fk.delete_rule.toLowerCase();
1231
- if (typeof foreignKeysToReturn[foreignKeyName] !== "undefined") {
1232
- foreignKeysToReturn[foreignKeyName].columnsFrom.push(columnFrom);
1233
- foreignKeysToReturn[foreignKeyName].columnsTo.push(columnTo);
1234
- } else {
1235
- foreignKeysToReturn[foreignKeyName] = {
1236
- name: foreignKeyName,
1237
- tableFrom: tableName,
1238
- tableTo,
1239
- columnsFrom: [columnFrom],
1240
- columnsTo: [columnTo],
1241
- onDelete,
1242
- onUpdate
1243
- };
1244
- }
1245
- foreignKeysToReturn[foreignKeyName].columnsFrom = [
1246
- ...new Set(foreignKeysToReturn[foreignKeyName].columnsFrom)
1247
- ];
1248
- foreignKeysToReturn[foreignKeyName].columnsTo = [
1249
- ...new Set(foreignKeysToReturn[foreignKeyName].columnsTo)
1250
- ];
1166
+ const tableToPk = {};
1167
+ for (const column of columns) {
1168
+ if (!tablesFilter(column.tableName))
1169
+ continue;
1170
+ columnsCount += 1;
1171
+ if (progressCallback) {
1172
+ progressCallback("columns", columnsCount, "fetching");
1173
+ }
1174
+ const tableName = column.tableName;
1175
+ tablesCount.add(tableName);
1176
+ if (progressCallback) {
1177
+ progressCallback("tables", tablesCount.size, "fetching");
1178
+ }
1179
+ const columnName = column.columnName;
1180
+ const isNotNull = column.notNull === 1;
1181
+ const columnType = column.columnType;
1182
+ const isPrimary = column.pk !== 0;
1183
+ const columnDefault = column.defaultValue;
1184
+ const isAutoincrement = isPrimary && tablesWithSeq.includes(tableName);
1185
+ if (isPrimary) {
1186
+ if (typeof tableToPk[tableName] === "undefined") {
1187
+ tableToPk[tableName] = [columnName];
1188
+ } else {
1189
+ tableToPk[tableName].push(columnName);
1190
+ }
1191
+ }
1192
+ const table = result[tableName];
1193
+ const newColumn = {
1194
+ default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) ? Number(columnDefault) : ["CURRENT_TIME", "CURRENT_DATE", "CURRENT_TIMESTAMP"].includes(
1195
+ columnDefault
1196
+ ) ? `(${columnDefault})` : columnDefault === "false" ? false : columnDefault === "true" ? true : columnDefault.startsWith("'") && columnDefault.endsWith("'") ? columnDefault : (
1197
+ // ? columnDefault.substring(1, columnDefault.length - 1)
1198
+ `(${columnDefault})`
1199
+ ),
1200
+ autoincrement: isAutoincrement,
1201
+ name: columnName,
1202
+ type: mapSqlToSqliteType(columnType),
1203
+ primaryKey: false,
1204
+ notNull: isNotNull
1205
+ };
1206
+ if (!table) {
1207
+ result[tableName] = {
1208
+ name: tableName,
1209
+ columns: {
1210
+ [columnName]: newColumn
1211
+ },
1212
+ compositePrimaryKeys: {},
1213
+ indexes: {},
1214
+ foreignKeys: {},
1215
+ uniqueConstraints: {}
1216
+ };
1217
+ } else {
1218
+ result[tableName].columns[columnName] = newColumn;
1219
+ }
1220
+ }
1221
+ for (const [key, value] of Object.entries(tableToPk)) {
1222
+ if (value.length > 1) {
1223
+ value.sort();
1224
+ result[key].compositePrimaryKeys = {
1225
+ [`${key}_${value.join("_")}_pk`]: {
1226
+ columns: value,
1227
+ name: `${key}_${value.join("_")}_pk`
1251
1228
  }
1252
- const uniqueConstrainsRows = tableConstraints.filter(
1253
- (mapRow) => mapRow.constraint_type === "UNIQUE"
1254
- );
1255
- for (const unqs of uniqueConstrainsRows) {
1256
- const columnName = unqs.column_name;
1257
- const constraintName = unqs.constraint_name;
1258
- if (typeof uniqueConstrains[constraintName] !== "undefined") {
1259
- uniqueConstrains[constraintName].columns.push(columnName);
1260
- } else {
1261
- uniqueConstrains[constraintName] = {
1262
- columns: [columnName],
1263
- nullsNotDistinct: false,
1264
- name: constraintName
1265
- };
1266
- }
1267
- }
1268
- for (const columnResponse of tableResponse) {
1269
- const columnName = columnResponse.attname;
1270
- const columnAdditionalDT = columnResponse.additional_dt;
1271
- const columnDimensions = columnResponse.array_dimensions;
1272
- let columnType = columnResponse.data_type;
1273
- const primaryKey = tableConstraints.filter(
1274
- (mapRow) => columnName === mapRow.column_name && mapRow.constraint_type === "PRIMARY KEY"
1275
- );
1276
- const cprimaryKey = tableConstraints.filter(
1277
- (mapRow) => mapRow.constraint_type === "PRIMARY KEY"
1278
- );
1279
- if (cprimaryKey.length > 1) {
1280
- const tableCompositePkName = await db.query(
1281
- `SELECT conname AS primary_key
1282
- FROM pg_constraint join pg_class on (pg_class.oid = conrelid)
1283
- WHERE contype = 'p'
1284
- AND connamespace = $1::regnamespace
1285
- AND pg_class.relname = $2;`,
1286
- [tableSchema, tableName]
1287
- );
1288
- primaryKeys[tableCompositePkName[0].primary_key] = {
1289
- name: tableCompositePkName[0].primary_key,
1290
- columns: cprimaryKey.map((c) => c.column_name)
1291
- };
1292
- }
1293
- const defaultValue = defaultForColumn(columnResponse);
1294
- const isSerial = columnType === "serial";
1295
- let columnTypeMapped = columnType;
1296
- if (columnTypeMapped.startsWith("numeric(")) {
1297
- columnTypeMapped = columnTypeMapped.replace(",", ", ");
1298
- }
1299
- if (columnAdditionalDT === "ARRAY") {
1300
- if (typeof internals.tables[tableName] === "undefined") {
1301
- internals.tables[tableName] = {
1302
- columns: {
1303
- [columnName]: {
1304
- isArray: true,
1305
- dimensions: columnDimensions,
1306
- rawType: columnTypeMapped.substring(
1307
- 0,
1308
- columnTypeMapped.length - 2
1309
- )
1310
- }
1311
- }
1312
- };
1313
- } else {
1314
- if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
1315
- internals.tables[tableName].columns[columnName] = {
1316
- isArray: true,
1317
- dimensions: columnDimensions,
1318
- rawType: columnTypeMapped.substring(
1319
- 0,
1320
- columnTypeMapped.length - 2
1321
- )
1322
- };
1323
- }
1324
- }
1325
- }
1326
- if (columnAdditionalDT === "ARRAY") {
1327
- for (let i = 1; i < Number(columnDimensions); i++) {
1328
- columnTypeMapped += "[]";
1329
- }
1330
- }
1331
- columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
1332
- columnTypeMapped = trimChar(columnTypeMapped, '"');
1333
- columnToReturn[columnName] = {
1334
- name: columnName,
1335
- type: columnTypeMapped,
1336
- primaryKey: primaryKey.length === 1 && cprimaryKey.length < 2,
1337
- // default: isSerial ? undefined : defaultValue,
1338
- notNull: columnResponse.is_nullable === "NO"
1339
- };
1340
- if (!isSerial && typeof defaultValue !== "undefined") {
1341
- columnToReturn[columnName].default = defaultValue;
1342
- }
1343
- }
1344
- const dbIndexes = await db.query(
1345
- `SELECT t.relname as table_name, i.relname AS index_name, ix.indisunique AS is_unique, a.attname AS column_name
1346
- FROM pg_class t
1347
- JOIN pg_index ix ON t.oid = ix.indrelid
1348
- JOIN pg_class i ON i.oid = ix.indexrelid
1349
- JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
1350
- JOIN pg_namespace ns ON ns.oid = t.relnamespace
1351
- WHERE ns.nspname = '${tableSchema}'
1352
- AND t.relname = '${tableName}'
1353
- and ix.indisprimary = false;`
1354
- );
1355
- const dbIndexFromConstraint = await db.query(
1356
- `SELECT
1357
- idx.indexrelname AS index_name,
1358
- idx.relname AS table_name,
1359
- schemaname,
1360
- CASE WHEN con.conname IS NOT NULL THEN 1 ELSE 0 END AS generated_by_constraint
1361
- FROM
1362
- pg_stat_user_indexes idx
1363
- LEFT JOIN
1364
- pg_constraint con ON con.conindid = idx.indexrelid
1365
- WHERE idx.relname = '${tableName}' and schemaname = '${tableSchema}'
1366
- group by index_name, table_name,schemaname, generated_by_constraint;`
1367
- );
1368
- const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map((it) => it.index_name);
1369
- for (const dbIndex of dbIndexes) {
1370
- const indexName2 = dbIndex.index_name;
1371
- const indexColumnName = dbIndex.column_name;
1372
- const indexIsUnique = dbIndex.is_unique;
1373
- if (idxsInConsteraint.includes(indexName2))
1374
- continue;
1375
- if (typeof indexToReturn[indexName2] !== "undefined") {
1376
- indexToReturn[indexName2].columns.push(indexColumnName);
1377
- } else {
1378
- indexToReturn[indexName2] = {
1379
- name: indexName2,
1380
- columns: [indexColumnName],
1381
- isUnique: indexIsUnique
1382
- };
1383
- }
1384
- }
1385
- indexesCount += Object.keys(indexToReturn).length;
1386
- if (progressCallback) {
1387
- progressCallback("indexes", indexesCount, "fetching");
1388
- }
1389
- result[tableName] = {
1390
- name: tableName,
1391
- schema: tableSchema !== "public" ? tableSchema : "",
1392
- columns: columnToReturn,
1393
- indexes: indexToReturn,
1394
- foreignKeys: foreignKeysToReturn,
1395
- compositePrimaryKeys: primaryKeys,
1396
- uniqueConstraints: uniqueConstrains
1397
- };
1398
- } catch (e) {
1399
- rej(e);
1400
- return;
1401
- }
1402
- res("");
1403
- });
1404
- });
1229
+ };
1230
+ } else if (value.length === 1) {
1231
+ result[key].columns[value[0]].primaryKey = true;
1232
+ } else {
1233
+ }
1234
+ }
1405
1235
  if (progressCallback) {
1406
- progressCallback("tables", tableCount, "done");
1236
+ progressCallback("columns", columnsCount, "done");
1237
+ progressCallback("tables", tablesCount.size, "done");
1407
1238
  }
1408
- for await (const _ of all) {
1239
+ try {
1240
+ const fks = await db.query(
1241
+ `SELECT m.name as "tableFrom", f.id as "id", f."table" as "tableTo", f."from", f."to", f."on_update" as "onUpdate", f."on_delete" as "onDelete", f.seq as "seq"
1242
+ FROM sqlite_master m, pragma_foreign_key_list(m.name) as f;`
1243
+ );
1244
+ const fkByTableName = {};
1245
+ for (const fkRow of fks) {
1246
+ foreignKeysCount += 1;
1247
+ if (progressCallback) {
1248
+ progressCallback("fks", foreignKeysCount, "fetching");
1249
+ }
1250
+ const tableName = fkRow.tableFrom;
1251
+ const columnName = fkRow.from;
1252
+ const refTableName = fkRow.tableTo;
1253
+ const refColumnName = fkRow.to;
1254
+ const updateRule = fkRow.onUpdate;
1255
+ const deleteRule = fkRow.onDelete;
1256
+ const sequence = fkRow.seq;
1257
+ const id = fkRow.id;
1258
+ const tableInResult = result[tableName];
1259
+ if (typeof tableInResult === "undefined")
1260
+ continue;
1261
+ if (typeof fkByTableName[`${tableName}_${id}`] !== "undefined") {
1262
+ fkByTableName[`${tableName}_${id}`].columnsFrom.push(columnName);
1263
+ fkByTableName[`${tableName}_${id}`].columnsTo.push(refColumnName);
1264
+ } else {
1265
+ fkByTableName[`${tableName}_${id}`] = {
1266
+ name: "",
1267
+ tableFrom: tableName,
1268
+ tableTo: refTableName,
1269
+ columnsFrom: [columnName],
1270
+ columnsTo: [refColumnName],
1271
+ onDelete: deleteRule == null ? void 0 : deleteRule.toLowerCase(),
1272
+ onUpdate: updateRule == null ? void 0 : updateRule.toLowerCase()
1273
+ };
1274
+ }
1275
+ const columnsFrom = fkByTableName[`${tableName}_${id}`].columnsFrom;
1276
+ const columnsTo = fkByTableName[`${tableName}_${id}`].columnsTo;
1277
+ fkByTableName[`${tableName}_${id}`].name = `${tableName}_${columnsFrom.join(
1278
+ "_"
1279
+ )}_${refTableName}_${columnsTo.join("_")}_fk`;
1280
+ }
1281
+ for (const idx of Object.keys(fkByTableName)) {
1282
+ const value = fkByTableName[idx];
1283
+ result[value.tableFrom].foreignKeys[value.name] = value;
1284
+ }
1285
+ } catch (e) {
1409
1286
  }
1410
1287
  if (progressCallback) {
1411
- progressCallback("columns", columnsCount, "done");
1412
- progressCallback("indexes", indexesCount, "done");
1413
1288
  progressCallback("fks", foreignKeysCount, "done");
1414
1289
  }
1415
- const allEnums = await db.query(
1416
- `select n.nspname as enum_schema,
1417
- t.typname as enum_name,
1418
- e.enumlabel as enum_value
1419
- from pg_type t
1420
- join pg_enum e on t.oid = e.enumtypid
1421
- join pg_catalog.pg_namespace n ON n.oid = t.typnamespace;`
1290
+ const idxs = await db.query(
1291
+ `SELECT
1292
+ m.tbl_name as tableName,
1293
+ il.name as indexName,
1294
+ ii.name as columnName,
1295
+ il.[unique] as isUnique,
1296
+ il.seq as seq
1297
+ FROM sqlite_master AS m,
1298
+ pragma_index_list(m.name) AS il,
1299
+ pragma_index_info(il.name) AS ii
1300
+ WHERE
1301
+ m.type = 'table' and il.name NOT LIKE 'sqlite_autoindex_%';`
1422
1302
  );
1423
- const enumsToReturn = {};
1424
- for (const dbEnum of allEnums) {
1425
- const enumName = dbEnum.enum_name;
1426
- const enumValue = dbEnum.enum_value;
1427
- if (enumsToReturn[enumName] !== void 0 && enumsToReturn[enumName] !== null) {
1428
- enumsToReturn[enumName].values[enumValue] = enumValue;
1303
+ for (const idxRow of idxs) {
1304
+ const tableName = idxRow.tableName;
1305
+ const constraintName = idxRow.indexName;
1306
+ const columnName = idxRow.columnName;
1307
+ const isUnique = idxRow.isUnique === 1;
1308
+ const tableInResult = result[tableName];
1309
+ if (typeof tableInResult === "undefined")
1310
+ continue;
1311
+ indexesCount += 1;
1312
+ if (progressCallback) {
1313
+ progressCallback("indexes", indexesCount, "fetching");
1314
+ }
1315
+ if (typeof tableInResult.indexes[constraintName] !== "undefined") {
1316
+ tableInResult.indexes[constraintName].columns.push(columnName);
1429
1317
  } else {
1430
- enumsToReturn[enumName] = {
1431
- name: enumName,
1432
- values: { [enumValue]: enumValue }
1318
+ tableInResult.indexes[constraintName] = {
1319
+ name: constraintName,
1320
+ columns: [columnName],
1321
+ isUnique
1433
1322
  };
1434
1323
  }
1435
1324
  }
1436
1325
  if (progressCallback) {
1437
- progressCallback("enums", Object.keys(enumsToReturn).length, "done");
1326
+ progressCallback("indexes", indexesCount, "done");
1327
+ progressCallback("enums", 0, "done");
1438
1328
  }
1439
- const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it]));
1440
1329
  return {
1441
1330
  version: "5",
1442
- dialect: "pg",
1331
+ dialect: "sqlite",
1443
1332
  tables: result,
1444
- enums: enumsToReturn,
1445
- schemas: schemasObject,
1333
+ enums: {},
1446
1334
  _meta: {
1447
- schemas: {},
1448
1335
  tables: {},
1449
1336
  columns: {}
1450
- },
1451
- internal: internals
1452
- };
1453
- };
1454
- columnToDefault = {
1455
- "numeric(": "::numeric",
1456
- // text: "::text",
1457
- // "character varying": "::character varying",
1458
- // "double precision": "::double precision",
1459
- // "time with time zone": "::time with time zone",
1460
- "time without time zone": "::time without time zone",
1461
- // "timestamp with time zone": "::timestamp with time zone",
1462
- "timestamp without time zone": "::timestamp without time zone",
1463
- // date: "::date",
1464
- // interval: "::interval",
1465
- // character: "::bpchar",
1466
- // macaddr8: "::macaddr8",
1467
- // macaddr: "::macaddr",
1468
- // inet: "::inet",
1469
- // cidr: "::cidr",
1470
- // jsonb: "::jsonb",
1471
- // json: "::json",
1472
- "character(": "::bpchar"
1473
- };
1474
- defaultForColumn = (column) => {
1475
- if (column.data_type === "serial" || column.data_type === "smallserial" || column.data_type === "bigserial") {
1476
- return void 0;
1477
- }
1478
- const hasDifferentDefaultCast = Object.keys(columnToDefault).find(
1479
- (it) => column.data_type.startsWith(it)
1480
- );
1481
- if (column.column_default === null) {
1482
- return void 0;
1483
- }
1484
- const columnDefaultAsString = column.column_default.toString();
1485
- if (columnDefaultAsString.endsWith(
1486
- hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : column.data_type
1487
- )) {
1488
- const nonPrefixPart = column.column_default.length - (hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : `::${column.data_type}`).length - 1;
1489
- const rt = column.column_default.toString().substring(1, nonPrefixPart);
1490
- if (/^-?[\d.]+(?:e-?\d+)?$/.test(rt) && !column.data_type.startsWith("numeric")) {
1491
- return Number(rt);
1492
- } else if (column.data_type === "json" || column.data_type === "jsonb") {
1493
- const jsonWithoutSpaces = JSON.stringify(JSON.parse(rt));
1494
- return `'${jsonWithoutSpaces}'${hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : `::${column.data_type}`}`;
1495
- } else if (column.data_type === "boolean") {
1496
- return column.column_default === "true";
1497
- } else {
1498
- return `'${rt}'`;
1499
- }
1500
- } else {
1501
- if (/^-?[\d.]+(?:e-?\d+)?$/.test(columnDefaultAsString) && !column.data_type.startsWith("numeric")) {
1502
- return Number(columnDefaultAsString);
1503
- } else if (column.data_type === "boolean") {
1504
- return column.column_default === "true";
1505
- } else {
1506
- return `${columnDefaultAsString}`;
1507
- }
1508
- }
1509
- };
1510
- toDrizzle = (schema, schemaName) => {
1511
- const tables = {};
1512
- Object.values(schema.tables).forEach((t) => {
1513
- const columns = {};
1514
- Object.values(t.columns).forEach((c) => {
1515
- const columnName = c.name;
1516
- const type = c.type;
1517
- let columnBuilder;
1518
- if (type === "bigint") {
1519
- columnBuilder = new import_pg_core.PgBigInt53Builder(columnName);
1520
- } else if (type === "bigserial") {
1521
- columnBuilder = new import_pg_core.PgBigSerial53Builder(columnName);
1522
- } else if (type === "boolean") {
1523
- columnBuilder = new import_pg_core.PgBooleanBuilder(columnName);
1524
- } else if (type === "cidr") {
1525
- columnBuilder = new import_pg_core.PgCidrBuilder(columnName);
1526
- } else if (type === "date") {
1527
- columnBuilder = new import_pg_core.PgDateBuilder(columnName);
1528
- } else if (type === "double precision") {
1529
- columnBuilder = new import_pg_core.PgDoublePrecisionBuilder(columnName);
1530
- } else if (type === "inet") {
1531
- columnBuilder = new import_pg_core.PgInetBuilder(columnName);
1532
- } else if (type === "integer") {
1533
- columnBuilder = new import_pg_core.PgIntegerBuilder(columnName);
1534
- } else if (type === "interval" || type.startsWith("interval ")) {
1535
- columnBuilder = new import_pg_core.PgIntervalBuilder(columnName, {});
1536
- } else if (type === "json") {
1537
- columnBuilder = new import_pg_core.PgJsonBuilder(columnName);
1538
- } else if (type === "jsonb") {
1539
- columnBuilder = new import_pg_core.PgJsonbBuilder(columnName);
1540
- } else if (type === "macaddr") {
1541
- columnBuilder = new import_pg_core.PgMacaddrBuilder(columnName);
1542
- } else if (type === "macaddr8") {
1543
- columnBuilder = new import_pg_core.PgMacaddr8Builder(columnName);
1544
- } else if (type === "numeric" || type.startsWith("numeric(")) {
1545
- columnBuilder = new import_pg_core.PgNumericBuilder(columnName);
1546
- } else if (type === "real") {
1547
- columnBuilder = new import_pg_core.PgRealBuilder(columnName);
1548
- } else if (type === "serial") {
1549
- columnBuilder = new import_pg_core.PgSerialBuilder(columnName);
1550
- } else if (type === "smallint") {
1551
- columnBuilder = new import_pg_core.PgSmallIntBuilder(columnName);
1552
- } else if (type === "smallserial") {
1553
- columnBuilder = new import_pg_core.PgSmallSerialBuilder(columnName);
1554
- } else if (type === "text") {
1555
- columnBuilder = new import_pg_core.PgTextBuilder(columnName, {});
1556
- } else if (type === "time" || type.startsWith("time(") || type === "time with time zone") {
1557
- columnBuilder = new import_pg_core.PgTimeBuilder(columnName, false, void 0);
1558
- } else if (type === "timestamp" || type.startsWith("timestamp(") || type === "timestamp with time zone") {
1559
- columnBuilder = new import_pg_core.PgTimestampBuilder(columnName, false, void 0);
1560
- } else if (type === "uuid") {
1561
- columnBuilder = new import_pg_core.PgUUIDBuilder(columnName);
1562
- } else if (type === "varchar" || type.startsWith("varchar(")) {
1563
- columnBuilder = new import_pg_core.PgVarcharBuilder(columnName, {});
1564
- } else if (type === "char" || type.startsWith("char(")) {
1565
- columnBuilder = new import_pg_core.PgCharBuilder(columnName, {});
1566
- } else {
1567
- columnBuilder = (0, import_pg_core.customType)({
1568
- dataType() {
1569
- return type;
1570
- }
1571
- })(columnName);
1572
- }
1573
- if (c.notNull) {
1574
- columnBuilder = columnBuilder.notNull();
1575
- }
1576
- if (c.default) {
1577
- columnBuilder = columnBuilder.default(c.default);
1578
- }
1579
- if (c.primaryKey) {
1580
- columnBuilder = columnBuilder.primaryKey();
1581
- }
1582
- columns[columnName] = columnBuilder;
1583
- });
1584
- if (schemaName === "public") {
1585
- tables[t.name] = (0, import_pg_core.pgTable)(t.name, columns, (cb) => {
1586
- const res = {};
1587
- Object.values(t.compositePrimaryKeys).forEach((cpk) => {
1588
- const gh = cpk.columns.map((c) => cb[c]);
1589
- res[cpk.name] = new import_pg_core.PrimaryKeyBuilder(
1590
- gh,
1591
- cpk.name
1592
- );
1593
- });
1594
- return res;
1595
- });
1596
- } else {
1597
- tables[t.name] = (0, import_pg_core.pgSchema)(schemaName).table(t.name, columns, (cb) => {
1598
- const res = {};
1599
- Object.values(t.compositePrimaryKeys).forEach((cpk) => {
1600
- const gh = cpk.columns.map((c) => cb[c]);
1601
- res[cpk.name] = new import_pg_core.PrimaryKeyBuilder(
1602
- gh,
1603
- cpk.name
1604
- );
1605
- });
1606
- return res;
1607
- });
1608
1337
  }
1609
- });
1610
- return tables;
1338
+ };
1611
1339
  };
1612
1340
  }
1613
1341
  });
1614
1342
 
1615
- // src/serializer/sqliteSerializer.ts
1616
- function mapSqlToSqliteType(sqlType) {
1617
- if ([
1618
- "int",
1619
- "integer",
1620
- "integer auto_increment",
1621
- "tinyint",
1622
- "smallint",
1623
- "mediumint",
1624
- "bigint",
1625
- "unsigned big int",
1626
- "int2",
1627
- "int8"
1628
- ].includes(sqlType.toLowerCase())) {
1629
- return "integer";
1630
- } else if ([
1631
- "character",
1632
- "varchar",
1633
- "vatying character",
1634
- "nchar",
1635
- "native character",
1636
- "nvarchar",
1637
- "text",
1638
- "clob"
1639
- ].some((it) => it.startsWith(sqlType.toLowerCase()))) {
1640
- return "text";
1641
- } else if (sqlType.toLowerCase() === "blob") {
1642
- return "blob";
1643
- } else if (["real", "double", "double precision", "float"].includes(
1644
- sqlType.toLowerCase()
1645
- )) {
1646
- return "real";
1647
- } else {
1648
- return "numeric";
1649
- }
1650
- }
1651
- var import_drizzle_orm2, import_sqlite_core, dialect2, fromDatabase2, toDrizzle2;
1652
- var init_sqliteSerializer = __esm({
1653
- "src/serializer/sqliteSerializer.ts"() {
1654
- import_drizzle_orm2 = require("drizzle-orm");
1655
- import_sqlite_core = require("drizzle-orm/sqlite-core");
1656
- init_serializer();
1657
- init_outputs();
1658
- init_source();
1659
- dialect2 = new import_sqlite_core.SQLiteSyncDialect();
1660
- fromDatabase2 = async (db, tablesFilter = (table) => true, progressCallback) => {
1661
- const result = {};
1662
- const columns = await db.query(
1663
- `SELECT
1664
- m.name as "tableName", p.name as "columnName", p.type as "columnType", p."notnull" as "notNull", p.dflt_value as "defaultValue", p.pk as pk
1665
- FROM sqlite_master AS m JOIN pragma_table_info(m.name) AS p
1666
- WHERE m.type = 'table' and m.tbl_name != 'sqlite_sequence' and m.tbl_name != 'sqlite_stat1' and m.tbl_name != '_litestream_seq' and m.tbl_name != '_litestream_lock' and m.tbl_name != 'libsql_wasm_func_table';
1667
- `
1668
- );
1669
- const tablesWithSeq = [];
1670
- const seq = await db.query(
1671
- `SELECT * FROM sqlite_master WHERE name != 'sqlite_sequence' and name != 'sqlite_stat1' and name != '_litestream_seq' and name != '_litestream_lock' and sql GLOB '*[ *' || CHAR(9) || CHAR(10) || CHAR(13) || ']AUTOINCREMENT[^'']*';`
1672
- );
1673
- for (const s of seq) {
1674
- tablesWithSeq.push(s.name);
1675
- }
1676
- let columnsCount = 0;
1677
- let tablesCount = /* @__PURE__ */ new Set();
1678
- let indexesCount = 0;
1679
- let foreignKeysCount = 0;
1680
- const tableToPk = {};
1681
- for (const column of columns) {
1682
- if (!tablesFilter(column.tableName))
1683
- continue;
1684
- columnsCount += 1;
1685
- if (progressCallback) {
1686
- progressCallback("columns", columnsCount, "fetching");
1687
- }
1688
- const tableName = column.tableName;
1689
- tablesCount.add(tableName);
1690
- if (progressCallback) {
1691
- progressCallback("tables", tablesCount.size, "fetching");
1343
+ // node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
1344
+ var require_balanced_match = __commonJS({
1345
+ "node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js"(exports, module2) {
1346
+ "use strict";
1347
+ module2.exports = balanced;
1348
+ function balanced(a, b, str) {
1349
+ if (a instanceof RegExp)
1350
+ a = maybeMatch(a, str);
1351
+ if (b instanceof RegExp)
1352
+ b = maybeMatch(b, str);
1353
+ var r = range(a, b, str);
1354
+ return r && {
1355
+ start: r[0],
1356
+ end: r[1],
1357
+ pre: str.slice(0, r[0]),
1358
+ body: str.slice(r[0] + a.length, r[1]),
1359
+ post: str.slice(r[1] + b.length)
1360
+ };
1361
+ }
1362
+ function maybeMatch(reg, str) {
1363
+ var m = str.match(reg);
1364
+ return m ? m[0] : null;
1365
+ }
1366
+ balanced.range = range;
1367
+ function range(a, b, str) {
1368
+ var begs, beg, left, right, result;
1369
+ var ai = str.indexOf(a);
1370
+ var bi = str.indexOf(b, ai + 1);
1371
+ var i = ai;
1372
+ if (ai >= 0 && bi > 0) {
1373
+ if (a === b) {
1374
+ return [ai, bi];
1692
1375
  }
1693
- const columnName = column.columnName;
1694
- const isNotNull = column.notNull === 1;
1695
- const columnType = column.columnType;
1696
- const isPrimary = column.pk !== 0;
1697
- const columnDefault = column.defaultValue;
1698
- const isAutoincrement = isPrimary && tablesWithSeq.includes(tableName);
1699
- if (isPrimary) {
1700
- if (typeof tableToPk[tableName] === "undefined") {
1701
- tableToPk[tableName] = [columnName];
1376
+ begs = [];
1377
+ left = str.length;
1378
+ while (i >= 0 && !result) {
1379
+ if (i == ai) {
1380
+ begs.push(i);
1381
+ ai = str.indexOf(a, i + 1);
1382
+ } else if (begs.length == 1) {
1383
+ result = [begs.pop(), bi];
1702
1384
  } else {
1703
- tableToPk[tableName].push(columnName);
1385
+ beg = begs.pop();
1386
+ if (beg < left) {
1387
+ left = beg;
1388
+ right = bi;
1389
+ }
1390
+ bi = str.indexOf(b, i + 1);
1704
1391
  }
1392
+ i = ai < bi && ai >= 0 ? ai : bi;
1705
1393
  }
1706
- const table = result[tableName];
1707
- const newColumn = {
1708
- default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) ? Number(columnDefault) : ["CURRENT_TIME", "CURRENT_DATE", "CURRENT_TIMESTAMP"].includes(
1709
- columnDefault
1710
- ) ? `(${columnDefault})` : columnDefault === "false" ? false : columnDefault === "true" ? true : columnDefault.startsWith("'") && columnDefault.endsWith("'") ? columnDefault : (
1711
- // ? columnDefault.substring(1, columnDefault.length - 1)
1712
- `(${columnDefault})`
1713
- ),
1714
- autoincrement: isAutoincrement,
1715
- name: columnName,
1716
- type: mapSqlToSqliteType(columnType),
1717
- primaryKey: false,
1718
- notNull: isNotNull
1719
- };
1720
- if (!table) {
1721
- result[tableName] = {
1722
- name: tableName,
1723
- columns: {
1724
- [columnName]: newColumn
1725
- },
1726
- compositePrimaryKeys: {},
1727
- indexes: {},
1728
- foreignKeys: {},
1729
- uniqueConstraints: {}
1730
- };
1731
- } else {
1732
- result[tableName].columns[columnName] = newColumn;
1394
+ if (begs.length) {
1395
+ result = [left, right];
1733
1396
  }
1734
1397
  }
1735
- for (const [key, value] of Object.entries(tableToPk)) {
1736
- if (value.length > 1) {
1737
- value.sort();
1738
- result[key].compositePrimaryKeys = {
1739
- [`${key}_${value.join("_")}_pk`]: {
1740
- columns: value,
1741
- name: `${key}_${value.join("_")}_pk`
1398
+ return result;
1399
+ }
1400
+ }
1401
+ });
1402
+
1403
+ // node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js
1404
+ var require_brace_expansion = __commonJS({
1405
+ "node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js"(exports, module2) {
1406
+ var balanced = require_balanced_match();
1407
+ module2.exports = expandTop;
1408
+ var escSlash = "\0SLASH" + Math.random() + "\0";
1409
+ var escOpen = "\0OPEN" + Math.random() + "\0";
1410
+ var escClose = "\0CLOSE" + Math.random() + "\0";
1411
+ var escComma = "\0COMMA" + Math.random() + "\0";
1412
+ var escPeriod = "\0PERIOD" + Math.random() + "\0";
1413
+ function numeric(str) {
1414
+ return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
1415
+ }
1416
+ function escapeBraces(str) {
1417
+ return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
1418
+ }
1419
+ function unescapeBraces(str) {
1420
+ return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
1421
+ }
1422
+ function parseCommaParts(str) {
1423
+ if (!str)
1424
+ return [""];
1425
+ var parts = [];
1426
+ var m = balanced("{", "}", str);
1427
+ if (!m)
1428
+ return str.split(",");
1429
+ var pre = m.pre;
1430
+ var body = m.body;
1431
+ var post = m.post;
1432
+ var p = pre.split(",");
1433
+ p[p.length - 1] += "{" + body + "}";
1434
+ var postParts = parseCommaParts(post);
1435
+ if (post.length) {
1436
+ p[p.length - 1] += postParts.shift();
1437
+ p.push.apply(p, postParts);
1438
+ }
1439
+ parts.push.apply(parts, p);
1440
+ return parts;
1441
+ }
1442
+ function expandTop(str) {
1443
+ if (!str)
1444
+ return [];
1445
+ if (str.substr(0, 2) === "{}") {
1446
+ str = "\\{\\}" + str.substr(2);
1447
+ }
1448
+ return expand2(escapeBraces(str), true).map(unescapeBraces);
1449
+ }
1450
+ function embrace(str) {
1451
+ return "{" + str + "}";
1452
+ }
1453
+ function isPadded(el) {
1454
+ return /^-?0\d/.test(el);
1455
+ }
1456
+ function lte(i, y) {
1457
+ return i <= y;
1458
+ }
1459
+ function gte(i, y) {
1460
+ return i >= y;
1461
+ }
1462
+ function expand2(str, isTop) {
1463
+ var expansions = [];
1464
+ var m = balanced("{", "}", str);
1465
+ if (!m)
1466
+ return [str];
1467
+ var pre = m.pre;
1468
+ var post = m.post.length ? expand2(m.post, false) : [""];
1469
+ if (/\$$/.test(m.pre)) {
1470
+ for (var k = 0; k < post.length; k++) {
1471
+ var expansion = pre + "{" + m.body + "}" + post[k];
1472
+ expansions.push(expansion);
1473
+ }
1474
+ } else {
1475
+ var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
1476
+ var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
1477
+ var isSequence = isNumericSequence || isAlphaSequence;
1478
+ var isOptions = m.body.indexOf(",") >= 0;
1479
+ if (!isSequence && !isOptions) {
1480
+ if (m.post.match(/,.*\}/)) {
1481
+ str = m.pre + "{" + m.body + escClose + m.post;
1482
+ return expand2(str);
1483
+ }
1484
+ return [str];
1485
+ }
1486
+ var n;
1487
+ if (isSequence) {
1488
+ n = m.body.split(/\.\./);
1489
+ } else {
1490
+ n = parseCommaParts(m.body);
1491
+ if (n.length === 1) {
1492
+ n = expand2(n[0], false).map(embrace);
1493
+ if (n.length === 1) {
1494
+ return post.map(function(p) {
1495
+ return m.pre + n[0] + p;
1496
+ });
1497
+ }
1498
+ }
1499
+ }
1500
+ var N;
1501
+ if (isSequence) {
1502
+ var x = numeric(n[0]);
1503
+ var y = numeric(n[1]);
1504
+ var width = Math.max(n[0].length, n[1].length);
1505
+ var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
1506
+ var test = lte;
1507
+ var reverse = y < x;
1508
+ if (reverse) {
1509
+ incr *= -1;
1510
+ test = gte;
1511
+ }
1512
+ var pad = n.some(isPadded);
1513
+ N = [];
1514
+ for (var i = x; test(i, y); i += incr) {
1515
+ var c;
1516
+ if (isAlphaSequence) {
1517
+ c = String.fromCharCode(i);
1518
+ if (c === "\\")
1519
+ c = "";
1520
+ } else {
1521
+ c = String(i);
1522
+ if (pad) {
1523
+ var need = width - c.length;
1524
+ if (need > 0) {
1525
+ var z = new Array(need + 1).join("0");
1526
+ if (i < 0)
1527
+ c = "-" + z + c.slice(1);
1528
+ else
1529
+ c = z + c;
1530
+ }
1531
+ }
1532
+ }
1533
+ N.push(c);
1534
+ }
1535
+ } else {
1536
+ N = [];
1537
+ for (var j = 0; j < n.length; j++) {
1538
+ N.push.apply(N, expand2(n[j], false));
1539
+ }
1540
+ }
1541
+ for (var j = 0; j < N.length; j++) {
1542
+ for (var k = 0; k < post.length; k++) {
1543
+ var expansion = pre + N[j] + post[k];
1544
+ if (!isTop || isSequence || expansion)
1545
+ expansions.push(expansion);
1546
+ }
1547
+ }
1548
+ }
1549
+ return expansions;
1550
+ }
1551
+ }
1552
+ });
1553
+
1554
+ // src/serializer/pgSerializer.ts
1555
+ var import_pg_core2, import_pg_core3, import_drizzle_orm2, dialect2, trimChar, fromDatabase2, columnToDefault, defaultForColumn;
1556
+ var init_pgSerializer = __esm({
1557
+ "src/serializer/pgSerializer.ts"() {
1558
+ import_pg_core2 = require("drizzle-orm/pg-core");
1559
+ import_pg_core3 = require("drizzle-orm/pg-core");
1560
+ import_drizzle_orm2 = require("drizzle-orm");
1561
+ init_serializer();
1562
+ init_source();
1563
+ init_outputs();
1564
+ dialect2 = new import_pg_core2.PgDialect();
1565
+ trimChar = (str, char) => {
1566
+ let start = 0;
1567
+ let end = str.length;
1568
+ while (start < end && str[start] === char)
1569
+ ++start;
1570
+ while (end > start && str[end - 1] === char)
1571
+ --end;
1572
+ return start > 0 || end < str.length ? str.substring(start, end) : str.toString();
1573
+ };
1574
+ fromDatabase2 = async (db, tablesFilter = (table) => true, schemaFilters, progressCallback) => {
1575
+ const result = {};
1576
+ const internals = { tables: {} };
1577
+ const where = schemaFilters.map((t) => `table_schema = '${t}'`).join(" or ");
1578
+ const allTables = await db.query(
1579
+ `SELECT table_schema, table_name FROM information_schema.tables WHERE ${where};`
1580
+ );
1581
+ const schemas = new Set(allTables.map((it) => it.table_schema));
1582
+ schemas.delete("public");
1583
+ const allSchemas = await db.query(`select s.nspname as table_schema
1584
+ from pg_catalog.pg_namespace s
1585
+ join pg_catalog.pg_user u on u.usesysid = s.nspowner
1586
+ where nspname not in ('information_schema', 'pg_catalog', 'public')
1587
+ and nspname not like 'pg_toast%'
1588
+ and nspname not like 'pg_temp_%'
1589
+ order by table_schema;`);
1590
+ allSchemas.forEach((item) => {
1591
+ if (schemaFilters.includes(item.table_schema)) {
1592
+ schemas.add(item.table_schema);
1593
+ }
1594
+ });
1595
+ let columnsCount = 0;
1596
+ let indexesCount = 0;
1597
+ let foreignKeysCount = 0;
1598
+ let tableCount = 0;
1599
+ const all = allTables.map((row) => {
1600
+ return new Promise(async (res, rej) => {
1601
+ const tableName = row.table_name;
1602
+ if (!tablesFilter(tableName))
1603
+ return res("");
1604
+ tableCount += 1;
1605
+ const tableSchema = row.table_schema;
1606
+ try {
1607
+ const columnToReturn = {};
1608
+ const indexToReturn = {};
1609
+ const foreignKeysToReturn = {};
1610
+ const primaryKeys = {};
1611
+ const uniqueConstrains = {};
1612
+ const tableResponse = await db.query(
1613
+ `SELECT a.attrelid::regclass::text, a.attname, is_nullable, a.attndims as array_dimensions
1614
+ , CASE WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[])
1615
+ AND EXISTS (
1616
+ SELECT FROM pg_attrdef ad
1617
+ WHERE ad.adrelid = a.attrelid
1618
+ AND ad.adnum = a.attnum
1619
+ AND pg_get_expr(ad.adbin, ad.adrelid)
1620
+ = 'nextval('''
1621
+ || (pg_get_serial_sequence (a.attrelid::regclass::text
1622
+ , a.attname))::regclass
1623
+ || '''::regclass)'
1624
+ )
1625
+ THEN CASE a.atttypid
1626
+ WHEN 'int'::regtype THEN 'serial'
1627
+ WHEN 'int8'::regtype THEN 'bigserial'
1628
+ WHEN 'int2'::regtype THEN 'smallserial'
1629
+ END
1630
+ ELSE format_type(a.atttypid, a.atttypmod)
1631
+ END AS data_type, INFORMATION_SCHEMA.COLUMNS.table_name, INFORMATION_SCHEMA.COLUMNS.column_name, INFORMATION_SCHEMA.COLUMNS.column_default, INFORMATION_SCHEMA.COLUMNS.data_type as additional_dt
1632
+ FROM pg_attribute a
1633
+ JOIN INFORMATION_SCHEMA.COLUMNS ON INFORMATION_SCHEMA.COLUMNS.column_name = a.attname
1634
+ WHERE a.attrelid = '"${tableSchema}"."${tableName}"'::regclass and INFORMATION_SCHEMA.COLUMNS.table_name = '${tableName}'
1635
+ AND a.attnum > 0
1636
+ AND NOT a.attisdropped
1637
+ ORDER BY a.attnum;`
1638
+ );
1639
+ const tableConstraints = await db.query(
1640
+ `SELECT c.column_name, c.data_type, constraint_type, constraint_name, constraint_schema
1641
+ FROM information_schema.table_constraints tc
1642
+ JOIN information_schema.constraint_column_usage AS ccu USING (constraint_schema, constraint_name)
1643
+ JOIN information_schema.columns AS c ON c.table_schema = tc.constraint_schema
1644
+ AND tc.table_name = c.table_name AND ccu.column_name = c.column_name
1645
+ WHERE tc.table_name = '${tableName}' and constraint_schema = '${tableSchema}';`
1646
+ );
1647
+ columnsCount += tableResponse.length;
1648
+ if (progressCallback) {
1649
+ progressCallback("columns", columnsCount, "fetching");
1650
+ }
1651
+ const tableForeignKeys = await db.query(
1652
+ `SELECT
1653
+ tc.table_schema,
1654
+ tc.constraint_name,
1655
+ tc.table_name,
1656
+ kcu.column_name,
1657
+ ccu.table_schema AS foreign_table_schema,
1658
+ ccu.table_name AS foreign_table_name,
1659
+ ccu.column_name AS foreign_column_name,
1660
+ rc.delete_rule, rc.update_rule
1661
+ FROM
1662
+ information_schema.table_constraints AS tc
1663
+ JOIN information_schema.key_column_usage AS kcu
1664
+ ON tc.constraint_name = kcu.constraint_name
1665
+ AND tc.table_schema = kcu.table_schema
1666
+ JOIN information_schema.constraint_column_usage AS ccu
1667
+ ON ccu.constraint_name = tc.constraint_name
1668
+ AND ccu.table_schema = tc.table_schema
1669
+ JOIN information_schema.referential_constraints AS rc
1670
+ ON ccu.constraint_name = rc.constraint_name
1671
+ WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='${tableName}' and tc.table_schema='${tableSchema}';`
1672
+ );
1673
+ foreignKeysCount += tableForeignKeys.length;
1674
+ if (progressCallback) {
1675
+ progressCallback("fks", foreignKeysCount, "fetching");
1676
+ }
1677
+ for (const fk of tableForeignKeys) {
1678
+ const columnFrom = fk.column_name;
1679
+ const tableTo = fk.foreign_table_name;
1680
+ const columnTo = fk.foreign_column_name;
1681
+ const foreignKeyName = fk.constraint_name;
1682
+ const onUpdate = fk.update_rule.toLowerCase();
1683
+ const onDelete = fk.delete_rule.toLowerCase();
1684
+ if (typeof foreignKeysToReturn[foreignKeyName] !== "undefined") {
1685
+ foreignKeysToReturn[foreignKeyName].columnsFrom.push(columnFrom);
1686
+ foreignKeysToReturn[foreignKeyName].columnsTo.push(columnTo);
1687
+ } else {
1688
+ foreignKeysToReturn[foreignKeyName] = {
1689
+ name: foreignKeyName,
1690
+ tableFrom: tableName,
1691
+ tableTo,
1692
+ columnsFrom: [columnFrom],
1693
+ columnsTo: [columnTo],
1694
+ onDelete,
1695
+ onUpdate
1696
+ };
1697
+ }
1698
+ foreignKeysToReturn[foreignKeyName].columnsFrom = [
1699
+ ...new Set(foreignKeysToReturn[foreignKeyName].columnsFrom)
1700
+ ];
1701
+ foreignKeysToReturn[foreignKeyName].columnsTo = [
1702
+ ...new Set(foreignKeysToReturn[foreignKeyName].columnsTo)
1703
+ ];
1704
+ }
1705
+ const uniqueConstrainsRows = tableConstraints.filter(
1706
+ (mapRow) => mapRow.constraint_type === "UNIQUE"
1707
+ );
1708
+ for (const unqs of uniqueConstrainsRows) {
1709
+ const columnName = unqs.column_name;
1710
+ const constraintName = unqs.constraint_name;
1711
+ if (typeof uniqueConstrains[constraintName] !== "undefined") {
1712
+ uniqueConstrains[constraintName].columns.push(columnName);
1713
+ } else {
1714
+ uniqueConstrains[constraintName] = {
1715
+ columns: [columnName],
1716
+ nullsNotDistinct: false,
1717
+ name: constraintName
1718
+ };
1719
+ }
1720
+ }
1721
+ for (const columnResponse of tableResponse) {
1722
+ const columnName = columnResponse.attname;
1723
+ const columnAdditionalDT = columnResponse.additional_dt;
1724
+ const columnDimensions = columnResponse.array_dimensions;
1725
+ let columnType = columnResponse.data_type;
1726
+ const primaryKey = tableConstraints.filter(
1727
+ (mapRow) => columnName === mapRow.column_name && mapRow.constraint_type === "PRIMARY KEY"
1728
+ );
1729
+ const cprimaryKey = tableConstraints.filter(
1730
+ (mapRow) => mapRow.constraint_type === "PRIMARY KEY"
1731
+ );
1732
+ if (cprimaryKey.length > 1) {
1733
+ const tableCompositePkName = await db.query(
1734
+ `SELECT conname AS primary_key
1735
+ FROM pg_constraint join pg_class on (pg_class.oid = conrelid)
1736
+ WHERE contype = 'p'
1737
+ AND connamespace = $1::regnamespace
1738
+ AND pg_class.relname = $2;`,
1739
+ [tableSchema, tableName]
1740
+ );
1741
+ primaryKeys[tableCompositePkName[0].primary_key] = {
1742
+ name: tableCompositePkName[0].primary_key,
1743
+ columns: cprimaryKey.map((c) => c.column_name)
1744
+ };
1745
+ }
1746
+ const defaultValue = defaultForColumn(columnResponse);
1747
+ const isSerial = columnType === "serial";
1748
+ let columnTypeMapped = columnType;
1749
+ if (columnTypeMapped.startsWith("numeric(")) {
1750
+ columnTypeMapped = columnTypeMapped.replace(",", ", ");
1751
+ }
1752
+ if (columnAdditionalDT === "ARRAY") {
1753
+ if (typeof internals.tables[tableName] === "undefined") {
1754
+ internals.tables[tableName] = {
1755
+ columns: {
1756
+ [columnName]: {
1757
+ isArray: true,
1758
+ dimensions: columnDimensions,
1759
+ rawType: columnTypeMapped.substring(
1760
+ 0,
1761
+ columnTypeMapped.length - 2
1762
+ )
1763
+ }
1764
+ }
1765
+ };
1766
+ } else {
1767
+ if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
1768
+ internals.tables[tableName].columns[columnName] = {
1769
+ isArray: true,
1770
+ dimensions: columnDimensions,
1771
+ rawType: columnTypeMapped.substring(
1772
+ 0,
1773
+ columnTypeMapped.length - 2
1774
+ )
1775
+ };
1776
+ }
1777
+ }
1778
+ }
1779
+ if (columnAdditionalDT === "ARRAY") {
1780
+ for (let i = 1; i < Number(columnDimensions); i++) {
1781
+ columnTypeMapped += "[]";
1782
+ }
1783
+ }
1784
+ columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
1785
+ columnTypeMapped = trimChar(columnTypeMapped, '"');
1786
+ columnToReturn[columnName] = {
1787
+ name: columnName,
1788
+ type: columnTypeMapped,
1789
+ primaryKey: primaryKey.length === 1 && cprimaryKey.length < 2,
1790
+ // default: isSerial ? undefined : defaultValue,
1791
+ notNull: columnResponse.is_nullable === "NO"
1792
+ };
1793
+ if (!isSerial && typeof defaultValue !== "undefined") {
1794
+ columnToReturn[columnName].default = defaultValue;
1795
+ }
1742
1796
  }
1743
- };
1744
- } else if (value.length === 1) {
1745
- result[key].columns[value[0]].primaryKey = true;
1746
- } else {
1747
- }
1748
- }
1749
- if (progressCallback) {
1750
- progressCallback("columns", columnsCount, "done");
1751
- progressCallback("tables", tablesCount.size, "done");
1752
- }
1753
- try {
1754
- const fks = await db.query(
1755
- `SELECT m.name as "tableFrom", f.id as "id", f."table" as "tableTo", f."from", f."to", f."on_update" as "onUpdate", f."on_delete" as "onDelete", f.seq as "seq"
1756
- FROM sqlite_master m, pragma_foreign_key_list(m.name) as f;`
1757
- );
1758
- const fkByTableName = {};
1759
- for (const fkRow of fks) {
1760
- foreignKeysCount += 1;
1761
- if (progressCallback) {
1762
- progressCallback("fks", foreignKeysCount, "fetching");
1763
- }
1764
- const tableName = fkRow.tableFrom;
1765
- const columnName = fkRow.from;
1766
- const refTableName = fkRow.tableTo;
1767
- const refColumnName = fkRow.to;
1768
- const updateRule = fkRow.onUpdate;
1769
- const deleteRule = fkRow.onDelete;
1770
- const sequence = fkRow.seq;
1771
- const id = fkRow.id;
1772
- const tableInResult = result[tableName];
1773
- if (typeof tableInResult === "undefined")
1774
- continue;
1775
- if (typeof fkByTableName[`${tableName}_${id}`] !== "undefined") {
1776
- fkByTableName[`${tableName}_${id}`].columnsFrom.push(columnName);
1777
- fkByTableName[`${tableName}_${id}`].columnsTo.push(refColumnName);
1778
- } else {
1779
- fkByTableName[`${tableName}_${id}`] = {
1780
- name: "",
1781
- tableFrom: tableName,
1782
- tableTo: refTableName,
1783
- columnsFrom: [columnName],
1784
- columnsTo: [refColumnName],
1785
- onDelete: deleteRule == null ? void 0 : deleteRule.toLowerCase(),
1786
- onUpdate: updateRule == null ? void 0 : updateRule.toLowerCase()
1797
+ const dbIndexes = await db.query(
1798
+ `SELECT t.relname as table_name, i.relname AS index_name, ix.indisunique AS is_unique, a.attname AS column_name
1799
+ FROM pg_class t
1800
+ JOIN pg_index ix ON t.oid = ix.indrelid
1801
+ JOIN pg_class i ON i.oid = ix.indexrelid
1802
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
1803
+ JOIN pg_namespace ns ON ns.oid = t.relnamespace
1804
+ WHERE ns.nspname = '${tableSchema}'
1805
+ AND t.relname = '${tableName}'
1806
+ and ix.indisprimary = false;`
1807
+ );
1808
+ const dbIndexFromConstraint = await db.query(
1809
+ `SELECT
1810
+ idx.indexrelname AS index_name,
1811
+ idx.relname AS table_name,
1812
+ schemaname,
1813
+ CASE WHEN con.conname IS NOT NULL THEN 1 ELSE 0 END AS generated_by_constraint
1814
+ FROM
1815
+ pg_stat_user_indexes idx
1816
+ LEFT JOIN
1817
+ pg_constraint con ON con.conindid = idx.indexrelid
1818
+ WHERE idx.relname = '${tableName}' and schemaname = '${tableSchema}'
1819
+ group by index_name, table_name,schemaname, generated_by_constraint;`
1820
+ );
1821
+ const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map((it) => it.index_name);
1822
+ for (const dbIndex of dbIndexes) {
1823
+ const indexName2 = dbIndex.index_name;
1824
+ const indexColumnName = dbIndex.column_name;
1825
+ const indexIsUnique = dbIndex.is_unique;
1826
+ if (idxsInConsteraint.includes(indexName2))
1827
+ continue;
1828
+ if (typeof indexToReturn[indexName2] !== "undefined") {
1829
+ indexToReturn[indexName2].columns.push(indexColumnName);
1830
+ } else {
1831
+ indexToReturn[indexName2] = {
1832
+ name: indexName2,
1833
+ columns: [indexColumnName],
1834
+ isUnique: indexIsUnique
1835
+ };
1836
+ }
1837
+ }
1838
+ indexesCount += Object.keys(indexToReturn).length;
1839
+ if (progressCallback) {
1840
+ progressCallback("indexes", indexesCount, "fetching");
1841
+ }
1842
+ result[tableName] = {
1843
+ name: tableName,
1844
+ schema: tableSchema !== "public" ? tableSchema : "",
1845
+ columns: columnToReturn,
1846
+ indexes: indexToReturn,
1847
+ foreignKeys: foreignKeysToReturn,
1848
+ compositePrimaryKeys: primaryKeys,
1849
+ uniqueConstraints: uniqueConstrains
1787
1850
  };
1851
+ } catch (e) {
1852
+ rej(e);
1853
+ return;
1788
1854
  }
1789
- const columnsFrom = fkByTableName[`${tableName}_${id}`].columnsFrom;
1790
- const columnsTo = fkByTableName[`${tableName}_${id}`].columnsTo;
1791
- fkByTableName[`${tableName}_${id}`].name = `${tableName}_${columnsFrom.join(
1792
- "_"
1793
- )}_${refTableName}_${columnsTo.join("_")}_fk`;
1794
- }
1795
- for (const idx of Object.keys(fkByTableName)) {
1796
- const value = fkByTableName[idx];
1797
- result[value.tableFrom].foreignKeys[value.name] = value;
1798
- }
1799
- } catch (e) {
1800
- }
1855
+ res("");
1856
+ });
1857
+ });
1801
1858
  if (progressCallback) {
1802
- progressCallback("fks", foreignKeysCount, "done");
1859
+ progressCallback("tables", tableCount, "done");
1803
1860
  }
1804
- const idxs = await db.query(
1805
- `SELECT
1806
- m.tbl_name as tableName,
1807
- il.name as indexName,
1808
- ii.name as columnName,
1809
- il.[unique] as isUnique,
1810
- il.seq as seq
1811
- FROM sqlite_master AS m,
1812
- pragma_index_list(m.name) AS il,
1813
- pragma_index_info(il.name) AS ii
1814
- WHERE
1815
- m.type = 'table' and il.name NOT LIKE 'sqlite_autoindex_%';`
1816
- );
1817
- for (const idxRow of idxs) {
1818
- const tableName = idxRow.tableName;
1819
- const constraintName = idxRow.indexName;
1820
- const columnName = idxRow.columnName;
1821
- const isUnique = idxRow.isUnique === 1;
1822
- const tableInResult = result[tableName];
1823
- if (typeof tableInResult === "undefined")
1824
- continue;
1825
- indexesCount += 1;
1826
- if (progressCallback) {
1827
- progressCallback("indexes", indexesCount, "fetching");
1828
- }
1829
- if (typeof tableInResult.indexes[constraintName] !== "undefined") {
1830
- tableInResult.indexes[constraintName].columns.push(columnName);
1831
- } else {
1832
- tableInResult.indexes[constraintName] = {
1833
- name: constraintName,
1834
- columns: [columnName],
1835
- isUnique
1836
- };
1837
- }
1861
+ for await (const _ of all) {
1838
1862
  }
1839
1863
  if (progressCallback) {
1864
+ progressCallback("columns", columnsCount, "done");
1840
1865
  progressCallback("indexes", indexesCount, "done");
1841
- progressCallback("enums", 0, "done");
1866
+ progressCallback("fks", foreignKeysCount, "done");
1842
1867
  }
1843
- return {
1844
- version: "5",
1845
- dialect: "sqlite",
1846
- tables: result,
1847
- enums: {},
1848
- _meta: {
1849
- tables: {},
1850
- columns: {}
1851
- }
1852
- };
1853
- };
1854
- toDrizzle2 = (schema) => {
1855
- const tables = {};
1856
- Object.values(schema.tables).forEach((t) => {
1857
- const columns = {};
1858
- Object.values(t.columns).forEach((c) => {
1859
- const columnName = c.name;
1860
- const type = c.type;
1861
- let columnBuilder;
1862
- if (type === "integer") {
1863
- columnBuilder = new import_sqlite_core.SQLiteIntegerBuilder(columnName);
1864
- } else if (type === "text") {
1865
- columnBuilder = new import_sqlite_core.SQLiteTextBuilder(columnName, {});
1866
- } else if (type === "blob") {
1867
- columnBuilder = new import_sqlite_core.SQLiteBlobBufferBuilder(columnName);
1868
- } else if (type === "real") {
1869
- columnBuilder = new import_sqlite_core.SQLiteRealBuilder(columnName);
1870
- } else {
1871
- columnBuilder = new import_sqlite_core.SQLiteNumericBuilder(columnName);
1872
- }
1873
- if (c.notNull) {
1874
- columnBuilder = columnBuilder.notNull();
1875
- }
1876
- if (c.default) {
1877
- columnBuilder = columnBuilder.default(c.default);
1878
- }
1879
- if (c.primaryKey) {
1880
- columnBuilder = columnBuilder.primaryKey();
1881
- }
1882
- columns[columnName] = columnBuilder;
1883
- });
1884
- tables[t.name] = (0, import_sqlite_core.sqliteTable)(t.name, columns, (cb) => {
1885
- const res = {};
1886
- Object.values(t.compositePrimaryKeys).forEach((cpk) => {
1887
- const gh = cpk.columns.map((c) => cb[c]);
1888
- res[cpk.name] = new import_sqlite_core.PrimaryKeyBuilder(
1889
- gh,
1890
- cpk.name
1891
- );
1892
- });
1893
- return res;
1894
- });
1895
- });
1896
- return tables;
1897
- };
1898
- }
1899
- });
1900
-
1901
- // node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
1902
- var require_balanced_match = __commonJS({
1903
- "node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js"(exports, module2) {
1904
- "use strict";
1905
- module2.exports = balanced;
1906
- function balanced(a, b, str) {
1907
- if (a instanceof RegExp)
1908
- a = maybeMatch(a, str);
1909
- if (b instanceof RegExp)
1910
- b = maybeMatch(b, str);
1911
- var r = range(a, b, str);
1912
- return r && {
1913
- start: r[0],
1914
- end: r[1],
1915
- pre: str.slice(0, r[0]),
1916
- body: str.slice(r[0] + a.length, r[1]),
1917
- post: str.slice(r[1] + b.length)
1918
- };
1919
- }
1920
- function maybeMatch(reg, str) {
1921
- var m = str.match(reg);
1922
- return m ? m[0] : null;
1923
- }
1924
- balanced.range = range;
1925
- function range(a, b, str) {
1926
- var begs, beg, left, right, result;
1927
- var ai = str.indexOf(a);
1928
- var bi = str.indexOf(b, ai + 1);
1929
- var i = ai;
1930
- if (ai >= 0 && bi > 0) {
1931
- if (a === b) {
1932
- return [ai, bi];
1933
- }
1934
- begs = [];
1935
- left = str.length;
1936
- while (i >= 0 && !result) {
1937
- if (i == ai) {
1938
- begs.push(i);
1939
- ai = str.indexOf(a, i + 1);
1940
- } else if (begs.length == 1) {
1941
- result = [begs.pop(), bi];
1942
- } else {
1943
- beg = begs.pop();
1944
- if (beg < left) {
1945
- left = beg;
1946
- right = bi;
1947
- }
1948
- bi = str.indexOf(b, i + 1);
1949
- }
1950
- i = ai < bi && ai >= 0 ? ai : bi;
1951
- }
1952
- if (begs.length) {
1953
- result = [left, right];
1868
+ const allEnums = await db.query(
1869
+ `select n.nspname as enum_schema,
1870
+ t.typname as enum_name,
1871
+ e.enumlabel as enum_value
1872
+ from pg_type t
1873
+ join pg_enum e on t.oid = e.enumtypid
1874
+ join pg_catalog.pg_namespace n ON n.oid = t.typnamespace;`
1875
+ );
1876
+ const enumsToReturn = {};
1877
+ for (const dbEnum of allEnums) {
1878
+ const enumName = dbEnum.enum_name;
1879
+ const enumValue = dbEnum.enum_value;
1880
+ if (enumsToReturn[enumName] !== void 0 && enumsToReturn[enumName] !== null) {
1881
+ enumsToReturn[enumName].values[enumValue] = enumValue;
1882
+ } else {
1883
+ enumsToReturn[enumName] = {
1884
+ name: enumName,
1885
+ values: { [enumValue]: enumValue }
1886
+ };
1954
1887
  }
1955
1888
  }
1956
- return result;
1957
- }
1958
- }
1959
- });
1960
-
1961
- // node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js
1962
- var require_brace_expansion = __commonJS({
1963
- "node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js"(exports, module2) {
1964
- var balanced = require_balanced_match();
1965
- module2.exports = expandTop;
1966
- var escSlash = "\0SLASH" + Math.random() + "\0";
1967
- var escOpen = "\0OPEN" + Math.random() + "\0";
1968
- var escClose = "\0CLOSE" + Math.random() + "\0";
1969
- var escComma = "\0COMMA" + Math.random() + "\0";
1970
- var escPeriod = "\0PERIOD" + Math.random() + "\0";
1971
- function numeric(str) {
1972
- return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
1973
- }
1974
- function escapeBraces(str) {
1975
- return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
1976
- }
1977
- function unescapeBraces(str) {
1978
- return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
1979
- }
1980
- function parseCommaParts(str) {
1981
- if (!str)
1982
- return [""];
1983
- var parts = [];
1984
- var m = balanced("{", "}", str);
1985
- if (!m)
1986
- return str.split(",");
1987
- var pre = m.pre;
1988
- var body = m.body;
1989
- var post = m.post;
1990
- var p = pre.split(",");
1991
- p[p.length - 1] += "{" + body + "}";
1992
- var postParts = parseCommaParts(post);
1993
- if (post.length) {
1994
- p[p.length - 1] += postParts.shift();
1995
- p.push.apply(p, postParts);
1889
+ if (progressCallback) {
1890
+ progressCallback("enums", Object.keys(enumsToReturn).length, "done");
1996
1891
  }
1997
- parts.push.apply(parts, p);
1998
- return parts;
1999
- }
2000
- function expandTop(str) {
2001
- if (!str)
2002
- return [];
2003
- if (str.substr(0, 2) === "{}") {
2004
- str = "\\{\\}" + str.substr(2);
1892
+ const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it]));
1893
+ return {
1894
+ version: "5",
1895
+ dialect: "pg",
1896
+ tables: result,
1897
+ enums: enumsToReturn,
1898
+ schemas: schemasObject,
1899
+ _meta: {
1900
+ schemas: {},
1901
+ tables: {},
1902
+ columns: {}
1903
+ },
1904
+ internal: internals
1905
+ };
1906
+ };
1907
+ columnToDefault = {
1908
+ "numeric(": "::numeric",
1909
+ // text: "::text",
1910
+ // "character varying": "::character varying",
1911
+ // "double precision": "::double precision",
1912
+ // "time with time zone": "::time with time zone",
1913
+ "time without time zone": "::time without time zone",
1914
+ // "timestamp with time zone": "::timestamp with time zone",
1915
+ "timestamp without time zone": "::timestamp without time zone",
1916
+ // date: "::date",
1917
+ // interval: "::interval",
1918
+ // character: "::bpchar",
1919
+ // macaddr8: "::macaddr8",
1920
+ // macaddr: "::macaddr",
1921
+ // inet: "::inet",
1922
+ // cidr: "::cidr",
1923
+ // jsonb: "::jsonb",
1924
+ // json: "::json",
1925
+ "character(": "::bpchar"
1926
+ };
1927
+ defaultForColumn = (column) => {
1928
+ if (column.data_type === "serial" || column.data_type === "smallserial" || column.data_type === "bigserial") {
1929
+ return void 0;
2005
1930
  }
2006
- return expand2(escapeBraces(str), true).map(unescapeBraces);
2007
- }
2008
- function embrace(str) {
2009
- return "{" + str + "}";
2010
- }
2011
- function isPadded(el) {
2012
- return /^-?0\d/.test(el);
2013
- }
2014
- function lte(i, y) {
2015
- return i <= y;
2016
- }
2017
- function gte(i, y) {
2018
- return i >= y;
2019
- }
2020
- function expand2(str, isTop) {
2021
- var expansions = [];
2022
- var m = balanced("{", "}", str);
2023
- if (!m)
2024
- return [str];
2025
- var pre = m.pre;
2026
- var post = m.post.length ? expand2(m.post, false) : [""];
2027
- if (/\$$/.test(m.pre)) {
2028
- for (var k = 0; k < post.length; k++) {
2029
- var expansion = pre + "{" + m.body + "}" + post[k];
2030
- expansions.push(expansion);
2031
- }
2032
- } else {
2033
- var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
2034
- var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
2035
- var isSequence = isNumericSequence || isAlphaSequence;
2036
- var isOptions = m.body.indexOf(",") >= 0;
2037
- if (!isSequence && !isOptions) {
2038
- if (m.post.match(/,.*\}/)) {
2039
- str = m.pre + "{" + m.body + escClose + m.post;
2040
- return expand2(str);
2041
- }
2042
- return [str];
2043
- }
2044
- var n;
2045
- if (isSequence) {
2046
- n = m.body.split(/\.\./);
1931
+ const hasDifferentDefaultCast = Object.keys(columnToDefault).find(
1932
+ (it) => column.data_type.startsWith(it)
1933
+ );
1934
+ if (column.column_default === null) {
1935
+ return void 0;
1936
+ }
1937
+ const columnDefaultAsString = column.column_default.toString();
1938
+ if (columnDefaultAsString.endsWith(
1939
+ hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : column.data_type
1940
+ )) {
1941
+ const nonPrefixPart = column.column_default.length - (hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : `::${column.data_type}`).length - 1;
1942
+ const rt = column.column_default.toString().substring(1, nonPrefixPart);
1943
+ if (/^-?[\d.]+(?:e-?\d+)?$/.test(rt) && !column.data_type.startsWith("numeric")) {
1944
+ return Number(rt);
1945
+ } else if (column.data_type === "json" || column.data_type === "jsonb") {
1946
+ const jsonWithoutSpaces = JSON.stringify(JSON.parse(rt));
1947
+ return `'${jsonWithoutSpaces}'${hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : `::${column.data_type}`}`;
1948
+ } else if (column.data_type === "boolean") {
1949
+ return column.column_default === "true";
2047
1950
  } else {
2048
- n = parseCommaParts(m.body);
2049
- if (n.length === 1) {
2050
- n = expand2(n[0], false).map(embrace);
2051
- if (n.length === 1) {
2052
- return post.map(function(p) {
2053
- return m.pre + n[0] + p;
2054
- });
2055
- }
2056
- }
1951
+ return `'${rt}'`;
2057
1952
  }
2058
- var N;
2059
- if (isSequence) {
2060
- var x = numeric(n[0]);
2061
- var y = numeric(n[1]);
2062
- var width = Math.max(n[0].length, n[1].length);
2063
- var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
2064
- var test = lte;
2065
- var reverse = y < x;
2066
- if (reverse) {
2067
- incr *= -1;
2068
- test = gte;
2069
- }
2070
- var pad = n.some(isPadded);
2071
- N = [];
2072
- for (var i = x; test(i, y); i += incr) {
2073
- var c;
2074
- if (isAlphaSequence) {
2075
- c = String.fromCharCode(i);
2076
- if (c === "\\")
2077
- c = "";
2078
- } else {
2079
- c = String(i);
2080
- if (pad) {
2081
- var need = width - c.length;
2082
- if (need > 0) {
2083
- var z = new Array(need + 1).join("0");
2084
- if (i < 0)
2085
- c = "-" + z + c.slice(1);
2086
- else
2087
- c = z + c;
2088
- }
2089
- }
2090
- }
2091
- N.push(c);
2092
- }
1953
+ } else {
1954
+ if (/^-?[\d.]+(?:e-?\d+)?$/.test(columnDefaultAsString) && !column.data_type.startsWith("numeric")) {
1955
+ return Number(columnDefaultAsString);
1956
+ } else if (column.data_type === "boolean") {
1957
+ return column.column_default === "true";
2093
1958
  } else {
2094
- N = [];
2095
- for (var j = 0; j < n.length; j++) {
2096
- N.push.apply(N, expand2(n[j], false));
2097
- }
2098
- }
2099
- for (var j = 0; j < N.length; j++) {
2100
- for (var k = 0; k < post.length; k++) {
2101
- var expansion = pre + N[j] + post[k];
2102
- if (!isTop || isSequence || expansion)
2103
- expansions.push(expansion);
2104
- }
1959
+ return `${columnDefaultAsString}`;
2105
1960
  }
2106
1961
  }
2107
- return expansions;
2108
- }
1962
+ };
2109
1963
  }
2110
1964
  });
2111
1965
 
@@ -2146,14 +2000,162 @@ var utils_studio_exports = {};
2146
2000
  __export(utils_studio_exports, {
2147
2001
  DrizzleORMPgClient: () => DrizzleORMPgClient,
2148
2002
  TursoSqlite: () => TursoSqlite,
2149
- drizzleSchemaPg: () => toDrizzle,
2150
- drizzleSchemaSQLite: () => toDrizzle2,
2003
+ drizzleSchemaPg: () => pgSchemaToDrizzle,
2004
+ drizzleSchemaSQLite: () => sqliteSchemaToDrizzle,
2151
2005
  pgPushIntrospect: () => pgPushIntrospect,
2152
2006
  sqlitePushIntrospect: () => sqlitePushIntrospect
2153
2007
  });
2154
2008
  module.exports = __toCommonJS(utils_studio_exports);
2155
- init_pgSerializer();
2156
- init_sqliteSerializer();
2009
+
2010
+ // src/serializer/schemaToDrizzle.ts
2011
+ var import_pg_core = require("drizzle-orm/pg-core");
2012
+ var import_sqlite_core = require("drizzle-orm/sqlite-core");
2013
+ var pgSchemaToDrizzle = (schema, schemaName) => {
2014
+ const tables = {};
2015
+ Object.values(schema.tables).forEach((t) => {
2016
+ const columns = {};
2017
+ Object.values(t.columns).forEach((c) => {
2018
+ const columnName = c.name;
2019
+ const type = c.type;
2020
+ let columnBuilder;
2021
+ if (type === "bigint") {
2022
+ columnBuilder = new import_pg_core.PgBigInt53Builder(columnName);
2023
+ } else if (type === "bigserial") {
2024
+ columnBuilder = new import_pg_core.PgBigSerial53Builder(columnName);
2025
+ } else if (type === "boolean") {
2026
+ columnBuilder = new import_pg_core.PgBooleanBuilder(columnName);
2027
+ } else if (type === "cidr") {
2028
+ columnBuilder = new import_pg_core.PgCidrBuilder(columnName);
2029
+ } else if (type === "date") {
2030
+ columnBuilder = new import_pg_core.PgDateBuilder(columnName);
2031
+ } else if (type === "double precision") {
2032
+ columnBuilder = new import_pg_core.PgDoublePrecisionBuilder(columnName);
2033
+ } else if (type === "inet") {
2034
+ columnBuilder = new import_pg_core.PgInetBuilder(columnName);
2035
+ } else if (type === "integer") {
2036
+ columnBuilder = new import_pg_core.PgIntegerBuilder(columnName);
2037
+ } else if (type === "interval" || type.startsWith("interval ")) {
2038
+ columnBuilder = new import_pg_core.PgIntervalBuilder(columnName, {});
2039
+ } else if (type === "json") {
2040
+ columnBuilder = new import_pg_core.PgJsonBuilder(columnName);
2041
+ } else if (type === "jsonb") {
2042
+ columnBuilder = new import_pg_core.PgJsonbBuilder(columnName);
2043
+ } else if (type === "macaddr") {
2044
+ columnBuilder = new import_pg_core.PgMacaddrBuilder(columnName);
2045
+ } else if (type === "macaddr8") {
2046
+ columnBuilder = new import_pg_core.PgMacaddr8Builder(columnName);
2047
+ } else if (type === "numeric" || type.startsWith("numeric(")) {
2048
+ columnBuilder = new import_pg_core.PgNumericBuilder(columnName);
2049
+ } else if (type === "real") {
2050
+ columnBuilder = new import_pg_core.PgRealBuilder(columnName);
2051
+ } else if (type === "serial") {
2052
+ columnBuilder = new import_pg_core.PgSerialBuilder(columnName);
2053
+ } else if (type === "smallint") {
2054
+ columnBuilder = new import_pg_core.PgSmallIntBuilder(columnName);
2055
+ } else if (type === "smallserial") {
2056
+ columnBuilder = new import_pg_core.PgSmallSerialBuilder(columnName);
2057
+ } else if (type === "text") {
2058
+ columnBuilder = new import_pg_core.PgTextBuilder(columnName, {});
2059
+ } else if (type === "time" || type.startsWith("time(") || type === "time with time zone") {
2060
+ columnBuilder = new import_pg_core.PgTimeBuilder(columnName, false, void 0);
2061
+ } else if (type === "timestamp" || type.startsWith("timestamp(") || type === "timestamp with time zone") {
2062
+ columnBuilder = new import_pg_core.PgTimestampBuilder(columnName, false, void 0);
2063
+ } else if (type === "uuid") {
2064
+ columnBuilder = new import_pg_core.PgUUIDBuilder(columnName);
2065
+ } else if (type === "varchar" || type.startsWith("varchar(")) {
2066
+ columnBuilder = new import_pg_core.PgVarcharBuilder(columnName, {});
2067
+ } else if (type === "char" || type.startsWith("char(")) {
2068
+ columnBuilder = new import_pg_core.PgCharBuilder(columnName, {});
2069
+ } else {
2070
+ columnBuilder = (0, import_pg_core.customType)({
2071
+ dataType() {
2072
+ return type;
2073
+ }
2074
+ })(columnName);
2075
+ }
2076
+ if (c.notNull) {
2077
+ columnBuilder = columnBuilder.notNull();
2078
+ }
2079
+ if (c.default) {
2080
+ columnBuilder = columnBuilder.default(c.default);
2081
+ }
2082
+ if (c.primaryKey) {
2083
+ columnBuilder = columnBuilder.primaryKey();
2084
+ }
2085
+ columns[columnName] = columnBuilder;
2086
+ });
2087
+ if (schemaName === "public") {
2088
+ tables[t.name] = (0, import_pg_core.pgTable)(t.name, columns, (cb) => {
2089
+ const res = {};
2090
+ Object.values(t.compositePrimaryKeys).forEach((cpk) => {
2091
+ const gh = cpk.columns.map((c) => cb[c]);
2092
+ res[cpk.name] = new import_pg_core.PrimaryKeyBuilder(
2093
+ gh,
2094
+ cpk.name
2095
+ );
2096
+ });
2097
+ return res;
2098
+ });
2099
+ } else {
2100
+ tables[t.name] = (0, import_pg_core.pgSchema)(schemaName).table(t.name, columns, (cb) => {
2101
+ const res = {};
2102
+ Object.values(t.compositePrimaryKeys).forEach((cpk) => {
2103
+ const gh = cpk.columns.map((c) => cb[c]);
2104
+ res[cpk.name] = new import_pg_core.PrimaryKeyBuilder(
2105
+ gh,
2106
+ cpk.name
2107
+ );
2108
+ });
2109
+ return res;
2110
+ });
2111
+ }
2112
+ });
2113
+ return tables;
2114
+ };
2115
+ var sqliteSchemaToDrizzle = (schema) => {
2116
+ const tables = {};
2117
+ Object.values(schema.tables).forEach((t) => {
2118
+ const columns = {};
2119
+ Object.values(t.columns).forEach((c) => {
2120
+ const columnName = c.name;
2121
+ const type = c.type;
2122
+ let columnBuilder;
2123
+ if (type === "integer") {
2124
+ columnBuilder = new import_sqlite_core.SQLiteIntegerBuilder(columnName);
2125
+ } else if (type === "text") {
2126
+ columnBuilder = new import_sqlite_core.SQLiteTextBuilder(columnName, {});
2127
+ } else if (type === "blob") {
2128
+ columnBuilder = new import_sqlite_core.SQLiteBlobBufferBuilder(columnName);
2129
+ } else if (type === "real") {
2130
+ columnBuilder = new import_sqlite_core.SQLiteRealBuilder(columnName);
2131
+ } else {
2132
+ columnBuilder = new import_sqlite_core.SQLiteNumericBuilder(columnName);
2133
+ }
2134
+ if (c.notNull) {
2135
+ columnBuilder = columnBuilder.notNull();
2136
+ }
2137
+ if (c.default) {
2138
+ columnBuilder = columnBuilder.default(c.default);
2139
+ }
2140
+ if (c.primaryKey) {
2141
+ columnBuilder = columnBuilder.primaryKey();
2142
+ }
2143
+ columns[columnName] = columnBuilder;
2144
+ });
2145
+ tables[t.name] = (0, import_sqlite_core.sqliteTable)(t.name, columns, (cb) => {
2146
+ const res = {};
2147
+ Object.values(t.compositePrimaryKeys).forEach((cpk) => {
2148
+ const gh = cpk.columns.map((c) => cb[c]);
2149
+ res[cpk.name] = new import_sqlite_core.PrimaryKeyBuilder(
2150
+ gh,
2151
+ cpk.name
2152
+ );
2153
+ });
2154
+ return res;
2155
+ });
2156
+ });
2157
+ return tables;
2158
+ };
2157
2159
 
2158
2160
  // src/cli/commands/sqliteIntrospect.ts
2159
2161
  init_views();
@@ -3331,7 +3333,7 @@ var sqlitePushIntrospect = async (client, filters) => {
3331
3333
  }
3332
3334
  return false;
3333
3335
  };
3334
- const res = await fromDatabase2(client, filter2);
3336
+ const res = await fromDatabase(client, filter2);
3335
3337
  const schema = { id: originUUID, prevId: "", ...res };
3336
3338
  return { schema };
3337
3339
  };
@@ -3362,7 +3364,7 @@ var pgPushIntrospect = async (connection, filters, schemaFilters) => {
3362
3364
  }
3363
3365
  return false;
3364
3366
  };
3365
- const res = await fromDatabase(client, filter2, schemaFilters);
3367
+ const res = await fromDatabase2(client, filter2, schemaFilters);
3366
3368
  const schema = { id: originUUID, prevId: "", ...res };
3367
3369
  const { internal, ...schemaWithoutInternals } = schema;
3368
3370
  return { schema: schemaWithoutInternals };