drizzle-kit 0.24.0 → 0.24.1-f7ddd08

Sign up to get free protection for your applications and to get access to all the features.
Files changed (8) hide show
  1. package/api.d.mts +10 -0
  2. package/api.d.ts +10 -0
  3. package/api.js +159 -107
  4. package/api.mjs +159 -107
  5. package/bin.cjs +1018 -478
  6. package/package.json +3 -3
  7. package/utils.js +2 -1
  8. package/utils.mjs +2 -1
package/bin.cjs CHANGED
@@ -5687,11 +5687,30 @@ var init_mysqlSchema = __esm({
5687
5687
  }
5688
5688
  });
5689
5689
 
5690
+ // src/extensions/vector.ts
5691
+ var vectorOps;
5692
+ var init_vector = __esm({
5693
+ "src/extensions/vector.ts"() {
5694
+ "use strict";
5695
+ vectorOps = [
5696
+ "vector_l2_ops",
5697
+ "vector_ip_ops",
5698
+ "vector_cosine_ops",
5699
+ "vector_l1_ops",
5700
+ "bit_hamming_ops",
5701
+ "bit_jaccard_ops",
5702
+ "halfvec_l2_ops",
5703
+ "sparsevec_l2_ops"
5704
+ ];
5705
+ }
5706
+ });
5707
+
5690
5708
  // src/serializer/pgSchema.ts
5691
5709
  var indexV2, columnV2, tableV2, enumSchemaV1, enumSchema, pgSchemaV2, references, columnV1, tableV1, pgSchemaV1, indexColumn, index2, indexV4, indexV5, indexV6, fk2, sequenceSchema, sequenceSquashed, columnV7, column2, columnSquashed, tableV32, compositePK2, uniqueConstraint2, tableV42, tableV5, tableV6, tableV7, table2, schemaHash2, kitInternals2, pgSchemaInternalV3, pgSchemaInternalV4, pgSchemaInternalV5, pgSchemaInternalV6, pgSchemaExternal, pgSchemaInternalV7, pgSchemaInternal, tableSquashed2, tableSquashedV42, pgSchemaSquashedV4, pgSchemaSquashedV6, pgSchemaSquashed, pgSchemaV3, pgSchemaV4, pgSchemaV5, pgSchemaV6, pgSchemaV7, pgSchema, backwardCompatiblePgSchema, PgSquasher, squashPgScheme, dryPg;
5692
5710
  var init_pgSchema = __esm({
5693
5711
  "src/serializer/pgSchema.ts"() {
5694
5712
  "use strict";
5713
+ init_vector();
5695
5714
  init_global();
5696
5715
  init_lib();
5697
5716
  indexV2 = objectType({
@@ -5938,7 +5957,8 @@ var init_pgSchema = __esm({
5938
5957
  objectType({
5939
5958
  isArray: booleanType().optional(),
5940
5959
  dimensions: numberType().optional(),
5941
- rawType: stringType().optional()
5960
+ rawType: stringType().optional(),
5961
+ isDefaultAnExpression: booleanType().optional()
5942
5962
  }).optional()
5943
5963
  )
5944
5964
  }).optional()
@@ -6076,7 +6096,7 @@ var init_pgSchema = __esm({
6076
6096
  squashIdx: (idx) => {
6077
6097
  index2.parse(idx);
6078
6098
  return `${idx.name};${idx.columns.map(
6079
- (c) => `${c.expression}--${c.isExpression}--${c.asc}--${c.nulls}--${c.opclass}`
6099
+ (c) => `${c.expression}--${c.isExpression}--${c.asc}--${c.nulls}--${c.opclass && vectorOps.includes(c.opclass) ? c.opclass : ""}`
6080
6100
  ).join(",,")};${idx.isUnique};${idx.concurrently};${idx.method};${idx.where};${JSON.stringify(idx.with)}`;
6081
6101
  },
6082
6102
  unsquashIdx: (input) => {
@@ -11370,9 +11390,9 @@ var init_cli = __esm({
11370
11390
  tablesFilter: unionType([stringType(), stringType().array()]).optional(),
11371
11391
  schemaFilter: unionType([stringType(), stringType().array()]).optional().default(["public"]),
11372
11392
  extensionsFilters: literalType("postgis").array().optional(),
11373
- introspectCasing: casing,
11393
+ casing,
11374
11394
  breakpoints: booleanType().optional().default(true),
11375
- database: objectType({
11395
+ migrations: objectType({
11376
11396
  prefix: prefix.optional().default("index")
11377
11397
  }).optional()
11378
11398
  }).passthrough();
@@ -17506,11 +17526,11 @@ var init_utils4 = __esm({
17506
17526
  dialect: "postgresql",
17507
17527
  out: config.out,
17508
17528
  breakpoints: config.breakpoints,
17509
- casing: config.introspectCasing,
17529
+ casing: config.casing,
17510
17530
  credentials: parsed2.data,
17511
17531
  tablesFilter,
17512
17532
  schemasFilter,
17513
- prefix: ((_a = config.database) == null ? void 0 : _a.prefix) || "index"
17533
+ prefix: ((_a = config.migrations) == null ? void 0 : _a.prefix) || "index"
17514
17534
  };
17515
17535
  }
17516
17536
  if (dialect7 === "mysql") {
@@ -17523,11 +17543,11 @@ var init_utils4 = __esm({
17523
17543
  dialect: "mysql",
17524
17544
  out: config.out,
17525
17545
  breakpoints: config.breakpoints,
17526
- casing: config.introspectCasing,
17546
+ casing: config.casing,
17527
17547
  credentials: parsed2.data,
17528
17548
  tablesFilter,
17529
17549
  schemasFilter,
17530
- prefix: ((_b = config.database) == null ? void 0 : _b.prefix) || "index"
17550
+ prefix: ((_b = config.migrations) == null ? void 0 : _b.prefix) || "index"
17531
17551
  };
17532
17552
  }
17533
17553
  if (dialect7 === "sqlite") {
@@ -17540,11 +17560,11 @@ var init_utils4 = __esm({
17540
17560
  dialect: "sqlite",
17541
17561
  out: config.out,
17542
17562
  breakpoints: config.breakpoints,
17543
- casing: config.introspectCasing,
17563
+ casing: config.casing,
17544
17564
  credentials: parsed2.data,
17545
17565
  tablesFilter,
17546
17566
  schemasFilter,
17547
- prefix: ((_c = config.database) == null ? void 0 : _c.prefix) || "index"
17567
+ prefix: ((_c = config.migrations) == null ? void 0 : _c.prefix) || "index"
17548
17568
  };
17549
17569
  }
17550
17570
  assertUnreachable(dialect7);
@@ -18372,24 +18392,6 @@ var init_pgImports = __esm({
18372
18392
  }
18373
18393
  });
18374
18394
 
18375
- // src/extensions/vector.ts
18376
- var vectorOps;
18377
- var init_vector = __esm({
18378
- "src/extensions/vector.ts"() {
18379
- "use strict";
18380
- vectorOps = [
18381
- "vector_l2_ops",
18382
- "vector_ip_ops",
18383
- "vector_cosine_ops",
18384
- "vector_l1_ops",
18385
- "bit_hamming_ops",
18386
- "bit_jaccard_ops",
18387
- "halfvec_l2_ops",
18388
- "sparsevec_l2_ops"
18389
- ];
18390
- }
18391
- });
18392
-
18393
18395
  // src/serializer/pgSerializer.ts
18394
18396
  var pgSerializer_exports = {};
18395
18397
  __export(pgSerializer_exports, {
@@ -18433,7 +18435,7 @@ function buildArrayString(array, sqlType) {
18433
18435
  }).join(",");
18434
18436
  return `{${values}}`;
18435
18437
  }
18436
- var import_drizzle_orm5, import_pg_core2, import_pg_core3, dialect5, indexName2, generatePgSnapshot, trimChar, fromDatabase2, columnToDefault, defaultForColumn;
18438
+ var import_drizzle_orm5, import_pg_core2, import_pg_core3, dialect5, indexName2, generatePgSnapshot, trimChar, fromDatabase2, defaultForColumn;
18437
18439
  var init_pgSerializer = __esm({
18438
18440
  "src/serializer/pgSerializer.ts"() {
18439
18441
  "use strict";
@@ -18556,7 +18558,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
18556
18558
  columnToSet.default = `'${buildArrayString(
18557
18559
  column7.default,
18558
18560
  sqlTypeLowered
18559
- )}'::${sqlTypeLowered}`;
18561
+ )}'`;
18560
18562
  } else {
18561
18563
  columnToSet.default = column7.default;
18562
18564
  }
@@ -18877,7 +18879,7 @@ ${withStyle.errorWarning(
18877
18879
  const sequencesInColumns = [];
18878
18880
  const all = allTables.map((row) => {
18879
18881
  return new Promise(async (res, rej) => {
18880
- var _a, _b, _c, _d;
18882
+ var _a, _b, _c, _d, _e, _f;
18881
18883
  const tableName = row.table_name;
18882
18884
  if (!tablesFilter(tableName))
18883
18885
  return res("");
@@ -18908,7 +18910,7 @@ ${withStyle.errorWarning(
18908
18910
  WHEN 'int2'::regtype THEN 'smallserial'
18909
18911
  END
18910
18912
  ELSE format_type(a.atttypid, a.atttypmod)
18911
- END AS data_type, INFORMATION_SCHEMA.COLUMNS.table_name,
18913
+ END AS data_type, INFORMATION_SCHEMA.COLUMNS.table_name, ns.nspname as type_schema,
18912
18914
  pg_get_serial_sequence('"${tableSchema}"."${tableName}"', a.attname)::regclass as seq_name, INFORMATION_SCHEMA.COLUMNS.column_name,
18913
18915
  INFORMATION_SCHEMA.COLUMNS.column_default, INFORMATION_SCHEMA.COLUMNS.data_type as additional_dt,
18914
18916
  INFORMATION_SCHEMA.COLUMNS.udt_name as enum_name,
@@ -18919,6 +18921,7 @@ ${withStyle.errorWarning(
18919
18921
  INFORMATION_SCHEMA.COLUMNS.identity_cycle
18920
18922
  FROM pg_attribute a
18921
18923
  JOIN INFORMATION_SCHEMA.COLUMNS ON INFORMATION_SCHEMA.COLUMNS.column_name = a.attname
18924
+ JOIN pg_type t ON t.oid = a.atttypid LEFT JOIN pg_namespace ns ON ns.oid = t.typnamespace
18922
18925
  WHERE a.attrelid = '"${tableSchema}"."${tableName}"'::regclass and INFORMATION_SCHEMA.COLUMNS.table_name = '${tableName}' and INFORMATION_SCHEMA.COLUMNS.table_schema = '${tableSchema}'
18923
18926
  AND a.attnum > 0
18924
18927
  AND NOT a.attisdropped
@@ -18938,30 +18941,42 @@ ${withStyle.errorWarning(
18938
18941
  }
18939
18942
  const tableForeignKeys = await db.query(
18940
18943
  `SELECT
18941
- tc.table_schema,
18942
- tc.constraint_name,
18943
- tc.table_name,
18944
- kcu.column_name,
18945
- (
18946
- SELECT ccu.table_schema
18947
- FROM information_schema.constraint_column_usage ccu
18948
- WHERE ccu.constraint_name = tc.constraint_name
18949
- LIMIT 1
18950
- ) AS foreign_table_schema,
18951
- ccu.table_name AS foreign_table_name,
18952
- ccu.column_name AS foreign_column_name,
18953
- rc.delete_rule,
18954
- rc.update_rule
18955
- FROM
18956
- information_schema.table_constraints AS tc
18957
- JOIN information_schema.key_column_usage AS kcu
18958
- ON tc.constraint_name = kcu.constraint_name
18959
- AND tc.table_schema = kcu.table_schema
18960
- JOIN information_schema.constraint_column_usage AS ccu
18961
- ON ccu.constraint_name = tc.constraint_name
18962
- JOIN information_schema.referential_constraints AS rc
18963
- ON ccu.constraint_name = rc.constraint_name
18964
- WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='${tableName}' and tc.table_schema='${tableSchema}';`
18944
+ con.contype AS constraint_type,
18945
+ nsp.nspname AS constraint_schema,
18946
+ con.conname AS constraint_name,
18947
+ rel.relname AS table_name,
18948
+ att.attname AS column_name,
18949
+ fnsp.nspname AS foreign_table_schema,
18950
+ frel.relname AS foreign_table_name,
18951
+ fatt.attname AS foreign_column_name,
18952
+ CASE con.confupdtype
18953
+ WHEN 'a' THEN 'NO ACTION'
18954
+ WHEN 'r' THEN 'RESTRICT'
18955
+ WHEN 'n' THEN 'SET NULL'
18956
+ WHEN 'c' THEN 'CASCADE'
18957
+ WHEN 'd' THEN 'SET DEFAULT'
18958
+ END AS update_rule,
18959
+ CASE con.confdeltype
18960
+ WHEN 'a' THEN 'NO ACTION'
18961
+ WHEN 'r' THEN 'RESTRICT'
18962
+ WHEN 'n' THEN 'SET NULL'
18963
+ WHEN 'c' THEN 'CASCADE'
18964
+ WHEN 'd' THEN 'SET DEFAULT'
18965
+ END AS delete_rule
18966
+ FROM
18967
+ pg_catalog.pg_constraint con
18968
+ JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid
18969
+ JOIN pg_catalog.pg_namespace nsp ON nsp.oid = con.connamespace
18970
+ LEFT JOIN pg_catalog.pg_attribute att ON att.attnum = ANY (con.conkey)
18971
+ AND att.attrelid = con.conrelid
18972
+ LEFT JOIN pg_catalog.pg_class frel ON frel.oid = con.confrelid
18973
+ LEFT JOIN pg_catalog.pg_namespace fnsp ON fnsp.oid = frel.relnamespace
18974
+ LEFT JOIN pg_catalog.pg_attribute fatt ON fatt.attnum = ANY (con.confkey)
18975
+ AND fatt.attrelid = con.confrelid
18976
+ WHERE
18977
+ nsp.nspname = '${tableSchema}'
18978
+ AND rel.relname = '${tableName}'
18979
+ AND con.contype IN ('f');`
18965
18980
  );
18966
18981
  foreignKeysCount += tableForeignKeys.length;
18967
18982
  if (progressCallback) {
@@ -18973,8 +18988,8 @@ ${withStyle.errorWarning(
18973
18988
  const columnTo = fk4.foreign_column_name;
18974
18989
  const schemaTo = fk4.foreign_table_schema;
18975
18990
  const foreignKeyName = fk4.constraint_name;
18976
- const onUpdate = fk4.update_rule.toLowerCase();
18977
- const onDelete = fk4.delete_rule.toLowerCase();
18991
+ const onUpdate = (_a = fk4.update_rule) == null ? void 0 : _a.toLowerCase();
18992
+ const onDelete = (_b = fk4.delete_rule) == null ? void 0 : _b.toLowerCase();
18978
18993
  if (typeof foreignKeysToReturn[foreignKeyName] !== "undefined") {
18979
18994
  foreignKeysToReturn[foreignKeyName].columnsFrom.push(columnFrom);
18980
18995
  foreignKeysToReturn[foreignKeyName].columnsTo.push(columnTo);
@@ -19019,6 +19034,8 @@ ${withStyle.errorWarning(
19019
19034
  const columnDimensions = columnResponse.array_dimensions;
19020
19035
  const enumType2 = columnResponse.enum_name;
19021
19036
  let columnType = columnResponse.data_type;
19037
+ const typeSchema = columnResponse.type_schema;
19038
+ const defaultValueRes = columnResponse.column_default;
19022
19039
  const isGenerated = columnResponse.is_generated === "ALWAYS";
19023
19040
  const generationExpression = columnResponse.generation_expression;
19024
19041
  const isIdentity = columnResponse.is_identity === "YES";
@@ -19049,12 +19066,7 @@ ${withStyle.errorWarning(
19049
19066
  columns: cprimaryKey.map((c) => c.column_name)
19050
19067
  };
19051
19068
  }
19052
- const defaultValue = defaultForColumn(columnResponse);
19053
- const isSerial = columnType === "serial";
19054
19069
  let columnTypeMapped = columnType;
19055
- if (columnTypeMapped.startsWith("numeric(")) {
19056
- columnTypeMapped = columnTypeMapped.replace(",", ", ");
19057
- }
19058
19070
  if (columnAdditionalDT === "ARRAY") {
19059
19071
  if (typeof internals.tables[tableName] === "undefined") {
19060
19072
  internals.tables[tableName] = {
@@ -19082,6 +19094,34 @@ ${withStyle.errorWarning(
19082
19094
  }
19083
19095
  }
19084
19096
  }
19097
+ const defaultValue = defaultForColumn(
19098
+ columnResponse,
19099
+ internals,
19100
+ tableName
19101
+ );
19102
+ if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
19103
+ if (typeof internals.tables[tableName] === "undefined") {
19104
+ internals.tables[tableName] = {
19105
+ columns: {
19106
+ [columnName]: {
19107
+ isDefaultAnExpression: true
19108
+ }
19109
+ }
19110
+ };
19111
+ } else {
19112
+ if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
19113
+ internals.tables[tableName].columns[columnName] = {
19114
+ isDefaultAnExpression: true
19115
+ };
19116
+ } else {
19117
+ internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
19118
+ }
19119
+ }
19120
+ }
19121
+ const isSerial = columnType === "serial";
19122
+ if (columnTypeMapped.startsWith("numeric(")) {
19123
+ columnTypeMapped = columnTypeMapped.replace(",", ", ");
19124
+ }
19085
19125
  if (columnAdditionalDT === "ARRAY") {
19086
19126
  for (let i2 = 1; i2 < Number(columnDimensions); i2++) {
19087
19127
  columnTypeMapped += "[]";
@@ -19095,7 +19135,7 @@ ${withStyle.errorWarning(
19095
19135
  // filter vectors, but in future we should filter any extension that was installed by user
19096
19136
  columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry"].includes(enumType2) ? enumType2 : columnTypeMapped
19097
19137
  ),
19098
- typeSchema: enumsToReturn[`${tableSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${tableSchema}.${enumType2}`].schema : void 0,
19138
+ typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0,
19099
19139
  primaryKey: primaryKey.length === 1 && cprimaryKey.length < 2,
19100
19140
  // default: isSerial ? undefined : defaultValue,
19101
19141
  notNull: columnResponse.is_nullable === "NO",
@@ -19107,13 +19147,13 @@ ${withStyle.errorWarning(
19107
19147
  minValue: stringFromDatabaseIdentityProperty(identityMinimum),
19108
19148
  maxValue: stringFromDatabaseIdentityProperty(identityMaximum),
19109
19149
  startWith: stringFromDatabaseIdentityProperty(identityStart),
19110
- cache: ((_a = sequencesToReturn[identityName]) == null ? void 0 : _a.cache) ? (_b = sequencesToReturn[identityName]) == null ? void 0 : _b.cache : ((_c = sequencesToReturn[`${tableSchema}.${identityName}`]) == null ? void 0 : _c.cache) ? (_d = sequencesToReturn[`${tableSchema}.${identityName}`]) == null ? void 0 : _d.cache : void 0,
19150
+ cache: ((_c = sequencesToReturn[identityName]) == null ? void 0 : _c.cache) ? (_d = sequencesToReturn[identityName]) == null ? void 0 : _d.cache : ((_e = sequencesToReturn[`${tableSchema}.${identityName}`]) == null ? void 0 : _e.cache) ? (_f = sequencesToReturn[`${tableSchema}.${identityName}`]) == null ? void 0 : _f.cache : void 0,
19111
19151
  cycle: identityCycle,
19112
19152
  schema: tableSchema
19113
19153
  } : void 0
19114
19154
  };
19115
19155
  if (identityName) {
19116
- delete sequencesToReturn[`${tableSchema}.${identityName}`];
19156
+ delete sequencesToReturn[`${tableSchema}.${identityName.startsWith('"') && identityName.endsWith('"') ? identityName.slice(1, -1) : identityName}`];
19117
19157
  delete sequencesToReturn[identityName];
19118
19158
  }
19119
19159
  if (!isSerial && typeof defaultValue !== "undefined") {
@@ -19267,59 +19307,72 @@ ${withStyle.errorWarning(
19267
19307
  internal: internals
19268
19308
  };
19269
19309
  };
19270
- columnToDefault = {
19271
- "numeric(": "::numeric",
19272
- // text: "::text",
19273
- // "character varying": "::character varying",
19274
- // "double precision": "::double precision",
19275
- // "time with time zone": "::time with time zone",
19276
- "time without time zone": "::time without time zone",
19277
- // "timestamp with time zone": "::timestamp with time zone",
19278
- "timestamp without time zone": "::timestamp without time zone",
19279
- "timestamp(": "::timestamp without time zone",
19280
- // date: "::date",
19281
- // interval: "::interval",
19282
- // character: "::bpchar",
19283
- // macaddr8: "::macaddr8",
19284
- // macaddr: "::macaddr",
19285
- // inet: "::inet",
19286
- // cidr: "::cidr",
19287
- // jsonb: "::jsonb",
19288
- // json: "::json",
19289
- "character(": "::bpchar"
19290
- };
19291
- defaultForColumn = (column7) => {
19310
+ defaultForColumn = (column7, internals, tableName) => {
19311
+ var _a, _b;
19312
+ const columnName = column7.attname;
19313
+ const isArray3 = ((_b = (_a = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a.columns[columnName]) == null ? void 0 : _b.isArray) ?? false;
19292
19314
  if (column7.column_default === null) {
19293
19315
  return void 0;
19294
19316
  }
19295
19317
  if (column7.data_type === "serial" || column7.data_type === "smallserial" || column7.data_type === "bigserial") {
19296
19318
  return void 0;
19297
19319
  }
19298
- const hasDifferentDefaultCast = Object.keys(columnToDefault).find((it) => column7.data_type.startsWith(it));
19320
+ if (column7.column_default.endsWith("[]")) {
19321
+ column7.column_default = column7.column_default.slice(0, -2);
19322
+ }
19323
+ column7.column_default = column7.column_default.replace(/::(.*?)(?<![^\w"])(?=$)/, "");
19299
19324
  const columnDefaultAsString = column7.column_default.toString();
19300
- if (columnDefaultAsString.endsWith(
19301
- hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : column7.data_type
19302
- )) {
19303
- const nonPrefixPart = column7.column_default.length - (hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : `::${column7.data_type}`).length - 1;
19304
- const rt = column7.column_default.toString().substring(1, nonPrefixPart);
19305
- if (/^-?[\d.]+(?:e-?\d+)?$/.test(rt) && !column7.data_type.startsWith("numeric")) {
19306
- return Number(rt);
19307
- } else if (column7.data_type === "json" || column7.data_type === "jsonb") {
19308
- const jsonWithoutSpaces = JSON.stringify(JSON.parse(rt));
19309
- return `'${jsonWithoutSpaces}'${hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : `::${column7.data_type}`}`;
19310
- } else if (column7.data_type === "boolean") {
19311
- return column7.column_default === "true";
19312
- } else {
19313
- return `'${rt}'`;
19314
- }
19315
- } else {
19316
- if (/^-?[\d.]+(?:e-?\d+)?$/.test(columnDefaultAsString) && !column7.data_type.startsWith("numeric")) {
19325
+ if (isArray3) {
19326
+ return `'{${columnDefaultAsString.slice(2, -2).split(/\s*,\s*/g).map((value) => {
19327
+ if (["integer", "smallint", "bigint", "double precision", "real"].includes(column7.data_type.slice(0, -2))) {
19328
+ return value;
19329
+ } else if (column7.data_type.startsWith("timestamp")) {
19330
+ return `${value}`;
19331
+ } else if (column7.data_type.slice(0, -2) === "interval") {
19332
+ return value.replaceAll('"', `"`);
19333
+ } else if (column7.data_type.slice(0, -2) === "boolean") {
19334
+ return value === "t" ? "true" : "false";
19335
+ } else if (["json", "jsonb"].includes(column7.data_type.slice(0, -2))) {
19336
+ return JSON.stringify(JSON.stringify(JSON.parse(JSON.parse(value)), null, 0));
19337
+ } else {
19338
+ return `"${value}"`;
19339
+ }
19340
+ }).join(",")}}'`;
19341
+ }
19342
+ if (["integer", "smallint", "bigint", "double precision", "real"].includes(column7.data_type)) {
19343
+ if (/^-?[\d.]+(?:e-?\d+)?$/.test(columnDefaultAsString)) {
19317
19344
  return Number(columnDefaultAsString);
19318
- } else if (column7.data_type === "boolean") {
19319
- return column7.column_default === "true";
19320
19345
  } else {
19321
- return `${columnDefaultAsString}`;
19346
+ if (typeof internals.tables[tableName] === "undefined") {
19347
+ internals.tables[tableName] = {
19348
+ columns: {
19349
+ [columnName]: {
19350
+ isDefaultAnExpression: true
19351
+ }
19352
+ }
19353
+ };
19354
+ } else {
19355
+ if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
19356
+ internals.tables[tableName].columns[columnName] = {
19357
+ isDefaultAnExpression: true
19358
+ };
19359
+ } else {
19360
+ internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
19361
+ }
19362
+ }
19363
+ return columnDefaultAsString;
19322
19364
  }
19365
+ } else if (column7.data_type === "json" || column7.data_type === "jsonb") {
19366
+ const jsonWithoutSpaces = JSON.stringify(JSON.parse(columnDefaultAsString.slice(1, -1)));
19367
+ return `'${jsonWithoutSpaces}'::${column7.data_type}`;
19368
+ } else if (column7.data_type === "boolean") {
19369
+ return column7.column_default === "true";
19370
+ } else if (columnDefaultAsString === "NULL") {
19371
+ return `NULL`;
19372
+ } else if (columnDefaultAsString.startsWith("'") && columnDefaultAsString.endsWith("'")) {
19373
+ return columnDefaultAsString;
19374
+ } else {
19375
+ return `${columnDefaultAsString.replace(/\\/g, "`\\")}`;
19323
19376
  }
19324
19377
  };
19325
19378
  }
@@ -22905,7 +22958,7 @@ var init_sqlgenerator = __esm({
22905
22958
  if (pgNativeTypes.has(it))
22906
22959
  return true;
22907
22960
  const toCheck = it.replace(/ /g, "");
22908
- return toCheck.startsWith("varchar(") || toCheck.startsWith("char(") || toCheck.startsWith("numeric(") || toCheck.startsWith("timestamp(") || toCheck.startsWith("intervalyear(") || toCheck.startsWith("intervalmonth(") || toCheck.startsWith("intervalday(") || toCheck.startsWith("intervalhour(") || toCheck.startsWith("intervalminute(") || toCheck.startsWith("intervalsecond(") || toCheck.startsWith("intervalyeartomonth(") || toCheck.startsWith("intervaldaytohour(") || toCheck.startsWith("intervaldaytominute(") || toCheck.startsWith("intervaldaytosecond(") || toCheck.startsWith("intervalhourtominute(") || toCheck.startsWith("intervalhourtosecond(") || toCheck.startsWith("intervalminutetosecond(") || toCheck.startsWith("vector(") || toCheck.startsWith("geometry(") || /^(\w+)(\[\d*])+$/.test(it);
22961
+ return toCheck.startsWith("varchar(") || toCheck.startsWith("char(") || toCheck.startsWith("numeric(") || toCheck.startsWith("timestamp(") || toCheck.startsWith("doubleprecision[") || toCheck.startsWith("intervalyear(") || toCheck.startsWith("intervalmonth(") || toCheck.startsWith("intervalday(") || toCheck.startsWith("intervalhour(") || toCheck.startsWith("intervalminute(") || toCheck.startsWith("intervalsecond(") || toCheck.startsWith("intervalyeartomonth(") || toCheck.startsWith("intervaldaytohour(") || toCheck.startsWith("intervaldaytominute(") || toCheck.startsWith("intervaldaytosecond(") || toCheck.startsWith("intervalhourtominute(") || toCheck.startsWith("intervalhourtosecond(") || toCheck.startsWith("intervalminutetosecond(") || toCheck.startsWith("vector(") || toCheck.startsWith("geometry(") || /^(\w+)(\[\d*])+$/.test(it);
22909
22962
  };
22910
22963
  Convertor = class {
22911
22964
  };
@@ -67495,9 +67548,9 @@ var require_dist_cjs47 = __commonJS({
67495
67548
  }
67496
67549
  });
67497
67550
 
67498
- // ../node_modules/.pnpm/@aws-sdk+token-providers@3.577.0_@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/token-providers/dist-cjs/index.js
67551
+ // ../node_modules/.pnpm/@aws-sdk+token-providers@3.577.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0_/node_modules/@aws-sdk/token-providers/dist-cjs/index.js
67499
67552
  var require_dist_cjs48 = __commonJS({
67500
- "../node_modules/.pnpm/@aws-sdk+token-providers@3.577.0_@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/token-providers/dist-cjs/index.js"(exports2, module2) {
67553
+ "../node_modules/.pnpm/@aws-sdk+token-providers@3.577.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0_/node_modules/@aws-sdk/token-providers/dist-cjs/index.js"(exports2, module2) {
67501
67554
  "use strict";
67502
67555
  var __create3 = Object.create;
67503
67556
  var __defProp3 = Object.defineProperty;
@@ -67675,9 +67728,9 @@ var require_dist_cjs48 = __commonJS({
67675
67728
  }
67676
67729
  });
67677
67730
 
67678
- // ../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.583.0_@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js
67731
+ // ../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.583.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0_/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js
67679
67732
  var require_dist_cjs49 = __commonJS({
67680
- "../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.583.0_@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js"(exports2, module2) {
67733
+ "../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.583.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0_/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js"(exports2, module2) {
67681
67734
  "use strict";
67682
67735
  var __defProp3 = Object.defineProperty;
67683
67736
  var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
@@ -69952,9 +70005,9 @@ var require_dist_cjs52 = __commonJS({
69952
70005
  }
69953
70006
  });
69954
70007
 
69955
- // ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.583.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js
70008
+ // ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.583.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts_n4voux45fymjghrdt4o3r57x4m/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js
69956
70009
  var require_dist_cjs53 = __commonJS({
69957
- "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.583.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js"(exports2, module2) {
70010
+ "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.583.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts_n4voux45fymjghrdt4o3r57x4m/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js"(exports2, module2) {
69958
70011
  "use strict";
69959
70012
  var __create3 = Object.create;
69960
70013
  var __defProp3 = Object.defineProperty;
@@ -70122,9 +70175,9 @@ var require_dist_cjs53 = __commonJS({
70122
70175
  }
70123
70176
  });
70124
70177
 
70125
- // ../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.583.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js
70178
+ // ../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.583.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-st_qaylqvuvqkdeetlwmxiq34v6lq/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js
70126
70179
  var require_dist_cjs54 = __commonJS({
70127
- "../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.583.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js"(exports2, module2) {
70180
+ "../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.583.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-st_qaylqvuvqkdeetlwmxiq34v6lq/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js"(exports2, module2) {
70128
70181
  "use strict";
70129
70182
  var __create3 = Object.create;
70130
70183
  var __defProp3 = Object.defineProperty;
@@ -74154,7 +74207,7 @@ var init_pgIntrospect = __esm({
74154
74207
  });
74155
74208
 
74156
74209
  // src/introspect-sqlite.ts
74157
- var sqliteImportsList, indexName3, objToStatement2, relations, withCasing, schemaToTypeScript, isCyclic, isSelf, mapColumnDefault, column4, createTableColumns, createTableIndexes, createTableUniques, createTablePKs, createTableFKs;
74210
+ var sqliteImportsList, indexName3, objToStatement2, relations, escapeColumnKey, withCasing, schemaToTypeScript, isCyclic, isSelf, mapColumnDefault, column4, createTableColumns, createTableIndexes, createTableUniques, createTablePKs, createTableFKs;
74158
74211
  var init_introspect_sqlite = __esm({
74159
74212
  "src/introspect-sqlite.ts"() {
74160
74213
  "use strict";
@@ -74181,12 +74234,18 @@ var init_introspect_sqlite = __esm({
74181
74234
  return statement;
74182
74235
  };
74183
74236
  relations = /* @__PURE__ */ new Set();
74237
+ escapeColumnKey = (value) => {
74238
+ if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
74239
+ return `"${value}"`;
74240
+ }
74241
+ return value;
74242
+ };
74184
74243
  withCasing = (value, casing2) => {
74185
- if (typeof casing2 === "undefined") {
74186
- return value;
74244
+ if (casing2 === "preserve") {
74245
+ return escapeColumnKey(value);
74187
74246
  }
74188
74247
  if (casing2 === "camel") {
74189
- return value.camelCase();
74248
+ return escapeColumnKey(value.camelCase());
74190
74249
  }
74191
74250
  return value;
74192
74251
  };
@@ -75184,7 +75243,7 @@ var require_pluralize = __commonJS({
75184
75243
  });
75185
75244
 
75186
75245
  // src/introspect-mysql.ts
75187
- var mysqlImportsList, objToStatement22, timeConfig, binaryConfig, importsPatch, relations2, prepareCasing, schemaToTypeScript2, isCyclic2, isSelf2, mapColumnDefault2, mapColumnDefaultForJson, column5, createTableColumns2, createTableIndexes2, createTableUniques2, createTablePKs2, createTableFKs2;
75246
+ var mysqlImportsList, objToStatement22, timeConfig, binaryConfig, importsPatch, relations2, escapeColumnKey2, prepareCasing, schemaToTypeScript2, isCyclic2, isSelf2, mapColumnDefault2, mapColumnDefaultForJson, column5, createTableColumns2, createTableIndexes2, createTableUniques2, createTablePKs2, createTableFKs2;
75188
75247
  var init_introspect_mysql = __esm({
75189
75248
  "src/introspect-mysql.ts"() {
75190
75249
  "use strict";
@@ -75255,14 +75314,20 @@ var init_introspect_mysql = __esm({
75255
75314
  "timestamp without time zone": "timestamp"
75256
75315
  };
75257
75316
  relations2 = /* @__PURE__ */ new Set();
75317
+ escapeColumnKey2 = (value) => {
75318
+ if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
75319
+ return `"${value}"`;
75320
+ }
75321
+ return value;
75322
+ };
75258
75323
  prepareCasing = (casing2) => (value) => {
75259
- if (typeof casing2 === "undefined") {
75260
- return value;
75324
+ if (casing2 === "preserve") {
75325
+ return escapeColumnKey2(value);
75261
75326
  }
75262
75327
  if (casing2 === "camel") {
75263
- return value.camelCase();
75328
+ return escapeColumnKey2(value.camelCase());
75264
75329
  }
75265
- return value;
75330
+ return escapeColumnKey2(value);
75266
75331
  };
75267
75332
  schemaToTypeScript2 = (schema5, casing2) => {
75268
75333
  const withCasing4 = prepareCasing(casing2);
@@ -75728,7 +75793,33 @@ import { sql } from "drizzle-orm"
75728
75793
  });
75729
75794
 
75730
75795
  // src/introspect-pg.ts
75731
- var import_drizzle_orm8, import_relations, pgImportsList, objToStatement23, timeConfig2, possibleIntervals, intervalStrToObj, intervalConfig, importsPatch2, relations3, withCasing2, paramNameFor, schemaToTypeScript3, isCyclic3, isSelf3, column6, dimensionsInArray, createTableColumns3, createTableIndexes3, createTablePKs3, createTableUniques3, createTableFKs3;
75796
+ function generateIdentityParams(identity) {
75797
+ let paramsObj = `{ name: "${identity.name}"`;
75798
+ if (identity == null ? void 0 : identity.startWith) {
75799
+ paramsObj += `, startWith: ${identity.startWith}`;
75800
+ }
75801
+ if (identity == null ? void 0 : identity.increment) {
75802
+ paramsObj += `, increment: ${identity.increment}`;
75803
+ }
75804
+ if (identity == null ? void 0 : identity.minValue) {
75805
+ paramsObj += `, minValue: ${identity.minValue}`;
75806
+ }
75807
+ if (identity == null ? void 0 : identity.maxValue) {
75808
+ paramsObj += `, maxValue: ${identity.maxValue}`;
75809
+ }
75810
+ if (identity == null ? void 0 : identity.cache) {
75811
+ paramsObj += `, cache: ${identity.cache}`;
75812
+ }
75813
+ if (identity == null ? void 0 : identity.cycle) {
75814
+ paramsObj += `, cycle: true`;
75815
+ }
75816
+ paramsObj += " }";
75817
+ if ((identity == null ? void 0 : identity.type) === "always") {
75818
+ return `.generatedAlwaysAsIdentity(${paramsObj})`;
75819
+ }
75820
+ return `.generatedByDefaultAsIdentity(${paramsObj})`;
75821
+ }
75822
+ var import_drizzle_orm8, import_relations, pgImportsList, timeConfig2, possibleIntervals, intervalStrToObj, intervalConfig, mapColumnDefault3, importsPatch2, relations3, escapeColumnKey3, withCasing2, paramNameFor, schemaToTypeScript3, isCyclic3, isSelf3, buildArrayDefault, mapDefault, column6, dimensionsInArray, createTableColumns3, createTableIndexes3, createTablePKs3, createTableUniques3, createTableFKs3;
75732
75823
  var init_introspect_pg = __esm({
75733
75824
  "src/introspect-pg.ts"() {
75734
75825
  "use strict";
@@ -75772,16 +75863,6 @@ var init_introspect_pg = __esm({
75772
75863
  "line",
75773
75864
  "geometry"
75774
75865
  ]);
75775
- objToStatement23 = (json) => {
75776
- json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
75777
- const keys = Object.keys(json);
75778
- if (keys.length === 0)
75779
- return;
75780
- let statement = "{ ";
75781
- statement += keys.map((it) => `${it}: "${json[it]}"`).join(", ");
75782
- statement += " }";
75783
- return statement;
75784
- };
75785
75866
  timeConfig2 = (json) => {
75786
75867
  json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
75787
75868
  const keys = Object.keys(json);
@@ -75841,6 +75922,12 @@ var init_introspect_pg = __esm({
75841
75922
  statement += " }";
75842
75923
  return statement;
75843
75924
  };
75925
+ mapColumnDefault3 = (defaultValue, isExpression) => {
75926
+ if (isExpression) {
75927
+ return `sql\`${defaultValue}\``;
75928
+ }
75929
+ return defaultValue;
75930
+ };
75844
75931
  importsPatch2 = {
75845
75932
  "double precision": "doublePrecision",
75846
75933
  "timestamp without time zone": "timestamp",
@@ -75849,12 +75936,18 @@ var init_introspect_pg = __esm({
75849
75936
  "time with time zone": "time"
75850
75937
  };
75851
75938
  relations3 = /* @__PURE__ */ new Set();
75939
+ escapeColumnKey3 = (value) => {
75940
+ if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
75941
+ return `"${value}"`;
75942
+ }
75943
+ return value;
75944
+ };
75852
75945
  withCasing2 = (value, casing2) => {
75853
75946
  if (casing2 === "preserve") {
75854
- return value;
75947
+ return escapeColumnKey3(value);
75855
75948
  }
75856
75949
  if (casing2 === "camel") {
75857
- return value.camelCase();
75950
+ return escapeColumnKey3(value.camelCase());
75858
75951
  }
75859
75952
  assertUnreachable(casing2);
75860
75953
  };
@@ -75874,7 +75967,13 @@ var init_introspect_pg = __esm({
75874
75967
  return [it[0], withCasing2(it[1], casing2)];
75875
75968
  })
75876
75969
  );
75877
- const enumTypes = new Set(Object.values(schema5.enums).map((it) => it.name));
75970
+ const enumTypes = Object.values(schema5.enums).reduce(
75971
+ (acc, cur) => {
75972
+ acc.add(`${cur.schema}.${cur.name}`);
75973
+ return acc;
75974
+ },
75975
+ /* @__PURE__ */ new Set()
75976
+ );
75878
75977
  const imports = Object.values(schema5.tables).reduce(
75879
75978
  (res, it) => {
75880
75979
  const idxImports = Object.values(it.indexes).map((idx) => idx.isUnique ? "uniqueIndex" : "index");
@@ -75895,11 +75994,9 @@ var init_introspect_pg = __esm({
75895
75994
  res.pg.push(...fkImpots);
75896
75995
  res.pg.push(...pkImports);
75897
75996
  res.pg.push(...uniqueImports);
75898
- if (enumTypes.size > 0) {
75899
- res.pg.push("pgEnum");
75900
- }
75901
75997
  const columnImports = Object.values(it.columns).map((col) => {
75902
- let patched = importsPatch2[col.type] || col.type;
75998
+ let patched = (importsPatch2[col.type] || col.type).replace("[]", "");
75999
+ patched = patched === "double precision" ? "doublePrecision" : patched;
75903
76000
  patched = patched.startsWith("varchar(") ? "varchar" : patched;
75904
76001
  patched = patched.startsWith("char(") ? "char" : patched;
75905
76002
  patched = patched.startsWith("numeric(") ? "numeric" : patched;
@@ -75916,12 +76013,54 @@ var init_introspect_pg = __esm({
75916
76013
  },
75917
76014
  { pg: [] }
75918
76015
  );
76016
+ Object.values(schema5.sequences).forEach((it) => {
76017
+ if (it.schema && it.schema !== "public" && it.schema !== "") {
76018
+ imports.pg.push("pgSchema");
76019
+ } else if (it.schema === "public") {
76020
+ imports.pg.push("pgSequence");
76021
+ }
76022
+ });
76023
+ Object.values(schema5.enums).forEach((it) => {
76024
+ if (it.schema && it.schema !== "public" && it.schema !== "") {
76025
+ imports.pg.push("pgSchema");
76026
+ } else if (it.schema === "public") {
76027
+ imports.pg.push("pgEnum");
76028
+ }
76029
+ });
75919
76030
  const enumStatements = Object.values(schema5.enums).map((it) => {
75920
76031
  const enumSchema3 = schemas[it.schema];
75921
76032
  const paramName = paramNameFor(it.name, enumSchema3);
75922
76033
  const func = enumSchema3 ? `${enumSchema3}.enum` : "pgEnum";
75923
76034
  const values = Object.values(it.values).map((it2) => `'${it2}'`).join(", ");
75924
76035
  return `export const ${withCasing2(paramName, casing2)} = ${func}("${it.name}", [${values}])
76036
+ `;
76037
+ }).join("").concat("\n");
76038
+ const sequencesStatements = Object.values(schema5.sequences).map((it) => {
76039
+ const seqSchema = schemas[it.schema];
76040
+ const paramName = paramNameFor(it.name, seqSchema);
76041
+ const func = seqSchema ? `${seqSchema}.sequence` : "pgSequence";
76042
+ let params = "";
76043
+ if (it.startWith) {
76044
+ params += `, startWith: "${it.startWith}"`;
76045
+ }
76046
+ if (it.increment) {
76047
+ params += `, increment: "${it.increment}"`;
76048
+ }
76049
+ if (it.minValue) {
76050
+ params += `, minValue: "${it.minValue}"`;
76051
+ }
76052
+ if (it.maxValue) {
76053
+ params += `, maxValue: "${it.maxValue}"`;
76054
+ }
76055
+ if (it.cache) {
76056
+ params += `, cache: "${it.cache}"`;
76057
+ }
76058
+ if (it.cycle) {
76059
+ params += `, cycle: true`;
76060
+ } else {
76061
+ params += `, cycle: false`;
76062
+ }
76063
+ return `export const ${withCasing2(paramName, casing2)} = ${func}("${it.name}"${params ? `, { ${params.trimChar(",")} }` : ""})
75925
76064
  `;
75926
76065
  }).join("").concat("\n");
75927
76066
  const schemaStatements = Object.entries(schemas).map((it) => {
@@ -75944,10 +76083,7 @@ var init_introspect_pg = __esm({
75944
76083
  schema5.internal
75945
76084
  );
75946
76085
  statement += "}";
75947
- const filteredFKs = Object.values(table4.foreignKeys).filter((it) => {
75948
- return it.columnsFrom.length > 1 || isSelf3(it);
75949
- });
75950
- if (Object.keys(table4.indexes).length > 0 || filteredFKs.length > 0 || Object.keys(table4.compositePrimaryKeys).length > 0 || Object.keys(table4.uniqueConstraints).length > 0) {
76086
+ if (Object.keys(table4.indexes).length > 0 || Object.values(table4.foreignKeys).length > 0 || Object.keys(table4.compositePrimaryKeys).length > 0 || Object.keys(table4.uniqueConstraints).length > 0) {
75951
76087
  statement += ",\n";
75952
76088
  statement += "(table) => {\n";
75953
76089
  statement += " return {\n";
@@ -75956,7 +76092,7 @@ var init_introspect_pg = __esm({
75956
76092
  Object.values(table4.indexes),
75957
76093
  casing2
75958
76094
  );
75959
- statement += createTableFKs3(Object.values(filteredFKs), schemas, casing2);
76095
+ statement += createTableFKs3(Object.values(table4.foreignKeys), schemas, casing2);
75960
76096
  statement += createTablePKs3(
75961
76097
  Object.values(table4.compositePrimaryKeys),
75962
76098
  casing2
@@ -75980,6 +76116,7 @@ var init_introspect_pg = __esm({
75980
76116
  `;
75981
76117
  let decalrations = schemaStatements;
75982
76118
  decalrations += enumStatements;
76119
+ decalrations += sequencesStatements;
75983
76120
  decalrations += "\n";
75984
76121
  decalrations += tableStatements.join("\n\n");
75985
76122
  const file = importsTs + decalrations;
@@ -75998,9 +76135,120 @@ var init_introspect_pg = __esm({
75998
76135
  isSelf3 = (fk4) => {
75999
76136
  return fk4.tableFrom === fk4.tableTo;
76000
76137
  };
76001
- column6 = (tableName, type, name, enumTypes, casing2, defaultValue, internals) => {
76002
- var _a;
76003
- const lowered = type.toLowerCase();
76138
+ buildArrayDefault = (defaultValue, typeName) => {
76139
+ if (typeof defaultValue === "string" && !(defaultValue.startsWith("{") || defaultValue.startsWith("'{"))) {
76140
+ return `sql\`${defaultValue}\``;
76141
+ }
76142
+ defaultValue = defaultValue.substring(2, defaultValue.length - 2);
76143
+ return `[${defaultValue.split(/\s*,\s*/g).map((value) => {
76144
+ if (typeName === "json" || typeName === "jsonb") {
76145
+ return value.substring(1, value.length - 1).replaceAll("\\", "");
76146
+ }
76147
+ return value;
76148
+ }).join(", ")}]`;
76149
+ };
76150
+ mapDefault = (tableName, type, name, enumTypes, typeSchema, defaultValue, internals) => {
76151
+ var _a, _b, _c, _d;
76152
+ const isExpression = ((_b = (_a = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a.columns[name]) == null ? void 0 : _b.isDefaultAnExpression) ?? false;
76153
+ const isArray3 = ((_d = (_c = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _c.columns[name]) == null ? void 0 : _d.isArray) ?? false;
76154
+ const lowered = type.toLowerCase().replace("[]", "");
76155
+ if (isArray3) {
76156
+ return typeof defaultValue !== "undefined" ? `.default(${buildArrayDefault(defaultValue, lowered)})` : "";
76157
+ }
76158
+ if (enumTypes.has(`${typeSchema}.${type.replace("[]", "")}`)) {
76159
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76160
+ }
76161
+ if (lowered.startsWith("integer")) {
76162
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76163
+ }
76164
+ if (lowered.startsWith("smallint")) {
76165
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76166
+ }
76167
+ if (lowered.startsWith("bigint")) {
76168
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76169
+ }
76170
+ if (lowered.startsWith("boolean")) {
76171
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76172
+ }
76173
+ if (lowered.startsWith("double precision")) {
76174
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76175
+ }
76176
+ if (lowered.startsWith("real")) {
76177
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76178
+ }
76179
+ if (lowered.startsWith("uuid")) {
76180
+ return defaultValue === "gen_random_uuid()" ? ".defaultRandom()" : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
76181
+ }
76182
+ if (lowered.startsWith("numeric")) {
76183
+ defaultValue = defaultValue ? defaultValue.startsWith(`'`) && defaultValue.endsWith(`'`) ? defaultValue.substring(1, defaultValue.length - 1) : defaultValue : void 0;
76184
+ return defaultValue ? `.default('${mapColumnDefault3(defaultValue, isExpression)}')` : "";
76185
+ }
76186
+ if (lowered.startsWith("timestamp")) {
76187
+ return defaultValue === "now()" ? ".defaultNow()" : defaultValue === "CURRENT_TIMESTAMP" ? ".default(sql`CURRENT_TIMESTAMP`)" : defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76188
+ }
76189
+ if (lowered.startsWith("time")) {
76190
+ return defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76191
+ }
76192
+ if (lowered.startsWith("interval")) {
76193
+ return defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76194
+ }
76195
+ if (lowered === "date") {
76196
+ return defaultValue === "now()" ? ".defaultNow()" : defaultValue === "CURRENT_DATE" ? `.default(sql\`${defaultValue}\`)` : defaultValue ? `.default(${defaultValue})` : "";
76197
+ }
76198
+ if (lowered.startsWith("text")) {
76199
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76200
+ }
76201
+ if (lowered.startsWith("jsonb")) {
76202
+ const def = typeof defaultValue !== "undefined" ? defaultValue.replace(/::(.*?)(?<![^\w"])(?=$)/, "").slice(1, -1) : null;
76203
+ return defaultValue ? `.default(${def})` : "";
76204
+ }
76205
+ if (lowered.startsWith("json")) {
76206
+ const def = defaultValue ? defaultValue.replace(/::(.*?)(?<![^\w"])(?=$)/, "").slice(1, -1) : null;
76207
+ return typeof defaultValue !== "undefined" ? `.default(${def})` : "";
76208
+ }
76209
+ if (lowered.startsWith("inet")) {
76210
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76211
+ }
76212
+ if (lowered.startsWith("cidr")) {
76213
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76214
+ }
76215
+ if (lowered.startsWith("macaddr8")) {
76216
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76217
+ }
76218
+ if (lowered.startsWith("macaddr")) {
76219
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76220
+ }
76221
+ if (lowered.startsWith("varchar")) {
76222
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76223
+ }
76224
+ if (lowered.startsWith("point")) {
76225
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76226
+ }
76227
+ if (lowered.startsWith("line")) {
76228
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76229
+ }
76230
+ if (lowered.startsWith("geometry")) {
76231
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76232
+ }
76233
+ if (lowered.startsWith("vector")) {
76234
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76235
+ }
76236
+ if (lowered.startsWith("char")) {
76237
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76238
+ }
76239
+ return "";
76240
+ };
76241
+ column6 = (tableName, type, name, enumTypes, typeSchema, casing2, defaultValue, internals) => {
76242
+ var _a, _b;
76243
+ const isExpression = ((_b = (_a = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a.columns[name]) == null ? void 0 : _b.isDefaultAnExpression) ?? false;
76244
+ const lowered = type.toLowerCase().replace("[]", "");
76245
+ if (enumTypes.has(`${typeSchema}.${type.replace("[]", "")}`)) {
76246
+ let out = `${withCasing2(name, casing2)}: ${withCasing2(
76247
+ paramNameFor(type.replace("[]", ""), typeSchema),
76248
+ casing2
76249
+ )}("${name}")`;
76250
+ return out;
76251
+ }
76004
76252
  if (lowered.startsWith("serial")) {
76005
76253
  return `${withCasing2(name, casing2)}: serial("${name}")`;
76006
76254
  }
@@ -76015,39 +76263,32 @@ var init_introspect_pg = __esm({
76015
76263
  }
76016
76264
  if (lowered.startsWith("integer")) {
76017
76265
  let out = `${withCasing2(name, casing2)}: integer("${name}")`;
76018
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76019
76266
  return out;
76020
76267
  }
76021
76268
  if (lowered.startsWith("smallint")) {
76022
76269
  let out = `${withCasing2(name, casing2)}: smallint("${name}")`;
76023
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76024
76270
  return out;
76025
76271
  }
76026
76272
  if (lowered.startsWith("bigint")) {
76027
76273
  let out = `// You can use { mode: "bigint" } if numbers are exceeding js number limitations
76028
76274
  `;
76029
76275
  out += `${withCasing2(name, casing2)}: bigint("${name}", { mode: "number" })`;
76030
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76031
76276
  return out;
76032
76277
  }
76033
76278
  if (lowered.startsWith("boolean")) {
76034
76279
  let out = `${withCasing2(name, casing2)}: boolean("${name}")`;
76035
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76036
76280
  return out;
76037
76281
  }
76038
76282
  if (lowered.startsWith("double precision")) {
76039
76283
  let out = `${withCasing2(name, casing2)}: doublePrecision("${name}")`;
76040
- out += defaultValue ? `.default(${defaultValue})` : "";
76041
76284
  return out;
76042
76285
  }
76043
76286
  if (lowered.startsWith("real")) {
76044
76287
  let out = `${withCasing2(name, casing2)}: real("${name}")`;
76045
- out += defaultValue ? `.default(${defaultValue})` : "";
76046
76288
  return out;
76047
76289
  }
76048
76290
  if (lowered.startsWith("uuid")) {
76049
76291
  let out = `${withCasing2(name, casing2)}: uuid("${name}")`;
76050
- out += defaultValue === "gen_random_uuid()" ? ".defaultRandom()" : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
76051
76292
  return out;
76052
76293
  }
76053
76294
  if (lowered.startsWith("numeric")) {
@@ -76057,8 +76298,6 @@ var init_introspect_pg = __esm({
76057
76298
  params = { precision, scale };
76058
76299
  }
76059
76300
  let out = params ? `${withCasing2(name, casing2)}: numeric("${name}", ${timeConfig2(params)})` : `${withCasing2(name, casing2)}: numeric("${name}")`;
76060
- defaultValue = defaultValue ? defaultValue.startsWith(`'`) && defaultValue.endsWith(`'`) ? defaultValue.substring(1, defaultValue.length - 1) : defaultValue : void 0;
76061
- out += defaultValue ? `.default('${defaultValue}')` : "";
76062
76301
  return out;
76063
76302
  }
76064
76303
  if (lowered.startsWith("timestamp")) {
@@ -76073,8 +76312,6 @@ var init_introspect_pg = __esm({
76073
76312
  mode: "'string'"
76074
76313
  });
76075
76314
  let out = params ? `${withCasing2(name, casing2)}: timestamp("${name}", ${params})` : `${withCasing2(name, casing2)}: timestamp("${name}")`;
76076
- defaultValue = defaultValue === "now()" || defaultValue === "CURRENT_TIMESTAMP" ? ".defaultNow()" : defaultValue ? `.default(${defaultValue})` : "";
76077
- out += defaultValue;
76078
76315
  return out;
76079
76316
  }
76080
76317
  if (lowered.startsWith("time")) {
@@ -76085,63 +76322,46 @@ var init_introspect_pg = __esm({
76085
76322
  precision = precision ? precision : null;
76086
76323
  const params = timeConfig2({ precision, withTimezone });
76087
76324
  let out = params ? `${withCasing2(name, casing2)}: time("${name}", ${params})` : `${withCasing2(name, casing2)}: time("${name}")`;
76088
- defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${defaultValue})` : "";
76089
- out += defaultValue;
76090
76325
  return out;
76091
76326
  }
76092
76327
  if (lowered.startsWith("interval")) {
76093
76328
  const params = intervalConfig(lowered);
76094
76329
  let out = params ? `${withCasing2(name, casing2)}: interval("${name}", ${params})` : `${withCasing2(name, casing2)}: interval("${name}")`;
76095
- out += defaultValue ? `.default(${defaultValue})` : "";
76096
76330
  return out;
76097
76331
  }
76098
76332
  if (lowered === "date") {
76099
76333
  let out = `${withCasing2(name, casing2)}: date("${name}")`;
76100
- defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue === "CURRENT_DATE" ? `.default(sql\`${defaultValue}\`)` : defaultValue ? `.default(${defaultValue})` : "";
76101
- out += defaultValue;
76102
76334
  return out;
76103
76335
  }
76104
76336
  if (lowered.startsWith("text")) {
76105
76337
  let out = `${withCasing2(name, casing2)}: text("${name}")`;
76106
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76107
76338
  return out;
76108
76339
  }
76109
- if (lowered === "json") {
76110
- let out = `${withCasing2(name, casing2)}: json("${name}")`;
76111
- defaultValue = (defaultValue == null ? void 0 : defaultValue.endsWith("::json")) ? defaultValue.substring(1, defaultValue.length - 7) : defaultValue;
76112
- const def = defaultValue ? defaultValue : null;
76113
- out += typeof defaultValue !== "undefined" ? `.default(${def})` : "";
76340
+ if (lowered.startsWith("jsonb")) {
76341
+ let out = `${withCasing2(name, casing2)}: jsonb("${name}")`;
76114
76342
  return out;
76115
76343
  }
76116
- if (lowered === "jsonb") {
76117
- let out = `${withCasing2(name, casing2)}: jsonb("${name}")`;
76118
- defaultValue = (defaultValue == null ? void 0 : defaultValue.endsWith("::jsonb")) ? defaultValue.substring(1, defaultValue.length - 8) : defaultValue;
76119
- const def = typeof defaultValue !== "undefined" ? defaultValue : null;
76120
- out += defaultValue ? `.default(${def})` : "";
76344
+ if (lowered.startsWith("json")) {
76345
+ let out = `${withCasing2(name, casing2)}: json("${name}")`;
76121
76346
  return out;
76122
76347
  }
76123
76348
  if (lowered.startsWith("inet")) {
76124
76349
  let out = `${withCasing2(name, casing2)}: inet("${name}")`;
76125
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76126
76350
  return out;
76127
76351
  }
76128
76352
  if (lowered.startsWith("cidr")) {
76129
76353
  let out = `${withCasing2(name, casing2)}: cidr("${name}")`;
76130
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76131
- return out;
76132
- }
76133
- if (lowered.startsWith("macaddr")) {
76134
- let out = `${withCasing2(name, casing2)}: macaddr("${name}")`;
76135
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76136
76354
  return out;
76137
76355
  }
76138
76356
  if (lowered.startsWith("macaddr8")) {
76139
76357
  let out = `${withCasing2(name, casing2)}: macaddr8("${name}")`;
76140
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76358
+ return out;
76359
+ }
76360
+ if (lowered.startsWith("macaddr")) {
76361
+ let out = `${withCasing2(name, casing2)}: macaddr("${name}")`;
76141
76362
  return out;
76142
76363
  }
76143
76364
  if (lowered.startsWith("varchar")) {
76144
- const split = lowered.split(" ");
76145
76365
  let out;
76146
76366
  if (lowered.length !== 7) {
76147
76367
  out = `${withCasing2(
@@ -76154,17 +76374,14 @@ var init_introspect_pg = __esm({
76154
76374
  } else {
76155
76375
  out = `${withCasing2(name, casing2)}: varchar("${name}")`;
76156
76376
  }
76157
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76158
76377
  return out;
76159
76378
  }
76160
76379
  if (lowered.startsWith("point")) {
76161
76380
  let out = `${withCasing2(name, casing2)}: point("${name}")`;
76162
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76163
76381
  return out;
76164
76382
  }
76165
76383
  if (lowered.startsWith("line")) {
76166
76384
  let out = `${withCasing2(name, casing2)}: point("${name}")`;
76167
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76168
76385
  return out;
76169
76386
  }
76170
76387
  if (lowered.startsWith("geometry")) {
@@ -76182,7 +76399,6 @@ var init_introspect_pg = __esm({
76182
76399
  } else {
76183
76400
  out = `${withCasing2(name, casing2)}: geometry("${name}")`;
76184
76401
  }
76185
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76186
76402
  if (isGeoUnknown) {
76187
76403
  let unknown2 = `// TODO: failed to parse geometry type because found more than 2 options inside geometry function '${type}'
76188
76404
  // Introspect is currently supporting only type and srid options
@@ -76193,7 +76409,6 @@ var init_introspect_pg = __esm({
76193
76409
  return out;
76194
76410
  }
76195
76411
  if (lowered.startsWith("vector")) {
76196
- const split = lowered.split(" ");
76197
76412
  let out;
76198
76413
  if (lowered.length !== 6) {
76199
76414
  out = `${withCasing2(
@@ -76206,7 +76421,6 @@ var init_introspect_pg = __esm({
76206
76421
  } else {
76207
76422
  out = `${withCasing2(name, casing2)}: vector("${name}")`;
76208
76423
  }
76209
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76210
76424
  return out;
76211
76425
  }
76212
76426
  if (lowered.startsWith("char")) {
@@ -76222,26 +76436,6 @@ var init_introspect_pg = __esm({
76222
76436
  } else {
76223
76437
  out = `${withCasing2(name, casing2)}: char("${name}")`;
76224
76438
  }
76225
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76226
- return out;
76227
- }
76228
- const columnInternals = (_a = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a.columns[name];
76229
- if (typeof columnInternals !== "undefined") {
76230
- if (columnInternals.isArray && columnInternals.rawType && enumTypes.has(columnInternals.rawType)) {
76231
- let out = `${withCasing2(columnInternals.rawType, casing2)}: ${withCasing2(
76232
- columnInternals.rawType,
76233
- casing2
76234
- )}("${name}")`;
76235
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76236
- return out;
76237
- }
76238
- }
76239
- if (enumTypes.has(type)) {
76240
- let out = `${withCasing2(name, casing2)}: ${withCasing2(
76241
- type,
76242
- casing2
76243
- )}("${name}")`;
76244
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76245
76439
  return out;
76246
76440
  }
76247
76441
  let unknown = `// TODO: failed to parse database type '${type}'
@@ -76276,6 +76470,7 @@ var init_introspect_pg = __esm({
76276
76470
  it.type,
76277
76471
  it.name,
76278
76472
  enumTypes,
76473
+ it.typeSchema ?? "public",
76279
76474
  casing2,
76280
76475
  it.default,
76281
76476
  internals
@@ -76287,59 +76482,19 @@ var init_introspect_pg = __esm({
76287
76482
  (_d = (_c = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _c.columns[it.name]) == null ? void 0 : _d.dimensions
76288
76483
  );
76289
76484
  }
76485
+ statement += mapDefault(
76486
+ tableName,
76487
+ it.type,
76488
+ it.name,
76489
+ enumTypes,
76490
+ it.typeSchema ?? "public",
76491
+ it.default,
76492
+ internals
76493
+ );
76290
76494
  statement += it.primaryKey ? ".primaryKey()" : "";
76291
76495
  statement += it.notNull && !it.identity ? ".notNull()" : "";
76292
- function generateIdentityParams(identity) {
76293
- let paramsObj = `{ name: "${identity.name}"`;
76294
- if (identity == null ? void 0 : identity.startWith) {
76295
- paramsObj += `, startWith: ${identity.startWith}`;
76296
- }
76297
- if (identity == null ? void 0 : identity.increment) {
76298
- paramsObj += `, increment: ${identity.increment}`;
76299
- }
76300
- if (identity == null ? void 0 : identity.minValue) {
76301
- paramsObj += `, minValue: ${identity.minValue}`;
76302
- }
76303
- if (identity == null ? void 0 : identity.maxValue) {
76304
- paramsObj += `, maxValue: ${identity.maxValue}`;
76305
- }
76306
- if (identity == null ? void 0 : identity.cache) {
76307
- paramsObj += `, cache: ${identity.cache}`;
76308
- }
76309
- if (identity == null ? void 0 : identity.cycle) {
76310
- paramsObj += `, cycle: true`;
76311
- }
76312
- paramsObj += " }";
76313
- if ((identity == null ? void 0 : identity.type) === "always") {
76314
- return `.generatedAlwaysAsIdentity(${paramsObj})`;
76315
- }
76316
- return `.generatedByDefaultAsIdentity(${paramsObj})`;
76317
- }
76318
76496
  statement += it.identity ? generateIdentityParams(it.identity) : "";
76319
76497
  statement += it.generated ? `.generatedAlwaysAs(sql\`${it.generated.as}\`)` : "";
76320
- const fks2 = fkByColumnName[it.name];
76321
- if (fks2) {
76322
- const fksStatement = fks2.map((it2) => {
76323
- const onDelete = it2.onDelete && it2.onDelete !== "no action" ? it2.onDelete : null;
76324
- const onUpdate = it2.onUpdate && it2.onUpdate !== "no action" ? it2.onUpdate : null;
76325
- const params = { onDelete, onUpdate };
76326
- const typeSuffix = isCyclic3(it2) ? ": AnyPgColumn" : "";
76327
- const paramsStr = objToStatement23(params);
76328
- const tableSchema = schemas[it2.schemaTo || ""];
76329
- const paramName = paramNameFor(it2.tableTo, tableSchema);
76330
- if (paramsStr) {
76331
- return `.references(()${typeSuffix} => ${withCasing2(
76332
- paramName,
76333
- casing2
76334
- )}.${withCasing2(it2.columnsTo[0], casing2)}, ${paramsStr} )`;
76335
- }
76336
- return `.references(()${typeSuffix} => ${withCasing2(
76337
- paramName,
76338
- casing2
76339
- )}.${withCasing2(it2.columnsTo[0], casing2)})`;
76340
- }).join("");
76341
- statement += fksStatement;
76342
- }
76343
76498
  statement += ",\n";
76344
76499
  });
76345
76500
  return statement;
@@ -76363,7 +76518,7 @@ var init_introspect_pg = __esm({
76363
76518
  if (it2.isExpression) {
76364
76519
  return `sql\`${it2.expression}\``;
76365
76520
  } else {
76366
- return `table.${withCasing2(it2.expression, casing2)}${it2.opclass && vectorOps.includes(it2.opclass) ? `.op("${it2.opclass}")` : ""}`;
76521
+ return `table.${withCasing2(it2.expression, casing2)}${it2.asc ? ".asc()" : ".desc()"}${it2.nulls === "first" ? ".nullsFirst()" : ".nullsLast()"}${it2.opclass && vectorOps.includes(it2.opclass) ? `.op("${it2.opclass}")` : ""}`;
76367
76522
  }
76368
76523
  }).join(", ")})`;
76369
76524
  statement += it.where ? `.where(sql\`${it.where}\`)` : "";
@@ -80519,7 +80674,7 @@ var init_studio2 = __esm({
80519
80674
  }
80520
80675
  });
80521
80676
 
80522
- // ../node_modules/.pnpm/@drizzle-team+brocli@0.8.2/node_modules/@drizzle-team/brocli/index.js
80677
+ // ../node_modules/.pnpm/@drizzle-team+brocli@0.10.1/node_modules/@drizzle-team/brocli/index.js
80523
80678
  var __create2 = Object.create;
80524
80679
  var __defProp2 = Object.defineProperty;
80525
80680
  var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
@@ -80966,130 +81121,299 @@ var require_shell_quote = __commonJS2({
80966
81121
  }
80967
81122
  });
80968
81123
  var BroCliError = class extends Error {
80969
- constructor(message) {
81124
+ constructor(message, event) {
80970
81125
  const errPrefix = "BroCli error: ";
80971
81126
  super(message === void 0 ? message : `${errPrefix}${message}`);
81127
+ this.event = event;
80972
81128
  }
80973
81129
  };
80974
81130
  var import_clone = __toESM2(require_clone(), 1);
80975
- var import_shell_quote = __toESM2(require_shell_quote(), 1);
80976
- var defaultTheme = (calledFor) => {
80977
- if (Array.isArray(calledFor)) {
80978
- const cmds = calledFor.filter((cmd) => !cmd.hidden);
80979
- const tableCmds = cmds.map((cmd) => ({
80980
- name: cmd.name,
80981
- aliases: cmd.aliases ? cmd.aliases.join(", ") : "-",
80982
- description: cmd.description ?? "-"
80983
- }));
80984
- console.log(`Here's the list of all available commands:`);
80985
- console.table(tableCmds);
80986
- console.log(
80987
- "To read the details about any particular command type: [commandName] --help"
80988
- );
80989
- } else {
80990
- const options = calledFor.options ? Object.values(calledFor.options).filter((opt) => {
80991
- var _a;
80992
- return !((_a = opt.config) == null ? void 0 : _a.isHidden);
80993
- }).map(
80994
- ({ config: opt }) => ({
80995
- name: opt.name,
80996
- aliases: opt.aliases.length ? `${opt.aliases.join(", ")}` : "-",
80997
- description: opt.description ?? "-",
80998
- type: opt.type,
80999
- required: opt.isRequired ? "\u2713" : "\u2717"
81000
- })
81001
- ) : void 0;
81002
- console.log(
81003
- `Command: ${calledFor.name}${calledFor.aliases ? ` [${calledFor.aliases.join(", ")}]` : ""}${calledFor.description ? ` - ${calledFor.description}` : ""}`
81004
- );
81005
- if (!(options == null ? void 0 : options.length))
81006
- return;
81007
- console.log("\nOptions:");
81008
- console.table(options);
81131
+ var getOptionTypeText = (option) => {
81132
+ let result = "";
81133
+ switch (option.type) {
81134
+ case "boolean":
81135
+ result = "";
81136
+ break;
81137
+ case "number": {
81138
+ if ((option.minVal ?? option.maxVal) !== void 0) {
81139
+ let text = "";
81140
+ if (option.isInt)
81141
+ text = text + `integer `;
81142
+ if (option.minVal !== void 0)
81143
+ text = text + `[${option.minVal};`;
81144
+ else
81145
+ text = text + `(\u221E;`;
81146
+ if (option.maxVal !== void 0)
81147
+ text = text + `${option.maxVal}]`;
81148
+ else
81149
+ text = text + `\u221E)`;
81150
+ result = text;
81151
+ break;
81152
+ }
81153
+ if (option.isInt) {
81154
+ result = "integer";
81155
+ break;
81156
+ }
81157
+ result = "number";
81158
+ break;
81159
+ }
81160
+ case "string": {
81161
+ if (option.enumVals) {
81162
+ result = "[ " + option.enumVals.join(" | ") + " ]";
81163
+ break;
81164
+ }
81165
+ result = "string";
81166
+ break;
81167
+ }
81168
+ case "positional": {
81169
+ result = `${option.isRequired ? "<" : "["}${option.enumVals ? option.enumVals.join("|") : option.name}${option.isRequired ? ">" : "]"}`;
81170
+ break;
81171
+ }
81172
+ }
81173
+ if (option.isRequired && option.type !== "positional")
81174
+ result = "!" + result.length ? " " : "" + result;
81175
+ return result;
81176
+ };
81177
+ var defaultEventHandler = async (event) => {
81178
+ var _a;
81179
+ switch (event.type) {
81180
+ case "command_help": {
81181
+ const command2 = event.command;
81182
+ const commandName = getCommandNameWithParents(command2);
81183
+ const cliName = event.name;
81184
+ const desc = command2.desc ?? command2.shortDesc;
81185
+ const subs = (_a = command2.subcommands) == null ? void 0 : _a.filter((s2) => !s2.hidden);
81186
+ const subcommands = subs && subs.length ? subs : void 0;
81187
+ if (desc !== void 0) {
81188
+ console.log(`
81189
+ ${desc}`);
81190
+ }
81191
+ const opts = Object.values(command2.options ?? {}).filter(
81192
+ (opt) => !opt.config.isHidden
81193
+ );
81194
+ const positionals = opts.filter((opt) => opt.config.type === "positional");
81195
+ const options = opts.filter((opt) => opt.config.type !== "positional");
81196
+ console.log("\nUsage:");
81197
+ if (command2.handler) {
81198
+ console.log(
81199
+ ` ${cliName ? cliName + " " : ""}${commandName}${positionals.length ? " " + positionals.map(({ config: p2 }) => getOptionTypeText(p2)).join(" ") : ""} [flags]`
81200
+ );
81201
+ } else
81202
+ console.log(` ${cliName ? cliName + " " : ""}${commandName} [command]`);
81203
+ if (command2.aliases) {
81204
+ console.log(`
81205
+ Aliases:`);
81206
+ console.log(` ${[command2.name, ...command2.aliases].join(", ")}`);
81207
+ }
81208
+ if (subcommands) {
81209
+ console.log("\nAvailable Commands:");
81210
+ const padding = 3;
81211
+ const maxLength = subcommands.reduce((p2, e2) => e2.name.length > p2 ? e2.name.length : p2, 0);
81212
+ const paddedLength = maxLength + padding;
81213
+ const preDescPad = 2 + paddedLength;
81214
+ const data = subcommands.map(
81215
+ (s2) => ` ${s2.name.padEnd(paddedLength)}${(() => {
81216
+ const description = s2.shortDesc ?? s2.desc;
81217
+ if (!(description == null ? void 0 : description.length))
81218
+ return "";
81219
+ const split = description.split("\n");
81220
+ const first = split.shift();
81221
+ const final = [first, ...split.map((s22) => "".padEnd(preDescPad) + s22)].join("\n");
81222
+ return final;
81223
+ })()}`
81224
+ ).join("\n");
81225
+ console.log(data);
81226
+ }
81227
+ if (options.length) {
81228
+ const aliasLength = options.reduce((p2, e2) => {
81229
+ const currentLength = e2.config.aliases.reduce((pa, a) => pa + a.length, 0) + (e2.config.aliases.length - 1) * 2 + 1;
81230
+ return currentLength > p2 ? currentLength : p2;
81231
+ }, 0);
81232
+ const paddedAliasLength = aliasLength > 0 ? aliasLength + 1 : 0;
81233
+ const nameLength = options.reduce((p2, e2) => {
81234
+ const typeLen = getOptionTypeText(e2.config).length;
81235
+ const length = typeLen > 0 ? e2.config.name.length + 1 + typeLen : e2.config.name.length;
81236
+ return length > p2 ? length : p2;
81237
+ }, 0) + 3;
81238
+ const preDescPad = paddedAliasLength + nameLength + 2;
81239
+ const data = options.map(
81240
+ ({ config: opt }) => ` ${`${opt.aliases.length ? opt.aliases.join(", ") + "," : ""}`.padEnd(paddedAliasLength)}${`${opt.name}${(() => {
81241
+ const typeText = getOptionTypeText(opt);
81242
+ return typeText.length ? " " + typeText : "";
81243
+ })()}`.padEnd(nameLength)}${(() => {
81244
+ var _a2;
81245
+ if (!((_a2 = opt.description) == null ? void 0 : _a2.length)) {
81246
+ return opt.default !== void 0 ? `default: ${JSON.stringify(opt.default)}` : "";
81247
+ }
81248
+ const split = opt.description.split("\n");
81249
+ const first = split.shift();
81250
+ const def = opt.default !== void 0 ? ` (default: ${JSON.stringify(opt.default)})` : "";
81251
+ const final = [first, ...split.map((s2) => "".padEnd(preDescPad) + s2)].join("\n") + def;
81252
+ return final;
81253
+ })()}`
81254
+ ).join("\n");
81255
+ console.log("\nFlags:");
81256
+ console.log(data);
81257
+ }
81258
+ console.log("\nGlobal flags:");
81259
+ console.log(` -h, --help help for ${commandName}`);
81260
+ console.log(` -v, --version version${cliName ? ` for ${cliName}` : ""}`);
81261
+ if (subcommands) {
81262
+ console.log(
81263
+ `
81264
+ Use "${cliName ? cliName + " " : ""}${commandName} [command] --help" for more information about a command.
81265
+ `
81266
+ );
81267
+ }
81268
+ return true;
81269
+ }
81270
+ case "global_help": {
81271
+ const cliName = event.name;
81272
+ const desc = event.description;
81273
+ const commands = event.commands.filter((c) => !c.hidden);
81274
+ if (desc !== void 0) {
81275
+ console.log(`${desc}
81276
+ `);
81277
+ }
81278
+ console.log("Usage:");
81279
+ console.log(` ${cliName ? cliName + " " : ""}[command]`);
81280
+ if (commands.length) {
81281
+ console.log("\nAvailable Commands:");
81282
+ const padding = 3;
81283
+ const maxLength = commands.reduce((p2, e2) => e2.name.length > p2 ? e2.name.length : p2, 0);
81284
+ const paddedLength = maxLength + padding;
81285
+ const data = commands.map(
81286
+ (\u0441) => ` ${\u0441.name.padEnd(paddedLength)}${(() => {
81287
+ const desc2 = \u0441.shortDesc ?? \u0441.desc;
81288
+ if (!(desc2 == null ? void 0 : desc2.length))
81289
+ return "";
81290
+ const split = desc2.split("\n");
81291
+ const first = split.shift();
81292
+ const final = [first, ...split.map((s2) => "".padEnd(paddedLength + 2) + s2)].join("\n");
81293
+ return final;
81294
+ })()}`
81295
+ ).join("\n");
81296
+ console.log(data);
81297
+ } else {
81298
+ console.log("\nNo available commands.");
81299
+ }
81300
+ console.log("\nFlags:");
81301
+ console.log(` -h, --help help${cliName ? ` for ${cliName}` : ""}`);
81302
+ console.log(` -v, --version version${cliName ? ` for ${cliName}` : ""}`);
81303
+ console.log("\n");
81304
+ return true;
81305
+ }
81306
+ case "version": {
81307
+ return true;
81308
+ }
81309
+ case "error": {
81310
+ let msg;
81311
+ switch (event.violation) {
81312
+ case "above_max": {
81313
+ const matchedName = event.offender.namePart;
81314
+ const data = event.offender.dataPart;
81315
+ const option = event.option;
81316
+ const max = option.maxVal;
81317
+ msg = `Invalid value: number type argument '${matchedName}' expects maximal value of ${max} as an input, got: ${data}`;
81318
+ break;
81319
+ }
81320
+ case "below_min": {
81321
+ const matchedName = event.offender.namePart;
81322
+ const data = event.offender.dataPart;
81323
+ const option = event.option;
81324
+ const min = option.minVal;
81325
+ msg = `Invalid value: number type argument '${matchedName}' expects minimal value of ${min} as an input, got: ${data}`;
81326
+ break;
81327
+ }
81328
+ case "expected_int": {
81329
+ const matchedName = event.offender.namePart;
81330
+ const data = event.offender.dataPart;
81331
+ msg = `Invalid value: number type argument '${matchedName}' expects an integer as an input, got: ${data}`;
81332
+ break;
81333
+ }
81334
+ case "invalid_boolean_syntax": {
81335
+ const matchedName = event.offender.namePart;
81336
+ const data = event.offender.dataPart;
81337
+ msg = `Invalid syntax: boolean type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value> | ${matchedName}.
81338
+ Allowed values: true, false, 0, 1`;
81339
+ break;
81340
+ }
81341
+ case "invalid_string_syntax": {
81342
+ const matchedName = event.offender.namePart;
81343
+ msg = `Invalid syntax: string type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value>`;
81344
+ break;
81345
+ }
81346
+ case "invalid_number_syntax": {
81347
+ const matchedName = event.offender.namePart;
81348
+ msg = `Invalid syntax: number type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value>`;
81349
+ break;
81350
+ }
81351
+ case "invalid_number_value": {
81352
+ const matchedName = event.offender.namePart;
81353
+ const data = event.offender.dataPart;
81354
+ msg = `Invalid value: number type argument '${matchedName}' expects a number as an input, got: ${data}`;
81355
+ break;
81356
+ }
81357
+ case "enum_violation": {
81358
+ const matchedName = event.offender.namePart;
81359
+ const data = event.offender.dataPart;
81360
+ const option = event.option;
81361
+ const values = option.enumVals;
81362
+ msg = option.type === "positional" ? `Invalid value: value for the positional argument '${option.name}' must be either one of the following: ${values.join(", ")}; Received: ${data}` : `Invalid value: value for the argument '${matchedName}' must be either one of the following: ${values.join(", ")}; Received: ${data}`;
81363
+ break;
81364
+ }
81365
+ case "unknown_command_error": {
81366
+ const msg2 = `Unknown command: '${event.offender}'.
81367
+ Type '--help' to get help on the cli.`;
81368
+ console.error(msg2);
81369
+ return true;
81370
+ }
81371
+ case "unknown_subcommand_error": {
81372
+ const cName = getCommandNameWithParents(event.command);
81373
+ const msg2 = `Unknown command: ${cName} ${event.offender}.
81374
+ Type '${cName} --help' to get the help on command.`;
81375
+ console.error(msg2);
81376
+ return true;
81377
+ }
81378
+ case "missing_args_error": {
81379
+ const missingOpts = event.missing;
81380
+ msg = `Command '${command.name}' is missing following required options: ${missingOpts.map((opt) => {
81381
+ const name = opt.shift();
81382
+ const aliases = opt;
81383
+ if (aliases.length)
81384
+ return `${name} [${aliases.join(", ")}]`;
81385
+ return name;
81386
+ }).join(", ")}`;
81387
+ break;
81388
+ }
81389
+ case "unrecognized_args_error": {
81390
+ const { command: command2, unrecognized } = event;
81391
+ msg = `Unrecognized options for command '${command2.name}': ${unrecognized.join(", ")}`;
81392
+ break;
81393
+ }
81394
+ case "unknown_error": {
81395
+ const e2 = event.error;
81396
+ console.error(typeof e2 === "object" && e2 !== null && "message" in e2 ? e2.message : e2);
81397
+ return true;
81398
+ }
81399
+ }
81400
+ console.error(msg);
81401
+ return true;
81402
+ }
81009
81403
  }
81404
+ return false;
81010
81405
  };
81406
+ var eventHandlerWrapper = (customEventHandler) => async (event) => await customEventHandler(event) ? true : await defaultEventHandler(event);
81407
+ var import_shell_quote = __toESM2(require_shell_quote(), 1);
81011
81408
  function isInt(value) {
81012
81409
  return value === Math.floor(value);
81013
81410
  }
81014
- var unknownCommand = (caller) => {
81015
- const msg = `Unknown command: '${caller}'.
81016
- Type '--help' to get help on the cli.`;
81017
- return new Error(msg);
81018
- };
81019
- var unknownSubcommand = (command2, caller) => {
81020
- const name = getCommandNameRecursive(command2);
81021
- const msg = `Unknown command: ${name} ${caller}.
81022
- Type '${name} --help' to get the help on command.`;
81023
- new Error(
81024
- msg
81025
- );
81026
- return new Error(msg);
81027
- };
81028
- var missingRequired = (command2, missingOpts) => {
81029
- const msg = `Command '${command2.name}' is missing following required options: ${missingOpts.map((opt) => {
81030
- const name = opt.shift();
81031
- const aliases = opt;
81032
- if (aliases.length)
81033
- return `${name} [${aliases.join(", ")}]`;
81034
- return name;
81035
- }).join(", ")}`;
81036
- return new Error(msg);
81037
- };
81038
- var unrecognizedOptions = (command2, unrecognizedArgs) => {
81039
- const msg = `Unrecognized options for command '${command2.name}': ${unrecognizedArgs.join(", ")}`;
81040
- return new Error(msg);
81041
- };
81042
- var invalidBooleanSyntax = (matchedName) => {
81043
- return new Error(
81044
- `Invalid syntax: boolean type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value> | ${matchedName}.
81045
- Allowed values: true, false, 0, 1`
81046
- );
81047
- };
81048
- var invalidStringSyntax = (matchedName) => {
81049
- return new Error(
81050
- `Invalid syntax: string type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value>`
81051
- );
81052
- };
81053
- var enumViolation = (matchedName, data, values) => {
81054
- return new Error(
81055
- `Invalid value: value for the argument '${matchedName}' must be either one of the following: ${values.join(", ")}; Received: ${data}`
81056
- );
81057
- };
81058
- var enumViolationPos = (matchedName, data, values) => {
81059
- return new Error(
81060
- `Invalid value: value for the argument '${matchedName}' must be either one of the following: ${values.join(", ")}; Received: ${data}`
81061
- );
81062
- };
81063
- var invalidNumberSyntax = (matchedName) => {
81064
- return new Error(
81065
- `Invalid syntax: number type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value>`
81066
- );
81067
- };
81068
- var invalidNumberValue = (matchedName, data) => {
81069
- return new Error(
81070
- `Invalid value: number type argument '${matchedName}' expects a number as an input, got: ${data}`
81071
- );
81072
- };
81073
- var invalidInteger = (matchedName, data) => {
81074
- return new Error(
81075
- `Invalid value: number type argument '${matchedName}' expects an integer as an input, got: ${data}`
81076
- );
81077
- };
81078
- var belowMin = (matchedName, data, min) => {
81079
- return new Error(
81080
- `Invalid value: number type argument '${matchedName}' expects minimal value of ${min} as an input, got: ${data}`
81081
- );
81082
- };
81083
- var aboveMax = (matchedName, data, max) => {
81084
- return new Error(
81085
- `Invalid value: number type argument '${matchedName}' expects maximal value of ${max} as an input, got: ${data}`
81086
- );
81087
- };
81411
+ var executeOrLog = async (target) => typeof target === "string" ? console.log(target) : target ? await target() : void 0;
81088
81412
  var generatePrefix = (name) => name.startsWith("-") ? name : name.length > 1 ? `--${name}` : `-${name}`;
81089
81413
  var validateOptions = (config) => {
81090
81414
  const cloned = (0, import_clone.default)(config);
81091
81415
  const entries = [];
81092
- const storedNames = {};
81416
+ const storedNames = [];
81093
81417
  const cfgEntries = Object.entries(cloned);
81094
81418
  for (const [key, value] of cfgEntries) {
81095
81419
  const cfg = value._.config;
@@ -81099,13 +81423,13 @@ var validateOptions = (config) => {
81099
81423
  continue;
81100
81424
  if (cfg.name.includes("=")) {
81101
81425
  throw new BroCliError(
81102
- `Can't define option ${cfg.name} - option names and aliases cannot contain '='!`
81426
+ `Can't define option '${generatePrefix(cfg.name)}' - option names and aliases cannot contain '='!`
81103
81427
  );
81104
81428
  }
81105
81429
  for (const alias of cfg.aliases) {
81106
81430
  if (alias.includes("=")) {
81107
81431
  throw new BroCliError(
81108
- `Can't define option ${cfg.name} - option names and aliases cannot contain '='!`
81432
+ `Can't define option '${generatePrefix(cfg.name)}' - option names and aliases cannot contain '='!`
81109
81433
  );
81110
81434
  }
81111
81435
  }
@@ -81123,33 +81447,33 @@ var validateOptions = (config) => {
81123
81447
  for (const name of allNames) {
81124
81448
  const match2 = reservedNames.find((n) => n === name);
81125
81449
  if (match2)
81126
- throw new BroCliError(`Can't define option ${cfg.name} - name '${match2}' is reserved!`);
81450
+ throw new BroCliError(`Can't define option '${cfg.name}' - name '${match2}' is reserved!`);
81127
81451
  }
81128
- const storageVals = Object.values(storedNames);
81129
- for (const storage2 of storageVals) {
81452
+ for (const storage2 of storedNames) {
81130
81453
  const nameOccupier = storage2.find((e2) => e2 === cfg.name);
81131
81454
  if (!nameOccupier)
81132
81455
  continue;
81133
81456
  throw new BroCliError(
81134
- `Can't define option '${cfg.name}': name is already in use by option '${storage2[0]}'!`
81457
+ `Can't define option '${cfg.name}' - name is already in use by option '${storage2[0]}'!`
81135
81458
  );
81136
81459
  }
81137
81460
  for (const alias of cfg.aliases) {
81138
- for (const storage2 of storageVals) {
81461
+ for (const storage2 of storedNames) {
81139
81462
  const nameOccupier = storage2.find((e2) => e2 === alias);
81140
81463
  if (!nameOccupier)
81141
81464
  continue;
81142
81465
  throw new BroCliError(
81143
- `Can't define option '${cfg.name}': alias '${alias}' is already in use by option '${storage2[0]}'!`
81466
+ `Can't define option '${cfg.name}' - alias '${alias}' is already in use by option '${storage2[0]}'!`
81144
81467
  );
81145
81468
  }
81146
81469
  }
81147
- storedNames[cfg.name] = [cfg.name, ...cfg.aliases];
81148
- storedNames[cfg.name].forEach((name, idx) => {
81149
- if (storedNames[cfg.name].findIndex((e2) => e2 === name) === idx)
81470
+ const currentNames = [cfg.name, ...cfg.aliases];
81471
+ storedNames.push(currentNames);
81472
+ currentNames.forEach((name, idx) => {
81473
+ if (currentNames.findIndex((e2) => e2 === name) === idx)
81150
81474
  return;
81151
81475
  throw new BroCliError(
81152
- `Can't define option '${cfg.name}': duplicate aliases '${name}'!`
81476
+ `Can't define option '${cfg.name}' - duplicate alias '${name}'!`
81153
81477
  );
81154
81478
  });
81155
81479
  entries.push([key, { config: cfg, $output: void 0 }]);
@@ -81170,14 +81494,17 @@ var command = (command2) => {
81170
81494
  `Can't define command '${cmd.name}' - command can't have subcommands and positional args at the same time!`
81171
81495
  );
81172
81496
  }
81497
+ if (!command2.handler && !command2.subcommands) {
81498
+ throw new BroCliError(
81499
+ `Can't define command '${cmd.name}' - command without subcommands must have a handler present!`
81500
+ );
81501
+ }
81173
81502
  const processedOptions = command2.options ? validateOptions(command2.options) : void 0;
81174
81503
  cmd.options = processedOptions;
81175
81504
  cmd.name = cmd.name ?? ((_a = cmd.aliases) == null ? void 0 : _a.shift());
81176
81505
  if (!cmd.name)
81177
81506
  throw new BroCliError(`Can't define command without name!`);
81178
81507
  cmd.aliases = ((_b = cmd.aliases) == null ? void 0 : _b.length) ? cmd.aliases : void 0;
81179
- if (!cmd.handler)
81180
- throw new BroCliError(`Can't define command '${cmd.name}' - command must have a handler!`);
81181
81508
  if (cmd.name.startsWith("-")) {
81182
81509
  throw new BroCliError(`Can't define command '${cmd.name}' - command name can't start with '-'!`);
81183
81510
  }
@@ -81207,7 +81534,7 @@ var command = (command2) => {
81207
81534
  }
81208
81535
  return cmd;
81209
81536
  };
81210
- var getCommandInner = (commands, candidates, args) => {
81537
+ var getCommandInner = (commands, candidates, args, cliName, cliDescription) => {
81211
81538
  const { data: arg, originalIndex: index4 } = candidates.shift();
81212
81539
  const command2 = commands.find((c) => {
81213
81540
  const names = c.aliases ? [c.name, ...c.aliases] : [c.name];
@@ -81228,12 +81555,20 @@ var getCommandInner = (commands, candidates, args) => {
81228
81555
  };
81229
81556
  }
81230
81557
  const newCandidates = candidates.map((c) => ({ data: c.data, originalIndex: c.originalIndex - 1 }));
81231
- const subcommand = getCommandInner(command2.subcommands, newCandidates, newArgs);
81232
- if (!subcommand.command)
81233
- throw unknownSubcommand(command2, candidates[0].data);
81558
+ const subcommand = getCommandInner(command2.subcommands, newCandidates, newArgs, cliName, cliDescription);
81559
+ if (!subcommand.command) {
81560
+ throw new BroCliError(void 0, {
81561
+ type: "error",
81562
+ violation: "unknown_subcommand_error",
81563
+ name: cliName,
81564
+ description: cliDescription,
81565
+ command: command2,
81566
+ offender: candidates[0].data
81567
+ });
81568
+ }
81234
81569
  return subcommand;
81235
81570
  };
81236
- var getCommand = (commands, args) => {
81571
+ var getCommand = (commands, args, cliName, cliDescription) => {
81237
81572
  var _a;
81238
81573
  const candidates = [];
81239
81574
  for (let i2 = 0; i2 < args.length; ++i2) {
@@ -81267,15 +81602,23 @@ var getCommand = (commands, args) => {
81267
81602
  args: removeByIndex(args, firstCandidate.originalIndex)
81268
81603
  };
81269
81604
  }
81270
- const { command: command2, args: argsRes } = getCommandInner(commands, candidates, args);
81271
- if (!command2)
81272
- throw unknownCommand(firstCandidate.data);
81605
+ const { command: command2, args: argsRes } = getCommandInner(commands, candidates, args, cliName, cliDescription);
81606
+ if (!command2) {
81607
+ throw new BroCliError(void 0, {
81608
+ type: "error",
81609
+ violation: "unknown_command_error",
81610
+ commands,
81611
+ name: cliName,
81612
+ description: cliDescription,
81613
+ offender: firstCandidate.data
81614
+ });
81615
+ }
81273
81616
  return {
81274
81617
  command: command2,
81275
81618
  args: argsRes
81276
81619
  };
81277
81620
  };
81278
- var parseArg = (options, positionals, arg, nextArg) => {
81621
+ var parseArg = (command2, options, positionals, arg, nextArg, cliName, cliDescription) => {
81279
81622
  let data = void 0;
81280
81623
  const argSplit = arg.split("=");
81281
81624
  const hasEq = arg.includes("=");
@@ -81296,8 +81639,18 @@ var parseArg = (options, positionals, arg, nextArg) => {
81296
81639
  if (!positionals.length)
81297
81640
  return {};
81298
81641
  const pos = positionals.shift();
81299
- if (pos[1].enumVals && !pos[1].enumVals.find((val2) => val2 === dataPart)) {
81300
- throw enumViolationPos(pos[1].name, arg, pos[1].enumVals);
81642
+ if (pos[1].enumVals && !pos[1].enumVals.find((val2) => val2 === arg)) {
81643
+ throw new BroCliError(void 0, {
81644
+ type: "error",
81645
+ name: cliName,
81646
+ description: cliDescription,
81647
+ violation: "enum_violation",
81648
+ command: command2,
81649
+ option: pos[1],
81650
+ offender: {
81651
+ dataPart: arg
81652
+ }
81653
+ });
81301
81654
  }
81302
81655
  data = arg;
81303
81656
  return {
@@ -81332,32 +81685,126 @@ var parseArg = (options, positionals, arg, nextArg) => {
81332
81685
  skipNext = false;
81333
81686
  return true;
81334
81687
  }
81335
- throw invalidBooleanSyntax(match2);
81688
+ throw new BroCliError(void 0, {
81689
+ type: "error",
81690
+ name: cliName,
81691
+ description: cliDescription,
81692
+ violation: "invalid_boolean_syntax",
81693
+ option: opt,
81694
+ command: command2,
81695
+ offender: {
81696
+ namePart,
81697
+ dataPart
81698
+ }
81699
+ });
81336
81700
  } else {
81337
81701
  const match2 = names.find((name) => name === namePart);
81338
81702
  if (!match2)
81339
81703
  return false;
81340
81704
  if (opt.type === "string") {
81341
- if (!hasEq && nextArg === void 0)
81342
- throw invalidStringSyntax(match2);
81705
+ if (!hasEq && nextArg === void 0) {
81706
+ throw new BroCliError(void 0, {
81707
+ type: "error",
81708
+ name: cliName,
81709
+ description: cliDescription,
81710
+ violation: "invalid_string_syntax",
81711
+ option: opt,
81712
+ command: command2,
81713
+ offender: {
81714
+ namePart,
81715
+ dataPart
81716
+ }
81717
+ });
81718
+ }
81343
81719
  if (opt.enumVals && !opt.enumVals.find((val2) => val2 === dataPart)) {
81344
- throw enumViolation(match2, dataPart, opt.enumVals);
81720
+ throw new BroCliError(void 0, {
81721
+ type: "error",
81722
+ name: cliName,
81723
+ description: cliDescription,
81724
+ violation: "enum_violation",
81725
+ option: opt,
81726
+ command: command2,
81727
+ offender: {
81728
+ namePart,
81729
+ dataPart
81730
+ }
81731
+ });
81345
81732
  }
81346
81733
  data = dataPart;
81347
81734
  return true;
81348
81735
  }
81349
- if (!hasEq && nextArg === void 0)
81350
- throw invalidNumberSyntax(match2);
81736
+ if (!hasEq && nextArg === void 0) {
81737
+ throw new BroCliError(void 0, {
81738
+ type: "error",
81739
+ name: cliName,
81740
+ description: cliDescription,
81741
+ violation: "invalid_number_syntax",
81742
+ option: opt,
81743
+ command: command2,
81744
+ offender: {
81745
+ namePart,
81746
+ dataPart
81747
+ }
81748
+ });
81749
+ }
81351
81750
  const numData = Number(dataPart);
81352
- if (isNaN(numData))
81353
- throw invalidNumberValue(match2, dataPart);
81354
- if (opt.isInt && !isInt(numData))
81355
- throw invalidInteger(match2, dataPart);
81356
- if (opt.minVal !== void 0 && numData < opt.minVal)
81357
- throw belowMin(match2, dataPart, opt.minVal);
81358
- if (opt.maxVal !== void 0 && numData > opt.maxVal)
81359
- throw aboveMax(match2, dataPart, opt.maxVal);
81360
- data = dataPart;
81751
+ if (isNaN(numData)) {
81752
+ throw new BroCliError(void 0, {
81753
+ type: "error",
81754
+ name: cliName,
81755
+ description: cliDescription,
81756
+ violation: "invalid_number_value",
81757
+ option: opt,
81758
+ command: command2,
81759
+ offender: {
81760
+ namePart,
81761
+ dataPart
81762
+ }
81763
+ });
81764
+ }
81765
+ if (opt.isInt && !isInt(numData)) {
81766
+ throw new BroCliError(void 0, {
81767
+ type: "error",
81768
+ name: cliName,
81769
+ description: cliDescription,
81770
+ violation: "expected_int",
81771
+ option: opt,
81772
+ command: command2,
81773
+ offender: {
81774
+ namePart,
81775
+ dataPart
81776
+ }
81777
+ });
81778
+ }
81779
+ if (opt.minVal !== void 0 && numData < opt.minVal) {
81780
+ throw new BroCliError(void 0, {
81781
+ type: "error",
81782
+ name: cliName,
81783
+ description: cliDescription,
81784
+ violation: "below_min",
81785
+ option: opt,
81786
+ command: command2,
81787
+ offender: {
81788
+ namePart,
81789
+ dataPart
81790
+ }
81791
+ });
81792
+ }
81793
+ if (opt.maxVal !== void 0 && numData > opt.maxVal) {
81794
+ throw new BroCliError(void 0, {
81795
+ type: "error",
81796
+ name: cliName,
81797
+ description: cliDescription,
81798
+ violation: "above_max",
81799
+ option: opt,
81800
+ command: command2,
81801
+ offender: {
81802
+ namePart,
81803
+ dataPart
81804
+ }
81805
+ });
81806
+ }
81807
+ data = numData;
81361
81808
  return true;
81362
81809
  }
81363
81810
  });
@@ -81368,7 +81815,7 @@ var parseArg = (options, positionals, arg, nextArg) => {
81368
81815
  option: option == null ? void 0 : option[1]
81369
81816
  };
81370
81817
  };
81371
- var parseOptions = (command2, args, omitKeysOfUndefinedOptions) => {
81818
+ var parseOptions = (command2, args, cliName, cliDescription, omitKeysOfUndefinedOptions) => {
81372
81819
  const options = command2.options;
81373
81820
  const optEntries = Object.entries(options ?? {}).map(
81374
81821
  (opt) => [opt[0], opt[1].config]
@@ -81388,16 +81835,16 @@ var parseOptions = (command2, args, omitKeysOfUndefinedOptions) => {
81388
81835
  skipNext,
81389
81836
  isHelp,
81390
81837
  isVersion
81391
- } = parseArg(nonPositionalEntries, positionalEntries, arg, nextArg);
81838
+ } = parseArg(command2, nonPositionalEntries, positionalEntries, arg, nextArg, cliName, cliDescription);
81392
81839
  if (!option)
81393
81840
  unrecognizedArgsArr.push(arg.split("=")[0]);
81394
81841
  if (skipNext)
81395
81842
  ++i2;
81396
- result[name] = data;
81397
81843
  if (isHelp)
81398
81844
  return "help";
81399
81845
  if (isVersion)
81400
81846
  return "version";
81847
+ result[name] = data;
81401
81848
  }
81402
81849
  for (const [optKey, option] of optEntries) {
81403
81850
  const data = result[optKey] ?? option.default;
@@ -81410,19 +81857,29 @@ var parseOptions = (command2, args, omitKeysOfUndefinedOptions) => {
81410
81857
  if (option.isRequired && result[optKey] === void 0)
81411
81858
  missingRequiredArr.push([option.name, ...option.aliases]);
81412
81859
  }
81413
- if (missingRequiredArr.length)
81414
- throw missingRequired(command2, missingRequiredArr);
81415
- if (unrecognizedArgsArr.length)
81416
- throw unrecognizedOptions(command2, unrecognizedArgsArr);
81417
- return result;
81418
- };
81419
- var executeOrLog = async (target) => {
81420
- if (!target || typeof target === "string")
81421
- console.log(target);
81422
- else
81423
- await target();
81860
+ if (missingRequiredArr.length) {
81861
+ throw new BroCliError(void 0, {
81862
+ type: "error",
81863
+ violation: "missing_args_error",
81864
+ name: cliName,
81865
+ description: cliDescription,
81866
+ command: command2,
81867
+ missing: missingRequiredArr
81868
+ });
81869
+ }
81870
+ if (unrecognizedArgsArr.length) {
81871
+ throw new BroCliError(void 0, {
81872
+ type: "error",
81873
+ violation: "unrecognized_args_error",
81874
+ name: cliName,
81875
+ description: cliDescription,
81876
+ command: command2,
81877
+ unrecognized: unrecognizedArgsArr
81878
+ });
81879
+ }
81880
+ return Object.keys(result).length ? result : void 0;
81424
81881
  };
81425
- var getCommandNameRecursive = (command2) => command2.parent ? `${getCommandNameRecursive(command2.parent)} ${command2.name}` : command2.name;
81882
+ var getCommandNameWithParents = (command2) => command2.parent ? `${getCommandNameWithParents(command2.parent)} ${command2.name}` : command2.name;
81426
81883
  var validateCommands = (commands, parent) => {
81427
81884
  const storedNames = {};
81428
81885
  for (const cmd of commands) {
@@ -81431,8 +81888,8 @@ var validateCommands = (commands, parent) => {
81431
81888
  const nameOccupier = storage2.find((e2) => e2 === cmd.name);
81432
81889
  if (!nameOccupier)
81433
81890
  continue;
81434
- throw new Error(
81435
- `Can't define command '${getCommandNameRecursive(cmd)}': name is already in use by command '${parent ? `${getCommandNameRecursive(parent)} ` : ""}${storage2[0]}'!`
81891
+ throw new BroCliError(
81892
+ `Can't define command '${getCommandNameWithParents(cmd)}': name is already in use by command '${parent ? `${getCommandNameWithParents(parent)} ` : ""}${storage2[0]}'!`
81436
81893
  );
81437
81894
  }
81438
81895
  if (cmd.aliases) {
@@ -81441,8 +81898,8 @@ var validateCommands = (commands, parent) => {
81441
81898
  const nameOccupier = storage2.find((e2) => e2 === alias);
81442
81899
  if (!nameOccupier)
81443
81900
  continue;
81444
- throw new Error(
81445
- `Can't define command '${getCommandNameRecursive(cmd)}': alias '${alias}' is already in use by command '${parent ? `${getCommandNameRecursive(parent)} ` : ""}${storage2[0]}'!`
81901
+ throw new BroCliError(
81902
+ `Can't define command '${getCommandNameWithParents(cmd)}': alias '${alias}' is already in use by command '${parent ? `${getCommandNameWithParents(parent)} ` : ""}${storage2[0]}'!`
81446
81903
  );
81447
81904
  }
81448
81905
  }
@@ -81454,53 +81911,135 @@ var validateCommands = (commands, parent) => {
81454
81911
  return commands;
81455
81912
  };
81456
81913
  var removeByIndex = (arr, idx) => [...arr.slice(0, idx), ...arr.slice(idx + 1, arr.length)];
81457
- var help = async (command2, commands, helpHandler) => typeof command2 === "object" ? command2.help !== void 0 ? await executeOrLog(command2.help) : await helpHandler(command2) : await helpHandler(commands);
81458
- var rawCli = async (commands, config) => {
81914
+ var run = async (commands, config) => {
81459
81915
  var _a, _b;
81460
- const processedCmds = validateCommands(commands);
81916
+ const eventHandler = (config == null ? void 0 : config.theme) ? eventHandlerWrapper(config.theme) : defaultEventHandler;
81461
81917
  const argSource = (config == null ? void 0 : config.argSource) ?? process.argv;
81462
81918
  const version3 = config == null ? void 0 : config.version;
81463
- const helpHandler = (config == null ? void 0 : config.help) ?? defaultTheme;
81919
+ const help = config == null ? void 0 : config.help;
81464
81920
  const omitKeysOfUndefinedOptions = (config == null ? void 0 : config.omitKeysOfUndefinedOptions) ?? false;
81465
- let args = argSource.slice(2, argSource.length);
81466
- if (!args.length)
81467
- return await helpHandler(processedCmds);
81468
- const helpIndex = args.findIndex((arg) => arg === "--help" || arg === "-h");
81469
- if (helpIndex !== -1 && (helpIndex > 0 ? ((_a = args[helpIndex - 1]) == null ? void 0 : _a.startsWith("-")) && !args[helpIndex - 1].includes("=") ? false : true : true)) {
81470
- const command3 = getCommand(processedCmds, args).command;
81471
- return help(command3, processedCmds, helpHandler);
81472
- }
81473
- const versionIndex = args.findIndex((arg) => arg === "--version" || arg === "-v");
81474
- if (versionIndex !== -1 && (versionIndex > 0 ? ((_b = args[versionIndex - 1]) == null ? void 0 : _b.startsWith("-")) ? false : true : true)) {
81475
- return await executeOrLog(version3);
81476
- }
81477
- const { command: command2, args: newArgs } = getCommand(processedCmds, args);
81478
- if (!command2)
81479
- return helpHandler(processedCmds);
81480
- if (command2 === "help") {
81481
- const { command: helpCommand } = getCommand(processedCmds, newArgs);
81482
- return help(helpCommand, processedCmds, helpHandler);
81483
- }
81484
- const optionResult = parseOptions(command2, newArgs, omitKeysOfUndefinedOptions);
81485
- if (optionResult === "help")
81486
- return await help(command2, commands, helpHandler);
81487
- if (optionResult === "version")
81488
- return await executeOrLog(version3);
81489
- if (optionResult) {
81490
- if (config == null ? void 0 : config.hook)
81491
- await config.hook("pre", command2);
81492
- await command2.handler(command2.transform ? await command2.transform(optionResult) : optionResult);
81493
- if (config == null ? void 0 : config.hook)
81494
- await config.hook("post", command2);
81495
- }
81496
- return void 0;
81497
- };
81498
- var run = async (commands, config) => {
81921
+ const cliName = config == null ? void 0 : config.name;
81922
+ const cliDescription = config == null ? void 0 : config.description;
81499
81923
  try {
81500
- await rawCli(commands, config);
81924
+ const processedCmds = validateCommands(commands);
81925
+ let args = argSource.slice(2, argSource.length);
81926
+ if (!args.length) {
81927
+ return help !== void 0 ? await executeOrLog(help) : await eventHandler({
81928
+ type: "global_help",
81929
+ description: cliDescription,
81930
+ name: cliName,
81931
+ commands: processedCmds
81932
+ });
81933
+ }
81934
+ const helpIndex = args.findIndex((arg) => arg === "--help" || arg === "-h");
81935
+ if (helpIndex !== -1 && (helpIndex > 0 ? ((_a = args[helpIndex - 1]) == null ? void 0 : _a.startsWith("-")) && !args[helpIndex - 1].includes("=") ? false : true : true)) {
81936
+ const command3 = getCommand(processedCmds, args, cliName, cliDescription).command;
81937
+ if (typeof command3 === "object") {
81938
+ return command3.help !== void 0 ? await executeOrLog(command3.help) : await eventHandler({
81939
+ type: "command_help",
81940
+ description: cliDescription,
81941
+ name: cliName,
81942
+ command: command3
81943
+ });
81944
+ } else {
81945
+ return help !== void 0 ? await executeOrLog(help) : await eventHandler({
81946
+ type: "global_help",
81947
+ description: cliDescription,
81948
+ name: cliName,
81949
+ commands: processedCmds
81950
+ });
81951
+ }
81952
+ }
81953
+ const versionIndex = args.findIndex((arg) => arg === "--version" || arg === "-v");
81954
+ if (versionIndex !== -1 && (versionIndex > 0 ? ((_b = args[versionIndex - 1]) == null ? void 0 : _b.startsWith("-")) ? false : true : true)) {
81955
+ return version3 !== void 0 ? await executeOrLog(version3) : await eventHandler({
81956
+ type: "version",
81957
+ name: cliName,
81958
+ description: cliDescription
81959
+ });
81960
+ }
81961
+ const { command: command2, args: newArgs } = getCommand(processedCmds, args, cliName, cliDescription);
81962
+ if (!command2) {
81963
+ return help !== void 0 ? await executeOrLog(help) : await eventHandler({
81964
+ type: "global_help",
81965
+ description: cliDescription,
81966
+ name: cliName,
81967
+ commands: processedCmds
81968
+ });
81969
+ }
81970
+ if (command2 === "help") {
81971
+ let helpCommand;
81972
+ let newestArgs = newArgs;
81973
+ do {
81974
+ const res = getCommand(processedCmds, newestArgs, cliName, cliDescription);
81975
+ helpCommand = res.command;
81976
+ newestArgs = res.args;
81977
+ } while (helpCommand === "help");
81978
+ return helpCommand ? helpCommand.help !== void 0 ? await executeOrLog(helpCommand.help) : await eventHandler({
81979
+ type: "command_help",
81980
+ description: cliDescription,
81981
+ name: cliName,
81982
+ command: helpCommand
81983
+ }) : help !== void 0 ? await executeOrLog(help) : await eventHandler({
81984
+ type: "global_help",
81985
+ description: cliDescription,
81986
+ name: cliName,
81987
+ commands: processedCmds
81988
+ });
81989
+ }
81990
+ const optionResult = parseOptions(command2, newArgs, cliName, cliDescription, omitKeysOfUndefinedOptions);
81991
+ if (optionResult === "help") {
81992
+ return command2.help !== void 0 ? await executeOrLog(command2.help) : await eventHandler({
81993
+ type: "command_help",
81994
+ description: cliDescription,
81995
+ name: cliName,
81996
+ command: command2
81997
+ });
81998
+ }
81999
+ if (optionResult === "version") {
82000
+ return version3 !== void 0 ? await executeOrLog(version3) : await eventHandler({
82001
+ type: "version",
82002
+ name: cliName,
82003
+ description: cliDescription
82004
+ });
82005
+ }
82006
+ if (command2.handler) {
82007
+ if (config == null ? void 0 : config.hook)
82008
+ await config.hook("before", command2);
82009
+ await command2.handler(command2.transform ? await command2.transform(optionResult) : optionResult);
82010
+ if (config == null ? void 0 : config.hook)
82011
+ await config.hook("after", command2);
82012
+ return;
82013
+ } else {
82014
+ return command2.help !== void 0 ? await executeOrLog(command2.help) : await eventHandler({
82015
+ type: "command_help",
82016
+ description: cliDescription,
82017
+ name: cliName,
82018
+ command: command2
82019
+ });
82020
+ }
81501
82021
  } catch (e2) {
81502
- console.error(typeof e2 === "object" && e2 !== null && "message" in e2 ? e2.message : e2);
81503
- process.exit(1);
82022
+ if (e2 instanceof BroCliError) {
82023
+ if (e2.event)
82024
+ await eventHandler(e2.event);
82025
+ else {
82026
+ if (!(config == null ? void 0 : config.noExit))
82027
+ console.error(e2.message);
82028
+ else
82029
+ return e2.message;
82030
+ }
82031
+ } else {
82032
+ await eventHandler({
82033
+ type: "error",
82034
+ violation: "unknown_error",
82035
+ name: cliName,
82036
+ description: cliDescription,
82037
+ error: e2
82038
+ });
82039
+ }
82040
+ if (!(config == null ? void 0 : config.noExit))
82041
+ process.exit(1);
82042
+ return;
81504
82043
  }
81505
82044
  };
81506
82045
  var OptionBuilderBase = class _OptionBuilderBase {
@@ -81578,7 +82117,7 @@ var OptionBuilderBase = class _OptionBuilderBase {
81578
82117
  max(value) {
81579
82118
  const config = this.config();
81580
82119
  const minVal = config.minVal;
81581
- if (minVal !== void 0 && minVal < value) {
82120
+ if (minVal !== void 0 && minVal > value) {
81582
82121
  throw new BroCliError("Unable to define option's max value to be lower than min value!");
81583
82122
  }
81584
82123
  return new _OptionBuilderBase({ ...config, maxVal: value });
@@ -83402,7 +83941,7 @@ init_utils2();
83402
83941
  var version2 = async () => {
83403
83942
  const { npmVersion } = await ormCoreVersions();
83404
83943
  const ormVersion = npmVersion ? `drizzle-orm: v${npmVersion}` : "";
83405
- const envVersion = "0.24.0";
83944
+ const envVersion = "0.24.1-f7ddd08";
83406
83945
  const kitVersion = envVersion ? `v${envVersion}` : "--";
83407
83946
  const versions = `drizzle-kit: ${kitVersion}
83408
83947
  ${ormVersion}`;
@@ -83437,6 +83976,7 @@ var legacy = [
83437
83976
  legacyCommand("check:sqlite", "check")
83438
83977
  ];
83439
83978
  run([generate, migrate, pull, push, studio, up, check, drop, ...legacy], {
83979
+ name: "drizzle-kit",
83440
83980
  version: version2
83441
83981
  });
83442
83982
  /*! Bundled license information: