drizzle-kit 0.16.9-fcedf83 → 0.17.0-6323eb6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.js +1773 -751
  2. package/package.json +11 -7
  3. package/utils.js +392 -111
package/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ "use strict";
2
3
  var __create = Object.create;
3
4
  var __defProp = Object.defineProperty;
4
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -613,7 +614,7 @@ var require_command = __commonJS({
613
614
  "node_modules/.pnpm/commander@9.5.0/node_modules/commander/lib/command.js"(exports) {
614
615
  var EventEmitter = require("events").EventEmitter;
615
616
  var childProcess = require("child_process");
616
- var path4 = require("path");
617
+ var path2 = require("path");
617
618
  var fs7 = require("fs");
618
619
  var process3 = require("process");
619
620
  var { Argument: Argument2, humanReadableArgName } = require_argument();
@@ -1053,10 +1054,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
1053
1054
  let launchWithNode = false;
1054
1055
  const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1055
1056
  function findFile(baseDir, baseName) {
1056
- const localBin = path4.resolve(baseDir, baseName);
1057
+ const localBin = path2.resolve(baseDir, baseName);
1057
1058
  if (fs7.existsSync(localBin))
1058
1059
  return localBin;
1059
- if (sourceExt.includes(path4.extname(baseName)))
1060
+ if (sourceExt.includes(path2.extname(baseName)))
1060
1061
  return void 0;
1061
1062
  const foundExt = sourceExt.find((ext) => fs7.existsSync(`${localBin}${ext}`));
1062
1063
  if (foundExt)
@@ -1074,19 +1075,19 @@ Expecting one of '${allowedValues.join("', '")}'`);
1074
1075
  } catch (err2) {
1075
1076
  resolvedScriptPath = this._scriptPath;
1076
1077
  }
1077
- executableDir = path4.resolve(path4.dirname(resolvedScriptPath), executableDir);
1078
+ executableDir = path2.resolve(path2.dirname(resolvedScriptPath), executableDir);
1078
1079
  }
1079
1080
  if (executableDir) {
1080
1081
  let localFile = findFile(executableDir, executableFile);
1081
1082
  if (!localFile && !subcommand._executableFile && this._scriptPath) {
1082
- const legacyName = path4.basename(this._scriptPath, path4.extname(this._scriptPath));
1083
+ const legacyName = path2.basename(this._scriptPath, path2.extname(this._scriptPath));
1083
1084
  if (legacyName !== this._name) {
1084
1085
  localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1085
1086
  }
1086
1087
  }
1087
1088
  executableFile = localFile || executableFile;
1088
1089
  }
1089
- launchWithNode = sourceExt.includes(path4.extname(executableFile));
1090
+ launchWithNode = sourceExt.includes(path2.extname(executableFile));
1090
1091
  let proc;
1091
1092
  if (process3.platform !== "win32") {
1092
1093
  if (launchWithNode) {
@@ -1658,13 +1659,13 @@ Expecting one of '${allowedValues.join("', '")}'`);
1658
1659
  return this;
1659
1660
  }
1660
1661
  nameFromFilename(filename) {
1661
- this._name = path4.basename(filename, path4.extname(filename));
1662
+ this._name = path2.basename(filename, path2.extname(filename));
1662
1663
  return this;
1663
1664
  }
1664
- executableDir(path5) {
1665
- if (path5 === void 0)
1665
+ executableDir(path3) {
1666
+ if (path3 === void 0)
1666
1667
  return this._executableDir;
1667
- this._executableDir = path5;
1668
+ this._executableDir = path3;
1668
1669
  return this;
1669
1670
  }
1670
1671
  helpInformation(contextOptions) {
@@ -1817,7 +1818,7 @@ var require_commander = __commonJS({
1817
1818
  }
1818
1819
  });
1819
1820
 
1820
- // node_modules/.pnpm/zod@3.20.2/node_modules/zod/lib/index.mjs
1821
+ // node_modules/.pnpm/zod@3.20.6/node_modules/zod/lib/index.mjs
1821
1822
  function getErrorMap() {
1822
1823
  return overrideErrorMap;
1823
1824
  }
@@ -1930,9 +1931,9 @@ function createZodEnum(values, params) {
1930
1931
  ...processCreateParams(params)
1931
1932
  });
1932
1933
  }
1933
- var util, ZodParsedType, getParsedType, ZodIssueCode, ZodError, errorMap, overrideErrorMap, makeIssue, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync, errorUtil, ParseInputLazyPath, handleResult, ZodType, cuidRegex, uuidRegex, emailRegex, datetimeRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, objectUtil, AugmentFactory, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, late, ZodFirstPartyTypeKind, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, coerce;
1934
+ var util, ZodParsedType, getParsedType, ZodIssueCode, ZodError, errorMap, overrideErrorMap, makeIssue, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync, errorUtil, ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, uuidRegex, emailRegex, datetimeRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, objectUtil, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, late, ZodFirstPartyTypeKind, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, coerce;
1934
1935
  var init_lib = __esm({
1935
- "node_modules/.pnpm/zod@3.20.2/node_modules/zod/lib/index.mjs"() {
1936
+ "node_modules/.pnpm/zod@3.20.6/node_modules/zod/lib/index.mjs"() {
1936
1937
  (function(util2) {
1937
1938
  util2.assertEqual = (val) => val;
1938
1939
  function assertIs(_arg) {
@@ -2252,8 +2253,8 @@ var init_lib = __esm({
2252
2253
  };
2253
2254
  overrideErrorMap = errorMap;
2254
2255
  makeIssue = (params) => {
2255
- const { data, path: path4, errorMaps, issueData } = params;
2256
- const fullPath = [...path4, ...issueData.path || []];
2256
+ const { data, path: path2, errorMaps, issueData } = params;
2257
+ const fullPath = [...path2, ...issueData.path || []];
2257
2258
  const fullIssue = {
2258
2259
  ...issueData,
2259
2260
  path: fullPath
@@ -2329,16 +2330,16 @@ var init_lib = __esm({
2329
2330
  isAborted = (x) => x.status === "aborted";
2330
2331
  isDirty = (x) => x.status === "dirty";
2331
2332
  isValid = (x) => x.status === "valid";
2332
- isAsync = (x) => typeof Promise !== void 0 && x instanceof Promise;
2333
+ isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
2333
2334
  (function(errorUtil2) {
2334
2335
  errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
2335
2336
  errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
2336
2337
  })(errorUtil || (errorUtil = {}));
2337
2338
  ParseInputLazyPath = class {
2338
- constructor(parent, value, path4, key) {
2339
+ constructor(parent, value, path2, key) {
2339
2340
  this.parent = parent;
2340
2341
  this.data = value;
2341
- this._path = path4;
2342
+ this._path = path2;
2342
2343
  this._key = key;
2343
2344
  }
2344
2345
  get path() {
@@ -2525,28 +2526,29 @@ var init_lib = __esm({
2525
2526
  return this._refinement(refinement);
2526
2527
  }
2527
2528
  optional() {
2528
- return ZodOptional.create(this);
2529
+ return ZodOptional.create(this, this._def);
2529
2530
  }
2530
2531
  nullable() {
2531
- return ZodNullable.create(this);
2532
+ return ZodNullable.create(this, this._def);
2532
2533
  }
2533
2534
  nullish() {
2534
- return this.optional().nullable();
2535
+ return this.nullable().optional();
2535
2536
  }
2536
2537
  array() {
2537
- return ZodArray.create(this);
2538
+ return ZodArray.create(this, this._def);
2538
2539
  }
2539
2540
  promise() {
2540
- return ZodPromise.create(this);
2541
+ return ZodPromise.create(this, this._def);
2541
2542
  }
2542
2543
  or(option) {
2543
- return ZodUnion.create([this, option]);
2544
+ return ZodUnion.create([this, option], this._def);
2544
2545
  }
2545
2546
  and(incoming) {
2546
- return ZodIntersection.create(this, incoming);
2547
+ return ZodIntersection.create(this, incoming, this._def);
2547
2548
  }
2548
2549
  transform(transform) {
2549
2550
  return new ZodEffects({
2551
+ ...processCreateParams(this._def),
2550
2552
  schema: this,
2551
2553
  typeName: ZodFirstPartyTypeKind.ZodEffects,
2552
2554
  effect: { type: "transform", transform }
@@ -2555,6 +2557,7 @@ var init_lib = __esm({
2555
2557
  default(def) {
2556
2558
  const defaultValueFunc = typeof def === "function" ? def : () => def;
2557
2559
  return new ZodDefault({
2560
+ ...processCreateParams(this._def),
2558
2561
  innerType: this,
2559
2562
  defaultValue: defaultValueFunc,
2560
2563
  typeName: ZodFirstPartyTypeKind.ZodDefault
@@ -2564,14 +2567,15 @@ var init_lib = __esm({
2564
2567
  return new ZodBranded({
2565
2568
  typeName: ZodFirstPartyTypeKind.ZodBranded,
2566
2569
  type: this,
2567
- ...processCreateParams(void 0)
2570
+ ...processCreateParams(this._def)
2568
2571
  });
2569
2572
  }
2570
2573
  catch(def) {
2571
- const defaultValueFunc = typeof def === "function" ? def : () => def;
2574
+ const catchValueFunc = typeof def === "function" ? def : () => def;
2572
2575
  return new ZodCatch({
2576
+ ...processCreateParams(this._def),
2573
2577
  innerType: this,
2574
- defaultValue: defaultValueFunc,
2578
+ catchValue: catchValueFunc,
2575
2579
  typeName: ZodFirstPartyTypeKind.ZodCatch
2576
2580
  });
2577
2581
  }
@@ -2593,24 +2597,25 @@ var init_lib = __esm({
2593
2597
  }
2594
2598
  };
2595
2599
  cuidRegex = /^c[^\s-]{8,}$/i;
2600
+ cuid2Regex = /^[a-z][a-z0-9]*$/;
2596
2601
  uuidRegex = /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
2597
- emailRegex = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
2602
+ emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|([^-]([a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}))$/;
2598
2603
  datetimeRegex = (args) => {
2599
2604
  if (args.precision) {
2600
2605
  if (args.offset) {
2601
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}:\\d{2})|Z)$`);
2606
+ return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
2602
2607
  } else {
2603
2608
  return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`);
2604
2609
  }
2605
2610
  } else if (args.precision === 0) {
2606
2611
  if (args.offset) {
2607
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}:\\d{2})|Z)$`);
2612
+ return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
2608
2613
  } else {
2609
2614
  return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`);
2610
2615
  }
2611
2616
  } else {
2612
2617
  if (args.offset) {
2613
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$`);
2618
+ return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
2614
2619
  } else {
2615
2620
  return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`);
2616
2621
  }
@@ -2732,6 +2737,16 @@ var init_lib = __esm({
2732
2737
  });
2733
2738
  status.dirty();
2734
2739
  }
2740
+ } else if (check.kind === "cuid2") {
2741
+ if (!cuid2Regex.test(input.data)) {
2742
+ ctx = this._getOrReturnCtx(input, ctx);
2743
+ addIssueToContext(ctx, {
2744
+ validation: "cuid2",
2745
+ code: ZodIssueCode.invalid_string,
2746
+ message: check.message
2747
+ });
2748
+ status.dirty();
2749
+ }
2735
2750
  } else if (check.kind === "url") {
2736
2751
  try {
2737
2752
  new URL(input.data);
@@ -2813,6 +2828,9 @@ var init_lib = __esm({
2813
2828
  cuid(message) {
2814
2829
  return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
2815
2830
  }
2831
+ cuid2(message) {
2832
+ return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
2833
+ }
2816
2834
  datetime(options) {
2817
2835
  var _a;
2818
2836
  if (typeof options === "string") {
@@ -2887,6 +2905,9 @@ var init_lib = __esm({
2887
2905
  get isCUID() {
2888
2906
  return !!this._def.checks.find((ch) => ch.kind === "cuid");
2889
2907
  }
2908
+ get isCUID2() {
2909
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
2910
+ }
2890
2911
  get minLength() {
2891
2912
  let min = null;
2892
2913
  for (const ch of this._def.checks) {
@@ -3109,7 +3130,22 @@ var init_lib = __esm({
3109
3130
  return max;
3110
3131
  }
3111
3132
  get isInt() {
3112
- return !!this._def.checks.find((ch) => ch.kind === "int");
3133
+ return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
3134
+ }
3135
+ get isFinite() {
3136
+ let max = null, min = null;
3137
+ for (const ch of this._def.checks) {
3138
+ if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
3139
+ return true;
3140
+ } else if (ch.kind === "min") {
3141
+ if (min === null || ch.value > min)
3142
+ min = ch.value;
3143
+ } else if (ch.kind === "max") {
3144
+ if (max === null || ch.value < max)
3145
+ max = ch.value;
3146
+ }
3147
+ }
3148
+ return Number.isFinite(min) && Number.isFinite(max);
3113
3149
  }
3114
3150
  };
3115
3151
  ZodNumber.create = (params) => {
@@ -3466,13 +3502,13 @@ var init_lib = __esm({
3466
3502
  }
3467
3503
  }
3468
3504
  if (ctx.common.async) {
3469
- return Promise.all(ctx.data.map((item, i) => {
3505
+ return Promise.all([...ctx.data].map((item, i) => {
3470
3506
  return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
3471
3507
  })).then((result2) => {
3472
3508
  return ParseStatus.mergeArray(status, result2);
3473
3509
  });
3474
3510
  }
3475
- const result = ctx.data.map((item, i) => {
3511
+ const result = [...ctx.data].map((item, i) => {
3476
3512
  return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
3477
3513
  });
3478
3514
  return ParseStatus.mergeArray(status, result);
@@ -3520,22 +3556,12 @@ var init_lib = __esm({
3520
3556
  };
3521
3557
  };
3522
3558
  })(objectUtil || (objectUtil = {}));
3523
- AugmentFactory = (def) => (augmentation) => {
3524
- return new ZodObject({
3525
- ...def,
3526
- shape: () => ({
3527
- ...def.shape(),
3528
- ...augmentation
3529
- })
3530
- });
3531
- };
3532
3559
  ZodObject = class extends ZodType {
3533
3560
  constructor() {
3534
3561
  super(...arguments);
3535
3562
  this._cached = null;
3536
3563
  this.nonstrict = this.passthrough;
3537
- this.augment = AugmentFactory(this._def);
3538
- this.extend = AugmentFactory(this._def);
3564
+ this.augment = this.extend;
3539
3565
  }
3540
3566
  _getCached() {
3541
3567
  if (this._cached !== null)
@@ -3664,8 +3690,14 @@ var init_lib = __esm({
3664
3690
  unknownKeys: "passthrough"
3665
3691
  });
3666
3692
  }
3667
- setKey(key, schema4) {
3668
- return this.augment({ [key]: schema4 });
3693
+ extend(augmentation) {
3694
+ return new ZodObject({
3695
+ ...this._def,
3696
+ shape: () => ({
3697
+ ...this._def.shape(),
3698
+ ...augmentation
3699
+ })
3700
+ });
3669
3701
  }
3670
3702
  merge(merging) {
3671
3703
  const merged = new ZodObject({
@@ -3676,6 +3708,9 @@ var init_lib = __esm({
3676
3708
  });
3677
3709
  return merged;
3678
3710
  }
3711
+ setKey(key, schema4) {
3712
+ return this.augment({ [key]: schema4 });
3713
+ }
3679
3714
  catchall(index4) {
3680
3715
  return new ZodObject({
3681
3716
  ...this._def,
@@ -3684,9 +3719,10 @@ var init_lib = __esm({
3684
3719
  }
3685
3720
  pick(mask) {
3686
3721
  const shape = {};
3687
- util.objectKeys(mask).map((key) => {
3688
- if (this.shape[key])
3722
+ util.objectKeys(mask).forEach((key) => {
3723
+ if (mask[key] && this.shape[key]) {
3689
3724
  shape[key] = this.shape[key];
3725
+ }
3690
3726
  });
3691
3727
  return new ZodObject({
3692
3728
  ...this._def,
@@ -3695,8 +3731,8 @@ var init_lib = __esm({
3695
3731
  }
3696
3732
  omit(mask) {
3697
3733
  const shape = {};
3698
- util.objectKeys(this.shape).map((key) => {
3699
- if (util.objectKeys(mask).indexOf(key) === -1) {
3734
+ util.objectKeys(this.shape).forEach((key) => {
3735
+ if (!mask[key]) {
3700
3736
  shape[key] = this.shape[key];
3701
3737
  }
3702
3738
  });
@@ -3710,24 +3746,14 @@ var init_lib = __esm({
3710
3746
  }
3711
3747
  partial(mask) {
3712
3748
  const newShape = {};
3713
- if (mask) {
3714
- util.objectKeys(this.shape).map((key) => {
3715
- if (util.objectKeys(mask).indexOf(key) === -1) {
3716
- newShape[key] = this.shape[key];
3717
- } else {
3718
- newShape[key] = this.shape[key].optional();
3719
- }
3720
- });
3721
- return new ZodObject({
3722
- ...this._def,
3723
- shape: () => newShape
3724
- });
3725
- } else {
3726
- for (const key in this.shape) {
3727
- const fieldSchema = this.shape[key];
3749
+ util.objectKeys(this.shape).forEach((key) => {
3750
+ const fieldSchema = this.shape[key];
3751
+ if (mask && !mask[key]) {
3752
+ newShape[key] = fieldSchema;
3753
+ } else {
3728
3754
  newShape[key] = fieldSchema.optional();
3729
3755
  }
3730
- }
3756
+ });
3731
3757
  return new ZodObject({
3732
3758
  ...this._def,
3733
3759
  shape: () => newShape
@@ -3735,21 +3761,10 @@ var init_lib = __esm({
3735
3761
  }
3736
3762
  required(mask) {
3737
3763
  const newShape = {};
3738
- if (mask) {
3739
- util.objectKeys(this.shape).map((key) => {
3740
- if (util.objectKeys(mask).indexOf(key) === -1) {
3741
- newShape[key] = this.shape[key];
3742
- } else {
3743
- const fieldSchema = this.shape[key];
3744
- let newField = fieldSchema;
3745
- while (newField instanceof ZodOptional) {
3746
- newField = newField._def.innerType;
3747
- }
3748
- newShape[key] = newField;
3749
- }
3750
- });
3751
- } else {
3752
- for (const key in this.shape) {
3764
+ util.objectKeys(this.shape).forEach((key) => {
3765
+ if (mask && !mask[key]) {
3766
+ newShape[key] = this.shape[key];
3767
+ } else {
3753
3768
  const fieldSchema = this.shape[key];
3754
3769
  let newField = fieldSchema;
3755
3770
  while (newField instanceof ZodOptional) {
@@ -3757,7 +3772,7 @@ var init_lib = __esm({
3757
3772
  }
3758
3773
  newShape[key] = newField;
3759
3774
  }
3760
- }
3775
+ });
3761
3776
  return new ZodObject({
3762
3777
  ...this._def,
3763
3778
  shape: () => newShape
@@ -4059,7 +4074,7 @@ var init_lib = __esm({
4059
4074
  });
4060
4075
  status.dirty();
4061
4076
  }
4062
- const items = ctx.data.map((item, itemIndex) => {
4077
+ const items = [...ctx.data].map((item, itemIndex) => {
4063
4078
  const schema4 = this._def.items[itemIndex] || this._def.rest;
4064
4079
  if (!schema4)
4065
4080
  return null;
@@ -4426,6 +4441,7 @@ var init_lib = __esm({
4426
4441
  if (input.data !== this._def.value) {
4427
4442
  const ctx = this._getOrReturnCtx(input);
4428
4443
  addIssueToContext(ctx, {
4444
+ received: ctx.data,
4429
4445
  code: ZodIssueCode.invalid_literal,
4430
4446
  expected: this._def.value
4431
4447
  });
@@ -4492,6 +4508,12 @@ var init_lib = __esm({
4492
4508
  }
4493
4509
  return enumValues;
4494
4510
  }
4511
+ extract(values) {
4512
+ return ZodEnum.create(values);
4513
+ }
4514
+ exclude(values) {
4515
+ return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));
4516
+ }
4495
4517
  };
4496
4518
  ZodEnum.create = createZodEnum;
4497
4519
  ZodNativeEnum = class extends ZodType {
@@ -4530,6 +4552,9 @@ var init_lib = __esm({
4530
4552
  });
4531
4553
  };
4532
4554
  ZodPromise = class extends ZodType {
4555
+ unwrap() {
4556
+ return this._def.type;
4557
+ }
4533
4558
  _parse(input) {
4534
4559
  const { ctx } = this._processInputParams(input);
4535
4560
  if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
@@ -4743,23 +4768,29 @@ var init_lib = __esm({
4743
4768
  const result = this._def.innerType._parse({
4744
4769
  data: ctx.data,
4745
4770
  path: ctx.path,
4746
- parent: ctx
4771
+ parent: {
4772
+ ...ctx,
4773
+ common: {
4774
+ ...ctx.common,
4775
+ issues: []
4776
+ }
4777
+ }
4747
4778
  });
4748
4779
  if (isAsync(result)) {
4749
4780
  return result.then((result2) => {
4750
4781
  return {
4751
4782
  status: "valid",
4752
- value: result2.status === "valid" ? result2.value : this._def.defaultValue()
4783
+ value: result2.status === "valid" ? result2.value : this._def.catchValue()
4753
4784
  };
4754
4785
  });
4755
4786
  } else {
4756
4787
  return {
4757
4788
  status: "valid",
4758
- value: result.status === "valid" ? result.value : this._def.defaultValue()
4789
+ value: result.status === "valid" ? result.value : this._def.catchValue()
4759
4790
  };
4760
4791
  }
4761
4792
  }
4762
- removeDefault() {
4793
+ removeCatch() {
4763
4794
  return this._def.innerType;
4764
4795
  }
4765
4796
  };
@@ -4767,7 +4798,7 @@ var init_lib = __esm({
4767
4798
  return new ZodCatch({
4768
4799
  innerType: type,
4769
4800
  typeName: ZodFirstPartyTypeKind.ZodCatch,
4770
- defaultValue: typeof params.default === "function" ? params.default : () => params.default,
4801
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
4771
4802
  ...processCreateParams(params)
4772
4803
  });
4773
4804
  };
@@ -4939,7 +4970,10 @@ var init_lib = __esm({
4939
4970
  coerce = {
4940
4971
  string: (arg) => ZodString.create({ ...arg, coerce: true }),
4941
4972
  number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
4942
- boolean: (arg) => ZodBoolean.create({ ...arg, coerce: true }),
4973
+ boolean: (arg) => ZodBoolean.create({
4974
+ ...arg,
4975
+ coerce: true
4976
+ }),
4943
4977
  bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
4944
4978
  date: (arg) => ZodDate.create({ ...arg, coerce: true })
4945
4979
  };
@@ -5982,6 +6016,7 @@ var require_hanji = __commonJS({
5982
6016
  var import_hanji, err, info, error, schema, isRenamePromptItem, ResolveColumnSelect, ResolveTableSelect, ResolveSchemasSelect, Spinner, IntrospectProgress, DropMigrationView, trimmedRange;
5983
6017
  var init_views = __esm({
5984
6018
  "src/cli/views.ts"() {
6019
+ "use strict";
5985
6020
  init_source();
5986
6021
  import_hanji = __toESM(require_hanji());
5987
6022
  err = (msg) => {
@@ -6303,15 +6338,17 @@ Is ${source_default.bold.blue(
6303
6338
  var originUUID, snapshotVersion;
6304
6339
  var init_global = __esm({
6305
6340
  "src/global.ts"() {
6341
+ "use strict";
6306
6342
  originUUID = "00000000-0000-0000-0000-000000000000";
6307
6343
  snapshotVersion = "5";
6308
6344
  }
6309
6345
  });
6310
6346
 
6311
6347
  // src/serializer/mysqlSchema.ts
6312
- var index, fk, column, tableV3, table, dialect, schemaHash, schemaInternalV3, schemaInternalV4, schemaInternal, schemaV3, schemaV4, schema2, tableSquashed, schemaSquashed, MySqlSquasher, squashMysqlScheme, mysqlSchema, mysqlSchemaV4, mysqlSchemaV3, backwardCompatibleMysqlSchema, dryMySql;
6348
+ var index, fk, column, tableV3, compositePK, table, dialect, schemaHash, schemaInternalV3, schemaInternalV4, schemaInternal, schemaV3, schemaV4, schema2, tableSquashed, schemaSquashed, MySqlSquasher, squashMysqlScheme, mysqlSchema, mysqlSchemaV4, mysqlSchemaV3, backwardCompatibleMysqlSchema, dryMySql;
6313
6349
  var init_mysqlSchema = __esm({
6314
6350
  "src/serializer/mysqlSchema.ts"() {
6351
+ "use strict";
6315
6352
  init_global();
6316
6353
  init_utils();
6317
6354
  init_lib();
@@ -6347,12 +6384,17 @@ var init_mysqlSchema = __esm({
6347
6384
  indexes: recordType(stringType(), index),
6348
6385
  foreignKeys: recordType(stringType(), fk)
6349
6386
  }).strict();
6387
+ compositePK = objectType({
6388
+ name: stringType(),
6389
+ columns: stringType().array()
6390
+ }).strict();
6350
6391
  table = objectType({
6351
6392
  name: stringType(),
6352
6393
  schema: stringType().optional(),
6353
6394
  columns: recordType(stringType(), column),
6354
6395
  indexes: recordType(stringType(), index),
6355
- foreignKeys: recordType(stringType(), fk)
6396
+ foreignKeys: recordType(stringType(), fk),
6397
+ compositePrimaryKeys: recordType(stringType(), compositePK)
6356
6398
  }).strict();
6357
6399
  dialect = literalType("mysql");
6358
6400
  schemaHash = objectType({
@@ -6389,7 +6431,8 @@ var init_mysqlSchema = __esm({
6389
6431
  schema: stringType().optional(),
6390
6432
  columns: recordType(stringType(), column),
6391
6433
  indexes: recordType(stringType(), stringType()),
6392
- foreignKeys: recordType(stringType(), stringType())
6434
+ foreignKeys: recordType(stringType(), stringType()),
6435
+ compositePrimaryKeys: recordType(stringType(), stringType())
6393
6436
  }).strict();
6394
6437
  schemaSquashed = objectType({
6395
6438
  version: literalType("5"),
@@ -6415,6 +6458,13 @@ var init_mysqlSchema = __esm({
6415
6458
  };
6416
6459
  return index.parse(destructed);
6417
6460
  },
6461
+ squashPK: (pk) => {
6462
+ return `${pk.name};${pk.columns.join(",")}`;
6463
+ },
6464
+ unsquashPK: (pk) => {
6465
+ const splitted = pk.split(";");
6466
+ return { name: splitted[0], columns: splitted[1].split(",") };
6467
+ },
6418
6468
  squashFK: (fk4) => {
6419
6469
  var _a, _b;
6420
6470
  return `${fk4.name};${fk4.tableFrom};${fk4.columnsFrom.join(",")};${fk4.tableTo};${fk4.columnsTo.join(",")};${(_a = fk4.onUpdate) != null ? _a : ""};${(_b = fk4.onDelete) != null ? _b : ""}`;
@@ -6450,6 +6500,9 @@ var init_mysqlSchema = __esm({
6450
6500
  const squashedFKs = mapValues(it[1].foreignKeys, (fk4) => {
6451
6501
  return MySqlSquasher.squashFK(fk4);
6452
6502
  });
6503
+ const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
6504
+ return MySqlSquasher.squashPK(pk);
6505
+ });
6453
6506
  return [
6454
6507
  it[0],
6455
6508
  {
@@ -6457,7 +6510,8 @@ var init_mysqlSchema = __esm({
6457
6510
  schema: it[1].schema,
6458
6511
  columns: it[1].columns,
6459
6512
  indexes: squashedIndexes,
6460
- foreignKeys: squashedFKs
6513
+ foreignKeys: squashedFKs,
6514
+ compositePrimaryKeys: squashedPKs
6461
6515
  }
6462
6516
  ];
6463
6517
  })
@@ -6490,9 +6544,10 @@ var init_mysqlSchema = __esm({
6490
6544
  });
6491
6545
 
6492
6546
  // src/serializer/pgSchema.ts
6493
- var indexV2, columnV2, tableV2, enumSchema, pgSchemaV2, references, columnV1, tableV1, pgSchemaV1, index2, fk2, column2, tableV32, table2, schemaHash2, pgSchemaInternalV3, pgSchemaInternalV4, pgSchemaInternal, tableSquashed2, pgSchemaSquashed, pgSchemaV3, pgSchemaV4, pgSchema, backwardCompatiblePgSchema, PgSquasher, squashPgScheme, dryPg;
6547
+ var indexV2, columnV2, tableV2, enumSchema, pgSchemaV2, references, columnV1, tableV1, pgSchemaV1, index2, fk2, column2, tableV32, compositePK2, table2, schemaHash2, pgSchemaInternalV3, pgSchemaInternalV4, pgSchemaInternal, tableSquashed2, pgSchemaSquashed, pgSchemaV3, pgSchemaV4, pgSchema, backwardCompatiblePgSchema, PgSquasher, squashPgScheme, dryPg;
6494
6548
  var init_pgSchema = __esm({
6495
6549
  "src/serializer/pgSchema.ts"() {
6550
+ "use strict";
6496
6551
  init_global();
6497
6552
  init_utils();
6498
6553
  init_lib();
@@ -6580,12 +6635,17 @@ var init_pgSchema = __esm({
6580
6635
  indexes: recordType(stringType(), index2),
6581
6636
  foreignKeys: recordType(stringType(), fk2)
6582
6637
  }).strict();
6638
+ compositePK2 = objectType({
6639
+ name: stringType(),
6640
+ columns: stringType().array()
6641
+ }).strict();
6583
6642
  table2 = objectType({
6584
6643
  name: stringType(),
6585
6644
  schema: stringType(),
6586
6645
  columns: recordType(stringType(), column2),
6587
6646
  indexes: recordType(stringType(), index2),
6588
- foreignKeys: recordType(stringType(), fk2)
6647
+ foreignKeys: recordType(stringType(), fk2),
6648
+ compositePrimaryKeys: recordType(stringType(), compositePK2)
6589
6649
  }).strict();
6590
6650
  schemaHash2 = objectType({
6591
6651
  id: stringType(),
@@ -6621,7 +6681,8 @@ var init_pgSchema = __esm({
6621
6681
  schema: stringType(),
6622
6682
  columns: recordType(stringType(), column2),
6623
6683
  indexes: recordType(stringType(), stringType()),
6624
- foreignKeys: recordType(stringType(), stringType())
6684
+ foreignKeys: recordType(stringType(), stringType()),
6685
+ compositePrimaryKeys: recordType(stringType(), stringType())
6625
6686
  }).strict();
6626
6687
  pgSchemaSquashed = objectType({
6627
6688
  version: literalType("5"),
@@ -6658,6 +6719,12 @@ var init_pgSchema = __esm({
6658
6719
  var _a, _b;
6659
6720
  return `${fk4.name};${fk4.tableFrom};${fk4.columnsFrom.join(",")};${fk4.tableTo};${fk4.columnsTo.join(",")};${(_a = fk4.onUpdate) != null ? _a : ""};${(_b = fk4.onDelete) != null ? _b : ""}`;
6660
6721
  },
6722
+ squashPK: (pk) => {
6723
+ return `${pk.columns.join(",")}`;
6724
+ },
6725
+ unsquashPK: (pk) => {
6726
+ return { name: "", columns: pk.split(",") };
6727
+ },
6661
6728
  unsquashFK: (input) => {
6662
6729
  const [
6663
6730
  name,
@@ -6689,6 +6756,9 @@ var init_pgSchema = __esm({
6689
6756
  const squashedFKs = mapValues(it[1].foreignKeys, (fk4) => {
6690
6757
  return PgSquasher.squashFK(fk4);
6691
6758
  });
6759
+ const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
6760
+ return PgSquasher.squashPK(pk);
6761
+ });
6692
6762
  return [
6693
6763
  it[0],
6694
6764
  {
@@ -6696,7 +6766,8 @@ var init_pgSchema = __esm({
6696
6766
  schema: it[1].schema,
6697
6767
  columns: it[1].columns,
6698
6768
  indexes: squashedIndexes,
6699
- foreignKeys: squashedFKs
6769
+ foreignKeys: squashedFKs,
6770
+ compositePrimaryKeys: squashedPKs
6700
6771
  }
6701
6772
  ];
6702
6773
  })
@@ -6727,9 +6798,10 @@ var init_pgSchema = __esm({
6727
6798
  });
6728
6799
 
6729
6800
  // src/serializer/sqliteSchema.ts
6730
- var index3, fk3, compositePK, column3, tableV33, table3, dialect2, schemaHash3, schemaInternalV32, schemaInternalV42, latestVersion, schemaInternal2, schemaV32, schemaV42, schema3, tableSquashed3, schemaSquashed2, SQLiteSquasher, squashSqliteScheme, drySQLite, sqliteSchemaV3, sqliteSchemaV4, sqliteSchema, backwardCompatibleSqliteSchema;
6801
+ var index3, fk3, compositePK3, column3, tableV33, table3, dialect2, schemaHash3, schemaInternalV32, schemaInternalV42, latestVersion, schemaInternal2, schemaV32, schemaV42, schema3, tableSquashed3, schemaSquashed2, SQLiteSquasher, squashSqliteScheme, drySQLite, sqliteSchemaV3, sqliteSchemaV4, sqliteSchema, backwardCompatibleSqliteSchema;
6731
6802
  var init_sqliteSchema = __esm({
6732
6803
  "src/serializer/sqliteSchema.ts"() {
6804
+ "use strict";
6733
6805
  init_global();
6734
6806
  init_utils();
6735
6807
  init_lib();
@@ -6748,7 +6820,7 @@ var init_sqliteSchema = __esm({
6748
6820
  onUpdate: stringType().optional(),
6749
6821
  onDelete: stringType().optional()
6750
6822
  }).strict();
6751
- compositePK = objectType({
6823
+ compositePK3 = objectType({
6752
6824
  columns: stringType().array()
6753
6825
  }).strict();
6754
6826
  column3 = objectType({
@@ -6770,7 +6842,7 @@ var init_sqliteSchema = __esm({
6770
6842
  columns: recordType(stringType(), column3),
6771
6843
  indexes: recordType(stringType(), index3),
6772
6844
  foreignKeys: recordType(stringType(), fk3),
6773
- compositePrimaryKeys: recordType(stringType(), compositePK)
6845
+ compositePrimaryKeys: recordType(stringType(), compositePK3)
6774
6846
  }).strict();
6775
6847
  dialect2 = enumType(["sqlite"]);
6776
6848
  schemaHash3 = objectType({
@@ -6889,7 +6961,7 @@ var init_sqliteSchema = __esm({
6889
6961
  })
6890
6962
  );
6891
6963
  return {
6892
- version: json.version,
6964
+ version: "5",
6893
6965
  dialect: json.dialect,
6894
6966
  tables: mappedTables,
6895
6967
  enums: json.enums
@@ -9852,7 +9924,7 @@ var require_get = __commonJS({
9852
9924
  return lastId;
9853
9925
  },
9854
9926
  delete: function(id) {
9855
- var index4 = 0, set = map, i, args = cache[id], length = args.length, path4 = [];
9927
+ var index4 = 0, set = map, i, args = cache[id], length = args.length, path2 = [];
9856
9928
  if (length === 0) {
9857
9929
  delete set[length];
9858
9930
  } else if (set = set[length]) {
@@ -9861,7 +9933,7 @@ var require_get = __commonJS({
9861
9933
  if (i === -1) {
9862
9934
  return;
9863
9935
  }
9864
- path4.push(set, i);
9936
+ path2.push(set, i);
9865
9937
  set = set[1][i];
9866
9938
  ++index4;
9867
9939
  }
@@ -9872,9 +9944,9 @@ var require_get = __commonJS({
9872
9944
  id = set[1][i];
9873
9945
  set[0].splice(i, 1);
9874
9946
  set[1].splice(i, 1);
9875
- while (!set[0].length && path4.length) {
9876
- i = path4.pop();
9877
- set = path4.pop();
9947
+ while (!set[0].length && path2.length) {
9948
+ i = path2.pop();
9949
+ set = path2.pop();
9878
9950
  set[0].splice(i, 1);
9879
9951
  set[1].splice(i, 1);
9880
9952
  }
@@ -9966,13 +10038,13 @@ var require_get_fixed = __commonJS({
9966
10038
  return lastId;
9967
10039
  },
9968
10040
  delete: function(id) {
9969
- var index4 = 0, set = map, i, path4 = [], args = cache[id];
10041
+ var index4 = 0, set = map, i, path2 = [], args = cache[id];
9970
10042
  while (index4 < length - 1) {
9971
10043
  i = indexOf.call(set[0], args[index4]);
9972
10044
  if (i === -1) {
9973
10045
  return;
9974
10046
  }
9975
- path4.push(set, i);
10047
+ path2.push(set, i);
9976
10048
  set = set[1][i];
9977
10049
  ++index4;
9978
10050
  }
@@ -9983,9 +10055,9 @@ var require_get_fixed = __commonJS({
9983
10055
  id = set[1][i];
9984
10056
  set[0].splice(i, 1);
9985
10057
  set[1].splice(i, 1);
9986
- while (!set[0].length && path4.length) {
9987
- i = path4.pop();
9988
- set = path4.pop();
10058
+ while (!set[0].length && path2.length) {
10059
+ i = path2.pop();
10060
+ set = path2.pop();
9989
10061
  set[0].splice(i, 1);
9990
10062
  set[1].splice(i, 1);
9991
10063
  }
@@ -13097,6 +13169,7 @@ function applyJsonDiff(json1, json2) {
13097
13169
  var import_json_diff, findAlternationsInTable, alternationsInColumn;
13098
13170
  var init_jsonDiffer = __esm({
13099
13171
  "src/jsonDiffer.js"() {
13172
+ "use strict";
13100
13173
  import_json_diff = __toESM(require_lib());
13101
13174
  "use-strict";
13102
13175
  findAlternationsInTable = (table4, tableSchema) => {
@@ -13238,9 +13311,10 @@ var init_jsonDiffer = __esm({
13238
13311
  });
13239
13312
 
13240
13313
  // src/sqlgenerator.ts
13241
- var pgNativeTypes, isPgNativeType, Convertor, PgCreateTableConvertor, MySqlCreateTableConvertor, SQLiteCreateTableConvertor, CreateTypeEnumConvertor, AlterTypeAddValueConvertor, DropTableConvertor, PgRenameTableConvertor, SqliteRenameTableConvertor, MySqlRenameTableConvertor, PgAlterTableRenameColumnConvertor, MySqlAlterTableRenameColumnConvertor, SQLiteAlterTableRenameColumnConvertor, PgAlterTableDropColumnConvertor, MySqlAlterTableDropColumnConvertor, SQLiteAlterTableDropColumnConvertor, PgAlterTableAddColumnConvertor, MySqlAlterTableAddColumnConvertor, SQLiteAlterTableAddColumnConvertor, PgAlterTableAlterColumnSetTypeConvertor, SQLiteAlterTableAlterColumnSetTypeConvertor, PgAlterTableAlterColumnSetDefaultConvertor, SqliteAlterTableAlterColumnSetDefaultConvertor, PgAlterTableAlterColumnDropDefaultConvertor, MySqlAlterTableAlterColumnSetDefaultConvertor, MySqlAlterTableAlterColumnDropDefaultConvertor, MySqlModifyColumn, SqliteAlterTableAlterColumnDropDefaultConvertor, SqliteAlterTableCreateCompositePrimaryKeyConvertor, SqliteAlterTableDeleteCompositePrimaryKeyConvertor, SqliteAlterTableAlterCompositePrimaryKeyConvertor, PgAlterTableAlterColumnSetNotNullConvertor, SqliteAlterTableAlterColumnSetNotNullConvertor, PgAlterTableAlterColumnDropNotNullConvertor, SqliteAlterTableAlterColumnDropNotNullConvertor, PgCreateForeignKeyConvertor, SqliteCreateForeignKeyConvertor, MySqlCreateForeignKeyConvertor, PgAlterForeignKeyConvertor, SqliteAlterForeignKeyConvertor, PgDeleteForeignKeyConvertor, SqliteDeleteForeignKeyConvertor, MySqlDeleteForeignKeyConvertor, CreatePgIndexConvertor, CreateMySqlIndexConvertor, CreateSqliteIndexConvertor, PgDropIndexConvertor, PgCreateSchemaConvertor, PgRenameSchemaConvertor, PgDropSchemaConvertor, PgAlterTableSetSchemaConvertor, PgAlterTableSetNewSchemaConvertor, PgAlterTableRemoveFromSchemaConvertor, SqliteDropIndexConvertor, MysqlCreateSchemaConvertor, MysqlDropSchemaConvertor, MysqlAlterTableSetSchemaConvertor, MysqlAlterTableSetNewSchemaConvertor, MysqlAlterTableRemoveFromSchemaConvertor, MySqlDropIndexConvertor, convertors, fromJson;
13314
+ var pgNativeTypes, isPgNativeType, Convertor, PgCreateTableConvertor, MySqlCreateTableConvertor, SQLiteCreateTableConvertor, CreateTypeEnumConvertor, AlterTypeAddValueConvertor, DropTableConvertor, PgRenameTableConvertor, SqliteRenameTableConvertor, MySqlRenameTableConvertor, PgAlterTableRenameColumnConvertor, MySqlAlterTableRenameColumnConvertor, SQLiteAlterTableRenameColumnConvertor, PgAlterTableDropColumnConvertor, MySqlAlterTableDropColumnConvertor, SQLiteAlterTableDropColumnConvertor, PgAlterTableAddColumnConvertor, MySqlAlterTableAddColumnConvertor, SQLiteAlterTableAddColumnConvertor, PgAlterTableAlterColumnSetTypeConvertor, SQLiteAlterTableAlterColumnSetTypeConvertor, PgAlterTableAlterColumnSetDefaultConvertor, SqliteAlterTableAlterColumnSetDefaultConvertor, PgAlterTableAlterColumnDropDefaultConvertor, MySqlAlterTableAlterColumnSetDefaultConvertor, MySqlAlterTableAlterColumnDropDefaultConvertor, MySqlModifyColumn, SqliteAlterTableAlterColumnDropDefaultConvertor, PgAlterTableCreateCompositePrimaryKeyConvertor, PgAlterTableDeleteCompositePrimaryKeyConvertor, PgAlterTableAlterCompositePrimaryKeyConvertor, MySqlAlterTableCreateCompositePrimaryKeyConvertor, MySqlAlterTableDeleteCompositePrimaryKeyConvertor, MySqlAlterTableAlterCompositePrimaryKeyConvertor, SqliteAlterTableCreateCompositePrimaryKeyConvertor, SqliteAlterTableDeleteCompositePrimaryKeyConvertor, SqliteAlterTableAlterCompositePrimaryKeyConvertor, PgAlterTableAlterColumnSetNotNullConvertor, SqliteAlterTableAlterColumnSetNotNullConvertor, PgAlterTableAlterColumnDropNotNullConvertor, SqliteAlterTableAlterColumnDropNotNullConvertor, PgCreateForeignKeyConvertor, SqliteCreateForeignKeyConvertor, MySqlCreateForeignKeyConvertor, PgAlterForeignKeyConvertor, SqliteAlterForeignKeyConvertor, PgDeleteForeignKeyConvertor, SqliteDeleteForeignKeyConvertor, MySqlDeleteForeignKeyConvertor, CreatePgIndexConvertor, CreateMySqlIndexConvertor, CreateSqliteIndexConvertor, PgDropIndexConvertor, PgCreateSchemaConvertor, PgRenameSchemaConvertor, PgDropSchemaConvertor, PgAlterTableSetSchemaConvertor, PgAlterTableSetNewSchemaConvertor, PgAlterTableRemoveFromSchemaConvertor, SqliteDropIndexConvertor, MysqlCreateSchemaConvertor, MysqlDropSchemaConvertor, MysqlAlterTableSetSchemaConvertor, MysqlAlterTableSetNewSchemaConvertor, MysqlAlterTableRemoveFromSchemaConvertor, MySqlDropIndexConvertor, convertors, fromJson;
13242
13315
  var init_sqlgenerator = __esm({
13243
13316
  "src/sqlgenerator.ts"() {
13317
+ "use strict";
13244
13318
  init_mysqlSchema();
13245
13319
  init_pgSchema();
13246
13320
  init_sqliteSchema();
@@ -13270,13 +13344,26 @@ var init_sqlgenerator = __esm({
13270
13344
  "interval",
13271
13345
  "bigint",
13272
13346
  "bigserial",
13273
- "double precision"
13347
+ "double precision",
13348
+ "interval year",
13349
+ "interval month",
13350
+ "interval day",
13351
+ "interval hour",
13352
+ "interval minute",
13353
+ "interval second",
13354
+ "interval year to month",
13355
+ "interval day to hour",
13356
+ "interval day to minute",
13357
+ "interval day to second",
13358
+ "interval hour to minute",
13359
+ "interval hour to second",
13360
+ "interval minute to second"
13274
13361
  ]);
13275
13362
  isPgNativeType = (it) => {
13276
13363
  if (pgNativeTypes.has(it))
13277
13364
  return true;
13278
13365
  const toCheck = it.replace(/ /g, "");
13279
- return toCheck.startsWith("varchar(") || toCheck.startsWith("numeric(") || toCheck.startsWith("timestamp(");
13366
+ return toCheck.startsWith("varchar(") || toCheck.startsWith("char(") || toCheck.startsWith("numeric(") || toCheck.startsWith("timestamp(");
13280
13367
  };
13281
13368
  Convertor = class {
13282
13369
  };
@@ -13285,7 +13372,7 @@ var init_sqlgenerator = __esm({
13285
13372
  return statement.type === "create_table" && dialect6 === "pg";
13286
13373
  }
13287
13374
  convert(st) {
13288
- const { tableName, schema: schema4, columns } = st;
13375
+ const { tableName, schema: schema4, columns, compositePKs } = st;
13289
13376
  let statement = "";
13290
13377
  const name = schema4 ? `"${schema4}"."${tableName}"` : `"${tableName}"`;
13291
13378
  statement += `CREATE TABLE IF NOT EXISTS ${name} (
@@ -13295,13 +13382,19 @@ var init_sqlgenerator = __esm({
13295
13382
  const primaryKeyStatement = column6.primaryKey ? "PRIMARY KEY" : "";
13296
13383
  const notNullStatement = column6.notNull ? "NOT NULL" : "";
13297
13384
  const defaultStatement = column6.default !== void 0 ? `DEFAULT ${column6.default}` : "";
13298
- const type = isPgNativeType(column6.type) ? column6.type : `"${column6.type}"`;
13385
+ const type = isPgNativeType(column6.type) ? column6.type : `${column6.type}`;
13299
13386
  statement += " " + `"${column6.name}" ${type} ${primaryKeyStatement} ${defaultStatement} ${notNullStatement}`.replace(/ +/g, " ").trim();
13300
13387
  statement += (i === columns.length - 1 ? "" : ",") + "\n";
13301
13388
  }
13302
13389
  statement += `);`;
13303
13390
  statement += `
13304
13391
  `;
13392
+ if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
13393
+ const compositePK4 = PgSquasher.unsquashPK(compositePKs[0]);
13394
+ statement += `ALTER TABLE ${name} ADD CONSTRAINT "${st.compositePkName}" PRIMARY KEY("${compositePK4.columns.join('","')}");`;
13395
+ statement += `
13396
+ `;
13397
+ }
13305
13398
  return statement;
13306
13399
  }
13307
13400
  };
@@ -13310,7 +13403,7 @@ var init_sqlgenerator = __esm({
13310
13403
  return statement.type === "create_table" && dialect6 === "mysql";
13311
13404
  }
13312
13405
  convert(st) {
13313
- const { tableName, columns, schema: schema4 } = st;
13406
+ const { tableName, columns, schema: schema4, compositePKs } = st;
13314
13407
  let statement = "";
13315
13408
  const tName = schema4 ? `\`${schema4}\`.\`${tableName}\`` : `\`${tableName}\``;
13316
13409
  statement += `CREATE TABLE ${tName} (
@@ -13328,6 +13421,12 @@ var init_sqlgenerator = __esm({
13328
13421
  statement += `);`;
13329
13422
  statement += `
13330
13423
  `;
13424
+ if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
13425
+ const compositePK4 = MySqlSquasher.unsquashPK(compositePKs[0]);
13426
+ statement += `ALTER TABLE ${tName} ADD PRIMARY KEY(\`${compositePK4.columns.join("`,`")}\`);`;
13427
+ statement += `
13428
+ `;
13429
+ }
13331
13430
  return statement;
13332
13431
  }
13333
13432
  };
@@ -13697,6 +13796,67 @@ var init_sqlgenerator = __esm({
13697
13796
  */`;
13698
13797
  }
13699
13798
  };
13799
+ PgAlterTableCreateCompositePrimaryKeyConvertor = class extends Convertor {
13800
+ can(statement, dialect6) {
13801
+ return statement.type === "create_composite_pk" && dialect6 === "pg";
13802
+ }
13803
+ convert(statement) {
13804
+ const { name, columns } = PgSquasher.unsquashPK(statement.data);
13805
+ return `ALTER TABLE "${statement.tableName}" ADD CONSTRAINT "${statement.constraintName}" PRIMARY KEY("${columns.join('","')}");`;
13806
+ }
13807
+ };
13808
+ PgAlterTableDeleteCompositePrimaryKeyConvertor = class extends Convertor {
13809
+ can(statement, dialect6) {
13810
+ return statement.type === "delete_composite_pk" && dialect6 === "pg";
13811
+ }
13812
+ convert(statement) {
13813
+ const { name, columns } = PgSquasher.unsquashPK(statement.data);
13814
+ return `ALTER TABLE "${statement.tableName}" DROP CONSTRAINT "${statement.constraintName}";`;
13815
+ }
13816
+ };
13817
+ PgAlterTableAlterCompositePrimaryKeyConvertor = class extends Convertor {
13818
+ can(statement, dialect6) {
13819
+ return statement.type === "alter_composite_pk" && dialect6 === "pg";
13820
+ }
13821
+ convert(statement) {
13822
+ const { name, columns } = PgSquasher.unsquashPK(statement.old);
13823
+ const { name: newName, columns: newColumns } = PgSquasher.unsquashPK(
13824
+ statement.new
13825
+ );
13826
+ return `ALTER TABLE "${statement.tableName}" DROP CONSTRAINT ${statement.oldConstraintName};
13827
+ ALTER TABLE "${statement.tableName}" ADD CONSTRAINT ${statement.newConstraintName} PRIMARY KEY(${newColumns.join(",")});`;
13828
+ }
13829
+ };
13830
+ MySqlAlterTableCreateCompositePrimaryKeyConvertor = class extends Convertor {
13831
+ can(statement, dialect6) {
13832
+ return statement.type === "create_composite_pk" && dialect6 === "mysql";
13833
+ }
13834
+ convert(statement) {
13835
+ const { name, columns } = MySqlSquasher.unsquashPK(statement.data);
13836
+ return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY(\`${columns.join("`,`")}\`);`;
13837
+ }
13838
+ };
13839
+ MySqlAlterTableDeleteCompositePrimaryKeyConvertor = class extends Convertor {
13840
+ can(statement, dialect6) {
13841
+ return statement.type === "delete_composite_pk" && dialect6 === "mysql";
13842
+ }
13843
+ convert(statement) {
13844
+ const { name, columns } = MySqlSquasher.unsquashPK(statement.data);
13845
+ return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY;`;
13846
+ }
13847
+ };
13848
+ MySqlAlterTableAlterCompositePrimaryKeyConvertor = class extends Convertor {
13849
+ can(statement, dialect6) {
13850
+ return statement.type === "alter_composite_pk" && dialect6 === "mysql";
13851
+ }
13852
+ convert(statement) {
13853
+ const { name, columns } = MySqlSquasher.unsquashPK(statement.old);
13854
+ const { name: newName, columns: newColumns } = MySqlSquasher.unsquashPK(
13855
+ statement.new
13856
+ );
13857
+ return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY, ADD PRIMARY KEY(\`${newColumns.join("`,`")}\`);`;
13858
+ }
13859
+ };
13700
13860
  SqliteAlterTableCreateCompositePrimaryKeyConvertor = class extends Convertor {
13701
13861
  can(statement, dialect6) {
13702
13862
  return statement.type === "create_composite_pk" && dialect6 === "sqlite";
@@ -14203,6 +14363,12 @@ var init_sqlgenerator = __esm({
14203
14363
  convertors.push(new SqliteAlterTableCreateCompositePrimaryKeyConvertor());
14204
14364
  convertors.push(new SqliteAlterTableDeleteCompositePrimaryKeyConvertor());
14205
14365
  convertors.push(new SqliteAlterTableAlterCompositePrimaryKeyConvertor());
14366
+ convertors.push(new PgAlterTableCreateCompositePrimaryKeyConvertor());
14367
+ convertors.push(new PgAlterTableDeleteCompositePrimaryKeyConvertor());
14368
+ convertors.push(new PgAlterTableAlterCompositePrimaryKeyConvertor());
14369
+ convertors.push(new MySqlAlterTableCreateCompositePrimaryKeyConvertor());
14370
+ convertors.push(new MySqlAlterTableDeleteCompositePrimaryKeyConvertor());
14371
+ convertors.push(new MySqlAlterTableAlterCompositePrimaryKeyConvertor());
14206
14372
  fromJson = (statements, dialect6) => {
14207
14373
  const result = statements.map((statement) => {
14208
14374
  const filtered = convertors.filter((it) => {
@@ -14245,17 +14411,37 @@ drop type __venum;
14245
14411
  });
14246
14412
 
14247
14413
  // src/jsonStatements.ts
14248
- var prepareCreateTableJson, prepareSQLiteCreateTable, prepareDropTableJson, prepareRenameTableJson, prepareCreateEnumJson, prepareAddValuesToEnumJson, prepareCreateSchemasJson, prepareRenameSchemasJson, prepareDeleteSchemasJson, prepareRenameColumns, prepareAlterTableColumnsJson, _prepareDropColumns, _prepareAddColumns, _prepareSQLiteAddColumns, _prepareAlterColumns, prepareCreateIndexesJson, prepareCreateReferencesJson, prepareDropReferencesJson, prepareAlterReferencesJson, prepareDropIndexesJson, prepareAddCompositePrimaryKeySqlite, prepareDeleteCompositePrimaryKeySqlite, prepareAlterCompositePrimaryKeySqlite;
14414
+ var preparePgCreateTableJson, prepareMySqlCreateTableJson, prepareSQLiteCreateTable, prepareDropTableJson, prepareRenameTableJson, prepareCreateEnumJson, prepareAddValuesToEnumJson, prepareCreateSchemasJson, prepareRenameSchemasJson, prepareDeleteSchemasJson, prepareRenameColumns, prepareAlterTableColumnsJson, _prepareDropColumns, _prepareAddColumns, _prepareSQLiteAddColumns, _prepareAlterColumns, prepareCreateIndexesJson, prepareCreateReferencesJson, prepareDropReferencesJson, prepareAlterReferencesJson, prepareDropIndexesJson, prepareAddCompositePrimaryKeySqlite, prepareDeleteCompositePrimaryKeySqlite, prepareAlterCompositePrimaryKeySqlite, prepareAddCompositePrimaryKeyPg, prepareDeleteCompositePrimaryKeyPg, prepareAlterCompositePrimaryKeyPg, prepareAddCompositePrimaryKeyMySql, prepareDeleteCompositePrimaryKeyMySql, prepareAlterCompositePrimaryKeyMySql;
14249
14415
  var init_jsonStatements = __esm({
14250
14416
  "src/jsonStatements.ts"() {
14417
+ "use strict";
14418
+ init_mysqlSchema();
14419
+ init_pgSchema();
14251
14420
  init_sqliteSchema();
14252
- prepareCreateTableJson = (table4) => {
14253
- const { name, schema: schema4, columns } = table4;
14421
+ preparePgCreateTableJson = (table4, json2) => {
14422
+ const { name, schema: schema4, columns, compositePrimaryKeys } = table4;
14254
14423
  return {
14255
14424
  type: "create_table",
14256
14425
  tableName: name,
14257
14426
  schema: schema4,
14258
- columns: Object.values(columns)
14427
+ columns: Object.values(columns),
14428
+ compositePKs: Object.values(compositePrimaryKeys),
14429
+ compositePkName: Object.values(compositePrimaryKeys).length > 0 ? json2.tables[name].compositePrimaryKeys[`${name}_${PgSquasher.unsquashPK(
14430
+ Object.values(compositePrimaryKeys)[0]
14431
+ ).columns.join("_")}`].name : ""
14432
+ };
14433
+ };
14434
+ prepareMySqlCreateTableJson = (table4, json2) => {
14435
+ const { name, schema: schema4, columns, compositePrimaryKeys } = table4;
14436
+ return {
14437
+ type: "create_table",
14438
+ tableName: name,
14439
+ schema: schema4,
14440
+ columns: Object.values(columns),
14441
+ compositePKs: Object.values(compositePrimaryKeys),
14442
+ compositePkName: Object.values(compositePrimaryKeys).length > 0 ? json2.tables[name].compositePrimaryKeys[`${name}_${MySqlSquasher.unsquashPK(
14443
+ Object.values(compositePrimaryKeys)[0]
14444
+ ).columns.join("_")}`].name : ""
14259
14445
  };
14260
14446
  };
14261
14447
  prepareSQLiteCreateTable = (table4) => {
@@ -14639,6 +14825,70 @@ var init_jsonStatements = __esm({
14639
14825
  };
14640
14826
  });
14641
14827
  };
14828
+ prepareAddCompositePrimaryKeyPg = (tableName, pks, json2) => {
14829
+ return Object.values(pks).map((it) => {
14830
+ return {
14831
+ type: "create_composite_pk",
14832
+ tableName,
14833
+ data: it,
14834
+ constraintName: json2.tables[tableName].compositePrimaryKeys[`${tableName}_${PgSquasher.unsquashPK(it).columns.join("_")}`].name
14835
+ };
14836
+ });
14837
+ };
14838
+ prepareDeleteCompositePrimaryKeyPg = (tableName, pks, json1) => {
14839
+ return Object.values(pks).map((it) => {
14840
+ return {
14841
+ type: "delete_composite_pk",
14842
+ tableName,
14843
+ data: it,
14844
+ constraintName: json1.tables[tableName].compositePrimaryKeys[`${tableName}_${PgSquasher.unsquashPK(it).columns.join("_")}`].name
14845
+ };
14846
+ });
14847
+ };
14848
+ prepareAlterCompositePrimaryKeyPg = (tableName, pks, json1, json2) => {
14849
+ return Object.values(pks).map((it) => {
14850
+ return {
14851
+ type: "alter_composite_pk",
14852
+ tableName,
14853
+ old: it.__old,
14854
+ new: it.__new,
14855
+ oldConstraintName: json1.tables[tableName].compositePrimaryKeys[`${tableName}_${PgSquasher.unsquashPK(it.__old).columns.join("_")}`].name,
14856
+ newConstraintName: json2.tables[tableName].compositePrimaryKeys[`${tableName}_${PgSquasher.unsquashPK(it.__new).columns.join("_")}`].name
14857
+ };
14858
+ });
14859
+ };
14860
+ prepareAddCompositePrimaryKeyMySql = (tableName, pks, json2) => {
14861
+ return Object.values(pks).map((it) => {
14862
+ return {
14863
+ type: "create_composite_pk",
14864
+ tableName,
14865
+ data: it,
14866
+ constraintName: json2.tables[tableName].compositePrimaryKeys[`${tableName}_${MySqlSquasher.unsquashPK(it).columns.join("_")}`].name
14867
+ };
14868
+ });
14869
+ };
14870
+ prepareDeleteCompositePrimaryKeyMySql = (tableName, pks, json1) => {
14871
+ return Object.values(pks).map((it) => {
14872
+ return {
14873
+ type: "delete_composite_pk",
14874
+ tableName,
14875
+ data: it,
14876
+ constraintName: json1.tables[tableName].compositePrimaryKeys[`${tableName}_${MySqlSquasher.unsquashPK(it).columns.join("_")}`].name
14877
+ };
14878
+ });
14879
+ };
14880
+ prepareAlterCompositePrimaryKeyMySql = (tableName, pks, json1, json2) => {
14881
+ return Object.values(pks).map((it) => {
14882
+ return {
14883
+ type: "alter_composite_pk",
14884
+ tableName,
14885
+ old: it.__old,
14886
+ new: it.__new,
14887
+ oldConstraintName: json1.tables[tableName].compositePrimaryKeys[`${tableName}_${MySqlSquasher.unsquashPK(it.__old).columns.join("_")}`].name,
14888
+ newConstraintName: json2.tables[tableName].compositePrimaryKeys[`${tableName}_${MySqlSquasher.unsquashPK(it.__new).columns.join("_")}`].name
14889
+ };
14890
+ });
14891
+ };
14642
14892
  }
14643
14893
  });
14644
14894
 
@@ -14646,6 +14896,7 @@ var init_jsonStatements = __esm({
14646
14896
  var makeChanged, makeSelfOrChanged, makePatched, makeSelfOrPatched, valueFromSelfOrPatchedNew, columnSchema, alteredColumnSchema, enumSchema2, changedEnumSchema, tableScheme, alteredTableScheme, diffResultScheme, applySnapshotsDiff;
14647
14897
  var init_snapshotsDiffer = __esm({
14648
14898
  "src/snapshotsDiffer.ts"() {
14899
+ "use strict";
14649
14900
  init_sqlgenerator();
14650
14901
  init_lib();
14651
14902
  init_jsonDiffer();
@@ -14790,7 +15041,7 @@ var init_snapshotsDiffer = __esm({
14790
15041
  addedSchemas: stringType().array(),
14791
15042
  deletedSchemas: stringType().array()
14792
15043
  }).strict();
14793
- applySnapshotsDiff = async (json1, json2, dialect6, schemasResolver, tablesResolver, columnsResolver) => {
15044
+ applySnapshotsDiff = async (json1, json2, dialect6, schemasResolver, tablesResolver, columnsResolver, prevFull, curFull) => {
14794
15045
  var _a, _b, _c, _d;
14795
15046
  const diffResult = applyJsonDiff(json1, json2);
14796
15047
  if (Object.keys(diffResult).length === 0) {
@@ -14820,9 +15071,6 @@ var init_snapshotsDiffer = __esm({
14820
15071
  const jsonSQLiteCreateTables = created.map((it) => {
14821
15072
  return prepareSQLiteCreateTable(it);
14822
15073
  });
14823
- const jsonCreateTables = created.map((it) => {
14824
- return prepareCreateTableJson(it);
14825
- });
14826
15074
  const jsonCreateIndexesForCreatedTables = created.map((it) => {
14827
15075
  return prepareCreateIndexesJson(it.name, it.schema, it.indexes);
14828
15076
  }).flat();
@@ -14880,18 +15128,57 @@ var init_snapshotsDiffer = __esm({
14880
15128
  const jsonRemoveTableFromSchemas = [];
14881
15129
  const jsonSetNewTableSchemas = [];
14882
15130
  allAlteredResolved.forEach((it) => {
14883
- const addedCompositePKs = prepareAddCompositePrimaryKeySqlite(
14884
- it.name,
14885
- it.addedCompositePKs
14886
- );
14887
- const deletedCompositePKs = prepareDeleteCompositePrimaryKeySqlite(
14888
- it.name,
14889
- it.deletedCompositePKs
14890
- );
14891
- const alteredCompositePKs = prepareAlterCompositePrimaryKeySqlite(
14892
- it.name,
14893
- it.alteredCompositePKs
14894
- );
15131
+ let addedCompositePKs;
15132
+ let deletedCompositePKs;
15133
+ let alteredCompositePKs;
15134
+ if (dialect6 === "sqlite") {
15135
+ addedCompositePKs = prepareAddCompositePrimaryKeySqlite(
15136
+ it.name,
15137
+ it.addedCompositePKs
15138
+ );
15139
+ deletedCompositePKs = prepareDeleteCompositePrimaryKeySqlite(
15140
+ it.name,
15141
+ it.deletedCompositePKs
15142
+ );
15143
+ alteredCompositePKs = prepareAlterCompositePrimaryKeySqlite(
15144
+ it.name,
15145
+ it.alteredCompositePKs
15146
+ );
15147
+ } else if (dialect6 === "pg") {
15148
+ addedCompositePKs = prepareAddCompositePrimaryKeyPg(
15149
+ it.name,
15150
+ it.addedCompositePKs,
15151
+ curFull
15152
+ );
15153
+ deletedCompositePKs = prepareDeleteCompositePrimaryKeyPg(
15154
+ it.name,
15155
+ it.deletedCompositePKs,
15156
+ prevFull
15157
+ );
15158
+ alteredCompositePKs = prepareAlterCompositePrimaryKeyPg(
15159
+ it.name,
15160
+ it.alteredCompositePKs,
15161
+ prevFull,
15162
+ curFull
15163
+ );
15164
+ } else {
15165
+ addedCompositePKs = prepareAddCompositePrimaryKeyMySql(
15166
+ it.name,
15167
+ it.addedCompositePKs,
15168
+ curFull
15169
+ );
15170
+ deletedCompositePKs = prepareDeleteCompositePrimaryKeyMySql(
15171
+ it.name,
15172
+ it.deletedCompositePKs,
15173
+ prevFull
15174
+ );
15175
+ alteredCompositePKs = prepareAlterCompositePrimaryKeyMySql(
15176
+ it.name,
15177
+ it.alteredCompositePKs,
15178
+ prevFull,
15179
+ curFull
15180
+ );
15181
+ }
14895
15182
  if (it.schema && typeof it.schema !== "string") {
14896
15183
  switch (it.schema.type) {
14897
15184
  case "added": {
@@ -15014,8 +15301,16 @@ var init_snapshotsDiffer = __esm({
15014
15301
  jsonStatements.push(...jsonAlterEnumsWithAddedValues);
15015
15302
  if (dialect6 === "sqlite") {
15016
15303
  jsonStatements.push(...jsonSQLiteCreateTables);
15304
+ } else if (dialect6 === "pg") {
15305
+ const jsonPgCreateTables = created.map((it) => {
15306
+ return preparePgCreateTableJson(it, curFull);
15307
+ });
15308
+ jsonStatements.push(...jsonPgCreateTables);
15017
15309
  } else {
15018
- jsonStatements.push(...jsonCreateTables);
15310
+ const jsonMySqlCreateTables = created.map((it) => {
15311
+ return prepareMySqlCreateTableJson(it, curFull);
15312
+ });
15313
+ jsonStatements.push(...jsonMySqlCreateTables);
15019
15314
  }
15020
15315
  jsonStatements.push(...jsonDropTables);
15021
15316
  jsonStatements.push(...jsonRenameTables);
@@ -15044,7 +15339,11 @@ var init_snapshotsDiffer = __esm({
15044
15339
  }
15045
15340
  });
15046
15341
  const _meta = prepareMigrationMeta(rSchemas, rTables, rColumns);
15047
- return { statements: jsonStatements, sqlStatements: uniqueSqlStatements, _meta };
15342
+ return {
15343
+ statements: jsonStatements,
15344
+ sqlStatements: uniqueSqlStatements,
15345
+ _meta
15346
+ };
15048
15347
  };
15049
15348
  }
15050
15349
  });
@@ -15053,6 +15352,7 @@ var init_snapshotsDiffer = __esm({
15053
15352
  var prepareMigrationMetadata, adjectives, heroes;
15054
15353
  var init_words = __esm({
15055
15354
  "src/utils/words.ts"() {
15355
+ "use strict";
15056
15356
  prepareMigrationMetadata = (idx) => {
15057
15357
  const prefix = idx.toFixed(0).padStart(4, "0");
15058
15358
  const suffix = `${adjectives.random()}_${heroes.random()}`;
@@ -16370,18 +16670,373 @@ var init_words = __esm({
16370
16670
  }
16371
16671
  });
16372
16672
 
16673
+ // src/cli/commands/pgUp.ts
16674
+ var import_crypto, import_fs, upPgHandlerV4toV5, upPgHandler, upPgHandlerV4, updateUpToV4, update1to2, update2to3, update3to4;
16675
+ var init_pgUp = __esm({
16676
+ "src/cli/commands/pgUp.ts"() {
16677
+ "use strict";
16678
+ init_source();
16679
+ import_crypto = require("crypto");
16680
+ import_fs = require("fs");
16681
+ init_global();
16682
+ init_pgSchema();
16683
+ init_utils();
16684
+ upPgHandlerV4toV5 = (obj) => {
16685
+ const mappedTables = {};
16686
+ for (const [key, table4] of Object.entries(obj.tables)) {
16687
+ const mappedColumns = {};
16688
+ for (const [ckey, column6] of Object.entries(table4.columns)) {
16689
+ let newDefault = column6.default;
16690
+ let newType = column6.type;
16691
+ if (column6.type.toLowerCase() === "date") {
16692
+ if (typeof column6.default !== "undefined") {
16693
+ if (column6.default.startsWith("'") && column6.default.endsWith("'")) {
16694
+ newDefault = `'${column6.default.substring(1, column6.default.length - 1).split("T")[0]}'`;
16695
+ } else {
16696
+ newDefault = column6.default.split("T")[0];
16697
+ }
16698
+ }
16699
+ } else if (column6.type.toLowerCase().startsWith("timestamp")) {
16700
+ if (typeof column6.default !== "undefined") {
16701
+ if (column6.default.startsWith("'") && column6.default.endsWith("'")) {
16702
+ newDefault = `'${column6.default.substring(1, column6.default.length - 1).replace("T", " ").slice(0, 23)}'`;
16703
+ } else {
16704
+ newDefault = column6.default.replace("T", " ").slice(0, 23);
16705
+ }
16706
+ }
16707
+ newType = column6.type.toLowerCase().replace("timestamp (", "timestamp(");
16708
+ } else if (column6.type.toLowerCase().startsWith("time")) {
16709
+ newType = column6.type.toLowerCase().replace("time (", "time(");
16710
+ } else if (column6.type.toLowerCase().startsWith("interval")) {
16711
+ newType = column6.type.toLowerCase().replace(" (", "(");
16712
+ }
16713
+ mappedColumns[ckey] = { ...column6, default: newDefault, type: newType };
16714
+ }
16715
+ mappedTables[key] = { ...table4, columns: mappedColumns };
16716
+ }
16717
+ return {
16718
+ version: "5",
16719
+ dialect: obj.dialect,
16720
+ id: obj.id,
16721
+ prevId: obj.prevId,
16722
+ tables: mappedTables,
16723
+ enums: obj.enums,
16724
+ schemas: obj.schemas,
16725
+ _meta: {
16726
+ schemas: {},
16727
+ tables: {},
16728
+ columns: {}
16729
+ }
16730
+ };
16731
+ };
16732
+ upPgHandler = (out) => {
16733
+ };
16734
+ upPgHandlerV4 = (out) => {
16735
+ const snapshots = snapshotsPriorV4(out);
16736
+ const report = validateWithReport(snapshots, "pg");
16737
+ let prevId = originUUID;
16738
+ report.nonLatest.map((it) => ({
16739
+ path: it,
16740
+ raw: report.rawMap[it]
16741
+ })).forEach((it) => {
16742
+ const path2 = it.path;
16743
+ const result = updateUpToV4(it.raw, prevId);
16744
+ prevId = result.id;
16745
+ console.log(`[${source_default.green("\u2713")}] ${path2}`);
16746
+ (0, import_fs.writeFileSync)(path2, JSON.stringify(result, null, 2));
16747
+ });
16748
+ console.log("Everything's fine \u{1F436}\u{1F525}");
16749
+ };
16750
+ updateUpToV4 = (json, prevId) => {
16751
+ const version = Number(json["version"]);
16752
+ if (version === 1) {
16753
+ const v1 = pgSchemaV1.parse(json);
16754
+ const v2 = update1to2(v1);
16755
+ const v3 = update2to3(v2, prevId);
16756
+ const v4 = update3to4(v3);
16757
+ return v4;
16758
+ }
16759
+ if (version === 2) {
16760
+ const v2 = pgSchemaV2.parse(json);
16761
+ const v3 = update2to3(v2, prevId);
16762
+ const v4 = update3to4(v3);
16763
+ return v4;
16764
+ }
16765
+ if (version === 3) {
16766
+ return update3to4(pgSchemaV3.parse(json));
16767
+ }
16768
+ return pgSchemaV4.parse(json);
16769
+ };
16770
+ update1to2 = (json) => {
16771
+ const tables = Object.fromEntries(
16772
+ Object.entries(json.tables).map((it) => {
16773
+ const table4 = it[1];
16774
+ const columns = Object.fromEntries(
16775
+ Object.entries(table4.columns).map((it2) => {
16776
+ const ref = it2[1].references;
16777
+ const fkName = ref == null ? void 0 : ref.foreignKeyName;
16778
+ const table5 = ref == null ? void 0 : ref.table;
16779
+ const column6 = ref == null ? void 0 : ref.column;
16780
+ const onDelete = ref == null ? void 0 : ref.onDelete;
16781
+ const onUpdate = ref == null ? void 0 : ref.onDelete;
16782
+ const newRef = ref ? `${fkName};${table5};${column6};${onDelete != null ? onDelete : ""};${onUpdate != null ? onUpdate : ""}` : void 0;
16783
+ return [it2[0], { ...it2[1], references: newRef }];
16784
+ })
16785
+ );
16786
+ return [it[0], { name: table4.name, columns, indexes: table4.indexes }];
16787
+ })
16788
+ );
16789
+ return { version: "2", tables, enums: json.enums };
16790
+ };
16791
+ update2to3 = (json, prevId) => {
16792
+ const tables = Object.fromEntries(
16793
+ Object.entries(json.tables).map((table4) => {
16794
+ const { name, columns, indexes } = table4[1];
16795
+ let refs = [];
16796
+ const newColumns = Object.fromEntries(
16797
+ Object.entries(columns).map((it) => {
16798
+ const {
16799
+ name: name2,
16800
+ type,
16801
+ primaryKey,
16802
+ notNull,
16803
+ default: defaultValue,
16804
+ references: references2
16805
+ } = it[1];
16806
+ const newColumn = {
16807
+ name: name2,
16808
+ type,
16809
+ primaryKey,
16810
+ notNull,
16811
+ default: defaultValue
16812
+ };
16813
+ if (references2) {
16814
+ refs.push({ column: name2, value: references2 });
16815
+ }
16816
+ return [it[0], newColumn];
16817
+ })
16818
+ );
16819
+ const tableName = name;
16820
+ const fks = Object.fromEntries(
16821
+ refs.map((it) => {
16822
+ const [name2, table5, column6, onDelete, onUpdate] = it.value.split(";");
16823
+ const fk4 = {
16824
+ name: name2,
16825
+ tableFrom: tableName,
16826
+ columnsFrom: [it.column],
16827
+ tableTo: table5,
16828
+ columnsTo: [column6],
16829
+ onUpdate,
16830
+ onDelete
16831
+ };
16832
+ return [name2, fk4];
16833
+ })
16834
+ );
16835
+ const idxs = Object.fromEntries(
16836
+ Object.entries(indexes).map((it) => {
16837
+ const { columns: columns2, isUnique, name: name2 } = it[1];
16838
+ const mappedColumns = Object.entries(columns2).map((it2) => {
16839
+ return it2[1].name;
16840
+ });
16841
+ const index4 = {
16842
+ name: name2,
16843
+ isUnique,
16844
+ columns: mappedColumns
16845
+ };
16846
+ return [it[0], index4];
16847
+ })
16848
+ );
16849
+ const newTable = {
16850
+ name,
16851
+ columns: newColumns,
16852
+ indexes: idxs,
16853
+ foreignKeys: fks
16854
+ };
16855
+ return [table4[0], newTable];
16856
+ })
16857
+ );
16858
+ return {
16859
+ version: "3",
16860
+ dialect: "pg",
16861
+ id: (0, import_crypto.randomUUID)(),
16862
+ prevId,
16863
+ tables,
16864
+ enums: json.enums
16865
+ };
16866
+ };
16867
+ update3to4 = (json) => {
16868
+ const tables = Object.fromEntries(
16869
+ Object.entries(json.tables).map((table4) => {
16870
+ const { name, columns, foreignKeys, indexes } = table4[1];
16871
+ const newColumns = Object.fromEntries(
16872
+ Object.entries(columns).map((it) => {
16873
+ const {
16874
+ name: name2,
16875
+ type,
16876
+ primaryKey,
16877
+ notNull,
16878
+ default: defaultValue
16879
+ } = it[1];
16880
+ const newColumn = {
16881
+ name: name2,
16882
+ type,
16883
+ primaryKey,
16884
+ notNull,
16885
+ default: defaultValue
16886
+ };
16887
+ return [it[0], newColumn];
16888
+ })
16889
+ );
16890
+ const newTable = {
16891
+ name,
16892
+ schema: "",
16893
+ columns: newColumns,
16894
+ indexes,
16895
+ foreignKeys
16896
+ };
16897
+ return [table4[0], newTable];
16898
+ })
16899
+ );
16900
+ return {
16901
+ version: "4",
16902
+ dialect: "pg",
16903
+ id: (0, import_crypto.randomUUID)(),
16904
+ prevId: json.prevId,
16905
+ tables,
16906
+ enums: json.enums,
16907
+ schemas: {}
16908
+ };
16909
+ };
16910
+ }
16911
+ });
16912
+
16913
+ // src/cli/commands/mysqlUp.ts
16914
+ var import_fs2, upMysqlHandler, upMySqlHandlerV4toV5, upMysqlHandlerV4, updateToLatestV4, updateV3toV4;
16915
+ var init_mysqlUp = __esm({
16916
+ "src/cli/commands/mysqlUp.ts"() {
16917
+ "use strict";
16918
+ init_source();
16919
+ import_fs2 = __toESM(require("fs"));
16920
+ init_mysqlSchema();
16921
+ init_utils();
16922
+ upMysqlHandler = (out) => {
16923
+ };
16924
+ upMySqlHandlerV4toV5 = (obj) => {
16925
+ const mappedTables = {};
16926
+ for (const [key, table4] of Object.entries(obj.tables)) {
16927
+ const mappedColumns = {};
16928
+ for (const [ckey, column6] of Object.entries(table4.columns)) {
16929
+ let newDefault = column6.default;
16930
+ let newType = column6.type;
16931
+ let newAutoIncrement = column6.autoincrement;
16932
+ if (column6.type.toLowerCase().startsWith("datetime")) {
16933
+ if (typeof column6.default !== "undefined") {
16934
+ if (column6.default.startsWith("'") && column6.default.endsWith("'")) {
16935
+ newDefault = `'${column6.default.substring(1, column6.default.length - 1).replace("T", " ").slice(0, 23)}'`;
16936
+ } else {
16937
+ newDefault = column6.default.replace("T", " ").slice(0, 23);
16938
+ }
16939
+ }
16940
+ newType = column6.type.toLowerCase().replace("datetime (", "datetime(");
16941
+ } else if (column6.type.toLowerCase() === "date") {
16942
+ if (typeof column6.default !== "undefined") {
16943
+ if (column6.default.startsWith("'") && column6.default.endsWith("'")) {
16944
+ newDefault = `'${column6.default.substring(1, column6.default.length - 1).split("T")[0]}'`;
16945
+ } else {
16946
+ newDefault = column6.default.split("T")[0];
16947
+ }
16948
+ }
16949
+ newType = column6.type.toLowerCase().replace("date (", "date(");
16950
+ } else if (column6.type.toLowerCase().startsWith("timestamp")) {
16951
+ if (typeof column6.default !== "undefined") {
16952
+ if (column6.default.startsWith("'") && column6.default.endsWith("'")) {
16953
+ newDefault = `'${column6.default.substring(1, column6.default.length - 1).replace("T", " ").slice(0, 23)}'`;
16954
+ } else {
16955
+ newDefault = column6.default.replace("T", " ").slice(0, 23);
16956
+ }
16957
+ }
16958
+ newType = column6.type.toLowerCase().replace("timestamp (", "timestamp(");
16959
+ } else if (column6.type.toLowerCase().startsWith("time")) {
16960
+ newType = column6.type.toLowerCase().replace("time (", "time(");
16961
+ } else if (column6.type.toLowerCase().startsWith("decimal")) {
16962
+ newType = column6.type.toLowerCase().replace(", ", ",");
16963
+ } else if (column6.type.toLowerCase().startsWith("enum")) {
16964
+ newType = column6.type.toLowerCase();
16965
+ } else if (column6.type.toLowerCase().startsWith("serial")) {
16966
+ newAutoIncrement = true;
16967
+ }
16968
+ mappedColumns[ckey] = {
16969
+ ...column6,
16970
+ default: newDefault,
16971
+ type: newType,
16972
+ autoincrement: newAutoIncrement
16973
+ };
16974
+ }
16975
+ mappedTables[key] = { ...table4, columns: mappedColumns };
16976
+ }
16977
+ return {
16978
+ version: "5",
16979
+ dialect: obj.dialect,
16980
+ id: obj.id,
16981
+ prevId: obj.prevId,
16982
+ tables: mappedTables,
16983
+ schemas: obj.schemas,
16984
+ _meta: {
16985
+ schemas: {},
16986
+ tables: {},
16987
+ columns: {}
16988
+ }
16989
+ };
16990
+ };
16991
+ upMysqlHandlerV4 = (out) => {
16992
+ const snapshots = snapshotsPriorV4(out);
16993
+ const report = validateWithReport(snapshots, "mysql");
16994
+ report.nonLatest.map((it) => ({
16995
+ path: it,
16996
+ raw: report.rawMap[it]
16997
+ })).forEach((it) => {
16998
+ const path2 = it.path;
16999
+ const result = updateToLatestV4(it.raw);
17000
+ console.log(`[${source_default.green("\u2713")}] ${path2}`);
17001
+ import_fs2.default.writeFileSync(path2, JSON.stringify(result, null, 2));
17002
+ });
17003
+ console.log("Everything's fine \u{1F436}\u{1F525}");
17004
+ };
17005
+ updateToLatestV4 = (json) => {
17006
+ const version = Number(json["version"]);
17007
+ if (version === 3) {
17008
+ const v3 = mysqlSchemaV3.parse(json);
17009
+ const v4 = updateV3toV4(v3);
17010
+ return v4;
17011
+ }
17012
+ return mysqlSchemaV4.parse(json);
17013
+ };
17014
+ updateV3toV4 = (old) => {
17015
+ return {
17016
+ ...old,
17017
+ version: "4",
17018
+ schemas: {}
17019
+ };
17020
+ };
17021
+ }
17022
+ });
17023
+
16373
17024
  // src/cli/commands/upFolders.ts
16374
- var import_fs, import_path, schemasResolverWithSQL, resolveSchemas, resolveTablesWithSQL, resolveTables, resolveColumnsWithSQL, resolveColumns, fullfill, fullfillpg, fullfillmysql, upgradeFolders;
17025
+ var import_fs3, import_path, schemasResolverWithSQL, resolveSchemas, resolveTablesWithSQL, resolveTables, resolveColumnsWithSQL, resolveColumns, fullfill, fullfillpg, fullfillmysql, fullfillsqlite, upgradeFolders;
16375
17026
  var init_upFolders = __esm({
16376
17027
  "src/cli/commands/upFolders.ts"() {
16377
- import_fs = require("fs");
17028
+ "use strict";
17029
+ import_fs3 = require("fs");
16378
17030
  import_path = require("path");
16379
17031
  init_jsonDiffer();
16380
17032
  init_mysqlSchema();
17033
+ init_sqliteSchema();
16381
17034
  init_snapshotsDiffer();
16382
17035
  init_utils();
16383
17036
  init_words();
17037
+ init_pgUp();
16384
17038
  init_pgSchema();
17039
+ init_mysqlUp();
16385
17040
  schemasResolverWithSQL = (missingSchemas, newSchemas, sql) => {
16386
17041
  return resolveSchemas(
16387
17042
  missingSchemas,
@@ -16449,6 +17104,10 @@ var init_upFolders = __esm({
16449
17104
  {
16450
17105
  value: it,
16451
17106
  sql: `RENAME TABLE ${mysqlSchemaPrefix}\`${it.name}\` TO ${mysqlSchemaPrefix}\`${created.name}\`;`
17107
+ },
17108
+ {
17109
+ value: it,
17110
+ sql: `ALTER TABLE ${it.name} RENAME TO ${created.name};`
16452
17111
  }
16453
17112
  ];
16454
17113
  }).flat();
@@ -16559,25 +17218,15 @@ var init_upFolders = __esm({
16559
17218
  if (dialect6 === "mysql") {
16560
17219
  return fullfillmysql(prev, cur, sql);
16561
17220
  }
17221
+ if (dialect6 === "sqlite") {
17222
+ return fullfillsqlite(prev, cur, sql);
17223
+ }
16562
17224
  throw new Error("");
16563
17225
  };
16564
17226
  fullfillpg = (prev, cur, sql) => {
16565
17227
  const b = pgSchemaV4.parse(cur);
16566
17228
  if (!prev) {
16567
- return {
16568
- version: "5",
16569
- dialect: b.dialect,
16570
- id: b.id,
16571
- prevId: b.prevId,
16572
- tables: b.tables,
16573
- enums: b.enums,
16574
- schemas: b.schemas,
16575
- _meta: {
16576
- schemas: {},
16577
- tables: {},
16578
- columns: {}
16579
- }
16580
- };
17229
+ return upPgHandlerV4toV5(b);
16581
17230
  }
16582
17231
  const a = pgSchemaV4.parse(prev);
16583
17232
  const json1 = squashPgScheme(a);
@@ -16616,7 +17265,12 @@ var init_upFolders = __esm({
16616
17265
  });
16617
17266
  const rColumns = allAltered.map((table4) => {
16618
17267
  const name = table4.name;
16619
- const result = resolveColumnsWithSQL(name, table4.deleted, table4.added, sql);
17268
+ const result = resolveColumnsWithSQL(
17269
+ name,
17270
+ table4.deleted,
17271
+ table4.added,
17272
+ sql
17273
+ );
16620
17274
  const tableName = table4.name;
16621
17275
  const schema4 = typeof table4.schema === "string" ? table4.schema : "";
16622
17276
  return result.renamed.map((it) => {
@@ -16627,30 +17281,93 @@ var init_upFolders = __esm({
16627
17281
  });
16628
17282
  }).flat();
16629
17283
  const _meta = prepareMigrationMeta(rSchemas, rTables, rColumns);
17284
+ const bUpV5 = upPgHandlerV4toV5(b);
16630
17285
  const bpatched = {
16631
17286
  version: "5",
16632
- dialect: b.dialect,
16633
- id: b.id,
16634
- prevId: b.prevId,
16635
- tables: b.tables,
16636
- enums: b.enums,
16637
- schemas: b.schemas,
17287
+ dialect: bUpV5.dialect,
17288
+ id: bUpV5.id,
17289
+ prevId: bUpV5.prevId,
17290
+ tables: bUpV5.tables,
17291
+ enums: bUpV5.enums,
17292
+ schemas: bUpV5.schemas,
16638
17293
  _meta
16639
17294
  };
16640
17295
  pgSchema.parse(bpatched);
16641
- return {
17296
+ return bUpV5;
17297
+ };
17298
+ fullfillmysql = (prev, cur, sql) => {
17299
+ const b = mysqlSchemaV4.parse(cur);
17300
+ if (!prev) {
17301
+ return upMySqlHandlerV4toV5(b);
17302
+ }
17303
+ const a = mysqlSchemaV4.parse(prev);
17304
+ const json1 = squashMysqlScheme(a);
17305
+ const json2 = squashMysqlScheme(b);
17306
+ const diffResult = applyJsonDiff(json1, json2);
17307
+ const parseResult = diffResultScheme.safeParse(diffResult);
17308
+ if (!parseResult.success) {
17309
+ parseResult.error.errors.forEach((it) => {
17310
+ console.error(it);
17311
+ });
17312
+ throw new Error();
17313
+ }
17314
+ const typedResult = parseResult.data;
17315
+ const { renamed: renamedSchemas } = schemasResolverWithSQL(
17316
+ typedResult.deletedSchemas.map((it) => ({ name: it })),
17317
+ typedResult.addedSchemas.map((it) => ({ name: it })),
17318
+ sql
17319
+ );
17320
+ const { renamed } = resolveTablesWithSQL(
17321
+ typedResult.deletedTables,
17322
+ typedResult.addedTables,
17323
+ sql
17324
+ );
17325
+ const renamedWithAlternations = Object.values(
17326
+ alteredTableScheme.array().parse(diffForRenamedTables(renamed))
17327
+ );
17328
+ const allAltered = typedResult.alteredTablesWithColumns.concat(
17329
+ renamedWithAlternations
17330
+ );
17331
+ const rSchemas = renamedSchemas.map((it) => ({
17332
+ from: it.from.name,
17333
+ to: it.to.name
17334
+ }));
17335
+ const rTables = renamed.map((it) => {
17336
+ return { from: it.from, to: it.to };
17337
+ });
17338
+ const rColumns = allAltered.map((table4) => {
17339
+ const name = table4.name;
17340
+ const result = resolveColumnsWithSQL(
17341
+ name,
17342
+ table4.deleted,
17343
+ table4.added,
17344
+ sql
17345
+ );
17346
+ const tableName = table4.name;
17347
+ const schema4 = typeof table4.schema === "string" ? table4.schema : "";
17348
+ return result.renamed.map((it) => {
17349
+ return {
17350
+ from: { schema: schema4, table: tableName, column: it.from.name },
17351
+ to: { schema: schema4, table: tableName, column: it.to.name }
17352
+ };
17353
+ });
17354
+ }).flat();
17355
+ const _meta = prepareMigrationMeta(rSchemas, rTables, rColumns);
17356
+ const bUpV5 = upMySqlHandlerV4toV5(b);
17357
+ const bpatched = {
16642
17358
  version: "5",
16643
- dialect: b.dialect,
16644
- id: b.id,
16645
- prevId: b.prevId,
16646
- tables: b.tables,
16647
- enums: b.enums,
16648
- schemas: b.schemas,
17359
+ dialect: bUpV5.dialect,
17360
+ id: bUpV5.id,
17361
+ prevId: bUpV5.prevId,
17362
+ tables: bUpV5.tables,
17363
+ schemas: bUpV5.schemas,
16649
17364
  _meta
16650
17365
  };
17366
+ mysqlSchema.parse(bpatched);
17367
+ return bUpV5;
16651
17368
  };
16652
- fullfillmysql = (prev, cur, sql) => {
16653
- const b = mysqlSchemaV4.parse(cur);
17369
+ fullfillsqlite = (prev, cur, sql) => {
17370
+ const b = sqliteSchemaV4.parse(cur);
16654
17371
  if (!prev) {
16655
17372
  return {
16656
17373
  version: "5",
@@ -16658,17 +17375,16 @@ var init_upFolders = __esm({
16658
17375
  id: b.id,
16659
17376
  prevId: b.prevId,
16660
17377
  tables: b.tables,
16661
- schemas: b.schemas,
17378
+ enums: {},
16662
17379
  _meta: {
16663
- schemas: {},
16664
17380
  tables: {},
16665
17381
  columns: {}
16666
17382
  }
16667
17383
  };
16668
17384
  }
16669
- const a = mysqlSchemaV4.parse(prev);
16670
- const json1 = squashMysqlScheme(a);
16671
- const json2 = squashMysqlScheme(b);
17385
+ const a = sqliteSchemaV4.parse(prev);
17386
+ const json1 = squashSqliteScheme(a);
17387
+ const json2 = squashSqliteScheme(b);
16672
17388
  const diffResult = applyJsonDiff(json1, json2);
16673
17389
  const parseResult = diffResultScheme.safeParse(diffResult);
16674
17390
  if (!parseResult.success) {
@@ -16703,7 +17419,12 @@ var init_upFolders = __esm({
16703
17419
  });
16704
17420
  const rColumns = allAltered.map((table4) => {
16705
17421
  const name = table4.name;
16706
- const result = resolveColumnsWithSQL(name, table4.deleted, table4.added, sql);
17422
+ const result = resolveColumnsWithSQL(
17423
+ name,
17424
+ table4.deleted,
17425
+ table4.added,
17426
+ sql
17427
+ );
16707
17428
  const tableName = table4.name;
16708
17429
  const schema4 = typeof table4.schema === "string" ? table4.schema : "";
16709
17430
  return result.renamed.map((it) => {
@@ -16720,22 +17441,22 @@ var init_upFolders = __esm({
16720
17441
  id: b.id,
16721
17442
  prevId: b.prevId,
16722
17443
  tables: b.tables,
16723
- schemas: b.schemas,
17444
+ enums: {},
16724
17445
  _meta
16725
17446
  };
16726
- mysqlSchema.parse(bpatched);
17447
+ sqliteSchema.parse(bpatched);
16727
17448
  return {
16728
17449
  version: "5",
16729
17450
  dialect: b.dialect,
16730
17451
  id: b.id,
16731
17452
  prevId: b.prevId,
16732
17453
  tables: b.tables,
16733
- schemas: b.schemas,
17454
+ enums: {},
16734
17455
  _meta
16735
17456
  };
16736
17457
  };
16737
17458
  upgradeFolders = (dialect6, out) => {
16738
- const oldMigrationFolders = (0, import_fs.readdirSync)(out).filter(
17459
+ const oldMigrationFolders = (0, import_fs3.readdirSync)(out).filter(
16739
17460
  (it) => it.length === 14 && /^\d+$/.test(it)
16740
17461
  );
16741
17462
  oldMigrationFolders.sort();
@@ -16748,17 +17469,18 @@ var init_upFolders = __esm({
16748
17469
  date.setUTCHours(Number(it.substring(8, 10)));
16749
17470
  date.setUTCMinutes(Number(it.substring(10, 12)));
16750
17471
  date.setUTCSeconds(Number(it.substring(12, 14)));
16751
- const path4 = (0, import_path.join)(out, it);
17472
+ const path2 = (0, import_path.join)(out, it);
16752
17473
  const pathJson = (0, import_path.join)(out, it, "snapshot.json");
16753
17474
  const pathSQL = (0, import_path.join)(out, it, "migration.sql");
16754
- const snapshot = JSON.parse((0, import_fs.readFileSync)(pathJson).toString());
16755
- const sql = (0, import_fs.readFileSync)(pathSQL).toString();
17475
+ const snapshot = JSON.parse((0, import_fs3.readFileSync)(pathJson).toString());
17476
+ const sql = (0, import_fs3.readFileSync)(pathSQL).toString();
16756
17477
  res2.entries.push({
16757
17478
  idx: res2.idx,
17479
+ version: snapshot["version"],
16758
17480
  json: snapshot,
16759
17481
  date,
16760
17482
  sql,
16761
- path: path4
17483
+ path: path2
16762
17484
  });
16763
17485
  res2.idx += 1;
16764
17486
  return res2;
@@ -16769,8 +17491,8 @@ var init_upFolders = __esm({
16769
17491
  }
16770
17492
  );
16771
17493
  const metaFolder = (0, import_path.join)(`${out}`, "meta");
16772
- if (!(0, import_fs.existsSync)(metaFolder)) {
16773
- (0, import_fs.mkdirSync)(metaFolder, { recursive: true });
17494
+ if (!(0, import_fs3.existsSync)(metaFolder)) {
17495
+ (0, import_fs3.mkdirSync)(metaFolder, { recursive: true });
16774
17496
  }
16775
17497
  const journal = dryJournal(dialect6);
16776
17498
  let prev = void 0;
@@ -16778,29 +17500,31 @@ var init_upFolders = __esm({
16778
17500
  const { prefix, suffix, tag } = prepareMigrationMetadata(it.idx);
16779
17501
  journal.entries.push({
16780
17502
  idx: it.idx,
17503
+ version: it.version,
16781
17504
  when: +it.date,
16782
17505
  tag,
16783
17506
  breakpoints: false
16784
17507
  });
16785
17508
  const patchedJSON = fullfill(prev, it.json, it.sql, dialect6);
16786
- (0, import_fs.writeFileSync)(
17509
+ (0, import_fs3.writeFileSync)(
16787
17510
  (0, import_path.join)(`${out}`, "meta", `${prefix}_snapshot.json`),
16788
17511
  JSON.stringify(patchedJSON)
16789
17512
  );
16790
- (0, import_fs.writeFileSync)((0, import_path.join)(`${out}`, `${tag}.sql`), it.sql);
16791
- (0, import_fs.rmSync)(it.path, { recursive: true });
17513
+ (0, import_fs3.writeFileSync)((0, import_path.join)(`${out}`, `${tag}.sql`), it.sql);
17514
+ (0, import_fs3.rmSync)(it.path, { recursive: true });
16792
17515
  prev = it.json;
16793
17516
  });
16794
- (0, import_fs.writeFileSync)((0, import_path.join)(metaFolder, "_journal.json"), JSON.stringify(journal));
17517
+ (0, import_fs3.writeFileSync)((0, import_path.join)(metaFolder, "_journal.json"), JSON.stringify(journal));
16795
17518
  };
16796
17519
  }
16797
17520
  });
16798
17521
 
16799
17522
  // src/utils.ts
16800
- var import_fs2, import_path2, assertV1OutFolder, dryJournal, snapshotsPriorV4, prepareOutFolder, mapValues, validatorForDialect, validateWithReport, prepareMigrationFolder, prepareMigrationMeta, schemaRenameKey, tableRenameKey, columnRenameKey;
17523
+ var import_fs4, import_path2, assertV1OutFolder, dryJournal, snapshotsPriorV4, prepareOutFolder2, mapValues, validatorForDialect, validateWithReport, prepareMigrationFolder, prepareMigrationMeta, schemaRenameKey, tableRenameKey, columnRenameKey;
16801
17524
  var init_utils = __esm({
16802
17525
  "src/utils.ts"() {
16803
- import_fs2 = require("fs");
17526
+ "use strict";
17527
+ import_fs4 = require("fs");
16804
17528
  init_views();
16805
17529
  init_mysqlSchema();
16806
17530
  init_pgSchema();
@@ -16811,9 +17535,9 @@ var init_utils = __esm({
16811
17535
  init_upFolders();
16812
17536
  init_snapshotsDiffer();
16813
17537
  assertV1OutFolder = (out, dialect6) => {
16814
- if (!(0, import_fs2.existsSync)(out))
17538
+ if (!(0, import_fs4.existsSync)(out))
16815
17539
  return;
16816
- const oldMigrationFolders = (0, import_fs2.readdirSync)(out).filter(
17540
+ const oldMigrationFolders = (0, import_fs4.readdirSync)(out).filter(
16817
17541
  (it) => it.length === 14 && /^\d+$/.test(it)
16818
17542
  );
16819
17543
  if (oldMigrationFolders.length > 0) {
@@ -16833,7 +17557,7 @@ var init_utils = __esm({
16833
17557
  };
16834
17558
  };
16835
17559
  snapshotsPriorV4 = (out) => {
16836
- const oldMigrationFolders = (0, import_fs2.readdirSync)(out).filter(
17560
+ const oldMigrationFolders = (0, import_fs4.readdirSync)(out).filter(
16837
17561
  (it) => it.length === 14 && /^\d+$/.test(it)
16838
17562
  );
16839
17563
  oldMigrationFolders.sort();
@@ -16843,15 +17567,15 @@ var init_utils = __esm({
16843
17567
  return pathJson;
16844
17568
  });
16845
17569
  };
16846
- prepareOutFolder = (out, dialect6) => {
17570
+ prepareOutFolder2 = (out, dialect6) => {
16847
17571
  const meta = (0, import_path2.join)(out, "meta");
16848
17572
  const journalPath = (0, import_path2.join)(meta, "_journal.json");
16849
- if (!(0, import_fs2.existsSync)((0, import_path2.join)(out, "meta"))) {
16850
- (0, import_fs2.mkdirSync)(meta, { recursive: true });
16851
- (0, import_fs2.writeFileSync)(journalPath, JSON.stringify(dryJournal(dialect6)));
17573
+ if (!(0, import_fs4.existsSync)((0, import_path2.join)(out, "meta"))) {
17574
+ (0, import_fs4.mkdirSync)(meta, { recursive: true });
17575
+ (0, import_fs4.writeFileSync)(journalPath, JSON.stringify(dryJournal(dialect6)));
16852
17576
  }
16853
- const journal = JSON.parse((0, import_fs2.readFileSync)(journalPath).toString());
16854
- const snapshots = (0, import_fs2.readdirSync)(meta).filter((it) => !it.startsWith("_")).map((it) => (0, import_path2.join)(meta, it));
17577
+ const journal = JSON.parse((0, import_fs4.readFileSync)(journalPath).toString());
17578
+ const snapshots = (0, import_fs4.readdirSync)(meta).filter((it) => !it.startsWith("_")).map((it) => (0, import_path2.join)(meta, it));
16855
17579
  snapshots.sort();
16856
17580
  return { meta, snapshots, journal };
16857
17581
  };
@@ -16867,7 +17591,7 @@ var init_utils = __esm({
16867
17591
  case "pg":
16868
17592
  return { validator: backwardCompatiblePgSchema, version: 5 };
16869
17593
  case "sqlite":
16870
- return { validator: backwardCompatibleSqliteSchema, version: 4 };
17594
+ return { validator: backwardCompatibleSqliteSchema, version: 5 };
16871
17595
  case "mysql":
16872
17596
  return { validator: backwardCompatibleMysqlSchema, version: 5 };
16873
17597
  }
@@ -16877,7 +17601,7 @@ var init_utils = __esm({
16877
17601
  const result = snapshots.reduce(
16878
17602
  (accum, it) => {
16879
17603
  var _a;
16880
- const raw = JSON.parse((0, import_fs2.readFileSync)(`./${it}`).toString());
17604
+ const raw = JSON.parse((0, import_fs4.readFileSync)(`./${it}`).toString());
16881
17605
  accum.rawMap[it] = raw;
16882
17606
  if (raw["version"] && Number(raw["version"]) > version) {
16883
17607
  console.log(
@@ -16916,7 +17640,7 @@ var init_utils = __esm({
16916
17640
  return result;
16917
17641
  };
16918
17642
  prepareMigrationFolder = (outFolder = "drizzle", dialect6) => {
16919
- const { snapshots, journal } = prepareOutFolder(outFolder, dialect6);
17643
+ const { snapshots, journal } = prepareOutFolder2(outFolder, dialect6);
16920
17644
  const report = validateWithReport(snapshots, dialect6);
16921
17645
  if (report.nonLatest.length > 0) {
16922
17646
  console.log(
@@ -17900,16 +18624,16 @@ var require_node2 = __commonJS({
17900
18624
  }
17901
18625
  exports2.urlGenerate = urlGenerate;
17902
18626
  function normalize(aPath) {
17903
- var path4 = aPath;
18627
+ var path2 = aPath;
17904
18628
  var url = urlParse(aPath);
17905
18629
  if (url) {
17906
18630
  if (!url.path) {
17907
18631
  return aPath;
17908
18632
  }
17909
- path4 = url.path;
18633
+ path2 = url.path;
17910
18634
  }
17911
- var isAbsolute = exports2.isAbsolute(path4);
17912
- var parts = path4.split(/\/+/);
18635
+ var isAbsolute = exports2.isAbsolute(path2);
18636
+ var parts = path2.split(/\/+/);
17913
18637
  for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
17914
18638
  part = parts[i];
17915
18639
  if (part === ".") {
@@ -17926,15 +18650,15 @@ var require_node2 = __commonJS({
17926
18650
  }
17927
18651
  }
17928
18652
  }
17929
- path4 = parts.join("/");
17930
- if (path4 === "") {
17931
- path4 = isAbsolute ? "/" : ".";
18653
+ path2 = parts.join("/");
18654
+ if (path2 === "") {
18655
+ path2 = isAbsolute ? "/" : ".";
17932
18656
  }
17933
18657
  if (url) {
17934
- url.path = path4;
18658
+ url.path = path2;
17935
18659
  return urlGenerate(url);
17936
18660
  }
17937
- return path4;
18661
+ return path2;
17938
18662
  }
17939
18663
  exports2.normalize = normalize;
17940
18664
  function join22(aRoot, aPath) {
@@ -19464,7 +20188,7 @@ var require_node2 = __commonJS({
19464
20188
  });
19465
20189
  var require_source_map_support = __commonJS2((exports2, module22) => {
19466
20190
  var SourceMapConsumer = require_source_map().SourceMapConsumer;
19467
- var path4 = require("path");
20191
+ var path2 = require("path");
19468
20192
  var fs32;
19469
20193
  try {
19470
20194
  fs32 = require("fs");
@@ -19537,15 +20261,15 @@ var require_node2 = __commonJS({
19537
20261
  function supportRelativeURL(file, url) {
19538
20262
  if (!file)
19539
20263
  return url;
19540
- var dir = path4.dirname(file);
20264
+ var dir = path2.dirname(file);
19541
20265
  var match = /^\w+:\/\/[^\/]*/.exec(dir);
19542
20266
  var protocol = match ? match[0] : "";
19543
20267
  var startPath = dir.slice(protocol.length);
19544
20268
  if (protocol && /^\/\w\:/.test(startPath)) {
19545
20269
  protocol += "/";
19546
- return protocol + path4.resolve(dir.slice(protocol.length), url).replace(/\\/g, "/");
20270
+ return protocol + path2.resolve(dir.slice(protocol.length), url).replace(/\\/g, "/");
19547
20271
  }
19548
- return protocol + path4.resolve(dir.slice(protocol.length), url);
20272
+ return protocol + path2.resolve(dir.slice(protocol.length), url);
19549
20273
  }
19550
20274
  function retrieveSourceMapURL(source) {
19551
20275
  var fileData;
@@ -20340,9 +21064,9 @@ var require_node2 = __commonJS({
20340
21064
  "use strict";
20341
21065
  Object.defineProperty(exports2, "__esModule", { value: true });
20342
21066
  var fs32 = require("fs");
20343
- function fileExistsSync(path4) {
21067
+ function fileExistsSync(path2) {
20344
21068
  try {
20345
- var stats = fs32.statSync(path4);
21069
+ var stats = fs32.statSync(path2);
20346
21070
  return stats.isFile();
20347
21071
  } catch (err2) {
20348
21072
  return false;
@@ -20356,8 +21080,8 @@ var require_node2 = __commonJS({
20356
21080
  return require(packageJsonPath);
20357
21081
  }
20358
21082
  exports2.readJsonFromDiskSync = readJsonFromDiskSync;
20359
- function readJsonFromDiskAsync(path4, callback) {
20360
- fs32.readFile(path4, "utf8", function(err2, result) {
21083
+ function readJsonFromDiskAsync(path2, callback) {
21084
+ fs32.readFile(path2, "utf8", function(err2, result) {
20361
21085
  if (err2 || !result) {
20362
21086
  return callback();
20363
21087
  }
@@ -20366,8 +21090,8 @@ var require_node2 = __commonJS({
20366
21090
  });
20367
21091
  }
20368
21092
  exports2.readJsonFromDiskAsync = readJsonFromDiskAsync;
20369
- function fileExistsAsync(path22, callback2) {
20370
- fs32.stat(path22, function(err2, stats) {
21093
+ function fileExistsAsync(path2, callback2) {
21094
+ fs32.stat(path2, function(err2, stats) {
20371
21095
  if (err2) {
20372
21096
  return callback2(void 0, false);
20373
21097
  }
@@ -20375,15 +21099,15 @@ var require_node2 = __commonJS({
20375
21099
  });
20376
21100
  }
20377
21101
  exports2.fileExistsAsync = fileExistsAsync;
20378
- function removeExtension(path4) {
20379
- return path4.substring(0, path4.lastIndexOf(".")) || path4;
21102
+ function removeExtension(path2) {
21103
+ return path2.substring(0, path2.lastIndexOf(".")) || path2;
20380
21104
  }
20381
21105
  exports2.removeExtension = removeExtension;
20382
21106
  });
20383
21107
  var require_mapping_entry = __commonJS2((exports2) => {
20384
21108
  "use strict";
20385
21109
  Object.defineProperty(exports2, "__esModule", { value: true });
20386
- var path4 = require("path");
21110
+ var path2 = require("path");
20387
21111
  function getAbsoluteMappingEntries(absoluteBaseUrl, paths, addMatchAll) {
20388
21112
  var sortedKeys = sortByLongestPrefix(Object.keys(paths));
20389
21113
  var absolutePaths = [];
@@ -20392,7 +21116,7 @@ var require_node2 = __commonJS({
20392
21116
  absolutePaths.push({
20393
21117
  pattern: key,
20394
21118
  paths: paths[key].map(function(pathToResolve) {
20395
- return path4.join(absoluteBaseUrl, pathToResolve);
21119
+ return path2.join(absoluteBaseUrl, pathToResolve);
20396
21120
  })
20397
21121
  });
20398
21122
  }
@@ -20418,11 +21142,11 @@ var require_node2 = __commonJS({
20418
21142
  var require_try_path = __commonJS2((exports2) => {
20419
21143
  "use strict";
20420
21144
  Object.defineProperty(exports2, "__esModule", { value: true });
20421
- var path4 = require("path");
21145
+ var path2 = require("path");
20422
21146
  var path_1 = require("path");
20423
21147
  var filesystem_1 = require_filesystem();
20424
21148
  function getPathsToTry(extensions, absolutePathMappings, requestedModule) {
20425
- if (!absolutePathMappings || !requestedModule || requestedModule[0] === "." || requestedModule[0] === path4.sep) {
21149
+ if (!absolutePathMappings || !requestedModule || requestedModule[0] === "." || requestedModule[0] === path2.sep) {
20426
21150
  return void 0;
20427
21151
  }
20428
21152
  var pathsToTry = [];
@@ -20438,9 +21162,9 @@ var require_node2 = __commonJS({
20438
21162
  }));
20439
21163
  pathsToTry.push({
20440
21164
  type: "package",
20441
- path: path4.join(physicalPath, "/package.json")
21165
+ path: path2.join(physicalPath, "/package.json")
20442
21166
  });
20443
- var indexPath = path4.join(physicalPath, "/index");
21167
+ var indexPath = path2.join(physicalPath, "/index");
20444
21168
  pathsToTry.push.apply(pathsToTry, extensions.map(function(e) {
20445
21169
  return { type: "index", path: indexPath + e };
20446
21170
  }));
@@ -20487,7 +21211,7 @@ var require_node2 = __commonJS({
20487
21211
  var require_match_path_sync = __commonJS2((exports2) => {
20488
21212
  "use strict";
20489
21213
  Object.defineProperty(exports2, "__esModule", { value: true });
20490
- var path4 = require("path");
21214
+ var path2 = require("path");
20491
21215
  var Filesystem = require_filesystem();
20492
21216
  var MappingEntry = require_mapping_entry();
20493
21217
  var TryPath = require_try_path();
@@ -20529,7 +21253,7 @@ var require_node2 = __commonJS({
20529
21253
  var mainFieldName = mainFields[index4];
20530
21254
  var candidateMapping = packageJson[mainFieldName];
20531
21255
  if (candidateMapping && typeof candidateMapping === "string") {
20532
- var candidateFilePath = path4.join(path4.dirname(packageJsonPath), candidateMapping);
21256
+ var candidateFilePath = path2.join(path2.dirname(packageJsonPath), candidateMapping);
20533
21257
  if (fileExists(candidateFilePath)) {
20534
21258
  return candidateFilePath;
20535
21259
  }
@@ -20568,7 +21292,7 @@ var require_node2 = __commonJS({
20568
21292
  var require_match_path_async = __commonJS2((exports2) => {
20569
21293
  "use strict";
20570
21294
  Object.defineProperty(exports2, "__esModule", { value: true });
20571
- var path4 = require("path");
21295
+ var path2 = require("path");
20572
21296
  var TryPath = require_try_path();
20573
21297
  var MappingEntry = require_mapping_entry();
20574
21298
  var Filesystem = require_filesystem();
@@ -20619,7 +21343,7 @@ var require_node2 = __commonJS({
20619
21343
  if (typeof mainFieldMapping !== "string") {
20620
21344
  return tryNext();
20621
21345
  }
20622
- var mappedFilePath = path4.join(path4.dirname(packageJsonPath), mainFieldMapping);
21346
+ var mappedFilePath = path2.join(path2.dirname(packageJsonPath), mainFieldMapping);
20623
21347
  fileExistsAsync(mappedFilePath, function(err2, exists) {
20624
21348
  if (err2) {
20625
21349
  return doneCallback(err2);
@@ -21839,7 +22563,7 @@ var require_node2 = __commonJS({
21839
22563
  return t;
21840
22564
  };
21841
22565
  Object.defineProperty(exports2, "__esModule", { value: true });
21842
- var path4 = require("path");
22566
+ var path2 = require("path");
21843
22567
  var fs32 = require("fs");
21844
22568
  var JSON5 = require_lib32();
21845
22569
  var StripBom = require_strip_bom();
@@ -21869,24 +22593,24 @@ var require_node2 = __commonJS({
21869
22593
  }
21870
22594
  function resolveConfigPath(cwd, filename) {
21871
22595
  if (filename) {
21872
- var absolutePath = fs32.lstatSync(filename).isDirectory() ? path4.resolve(filename, "./tsconfig.json") : path4.resolve(cwd, filename);
22596
+ var absolutePath = fs32.lstatSync(filename).isDirectory() ? path2.resolve(filename, "./tsconfig.json") : path2.resolve(cwd, filename);
21873
22597
  return absolutePath;
21874
22598
  }
21875
22599
  if (fs32.statSync(cwd).isFile()) {
21876
- return path4.resolve(cwd);
22600
+ return path2.resolve(cwd);
21877
22601
  }
21878
22602
  var configAbsolutePath = walkForTsConfig(cwd);
21879
- return configAbsolutePath ? path4.resolve(configAbsolutePath) : void 0;
22603
+ return configAbsolutePath ? path2.resolve(configAbsolutePath) : void 0;
21880
22604
  }
21881
22605
  function walkForTsConfig(directory, existsSync4) {
21882
22606
  if (existsSync4 === void 0) {
21883
22607
  existsSync4 = fs32.existsSync;
21884
22608
  }
21885
- var configPath = path4.join(directory, "./tsconfig.json");
22609
+ var configPath = path2.join(directory, "./tsconfig.json");
21886
22610
  if (existsSync4(configPath)) {
21887
22611
  return configPath;
21888
22612
  }
21889
- var parentDirectory = path4.join(directory, "../");
22613
+ var parentDirectory = path2.join(directory, "../");
21890
22614
  if (directory === parentDirectory) {
21891
22615
  return void 0;
21892
22616
  }
@@ -21913,15 +22637,15 @@ var require_node2 = __commonJS({
21913
22637
  if (typeof extendedConfig === "string" && extendedConfig.indexOf(".json") === -1) {
21914
22638
  extendedConfig += ".json";
21915
22639
  }
21916
- var currentDir = path4.dirname(configFilePath);
21917
- var extendedConfigPath = path4.join(currentDir, extendedConfig);
22640
+ var currentDir = path2.dirname(configFilePath);
22641
+ var extendedConfigPath = path2.join(currentDir, extendedConfig);
21918
22642
  if (extendedConfig.indexOf("/") !== -1 && extendedConfig.indexOf(".") !== -1 && !existsSync4(extendedConfigPath)) {
21919
- extendedConfigPath = path4.join(currentDir, "node_modules", extendedConfig);
22643
+ extendedConfigPath = path2.join(currentDir, "node_modules", extendedConfig);
21920
22644
  }
21921
22645
  var base = loadTsconfig(extendedConfigPath, existsSync4, readFileSync4) || {};
21922
22646
  if (base.compilerOptions && base.compilerOptions.baseUrl) {
21923
- var extendsDir = path4.dirname(extendedConfig);
21924
- base.compilerOptions.baseUrl = path4.join(extendsDir, base.compilerOptions.baseUrl);
22647
+ var extendsDir = path2.dirname(extendedConfig);
22648
+ base.compilerOptions.baseUrl = path2.join(extendsDir, base.compilerOptions.baseUrl);
21925
22649
  }
21926
22650
  return __assign({}, base, config, { compilerOptions: __assign({}, base.compilerOptions, config.compilerOptions) });
21927
22651
  }
@@ -22146,7 +22870,7 @@ var require_node2 = __commonJS({
22146
22870
  "use strict";
22147
22871
  Object.defineProperty(exports2, "__esModule", { value: true });
22148
22872
  var TsConfigLoader = require_tsconfig_loader();
22149
- var path4 = require("path");
22873
+ var path2 = require("path");
22150
22874
  var options_1 = require_options();
22151
22875
  function loadConfig2(cwd) {
22152
22876
  if (cwd === void 0) {
@@ -22158,7 +22882,7 @@ var require_node2 = __commonJS({
22158
22882
  function configLoader(_a) {
22159
22883
  var cwd = _a.cwd, explicitParams = _a.explicitParams, _b = _a.tsConfigLoader, tsConfigLoader = _b === void 0 ? TsConfigLoader.tsConfigLoader : _b;
22160
22884
  if (explicitParams) {
22161
- var absoluteBaseUrl_1 = path4.isAbsolute(explicitParams.baseUrl) ? explicitParams.baseUrl : path4.join(cwd, explicitParams.baseUrl);
22885
+ var absoluteBaseUrl_1 = path2.isAbsolute(explicitParams.baseUrl) ? explicitParams.baseUrl : path2.join(cwd, explicitParams.baseUrl);
22162
22886
  return {
22163
22887
  resultType: "success",
22164
22888
  configFileAbsolutePath: "",
@@ -22187,8 +22911,8 @@ var require_node2 = __commonJS({
22187
22911
  message: "Missing baseUrl in compilerOptions"
22188
22912
  };
22189
22913
  }
22190
- var tsConfigDir = path4.dirname(loadResult.tsConfigPath);
22191
- var absoluteBaseUrl = path4.join(tsConfigDir, loadResult.baseUrl);
22914
+ var tsConfigDir = path2.dirname(loadResult.tsConfigPath);
22915
+ var absoluteBaseUrl = path2.join(tsConfigDir, loadResult.baseUrl);
22192
22916
  return {
22193
22917
  resultType: "success",
22194
22918
  configFileAbsolutePath: loadResult.tsConfigPath,
@@ -22389,8 +23113,8 @@ var require_node2 = __commonJS({
22389
23113
  });
22390
23114
  var getOptions = (cwd) => {
22391
23115
  var _a, _b, _c, _d;
22392
- const { data, path: path4 } = joycon.loadSync(["tsconfig.json", "jsconfig.json"], cwd);
22393
- if (path4 && data) {
23116
+ const { data, path: path2 } = joycon.loadSync(["tsconfig.json", "jsconfig.json"], cwd);
23117
+ if (path2 && data) {
22394
23118
  return {
22395
23119
  jsxFactory: (_a = data.compilerOptions) == null ? void 0 : _a.jsxFactory,
22396
23120
  jsxFragment: (_b = data.compilerOptions) == null ? void 0 : _b.jsxFragmentFactory,
@@ -23056,8 +23780,8 @@ var require_minimatch = __commonJS({
23056
23780
  return new Minimatch(pattern, options).match(p);
23057
23781
  };
23058
23782
  module2.exports = minimatch;
23059
- var path4 = require_path();
23060
- minimatch.sep = path4.sep;
23783
+ var path2 = require_path();
23784
+ minimatch.sep = path2.sep;
23061
23785
  var GLOBSTAR = Symbol("globstar **");
23062
23786
  minimatch.GLOBSTAR = GLOBSTAR;
23063
23787
  var expand = require_brace_expansion();
@@ -23573,8 +24297,8 @@ var require_minimatch = __commonJS({
23573
24297
  if (f === "/" && partial)
23574
24298
  return true;
23575
24299
  const options = this.options;
23576
- if (path4.sep !== "/") {
23577
- f = f.split(path4.sep).join("/");
24300
+ if (path2.sep !== "/") {
24301
+ f = f.split(path2.sep).join("/");
23578
24302
  }
23579
24303
  f = f.split(slashSplit);
23580
24304
  this.debug(this.pattern, "split", f);
@@ -23672,7 +24396,7 @@ var require_common2 = __commonJS({
23672
24396
  return Object.prototype.hasOwnProperty.call(obj, field);
23673
24397
  }
23674
24398
  var fs7 = require("fs");
23675
- var path4 = require("path");
24399
+ var path2 = require("path");
23676
24400
  var minimatch = require_minimatch();
23677
24401
  var isAbsolute = require("path").isAbsolute;
23678
24402
  var Minimatch = minimatch.Minimatch;
@@ -23739,13 +24463,13 @@ var require_common2 = __commonJS({
23739
24463
  self2.changedCwd = false;
23740
24464
  var cwd = process.cwd();
23741
24465
  if (!ownProp(options, "cwd"))
23742
- self2.cwd = path4.resolve(cwd);
24466
+ self2.cwd = path2.resolve(cwd);
23743
24467
  else {
23744
- self2.cwd = path4.resolve(options.cwd);
24468
+ self2.cwd = path2.resolve(options.cwd);
23745
24469
  self2.changedCwd = self2.cwd !== cwd;
23746
24470
  }
23747
- self2.root = options.root || path4.resolve(self2.cwd, "/");
23748
- self2.root = path4.resolve(self2.root);
24471
+ self2.root = options.root || path2.resolve(self2.cwd, "/");
24472
+ self2.root = path2.resolve(self2.root);
23749
24473
  self2.cwdAbs = isAbsolute(self2.cwd) ? self2.cwd : makeAbs(self2, self2.cwd);
23750
24474
  self2.nomount = !!options.nomount;
23751
24475
  if (process.platform === "win32") {
@@ -23827,30 +24551,30 @@ var require_common2 = __commonJS({
23827
24551
  function makeAbs(self2, f) {
23828
24552
  var abs = f;
23829
24553
  if (f.charAt(0) === "/") {
23830
- abs = path4.join(self2.root, f);
24554
+ abs = path2.join(self2.root, f);
23831
24555
  } else if (isAbsolute(f) || f === "") {
23832
24556
  abs = f;
23833
24557
  } else if (self2.changedCwd) {
23834
- abs = path4.resolve(self2.cwd, f);
24558
+ abs = path2.resolve(self2.cwd, f);
23835
24559
  } else {
23836
- abs = path4.resolve(f);
24560
+ abs = path2.resolve(f);
23837
24561
  }
23838
24562
  if (process.platform === "win32")
23839
24563
  abs = abs.replace(/\\/g, "/");
23840
24564
  return abs;
23841
24565
  }
23842
- function isIgnored(self2, path5) {
24566
+ function isIgnored(self2, path3) {
23843
24567
  if (!self2.ignore.length)
23844
24568
  return false;
23845
24569
  return self2.ignore.some(function(item) {
23846
- return item.matcher.match(path5) || !!(item.gmatcher && item.gmatcher.match(path5));
24570
+ return item.matcher.match(path3) || !!(item.gmatcher && item.gmatcher.match(path3));
23847
24571
  });
23848
24572
  }
23849
- function childrenIgnored(self2, path5) {
24573
+ function childrenIgnored(self2, path3) {
23850
24574
  if (!self2.ignore.length)
23851
24575
  return false;
23852
24576
  return self2.ignore.some(function(item) {
23853
- return !!(item.gmatcher && item.gmatcher.match(path5));
24577
+ return !!(item.gmatcher && item.gmatcher.match(path3));
23854
24578
  });
23855
24579
  }
23856
24580
  }
@@ -23866,7 +24590,7 @@ var require_sync = __commonJS({
23866
24590
  var Minimatch = minimatch.Minimatch;
23867
24591
  var Glob = require_glob().Glob;
23868
24592
  var util2 = require("util");
23869
- var path4 = require("path");
24593
+ var path2 = require("path");
23870
24594
  var assert = require("assert");
23871
24595
  var isAbsolute = require("path").isAbsolute;
23872
24596
  var common = require_common2();
@@ -23994,7 +24718,7 @@ var require_sync = __commonJS({
23994
24718
  e = prefix + e;
23995
24719
  }
23996
24720
  if (e.charAt(0) === "/" && !this.nomount) {
23997
- e = path4.join(this.root, e);
24721
+ e = path2.join(this.root, e);
23998
24722
  }
23999
24723
  this._emitMatch(index4, e);
24000
24724
  }
@@ -24143,9 +24867,9 @@ var require_sync = __commonJS({
24143
24867
  if (prefix && isAbsolute(prefix) && !this.nomount) {
24144
24868
  var trail = /[\/\\]$/.test(prefix);
24145
24869
  if (prefix.charAt(0) === "/") {
24146
- prefix = path4.join(this.root, prefix);
24870
+ prefix = path2.join(this.root, prefix);
24147
24871
  } else {
24148
- prefix = path4.resolve(this.root, prefix);
24872
+ prefix = path2.resolve(this.root, prefix);
24149
24873
  if (trail)
24150
24874
  prefix += "/";
24151
24875
  }
@@ -24340,7 +25064,7 @@ var require_glob = __commonJS({
24340
25064
  var Minimatch = minimatch.Minimatch;
24341
25065
  var inherits = require_inherits();
24342
25066
  var EE = require("events").EventEmitter;
24343
- var path4 = require("path");
25067
+ var path2 = require("path");
24344
25068
  var assert = require("assert");
24345
25069
  var isAbsolute = require("path").isAbsolute;
24346
25070
  var globSync = require_sync();
@@ -24623,7 +25347,7 @@ var require_glob = __commonJS({
24623
25347
  e = prefix + e;
24624
25348
  }
24625
25349
  if (e.charAt(0) === "/" && !this.nomount) {
24626
- e = path4.join(this.root, e);
25350
+ e = path2.join(this.root, e);
24627
25351
  }
24628
25352
  this._emitMatch(index4, e);
24629
25353
  }
@@ -24810,9 +25534,9 @@ var require_glob = __commonJS({
24810
25534
  if (prefix && isAbsolute(prefix) && !this.nomount) {
24811
25535
  var trail = /[\/\\]$/.test(prefix);
24812
25536
  if (prefix.charAt(0) === "/") {
24813
- prefix = path4.join(this.root, prefix);
25537
+ prefix = path2.join(this.root, prefix);
24814
25538
  } else {
24815
- prefix = path4.resolve(this.root, prefix);
25539
+ prefix = path2.resolve(this.root, prefix);
24816
25540
  if (trail)
24817
25541
  prefix += "/";
24818
25542
  }
@@ -24894,6 +25618,7 @@ __export(mysqlImports_exports, {
24894
25618
  var import_mysql_core, prepareFromMySqlImports;
24895
25619
  var init_mysqlImports = __esm({
24896
25620
  "src/serializer/mysqlImports.ts"() {
25621
+ "use strict";
24897
25622
  import_mysql_core = require("drizzle-orm/mysql-core");
24898
25623
  prepareFromMySqlImports = (imports) => {
24899
25624
  const tables = [];
@@ -24934,20 +25659,21 @@ function clearDefaults(defaultValue, collate) {
24934
25659
  if (defaultValue.startsWith(collate)) {
24935
25660
  resultDefault = resultDefault.substring(collate.length, defaultValue.length).replace(/\\/g, "");
24936
25661
  if (resultDefault.startsWith("'") && resultDefault.endsWith("'")) {
24937
- return `("${resultDefault.substring(1, resultDefault.length - 1)}")`;
25662
+ return `('${resultDefault.substring(1, resultDefault.length - 1)}')`;
24938
25663
  } else {
24939
- return `("${resultDefault}")`;
25664
+ return `('${resultDefault}')`;
24940
25665
  }
24941
25666
  } else {
24942
25667
  return `(${resultDefault})`;
24943
25668
  }
24944
25669
  }
24945
- var import_mysql_core2, import_table, import_utils7, import_sql, import_common, import_date, dialect3, indexName, generateMySqlSnapshot, fromDatabase;
25670
+ var import_mysql_core2, import_table, import_utils9, import_sql, import_common, import_date, dialect3, indexName, generateMySqlSnapshot, fromDatabase;
24946
25671
  var init_mysqlSerializer = __esm({
24947
25672
  "src/serializer/mysqlSerializer.ts"() {
25673
+ "use strict";
24948
25674
  import_mysql_core2 = require("drizzle-orm/mysql-core");
24949
25675
  import_table = require("drizzle-orm/table");
24950
- import_utils7 = require("drizzle-orm/mysql-core/utils");
25676
+ import_utils9 = require("drizzle-orm/mysql-core/utils");
24951
25677
  import_sql = require("drizzle-orm/sql");
24952
25678
  import_common = require("drizzle-orm/mysql-core/columns/common");
24953
25679
  import_date = require("drizzle-orm/mysql-core/columns/date.common");
@@ -24963,11 +25689,13 @@ var init_mysqlSerializer = __esm({
24963
25689
  columns,
24964
25690
  indexes,
24965
25691
  foreignKeys,
24966
- schema: schema4
24967
- } = (0, import_utils7.getTableConfig)(table4);
25692
+ schema: schema4,
25693
+ primaryKeys
25694
+ } = (0, import_utils9.getTableConfig)(table4);
24968
25695
  const columnsObject = {};
24969
25696
  const indexesObject = {};
24970
25697
  const foreignKeysObject = {};
25698
+ const primaryKeysObject = {};
24971
25699
  columns.forEach((column6) => {
24972
25700
  const notNull = column6.notNull;
24973
25701
  const primaryKey = column6.primary;
@@ -24990,23 +25718,34 @@ var init_mysqlSerializer = __esm({
24990
25718
  }).join();
24991
25719
  } else {
24992
25720
  if (typeof column6.default === "string") {
24993
- columnToSet.default = `"${column6.default}"`;
25721
+ columnToSet.default = `'${column6.default}'`;
24994
25722
  } else {
24995
25723
  if (sqlTypeLowered === "json") {
24996
25724
  columnToSet.default = `'${JSON.stringify(column6.default)}'`;
24997
25725
  } else if (column6.default instanceof Date) {
24998
- columnToSet.default = `'${column6.default.toISOString()}'`;
25726
+ if (sqlTypeLowered === "date") {
25727
+ columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`;
25728
+ } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
25729
+ columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`;
25730
+ }
24999
25731
  } else {
25000
25732
  columnToSet.default = column6.default;
25001
25733
  }
25002
25734
  }
25003
- }
25004
- if (["blob", "text", "json"].includes(column6.getSQLType())) {
25005
- columnToSet.default = `(${columnToSet.default})`;
25735
+ if (["blob", "text", "json"].includes(column6.getSQLType())) {
25736
+ columnToSet.default = `(${columnToSet.default})`;
25737
+ }
25006
25738
  }
25007
25739
  }
25008
25740
  columnsObject[column6.name] = columnToSet;
25009
25741
  });
25742
+ primaryKeys.map((pk) => {
25743
+ const columnNames = pk.columns.map((c) => c.name);
25744
+ primaryKeysObject[`${tableName}_${columnNames.join("_")}`] = {
25745
+ name: `${tableName}_${columnNames.join("_")}`,
25746
+ columns: columnNames
25747
+ };
25748
+ });
25010
25749
  const fks = foreignKeys.map((fk4) => {
25011
25750
  const name = fk4.getName();
25012
25751
  const tableFrom = tableName;
@@ -25055,7 +25794,8 @@ var init_mysqlSerializer = __esm({
25055
25794
  schema: schema4,
25056
25795
  columns: columnsObject,
25057
25796
  indexes: indexesObject,
25058
- foreignKeys: foreignKeysObject
25797
+ foreignKeys: foreignKeysObject,
25798
+ compositePrimaryKeys: primaryKeysObject
25059
25799
  };
25060
25800
  }
25061
25801
  const schemas = Object.fromEntries(
@@ -25084,13 +25824,18 @@ var init_mysqlSerializer = __esm({
25084
25824
  let tablesCount = /* @__PURE__ */ new Set();
25085
25825
  let indexesCount = 0;
25086
25826
  let foreignKeysCount = 0;
25827
+ const tableToPk = {};
25087
25828
  for (const column6 of response) {
25088
25829
  columnsCount += 1;
25089
- progressCallback("columns", columnsCount, "fetching");
25830
+ if (progressCallback) {
25831
+ progressCallback("columns", columnsCount, "fetching");
25832
+ }
25090
25833
  const schema4 = column6["TABLE_SCHEMA"];
25091
25834
  const tableName = column6["TABLE_NAME"];
25092
25835
  tablesCount.add(`${schema4}.${tableName}`);
25093
- progressCallback("columns", tablesCount.size, "fetching");
25836
+ if (progressCallback) {
25837
+ progressCallback("columns", tablesCount.size, "fetching");
25838
+ }
25094
25839
  const columnName = column6["COLUMN_NAME"];
25095
25840
  const isNullable = column6["IS_NULLABLE"] === "YES";
25096
25841
  const dataType = column6["DATA_TYPE"];
@@ -25100,16 +25845,27 @@ var init_mysqlSerializer = __esm({
25100
25845
  const isDefaultAnExpression = column6["EXTRA"] === "DEFAULT_GENERATED";
25101
25846
  const columnDefault = column6["COLUMN_DEFAULT"];
25102
25847
  const collation = column6["CHARACTER_SET_NAME"];
25848
+ if (isPrimary) {
25849
+ if (typeof tableToPk[tableName] === "undefined") {
25850
+ tableToPk[tableName] = [columnName];
25851
+ } else {
25852
+ tableToPk[tableName].push(columnName);
25853
+ }
25854
+ }
25103
25855
  if (schema4 !== inputSchema) {
25104
25856
  schemas.push(schema4);
25105
25857
  }
25106
25858
  const table4 = result[tableName];
25859
+ let changedType = columnType.replace("bigint unsigned", "serial");
25860
+ if (columnType.startsWith("tinyint")) {
25861
+ changedType = "tinyint";
25862
+ }
25107
25863
  const newColumn = {
25108
- default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) ? Number(columnDefault) : isDefaultAnExpression ? clearDefaults(columnDefault, collation) : `"${columnDefault}"`,
25864
+ default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) ? Number(columnDefault) : isDefaultAnExpression ? clearDefaults(columnDefault, collation) : `'${columnDefault}'`,
25109
25865
  autoincrement: isAutoincrement,
25110
25866
  name: columnName,
25111
- type: columnType.replace("bigint unsigned", "serial"),
25112
- primaryKey: isPrimary,
25867
+ type: changedType,
25868
+ primaryKey: false,
25113
25869
  notNull: !isNullable
25114
25870
  };
25115
25871
  if (!table4) {
@@ -25119,6 +25875,7 @@ var init_mysqlSerializer = __esm({
25119
25875
  columns: {
25120
25876
  [columnName]: newColumn
25121
25877
  },
25878
+ compositePrimaryKeys: {},
25122
25879
  indexes: {},
25123
25880
  foreignKeys: {}
25124
25881
  };
@@ -25126,8 +25883,23 @@ var init_mysqlSerializer = __esm({
25126
25883
  result[tableName].columns[columnName] = newColumn;
25127
25884
  }
25128
25885
  }
25129
- progressCallback("columns", columnsCount, "done");
25130
- progressCallback("tables", tablesCount.size, "done");
25886
+ for (const [key, value] of Object.entries(tableToPk)) {
25887
+ if (value.length > 1) {
25888
+ result[key].compositePrimaryKeys = {
25889
+ [`${key}_${value.join("_")}`]: {
25890
+ name: `${key}_${value.join("_")}`,
25891
+ columns: value
25892
+ }
25893
+ };
25894
+ } else if (value.length === 1) {
25895
+ result[key].columns[value[0]].primaryKey = true;
25896
+ } else {
25897
+ }
25898
+ }
25899
+ if (progressCallback) {
25900
+ progressCallback("columns", columnsCount, "done");
25901
+ progressCallback("tables", tablesCount.size, "done");
25902
+ }
25131
25903
  try {
25132
25904
  const fks = await db.execute(
25133
25905
  `SELECT INFORMATION_SCHEMA.KEY_COLUMN_USAGE.TABLE_SCHEMA,INFORMATION_SCHEMA.KEY_COLUMN_USAGE.TABLE_NAME,INFORMATION_SCHEMA.KEY_COLUMN_USAGE.CONSTRAINT_NAME,INFORMATION_SCHEMA.KEY_COLUMN_USAGE.COLUMN_NAME,INFORMATION_SCHEMA.KEY_COLUMN_USAGE.REFERENCED_TABLE_SCHEMA,INFORMATION_SCHEMA.KEY_COLUMN_USAGE.REFERENCED_TABLE_NAME, INFORMATION_SCHEMA.KEY_COLUMN_USAGE.REFERENCED_COLUMN_NAME,information_schema.referential_constraints.UPDATE_RULE, information_schema.referential_constraints.DELETE_RULE
@@ -25140,7 +25912,9 @@ var init_mysqlSerializer = __esm({
25140
25912
  const fkRows = fks[0];
25141
25913
  for (const fkRow of fkRows) {
25142
25914
  foreignKeysCount += 1;
25143
- progressCallback("fks", foreignKeysCount, "fetching");
25915
+ if (progressCallback) {
25916
+ progressCallback("fks", foreignKeysCount, "fetching");
25917
+ }
25144
25918
  const tableSchema = fkRow["TABLE_SCHEMA"];
25145
25919
  const tableName = fkRow["TABLE_NAME"];
25146
25920
  const constraintName = fkRow["CONSTRAINT_NAME"];
@@ -25179,7 +25953,9 @@ var init_mysqlSerializer = __esm({
25179
25953
  } catch (e) {
25180
25954
  console.log(`Can't proccess foreign keys`);
25181
25955
  }
25182
- progressCallback("fks", foreignKeysCount, "done");
25956
+ if (progressCallback) {
25957
+ progressCallback("fks", foreignKeysCount, "done");
25958
+ }
25183
25959
  const idxs = await db.execute(
25184
25960
  `select * from INFORMATION_SCHEMA.STATISTICS
25185
25961
  WHERE INFORMATION_SCHEMA.STATISTICS.TABLE_SCHEMA = ? and INFORMATION_SCHEMA.STATISTICS.INDEX_NAME != 'PRIMARY';`,
@@ -25198,7 +25974,9 @@ var init_mysqlSerializer = __esm({
25198
25974
  if (tableInResult.columns[columnName].type === "serial")
25199
25975
  continue;
25200
25976
  indexesCount += 1;
25201
- progressCallback("indexes", indexesCount, "fetching");
25977
+ if (progressCallback) {
25978
+ progressCallback("indexes", indexesCount, "fetching");
25979
+ }
25202
25980
  if (typeof tableInResult.indexes[constraintName] !== "undefined") {
25203
25981
  tableInResult.indexes[constraintName].columns.push(columnName);
25204
25982
  } else {
@@ -25209,8 +25987,10 @@ var init_mysqlSerializer = __esm({
25209
25987
  };
25210
25988
  }
25211
25989
  }
25212
- progressCallback("indexes", indexesCount, "done");
25213
- progressCallback("enums", 0, "done");
25990
+ if (progressCallback) {
25991
+ progressCallback("indexes", indexesCount, "done");
25992
+ progressCallback("enums", 0, "done");
25993
+ }
25214
25994
  const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it]));
25215
25995
  return {
25216
25996
  version: "5",
@@ -25235,6 +26015,7 @@ __export(pgImports_exports, {
25235
26015
  var import_pg_core, prepareFromPgImports;
25236
26016
  var init_pgImports = __esm({
25237
26017
  "src/serializer/pgImports.ts"() {
26018
+ "use strict";
25238
26019
  import_pg_core = require("drizzle-orm/pg-core");
25239
26020
  prepareFromPgImports = (imports) => {
25240
26021
  const tables = [];
@@ -25270,11 +26051,12 @@ __export(pgSerializer_exports, {
25270
26051
  generatePgSnapshot: () => generatePgSnapshot,
25271
26052
  indexName: () => indexName2
25272
26053
  });
25273
- var import_pg_core2, import_utils8, import_sql2, import_table2, dialect4, indexName2, generatePgSnapshot, fromDatabase2, defaultForColumn;
26054
+ var import_pg_core2, import_utils10, import_sql2, import_table2, dialect4, indexName2, generatePgSnapshot, trimChar, fromDatabase2, columnToDefault, defaultForColumn;
25274
26055
  var init_pgSerializer = __esm({
25275
26056
  "src/serializer/pgSerializer.ts"() {
26057
+ "use strict";
25276
26058
  import_pg_core2 = require("drizzle-orm/pg-core");
25277
- import_utils8 = require("drizzle-orm/pg-core/utils");
26059
+ import_utils10 = require("drizzle-orm/pg-core/utils");
25278
26060
  import_sql2 = require("drizzle-orm/sql");
25279
26061
  import_table2 = require("drizzle-orm/table");
25280
26062
  dialect4 = new import_pg_core2.PgDialect();
@@ -25290,11 +26072,13 @@ var init_pgSerializer = __esm({
25290
26072
  indexes,
25291
26073
  foreignKeys,
25292
26074
  checks,
25293
- schema: schema4
25294
- } = (0, import_utils8.getTableConfig)(table4);
26075
+ schema: schema4,
26076
+ primaryKeys
26077
+ } = (0, import_utils10.getTableConfig)(table4);
25295
26078
  const columnsObject = {};
25296
26079
  const indexesObject = {};
25297
26080
  const foreignKeysObject = {};
26081
+ const primaryKeysObject = {};
25298
26082
  columns.forEach((column6) => {
25299
26083
  const notNull = column6.notNull;
25300
26084
  const primaryKey = column6.primary;
@@ -25322,7 +26106,13 @@ var init_pgSerializer = __esm({
25322
26106
  column6.default
25323
26107
  )}'::${sqlTypeLowered}`;
25324
26108
  } else if (column6.default instanceof Date) {
25325
- columnToSet.default = `'${column6.default.toISOString()}'`;
26109
+ if (sqlTypeLowered === "date") {
26110
+ columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`;
26111
+ } else if (sqlTypeLowered === "timestamp") {
26112
+ columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`;
26113
+ } else {
26114
+ columnToSet.default = `'${column6.default.toISOString()}'`;
26115
+ }
25326
26116
  } else {
25327
26117
  columnToSet.default = column6.default;
25328
26118
  }
@@ -25331,6 +26121,13 @@ var init_pgSerializer = __esm({
25331
26121
  }
25332
26122
  columnsObject[column6.name] = columnToSet;
25333
26123
  });
26124
+ primaryKeys.map((pk) => {
26125
+ const columnNames = pk.columns.map((c) => c.name);
26126
+ primaryKeysObject[`${tableName}_${columnNames.join("_")}`] = {
26127
+ name: `${tableName}_${columnNames.join("_")}`,
26128
+ columns: columnNames
26129
+ };
26130
+ });
25334
26131
  const fks = foreignKeys.map((fk4) => {
25335
26132
  const name = fk4.getName();
25336
26133
  const tableFrom = tableName;
@@ -25379,7 +26176,8 @@ var init_pgSerializer = __esm({
25379
26176
  schema: schema4 != null ? schema4 : "",
25380
26177
  columns: columnsObject,
25381
26178
  indexes: indexesObject,
25382
- foreignKeys: foreignKeysObject
26179
+ foreignKeys: foreignKeysObject,
26180
+ compositePrimaryKeys: primaryKeysObject
25383
26181
  };
25384
26182
  }
25385
26183
  const enumsToReturn = enums.reduce((map, obj) => {
@@ -25407,16 +26205,25 @@ var init_pgSerializer = __esm({
25407
26205
  }
25408
26206
  };
25409
26207
  };
26208
+ trimChar = (str, char) => {
26209
+ let start = 0;
26210
+ let end = str.length;
26211
+ while (start < end && str[start] === char)
26212
+ ++start;
26213
+ while (end > start && str[end - 1] === char)
26214
+ --end;
26215
+ return start > 0 || end < str.length ? str.substring(start, end) : str.toString();
26216
+ };
25410
26217
  fromDatabase2 = async (db, progressCallback) => {
25411
26218
  const result = {};
25412
26219
  const allTables = await db.query(
25413
26220
  `SELECT table_schema, table_name FROM information_schema.tables WHERE table_schema = 'public';`
25414
26221
  );
25415
- const schemas = new Set(
25416
- allTables.rows.map((it) => it.table_schema)
25417
- );
26222
+ const schemas = new Set(allTables.rows.map((it) => it.table_schema));
25418
26223
  schemas.delete("public");
25419
- progressCallback("tables", allTables.rows.length, "done");
26224
+ if (progressCallback) {
26225
+ progressCallback("tables", allTables.rows.length, "done");
26226
+ }
25420
26227
  let columnsCount = 0;
25421
26228
  let indexesCount = 0;
25422
26229
  let foreignKeysCount = 0;
@@ -25428,8 +26235,9 @@ var init_pgSerializer = __esm({
25428
26235
  const columnToReturn = {};
25429
26236
  const indexToReturn = {};
25430
26237
  const foreignKeysToReturn = {};
26238
+ const primaryKeys = {};
25431
26239
  const tableResponse = await db.query(
25432
- `SELECT a.attrelid::regclass::text, a.attname, is_nullable
26240
+ `SELECT a.attrelid::regclass::text, a.attname, is_nullable, a.attndims as array_dimensions
25433
26241
  , CASE WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[])
25434
26242
  AND EXISTS (
25435
26243
  SELECT FROM pg_attrdef ad
@@ -25447,7 +26255,7 @@ var init_pgSerializer = __esm({
25447
26255
  WHEN 'int2'::regtype THEN 'smallserial'
25448
26256
  END
25449
26257
  ELSE format_type(a.atttypid, a.atttypmod)
25450
- END AS data_type, INFORMATION_SCHEMA.COLUMNS.table_name, INFORMATION_SCHEMA.COLUMNS.column_name, INFORMATION_SCHEMA.COLUMNS.column_default
26258
+ END AS data_type, INFORMATION_SCHEMA.COLUMNS.table_name, INFORMATION_SCHEMA.COLUMNS.column_name, INFORMATION_SCHEMA.COLUMNS.column_default, INFORMATION_SCHEMA.COLUMNS.data_type as additional_dt
25451
26259
  FROM pg_attribute a
25452
26260
  JOIN INFORMATION_SCHEMA.COLUMNS ON INFORMATION_SCHEMA.COLUMNS.column_name = a.attname
25453
26261
  WHERE a.attrelid = '"${tableName}"'::regclass and INFORMATION_SCHEMA.COLUMNS.table_name = '${tableName}'
@@ -25464,7 +26272,9 @@ var init_pgSerializer = __esm({
25464
26272
  WHERE tc.table_name = '${tableName}';`
25465
26273
  );
25466
26274
  columnsCount += tableResponse.rows.length;
25467
- progressCallback("columns", columnsCount, "fetching");
26275
+ if (progressCallback) {
26276
+ progressCallback("columns", columnsCount, "fetching");
26277
+ }
25468
26278
  const tableForeignKeys = await db.query(
25469
26279
  `SELECT
25470
26280
  tc.table_schema,
@@ -25488,7 +26298,9 @@ var init_pgSerializer = __esm({
25488
26298
  WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='${tableName}';`
25489
26299
  );
25490
26300
  foreignKeysCount += tableForeignKeys.rows.length;
25491
- progressCallback("fks", foreignKeysCount, "fetching");
26301
+ if (progressCallback) {
26302
+ progressCallback("fks", foreignKeysCount, "fetching");
26303
+ }
25492
26304
  for (const fk4 of tableForeignKeys.rows) {
25493
26305
  const columnFrom = fk4.column_name;
25494
26306
  const tableTo = fk4.foreign_table_name;
@@ -25519,19 +26331,49 @@ var init_pgSerializer = __esm({
25519
26331
  }
25520
26332
  for (const columnResponse of tableResponse.rows) {
25521
26333
  const columnName = columnResponse.attname;
25522
- const columnType = columnResponse.data_type;
26334
+ const columnAdditionalDT = columnResponse.additional_dt;
26335
+ const columnDimensions = columnResponse.array_dimensions;
26336
+ let columnType = columnResponse.data_type;
25523
26337
  const primaryKey = tableConstraints.rows.filter(
25524
- (mapRow) => columnName === mapRow.column_name && mapRow.constraint_type === "PRIMARY KEY"
26338
+ (mapRow) => mapRow.constraint_type === "PRIMARY KEY"
26339
+ );
26340
+ const cprimaryKey = tableConstraints.rows.filter(
26341
+ (mapRow) => mapRow.constraint_type === "PRIMARY KEY"
25525
26342
  );
26343
+ if (cprimaryKey.length > 1) {
26344
+ const tableCompositePkName = await db.query(
26345
+ `SELECT conname AS primary_key
26346
+ FROM pg_constraint
26347
+ WHERE contype = 'p'
26348
+ AND connamespace = 'public'::regnamespace
26349
+ AND conrelid::regclass::text = $1;`,
26350
+ [tableName]
26351
+ );
26352
+ primaryKeys[`${tableName}_${cprimaryKey.map((pk) => pk.column_name).join("_")}`] = {
26353
+ name: tableCompositePkName.rows[0].primary_key,
26354
+ columns: cprimaryKey.map((c) => c.column_name)
26355
+ };
26356
+ }
25526
26357
  const uniqueKey = tableConstraints.rows.filter(
25527
26358
  (mapRow) => columnName === mapRow.column_name && mapRow.constraint_type === "UNIQUE"
25528
26359
  );
25529
26360
  const defaultValue = defaultForColumn(columnResponse);
25530
26361
  const isSerial = columnType === "serial";
26362
+ let columnTypeMapped = columnType;
26363
+ if (columnTypeMapped.startsWith("numeric(")) {
26364
+ columnTypeMapped = columnTypeMapped.replace(",", ", ");
26365
+ }
26366
+ if (columnAdditionalDT === "ARRAY") {
26367
+ for (let i = 1; i < Number(columnDimensions); i++) {
26368
+ columnTypeMapped += "[]";
26369
+ }
26370
+ }
26371
+ columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
26372
+ columnTypeMapped = trimChar(columnTypeMapped, '"');
25531
26373
  columnToReturn[columnName] = {
25532
26374
  name: columnName,
25533
- type: columnType.replace("character varying", "varchar").trimChar('"'),
25534
- primaryKey: !!primaryKey[0],
26375
+ type: columnTypeMapped,
26376
+ primaryKey: primaryKey.length === 1 && cprimaryKey.length < 1,
25535
26377
  notNull: columnResponse.is_nullable === "NO"
25536
26378
  };
25537
26379
  if (!isSerial && typeof defaultValue !== "undefined") {
@@ -25576,13 +26418,16 @@ var init_pgSerializer = __esm({
25576
26418
  }
25577
26419
  }
25578
26420
  indexesCount += Object.keys(indexToReturn).length;
25579
- progressCallback("indexes", indexesCount, "fetching");
26421
+ if (progressCallback) {
26422
+ progressCallback("indexes", indexesCount, "fetching");
26423
+ }
25580
26424
  result[tableName] = {
25581
26425
  name: tableName,
25582
26426
  schema: tableSchema !== "public" ? tableSchema : "",
25583
26427
  columns: columnToReturn,
25584
26428
  indexes: indexToReturn,
25585
- foreignKeys: foreignKeysToReturn
26429
+ foreignKeys: foreignKeysToReturn,
26430
+ compositePrimaryKeys: primaryKeys
25586
26431
  };
25587
26432
  } catch (e) {
25588
26433
  rej(e);
@@ -25593,9 +26438,11 @@ var init_pgSerializer = __esm({
25593
26438
  });
25594
26439
  for await (const _ of all) {
25595
26440
  }
25596
- progressCallback("columns", columnsCount, "done");
25597
- progressCallback("indexes", indexesCount, "done");
25598
- progressCallback("fks", foreignKeysCount, "done");
26441
+ if (progressCallback) {
26442
+ progressCallback("columns", columnsCount, "done");
26443
+ progressCallback("indexes", indexesCount, "done");
26444
+ progressCallback("fks", foreignKeysCount, "done");
26445
+ }
25599
26446
  const allEnums = await db.query(
25600
26447
  `select n.nspname as enum_schema,
25601
26448
  t.typname as enum_name,
@@ -25617,7 +26464,9 @@ var init_pgSerializer = __esm({
25617
26464
  };
25618
26465
  }
25619
26466
  }
25620
- progressCallback("enums", Object.keys(enumsToReturn).length, "done");
26467
+ if (progressCallback) {
26468
+ progressCallback("enums", Object.keys(enumsToReturn).length, "done");
26469
+ }
25621
26470
  const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it]));
25622
26471
  return {
25623
26472
  version: "5",
@@ -25632,12 +26481,47 @@ var init_pgSerializer = __esm({
25632
26481
  }
25633
26482
  };
25634
26483
  };
26484
+ columnToDefault = {
26485
+ "numeric(": "::numeric",
26486
+ "time without time zone": "::time without time zone",
26487
+ "timestamp without time zone": "::timestamp without time zone",
26488
+ "character(": "::bpchar"
26489
+ };
25635
26490
  defaultForColumn = (column6) => {
25636
26491
  if (column6.data_type === "serial" || column6.data_type === "smallserial" || column6.data_type === "bigserial") {
25637
26492
  return void 0;
25638
26493
  }
25639
- const defaultValue = column6.column_default === null ? void 0 : column6.column_default;
25640
- return defaultValue;
26494
+ const hasDifferentDefaultCast = Object.keys(columnToDefault).find(
26495
+ (it) => column6.data_type.startsWith(it)
26496
+ );
26497
+ if (column6.column_default === null) {
26498
+ return void 0;
26499
+ }
26500
+ const columnDefaultAsString = column6.column_default.toString();
26501
+ if (columnDefaultAsString.endsWith(
26502
+ hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : column6.data_type
26503
+ )) {
26504
+ const nonPrefixPart = column6.column_default.length - (hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : `::${column6.data_type}`).length - 1;
26505
+ const rt = column6.column_default.toString().substring(1, nonPrefixPart);
26506
+ if (/^-?[\d.]+(?:e-?\d+)?$/.test(rt) && !column6.data_type.startsWith("numeric")) {
26507
+ return Number(rt);
26508
+ } else if (column6.data_type === "json" || column6.data_type === "jsonb") {
26509
+ const jsonWithoutSpaces = JSON.stringify(JSON.parse(rt));
26510
+ return `'${jsonWithoutSpaces}'${hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : `::${column6.data_type}`}`;
26511
+ } else if (column6.data_type === "boolean") {
26512
+ return column6.column_default === "true";
26513
+ } else {
26514
+ return `'${rt}'`;
26515
+ }
26516
+ } else {
26517
+ if (/^-?[\d.]+(?:e-?\d+)?$/.test(columnDefaultAsString) && !column6.data_type.startsWith("numeric")) {
26518
+ return Number(columnDefaultAsString);
26519
+ } else if (column6.data_type === "boolean") {
26520
+ return column6.column_default === "true";
26521
+ } else {
26522
+ return `${columnDefaultAsString}`;
26523
+ }
26524
+ }
25641
26525
  };
25642
26526
  }
25643
26527
  });
@@ -25650,6 +26534,7 @@ __export(sqliteImports_exports, {
25650
26534
  var import_sqlite_core, prepareFromSqliteImports;
25651
26535
  var init_sqliteImports = __esm({
25652
26536
  "src/serializer/sqliteImports.ts"() {
26537
+ "use strict";
25653
26538
  import_sqlite_core = require("drizzle-orm/sqlite-core");
25654
26539
  prepareFromSqliteImports = (imports) => {
25655
26540
  const tables = [];
@@ -25673,13 +26558,14 @@ var sqliteSerializer_exports = {};
25673
26558
  __export(sqliteSerializer_exports, {
25674
26559
  generateSqliteSnapshot: () => generateSqliteSnapshot
25675
26560
  });
25676
- var import_table3, import_sql3, import_sqlite_core2, import_utils9, dialect5, generateSqliteSnapshot;
26561
+ var import_table3, import_sql3, import_sqlite_core2, import_utils11, dialect5, generateSqliteSnapshot;
25677
26562
  var init_sqliteSerializer = __esm({
25678
26563
  "src/serializer/sqliteSerializer.ts"() {
26564
+ "use strict";
25679
26565
  import_table3 = require("drizzle-orm/table");
25680
26566
  import_sql3 = require("drizzle-orm/sql");
25681
26567
  import_sqlite_core2 = require("drizzle-orm/sqlite-core");
25682
- import_utils9 = require("drizzle-orm/sqlite-core/utils");
26568
+ import_utils11 = require("drizzle-orm/sqlite-core/utils");
25683
26569
  dialect5 = new import_sqlite_core2.SQLiteSyncDialect();
25684
26570
  generateSqliteSnapshot = (tables, enums) => {
25685
26571
  const result = {};
@@ -25689,7 +26575,7 @@ var init_sqliteSerializer = __esm({
25689
26575
  const indexesObject = {};
25690
26576
  const foreignKeysObject = {};
25691
26577
  const primaryKeysObject = {};
25692
- (0, import_utils9.getTableColumns)(table4).forEach((column6) => {
26578
+ (0, import_utils11.getTableColumns)(table4).forEach((column6) => {
25693
26579
  const notNull = column6.notNull;
25694
26580
  const primaryKey = column6.primary;
25695
26581
  const columnToSet = {
@@ -25716,7 +26602,7 @@ var init_sqliteSerializer = __esm({
25716
26602
  }
25717
26603
  columnsObject[column6.name] = columnToSet;
25718
26604
  });
25719
- const foreignKeys = (0, import_utils9.getTableForeignKeys)(table4).map((fk4) => {
26605
+ const foreignKeys = (0, import_utils11.getTableForeignKeys)(table4).map((fk4) => {
25720
26606
  const name = fk4.getName();
25721
26607
  const tableFrom = tableName;
25722
26608
  const onDelete = fk4.onDelete;
@@ -25739,7 +26625,7 @@ var init_sqliteSerializer = __esm({
25739
26625
  foreignKeys.forEach((it) => {
25740
26626
  foreignKeysObject[it.name] = it;
25741
26627
  });
25742
- (0, import_utils9.getTableIndexes)(table4).forEach((value) => {
26628
+ (0, import_utils11.getTableIndexes)(table4).forEach((value) => {
25743
26629
  var _a;
25744
26630
  const columns = value.config.columns;
25745
26631
  const name = value.config.name;
@@ -25763,7 +26649,7 @@ var init_sqliteSerializer = __esm({
25763
26649
  where
25764
26650
  };
25765
26651
  });
25766
- (0, import_utils9.getTableCompositePrimaryKeys)(table4).forEach((it) => {
26652
+ (0, import_utils11.getTableCompositePrimaryKeys)(table4).forEach((it) => {
25767
26653
  primaryKeysObject[it.getName()] = {
25768
26654
  columns: it.columns.map((it2) => it2.name)
25769
26655
  };
@@ -25791,10 +26677,11 @@ var init_sqliteSerializer = __esm({
25791
26677
  });
25792
26678
 
25793
26679
  // src/serializer/index.ts
25794
- var import_fs3, import_node, import_path3, import_glob, safeRegister, serializeMySql, serializePg, serializeSQLite, prepareFilenames;
26680
+ var import_fs5, import_node, import_path3, import_glob, safeRegister, serializeMySql, serializePg, serializeSQLite, prepareFilenames;
25795
26681
  var init_serializer = __esm({
25796
26682
  "src/serializer/index.ts"() {
25797
- import_fs3 = __toESM(require("fs"));
26683
+ "use strict";
26684
+ import_fs5 = __toESM(require("fs"));
25798
26685
  import_node = __toESM(require_node2());
25799
26686
  import_path3 = __toESM(require("path"));
25800
26687
  import_glob = __toESM(require_glob());
@@ -25810,8 +26697,8 @@ var init_serializer = __esm({
25810
26697
  } };
25811
26698
  }
25812
26699
  };
25813
- serializeMySql = (path4) => {
25814
- const filenames = prepareFilenames(path4);
26700
+ serializeMySql = (path2) => {
26701
+ const filenames = prepareFilenames(path2);
25815
26702
  const { unregister } = safeRegister();
25816
26703
  const { prepareFromMySqlImports: prepareFromMySqlImports2 } = (init_mysqlImports(), __toCommonJS(mysqlImports_exports));
25817
26704
  const { generateMySqlSnapshot: generateMySqlSnapshot2 } = (init_mysqlSerializer(), __toCommonJS(mysqlSerializer_exports));
@@ -25819,8 +26706,8 @@ var init_serializer = __esm({
25819
26706
  unregister();
25820
26707
  return generateMySqlSnapshot2(tables, enums, schemas);
25821
26708
  };
25822
- serializePg = (path4) => {
25823
- const filenames = prepareFilenames(path4);
26709
+ serializePg = (path2) => {
26710
+ const filenames = prepareFilenames(path2);
25824
26711
  const { unregister } = safeRegister();
25825
26712
  const { prepareFromPgImports: prepareFromPgImports2 } = (init_pgImports(), __toCommonJS(pgImports_exports));
25826
26713
  const { generatePgSnapshot: generatePgSnapshot2 } = (init_pgSerializer(), __toCommonJS(pgSerializer_exports));
@@ -25828,8 +26715,8 @@ var init_serializer = __esm({
25828
26715
  unregister();
25829
26716
  return generatePgSnapshot2(tables, enums, schemas);
25830
26717
  };
25831
- serializeSQLite = (path4) => {
25832
- const filenames = prepareFilenames(path4);
26718
+ serializeSQLite = (path2) => {
26719
+ const filenames = prepareFilenames(path2);
25833
26720
  const { unregister } = safeRegister();
25834
26721
  const { prepareFromSqliteImports: prepareFromSqliteImports2 } = (init_sqliteImports(), __toCommonJS(sqliteImports_exports));
25835
26722
  const { generateSqliteSnapshot: generateSqliteSnapshot2 } = (init_sqliteSerializer(), __toCommonJS(sqliteSerializer_exports));
@@ -25837,16 +26724,16 @@ var init_serializer = __esm({
25837
26724
  unregister();
25838
26725
  return generateSqliteSnapshot2(tables, enums);
25839
26726
  };
25840
- prepareFilenames = (path4) => {
25841
- if (typeof path4 === "string") {
25842
- path4 = [path4];
26727
+ prepareFilenames = (path2) => {
26728
+ if (typeof path2 === "string") {
26729
+ path2 = [path2];
25843
26730
  }
25844
- const result = path4.reduce((result2, cur) => {
26731
+ const result = path2.reduce((result2, cur) => {
25845
26732
  const globbed = import_glob.default.sync(cur);
25846
26733
  globbed.forEach((it) => {
25847
- const fileName = import_fs3.default.lstatSync(it).isDirectory() ? null : import_path3.default.resolve(it);
25848
- const filenames = fileName ? [fileName] : import_fs3.default.readdirSync(it).map((file) => import_path3.default.join(import_path3.default.resolve(it), file));
25849
- filenames.filter((file) => !import_fs3.default.lstatSync(file).isDirectory()).forEach((file) => result2.add(file));
26734
+ const fileName = import_fs5.default.lstatSync(it).isDirectory() ? null : import_path3.default.resolve(it);
26735
+ const filenames = fileName ? [fileName] : import_fs5.default.readdirSync(it).map((file) => import_path3.default.join(import_path3.default.resolve(it), file));
26736
+ filenames.filter((file) => !import_fs5.default.lstatSync(file).isDirectory()).forEach((file) => result2.add(file));
25850
26737
  });
25851
26738
  return result2;
25852
26739
  }, /* @__PURE__ */ new Set());
@@ -25856,11 +26743,12 @@ var init_serializer = __esm({
25856
26743
  });
25857
26744
 
25858
26745
  // src/migrationPreparator.ts
25859
- var import_fs4, import_crypto, prepareMySqlMigrationSnapshot, prepareSqliteMigrationSnapshot, preparePgMigrationSnapshot, preparePrevSnapshot;
26746
+ var import_fs6, import_crypto2, prepareMySqlMigrationSnapshot, prepareSqliteMigrationSnapshot, preparePgMigrationSnapshot, preparePrevSnapshot;
25860
26747
  var init_migrationPreparator = __esm({
25861
26748
  "src/migrationPreparator.ts"() {
25862
- import_fs4 = __toESM(require("fs"));
25863
- import_crypto = require("crypto");
26749
+ "use strict";
26750
+ import_fs6 = __toESM(require("fs"));
26751
+ import_crypto2 = require("crypto");
25864
26752
  init_serializer();
25865
26753
  init_pgSchema();
25866
26754
  init_sqliteSchema();
@@ -25870,7 +26758,7 @@ var init_migrationPreparator = __esm({
25870
26758
  preparePrevSnapshot(migrationFolders, dryMySql)
25871
26759
  );
25872
26760
  const serialized = serializeMySql(schemaPath);
25873
- const id = (0, import_crypto.randomUUID)();
26761
+ const id = (0, import_crypto2.randomUUID)();
25874
26762
  const idPrev = prevSnapshot.id;
25875
26763
  const { version, dialect: dialect6, ...rest } = serialized;
25876
26764
  const result = { version, dialect: dialect6, id, prevId: idPrev, ...rest };
@@ -25881,7 +26769,7 @@ var init_migrationPreparator = __esm({
25881
26769
  preparePrevSnapshot(snapshots, drySQLite)
25882
26770
  );
25883
26771
  const serialized = serializeSQLite(schemaPath);
25884
- const id = (0, import_crypto.randomUUID)();
26772
+ const id = (0, import_crypto2.randomUUID)();
25885
26773
  const idPrev = prevSnapshot.id;
25886
26774
  const { version, dialect: dialect6, ...rest } = serialized;
25887
26775
  const result = {
@@ -25896,7 +26784,7 @@ var init_migrationPreparator = __esm({
25896
26784
  preparePgMigrationSnapshot = (snapshots, schemaPath) => {
25897
26785
  const prevSnapshot = pgSchema.parse(preparePrevSnapshot(snapshots, dryPg));
25898
26786
  const serialized = serializePg(schemaPath);
25899
- const id = (0, import_crypto.randomUUID)();
26787
+ const id = (0, import_crypto2.randomUUID)();
25900
26788
  const idPrev = prevSnapshot.id;
25901
26789
  const { version, dialect: dialect6, ...rest } = serialized;
25902
26790
  const result = { version, dialect: dialect6, id, prevId: idPrev, ...rest };
@@ -25908,7 +26796,7 @@ var init_migrationPreparator = __esm({
25908
26796
  prevSnapshot = defaultPrev;
25909
26797
  } else {
25910
26798
  const lastSnapshot = snapshots[snapshots.length - 1];
25911
- prevSnapshot = JSON.parse(import_fs4.default.readFileSync(lastSnapshot).toString());
26799
+ prevSnapshot = JSON.parse(import_fs6.default.readFileSync(lastSnapshot).toString());
25912
26800
  }
25913
26801
  return prevSnapshot;
25914
26802
  };
@@ -25925,10 +26813,11 @@ __export(migrate_exports, {
25925
26813
  prepareSnapshotFolderName: () => prepareSnapshotFolderName,
25926
26814
  writeResult: () => writeResult
25927
26815
  });
25928
- var import_fs5, import_path4, import_hanji2, prepareAndMigratePg, prepareAndMigrateMySql, prepareAndMigrateSqlite, prepareSQL, promptColumnsConflicts, promptTablesConflict, promptSchemasConflict, writeResult, prepareSnapshotFolderName, two;
26816
+ var import_fs7, import_path4, import_hanji2, prepareAndMigratePg, prepareAndMigrateMySql, prepareAndMigrateSqlite, prepareSQL, promptColumnsConflicts, promptTablesConflict, promptSchemasConflict, writeResult, prepareSnapshotFolderName, two;
25929
26817
  var init_migrate = __esm({
25930
26818
  "src/cli/commands/migrate.ts"() {
25931
- import_fs5 = __toESM(require("fs"));
26819
+ "use strict";
26820
+ import_fs7 = __toESM(require("fs"));
25932
26821
  init_migrationPreparator();
25933
26822
  init_snapshotsDiffer();
25934
26823
  import_path4 = __toESM(require("path"));
@@ -25954,7 +26843,9 @@ var init_migrate = __esm({
25954
26843
  const { sqlStatements, _meta } = await prepareSQL(
25955
26844
  squashedPrev,
25956
26845
  squashedCur,
25957
- "pg"
26846
+ "pg",
26847
+ validatedPrev,
26848
+ validatedCur
25958
26849
  );
25959
26850
  writeResult(
25960
26851
  cur,
@@ -25982,7 +26873,9 @@ var init_migrate = __esm({
25982
26873
  const { sqlStatements, _meta } = await prepareSQL(
25983
26874
  squashedPrev,
25984
26875
  squashedCur,
25985
- "mysql"
26876
+ "mysql",
26877
+ validatedPrev,
26878
+ validatedCur
25986
26879
  );
25987
26880
  writeResult(
25988
26881
  cur,
@@ -26010,7 +26903,7 @@ var init_migrate = __esm({
26010
26903
  const { sqlStatements, _meta } = await prepareSQL(
26011
26904
  squashedPrev,
26012
26905
  squashedCur,
26013
- "mysql"
26906
+ "sqlite"
26014
26907
  );
26015
26908
  writeResult(
26016
26909
  cur,
@@ -26024,7 +26917,7 @@ var init_migrate = __esm({
26024
26917
  console.error(e);
26025
26918
  }
26026
26919
  };
26027
- prepareSQL = async (prev, cur, dialect6) => {
26920
+ prepareSQL = async (prev, cur, dialect6, prevFull, curFull) => {
26028
26921
  const schemasResolver = async (input) => {
26029
26922
  try {
26030
26923
  const { created, deleted, renamed } = await promptSchemasConflict(
@@ -26069,7 +26962,9 @@ var init_migrate = __esm({
26069
26962
  dialect6,
26070
26963
  schemasResolver,
26071
26964
  tablesResolver,
26072
- columnsResolver
26965
+ columnsResolver,
26966
+ prevFull,
26967
+ curFull
26073
26968
  );
26074
26969
  };
26075
26970
  promptColumnsConflicts = async (tableName, newColumns, missingColumns) => {
@@ -26205,19 +27100,19 @@ var init_migrate = __esm({
26205
27100
  return result;
26206
27101
  };
26207
27102
  writeResult = (cur, sqlStatements, journal, _meta, outFolder, breakpoints) => {
26208
- var _a, _b;
26209
27103
  console.log(schema(cur));
26210
27104
  if (sqlStatements.length === 0) {
26211
27105
  console.log("No schema changes, nothing to migrate \u{1F634}");
26212
27106
  return;
26213
27107
  }
26214
- const idx = (_b = (_a = journal.entries[journal.entries.length - 1]) == null ? void 0 : _a.idx) != null ? _b : 0;
27108
+ const lastEntryInJournal = journal.entries[journal.entries.length - 1];
27109
+ const idx = typeof lastEntryInJournal === "undefined" ? 0 : lastEntryInJournal.idx + 1;
26215
27110
  const { prefix, tag } = prepareMigrationMetadata(idx);
26216
27111
  const toSave = JSON.parse(JSON.stringify(cur));
26217
27112
  toSave["_meta"] = _meta;
26218
27113
  const metaFolderPath = (0, import_path4.join)(outFolder, "meta");
26219
27114
  const metaJournal = (0, import_path4.join)(metaFolderPath, "_journal.json");
26220
- import_fs5.default.writeFileSync(
27115
+ import_fs7.default.writeFileSync(
26221
27116
  (0, import_path4.join)(metaFolderPath, `${prefix}_snapshot.json`),
26222
27117
  JSON.stringify(toSave, null, 2)
26223
27118
  );
@@ -26225,12 +27120,13 @@ var init_migrate = __esm({
26225
27120
  const sql = sqlStatements.join(sqlDelimiter);
26226
27121
  journal.entries.push({
26227
27122
  idx,
27123
+ version: cur.version,
26228
27124
  when: +new Date(),
26229
27125
  tag,
26230
27126
  breakpoints
26231
27127
  });
26232
- import_fs5.default.writeFileSync(metaJournal, JSON.stringify(journal, null, 2));
26233
- import_fs5.default.writeFileSync(`${outFolder}/${tag}.sql`, sql);
27128
+ import_fs7.default.writeFileSync(metaJournal, JSON.stringify(journal, null, 2));
27129
+ import_fs7.default.writeFileSync(`${outFolder}/${tag}.sql`, sql);
26234
27130
  (0, import_hanji2.render)(
26235
27131
  `[${source_default.green(
26236
27132
  "\u2713"
@@ -26343,6 +27239,7 @@ var init_camelcase = __esm({
26343
27239
  // src/@types/utils.ts
26344
27240
  var init_utils2 = __esm({
26345
27241
  "src/@types/utils.ts"() {
27242
+ "use strict";
26346
27243
  init_camelcase();
26347
27244
  String.prototype.trimChar = function(char) {
26348
27245
  let start = 0;
@@ -27754,7 +28651,7 @@ var require_split2 = __commonJS({
27754
28651
  var require_helper = __commonJS({
27755
28652
  "node_modules/.pnpm/pgpass@1.0.5/node_modules/pgpass/lib/helper.js"(exports, module2) {
27756
28653
  "use strict";
27757
- var path4 = require("path");
28654
+ var path2 = require("path");
27758
28655
  var Stream = require("stream").Stream;
27759
28656
  var split = require_split2();
27760
28657
  var util2 = require("util");
@@ -27793,7 +28690,7 @@ var require_helper = __commonJS({
27793
28690
  };
27794
28691
  module2.exports.getFileName = function(rawEnv) {
27795
28692
  var env2 = rawEnv || process.env;
27796
- var file = env2.PGPASSFILE || (isWin ? path4.join(env2.APPDATA || "./", "postgresql", "pgpass.conf") : path4.join(env2.HOME || "./", ".pgpass"));
28693
+ var file = env2.PGPASSFILE || (isWin ? path2.join(env2.APPDATA || "./", "postgresql", "pgpass.conf") : path2.join(env2.HOME || "./", ".pgpass"));
27797
28694
  return file;
27798
28695
  };
27799
28696
  module2.exports.usePgPass = function(stats, fname) {
@@ -27920,7 +28817,7 @@ var require_helper = __commonJS({
27920
28817
  var require_lib2 = __commonJS({
27921
28818
  "node_modules/.pnpm/pgpass@1.0.5/node_modules/pgpass/lib/index.js"(exports, module2) {
27922
28819
  "use strict";
27923
- var path4 = require("path");
28820
+ var path2 = require("path");
27924
28821
  var fs7 = require("fs");
27925
28822
  var helper = require_helper();
27926
28823
  module2.exports = function(connInfo, cb) {
@@ -30743,9 +31640,10 @@ var require_lib3 = __commonJS({
30743
31640
  });
30744
31641
 
30745
31642
  // src/introspect.ts
30746
- var pgImportsList, objToStatement, objToStatement2, timeConfig, importsPatch, relations, schemaToTypeScript, isCyclic, isSelf, column4, createTableColumns, createTableIndexes, createTableFKs;
31643
+ var pgImportsList, objToStatement2, timeConfig, possibleIntervals, intervalStrToObj, intervalConfig, importsPatch, relations, schemaToTypeScript, isCyclic, isSelf, column4, dimensionsInArray, createTableColumns, createTableIndexes, createTablePKs, createTableFKs;
30747
31644
  var init_introspect = __esm({
30748
31645
  "src/introspect.ts"() {
31646
+ "use strict";
30749
31647
  init_utils2();
30750
31648
  init_pgSerializer();
30751
31649
  pgImportsList = /* @__PURE__ */ new Set([
@@ -30757,7 +31655,9 @@ var init_introspect = __esm({
30757
31655
  "boolean",
30758
31656
  "text",
30759
31657
  "varchar",
31658
+ "char",
30760
31659
  "serial",
31660
+ "smallserial",
30761
31661
  "bigserial",
30762
31662
  "decimal",
30763
31663
  "numeric",
@@ -30768,33 +31668,75 @@ var init_introspect = __esm({
30768
31668
  "timestamp",
30769
31669
  "date",
30770
31670
  "interval",
31671
+ "cidr",
31672
+ "inet",
31673
+ "macaddr",
31674
+ "macaddr8",
30771
31675
  "bigint",
30772
- "bigserial",
30773
31676
  "doublePrecision",
30774
31677
  "uuid"
30775
31678
  ]);
30776
- objToStatement = (json) => {
31679
+ objToStatement2 = (json) => {
30777
31680
  json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
30778
31681
  const keys = Object.keys(json);
30779
31682
  if (keys.length === 0)
30780
31683
  return;
30781
31684
  let statement = "{ ";
30782
- statement += keys.map((it) => `"${it}": "${json[it]}"`).join(", ");
31685
+ statement += keys.map((it) => `${it}: "${json[it]}"`).join(", ");
30783
31686
  statement += " }";
30784
31687
  return statement;
30785
31688
  };
30786
- objToStatement2 = (json) => {
31689
+ timeConfig = (json) => {
30787
31690
  json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
30788
31691
  const keys = Object.keys(json);
30789
31692
  if (keys.length === 0)
30790
31693
  return;
30791
31694
  let statement = "{ ";
30792
- statement += keys.map((it) => `${it}: "${json[it]}"`).join(", ");
31695
+ statement += keys.map((it) => `${it}: ${json[it]}`).join(", ");
30793
31696
  statement += " }";
30794
31697
  return statement;
30795
31698
  };
30796
- timeConfig = (json) => {
30797
- json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
31699
+ possibleIntervals = [
31700
+ "year",
31701
+ "month",
31702
+ "day",
31703
+ "hour",
31704
+ "minute",
31705
+ "second",
31706
+ "year to month",
31707
+ "day to hour",
31708
+ "day to minute",
31709
+ "day to second",
31710
+ "hour to minute",
31711
+ "hour to second",
31712
+ "minute to second"
31713
+ ];
31714
+ intervalStrToObj = (str) => {
31715
+ if (str.startsWith("interval(")) {
31716
+ return {
31717
+ precision: Number(str.substring("interval(".length, str.length - 1))
31718
+ };
31719
+ }
31720
+ const splitted = str.split(" ");
31721
+ if (splitted.length === 1) {
31722
+ return {};
31723
+ }
31724
+ const rest = splitted.slice(1, splitted.length).join(" ");
31725
+ if (possibleIntervals.includes(rest)) {
31726
+ return { fields: `"${rest}"` };
31727
+ }
31728
+ for (const s of possibleIntervals) {
31729
+ if (rest.startsWith(`${s}(`)) {
31730
+ return {
31731
+ fields: `"${s}"`,
31732
+ precision: Number(rest.substring(s.length + 1, rest.length - 1))
31733
+ };
31734
+ }
31735
+ }
31736
+ return {};
31737
+ };
31738
+ intervalConfig = (str) => {
31739
+ let json = intervalStrToObj(str);
30798
31740
  const keys = Object.keys(json);
30799
31741
  if (keys.length === 0)
30800
31742
  return;
@@ -30805,7 +31747,10 @@ var init_introspect = __esm({
30805
31747
  };
30806
31748
  importsPatch = {
30807
31749
  "double precision": "doublePrecision",
30808
- "timestamp without time zone": "timestamp"
31750
+ "timestamp without time zone": "timestamp",
31751
+ "timestamp with time zone": "timestamp",
31752
+ "time without time zone": "time",
31753
+ "time with time zone": "time"
30809
31754
  };
30810
31755
  relations = /* @__PURE__ */ new Set();
30811
31756
  schemaToTypeScript = (schema4) => {
@@ -30827,13 +31772,20 @@ var init_introspect = __esm({
30827
31772
  (idx) => idx.isUnique ? "uniqueIndex" : "index"
30828
31773
  );
30829
31774
  const fkImpots = Object.values(it.foreignKeys).map((it2) => "foreignKey");
31775
+ const pkImports = Object.values(it.compositePrimaryKeys).map(
31776
+ (it2) => "primaryKey"
31777
+ );
30830
31778
  res.pg.push(...idxImports);
30831
31779
  res.pg.push(...fkImpots);
31780
+ res.pg.push(...pkImports);
30832
31781
  const columnImports = Object.values(it.columns).map((col) => {
30833
31782
  var _a;
30834
31783
  let patched = (_a = importsPatch[col.type]) != null ? _a : col.type;
30835
31784
  patched = patched.startsWith("varchar(") ? "varchar" : patched;
31785
+ patched = patched.startsWith("char(") ? "char" : patched;
30836
31786
  patched = patched.startsWith("numeric(") ? "numeric" : patched;
31787
+ patched = patched.startsWith("time(") ? "time" : patched;
31788
+ patched = patched.startsWith("timestamp(") ? "timestamp" : patched;
30837
31789
  return patched;
30838
31790
  }).filter((type) => {
30839
31791
  return pgImportsList.has(type);
@@ -30866,12 +31818,13 @@ var init_introspect = __esm({
30866
31818
  const filteredFKs = Object.values(table4.foreignKeys).filter((it) => {
30867
31819
  return it.columnsFrom.length > 1 || isSelf(it);
30868
31820
  });
30869
- if (Object.keys(table4.indexes).length > 0 || filteredFKs.length > 0) {
31821
+ if (Object.keys(table4.indexes).length > 0 || filteredFKs.length > 0 || Object.keys(table4.compositePrimaryKeys).length > 0) {
30870
31822
  statement += ",\n";
30871
31823
  statement += "(table) => {\n";
30872
31824
  statement += " return {\n";
30873
31825
  statement += createTableIndexes(table4.name, Object.values(table4.indexes));
30874
31826
  statement += createTableFKs(Object.values(filteredFKs));
31827
+ statement += createTablePKs(Object.values(table4.compositePrimaryKeys));
30875
31828
  statement += " }\n";
30876
31829
  statement += "}";
30877
31830
  }
@@ -30908,43 +31861,48 @@ var init_introspect = __esm({
30908
31861
  };
30909
31862
  column4 = (type, name, enumTypes, defaultValue) => {
30910
31863
  const lowered = type.toLowerCase();
30911
- if (lowered === "serial") {
31864
+ if (lowered.startsWith("serial")) {
30912
31865
  return `${name.camelCase()}: serial("${name}")`;
30913
31866
  }
30914
- if (lowered === "bigserial") {
31867
+ if (lowered.startsWith("smallserial")) {
31868
+ return `${name.camelCase()}: smallserial("${name}")`;
31869
+ }
31870
+ if (lowered.startsWith("bigserial")) {
30915
31871
  return `${name.camelCase()}: bigserial("${name}", { mode: "bigint" })`;
30916
31872
  }
30917
- if (lowered === "integer") {
31873
+ if (lowered.startsWith("integer")) {
30918
31874
  let out = `${name.camelCase()}: integer("${name}")`;
30919
31875
  out += defaultValue ? `.default(${defaultValue})` : "";
30920
31876
  return out;
30921
31877
  }
30922
- if (lowered === "smallint") {
31878
+ if (lowered.startsWith("smallint")) {
30923
31879
  let out = `${name.camelCase()}: smallint("${name}")`;
30924
31880
  out += defaultValue ? `.default(${defaultValue})` : "";
30925
31881
  return out;
30926
31882
  }
30927
- if (lowered === "bigint") {
30928
- let out = `${name.camelCase()}: bigint("${name}", { mode: "bigint" })`;
30929
- out += defaultValue ? `.default(BigInt(${defaultValue}))` : "";
31883
+ if (lowered.startsWith("bigint")) {
31884
+ let out = `// You can use { mode: "bigint" } if numbers are exceeding js number limitations
31885
+ `;
31886
+ out += `${name.camelCase()}: bigint("${name}", { mode: "number" })`;
31887
+ out += defaultValue ? `.default(${defaultValue})` : "";
30930
31888
  return out;
30931
31889
  }
30932
- if (lowered === "boolean") {
31890
+ if (lowered.startsWith("boolean")) {
30933
31891
  let out = `${name.camelCase()}: boolean("${name}")`;
30934
31892
  out += defaultValue ? `.default(${defaultValue})` : "";
30935
31893
  return out;
30936
31894
  }
30937
- if (lowered === "double precision") {
31895
+ if (lowered.startsWith("double precision")) {
30938
31896
  let out = `${name.camelCase()}: doublePrecision("${name}")`;
30939
31897
  out += defaultValue ? `.default(${defaultValue})` : "";
30940
31898
  return out;
30941
31899
  }
30942
- if (lowered === "real") {
31900
+ if (lowered.startsWith("real")) {
30943
31901
  let out = `${name.camelCase()}: real("${name}")`;
30944
31902
  out += defaultValue ? `.default(${defaultValue})` : "";
30945
31903
  return out;
30946
31904
  }
30947
- if (lowered === "uuid") {
31905
+ if (lowered.startsWith("uuid")) {
30948
31906
  let out = `${name.camelCase()}: uuid("${name}")`;
30949
31907
  out += defaultValue === "gen_random_uuid()" ? ".defaultRandom()" : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
30950
31908
  return out;
@@ -30956,25 +31914,31 @@ var init_introspect = __esm({
30956
31914
  params = { precision, scale };
30957
31915
  }
30958
31916
  let out = params ? `${name.camelCase()}: numeric("${name}", ${timeConfig(params)})` : `${name.camelCase()}: numeric("${name}")`;
31917
+ defaultValue = defaultValue ? defaultValue.startsWith(`'`) && defaultValue.endsWith(`'`) ? defaultValue.substring(1, defaultValue.length - 1) : defaultValue : void 0;
31918
+ out += defaultValue ? `.default('${defaultValue}')` : "";
30959
31919
  return out;
30960
31920
  }
30961
31921
  if (lowered.startsWith("timestamp")) {
30962
31922
  const withTimezone = lowered.includes("with time zone");
30963
- const split = lowered.split(" ");
30964
- let precision = split.length >= 2 ? Number(split[1].substring(1, 2)) : null;
31923
+ let precision = lowered.startsWith("timestamp(") ? Number(
31924
+ lowered.split(" ")[0].substring("timestamp(".length, lowered.split(" ")[0].length - 1)
31925
+ ) : null;
30965
31926
  precision = precision ? precision : null;
30966
- const params = timeConfig({ precision, withTimezone });
31927
+ const params = timeConfig({
31928
+ precision,
31929
+ withTimezone,
31930
+ mode: "'string'"
31931
+ });
30967
31932
  let out = params ? `${name.camelCase()}: timestamp("${name}", ${params})` : `${name.camelCase()}: timestamp("${name}")`;
30968
- defaultValue = (defaultValue == null ? void 0 : defaultValue.endsWith("::timestamp without time zone")) ? defaultValue.substring(0, defaultValue.length - 29) : defaultValue;
30969
- defaultValue = (defaultValue == null ? void 0 : defaultValue.endsWith("::timestamp with time zone")) ? defaultValue.substring(0, defaultValue.length - 26) : defaultValue;
30970
31933
  defaultValue = defaultValue === "now()" || defaultValue === "CURRENT_TIMESTAMP" ? ".defaultNow()" : defaultValue ? `.default(${defaultValue})` : "";
30971
31934
  out += defaultValue;
30972
31935
  return out;
30973
31936
  }
30974
31937
  if (lowered.startsWith("time")) {
30975
31938
  const withTimezone = lowered.includes("with time zone");
30976
- const split = lowered.split(" ");
30977
- let precision = split.length >= 2 ? Number(split[1].substring(1, 2)) : null;
31939
+ let precision = lowered.startsWith("time(") ? Number(
31940
+ lowered.split(" ")[0].substring("time(".length, lowered.split(" ")[0].length - 1)
31941
+ ) : null;
30978
31942
  precision = precision ? precision : null;
30979
31943
  const params = timeConfig({ precision, withTimezone });
30980
31944
  let out = params ? `${name.camelCase()}: time("${name}", ${params})` : `${name.camelCase()}: time("${name}")`;
@@ -30983,12 +31947,8 @@ var init_introspect = __esm({
30983
31947
  return out;
30984
31948
  }
30985
31949
  if (lowered.startsWith("interval")) {
30986
- const withTimezone = lowered.includes("with time zone");
30987
- const split = lowered.split(" ");
30988
- let precision = split.length >= 2 ? Number(split[1].substring(1, 2)) : null;
30989
- precision = precision ? precision : null;
30990
- const params = timeConfig({ precision, withTimezone });
30991
- let out = params ? `${name.camelCase()}: interval(${name}, ${params})` : `${name.camelCase()}: interval("${name}")`;
31950
+ const params = intervalConfig(lowered);
31951
+ let out = params ? `${name.camelCase()}: interval("${name}", ${params})` : `${name.camelCase()}: interval("${name}")`;
30992
31952
  out += defaultValue ? `.default(${defaultValue})` : "";
30993
31953
  return out;
30994
31954
  }
@@ -30998,7 +31958,7 @@ var init_introspect = __esm({
30998
31958
  out += defaultValue;
30999
31959
  return out;
31000
31960
  }
31001
- if (lowered === "text") {
31961
+ if (lowered.startsWith("text")) {
31002
31962
  let out = `${name.camelCase()}: text("${name}")`;
31003
31963
  out += defaultValue ? `.default(${defaultValue})` : "";
31004
31964
  return out;
@@ -31006,37 +31966,83 @@ var init_introspect = __esm({
31006
31966
  if (lowered === "json") {
31007
31967
  let out = `${name.camelCase()}: json("${name}")`;
31008
31968
  defaultValue = (defaultValue == null ? void 0 : defaultValue.endsWith("::json")) ? defaultValue.substring(1, defaultValue.length - 7) : defaultValue;
31009
- const def = defaultValue ? objToStatement(JSON.parse(defaultValue)) : null;
31969
+ const def = defaultValue ? defaultValue : null;
31010
31970
  out += defaultValue ? `.default(${def})` : "";
31011
31971
  return out;
31012
31972
  }
31013
31973
  if (lowered === "jsonb") {
31014
31974
  let out = `${name.camelCase()}: jsonb("${name}")`;
31015
31975
  defaultValue = (defaultValue == null ? void 0 : defaultValue.endsWith("::jsonb")) ? defaultValue.substring(1, defaultValue.length - 8) : defaultValue;
31016
- const def = defaultValue ? objToStatement(JSON.parse(defaultValue)) : null;
31976
+ const def = defaultValue ? defaultValue : null;
31017
31977
  out += defaultValue ? `.default(${def})` : "";
31018
31978
  return out;
31019
31979
  }
31980
+ if (lowered.startsWith("inet")) {
31981
+ let out = `${name.camelCase()}: inet("${name}")`;
31982
+ out += defaultValue ? `.default(${defaultValue})` : "";
31983
+ return out;
31984
+ }
31985
+ if (lowered.startsWith("cidr")) {
31986
+ let out = `${name.camelCase()}: cidr("${name}")`;
31987
+ out += defaultValue ? `.default(${defaultValue})` : "";
31988
+ return out;
31989
+ }
31990
+ if (lowered.startsWith("macaddr")) {
31991
+ let out = `${name.camelCase()}: macaddr("${name}")`;
31992
+ out += defaultValue ? `.default(${defaultValue})` : "";
31993
+ return out;
31994
+ }
31995
+ if (lowered.startsWith("macaddr8")) {
31996
+ let out = `${name.camelCase()}: macaddr8("${name}")`;
31997
+ out += defaultValue ? `.default(${defaultValue})` : "";
31998
+ return out;
31999
+ }
31020
32000
  if (lowered.startsWith("varchar")) {
31021
32001
  const split = lowered.split(" ");
31022
32002
  let out;
31023
- if (split[1]) {
31024
- out = `${name.camelCase()}: varchar("${name}", { size: ${split[1]} })`;
32003
+ if (lowered.length !== 7) {
32004
+ out = `${name.camelCase()}: varchar("${name}", { length: ${lowered.substring(
32005
+ 8,
32006
+ lowered.length - 1
32007
+ )} })`;
31025
32008
  } else {
31026
32009
  out = `${name.camelCase()}: varchar("${name}")`;
31027
32010
  }
31028
- defaultValue = (defaultValue == null ? void 0 : defaultValue.endsWith("::character varying")) ? defaultValue.substring(0, defaultValue.length - 19) : defaultValue;
32011
+ out += defaultValue ? `.default(${defaultValue})` : "";
32012
+ return out;
32013
+ }
32014
+ if (lowered.startsWith("char")) {
32015
+ let out;
32016
+ if (lowered.length !== 4) {
32017
+ out = `${name.camelCase()}: char("${name}", { length: ${lowered.substring(
32018
+ 5,
32019
+ lowered.length - 1
32020
+ )} })`;
32021
+ } else {
32022
+ out = `${name.camelCase()}: char("${name}")`;
32023
+ }
31029
32024
  out += defaultValue ? `.default(${defaultValue})` : "";
31030
32025
  return out;
31031
32026
  }
31032
32027
  if (enumTypes.has(type)) {
31033
- return `${name.camelCase()}: ${type.camelCase()}("${name}")`;
32028
+ let out = `${name.camelCase()}: ${type.camelCase()}("${name}")`;
32029
+ out += defaultValue ? `.default(${defaultValue})` : "";
32030
+ return out;
31034
32031
  }
31035
32032
  let unknown = `// TODO: failed to parse database type '${type}'
31036
32033
  `;
31037
32034
  unknown += ` ${name.camelCase()}: unknown("${name}")`;
31038
32035
  return unknown;
31039
32036
  };
32037
+ dimensionsInArray = (str) => {
32038
+ let res = "";
32039
+ for (let i = 0; i < str.length; i++) {
32040
+ if (str[i] === "[" && str[i + 1] === "]") {
32041
+ res += ".array()";
32042
+ }
32043
+ }
32044
+ return res;
32045
+ };
31040
32046
  createTableColumns = (columns, fks, enumTypes) => {
31041
32047
  let statement = "";
31042
32048
  const oneColumnsFKs = Object.values(fks).filter((it) => {
@@ -31052,6 +32058,7 @@ var init_introspect = __esm({
31052
32058
  const columnStatement = column4(it.type, it.name, enumTypes, it.default);
31053
32059
  statement += " ";
31054
32060
  statement += columnStatement;
32061
+ statement += dimensionsInArray(it.type);
31055
32062
  statement += it.primaryKey ? ".primaryKey()" : "";
31056
32063
  statement += it.notNull ? ".notNull()" : "";
31057
32064
  const fks2 = fkByColumnName[it.name];
@@ -31086,6 +32093,21 @@ var init_introspect = __esm({
31086
32093
  statement += `${escapedIndexName})`;
31087
32094
  statement += `.on(${it.columns.map((it2) => `table.${it2.camelCase()}`).join(", ")}),`;
31088
32095
  statement += `
32096
+ `;
32097
+ });
32098
+ return statement;
32099
+ };
32100
+ createTablePKs = (pks) => {
32101
+ let statement = "";
32102
+ pks.forEach((it) => {
32103
+ let idxKey = it.name.camelCase();
32104
+ statement += ` ${idxKey}: `;
32105
+ statement += "primaryKey(";
32106
+ statement += `${it.columns.map((c) => {
32107
+ return `table.${c.camelCase()}`;
32108
+ }).join(", ")}`;
32109
+ statement += ")";
32110
+ statement += `
31089
32111
  `;
31090
32112
  });
31091
32113
  return statement;
@@ -31122,6 +32144,7 @@ __export(pgIntrospect_exports, {
31122
32144
  var import_hanji4, import_pg, PgConfig1, PgConfig2, Conf, pgIntrospect;
31123
32145
  var init_pgIntrospect = __esm({
31124
32146
  "src/cli/commands/pgIntrospect.ts"() {
32147
+ "use strict";
31125
32148
  import_hanji4 = __toESM(require_hanji());
31126
32149
  init_lib();
31127
32150
  init_views();
@@ -43284,12 +44307,12 @@ var require_query4 = __commonJS({
43284
44307
  this._fields.push([]);
43285
44308
  return this.readField;
43286
44309
  }
43287
- _streamLocalInfile(connection, path4) {
44310
+ _streamLocalInfile(connection, path2) {
43288
44311
  if (this._streamFactory) {
43289
- this._localStream = this._streamFactory(path4);
44312
+ this._localStream = this._streamFactory(path2);
43290
44313
  } else {
43291
44314
  this._localStreamError = new Error(
43292
- `As a result of LOCAL INFILE command server wants to read ${path4} file, but as of v2.0 you must provide streamFactory option returning ReadStream.`
44315
+ `As a result of LOCAL INFILE command server wants to read ${path2} file, but as of v2.0 you must provide streamFactory option returning ReadStream.`
43293
44316
  );
43294
44317
  connection.writePacket(EmptyPacket);
43295
44318
  return this.infileOk;
@@ -44514,30 +45537,35 @@ var require_connection_config = __commonJS({
44514
45537
  }
44515
45538
  });
44516
45539
 
44517
- // node_modules/.pnpm/lru-cache@7.14.1/node_modules/lru-cache/index.js
45540
+ // node_modules/.pnpm/lru-cache@7.18.1/node_modules/lru-cache/index.js
44518
45541
  var require_lru_cache2 = __commonJS({
44519
- "node_modules/.pnpm/lru-cache@7.14.1/node_modules/lru-cache/index.js"(exports, module2) {
45542
+ "node_modules/.pnpm/lru-cache@7.18.1/node_modules/lru-cache/index.js"(exports, module2) {
44520
45543
  var perf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
44521
45544
  var hasAbortController = typeof AbortController === "function";
44522
45545
  var AC = hasAbortController ? AbortController : class AbortController {
44523
45546
  constructor() {
44524
45547
  this.signal = new AS();
44525
45548
  }
44526
- abort() {
44527
- this.signal.dispatchEvent("abort");
45549
+ abort(reason = new Error("This operation was aborted")) {
45550
+ this.signal.reason = this.signal.reason || reason;
45551
+ this.signal.aborted = true;
45552
+ this.signal.dispatchEvent({
45553
+ type: "abort",
45554
+ target: this.signal
45555
+ });
44528
45556
  }
44529
45557
  };
44530
45558
  var hasAbortSignal = typeof AbortSignal === "function";
44531
45559
  var hasACAbortSignal = typeof AC.AbortSignal === "function";
44532
45560
  var AS = hasAbortSignal ? AbortSignal : hasACAbortSignal ? AC.AbortController : class AbortSignal {
44533
45561
  constructor() {
45562
+ this.reason = void 0;
44534
45563
  this.aborted = false;
44535
45564
  this._listeners = [];
44536
45565
  }
44537
- dispatchEvent(type) {
44538
- if (type === "abort") {
45566
+ dispatchEvent(e) {
45567
+ if (e.type === "abort") {
44539
45568
  this.aborted = true;
44540
- const e = { type, target: this };
44541
45569
  this.onabort(e);
44542
45570
  this._listeners.forEach((f) => f(e), this);
44543
45571
  }
@@ -44631,7 +45659,10 @@ var require_lru_cache2 = __commonJS({
44631
45659
  fetchMethod,
44632
45660
  fetchContext,
44633
45661
  noDeleteOnFetchRejection,
44634
- noDeleteOnStaleGet
45662
+ noDeleteOnStaleGet,
45663
+ allowStaleOnFetchRejection,
45664
+ allowStaleOnFetchAbort,
45665
+ ignoreFetchAbort
44635
45666
  } = options;
44636
45667
  const { length, maxAge, stale } = options instanceof LRUCache ? {} : options;
44637
45668
  if (max !== 0 && !isPosInt(max)) {
@@ -44690,6 +45721,9 @@ var require_lru_cache2 = __commonJS({
44690
45721
  this.noDisposeOnSet = !!noDisposeOnSet;
44691
45722
  this.noUpdateTTL = !!noUpdateTTL;
44692
45723
  this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
45724
+ this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
45725
+ this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
45726
+ this.ignoreFetchAbort = !!ignoreFetchAbort;
44693
45727
  if (this.maxEntrySize !== 0) {
44694
45728
  if (this.maxSize !== 0) {
44695
45729
  if (!isPosInt(this.maxSize)) {
@@ -44766,6 +45800,14 @@ var require_lru_cache2 = __commonJS({
44766
45800
  this.updateItemAge = (index4) => {
44767
45801
  this.starts[index4] = this.ttls[index4] !== 0 ? perf.now() : 0;
44768
45802
  };
45803
+ this.statusTTL = (status, index4) => {
45804
+ if (status) {
45805
+ status.ttl = this.ttls[index4];
45806
+ status.start = this.starts[index4];
45807
+ status.now = cachedNow || getNow();
45808
+ status.remainingTTL = status.now + status.ttl - status.start;
45809
+ }
45810
+ };
44769
45811
  let cachedNow = 0;
44770
45812
  const getNow = () => {
44771
45813
  const n = perf.now();
@@ -44792,11 +45834,13 @@ var require_lru_cache2 = __commonJS({
44792
45834
  return this.ttls[index4] !== 0 && this.starts[index4] !== 0 && (cachedNow || getNow()) - this.starts[index4] > this.ttls[index4];
44793
45835
  };
44794
45836
  }
44795
- updateItemAge(index4) {
45837
+ updateItemAge(_index) {
44796
45838
  }
44797
- setItemTTL(index4, ttl, start) {
45839
+ statusTTL(_status, _index) {
44798
45840
  }
44799
- isStale(index4) {
45841
+ setItemTTL(_index, _ttl, _start) {
45842
+ }
45843
+ isStale(_index) {
44800
45844
  return false;
44801
45845
  }
44802
45846
  initializeSizeTracking() {
@@ -44823,13 +45867,13 @@ var require_lru_cache2 = __commonJS({
44823
45867
  }
44824
45868
  } else {
44825
45869
  throw new TypeError(
44826
- "invalid size value (must be positive integer)"
45870
+ "invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set."
44827
45871
  );
44828
45872
  }
44829
45873
  }
44830
45874
  return size;
44831
45875
  };
44832
- this.addItemSize = (index4, size) => {
45876
+ this.addItemSize = (index4, size, status) => {
44833
45877
  this.sizes[index4] = size;
44834
45878
  if (this.maxSize) {
44835
45879
  const maxSize = this.maxSize - this.sizes[index4];
@@ -44838,13 +45882,17 @@ var require_lru_cache2 = __commonJS({
44838
45882
  }
44839
45883
  }
44840
45884
  this.calculatedSize += this.sizes[index4];
45885
+ if (status) {
45886
+ status.entrySize = size;
45887
+ status.totalCalculatedSize = this.calculatedSize;
45888
+ }
44841
45889
  };
44842
45890
  }
44843
- removeItemSize(index4) {
45891
+ removeItemSize(_index) {
44844
45892
  }
44845
- addItemSize(index4, size) {
45893
+ addItemSize(_index, _size) {
44846
45894
  }
44847
- requireSize(k, v, size, sizeCalculation) {
45895
+ requireSize(_k, _v, size, sizeCalculation) {
44848
45896
  if (size || sizeCalculation) {
44849
45897
  throw new TypeError(
44850
45898
  "cannot set size without setting maxSize or maxEntrySize on cache"
@@ -44890,32 +45938,44 @@ var require_lru_cache2 = __commonJS({
44890
45938
  }
44891
45939
  *entries() {
44892
45940
  for (const i of this.indexes()) {
44893
- yield [this.keyList[i], this.valList[i]];
45941
+ if (!this.isBackgroundFetch(this.valList[i])) {
45942
+ yield [this.keyList[i], this.valList[i]];
45943
+ }
44894
45944
  }
44895
45945
  }
44896
45946
  *rentries() {
44897
45947
  for (const i of this.rindexes()) {
44898
- yield [this.keyList[i], this.valList[i]];
45948
+ if (!this.isBackgroundFetch(this.valList[i])) {
45949
+ yield [this.keyList[i], this.valList[i]];
45950
+ }
44899
45951
  }
44900
45952
  }
44901
45953
  *keys() {
44902
45954
  for (const i of this.indexes()) {
44903
- yield this.keyList[i];
45955
+ if (!this.isBackgroundFetch(this.valList[i])) {
45956
+ yield this.keyList[i];
45957
+ }
44904
45958
  }
44905
45959
  }
44906
45960
  *rkeys() {
44907
45961
  for (const i of this.rindexes()) {
44908
- yield this.keyList[i];
45962
+ if (!this.isBackgroundFetch(this.valList[i])) {
45963
+ yield this.keyList[i];
45964
+ }
44909
45965
  }
44910
45966
  }
44911
45967
  *values() {
44912
45968
  for (const i of this.indexes()) {
44913
- yield this.valList[i];
45969
+ if (!this.isBackgroundFetch(this.valList[i])) {
45970
+ yield this.valList[i];
45971
+ }
44914
45972
  }
44915
45973
  }
44916
45974
  *rvalues() {
44917
45975
  for (const i of this.rindexes()) {
44918
- yield this.valList[i];
45976
+ if (!this.isBackgroundFetch(this.valList[i])) {
45977
+ yield this.valList[i];
45978
+ }
44919
45979
  }
44920
45980
  }
44921
45981
  [Symbol.iterator]() {
@@ -44958,6 +46018,8 @@ var require_lru_cache2 = __commonJS({
44958
46018
  const key = this.keyList[i];
44959
46019
  const v = this.valList[i];
44960
46020
  const value = this.isBackgroundFetch(v) ? v.__staleWhileFetching : v;
46021
+ if (value === void 0)
46022
+ continue;
44961
46023
  const entry = { value };
44962
46024
  if (this.ttls) {
44963
46025
  entry.ttl = this.ttls[i];
@@ -44981,7 +46043,7 @@ var require_lru_cache2 = __commonJS({
44981
46043
  this.set(key, entry.value, entry);
44982
46044
  }
44983
46045
  }
44984
- dispose(v, k, reason) {
46046
+ dispose(_v, _k, _reason) {
44985
46047
  }
44986
46048
  set(k, v, {
44987
46049
  ttl = this.ttl,
@@ -44989,10 +46051,15 @@ var require_lru_cache2 = __commonJS({
44989
46051
  noDisposeOnSet = this.noDisposeOnSet,
44990
46052
  size = 0,
44991
46053
  sizeCalculation = this.sizeCalculation,
44992
- noUpdateTTL = this.noUpdateTTL
46054
+ noUpdateTTL = this.noUpdateTTL,
46055
+ status
44993
46056
  } = {}) {
44994
46057
  size = this.requireSize(k, v, size, sizeCalculation);
44995
46058
  if (this.maxEntrySize && size > this.maxEntrySize) {
46059
+ if (status) {
46060
+ status.set = "miss";
46061
+ status.maxEntrySizeExceeded = true;
46062
+ }
44996
46063
  this.delete(k);
44997
46064
  return this;
44998
46065
  }
@@ -45006,13 +46073,17 @@ var require_lru_cache2 = __commonJS({
45006
46073
  this.prev[index4] = this.tail;
45007
46074
  this.tail = index4;
45008
46075
  this.size++;
45009
- this.addItemSize(index4, size);
46076
+ this.addItemSize(index4, size, status);
46077
+ if (status) {
46078
+ status.set = "add";
46079
+ }
45010
46080
  noUpdateTTL = false;
45011
46081
  } else {
46082
+ this.moveToTail(index4);
45012
46083
  const oldVal = this.valList[index4];
45013
46084
  if (v !== oldVal) {
45014
46085
  if (this.isBackgroundFetch(oldVal)) {
45015
- oldVal.__abortController.abort();
46086
+ oldVal.__abortController.abort(new Error("replaced"));
45016
46087
  } else {
45017
46088
  if (!noDisposeOnSet) {
45018
46089
  this.dispose(oldVal, k, "set");
@@ -45023,9 +46094,16 @@ var require_lru_cache2 = __commonJS({
45023
46094
  }
45024
46095
  this.removeItemSize(index4);
45025
46096
  this.valList[index4] = v;
45026
- this.addItemSize(index4, size);
46097
+ this.addItemSize(index4, size, status);
46098
+ if (status) {
46099
+ status.set = "replace";
46100
+ const oldValue = oldVal && this.isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal;
46101
+ if (oldValue !== void 0)
46102
+ status.oldValue = oldValue;
46103
+ }
46104
+ } else if (status) {
46105
+ status.set = "update";
45027
46106
  }
45028
- this.moveToTail(index4);
45029
46107
  }
45030
46108
  if (ttl !== 0 && this.ttl === 0 && !this.ttls) {
45031
46109
  this.initializeTTLTracking();
@@ -45033,6 +46111,7 @@ var require_lru_cache2 = __commonJS({
45033
46111
  if (!noUpdateTTL) {
45034
46112
  this.setItemTTL(index4, ttl, start);
45035
46113
  }
46114
+ this.statusTTL(status, index4);
45036
46115
  if (this.disposeAfter) {
45037
46116
  while (this.disposed.length) {
45038
46117
  this.disposeAfter(...this.disposed.shift());
@@ -45064,7 +46143,7 @@ var require_lru_cache2 = __commonJS({
45064
46143
  const k = this.keyList[head];
45065
46144
  const v = this.valList[head];
45066
46145
  if (this.isBackgroundFetch(v)) {
45067
- v.__abortController.abort();
46146
+ v.__abortController.abort(new Error("evicted"));
45068
46147
  } else {
45069
46148
  this.dispose(v, k, "evict");
45070
46149
  if (this.disposeAfter) {
@@ -45082,15 +46161,23 @@ var require_lru_cache2 = __commonJS({
45082
46161
  this.size--;
45083
46162
  return head;
45084
46163
  }
45085
- has(k, { updateAgeOnHas = this.updateAgeOnHas } = {}) {
46164
+ has(k, { updateAgeOnHas = this.updateAgeOnHas, status } = {}) {
45086
46165
  const index4 = this.keyMap.get(k);
45087
46166
  if (index4 !== void 0) {
45088
46167
  if (!this.isStale(index4)) {
45089
46168
  if (updateAgeOnHas) {
45090
46169
  this.updateItemAge(index4);
45091
46170
  }
46171
+ if (status)
46172
+ status.has = "hit";
46173
+ this.statusTTL(status, index4);
45092
46174
  return true;
46175
+ } else if (status) {
46176
+ status.has = "stale";
46177
+ this.statusTTL(status, index4);
45093
46178
  }
46179
+ } else if (status) {
46180
+ status.has = "miss";
45094
46181
  }
45095
46182
  return false;
45096
46183
  }
@@ -45107,37 +46194,96 @@ var require_lru_cache2 = __commonJS({
45107
46194
  return v;
45108
46195
  }
45109
46196
  const ac = new AC();
46197
+ if (options.signal) {
46198
+ options.signal.addEventListener(
46199
+ "abort",
46200
+ () => ac.abort(options.signal.reason)
46201
+ );
46202
+ }
45110
46203
  const fetchOpts = {
45111
46204
  signal: ac.signal,
45112
46205
  options,
45113
46206
  context
45114
46207
  };
45115
- const cb = (v2) => {
45116
- if (!ac.signal.aborted) {
45117
- this.set(k, v2, fetchOpts.options);
46208
+ const cb = (v2, updateCache = false) => {
46209
+ const { aborted } = ac.signal;
46210
+ const ignoreAbort = options.ignoreFetchAbort && v2 !== void 0;
46211
+ if (options.status) {
46212
+ if (aborted && !updateCache) {
46213
+ options.status.fetchAborted = true;
46214
+ options.status.fetchError = ac.signal.reason;
46215
+ if (ignoreAbort)
46216
+ options.status.fetchAbortIgnored = true;
46217
+ } else {
46218
+ options.status.fetchResolved = true;
46219
+ }
46220
+ }
46221
+ if (aborted && !ignoreAbort && !updateCache) {
46222
+ return fetchFail(ac.signal.reason);
46223
+ }
46224
+ if (this.valList[index4] === p) {
46225
+ if (v2 === void 0) {
46226
+ if (p.__staleWhileFetching) {
46227
+ this.valList[index4] = p.__staleWhileFetching;
46228
+ } else {
46229
+ this.delete(k);
46230
+ }
46231
+ } else {
46232
+ if (options.status)
46233
+ options.status.fetchUpdated = true;
46234
+ this.set(k, v2, fetchOpts.options);
46235
+ }
45118
46236
  }
45119
46237
  return v2;
45120
46238
  };
45121
46239
  const eb = (er) => {
46240
+ if (options.status) {
46241
+ options.status.fetchRejected = true;
46242
+ options.status.fetchError = er;
46243
+ }
46244
+ return fetchFail(er);
46245
+ };
46246
+ const fetchFail = (er) => {
46247
+ const { aborted } = ac.signal;
46248
+ const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
46249
+ const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
46250
+ const noDelete = allowStale || options.noDeleteOnFetchRejection;
45122
46251
  if (this.valList[index4] === p) {
45123
- const del = !options.noDeleteOnFetchRejection || p.__staleWhileFetching === void 0;
46252
+ const del = !noDelete || p.__staleWhileFetching === void 0;
45124
46253
  if (del) {
45125
46254
  this.delete(k);
45126
- } else {
46255
+ } else if (!allowStaleAborted) {
45127
46256
  this.valList[index4] = p.__staleWhileFetching;
45128
46257
  }
45129
46258
  }
45130
- if (p.__returned === p) {
46259
+ if (allowStale) {
46260
+ if (options.status && p.__staleWhileFetching !== void 0) {
46261
+ options.status.returnedStale = true;
46262
+ }
46263
+ return p.__staleWhileFetching;
46264
+ } else if (p.__returned === p) {
45131
46265
  throw er;
45132
46266
  }
45133
46267
  };
45134
- const pcall = (res) => res(this.fetchMethod(k, v, fetchOpts));
46268
+ const pcall = (res, rej) => {
46269
+ this.fetchMethod(k, v, fetchOpts).then((v2) => res(v2), rej);
46270
+ ac.signal.addEventListener("abort", () => {
46271
+ if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {
46272
+ res();
46273
+ if (options.allowStaleOnFetchAbort) {
46274
+ res = (v2) => cb(v2, true);
46275
+ }
46276
+ }
46277
+ });
46278
+ };
46279
+ if (options.status)
46280
+ options.status.fetchDispatched = true;
45135
46281
  const p = new Promise(pcall).then(cb, eb);
45136
46282
  p.__abortController = ac;
45137
46283
  p.__staleWhileFetching = v;
45138
46284
  p.__returned = null;
45139
46285
  if (index4 === void 0) {
45140
- this.set(k, p, fetchOpts.options);
46286
+ this.set(k, p, { ...fetchOpts.options, status: void 0 });
45141
46287
  index4 = this.keyMap.get(k);
45142
46288
  } else {
45143
46289
  this.valList[index4] = p;
@@ -45160,14 +46306,22 @@ var require_lru_cache2 = __commonJS({
45160
46306
  sizeCalculation = this.sizeCalculation,
45161
46307
  noUpdateTTL = this.noUpdateTTL,
45162
46308
  noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,
46309
+ allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,
46310
+ ignoreFetchAbort = this.ignoreFetchAbort,
46311
+ allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,
45163
46312
  fetchContext = this.fetchContext,
45164
- forceRefresh = false
46313
+ forceRefresh = false,
46314
+ status,
46315
+ signal
45165
46316
  } = {}) {
45166
46317
  if (!this.fetchMethod) {
46318
+ if (status)
46319
+ status.fetch = "get";
45167
46320
  return this.get(k, {
45168
46321
  allowStale,
45169
46322
  updateAgeOnGet,
45170
- noDeleteOnStaleGet
46323
+ noDeleteOnStaleGet,
46324
+ status
45171
46325
  });
45172
46326
  }
45173
46327
  const options = {
@@ -45179,49 +46333,84 @@ var require_lru_cache2 = __commonJS({
45179
46333
  size,
45180
46334
  sizeCalculation,
45181
46335
  noUpdateTTL,
45182
- noDeleteOnFetchRejection
46336
+ noDeleteOnFetchRejection,
46337
+ allowStaleOnFetchRejection,
46338
+ allowStaleOnFetchAbort,
46339
+ ignoreFetchAbort,
46340
+ status,
46341
+ signal
45183
46342
  };
45184
46343
  let index4 = this.keyMap.get(k);
45185
46344
  if (index4 === void 0) {
46345
+ if (status)
46346
+ status.fetch = "miss";
45186
46347
  const p = this.backgroundFetch(k, index4, options, fetchContext);
45187
46348
  return p.__returned = p;
45188
46349
  } else {
45189
46350
  const v = this.valList[index4];
45190
46351
  if (this.isBackgroundFetch(v)) {
45191
- return allowStale && v.__staleWhileFetching !== void 0 ? v.__staleWhileFetching : v.__returned = v;
45192
- }
45193
- if (!forceRefresh && !this.isStale(index4)) {
46352
+ const stale = allowStale && v.__staleWhileFetching !== void 0;
46353
+ if (status) {
46354
+ status.fetch = "inflight";
46355
+ if (stale)
46356
+ status.returnedStale = true;
46357
+ }
46358
+ return stale ? v.__staleWhileFetching : v.__returned = v;
46359
+ }
46360
+ const isStale = this.isStale(index4);
46361
+ if (!forceRefresh && !isStale) {
46362
+ if (status)
46363
+ status.fetch = "hit";
45194
46364
  this.moveToTail(index4);
45195
46365
  if (updateAgeOnGet) {
45196
46366
  this.updateItemAge(index4);
45197
46367
  }
46368
+ this.statusTTL(status, index4);
45198
46369
  return v;
45199
46370
  }
45200
46371
  const p = this.backgroundFetch(k, index4, options, fetchContext);
45201
- return allowStale && p.__staleWhileFetching !== void 0 ? p.__staleWhileFetching : p.__returned = p;
46372
+ const hasStale = p.__staleWhileFetching !== void 0;
46373
+ const staleVal = hasStale && allowStale;
46374
+ if (status) {
46375
+ status.fetch = hasStale && isStale ? "stale" : "refresh";
46376
+ if (staleVal && isStale)
46377
+ status.returnedStale = true;
46378
+ }
46379
+ return staleVal ? p.__staleWhileFetching : p.__returned = p;
45202
46380
  }
45203
46381
  }
45204
46382
  get(k, {
45205
46383
  allowStale = this.allowStale,
45206
46384
  updateAgeOnGet = this.updateAgeOnGet,
45207
- noDeleteOnStaleGet = this.noDeleteOnStaleGet
46385
+ noDeleteOnStaleGet = this.noDeleteOnStaleGet,
46386
+ status
45208
46387
  } = {}) {
45209
46388
  const index4 = this.keyMap.get(k);
45210
46389
  if (index4 !== void 0) {
45211
46390
  const value = this.valList[index4];
45212
46391
  const fetching = this.isBackgroundFetch(value);
46392
+ this.statusTTL(status, index4);
45213
46393
  if (this.isStale(index4)) {
46394
+ if (status)
46395
+ status.get = "stale";
45214
46396
  if (!fetching) {
45215
46397
  if (!noDeleteOnStaleGet) {
45216
46398
  this.delete(k);
45217
46399
  }
46400
+ if (status)
46401
+ status.returnedStale = allowStale;
45218
46402
  return allowStale ? value : void 0;
45219
46403
  } else {
46404
+ if (status) {
46405
+ status.returnedStale = allowStale && value.__staleWhileFetching !== void 0;
46406
+ }
45220
46407
  return allowStale ? value.__staleWhileFetching : void 0;
45221
46408
  }
45222
46409
  } else {
46410
+ if (status)
46411
+ status.get = "hit";
45223
46412
  if (fetching) {
45224
- return void 0;
46413
+ return value.__staleWhileFetching;
45225
46414
  }
45226
46415
  this.moveToTail(index4);
45227
46416
  if (updateAgeOnGet) {
@@ -45229,6 +46418,8 @@ var require_lru_cache2 = __commonJS({
45229
46418
  }
45230
46419
  return value;
45231
46420
  }
46421
+ } else if (status) {
46422
+ status.get = "miss";
45232
46423
  }
45233
46424
  }
45234
46425
  connect(p, n) {
@@ -45262,7 +46453,7 @@ var require_lru_cache2 = __commonJS({
45262
46453
  this.removeItemSize(index4);
45263
46454
  const v = this.valList[index4];
45264
46455
  if (this.isBackgroundFetch(v)) {
45265
- v.__abortController.abort();
46456
+ v.__abortController.abort(new Error("deleted"));
45266
46457
  } else {
45267
46458
  this.dispose(v, k, "delete");
45268
46459
  if (this.disposeAfter) {
@@ -45296,7 +46487,7 @@ var require_lru_cache2 = __commonJS({
45296
46487
  for (const index4 of this.rindexes({ allowStale: true })) {
45297
46488
  const v = this.valList[index4];
45298
46489
  if (this.isBackgroundFetch(v)) {
45299
- v.__abortController.abort();
46490
+ v.__abortController.abort(new Error("deleted"));
45300
46491
  } else {
45301
46492
  const k = this.keyList[index4];
45302
46493
  this.dispose(v, k, "delete");
@@ -47366,9 +48557,10 @@ var require_promise2 = __commonJS({
47366
48557
  });
47367
48558
 
47368
48559
  // src/mysql-introspect.ts
47369
- var mysqlImportsList, objToStatement22, timeConfig2, binaryConfig, importsPatch2, relations2, schemaToTypeScript2, isCyclic2, isSelf2, mapColumnDefault, column5, createTableColumns2, createTableIndexes2, createTableFKs2;
48560
+ var mysqlImportsList, objToStatement22, timeConfig2, binaryConfig, importsPatch2, relations2, schemaToTypeScript2, isCyclic2, isSelf2, mapColumnDefault, mapColumnDefaultForJson, column5, createTableColumns2, createTableIndexes2, createTablePKs2, createTableFKs2;
47370
48561
  var init_mysql_introspect = __esm({
47371
48562
  "src/mysql-introspect.ts"() {
48563
+ "use strict";
47372
48564
  init_utils2();
47373
48565
  init_mysqlSerializer();
47374
48566
  mysqlImportsList = /* @__PURE__ */ new Set([
@@ -47398,7 +48590,8 @@ var init_mysql_introspect = __esm({
47398
48590
  "tinyint",
47399
48591
  "varbinary",
47400
48592
  "varchar",
47401
- "year"
48593
+ "year",
48594
+ "enum"
47402
48595
  ]);
47403
48596
  objToStatement22 = (json) => {
47404
48597
  json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
@@ -47453,8 +48646,10 @@ var init_mysql_introspect = __esm({
47453
48646
  (idx) => idx.isUnique ? "uniqueIndex" : "index"
47454
48647
  );
47455
48648
  const fkImpots = Object.values(it.foreignKeys).map((it2) => "foreignKey");
48649
+ const pkImports = Object.values(it.compositePrimaryKeys).map((it2) => "primaryKey");
47456
48650
  res.mysql.push(...idxImports);
47457
48651
  res.mysql.push(...fkImpots);
48652
+ res.mysql.push(...pkImports);
47458
48653
  const columnImports = Object.values(it.columns).map((col) => {
47459
48654
  var _a;
47460
48655
  let patched = (_a = importsPatch2[col.type]) != null ? _a : col.type;
@@ -47463,6 +48658,7 @@ var init_mysql_introspect = __esm({
47463
48658
  patched = patched.startsWith("binary(") ? "binary" : patched;
47464
48659
  patched = patched.startsWith("decimal(") ? "decimal" : patched;
47465
48660
  patched = patched.startsWith("smallint(") ? "smallint" : patched;
48661
+ patched = patched.startsWith("enum(") ? "mysqlEnum" : patched;
47466
48662
  patched = patched.startsWith("varbinary(") ? "varbinary" : patched;
47467
48663
  return patched;
47468
48664
  }).filter((type) => {
@@ -47496,12 +48692,13 @@ var init_mysql_introspect = __esm({
47496
48692
  const filteredFKs = Object.values(table4.foreignKeys).filter((it) => {
47497
48693
  return it.columnsFrom.length > 1 || isSelf2(it);
47498
48694
  });
47499
- if (Object.keys(table4.indexes).length > 0 || filteredFKs.length > 0) {
48695
+ if (Object.keys(table4.indexes).length > 0 || filteredFKs.length > 0 || Object.keys(table4.compositePrimaryKeys).length > 0) {
47500
48696
  statement += ",\n";
47501
48697
  statement += "(table) => {\n";
47502
48698
  statement += " return {\n";
47503
48699
  statement += createTableIndexes2(table4.name, Object.values(table4.indexes));
47504
48700
  statement += createTableFKs2(Object.values(filteredFKs));
48701
+ statement += createTablePKs2(Object.values(table4.compositePrimaryKeys));
47505
48702
  statement += " }\n";
47506
48703
  statement += "}";
47507
48704
  }
@@ -47539,34 +48736,45 @@ import { sql } from "drizzle-orm/sql"
47539
48736
  }
47540
48737
  return defaultValue;
47541
48738
  };
47542
- column5 = (type, name, defaultValue) => {
48739
+ mapColumnDefaultForJson = (defaultValue) => {
48740
+ if (typeof defaultValue === "string" && defaultValue.startsWith("('") && defaultValue.endsWith("')")) {
48741
+ return defaultValue.substring(2, defaultValue.length - 2);
48742
+ }
48743
+ return defaultValue;
48744
+ };
48745
+ column5 = (type, name, defaultValue, autoincrement) => {
47543
48746
  const lowered = type.toLowerCase();
47544
48747
  if (lowered === "serial") {
47545
48748
  return `${name.camelCase()}: serial("${name}")`;
47546
48749
  }
47547
48750
  if (lowered.startsWith("int")) {
47548
48751
  let out = `${name.camelCase()}: int("${name}")`;
48752
+ out += autoincrement ? `.autoincrement()` : "";
47549
48753
  out += defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
47550
48754
  return out;
47551
48755
  }
47552
48756
  if (lowered.startsWith("tinyint")) {
47553
48757
  let out = `${name.camelCase()}: tinyint("${name}")`;
48758
+ out += autoincrement ? `.autoincrement()` : "";
47554
48759
  out += defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
47555
48760
  return out;
47556
48761
  }
47557
48762
  if (lowered.startsWith("smallint")) {
47558
48763
  let out = `${name.camelCase()}: smallint("${name}")`;
48764
+ out += autoincrement ? `.autoincrement()` : "";
47559
48765
  out += defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
47560
48766
  return out;
47561
48767
  }
47562
48768
  if (lowered.startsWith("mediumint")) {
47563
48769
  let out = `${name.camelCase()}: mediumint("${name}")`;
48770
+ out += autoincrement ? `.autoincrement()` : "";
47564
48771
  out += defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
47565
48772
  return out;
47566
48773
  }
47567
48774
  if (lowered.startsWith("bigint")) {
47568
- let out = `${name.camelCase()}: bigint("${name}", { mode: "bigint" })`;
47569
- out += defaultValue ? `.default(BigInt(${mapColumnDefault(defaultValue)}))` : "";
48775
+ let out = `${name.camelCase()}: bigint("${name}", { mode: "number" })`;
48776
+ out += autoincrement ? `.autoincrement()` : "";
48777
+ out += defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
47570
48778
  return out;
47571
48779
  }
47572
48780
  if (lowered === "boolean") {
@@ -47574,8 +48782,13 @@ import { sql } from "drizzle-orm/sql"
47574
48782
  out += defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
47575
48783
  return out;
47576
48784
  }
47577
- if (lowered === "double") {
47578
- let out = `${name.camelCase()}: double("${name}")`;
48785
+ if (lowered.startsWith("double")) {
48786
+ let params;
48787
+ if (lowered.length > 6) {
48788
+ const [precision, scale] = lowered.slice(7, lowered.length - 1).split(",");
48789
+ params = { precision, scale };
48790
+ }
48791
+ let out = params ? `${name.camelCase()}: double("${name}", ${timeConfig2(params)})` : `${name.camelCase()}: double("${name}")`;
47579
48792
  out += defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
47580
48793
  return out;
47581
48794
  }
@@ -47593,7 +48806,7 @@ import { sql } from "drizzle-orm/sql"
47593
48806
  const keyLength = "timestamp".length + 1;
47594
48807
  let fsp = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
47595
48808
  fsp = fsp ? fsp : null;
47596
- const params = timeConfig2({ fsp });
48809
+ const params = timeConfig2({ fsp, mode: "'string'" });
47597
48810
  let out = params ? `${name.camelCase()}: timestamp("${name}", ${params})` : `${name.camelCase()}: timestamp("${name}")`;
47598
48811
  defaultValue = defaultValue === "now()" || defaultValue === "(CURRENT_TIMESTAMP)" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
47599
48812
  out += defaultValue;
@@ -47601,9 +48814,9 @@ import { sql } from "drizzle-orm/sql"
47601
48814
  }
47602
48815
  if (lowered.startsWith("time")) {
47603
48816
  const keyLength = "time".length + 1;
47604
- let precision = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
47605
- precision = precision ? precision : null;
47606
- const params = timeConfig2({ precision });
48817
+ let fsp = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
48818
+ fsp = fsp ? fsp : null;
48819
+ const params = timeConfig2({ fsp });
47607
48820
  let out = params ? `${name.camelCase()}: time("${name}", ${params})` : `${name.camelCase()}: time("${name}")`;
47608
48821
  defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
47609
48822
  out += defaultValue;
@@ -47643,6 +48856,7 @@ import { sql } from "drizzle-orm/sql"
47643
48856
  }
47644
48857
  if (lowered === "json") {
47645
48858
  let out = `${name.camelCase()}: json("${name}")`;
48859
+ out += defaultValue ? `.default(${mapColumnDefaultForJson(defaultValue)})` : "";
47646
48860
  return out;
47647
48861
  }
47648
48862
  if (lowered.startsWith("varchar")) {
@@ -47663,7 +48877,12 @@ import { sql } from "drizzle-orm/sql"
47663
48877
  }
47664
48878
  if (lowered.startsWith("datetime")) {
47665
48879
  let out = `// you can use { mode: 'date' }, if you want to have Date as type for this column
47666
- ${name}: datetime("${name}", { mode: 'string' } )`;
48880
+ `;
48881
+ const fsp = lowered.startsWith("datetime(") ? lowered.substring("datetime".length + 1, lowered.length - 1) : void 0;
48882
+ out = fsp ? `${name.camelCase()}: datetime("${name}", { mode: 'string', fsp: ${lowered.substring(
48883
+ "datetime".length + 1,
48884
+ lowered.length - 1
48885
+ )} })` : `${name.camelCase()}: datetime("${name}", { mode: 'string'})`;
47667
48886
  defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
47668
48887
  out += defaultValue;
47669
48888
  return out;
@@ -47675,6 +48894,8 @@ import { sql } from "drizzle-orm/sql"
47675
48894
  params = { precision, scale };
47676
48895
  }
47677
48896
  let out = params ? `${name.camelCase()}: decimal("${name}", ${timeConfig2(params)})` : `${name.camelCase()}: decimal("${name}")`;
48897
+ defaultValue = defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
48898
+ out += defaultValue;
47678
48899
  return out;
47679
48900
  }
47680
48901
  if (lowered.startsWith("binary")) {
@@ -47687,6 +48908,12 @@ import { sql } from "drizzle-orm/sql"
47687
48908
  out += defaultValue;
47688
48909
  return out;
47689
48910
  }
48911
+ if (lowered.startsWith("enum")) {
48912
+ const values = lowered.substring("enum".length + 1, lowered.length - 1);
48913
+ let out = `${name.camelCase()}: mysqlEnum("${name}", [${values}])`;
48914
+ out += defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
48915
+ return out;
48916
+ }
47690
48917
  if (lowered.startsWith("varbinary")) {
47691
48918
  const keyLength = "varbinary".length + 1;
47692
48919
  let length = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
@@ -47714,7 +48941,7 @@ import { sql } from "drizzle-orm/sql"
47714
48941
  }, {});
47715
48942
  columns.forEach((it) => {
47716
48943
  statement += " ";
47717
- statement += column5(it.type, it.name, it.default);
48944
+ statement += column5(it.type, it.name, it.default, it.autoincrement);
47718
48945
  statement += it.primaryKey ? ".primaryKey()" : "";
47719
48946
  statement += it.notNull ? ".notNull()" : "";
47720
48947
  const fks2 = fkByColumnName[it.name];
@@ -47749,6 +48976,21 @@ import { sql } from "drizzle-orm/sql"
47749
48976
  statement += `${escapedIndexName})`;
47750
48977
  statement += `.on(${it.columns.map((it2) => `table.${it2.camelCase()}`).join(", ")}),`;
47751
48978
  statement += `
48979
+ `;
48980
+ });
48981
+ return statement;
48982
+ };
48983
+ createTablePKs2 = (pks) => {
48984
+ let statement = "";
48985
+ pks.forEach((it) => {
48986
+ let idxKey = it.name.camelCase();
48987
+ statement += ` ${idxKey}: `;
48988
+ statement += "primaryKey(";
48989
+ statement += `${it.columns.map((c) => {
48990
+ return `table.${c.camelCase()}`;
48991
+ }).join(", ")}`;
48992
+ statement += ")";
48993
+ statement += `
47752
48994
  `;
47753
48995
  });
47754
48996
  return statement;
@@ -47785,6 +49027,7 @@ __export(mysqlIntrospect_exports, {
47785
49027
  var import_hanji5, import_promise, MySQLConfig1, MySQLConfig2, Conf2, mysqlIntrospect;
47786
49028
  var init_mysqlIntrospect = __esm({
47787
49029
  "src/cli/commands/mysqlIntrospect.ts"() {
49030
+ "use strict";
47788
49031
  import_hanji5 = __toESM(require_hanji());
47789
49032
  init_lib();
47790
49033
  init_views();
@@ -47862,7 +49105,7 @@ init_lib();
47862
49105
  // src/cli/commands/check.ts
47863
49106
  init_utils();
47864
49107
  var checkHandler = (out, dialect6) => {
47865
- const { snapshots } = prepareOutFolder(out, dialect6);
49108
+ const { snapshots } = prepareOutFolder2(out, dialect6);
47866
49109
  const report = validateWithReport(snapshots, dialect6);
47867
49110
  if (report.nonLatest.length > 0) {
47868
49111
  console.log(
@@ -47899,7 +49142,7 @@ var checkHandler = (out, dialect6) => {
47899
49142
  // src/cli/index.ts
47900
49143
  var import_hanji6 = __toESM(require_hanji());
47901
49144
  init_views();
47902
- var import_path8 = __toESM(require("path"));
49145
+ var import_path6 = __toESM(require("path"));
47903
49146
 
47904
49147
  // src/cli/utils.ts
47905
49148
  init_views();
@@ -47946,7 +49189,7 @@ init_source();
47946
49189
  // package.json
47947
49190
  var package_default = {
47948
49191
  name: "drizzle-kit",
47949
- version: "0.16.9",
49192
+ version: "0.17.0",
47950
49193
  repository: "https://github.com/drizzle-team/drizzle-kit-mirror",
47951
49194
  author: "Drizzle Team",
47952
49195
  license: "MIT",
@@ -47954,11 +49197,15 @@ var package_default = {
47954
49197
  "drizzle-kit": "./index.js"
47955
49198
  },
47956
49199
  scripts: {
47957
- "start:pg": "node -r esbuild-register ./src/cli/index.ts generate --out ./dev/migrations --dialect pg --schema ./dev/data",
47958
- "start:mysql": "node -r esbuild-register ./src/cli/index.ts generate:mysql --out ./dev/migrations --schema ./dev/migrations/schema.ts",
49200
+ "migrate:old": "drizzle-kit generate:pg --out ./dev/migrations-pg --schema ./dev/migrations-pg/schema.ts",
49201
+ "migrate:old:mysql": "drizzle-kit generate:mysql --out ./dev/migrations-mysql --schema ./dev/migrations-mysql/schema.ts",
49202
+ "start:pg": "node -r esbuild-register ./src/cli/index.ts generate:pg --out ./dev/introspect-pg --schema ./dev/introspect-pg/schema.ts",
49203
+ "start:mysql": "node -r esbuild-register ./src/cli/index.ts generate:mysql --out ./dev/introspect-mysql --schema ./dev/introspect-mysql/schema.ts",
47959
49204
  "check:pg": "node -r esbuild-register ./src/cli/index.ts check --out ./dev/migrations --dialect pg",
47960
- "introspect:mysql": "node -r esbuild-register ./src/cli/index.ts introspect:mysql --out ./dev/migrations --connectionString ",
47961
- "up:pg": "node -r esbuild-register ./src/cli/index.ts up --out ./dev/equedi --dialect pg",
49205
+ "introspect:mysql": "node -r esbuild-register ./src/cli/index.ts introspect:mysql --out ./dev/introspect-mysql --connectionString",
49206
+ "introspect:pg": "node -r esbuild-register ./src/cli/index.ts introspect:pg --out ./dev/introspect-pg --connectionString=postgresql://postgres@localhost:5432/introspect",
49207
+ "up:pg": "node -r esbuild-register ./src/cli/index.ts up:pg --out ./dev/migrations-pg",
49208
+ "up:mysql": "node -r esbuild-register ./src/cli/index.ts up:mysql --out ./dev/migrations-mysql",
47962
49209
  "check:equedi": "node -r esbuild-register ./src/cli/index.ts check --out ./dev/equedi --dialect pg",
47963
49210
  run: "node -r esbuild-register index.ts",
47964
49211
  watch: "esbuild ./src/clie/index.ts --bundle --platform=node --target=node10.4 --outfile=./dist/index.js --external:esbuild --external:pg-native --sourcemap --watch",
@@ -47968,7 +49215,7 @@ var package_default = {
47968
49215
  "prepare-snapshot": "node -r esbuild-register ./dev/prepare-snapshot prepare ./dev/data",
47969
49216
  sim: "node -r esbuild-register ./dev/simulate.ts",
47970
49217
  "sim:sqlite": "node -r esbuild-register ./dev/sqlite/index.ts",
47971
- test: "ava test",
49218
+ test: "ava test --timeout=60s",
47972
49219
  build: "pnpm build:cli && pnpm build:utils",
47973
49220
  "build:cli": "esbuild ./src/cli/index.ts --bundle --platform=node --target=node10.4 --outfile=./dist/index.js --external:esbuild --external:drizzle-orm-pg --external:drizzle-orm-sqlite --external:drizzle-orm-mysql --external:drizzle-orm --external:pg-native",
47974
49221
  "build:utils": "esbuild ./src/utils.ts --bundle --platform=node --target=node10.4 --outfile=./dist/utils.js",
@@ -48008,7 +49255,7 @@ var package_default = {
48008
49255
  ava: "^5.1.0",
48009
49256
  dockerode: "^3.3.4",
48010
49257
  "drizzle-kit": "^0.16.8",
48011
- "drizzle-orm": "0.21.0-2e66963",
49258
+ "drizzle-orm": "0.21.0-26e3751",
48012
49259
  esbuild: "^0.15.7",
48013
49260
  "esbuild-register": "^3.3.3",
48014
49261
  eslint: "^8.29.0",
@@ -48029,228 +49276,39 @@ init_migrate();
48029
49276
  init_utils2();
48030
49277
  init_pgSchema();
48031
49278
  init_utils();
48032
-
48033
- // src/cli/commands/pgUp.ts
48034
- init_source();
48035
- var import_crypto2 = require("crypto");
48036
- var import_fs6 = require("fs");
48037
- init_global();
48038
- init_pgSchema();
48039
- init_utils();
48040
- var upPgHandler = (out) => {
48041
- };
48042
- var upPgHandlerV4 = (out) => {
48043
- const snapshots = snapshotsPriorV4(out);
48044
- const report = validateWithReport(snapshots, "pg");
48045
- let prevId = originUUID;
48046
- report.nonLatest.map((it) => ({
48047
- path: it,
48048
- raw: report.rawMap[it]
48049
- })).forEach((it) => {
48050
- const path4 = it.path;
48051
- const result = updateUpToV4(it.raw, prevId);
48052
- prevId = result.id;
48053
- console.log(`[${source_default.green("\u2713")}] ${path4}`);
48054
- (0, import_fs6.writeFileSync)(path4, JSON.stringify(result, null, 2));
48055
- });
48056
- console.log("Everything's fine \u{1F436}\u{1F525}");
48057
- };
48058
- var updateUpToV4 = (json, prevId) => {
48059
- const version = Number(json["version"]);
48060
- if (version === 1) {
48061
- const v1 = pgSchemaV1.parse(json);
48062
- const v2 = update1to2(v1);
48063
- const v3 = update2to3(v2, prevId);
48064
- const v4 = update3to4(v3);
48065
- return v4;
48066
- }
48067
- if (version === 2) {
48068
- const v2 = pgSchemaV2.parse(json);
48069
- const v3 = update2to3(v2, prevId);
48070
- const v4 = update3to4(v3);
48071
- return v4;
48072
- }
48073
- if (version === 3) {
48074
- return update3to4(pgSchemaV3.parse(json));
48075
- }
48076
- return pgSchemaV4.parse(json);
48077
- };
48078
- var update1to2 = (json) => {
48079
- const tables = Object.fromEntries(
48080
- Object.entries(json.tables).map((it) => {
48081
- const table4 = it[1];
48082
- const columns = Object.fromEntries(
48083
- Object.entries(table4.columns).map((it2) => {
48084
- const ref = it2[1].references;
48085
- const fkName = ref == null ? void 0 : ref.foreignKeyName;
48086
- const table5 = ref == null ? void 0 : ref.table;
48087
- const column6 = ref == null ? void 0 : ref.column;
48088
- const onDelete = ref == null ? void 0 : ref.onDelete;
48089
- const onUpdate = ref == null ? void 0 : ref.onDelete;
48090
- const newRef = ref ? `${fkName};${table5};${column6};${onDelete != null ? onDelete : ""};${onUpdate != null ? onUpdate : ""}` : void 0;
48091
- return [it2[0], { ...it2[1], references: newRef }];
48092
- })
48093
- );
48094
- return [it[0], { name: table4.name, columns, indexes: table4.indexes }];
48095
- })
48096
- );
48097
- return { version: "2", tables, enums: json.enums };
48098
- };
48099
- var update2to3 = (json, prevId) => {
48100
- const tables = Object.fromEntries(
48101
- Object.entries(json.tables).map((table4) => {
48102
- const { name, columns, indexes } = table4[1];
48103
- let refs = [];
48104
- const newColumns = Object.fromEntries(
48105
- Object.entries(columns).map((it) => {
48106
- const {
48107
- name: name2,
48108
- type,
48109
- primaryKey,
48110
- notNull,
48111
- default: defaultValue,
48112
- references: references2
48113
- } = it[1];
48114
- const newColumn = {
48115
- name: name2,
48116
- type,
48117
- primaryKey,
48118
- notNull,
48119
- default: defaultValue
48120
- };
48121
- if (references2) {
48122
- refs.push({ column: name2, value: references2 });
48123
- }
48124
- return [it[0], newColumn];
48125
- })
48126
- );
48127
- const tableName = name;
48128
- const fks = Object.fromEntries(
48129
- refs.map((it) => {
48130
- const [name2, table5, column6, onDelete, onUpdate] = it.value.split(";");
48131
- const fk4 = {
48132
- name: name2,
48133
- tableFrom: tableName,
48134
- columnsFrom: [it.column],
48135
- tableTo: table5,
48136
- columnsTo: [column6],
48137
- onUpdate,
48138
- onDelete
48139
- };
48140
- return [name2, fk4];
48141
- })
48142
- );
48143
- const idxs = Object.fromEntries(
48144
- Object.entries(indexes).map((it) => {
48145
- const { columns: columns2, isUnique, name: name2 } = it[1];
48146
- const mappedColumns = Object.entries(columns2).map((it2) => {
48147
- return it2[1].name;
48148
- });
48149
- const index4 = {
48150
- name: name2,
48151
- isUnique,
48152
- columns: mappedColumns
48153
- };
48154
- return [it[0], index4];
48155
- })
48156
- );
48157
- const newTable = {
48158
- name,
48159
- columns: newColumns,
48160
- indexes: idxs,
48161
- foreignKeys: fks
48162
- };
48163
- return [table4[0], newTable];
48164
- })
48165
- );
48166
- return {
48167
- version: "3",
48168
- dialect: "pg",
48169
- id: (0, import_crypto2.randomUUID)(),
48170
- prevId,
48171
- tables,
48172
- enums: json.enums
48173
- };
48174
- };
48175
- var update3to4 = (json) => {
48176
- const tables = Object.fromEntries(
48177
- Object.entries(json.tables).map((table4) => {
48178
- const { name, columns, foreignKeys, indexes } = table4[1];
48179
- const newColumns = Object.fromEntries(
48180
- Object.entries(columns).map((it) => {
48181
- const {
48182
- name: name2,
48183
- type,
48184
- primaryKey,
48185
- notNull,
48186
- default: defaultValue
48187
- } = it[1];
48188
- const newColumn = {
48189
- name: name2,
48190
- type,
48191
- primaryKey,
48192
- notNull,
48193
- default: defaultValue
48194
- };
48195
- return [it[0], newColumn];
48196
- })
48197
- );
48198
- const newTable = {
48199
- name,
48200
- schema: "",
48201
- columns: newColumns,
48202
- indexes,
48203
- foreignKeys
48204
- };
48205
- return [table4[0], newTable];
48206
- })
48207
- );
48208
- return {
48209
- version: "4",
48210
- dialect: "pg",
48211
- id: (0, import_crypto2.randomUUID)(),
48212
- prevId: json.prevId,
48213
- tables,
48214
- enums: json.enums,
48215
- schemas: {}
48216
- };
48217
- };
49279
+ init_pgUp();
48218
49280
 
48219
49281
  // src/cli/commands/sqliteUp.ts
48220
49282
  init_source();
48221
- var import_fs7 = __toESM(require("fs"));
48222
- var import_path5 = __toESM(require("path"));
49283
+ var import_fs8 = __toESM(require("fs"));
48223
49284
  init_sqliteSchema();
48224
49285
  init_utils();
48225
49286
  var upSqliteHandler = (out) => {
48226
- const { snapshots } = prepareOutFolder(out, "sqlite");
49287
+ };
49288
+ var upSqliteHandlerV4 = (out) => {
49289
+ const snapshots = snapshotsPriorV4(out);
48227
49290
  const report = validateWithReport(snapshots, "sqlite");
48228
49291
  report.nonLatest.map((it) => ({
48229
- folder: it,
49292
+ path: it,
48230
49293
  raw: report.rawMap[it]
48231
49294
  })).forEach((it) => {
48232
- const folder = it.folder;
48233
- const result = updateToLatest(it.raw);
48234
- console.log(
48235
- `[${source_default.green("\u2713")}] ${import_path5.default.join(out, folder, "snapshot.json")}`
48236
- );
48237
- import_fs7.default.writeFileSync(
48238
- import_path5.default.join(out, folder, "snapshot.json"),
48239
- JSON.stringify(result, null, 2)
48240
- );
49295
+ const path2 = it.path;
49296
+ const result = updateToLatestV42(it.raw);
49297
+ console.log(`[${source_default.green("\u2713")}] ${path2}`);
49298
+ import_fs8.default.writeFileSync(path2, JSON.stringify(result, null, 2));
48241
49299
  });
48242
49300
  console.log("Everything's fine \u{1F436}\u{1F525}");
48243
49301
  };
48244
- var updateToLatest = (json) => {
49302
+ var updateToLatestV42 = (json) => {
48245
49303
  const version = Number(json["version"]);
48246
49304
  if (version === 3) {
48247
49305
  const v3 = sqliteSchemaV3.parse(json);
48248
- const v4 = updateV3toV4(v3);
49306
+ const v4 = updateV3toV42(v3);
48249
49307
  return v4;
48250
49308
  }
48251
49309
  return sqliteSchemaV4.parse(json);
48252
49310
  };
48253
- var updateV3toV4 = (old) => {
49311
+ var updateV3toV42 = (old) => {
48254
49312
  const mappedTables = Object.fromEntries(
48255
49313
  Object.entries(old.tables).map((it) => {
48256
49314
  const mappedTable = { ...it[1], compositePrimaryKeys: {} };
@@ -48264,51 +49322,8 @@ var updateV3toV4 = (old) => {
48264
49322
  };
48265
49323
  };
48266
49324
 
48267
- // src/cli/commands/mysqlUp.ts
48268
- init_source();
48269
- var import_fs8 = __toESM(require("fs"));
48270
- var import_path6 = __toESM(require("path"));
48271
- init_mysqlSchema();
48272
- init_utils();
48273
- var upMysqlHandler = (out) => {
48274
- };
48275
- var upMysqlHandlerV4 = (out) => {
48276
- const { snapshots } = prepareOutFolder(out, "mysql");
48277
- const report = validateWithReport(snapshots, "mysql");
48278
- report.nonLatest.map((it) => ({
48279
- folder: it,
48280
- raw: report.rawMap[it]
48281
- })).forEach((it) => {
48282
- const folder = it.folder;
48283
- const result = updateToLatestV4(it.raw);
48284
- console.log(
48285
- `[${source_default.green("\u2713")}] ${import_path6.default.join(out, folder, "snapshot.json")}`
48286
- );
48287
- import_fs8.default.writeFileSync(
48288
- import_path6.default.join(out, folder, "snapshot.json"),
48289
- JSON.stringify(result, null, 2)
48290
- );
48291
- });
48292
- console.log("Everything's fine \u{1F436}\u{1F525}");
48293
- };
48294
- var updateToLatestV4 = (json) => {
48295
- const version = Number(json["version"]);
48296
- if (version === 3) {
48297
- const v3 = mysqlSchemaV3.parse(json);
48298
- const v4 = updateV3toV42(v3);
48299
- return v4;
48300
- }
48301
- return mysqlSchemaV4.parse(json);
48302
- };
48303
- var updateV3toV42 = (old) => {
48304
- return {
48305
- ...old,
48306
- version: "4",
48307
- schemas: {}
48308
- };
48309
- };
48310
-
48311
49325
  // src/cli/index.ts
49326
+ init_mysqlUp();
48312
49327
  init_upFolders();
48313
49328
  init_mysqlSchema();
48314
49329
 
@@ -48316,10 +49331,10 @@ init_mysqlSchema();
48316
49331
  init_source();
48317
49332
  var import_fs9 = require("fs");
48318
49333
  var import_hanji3 = __toESM(require_hanji());
48319
- var import_path7 = require("path");
49334
+ var import_path5 = require("path");
48320
49335
  init_views();
48321
49336
  var dropMigration = async (out) => {
48322
- const metaFilePath = (0, import_path7.join)(out, "meta", "_journal.json");
49337
+ const metaFilePath = (0, import_path5.join)(out, "meta", "_journal.json");
48323
49338
  const journal = JSON.parse(
48324
49339
  (0, import_fs9.readFileSync)(metaFilePath, "utf-8")
48325
49340
  );
@@ -48331,8 +49346,8 @@ var dropMigration = async (out) => {
48331
49346
  ...journal,
48332
49347
  entries: journal.entries.filter(Boolean)
48333
49348
  };
48334
- const sqlFilePath = (0, import_path7.join)(out, `${result.data.tag}.sql`);
48335
- const snapshotFilePath = (0, import_path7.join)(out, "meta", `${result.data.idx.toFixed(0).padStart(4, "0")}_snapshot.json`);
49349
+ const sqlFilePath = (0, import_path5.join)(out, `${result.data.tag}.sql`);
49350
+ const snapshotFilePath = (0, import_path5.join)(out, "meta", `${result.data.idx.toFixed(0).padStart(4, "0")}_snapshot.json`);
48336
49351
  (0, import_fs9.rmSync)(sqlFilePath);
48337
49352
  (0, import_fs9.rmSync)(snapshotFilePath);
48338
49353
  (0, import_fs9.writeFileSync)(metaFilePath, JSON.stringify(resultJournal));
@@ -48347,13 +49362,13 @@ var printVersions = () => {
48347
49362
  var assertEitherConfigOrOut = (config, out) => {
48348
49363
  if (out)
48349
49364
  return out;
48350
- if (!(0, import_fs10.existsSync)(import_path8.default.join(import_path8.default.resolve(config)))) {
49365
+ if (!(0, import_fs10.existsSync)(import_path6.default.join(import_path6.default.resolve(config)))) {
48351
49366
  console.log(`${config} file does not exist`);
48352
49367
  process.exit(1);
48353
49368
  }
48354
49369
  console.log(`Reading ${config}`);
48355
49370
  const drizzleConfig = JSON.parse(
48356
- import_fs10.default.readFileSync(import_path8.default.join(import_path8.default.resolve(config))).toString()
49371
+ import_fs10.default.readFileSync(import_path6.default.join(import_path6.default.resolve(config))).toString()
48357
49372
  );
48358
49373
  return drizzleConfig.out;
48359
49374
  };
@@ -48375,12 +49390,13 @@ var optionsSchema = objectType({
48375
49390
  config: stringType().optional(),
48376
49391
  breakpoints: booleanType().optional().default(false)
48377
49392
  }).strict();
48378
- var generatePgCommand = new Command("generate:pg").option("--schema <schema>", "Path to a schema file or folder").option("--out <out>", `Output folder, 'drizzle' by default`).option("--breakpoints", `Prepare SQL statements with breakpoints`).option(
49393
+ var generatePgCommand = new Command("generate:pg").option("--schema <schema...>", "Path to a schema file or folder").option("--out <out>", `Output folder, 'drizzle' by default`).option("--breakpoints", `Prepare SQL statements with breakpoints`).option(
48379
49394
  "--config <config>",
48380
49395
  "Path to a config.json file, drizzle.config.json by default"
48381
49396
  ).action(async (options) => {
48382
49397
  printVersions();
48383
49398
  assertOrmCoreVersion();
49399
+ console.log(options);
48384
49400
  const oprtionsParsed = optionsSchema.parse(options);
48385
49401
  const result = prepareGenerateConfig(oprtionsParsed);
48386
49402
  if (result instanceof Error) {
@@ -48391,7 +49407,7 @@ var generatePgCommand = new Command("generate:pg").option("--schema <schema>", "
48391
49407
  const { prepareAndMigratePg: prepareAndMigratePg2 } = (init_migrate(), __toCommonJS(migrate_exports));
48392
49408
  await prepareAndMigratePg2(result);
48393
49409
  });
48394
- var generateMysqlCommand = new Command("generate:mysql").option("--schema <schema>", "Path to a schema file or folder").option("--out <out>", `Output folder, 'drizzle' by default`).option("--breakpoints", `Prepare SQL statements with breakpoints`).option(
49410
+ var generateMysqlCommand = new Command("generate:mysql").option("--schema <schema...>", "Path to a schema file or folder").option("--out <out>", `Output folder, 'drizzle' by default`).option("--breakpoints", `Prepare SQL statements with breakpoints`).option(
48395
49411
  "--config <config>",
48396
49412
  "Path to a config.json file, drizzle.config.json by default"
48397
49413
  ).action(async (options) => {
@@ -48407,7 +49423,7 @@ var generateMysqlCommand = new Command("generate:mysql").option("--schema <schem
48407
49423
  const { prepareAndMigrateMySql: prepareAndMigrateMySql2 } = (init_migrate(), __toCommonJS(migrate_exports));
48408
49424
  await prepareAndMigrateMySql2(result);
48409
49425
  });
48410
- var generateSqliteCommand = new Command("generate:sqlite").option("--schema <schema>", "Path to a schema file or folder").option("--out <out>", `Output folder, 'drizzle' by default`).option("--breakpoints", `Prepare SQL statements with breakpoints`).option(
49426
+ var generateSqliteCommand = new Command("generate:sqlite").option("--schema <schema...>", "Path to a schema file or folder").option("--out <out>", `Output folder, 'drizzle' by default`).option("--breakpoints", `Prepare SQL statements with breakpoints`).option(
48411
49427
  "--config <config>",
48412
49428
  "Path to a config.json file, drizzle.config.json by default"
48413
49429
  ).action(async (options) => {
@@ -48426,9 +49442,9 @@ var generateSqliteCommand = new Command("generate:sqlite").option("--schema <sch
48426
49442
  var prepareGenerateConfig = (options) => {
48427
49443
  const { schema: schema4, out, config, breakpoints } = options;
48428
49444
  if (!(schema4 || out)) {
48429
- const path4 = config != null ? config : "drizzle.config.json";
49445
+ const path2 = config != null ? config : "drizzle.config.json";
48430
49446
  const drizzleConfig = JSON.parse(
48431
- import_fs10.default.readFileSync(import_path8.default.join(import_path8.default.resolve(path4))).toString()
49447
+ import_fs10.default.readFileSync(import_path6.default.join(import_path6.default.resolve(path2))).toString()
48432
49448
  );
48433
49449
  return drizzleConfig;
48434
49450
  }
@@ -48514,6 +49530,8 @@ var upSqliteCommand = new Command("up:sqlite").option("--out <out>", `Output fol
48514
49530
  console.log(error(`'out' folder param must be set`));
48515
49531
  process.exit(0);
48516
49532
  }
49533
+ upSqliteHandlerV4(out);
49534
+ upgradeFolders("sqlite", out);
48517
49535
  upSqliteHandler(out);
48518
49536
  });
48519
49537
  var pt1 = objectType({
@@ -48534,16 +49552,18 @@ var introspectPgCommand = new Command("introspect:pg").option("--out <out>", `Mi
48534
49552
  console.log("Missing required params");
48535
49553
  return;
48536
49554
  }
48537
- const { snapshots, journal } = prepareOutFolder(res.data.out, "pg");
49555
+ const { snapshots, journal } = prepareOutFolder2(res.data.out, "pg");
48538
49556
  const { schema: schema4, ts } = await pgIntrospect2(res.data);
48539
- const schemaFile = import_path8.default.join(res.data.out, "schema.ts");
49557
+ const schemaFile = import_path6.default.join(res.data.out, "schema.ts");
48540
49558
  (0, import_fs10.writeFileSync)(schemaFile, ts);
48541
49559
  console.log();
48542
49560
  if (snapshots.length === 0) {
48543
49561
  const { sqlStatements, _meta } = await prepareSQL(
48544
49562
  squashPgScheme(dryPg),
48545
49563
  squashPgScheme(schema4),
48546
- "pg"
49564
+ "pg",
49565
+ dryMySql,
49566
+ schema4
48547
49567
  );
48548
49568
  writeResult(
48549
49569
  schema4,
@@ -48583,16 +49603,18 @@ var introspectMySqlCommand = new Command("introspect:mysql").option("--out <out>
48583
49603
  console.log("Missing required params");
48584
49604
  return;
48585
49605
  }
48586
- const { snapshots, journal } = prepareOutFolder(res.data.out, "mysql");
49606
+ const { snapshots, journal } = prepareOutFolder2(res.data.out, "mysql");
48587
49607
  const { schema: schema4, ts } = await mysqlIntrospect2(res.data);
48588
- const schemaFile = import_path8.default.join(res.data.out, "schema.ts");
49608
+ const schemaFile = import_path6.default.join(res.data.out, "schema.ts");
48589
49609
  (0, import_fs10.writeFileSync)(schemaFile, ts);
48590
49610
  console.log();
48591
49611
  if (snapshots.length === 0) {
48592
49612
  const { sqlStatements, _meta } = await prepareSQL(
48593
49613
  squashMysqlScheme(dryMySql),
48594
49614
  squashMysqlScheme(schema4),
48595
- "mysql"
49615
+ "mysql",
49616
+ dryMySql,
49617
+ schema4
48596
49618
  );
48597
49619
  writeResult(
48598
49620
  schema4,