drizzle-kit 0.20.8 → 0.20.9-1dc10f5

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