drizzle-seed 0.3.2-f8a2f3c → 0.4.0-08bb2d5

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 (74) hide show
  1. package/{services/SeedService.d.cts → SeedService.d.cts} +18 -26
  2. package/{services/SeedService.d.mts → SeedService.d.mts} +18 -26
  3. package/{services/SeedService.d.ts → SeedService.d.ts} +18 -26
  4. package/cockroach-core/index.d.cts +24 -0
  5. package/cockroach-core/index.d.mts +24 -0
  6. package/cockroach-core/index.d.ts +24 -0
  7. package/cockroach-core/selectGensForColumn.d.cts +3 -0
  8. package/cockroach-core/selectGensForColumn.d.mts +3 -0
  9. package/cockroach-core/selectGensForColumn.d.ts +3 -0
  10. package/{services → generators}/GeneratorFuncs.d.cts +311 -35
  11. package/{services → generators}/GeneratorFuncs.d.mts +311 -35
  12. package/{services → generators}/GeneratorFuncs.d.ts +311 -35
  13. package/{services → generators}/Generators.d.cts +149 -23
  14. package/{services → generators}/Generators.d.mts +149 -23
  15. package/{services → generators}/Generators.d.ts +149 -23
  16. package/generators/utils.d.cts +38 -0
  17. package/generators/utils.d.mts +38 -0
  18. package/generators/utils.d.ts +38 -0
  19. package/{services → generators}/versioning/v2.d.cts +1 -1
  20. package/{services → generators}/versioning/v2.d.mts +1 -1
  21. package/{services → generators}/versioning/v2.d.ts +1 -1
  22. package/index.cjs +2799 -1003
  23. package/index.cjs.map +1 -1
  24. package/index.d.cts +136 -81
  25. package/index.d.mts +136 -81
  26. package/index.d.ts +136 -81
  27. package/index.mjs +2813 -1016
  28. package/index.mjs.map +1 -1
  29. package/mssql-core/index.d.cts +24 -0
  30. package/mssql-core/index.d.mts +24 -0
  31. package/mssql-core/index.d.ts +24 -0
  32. package/mssql-core/selectGensForColumn.d.cts +2 -0
  33. package/mssql-core/selectGensForColumn.d.mts +2 -0
  34. package/mssql-core/selectGensForColumn.d.ts +2 -0
  35. package/mysql-core/index.d.cts +24 -0
  36. package/mysql-core/index.d.mts +24 -0
  37. package/mysql-core/index.d.ts +24 -0
  38. package/mysql-core/selectGensForColumn.d.cts +2 -0
  39. package/mysql-core/selectGensForColumn.d.mts +2 -0
  40. package/mysql-core/selectGensForColumn.d.ts +2 -0
  41. package/package.json +11 -7
  42. package/pg-core/index.d.cts +24 -0
  43. package/pg-core/index.d.mts +24 -0
  44. package/pg-core/index.d.ts +24 -0
  45. package/pg-core/selectGensForColumn.d.cts +3 -0
  46. package/pg-core/selectGensForColumn.d.mts +3 -0
  47. package/pg-core/selectGensForColumn.d.ts +3 -0
  48. package/singlestore-core/index.d.cts +24 -0
  49. package/singlestore-core/index.d.mts +24 -0
  50. package/singlestore-core/index.d.ts +24 -0
  51. package/singlestore-core/selectGensForColumn.d.cts +2 -0
  52. package/singlestore-core/selectGensForColumn.d.mts +2 -0
  53. package/singlestore-core/selectGensForColumn.d.ts +2 -0
  54. package/sqlite-core/index.d.cts +24 -0
  55. package/sqlite-core/index.d.mts +24 -0
  56. package/sqlite-core/index.d.ts +24 -0
  57. package/sqlite-core/selectGensForColumn.d.cts +2 -0
  58. package/sqlite-core/selectGensForColumn.d.mts +2 -0
  59. package/sqlite-core/selectGensForColumn.d.ts +2 -0
  60. package/types/seedService.d.cts +12 -2
  61. package/types/seedService.d.mts +12 -2
  62. package/types/seedService.d.ts +12 -2
  63. package/types/tables.d.cts +2 -0
  64. package/types/tables.d.mts +2 -0
  65. package/types/tables.d.ts +2 -0
  66. package/utils.d.cts +4 -0
  67. package/utils.d.mts +4 -0
  68. package/utils.d.ts +4 -0
  69. package/services/utils.d.cts +0 -23
  70. package/services/utils.d.mts +0 -23
  71. package/services/utils.d.ts +0 -23
  72. /package/{services → generators}/apiVersion.d.cts +0 -0
  73. /package/{services → generators}/apiVersion.d.mts +0 -0
  74. /package/{services → generators}/apiVersion.d.ts +0 -0
package/index.cjs CHANGED
@@ -4,6 +4,9 @@ var drizzleOrm = require('drizzle-orm');
4
4
  var mysqlCore = require('drizzle-orm/mysql-core');
5
5
  var pgCore = require('drizzle-orm/pg-core');
6
6
  var sqliteCore = require('drizzle-orm/sqlite-core');
7
+ var mssqlCore = require('drizzle-orm/mssql-core');
8
+ var cockroachCore = require('drizzle-orm/cockroach-core');
9
+ var singlestoreCore = require('drizzle-orm/singlestore-core');
7
10
  var prand = require('pure-rand');
8
11
 
9
12
  /**
@@ -131132,18 +131135,60 @@ var streetSuffix = [
131132
131135
  ];
131133
131136
  const maxStringLength = 10;
131134
131137
 
131138
+ /* eslint-disable drizzle-internal/require-entity-kind */
131135
131139
  const fastCartesianProduct = (sets, index) => {
131136
131140
  const resultList = [];
131137
131141
  let currSet;
131138
131142
  let element;
131139
131143
  for (let i = sets.length - 1; i >= 0; i--) {
131140
131144
  currSet = sets[i];
131141
- element = currSet[index % currSet.length];
131145
+ element = currSet[index % Number(currSet.length)];
131142
131146
  resultList.unshift(element);
131143
- index = Math.floor(index / currSet.length);
131147
+ index = Math.floor(index / Number(currSet.length));
131144
131148
  }
131145
131149
  return resultList;
131146
131150
  };
131151
+ const fastCartesianProductForBigint = (sets, index) => {
131152
+ const resultList = [];
131153
+ let currSet;
131154
+ let element;
131155
+ for (let i = sets.length - 1; i >= 0; i--) {
131156
+ currSet = sets[i];
131157
+ const remainder = index % BigInt(currSet.length);
131158
+ // TODO check how it works
131159
+ // remainder = remainder <= Number.MAX_SAFE_INTEGER ? Number(remainder) : remainder;
131160
+ element = currSet[remainder];
131161
+ resultList.unshift(element);
131162
+ index = index / BigInt(currSet.length);
131163
+ }
131164
+ return resultList;
131165
+ };
131166
+ class OrderedNumberRange {
131167
+ min;
131168
+ max;
131169
+ step;
131170
+ length;
131171
+ constructor(min, max, step) {
131172
+ this.min = min;
131173
+ this.max = max;
131174
+ this.step = step;
131175
+ this.length = Math.floor((this.max - this.min) / this.step) + 1;
131176
+ const handler = {
131177
+ get(target, prop, receiver) {
131178
+ if (typeof prop === 'string' && /^\d+$/.test(prop)) {
131179
+ const idx = Number(prop);
131180
+ if (idx >= target.length)
131181
+ return undefined;
131182
+ return (target.min + idx * target.step);
131183
+ }
131184
+ // fallback to normal lookup (and TS knows this has the right signature)
131185
+ return Reflect.get(target, prop, receiver);
131186
+ },
131187
+ };
131188
+ return new Proxy(this, handler);
131189
+ }
131190
+ }
131191
+ const abs = (n) => (n < 0n) ? -n : n;
131147
131192
  const sumArray = (weights) => {
131148
131193
  const scale = 1e10;
131149
131194
  const scaledSum = weights.reduce((acc, currVal) => acc + Math.round(currVal * scale), 0);
@@ -131167,16 +131212,6 @@ const getWeightedIndices = (weights, accuracy = 100) => {
131167
131212
  }
131168
131213
  return weightedIndices;
131169
131214
  };
131170
- const generateHashFromString = (s) => {
131171
- let hash = 0;
131172
- // p and m are prime numbers
131173
- const p = 53;
131174
- const m = 28871271685163;
131175
- for (let i = 0; i < s.length; i++) {
131176
- hash += ((s.codePointAt(i) || 0) * Math.pow(p, i)) % m;
131177
- }
131178
- return hash;
131179
- };
131180
131215
  /**
131181
131216
  * @param param0.template example: "#####" or "#####-####"
131182
131217
  * @param param0.values example: ["3", "2", "h"]
@@ -131213,12 +131248,27 @@ const isObject = (value) => {
131213
131248
  return true;
131214
131249
  return false;
131215
131250
  };
131216
- const equalSets = (set1, set2) => {
131217
- return set1.size === set2.size && [...set1].every((si) => set2.has(si));
131218
- };
131219
- const isValidDate = (date) => {
131220
- return !Number.isNaN(date.getTime());
131221
- };
131251
+ // const main = () => {
131252
+ // console.time('range');
131253
+ // const range = new OrderedBigintRange(BigInt(-10), BigInt(10), BigInt(1));
131254
+ // console.log(range.length);
131255
+ // for (let i = 0; i < Number(range.length) + 1; i++) {
131256
+ // console.log(range[i]);
131257
+ // }
131258
+ // console.timeEnd('range');
131259
+ // const list = Array.from({ length: 2e6 + 1 }, (_, idx) => idx);
131260
+ // console.time('list');
131261
+ // console.log(list.length);
131262
+ // for (let i = 0; i < 2e6 + 1; i++) {
131263
+ // list[i];
131264
+ // }
131265
+ // console.timeEnd('list');
131266
+ // // const n = 5;
131267
+ // // for (let i = 0; i < n; i++) {
131268
+ // // console.log(fastCartesianProduct([[1, 2], [1, 2]], i));
131269
+ // // }
131270
+ // };
131271
+ // main();
131222
131272
 
131223
131273
  /* eslint-disable drizzle-internal/require-entity-kind */
131224
131274
  class AbstractGenerator {
@@ -131234,10 +131284,11 @@ class AbstractGenerator {
131234
131284
  arraySize;
131235
131285
  baseColumnDataType;
131236
131286
  // param for text-like generators
131237
- stringLength;
131287
+ // public stringLength?: number;
131238
131288
  // params for GenerateValuesFromArray
131239
131289
  weightedCountSeed;
131240
131290
  maxRepeatedValuesCount;
131291
+ typeParams = {};
131241
131292
  params;
131242
131293
  constructor(params) {
131243
131294
  this.params = params === undefined ? {} : params;
@@ -131269,6 +131320,7 @@ class AbstractGenerator {
131269
131320
  });
131270
131321
  uniqueGen.isUnique = this.isUnique;
131271
131322
  uniqueGen.dataType = this.dataType;
131323
+ uniqueGen.typeParams = this.typeParams;
131272
131324
  return uniqueGen;
131273
131325
  }
131274
131326
  return;
@@ -131279,10 +131331,13 @@ class AbstractGenerator {
131279
131331
  const uniqueGen = this.replaceIfUnique();
131280
131332
  const baseColumnGen = uniqueGen === undefined ? this : uniqueGen;
131281
131333
  baseColumnGen.dataType = this.baseColumnDataType;
131334
+ const { dimensions, ...rest } = baseColumnGen.typeParams;
131335
+ baseColumnGen.typeParams = rest;
131282
131336
  const arrayGen = new GenerateArray({
131283
131337
  baseColumnGen,
131284
131338
  size: this.arraySize,
131285
131339
  });
131340
+ arrayGen.typeParams = { dimensions };
131286
131341
  return arrayGen;
131287
131342
  }
131288
131343
  return;
@@ -131537,6 +131592,7 @@ class GenerateNumber extends AbstractGenerator {
131537
131592
  static entityKind = 'GenerateNumber';
131538
131593
  state;
131539
131594
  uniqueVersionOfGen = GenerateUniqueNumber;
131595
+ // TODO rewrite precision to decimalPlaces
131540
131596
  init({ count, seed }) {
131541
131597
  super.init({ count, seed });
131542
131598
  let { minValue, maxValue, precision } = this.params;
@@ -131790,20 +131846,13 @@ class GenerateDate extends AbstractGenerator {
131790
131846
  const rng = prand.xoroshiro128plus(seed);
131791
131847
  let { minDate, maxDate } = this.params;
131792
131848
  const anchorDate = new Date('2024-05-08');
131793
- // 4 years in milliseconds
131794
131849
  const deltaMilliseconds = 4 * 31536000000;
131795
131850
  if (typeof minDate === 'string') {
131796
131851
  minDate = new Date(minDate);
131797
131852
  }
131798
- if (typeof minDate === 'object' && !isValidDate(minDate)) {
131799
- throw new Error('Invalid Date was provided for the minDate parameter.');
131800
- }
131801
131853
  if (typeof maxDate === 'string') {
131802
131854
  maxDate = new Date(maxDate);
131803
131855
  }
131804
- if (typeof maxDate === 'object' && !isValidDate(maxDate)) {
131805
- throw new Error('Invalid Date was provided for the maxDate parameter.');
131806
- }
131807
131856
  if (minDate === undefined) {
131808
131857
  if (maxDate === undefined) {
131809
131858
  minDate = new Date(anchorDate.getTime() - deltaMilliseconds);
@@ -131816,9 +131865,6 @@ class GenerateDate extends AbstractGenerator {
131816
131865
  if (maxDate === undefined) {
131817
131866
  maxDate = new Date(minDate.getTime() + (2 * deltaMilliseconds));
131818
131867
  }
131819
- if (minDate > maxDate) {
131820
- throw new Error(`The minDate parameter must be less than or equal to the maxDate parameter.`);
131821
- }
131822
131868
  this.state = { rng, minDate, maxDate };
131823
131869
  }
131824
131870
  generate() {
@@ -131840,83 +131886,18 @@ class GenerateTime extends AbstractGenerator {
131840
131886
  init({ count, seed }) {
131841
131887
  super.init({ count, seed });
131842
131888
  const rng = prand.xoroshiro128plus(seed);
131843
- let { minTime, maxTime } = this.params;
131844
- if (minTime === undefined && maxTime === undefined) {
131845
- // TODO: maybe need to change in major version release
131846
- // This is required to ensure that this generator remains deterministic when used without minTime, maxTime parameters.
131847
- const oneDayInMilliseconds = 86400000;
131848
- minTime = new Date(new Date('2024-05-08T12:00:00.000Z').getTime() - oneDayInMilliseconds);
131849
- maxTime = new Date(new Date('2024-05-08T12:00:00.000Z').getTime() + oneDayInMilliseconds);
131850
- this.state = { rng, minTime, maxTime };
131851
- return;
131852
- }
131853
- if (minTime === undefined) {
131854
- if (maxTime === undefined) {
131855
- minTime = '00:00:00.000Z';
131856
- maxTime = '23:59:59.999Z';
131857
- }
131858
- else {
131859
- minTime = '00:00:00.000Z';
131860
- }
131861
- }
131862
- if (maxTime === undefined) {
131863
- maxTime = '23:59:59.999Z';
131864
- new Date().toISOString();
131865
- }
131866
- const anchorDate = new Date('2024-05-08');
131867
- const anchorDateString0 = anchorDate.toISOString().replace(/T\d{2}:\d{2}:\d{2}.\d{3}Z/, '');
131868
- if (typeof minTime === 'string') {
131869
- // const timeMatch0 = minTime.match(/^\d{2}:\d{2}:\d{2}.\d{1,3}Z?$/);
131870
- const timeMatch1 = minTime.match(/^\d{2}:\d{2}:\d{2}Z?$/);
131871
- const timeMatch2 = minTime.match(/^\d{2}:\d{2}Z?$/);
131872
- if (
131873
- // timeMatch0 === null
131874
- timeMatch1 === null
131875
- && timeMatch2 === null) {
131876
- throw new Error(`You're using the wrong format for the minTime parameter.`
131877
- + `\nPlease use one of these formats: 'HH:mm:ss', 'HH:mm' (with or without a trailing 'Z')`);
131878
- }
131879
- minTime = minTime.at(-1) === 'Z' ? minTime : minTime + 'Z';
131880
- minTime = new Date(anchorDate.toISOString().replace(/\d{2}:\d{2}:\d{2}.\d{3}Z/, minTime));
131881
- }
131882
- if (typeof minTime === 'object') {
131883
- if (!isValidDate(minTime)) {
131884
- throw new Error('Invalid Date was provided for the minTime parameter.');
131885
- }
131886
- minTime = new Date(minTime.toISOString().replace(/\d{4}-\d{2}-\d{2}/, anchorDateString0));
131887
- }
131888
- if (typeof maxTime === 'string') {
131889
- // const timeMatch0 = maxTime.match(/^\d{2}:\d{2}:\d{2}.\d{1,3}Z?$/);
131890
- const timeMatch1 = maxTime.match(/^\d{2}:\d{2}:\d{2}Z?$/);
131891
- const timeMatch2 = maxTime.match(/^\d{2}:\d{2}Z?$/);
131892
- if (
131893
- // timeMatch0 === null
131894
- timeMatch1 === null
131895
- && timeMatch2 === null) {
131896
- throw new Error(`You're using the wrong format for the maxTime parameter.`
131897
- + `\nPlease use one of these formats: 'HH:mm:ss', 'HH:mm' (with or without a trailing 'Z').`);
131898
- }
131899
- maxTime = maxTime.at(-1) === 'Z' ? maxTime : maxTime + 'Z';
131900
- maxTime = new Date(anchorDate.toISOString().replace(/\d{2}:\d{2}:\d{2}.\d{3}Z/, maxTime));
131901
- }
131902
- if (typeof maxTime === 'object') {
131903
- if (!isValidDate(maxTime)) {
131904
- throw new Error('Invalid Date was provided for the maxTime parameter.');
131905
- }
131906
- maxTime = new Date(maxTime.toISOString().replace(/\d{4}-\d{2}-\d{2}/, anchorDateString0));
131907
- }
131908
- if (minTime > maxTime) {
131909
- throw new Error(`The minTime parameter must be less than or equal to the maxTime parameter.`);
131910
- }
131911
- this.state = { rng, minTime, maxTime };
131889
+ this.state = { rng };
131912
131890
  }
131913
131891
  generate() {
131914
131892
  if (this.state === undefined) {
131915
131893
  throw new Error('state is not defined.');
131916
131894
  }
131895
+ const anchorDateTime = new Date('2024-05-08T12:00:00.000Z');
131896
+ const oneDayInMilliseconds = 86400000;
131897
+ let date = new Date();
131917
131898
  let milliseconds;
131918
- [milliseconds, this.state.rng] = prand.uniformIntDistribution(this.state.minTime.getTime(), this.state.maxTime.getTime(), this.state.rng);
131919
- const date = new Date(milliseconds);
131899
+ [milliseconds, this.state.rng] = prand.uniformIntDistribution(-oneDayInMilliseconds, oneDayInMilliseconds, this.state.rng);
131900
+ date = new Date(date.setTime(anchorDateTime.getTime() + milliseconds));
131920
131901
  return date.toISOString().replace(/(\d{4}-\d{2}-\d{2}T)|(\.\d{3}Z)/g, '');
131921
131902
  }
131922
131903
  }
@@ -131926,46 +131907,18 @@ class GenerateTimestamp extends AbstractGenerator {
131926
131907
  init({ count, seed }) {
131927
131908
  super.init({ count, seed });
131928
131909
  const rng = prand.xoroshiro128plus(seed);
131929
- let { minTimestamp, maxTimestamp } = this.params;
131930
- const anchorDate = new Date('2024-05-08');
131931
- // 2 years in milliseconds
131932
- const deltaMilliseconds = 2 * 31536000000;
131933
- if (typeof minTimestamp === 'string') {
131934
- minTimestamp = new Date(minTimestamp);
131935
- }
131936
- if (typeof minTimestamp === 'object' && !isValidDate(minTimestamp)) {
131937
- throw new Error('Invalid Date was provided for the minTimestamp parameter.');
131938
- }
131939
- if (typeof maxTimestamp === 'string') {
131940
- maxTimestamp = new Date(maxTimestamp);
131941
- }
131942
- if (typeof maxTimestamp === 'object' && !isValidDate(maxTimestamp)) {
131943
- throw new Error('Invalid Date was provided for the maxTimestamp parameter.');
131944
- }
131945
- if (minTimestamp === undefined) {
131946
- if (maxTimestamp === undefined) {
131947
- minTimestamp = new Date(anchorDate.getTime() - deltaMilliseconds);
131948
- maxTimestamp = new Date(anchorDate.getTime() + deltaMilliseconds);
131949
- }
131950
- else {
131951
- minTimestamp = new Date(maxTimestamp.getTime() - (2 * deltaMilliseconds));
131952
- }
131953
- }
131954
- if (maxTimestamp === undefined) {
131955
- maxTimestamp = new Date(minTimestamp.getTime() + (2 * deltaMilliseconds));
131956
- }
131957
- if (minTimestamp > maxTimestamp) {
131958
- throw new Error(`The minTimestamp parameter must be less than or equal to the maxTimestamp parameter.`);
131959
- }
131960
- this.state = { rng, minTimestamp, maxTimestamp };
131910
+ this.state = { rng };
131961
131911
  }
131962
131912
  generate() {
131963
131913
  if (this.state === undefined) {
131964
131914
  throw new Error('state is not defined.');
131965
131915
  }
131916
+ const anchorTimestamp = new Date('2024-05-08');
131917
+ const twoYearsInMilliseconds = 2 * 31536000000;
131918
+ let date = new Date();
131966
131919
  let milliseconds;
131967
- [milliseconds, this.state.rng] = prand.uniformIntDistribution(this.state.minTimestamp.getTime(), this.state.maxTimestamp.getTime(), this.state.rng);
131968
- const date = new Date(milliseconds);
131920
+ [milliseconds, this.state.rng] = prand.uniformIntDistribution(-twoYearsInMilliseconds, twoYearsInMilliseconds, this.state.rng);
131921
+ date = new Date(date.setTime(anchorTimestamp.getTime() + milliseconds));
131969
131922
  if (this.dataType === 'string') {
131970
131923
  return date
131971
131924
  .toISOString()
@@ -131981,46 +131934,18 @@ class GenerateDatetime extends AbstractGenerator {
131981
131934
  init({ count, seed }) {
131982
131935
  super.init({ count, seed });
131983
131936
  const rng = prand.xoroshiro128plus(seed);
131984
- let { minDatetime, maxDatetime } = this.params;
131985
- const anchorDate = new Date('2024-05-08');
131986
- // 2 years in milliseconds
131987
- const deltaMilliseconds = 2 * 31536000000;
131988
- if (typeof minDatetime === 'string') {
131989
- minDatetime = new Date(minDatetime);
131990
- }
131991
- if (typeof minDatetime === 'object' && !isValidDate(minDatetime)) {
131992
- throw new Error('Invalid Date was provided for the minDatetime parameter.');
131993
- }
131994
- if (typeof maxDatetime === 'string') {
131995
- maxDatetime = new Date(maxDatetime);
131996
- }
131997
- if (typeof maxDatetime === 'object' && !isValidDate(maxDatetime)) {
131998
- throw new Error('Invalid Date was provided for the maxDatetime parameter.');
131999
- }
132000
- if (minDatetime === undefined) {
132001
- if (maxDatetime === undefined) {
132002
- minDatetime = new Date(anchorDate.getTime() - deltaMilliseconds);
132003
- maxDatetime = new Date(anchorDate.getTime() + deltaMilliseconds);
132004
- }
132005
- else {
132006
- minDatetime = new Date(maxDatetime.getTime() - (2 * deltaMilliseconds));
132007
- }
132008
- }
132009
- if (maxDatetime === undefined) {
132010
- maxDatetime = new Date(minDatetime.getTime() + (2 * deltaMilliseconds));
132011
- }
132012
- if (minDatetime > maxDatetime) {
132013
- throw new Error(`The minDatetime parameter must be less than or equal to the maxDatetime parameter.`);
132014
- }
132015
- this.state = { rng, minDatetime, maxDatetime };
131937
+ this.state = { rng };
132016
131938
  }
132017
131939
  generate() {
132018
131940
  if (this.state === undefined) {
132019
131941
  throw new Error('state is not defined.');
132020
131942
  }
131943
+ const anchorDate = new Date('2024-05-08');
131944
+ const twoYearsInMilliseconds = 2 * 31536000000;
131945
+ let date = new Date();
132021
131946
  let milliseconds;
132022
- [milliseconds, this.state.rng] = prand.uniformIntDistribution(this.state.minDatetime.getTime(), this.state.maxDatetime.getTime(), this.state.rng);
132023
- const date = new Date(milliseconds);
131947
+ [milliseconds, this.state.rng] = prand.uniformIntDistribution(-twoYearsInMilliseconds, twoYearsInMilliseconds, this.state.rng);
131948
+ date = new Date(date.setTime(anchorDate.getTime() + milliseconds));
132024
131949
  if (this.dataType === 'string') {
132025
131950
  return date
132026
131951
  .toISOString()
@@ -132376,8 +132301,8 @@ class GenerateFirstName extends AbstractGenerator {
132376
132301
  init({ count, seed }) {
132377
132302
  super.init({ count, seed });
132378
132303
  const rng = prand.xoroshiro128plus(seed);
132379
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$5) {
132380
- throw new Error(`You can't use first name generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$5}.`);
132304
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$5) {
132305
+ throw new Error(`You can't use first name generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$5}.`);
132381
132306
  }
132382
132307
  this.state = { rng };
132383
132308
  }
@@ -132400,8 +132325,8 @@ class GenerateUniqueFirstName extends AbstractGenerator {
132400
132325
  if (count > firstNames.length) {
132401
132326
  throw new Error('count exceeds max number of unique first names.');
132402
132327
  }
132403
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$5) {
132404
- throw new Error(`You can't use first name generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$5}.`);
132328
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$5) {
132329
+ throw new Error(`You can't use first name generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$5}.`);
132405
132330
  }
132406
132331
  const genIndicesObj = new GenerateUniqueInt({ minValue: 0, maxValue: firstNames.length - 1 });
132407
132332
  genIndicesObj.init({ count, seed });
@@ -132424,8 +132349,8 @@ class GenerateLastName extends AbstractGenerator {
132424
132349
  init({ count, seed }) {
132425
132350
  super.init({ count, seed });
132426
132351
  const rng = prand.xoroshiro128plus(seed);
132427
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$3) {
132428
- throw new Error(`You can't use last name generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$3}.`);
132352
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$3) {
132353
+ throw new Error(`You can't use last name generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$3}.`);
132429
132354
  }
132430
132355
  this.state = { rng };
132431
132356
  }
@@ -132446,8 +132371,8 @@ class GenerateUniqueLastName extends AbstractGenerator {
132446
132371
  if (count > lastNames.length) {
132447
132372
  throw new Error('count exceeds max number of unique last names.');
132448
132373
  }
132449
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$3) {
132450
- throw new Error(`You can't use last name generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$3}.`);
132374
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$3) {
132375
+ throw new Error(`You can't use last name generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$3}.`);
132451
132376
  }
132452
132377
  const genIndicesObj = new GenerateUniqueInt({ minValue: 0, maxValue: lastNames.length - 1 });
132453
132378
  genIndicesObj.init({ count, seed });
@@ -132469,8 +132394,8 @@ class GenerateFullName extends AbstractGenerator {
132469
132394
  init({ count, seed }) {
132470
132395
  super.init({ count, seed });
132471
132396
  const rng = prand.xoroshiro128plus(seed);
132472
- if (this.stringLength !== undefined && this.stringLength < (maxStringLength$5 + maxStringLength$3 + 1)) {
132473
- throw new Error(`You can't use full name generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$5 + maxStringLength$3 + 1}.`);
132397
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < (maxStringLength$5 + maxStringLength$3 + 1)) {
132398
+ throw new Error(`You can't use full name generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$5 + maxStringLength$3 + 1}.`);
132474
132399
  }
132475
132400
  this.state = { rng };
132476
132401
  }
@@ -132498,8 +132423,8 @@ class GenerateUniqueFullName extends AbstractGenerator {
132498
132423
  if (count > maxUniqueFullNamesNumber) {
132499
132424
  throw new RangeError(`count exceeds max number of unique full names(${maxUniqueFullNamesNumber}).`);
132500
132425
  }
132501
- if (this.stringLength !== undefined && this.stringLength < (maxStringLength$5 + maxStringLength$3 + 1)) {
132502
- throw new Error(`You can't use full name generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$5 + maxStringLength$3 + 1}.`);
132426
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < (maxStringLength$5 + maxStringLength$3 + 1)) {
132427
+ throw new Error(`You can't use full name generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$5 + maxStringLength$3 + 1}.`);
132503
132428
  }
132504
132429
  const rng = prand.xoroshiro128plus(seed);
132505
132430
  const fullnameSet = new Set();
@@ -132542,8 +132467,8 @@ class GenerateEmail extends AbstractGenerator {
132542
132467
  throw new RangeError(`count exceeds max number of unique emails(${maxUniqueEmailsNumber}).`);
132543
132468
  }
132544
132469
  const maxEmailLength = maxStringLength$a + maxStringLength$5 + maxStringLength$6 + 2;
132545
- if (this.stringLength !== undefined && this.stringLength < maxEmailLength) {
132546
- throw new Error(`You can't use email generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxEmailLength}.`);
132470
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxEmailLength) {
132471
+ throw new Error(`You can't use email generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxEmailLength}.`);
132547
132472
  }
132548
132473
  const arraysToGenerateFrom = [adjectivesArray, namesArray, domainsArray];
132549
132474
  const genIndicesObj = new GenerateUniqueInt({
@@ -132576,8 +132501,8 @@ class GeneratePhoneNumber extends AbstractGenerator {
132576
132501
  const { prefixes, template } = this.params;
132577
132502
  const rng = prand.xoroshiro128plus(seed);
132578
132503
  if (template !== undefined) {
132579
- if (this.stringLength !== undefined && this.stringLength < template.length) {
132580
- throw new Error(`Length of phone number template is shorter than db column length restriction: ${this.stringLength}.
132504
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < template.length) {
132505
+ throw new Error(`Length of phone number template is shorter than db column length restriction: ${this.typeParams?.length}.
132581
132506
  Set the maximum string length to at least ${template.length}.`);
132582
132507
  }
132583
132508
  const iterArray = [...template.matchAll(/#/g)];
@@ -132622,8 +132547,8 @@ class GeneratePhoneNumber extends AbstractGenerator {
132622
132547
  }
132623
132548
  const maxPrefixLength = Math.max(...prefixesArray.map((prefix) => prefix.length));
132624
132549
  const maxGeneratedDigits = Math.max(...generatedDigitsNumbers);
132625
- if (this.stringLength !== undefined && this.stringLength < (maxPrefixLength + maxGeneratedDigits)) {
132626
- throw new Error(`You can't use phone number generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxPrefixLength + maxGeneratedDigits}.`);
132550
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < (maxPrefixLength + maxGeneratedDigits)) {
132551
+ throw new Error(`You can't use phone number generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxPrefixLength + maxGeneratedDigits}.`);
132627
132552
  }
132628
132553
  if (new Set(prefixesArray).size !== prefixesArray.length) {
132629
132554
  throw new Error('prefixes are not unique.');
@@ -132700,8 +132625,8 @@ class GenerateCountry extends AbstractGenerator {
132700
132625
  init({ count, seed }) {
132701
132626
  super.init({ count, seed });
132702
132627
  const rng = prand.xoroshiro128plus(seed);
132703
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$7) {
132704
- throw new Error(`You can't use country generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$7}.`);
132628
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$7) {
132629
+ throw new Error(`You can't use country generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$7}.`);
132705
132630
  }
132706
132631
  this.state = { rng };
132707
132632
  }
@@ -132723,8 +132648,8 @@ class GenerateUniqueCountry extends AbstractGenerator {
132723
132648
  if (count > countries.length) {
132724
132649
  throw new Error('count exceeds max number of unique countries.');
132725
132650
  }
132726
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$7) {
132727
- throw new Error(`You can't use country generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$7}.`);
132651
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$7) {
132652
+ throw new Error(`You can't use country generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$7}.`);
132728
132653
  }
132729
132654
  const genIndicesObj = new GenerateUniqueInt({ minValue: 0, maxValue: countries.length - 1 });
132730
132655
  genIndicesObj.init({ count, seed });
@@ -132745,8 +132670,8 @@ class GenerateJobTitle extends AbstractGenerator {
132745
132670
  init({ count, seed }) {
132746
132671
  super.init({ count, seed });
132747
132672
  const rng = prand.xoroshiro128plus(seed);
132748
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$4) {
132749
- throw new Error(`You can't use job title generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$4}.`);
132673
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$4) {
132674
+ throw new Error(`You can't use job title generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$4}.`);
132750
132675
  }
132751
132676
  this.state = { rng };
132752
132677
  }
@@ -132768,8 +132693,8 @@ class GenerateStreetAddress extends AbstractGenerator {
132768
132693
  const rng = prand.xoroshiro128plus(seed);
132769
132694
  const possStreetNames = [firstNames, lastNames];
132770
132695
  const maxStreetAddressLength = 4 + Math.max(maxStringLength$5, maxStringLength$3) + 1 + maxStringLength;
132771
- if (this.stringLength !== undefined && this.stringLength < maxStreetAddressLength) {
132772
- throw new Error(`You can't use street address generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStreetAddressLength}.`);
132696
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStreetAddressLength) {
132697
+ throw new Error(`You can't use street address generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStreetAddressLength}.`);
132773
132698
  }
132774
132699
  this.state = { rng, possStreetNames };
132775
132700
  }
@@ -132798,8 +132723,8 @@ class GenerateUniqueStreetAddress extends AbstractGenerator {
132798
132723
  throw new RangeError(`count exceeds max number of unique street names(${maxUniqueStreetnamesNumber}).`);
132799
132724
  }
132800
132725
  const maxStreetAddressLength = 4 + Math.max(maxStringLength$5, maxStringLength$3) + 1 + maxStringLength;
132801
- if (this.stringLength !== undefined && this.stringLength < maxStreetAddressLength) {
132802
- throw new Error(`You can't use street address generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStreetAddressLength}.`);
132726
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStreetAddressLength) {
132727
+ throw new Error(`You can't use street address generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStreetAddressLength}.`);
132803
132728
  }
132804
132729
  const rng = prand.xoroshiro128plus(seed);
132805
132730
  // ["1", "2", ..., "999"]
@@ -132855,8 +132780,8 @@ class GenerateCity extends AbstractGenerator {
132855
132780
  init({ count, seed }) {
132856
132781
  super.init({ count, seed });
132857
132782
  const rng = prand.xoroshiro128plus(seed);
132858
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$9) {
132859
- throw new Error(`You can't use city generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$9}.`);
132783
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$9) {
132784
+ throw new Error(`You can't use city generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$9}.`);
132860
132785
  }
132861
132786
  this.state = { rng };
132862
132787
  }
@@ -132877,8 +132802,8 @@ class GenerateUniqueCity extends AbstractGenerator {
132877
132802
  if (count > cityNames.length) {
132878
132803
  throw new Error('count exceeds max number of unique cities.');
132879
132804
  }
132880
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$9) {
132881
- throw new Error(`You can't use city generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$9}.`);
132805
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$9) {
132806
+ throw new Error(`You can't use city generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$9}.`);
132882
132807
  }
132883
132808
  const genIndicesObj = new GenerateUniqueInt({ minValue: 0, maxValue: cityNames.length - 1 });
132884
132809
  genIndicesObj.init({ count, seed });
@@ -132902,8 +132827,8 @@ class GeneratePostcode extends AbstractGenerator {
132902
132827
  const rng = prand.xoroshiro128plus(seed);
132903
132828
  const templates = ['#####', '#####-####'];
132904
132829
  const maxPostcodeLength = Math.max(...templates.map((template) => template.length));
132905
- if (this.stringLength !== undefined && this.stringLength < maxPostcodeLength) {
132906
- throw new Error(`You can't use postcode generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxPostcodeLength}.`);
132830
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxPostcodeLength) {
132831
+ throw new Error(`You can't use postcode generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxPostcodeLength}.`);
132907
132832
  }
132908
132833
  this.state = { rng, templates };
132909
132834
  }
@@ -132953,8 +132878,8 @@ class GenerateUniquePostcode extends AbstractGenerator {
132953
132878
  },
132954
132879
  ];
132955
132880
  const maxPostcodeLength = Math.max(...templates.map((template) => template.template.length));
132956
- if (this.stringLength !== undefined && this.stringLength < maxPostcodeLength) {
132957
- throw new Error(`You can't use postcode generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxPostcodeLength}.`);
132881
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxPostcodeLength) {
132882
+ throw new Error(`You can't use postcode generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxPostcodeLength}.`);
132958
132883
  }
132959
132884
  for (const templateObj of templates) {
132960
132885
  templateObj.indicesGen.skipCheck = true;
@@ -132990,8 +132915,8 @@ class GenerateState extends AbstractGenerator {
132990
132915
  init({ count, seed }) {
132991
132916
  super.init({ count, seed });
132992
132917
  const rng = prand.xoroshiro128plus(seed);
132993
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$1) {
132994
- throw new Error(`You can't use state generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$1}.`);
132918
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$1) {
132919
+ throw new Error(`You can't use state generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$1}.`);
132995
132920
  }
132996
132921
  this.state = { rng };
132997
132922
  }
@@ -133019,8 +132944,8 @@ class GenerateCompanyName extends AbstractGenerator {
133019
132944
  ];
133020
132945
  // max( { template: '#', placeholdersCount: 1 }, { template: '#, # and #', placeholdersCount: 3 } )
133021
132946
  const maxCompanyNameLength = Math.max(maxStringLength$3 + maxStringLength$8 + 1, 3 * maxStringLength$3 + 7);
133022
- if (this.stringLength !== undefined && this.stringLength < maxCompanyNameLength) {
133023
- throw new Error(`You can't use company name generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxCompanyNameLength}.`);
132947
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxCompanyNameLength) {
132948
+ throw new Error(`You can't use company name generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxCompanyNameLength}.`);
133024
132949
  }
133025
132950
  this.state = { rng, templates };
133026
132951
  }
@@ -133064,8 +132989,8 @@ class GenerateUniqueCompanyName extends AbstractGenerator {
133064
132989
  }
133065
132990
  // max( { template: '#', placeholdersCount: 1 }, { template: '#, # and #', placeholdersCount: 3 } )
133066
132991
  const maxCompanyNameLength = Math.max(maxStringLength$3 + maxStringLength$8 + 1, 3 * maxStringLength$3 + 7);
133067
- if (this.stringLength !== undefined && this.stringLength < maxCompanyNameLength) {
133068
- throw new Error(`You can't use company name generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxCompanyNameLength}.`);
132992
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxCompanyNameLength) {
132993
+ throw new Error(`You can't use company name generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxCompanyNameLength}.`);
133069
132994
  }
133070
132995
  const rng = prand.xoroshiro128plus(seed);
133071
132996
  // when count reach maxUniqueCompanyNameNumber template will be deleted from array
@@ -133141,8 +133066,8 @@ class GenerateLoremIpsum extends AbstractGenerator {
133141
133066
  this.params.sentencesCount = 1;
133142
133067
  const maxLoremIpsumSentencesLength = maxStringLength$2 * this.params.sentencesCount + this.params.sentencesCount
133143
133068
  - 1;
133144
- if (this.stringLength !== undefined && this.stringLength < maxLoremIpsumSentencesLength) {
133145
- throw new Error(`You can't use lorem ipsum generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxLoremIpsumSentencesLength}.`);
133069
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxLoremIpsumSentencesLength) {
133070
+ throw new Error(`You can't use lorem ipsum generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxLoremIpsumSentencesLength}.`);
133146
133071
  }
133147
133072
  this.state = { rng };
133148
133073
  }
@@ -133248,6 +133173,7 @@ class GenerateUniquePoint extends AbstractGenerator {
133248
133173
  state;
133249
133174
  isUnique = true;
133250
133175
  init({ count, seed }) {
133176
+ // TODO: rewrite the unique generator to use fastCartesianProduct for generating unique points.
133251
133177
  const xCoordinateGen = new GenerateUniqueNumber({
133252
133178
  minValue: this.params.minXValue,
133253
133179
  maxValue: this.params.maxXValue,
@@ -133334,6 +133260,7 @@ class GenerateUniqueLine extends AbstractGenerator {
133334
133260
  state;
133335
133261
  isUnique = true;
133336
133262
  init({ count, seed }) {
133263
+ // TODO: rewrite the unique generator to use fastCartesianProduct for generating unique triplets(liens).
133337
133264
  const aCoefficientGen = new GenerateUniqueNumber({
133338
133265
  minValue: this.params.minAValue,
133339
133266
  maxValue: this.params.maxAValue,
@@ -133377,6 +133304,397 @@ class GenerateUniqueLine extends AbstractGenerator {
133377
133304
  }
133378
133305
  }
133379
133306
  }
133307
+ class GenerateBitString extends AbstractGenerator {
133308
+ static entityKind = 'GenerateBitString';
133309
+ dimensions = 11;
133310
+ state;
133311
+ uniqueVersionOfGen = GenerateUniqueBitString;
133312
+ init({ count, seed }) {
133313
+ super.init({ count, seed });
133314
+ this.dimensions = this.params.dimensions ?? this.typeParams?.length ?? this.dimensions;
133315
+ let intGen;
133316
+ if (this.dimensions > 53) {
133317
+ const maxValue = (BigInt(2) ** BigInt(this.dimensions)) - BigInt(1);
133318
+ intGen = new GenerateInt({ minValue: BigInt(0), maxValue });
133319
+ }
133320
+ else {
133321
+ // dimensions <= 53
133322
+ const maxValue = Math.pow(2, this.dimensions) - 1;
133323
+ intGen = new GenerateInt({ minValue: 0, maxValue });
133324
+ }
133325
+ intGen.init({ count, seed });
133326
+ this.state = { intGen };
133327
+ }
133328
+ generate() {
133329
+ if (this.state === undefined) {
133330
+ throw new Error('state is not defined.');
133331
+ }
133332
+ const bitString = this.state.intGen.generate().toString(2);
133333
+ return bitString.padStart(this.dimensions, '0');
133334
+ }
133335
+ }
133336
+ class GenerateUniqueBitString extends AbstractGenerator {
133337
+ static entityKind = 'GenerateUniqueBitString';
133338
+ dimensions = 11;
133339
+ state;
133340
+ isUnique = true;
133341
+ init({ count, seed }) {
133342
+ this.dimensions = this.params.dimensions ?? this.typeParams?.length ?? this.dimensions;
133343
+ let intGen;
133344
+ if (this.dimensions > 53) {
133345
+ const maxValue = (BigInt(2) ** BigInt(this.dimensions)) - BigInt(1);
133346
+ intGen = new GenerateUniqueInt({ minValue: BigInt(0), maxValue });
133347
+ }
133348
+ else {
133349
+ // dimensions <= 53
133350
+ const maxValue = Math.pow(2, this.dimensions) - 1;
133351
+ intGen = new GenerateUniqueInt({ minValue: 0, maxValue });
133352
+ }
133353
+ intGen.init({ count, seed });
133354
+ this.state = { intGen };
133355
+ }
133356
+ generate() {
133357
+ if (this.state === undefined) {
133358
+ throw new Error('state is not defined.');
133359
+ }
133360
+ const bitString = this.state.intGen.generate().toString(2);
133361
+ return bitString.padStart(this.dimensions, '0');
133362
+ }
133363
+ }
133364
+ class GenerateInet extends AbstractGenerator {
133365
+ static entityKind = 'GenerateInet';
133366
+ ipAddress = 'ipv4';
133367
+ includeCidr = true;
133368
+ state;
133369
+ uniqueVersionOfGen = GenerateUniqueInet;
133370
+ init({ count, seed }) {
133371
+ super.init({ count, seed });
133372
+ this.ipAddress = this.params.ipAddress ?? this.ipAddress;
133373
+ this.includeCidr = this.params.includeCidr ?? this.includeCidr;
133374
+ const rng = prand.xoroshiro128plus(seed);
133375
+ this.state = { rng };
133376
+ }
133377
+ generate() {
133378
+ if (this.state === undefined) {
133379
+ throw new Error('state is not defined.');
133380
+ }
133381
+ let value;
133382
+ const values = [];
133383
+ let inetVal = '';
133384
+ if (this.ipAddress === 'ipv4') {
133385
+ for (let octet = 0; octet < 4; octet++) {
133386
+ [value, this.state.rng] = prand.uniformIntDistribution(0, 255, this.state.rng);
133387
+ values.push(value.toString());
133388
+ }
133389
+ inetVal += values.join('.');
133390
+ if (this.includeCidr) {
133391
+ [value, this.state.rng] = prand.uniformIntDistribution(0, 32, this.state.rng);
133392
+ inetVal += `/${value}`;
133393
+ }
133394
+ return inetVal;
133395
+ }
133396
+ else {
133397
+ // this.ipAddress === 'ipv6'
133398
+ for (let hextet = 0; hextet < 8; hextet++) {
133399
+ [value, this.state.rng] = prand.uniformIntDistribution(0, 65535, this.state.rng);
133400
+ values.push(value.toString(16));
133401
+ }
133402
+ inetVal += values.join(':');
133403
+ if (this.includeCidr) {
133404
+ [value, this.state.rng] = prand.uniformIntDistribution(0, 128, this.state.rng);
133405
+ inetVal += `/${value}`;
133406
+ }
133407
+ return inetVal;
133408
+ }
133409
+ }
133410
+ }
133411
+ // TODO: add defaults to js doc
133412
+ class GenerateUniqueInet extends AbstractGenerator {
133413
+ static entityKind = 'GenerateUniqueInet';
133414
+ ipAddress = 'ipv4';
133415
+ includeCidr = true;
133416
+ delimiter = '.';
133417
+ state;
133418
+ isUnique = true;
133419
+ init({ count, seed }) {
133420
+ this.ipAddress = this.params.ipAddress ?? this.ipAddress;
133421
+ this.delimiter = this.ipAddress === 'ipv4' ? '.' : ':';
133422
+ this.includeCidr = this.params.includeCidr ?? this.includeCidr;
133423
+ // maxValue - number of combinations for cartesian product: {0…255} × {0…255} × {0…255} × {0…255} × {0…32}
133424
+ // where pattern for ipv4 ip is {0–255}.{0–255}.{0–255}.{0–255}[/{0–32}?]
133425
+ // or number of combinations for cartesian product: {0…65535} × {0…65535} × {0…65535} × {0…65535} × {0…65535} × {0…65535} × {0…65535} × {0…65535} × {0…128}
133426
+ // where pattern for ipv6 ip is {0-65535}:{0-65535}:{0-65535}:{0-65535}:{0-65535}:{0-65535}:{0-65535}:{0-65535}[/0-128?]
133427
+ let minValue, maxValue;
133428
+ if (this.ipAddress === 'ipv4') {
133429
+ minValue = 0;
133430
+ maxValue = 256 ** 4;
133431
+ if (this.includeCidr) {
133432
+ maxValue = maxValue * 33;
133433
+ }
133434
+ }
133435
+ else {
133436
+ // this.ipAddress === 'ipv6'
133437
+ minValue = BigInt(0);
133438
+ maxValue = BigInt(65535) ** BigInt(8);
133439
+ if (this.includeCidr) {
133440
+ maxValue = maxValue * BigInt(129);
133441
+ }
133442
+ }
133443
+ const indexGen = new GenerateUniqueInt({ minValue, maxValue });
133444
+ indexGen.init({ count, seed });
133445
+ const octetSet = Array.from({ length: 256 }, (_, i) => i.toString());
133446
+ const ipv4PrefixSet = Array.from({ length: 33 }, (_, i) => i.toString());
133447
+ const hextetSet = Array.from({ length: 65536 }, (_, i) => i.toString(16));
133448
+ const ipv6PrefixSet = Array.from({ length: 129 }, (_, i) => i.toString());
133449
+ this.state = { indexGen, octetSet, ipv4PrefixSet, hextetSet, ipv6PrefixSet };
133450
+ }
133451
+ generate() {
133452
+ if (this.state === undefined) {
133453
+ throw new Error('state is not defined.');
133454
+ }
133455
+ let inetVal = '';
133456
+ let tokens = [];
133457
+ if (this.ipAddress === 'ipv4') {
133458
+ const sets = Array.from({ length: 4 }).fill(this.state.octetSet);
133459
+ if (this.includeCidr)
133460
+ sets.push(this.state.ipv4PrefixSet);
133461
+ const index = this.state.indexGen.generate();
133462
+ tokens = fastCartesianProduct(sets, index);
133463
+ }
133464
+ else {
133465
+ // this.ipAddress === 'ipv6'
133466
+ const sets = Array.from({ length: 8 }).fill(this.state.hextetSet);
133467
+ if (this.includeCidr)
133468
+ sets.push(this.state.ipv6PrefixSet);
133469
+ const idx = this.state.indexGen.generate();
133470
+ tokens = fastCartesianProductForBigint(sets, idx);
133471
+ }
133472
+ inetVal = this.includeCidr
133473
+ ? tokens.slice(0, -1).join(this.delimiter) + `/${tokens.at(-1)}`
133474
+ : tokens.join(this.delimiter);
133475
+ return inetVal;
133476
+ }
133477
+ }
133478
+ class GenerateGeometry extends AbstractGenerator {
133479
+ static entityKind = 'GenerateGeometry';
133480
+ type = 'point';
133481
+ srid = 4326;
133482
+ decimalPlaces = 6;
133483
+ state;
133484
+ uniqueVersionOfGen = GenerateUniqueGeometry;
133485
+ init({ count, seed }) {
133486
+ super.init({ count, seed });
133487
+ this.type = this.params.type ?? this.type;
133488
+ this.srid = this.params.srid ?? this.srid;
133489
+ this.decimalPlaces = this.params.decimalPlaces ?? this.decimalPlaces;
133490
+ let minXValue, maxXValue, minYValue, maxYValue, denominator;
133491
+ if (this.type === 'point') {
133492
+ if (this.srid === 4326) {
133493
+ // Degrees (latitude / longitude)
133494
+ denominator = 10 ** this.decimalPlaces;
133495
+ minXValue = -180 * denominator;
133496
+ maxXValue = 180 * denominator;
133497
+ minYValue = -90 * denominator;
133498
+ maxYValue = 90 * denominator;
133499
+ }
133500
+ else {
133501
+ // this.srid === 3857
133502
+ // Meters (projected X / Y)
133503
+ denominator = 1;
133504
+ minXValue = -20026376;
133505
+ maxXValue = 20026376;
133506
+ minYValue = -20048966;
133507
+ maxYValue = 20048966;
133508
+ }
133509
+ }
133510
+ else {
133511
+ throw new Error('geometry generator currently supports only the point type.');
133512
+ }
133513
+ const rng = prand.xoroshiro128plus(seed);
133514
+ this.state = { rng, minXValue, maxXValue, minYValue, maxYValue, denominator };
133515
+ }
133516
+ generate() {
133517
+ if (this.state === undefined) {
133518
+ throw new Error('state is not defined.');
133519
+ }
133520
+ let x, y;
133521
+ [x, this.state.rng] = prand.uniformIntDistribution(this.state.minXValue, this.state.maxXValue, this.state.rng);
133522
+ x = x / this.state.denominator;
133523
+ [y, this.state.rng] = prand.uniformIntDistribution(this.state.minYValue, this.state.maxYValue, this.state.rng);
133524
+ y = y / this.state.denominator;
133525
+ if (this.dataType === 'array') {
133526
+ return [x, y];
133527
+ }
133528
+ // this.dataType === 'object'
133529
+ return { x, y };
133530
+ }
133531
+ }
133532
+ class GenerateUniqueGeometry extends AbstractGenerator {
133533
+ static entityKind = 'GenerateUniqueGeometry';
133534
+ type = 'point';
133535
+ srid = 4326;
133536
+ decimalPlaces = 6;
133537
+ state;
133538
+ isUnique = true;
133539
+ init({ count, seed }) {
133540
+ this.type = this.params.type ?? this.type;
133541
+ this.srid = this.params.srid ?? this.srid;
133542
+ this.decimalPlaces = this.params.decimalPlaces ?? this.decimalPlaces;
133543
+ let minXValue, maxXValue, minYValue, maxYValue, denominator;
133544
+ if (this.type === 'point') {
133545
+ if (this.srid === 4326) {
133546
+ // Degrees (latitude / longitude)
133547
+ denominator = 10 ** this.decimalPlaces;
133548
+ minXValue = -180 * denominator;
133549
+ maxXValue = 180 * denominator;
133550
+ minYValue = -90 * denominator;
133551
+ maxYValue = 90 * denominator;
133552
+ }
133553
+ else {
133554
+ // this.srid === 3857
133555
+ // Meters (projected X / Y)
133556
+ denominator = 1;
133557
+ minXValue = -20026376;
133558
+ maxXValue = 20026376;
133559
+ minYValue = -20048966;
133560
+ maxYValue = 20048966;
133561
+ }
133562
+ }
133563
+ else {
133564
+ throw new Error('geometry generator currently supports only the point type.');
133565
+ }
133566
+ const xRange = new OrderedNumberRange(minXValue, maxXValue, 1);
133567
+ const yRange = new OrderedNumberRange(minYValue, maxYValue, 1);
133568
+ const xySets = [xRange, yRange];
133569
+ const maxCombIdx = BigInt(maxXValue - minXValue + 1) * BigInt(maxYValue - minYValue + 1) - BigInt(1);
133570
+ const indexGen = maxCombIdx <= 2 ** 53
133571
+ ? new GenerateUniqueInt({ minValue: 0, maxValue: Number(maxCombIdx) })
133572
+ : new GenerateUniqueInt({ minValue: BigInt(0), maxValue: maxCombIdx });
133573
+ indexGen.init({ count, seed });
133574
+ this.state = { denominator, indexGen, xySets };
133575
+ }
133576
+ generate() {
133577
+ if (this.state === undefined) {
133578
+ throw new Error('state is not defined.');
133579
+ }
133580
+ const idx = this.state.indexGen.generate();
133581
+ let x, y;
133582
+ if (typeof idx === 'number') {
133583
+ [x, y] = fastCartesianProduct(this.state.xySets, idx);
133584
+ }
133585
+ else {
133586
+ // typeof idx === 'bigint'
133587
+ [x, y] = fastCartesianProductForBigint(this.state.xySets, idx);
133588
+ }
133589
+ if (this.dataType === 'array') {
133590
+ return [x, y];
133591
+ }
133592
+ // this.dataType === 'object'
133593
+ return { x, y };
133594
+ }
133595
+ }
133596
+ class GenerateVector extends AbstractGenerator {
133597
+ static entityKind = 'GenerateVector';
133598
+ // property below should be overridden in init
133599
+ dimensions = 3;
133600
+ minValue = -1000;
133601
+ maxValue = 1000;
133602
+ decimalPlaces = 2;
133603
+ state;
133604
+ uniqueVersionOfGen = GenerateUniqueVector;
133605
+ init({ count, seed }) {
133606
+ super.init({ count, seed });
133607
+ this.dimensions = this.params.dimensions ?? this.typeParams.length ?? this.dimensions;
133608
+ this.decimalPlaces = this.params.decimalPlaces ?? this.decimalPlaces;
133609
+ this.minValue = this.params.minValue ?? this.minValue;
133610
+ this.maxValue = this.params.maxValue ?? this.maxValue;
133611
+ if (this.minValue > this.maxValue) {
133612
+ throw new Error(`minValue ( ${this.minValue} ) cannot be greater than maxValue ( ${this.maxValue} ).\n`
133613
+ + `Did you forget to pass both minValue and maxValue to the generator's properties?`);
133614
+ }
133615
+ if (this.decimalPlaces < 0) {
133616
+ throw new Error(`decimalPlaces value must be greater than or equal to zero.`);
133617
+ }
133618
+ if (abs(BigInt(this.minValue) * BigInt(10 ** this.decimalPlaces)) > Number.MAX_SAFE_INTEGER
133619
+ || abs(BigInt(this.maxValue) * BigInt(10 ** this.decimalPlaces)) > Number.MAX_SAFE_INTEGER) {
133620
+ console.warn(`vector generator: minValue or maxValue multiplied by 10^decimalPlaces exceeds Number.MAX_SAFE_INTEGER (2^53 -1).\n`
133621
+ + `This overflow may result in less accurate values being generated.`);
133622
+ }
133623
+ // `numberGen` is initialized in the `init` method of `GenerateArray`
133624
+ const numberGen = new GenerateNumber({
133625
+ minValue: this.minValue,
133626
+ maxValue: this.maxValue,
133627
+ precision: 10 ** this.decimalPlaces,
133628
+ });
133629
+ const vectorGen = new GenerateArray({ baseColumnGen: numberGen, size: this.dimensions });
133630
+ vectorGen.init({ count, seed });
133631
+ this.state = { vectorGen };
133632
+ }
133633
+ generate() {
133634
+ if (this.state === undefined) {
133635
+ throw new Error('state is not defined.');
133636
+ }
133637
+ const vectorVal = this.state.vectorGen.generate();
133638
+ return vectorVal;
133639
+ }
133640
+ }
133641
+ class GenerateUniqueVector extends AbstractGenerator {
133642
+ static entityKind = 'GenerateUniqueVector';
133643
+ // property below should be overridden in init
133644
+ dimensions = 3;
133645
+ minValue = -1000;
133646
+ maxValue = 1000;
133647
+ decimalPlaces = 2;
133648
+ state;
133649
+ isUnique = true;
133650
+ init({ count, seed }) {
133651
+ this.dimensions = this.params.dimensions ?? this.typeParams.length ?? this.dimensions;
133652
+ this.decimalPlaces = this.params.decimalPlaces ?? this.decimalPlaces;
133653
+ const denominator = 10 ** this.decimalPlaces;
133654
+ this.minValue = this.params.minValue ?? this.minValue;
133655
+ this.maxValue = this.params.maxValue ?? this.maxValue;
133656
+ if (this.minValue > this.maxValue) {
133657
+ throw new Error(`minValue ( ${this.minValue} ) cannot be greater than maxValue ( ${this.maxValue} ).\n`
133658
+ + `Did you forget to pass both minValue and maxValue to the generator's properties?`);
133659
+ }
133660
+ if (this.decimalPlaces < 0) {
133661
+ throw new Error(`decimalPlaces value must be greater than or equal to zero.`);
133662
+ }
133663
+ if (abs(BigInt(this.minValue) * BigInt(denominator)) > Number.MAX_SAFE_INTEGER
133664
+ || abs(BigInt(this.maxValue) * BigInt(denominator)) > Number.MAX_SAFE_INTEGER) {
133665
+ console.warn(`vector generator: minValue or maxValue multiplied by 10^decimalPlaces exceeds Number.MAX_SAFE_INTEGER (2^53 -1).\n`
133666
+ + `This overflow may result in less accurate values being generated.`);
133667
+ }
133668
+ const dimensionRange = new OrderedNumberRange(this.minValue * denominator, this.maxValue * denominator, 1);
133669
+ const vectorSets = Array.from({ length: this.dimensions }).fill(dimensionRange);
133670
+ const maxCombIdx = vectorSets.reduce((acc, curr) => acc * BigInt(curr.length), BigInt(1)) - BigInt(1);
133671
+ const indexGen = maxCombIdx <= Number.MAX_SAFE_INTEGER
133672
+ ? new GenerateUniqueInt({ minValue: 0, maxValue: Number(maxCombIdx) })
133673
+ : new GenerateUniqueInt({ minValue: BigInt(0), maxValue: maxCombIdx });
133674
+ indexGen.init({ count, seed });
133675
+ const transformVector = denominator === 1
133676
+ ? (_vector, _denominator) => { }
133677
+ : (vector, denominator) => {
133678
+ for (let i = 0; i < vector.length; i++) {
133679
+ vector[i] = vector[i] / denominator;
133680
+ }
133681
+ return;
133682
+ };
133683
+ this.state = { indexGen, vectorSets, denominator, transformVector };
133684
+ }
133685
+ generate() {
133686
+ if (this.state === undefined) {
133687
+ throw new Error('state is not defined.');
133688
+ }
133689
+ const idx = this.state.indexGen.generate();
133690
+ const vector = typeof idx === 'number'
133691
+ ? fastCartesianProduct(this.state.vectorSets, idx)
133692
+ // typeof idx === 'bigint'
133693
+ : fastCartesianProductForBigint(this.state.vectorSets, idx);
133694
+ this.state.transformVector(vector, this.state.denominator);
133695
+ return vector;
133696
+ }
133697
+ }
133380
133698
 
133381
133699
  /* eslint-disable drizzle-internal/require-entity-kind */
133382
133700
  class GenerateUniqueIntervalV2 extends AbstractGenerator {
@@ -133463,8 +133781,8 @@ class GenerateStringV2 extends AbstractGenerator {
133463
133781
  super.init({ count, seed });
133464
133782
  let minStringLength = 7;
133465
133783
  let maxStringLength = 20;
133466
- if (this.stringLength !== undefined) {
133467
- maxStringLength = this.stringLength;
133784
+ if (this.typeParams?.length !== undefined) {
133785
+ maxStringLength = this.typeParams?.length;
133468
133786
  if (maxStringLength === 1)
133469
133787
  minStringLength = maxStringLength;
133470
133788
  if (maxStringLength < minStringLength)
@@ -133486,6 +133804,8 @@ class GenerateStringV2 extends AbstractGenerator {
133486
133804
  [idx, this.state.rng] = prand.uniformIntDistribution(0, stringChars.length - 1, this.state.rng);
133487
133805
  currStr += stringChars[idx];
133488
133806
  }
133807
+ if (this.dataType === 'buffer')
133808
+ return Buffer.from(currStr);
133489
133809
  return currStr;
133490
133810
  }
133491
133811
  }
@@ -133499,8 +133819,8 @@ class GenerateUniqueStringV2 extends AbstractGenerator {
133499
133819
  let minStringLength = 7;
133500
133820
  let maxStringLength = 20;
133501
133821
  // TODO: revise later
133502
- if (this.stringLength !== undefined) {
133503
- maxStringLength = this.stringLength;
133822
+ if (this.typeParams?.length !== undefined) {
133823
+ maxStringLength = this.typeParams?.length;
133504
133824
  if (maxStringLength === 1 || maxStringLength < minStringLength)
133505
133825
  minStringLength = maxStringLength;
133506
133826
  }
@@ -133693,8 +134013,6 @@ const generatorsFuncs = {
133693
134013
  date: createGenerator(GenerateDate),
133694
134014
  /**
133695
134015
  * generates time in 24 hours style.
133696
- * @param minTime - lower border of range.
133697
- * @param maxTime - upper border of range.
133698
134016
  * @param arraySize - number of elements in each one-dimensional array. (If specified, arrays will be generated.)
133699
134017
  *
133700
134018
  * @example
@@ -133702,7 +134020,7 @@ const generatorsFuncs = {
133702
134020
  * await seed(db, schema, { count: 1000 }).refine((funcs) => ({
133703
134021
  * users: {
133704
134022
  * columns: {
133705
- * birthTime: funcs.time({ minTime: "11:12:13.141", maxTime: "15:16:17.181" })
134023
+ * birthTime: funcs.time()
133706
134024
  * },
133707
134025
  * },
133708
134026
  * }));
@@ -133712,8 +134030,6 @@ const generatorsFuncs = {
133712
134030
  time: createGenerator(GenerateTime),
133713
134031
  /**
133714
134032
  * generates timestamps.
133715
- * @param minTimestamp - lower border of range.
133716
- * @param maxTimestamp - upper border of range.
133717
134033
  * @param arraySize - number of elements in each one-dimensional array. (If specified, arrays will be generated.)
133718
134034
  *
133719
134035
  * @example
@@ -133721,7 +134037,7 @@ const generatorsFuncs = {
133721
134037
  * await seed(db, schema, { count: 1000 }).refine((funcs) => ({
133722
134038
  * orders: {
133723
134039
  * columns: {
133724
- * shippedDate: funcs.timestamp({ minTimestamp: "2025-03-07T11:12:13.141", maxTimestamp: "2025-03-08T15:16:17.181" })
134040
+ * shippedDate: funcs.timestamp()
133725
134041
  * },
133726
134042
  * },
133727
134043
  * }));
@@ -133731,8 +134047,6 @@ const generatorsFuncs = {
133731
134047
  timestamp: createGenerator(GenerateTimestamp),
133732
134048
  /**
133733
134049
  * generates datetime objects.
133734
- * @param minDatetime - lower border of range.
133735
- * @param maxDatetime - upper border of range.
133736
134050
  * @param arraySize - number of elements in each one-dimensional array. (If specified, arrays will be generated.)
133737
134051
  *
133738
134052
  * @example
@@ -133740,7 +134054,7 @@ const generatorsFuncs = {
133740
134054
  * await seed(db, schema, { count: 1000 }).refine((funcs) => ({
133741
134055
  * orders: {
133742
134056
  * columns: {
133743
- * shippedDate: funcs.datetime({ minDatetime: "2025-03-07T11:12:13.141", maxDatetime: "2025-03-08T15:16:17.181" })
134057
+ * shippedDate: funcs.datetime()
133744
134058
  * },
133745
134059
  * },
133746
134060
  * }));
@@ -134200,8 +134514,132 @@ const generatorsFuncs = {
134200
134514
  * ```
134201
134515
  */
134202
134516
  weightedRandom: createGenerator(WeightedRandomGenerator),
134517
+ /**
134518
+ * generates bit strings based on specified parameters
134519
+ *
134520
+ * @param isUnique - property that controls if generated values gonna be unique or not.
134521
+ * @param arraySize - number of elements in each one-dimensional array (If specified, arrays will be generated).
134522
+ * @param dimensions - desired length of each bit string (e.g., `dimensions = 3` produces values like `'010'`).
134523
+ *
134524
+ * Defaults to the value of the database column bit-length.
134525
+ *
134526
+ * @example
134527
+ * ```ts
134528
+ * await seed(db, { bitStringTable: schema.bitStringTable }).refine((funcs) => ({
134529
+ * bitStringTable: {
134530
+ * count,
134531
+ * columns: {
134532
+ * bit: funcs.bitString({
134533
+ * dimensions: 12,
134534
+ * isUnique: true
134535
+ * }),
134536
+ * },
134537
+ * },
134538
+ * }));
134539
+ * ```
134540
+ */
134541
+ bitString: createGenerator(GenerateBitString),
134542
+ /**
134543
+ * generates ip addresses based on specified parameters
134544
+ *
134545
+ * @param isUnique - property that controls if generated values gonna be unique or not.
134546
+ * @param arraySize - number of elements in each one-dimensional array (If specified, arrays will be generated).
134547
+ * @param ipAddress - type of IP address to generate — either "ipv4" or "ipv6".
134548
+ *
134549
+ * Defaults to `'ipv4'`.
134550
+ * @param includeCidr - determines whether generated IPs include a CIDR suffix.
134551
+ *
134552
+ * Defaults to `true`.
134553
+ *
134554
+ * @example
134555
+ * ```ts
134556
+ * await seed(db, { inetTable: schema.inetTable }).refine((funcs) => ({
134557
+ * inetTable: {
134558
+ * count,
134559
+ * columns: {
134560
+ * inet: funcs.inet({
134561
+ * ipAddress: 'ipv4',
134562
+ * includeCidr: true,
134563
+ * isUnique: true
134564
+ * }),
134565
+ * },
134566
+ * },
134567
+ * }));
134568
+ * ```
134569
+ */
134570
+ inet: createGenerator(GenerateInet),
134571
+ /**
134572
+ * generates PostGIS geometry objects based on the given parameters.
134573
+ *
134574
+ * @param isUnique - property that controls if generated values gonna be unique or not.
134575
+ * @param arraySize - number of elements in each one-dimensional array (If specified, arrays will be generated).
134576
+ * @param type - geometry type to generate; currently only `'point'` is supported.
134577
+ *
134578
+ * Defaults to `'point'`.
134579
+ * @param srid - Spatial Reference System Identifier: determines what type of point will be generated - either `4326` or `3857`.
134580
+ *
134581
+ * Defaults to `4326`.
134582
+ * @param decimalPlaces - number of decimal places for points when `srid` is `4326` (e.g., `decimalPlaces = 3` produces values like `'point(30.723 46.482)'`).
134583
+ *
134584
+ * Defaults to `6`.
134585
+ *
134586
+ * @example
134587
+ * ```ts
134588
+ * await seed(db, { geometryTable: schema.geometryTable }).refine((funcs) => ({
134589
+ * geometryTable: {
134590
+ * count,
134591
+ * columns: {
134592
+ * geometryPointTuple: funcs.geometry({
134593
+ * type: 'point',
134594
+ * srid: 4326,
134595
+ * decimalPlaces: 5,
134596
+ * isUnique: true
134597
+ * })
134598
+ * },
134599
+ * },
134600
+ * }));
134601
+ * ```
134602
+ */
134603
+ geometry: createGenerator(GenerateGeometry),
134604
+ /**
134605
+ * generates vectors based on the provided parameters.
134606
+ *
134607
+ * @param isUnique - property that controls if generated values gonna be unique or not.
134608
+ * @param arraySize - number of elements in each one-dimensional array (If specified, arrays will be generated).
134609
+ * @param decimalPlaces - number of decimal places for each vector element (e.g., `decimalPlaces = 3` produces values like `1.123`).
134610
+ *
134611
+ * Defaults to `2`.
134612
+ * @param dimensions - number of elements in each generated vector (e.g., `dimensions = 3` produces values like `[1,2,3]`).
134613
+ *
134614
+ * Defaults to the value of the database column’s dimensions.
134615
+ * @param minValue - minimum allowed value for each vector element.
134616
+ *
134617
+ * Defaults to `-1000`.
134618
+ * @param maxValue - maximum allowed value for each vector element.
134619
+ *
134620
+ * Defaults to `1000`.
134621
+ *
134622
+ * @example
134623
+ * ```ts
134624
+ * await seed(db, { vectorTable: schema.vectorTable }).refine((funcs) => ({
134625
+ * vectorTable: {
134626
+ * count,
134627
+ * columns: {
134628
+ * vector: funcs.vector({
134629
+ * decimalPlaces: 5,
134630
+ * dimensions: 12,
134631
+ * minValue: -100,
134632
+ * maxValue: 100,
134633
+ * isUnique: true
134634
+ * }),
134635
+ * },
134636
+ * },
134637
+ * }));
134638
+ * ```
134639
+ */
134640
+ vector: createGenerator(GenerateVector),
134203
134641
  };
134204
- // so far, version changes don’t change generator parameters.
134642
+ // so far, version changes don’t affect generator parameters.
134205
134643
  const generatorsFuncsV2 = {
134206
134644
  ...generatorsFuncs,
134207
134645
  };
@@ -134359,10 +134797,1128 @@ const generatorsMap = {
134359
134797
  GenerateWeightedCount: [
134360
134798
  GenerateWeightedCount,
134361
134799
  ],
134800
+ GenerateBitString: [
134801
+ GenerateBitString,
134802
+ ],
134803
+ GenerateUniqueBitString: [
134804
+ GenerateUniqueBitString,
134805
+ ],
134806
+ GenerateInet: [
134807
+ GenerateInet,
134808
+ ],
134809
+ GenerateUniqueInet: [
134810
+ GenerateUniqueInet,
134811
+ ],
134812
+ GenerateGeometry: [
134813
+ GenerateGeometry,
134814
+ ],
134815
+ GenerateUniqueGeometry: [
134816
+ GenerateUniqueGeometry,
134817
+ ],
134818
+ GenerateVector: [
134819
+ GenerateVector,
134820
+ ],
134821
+ GenerateUniqueVector: [
134822
+ GenerateUniqueVector,
134823
+ ],
134824
+ };
134825
+
134826
+ // TODO: revise serial part generators
134827
+ const selectGeneratorForCockroachColumn = (table, col) => {
134828
+ const pickGenerator = (table, col) => {
134829
+ // ARRAY
134830
+ if (col.columnType.match(/\[\w*]/g) !== null && col.baseColumn !== undefined) {
134831
+ const baseColumnGen = selectGeneratorForCockroachColumn(table, col.baseColumn);
134832
+ if (baseColumnGen === undefined) {
134833
+ throw new Error(`column with type ${col.baseColumn.columnType} is not supported for now.`);
134834
+ }
134835
+ // const getBaseColumnDataType = (baseColumn: Column) => {
134836
+ // if (baseColumn.baseColumn !== undefined) {
134837
+ // return getBaseColumnDataType(baseColumn.baseColumn);
134838
+ // }
134839
+ // return baseColumn.dataType;
134840
+ // };
134841
+ // const baseColumnDataType = getBaseColumnDataType(col.baseColumn);
134842
+ const generator = new generatorsMap.GenerateArray[0]({ baseColumnGen, size: col.size });
134843
+ // generator.baseColumnDataType = baseColumnDataType;
134844
+ return generator;
134845
+ }
134846
+ // ARRAY for studio
134847
+ if (col.columnType.match(/\[\w*]/g) !== null) {
134848
+ // remove dimensions from type
134849
+ const baseColumnType = col.columnType.replace(/\[\w*]/g, '');
134850
+ const baseColumn = {
134851
+ ...col,
134852
+ };
134853
+ baseColumn.columnType = baseColumnType;
134854
+ const baseColumnGen = selectGeneratorForCockroachColumn(table, baseColumn);
134855
+ if (baseColumnGen === undefined) {
134856
+ throw new Error(`column with type ${col.baseColumn.columnType} is not supported for now.`);
134857
+ }
134858
+ let generator = new generatorsMap.GenerateArray[0]({ baseColumnGen });
134859
+ for (let i = 0; i < col.typeParams.dimensions - 1; i++) {
134860
+ generator = new generatorsMap.GenerateArray[0]({ baseColumnGen: generator });
134861
+ }
134862
+ return generator;
134863
+ }
134864
+ // INT ------------------------------------------------------------------------------------------------------------
134865
+ if ((col.columnType === 'int2'
134866
+ || col.columnType === 'int4'
134867
+ || col.columnType.includes('int8'))
134868
+ && table.primaryKeys.includes(col.name)) {
134869
+ const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
134870
+ return generator;
134871
+ }
134872
+ let minValue;
134873
+ let maxValue;
134874
+ if (col.columnType.startsWith('int')) {
134875
+ if (col.columnType === 'int2') {
134876
+ // 2^16 / 2 - 1, 2 bytes
134877
+ minValue = -32768;
134878
+ maxValue = 32767;
134879
+ }
134880
+ else if (col.columnType === 'int4') {
134881
+ // 2^32 / 2 - 1, 4 bytes
134882
+ minValue = -2147483648;
134883
+ maxValue = 2147483647;
134884
+ }
134885
+ else if (col.columnType.includes('int8')) {
134886
+ if (col.dataType === 'bigint') {
134887
+ // 2^64 / 2 - 1, 8 bytes
134888
+ minValue = BigInt('-9223372036854775808');
134889
+ maxValue = BigInt('9223372036854775807');
134890
+ }
134891
+ else {
134892
+ // if (col.dataType === 'number')
134893
+ // if you’re expecting values above 2^31 but below 2^53
134894
+ minValue = -9007199254740991;
134895
+ maxValue = 9007199254740991;
134896
+ }
134897
+ }
134898
+ }
134899
+ if (col.columnType.startsWith('int')
134900
+ && !col.columnType.includes('interval')) {
134901
+ const generator = new generatorsMap.GenerateInt[0]({
134902
+ minValue,
134903
+ maxValue,
134904
+ });
134905
+ return generator;
134906
+ }
134907
+ // NUMBER(real, double, decimal, numeric)
134908
+ if (col.columnType.startsWith('real')
134909
+ || col.columnType.startsWith('float')
134910
+ || col.columnType.startsWith('decimal')
134911
+ || col.columnType.startsWith('numeric')) {
134912
+ if (col.typeParams.precision !== undefined) {
134913
+ const precision = col.typeParams.precision;
134914
+ const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
134915
+ const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
134916
+ const generator = new generatorsMap.GenerateNumber[0]({
134917
+ minValue: -maxAbsoluteValue,
134918
+ maxValue: maxAbsoluteValue,
134919
+ precision: Math.pow(10, scale),
134920
+ });
134921
+ return generator;
134922
+ }
134923
+ const generator = new generatorsMap.GenerateNumber[0]();
134924
+ return generator;
134925
+ }
134926
+ // STRING
134927
+ if ((col.columnType === 'string'
134928
+ || col.columnType.startsWith('varchar')
134929
+ || col.columnType.startsWith('char'))
134930
+ && table.primaryKeys.includes(col.name)) {
134931
+ const generator = new generatorsMap.GenerateUniqueString[0]();
134932
+ return generator;
134933
+ }
134934
+ if ((col.columnType === 'string'
134935
+ || col.columnType.startsWith('varchar')
134936
+ || col.columnType.startsWith('char'))
134937
+ && col.name.toLowerCase().includes('name')) {
134938
+ const generator = new generatorsMap.GenerateFirstName[0]();
134939
+ return generator;
134940
+ }
134941
+ if ((col.columnType === 'string'
134942
+ || col.columnType.startsWith('varchar')
134943
+ || col.columnType.startsWith('char'))
134944
+ && col.name.toLowerCase().includes('email')) {
134945
+ const generator = new generatorsMap.GenerateEmail[0]();
134946
+ return generator;
134947
+ }
134948
+ if (col.columnType === 'string'
134949
+ || col.columnType.startsWith('varchar')
134950
+ || col.columnType.startsWith('char')) {
134951
+ const generator = new generatorsMap.GenerateString[0]();
134952
+ return generator;
134953
+ }
134954
+ // BIT
134955
+ if (col.columnType.startsWith('bit')) {
134956
+ const generator = new generatorsMap.GenerateBitString[0]();
134957
+ return generator;
134958
+ }
134959
+ // INET
134960
+ if (col.columnType === 'inet') {
134961
+ const generator = new generatorsMap.GenerateInet[0]();
134962
+ return generator;
134963
+ }
134964
+ // geometry(point)
134965
+ if (col.columnType.startsWith('geometry')) {
134966
+ const generator = new generatorsMap.GenerateGeometry[0]();
134967
+ return generator;
134968
+ }
134969
+ // vector
134970
+ if (col.columnType.startsWith('vector')) {
134971
+ const generator = new generatorsMap.GenerateVector[0]();
134972
+ return generator;
134973
+ }
134974
+ // UUID
134975
+ if (col.columnType === 'uuid') {
134976
+ const generator = new generatorsMap.GenerateUUID[0]();
134977
+ return generator;
134978
+ }
134979
+ // BOOLEAN
134980
+ if (col.columnType === 'boolean') {
134981
+ const generator = new generatorsMap.GenerateBoolean[0]();
134982
+ return generator;
134983
+ }
134984
+ // DATE, TIME, TIMESTAMP
134985
+ if (col.columnType.includes('date')) {
134986
+ const generator = new generatorsMap.GenerateDate[0]();
134987
+ return generator;
134988
+ }
134989
+ if (col.columnType === 'time') {
134990
+ const generator = new generatorsMap.GenerateTime[0]();
134991
+ return generator;
134992
+ }
134993
+ if (col.columnType.includes('timestamp')) {
134994
+ const generator = new generatorsMap.GenerateTimestamp[0]();
134995
+ return generator;
134996
+ }
134997
+ // JSON, JSONB
134998
+ if (col.columnType === 'json' || col.columnType === 'jsonb') {
134999
+ const generator = new generatorsMap.GenerateJson[0]();
135000
+ return generator;
135001
+ }
135002
+ // if (col.columnType === "jsonb") {
135003
+ // const generator = new GenerateJsonb({});
135004
+ // return generator;
135005
+ // }
135006
+ // ENUM
135007
+ if (col.enumValues !== undefined) {
135008
+ const generator = new generatorsMap.GenerateEnum[0]({
135009
+ enumValues: col.enumValues,
135010
+ });
135011
+ return generator;
135012
+ }
135013
+ // INTERVAL
135014
+ if (col.columnType.startsWith('interval')) {
135015
+ if (col.columnType === 'interval') {
135016
+ const generator = new generatorsMap.GenerateInterval[0]();
135017
+ return generator;
135018
+ }
135019
+ const fields = col.columnType.replace('interval ', '');
135020
+ const generator = new generatorsMap.GenerateInterval[0]({ fields });
135021
+ return generator;
135022
+ }
135023
+ if (col.hasDefault && col.default !== undefined) {
135024
+ const generator = new generatorsMap.GenerateDefault[0]({
135025
+ defaultValue: col.default,
135026
+ });
135027
+ return generator;
135028
+ }
135029
+ return;
135030
+ };
135031
+ const generator = pickGenerator(table, col);
135032
+ // set params for base column
135033
+ if (generator !== undefined) {
135034
+ generator.isUnique = col.isUnique;
135035
+ generator.dataType = col.dataType;
135036
+ // generator.stringLength = col.typeParams.length;
135037
+ generator.typeParams = col.typeParams;
135038
+ }
135039
+ return generator;
134362
135040
  };
134363
135041
 
134364
135042
  const latestVersion = 2;
134365
135043
 
135044
+ const selectGeneratorForMssqlColumn = (table, col) => {
135045
+ const pickGenerator = (table, col) => {
135046
+ // INT ------------------------------------------------------------------------------------------------------------
135047
+ if (col.columnType.includes('int') && table.primaryKeys.includes(col.name)) {
135048
+ const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
135049
+ return generator;
135050
+ }
135051
+ let minValue;
135052
+ let maxValue;
135053
+ if (col.columnType.includes('int')) {
135054
+ if (col.columnType === 'tinyint') {
135055
+ // 2^8 / 2 - 1, 1 bytes
135056
+ // more like unsigned tinyint
135057
+ minValue = 0;
135058
+ maxValue = 255;
135059
+ }
135060
+ else if (col.columnType === 'smallint') {
135061
+ // 2^16 / 2 - 1, 2 bytes
135062
+ minValue = -32768;
135063
+ maxValue = 32767;
135064
+ }
135065
+ else if (col.columnType === 'int') {
135066
+ // 2^32 / 2 - 1, 4 bytes
135067
+ minValue = -2147483648;
135068
+ maxValue = 2147483647;
135069
+ }
135070
+ else if (col.columnType === 'bigint') {
135071
+ // 2^64 / 2 - 1, 8 bytes
135072
+ minValue = BigInt('-9223372036854775808');
135073
+ maxValue = BigInt('9223372036854775807');
135074
+ }
135075
+ const generator = new generatorsMap.GenerateInt[0]({
135076
+ minValue,
135077
+ maxValue,
135078
+ });
135079
+ return generator;
135080
+ }
135081
+ // NUMBER(real, decimal, numeric, float)
135082
+ if (col.columnType.startsWith('real')
135083
+ || col.columnType.startsWith('decimal')
135084
+ || col.columnType.startsWith('float')
135085
+ || col.columnType.startsWith('numeric')) {
135086
+ if (col.typeParams.precision !== undefined) {
135087
+ const precision = col.typeParams.precision;
135088
+ const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
135089
+ const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
135090
+ const generator = new generatorsMap.GenerateNumber[0]({
135091
+ minValue: -maxAbsoluteValue,
135092
+ maxValue: maxAbsoluteValue,
135093
+ precision: Math.pow(10, scale),
135094
+ });
135095
+ return generator;
135096
+ }
135097
+ const generator = new generatorsMap.GenerateNumber[0]();
135098
+ return generator;
135099
+ }
135100
+ // STRING
135101
+ if ((col.columnType === 'text'
135102
+ || col.columnType.startsWith('char')
135103
+ || col.columnType.startsWith('varchar')
135104
+ || col.columnType.startsWith('binary')
135105
+ || col.columnType.startsWith('varbinary'))
135106
+ && table.primaryKeys.includes(col.name)) {
135107
+ const generator = new generatorsMap.GenerateUniqueString[0]();
135108
+ return generator;
135109
+ }
135110
+ if ((col.columnType === 'text'
135111
+ || col.columnType.startsWith('char')
135112
+ || col.columnType.startsWith('varchar')
135113
+ || col.columnType.startsWith('binary')
135114
+ || col.columnType.startsWith('varbinary'))
135115
+ && col.name.toLowerCase().includes('name')) {
135116
+ const generator = new generatorsMap.GenerateFirstName[0]();
135117
+ return generator;
135118
+ }
135119
+ if ((col.columnType === 'text'
135120
+ || col.columnType.startsWith('char')
135121
+ || col.columnType.startsWith('varchar')
135122
+ || col.columnType.startsWith('binary')
135123
+ || col.columnType.startsWith('varbinary'))
135124
+ && col.name.toLowerCase().includes('email')) {
135125
+ const generator = new generatorsMap.GenerateEmail[0]();
135126
+ return generator;
135127
+ }
135128
+ if (col.columnType === 'text'
135129
+ || col.columnType.startsWith('char')
135130
+ || col.columnType.startsWith('varchar')
135131
+ || col.columnType.startsWith('binary')
135132
+ || col.columnType.startsWith('varbinary')) {
135133
+ const generator = new generatorsMap.GenerateString[0]();
135134
+ return generator;
135135
+ }
135136
+ // bit
135137
+ if (col.columnType === 'bit') {
135138
+ const generator = new generatorsMap.GenerateBoolean[0]();
135139
+ return generator;
135140
+ }
135141
+ // DATE, TIME, TIMESTAMP, DATETIME, YEAR
135142
+ if (col.columnType.includes('datetime')) {
135143
+ const generator = new generatorsMap.GenerateDatetime[0]();
135144
+ return generator;
135145
+ }
135146
+ if (col.columnType.includes('date')) {
135147
+ const generator = new generatorsMap.GenerateDate[0]();
135148
+ return generator;
135149
+ }
135150
+ if (col.columnType === 'time') {
135151
+ const generator = new generatorsMap.GenerateTime[0]();
135152
+ return generator;
135153
+ }
135154
+ // JSON
135155
+ if (col.columnType === 'json') {
135156
+ const generator = new generatorsMap.GenerateJson[0]();
135157
+ return generator;
135158
+ }
135159
+ if (col.hasDefault && col.default !== undefined) {
135160
+ const generator = new generatorsMap.GenerateDefault[0]({
135161
+ defaultValue: col.default,
135162
+ });
135163
+ return generator;
135164
+ }
135165
+ return;
135166
+ };
135167
+ const generator = pickGenerator(table, col);
135168
+ return generator;
135169
+ };
135170
+
135171
+ const selectGeneratorForMysqlColumn = (table, col) => {
135172
+ const pickGenerator = (table, col) => {
135173
+ // INT ------------------------------------------------------------------------------------------------------------
135174
+ if ((col.columnType.includes('serial') || col.columnType.includes('int'))
135175
+ && table.primaryKeys.includes(col.name)) {
135176
+ const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
135177
+ return generator;
135178
+ }
135179
+ let minValue;
135180
+ let maxValue;
135181
+ if (col.columnType === 'serial') {
135182
+ // 2^64 % 2 - 1, 8 bytes
135183
+ minValue = BigInt(0);
135184
+ maxValue = BigInt('9223372036854775807');
135185
+ }
135186
+ else if (col.columnType.includes('int')) {
135187
+ if (col.columnType === 'tinyint') {
135188
+ // 2^8 / 2 - 1, 1 bytes
135189
+ minValue = -128;
135190
+ maxValue = 127;
135191
+ }
135192
+ else if (col.columnType === 'smallint') {
135193
+ // 2^16 / 2 - 1, 2 bytes
135194
+ minValue = -32768;
135195
+ maxValue = 32767;
135196
+ }
135197
+ else if (col.columnType === 'mediumint') {
135198
+ // 2^16 / 2 - 1, 2 bytes
135199
+ minValue = -8388608;
135200
+ maxValue = 8388607;
135201
+ }
135202
+ else if (col.columnType === 'int') {
135203
+ // 2^32 / 2 - 1, 4 bytes
135204
+ minValue = -2147483648;
135205
+ maxValue = 2147483647;
135206
+ }
135207
+ else if (col.columnType === 'bigint') {
135208
+ // 2^64 / 2 - 1, 8 bytes
135209
+ minValue = BigInt('-9223372036854775808');
135210
+ maxValue = BigInt('9223372036854775807');
135211
+ }
135212
+ }
135213
+ if (col.columnType.includes('int')) {
135214
+ const generator = new generatorsMap.GenerateInt[0]({
135215
+ minValue,
135216
+ maxValue,
135217
+ });
135218
+ return generator;
135219
+ }
135220
+ if (col.columnType.includes('serial')) {
135221
+ const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
135222
+ generator.maxValue = maxValue;
135223
+ return generator;
135224
+ }
135225
+ // NUMBER(real, double, decimal, float)
135226
+ if (col.columnType.startsWith('real')
135227
+ || col.columnType.startsWith('double')
135228
+ || col.columnType.startsWith('decimal')
135229
+ || col.columnType.startsWith('float')
135230
+ || col.columnType.startsWith('numeric')) {
135231
+ if (col.typeParams.precision !== undefined) {
135232
+ const precision = col.typeParams.precision;
135233
+ const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
135234
+ const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
135235
+ const generator = new generatorsMap.GenerateNumber[0]({
135236
+ minValue: -maxAbsoluteValue,
135237
+ maxValue: maxAbsoluteValue,
135238
+ precision: Math.pow(10, scale),
135239
+ });
135240
+ return generator;
135241
+ }
135242
+ const generator = new generatorsMap.GenerateNumber[0]();
135243
+ return generator;
135244
+ }
135245
+ // STRING
135246
+ if ((col.columnType === 'text'
135247
+ || col.columnType === 'blob'
135248
+ || col.columnType.startsWith('char')
135249
+ || col.columnType.startsWith('varchar')
135250
+ || col.columnType.startsWith('binary')
135251
+ || col.columnType.startsWith('varbinary'))
135252
+ && table.primaryKeys.includes(col.name)) {
135253
+ const generator = new generatorsMap.GenerateUniqueString[0]();
135254
+ return generator;
135255
+ }
135256
+ if ((col.columnType === 'text'
135257
+ || col.columnType === 'blob'
135258
+ || col.columnType.startsWith('char')
135259
+ || col.columnType.startsWith('varchar')
135260
+ || col.columnType.startsWith('binary')
135261
+ || col.columnType.startsWith('varbinary'))
135262
+ && col.name.toLowerCase().includes('name')) {
135263
+ const generator = new generatorsMap.GenerateFirstName[0]();
135264
+ return generator;
135265
+ }
135266
+ if ((col.columnType === 'text'
135267
+ || col.columnType === 'blob'
135268
+ || col.columnType.startsWith('char')
135269
+ || col.columnType.startsWith('varchar')
135270
+ || col.columnType.startsWith('binary')
135271
+ || col.columnType.startsWith('varbinary'))
135272
+ && col.name.toLowerCase().includes('email')) {
135273
+ const generator = new generatorsMap.GenerateEmail[0]();
135274
+ return generator;
135275
+ }
135276
+ if (col.columnType === 'text'
135277
+ || col.columnType === 'blob'
135278
+ || col.columnType.startsWith('char')
135279
+ || col.columnType.startsWith('varchar')
135280
+ || col.columnType.startsWith('binary')
135281
+ || col.columnType.startsWith('varbinary')) {
135282
+ const generator = new generatorsMap.GenerateString[0]();
135283
+ return generator;
135284
+ }
135285
+ // BOOLEAN
135286
+ if (col.columnType === 'boolean') {
135287
+ const generator = new generatorsMap.GenerateBoolean[0]();
135288
+ return generator;
135289
+ }
135290
+ // DATE, TIME, TIMESTAMP, DATETIME, YEAR
135291
+ if (col.columnType.includes('datetime')) {
135292
+ const generator = new generatorsMap.GenerateDatetime[0]();
135293
+ return generator;
135294
+ }
135295
+ if (col.columnType.includes('date')) {
135296
+ const generator = new generatorsMap.GenerateDate[0]();
135297
+ return generator;
135298
+ }
135299
+ if (col.columnType === 'time') {
135300
+ const generator = new generatorsMap.GenerateTime[0]();
135301
+ return generator;
135302
+ }
135303
+ if (col.columnType.includes('timestamp')) {
135304
+ const generator = new generatorsMap.GenerateTimestamp[0]();
135305
+ return generator;
135306
+ }
135307
+ if (col.columnType === 'year') {
135308
+ const generator = new generatorsMap.GenerateYear[0]();
135309
+ return generator;
135310
+ }
135311
+ // JSON
135312
+ if (col.columnType === 'json') {
135313
+ const generator = new generatorsMap.GenerateJson[0]();
135314
+ return generator;
135315
+ }
135316
+ // ENUM
135317
+ if (col.enumValues !== undefined) {
135318
+ const generator = new generatorsMap.GenerateEnum[0]({
135319
+ enumValues: col.enumValues,
135320
+ });
135321
+ return generator;
135322
+ }
135323
+ if (col.hasDefault && col.default !== undefined) {
135324
+ const generator = new generatorsMap.GenerateDefault[0]({
135325
+ defaultValue: col.default,
135326
+ });
135327
+ return generator;
135328
+ }
135329
+ return;
135330
+ };
135331
+ const generator = pickGenerator(table, col);
135332
+ return generator;
135333
+ };
135334
+
135335
+ // TODO: revise serial part generators
135336
+ const selectGeneratorForPostgresColumn = (table, col) => {
135337
+ const pickGenerator = (table, col) => {
135338
+ // ARRAY
135339
+ if (col.columnType.match(/\[\w*]/g) !== null && col.baseColumn !== undefined) {
135340
+ const baseColumnGen = selectGeneratorForPostgresColumn(table, col.baseColumn);
135341
+ if (baseColumnGen === undefined) {
135342
+ throw new Error(`column with type ${col.baseColumn.columnType} is not supported for now.`);
135343
+ }
135344
+ // const getBaseColumnDataType = (baseColumn: Column) => {
135345
+ // if (baseColumn.baseColumn !== undefined) {
135346
+ // return getBaseColumnDataType(baseColumn.baseColumn);
135347
+ // }
135348
+ // return baseColumn.dataType;
135349
+ // };
135350
+ // const baseColumnDataType = getBaseColumnDataType(col.baseColumn);
135351
+ const generator = new generatorsMap.GenerateArray[0]({ baseColumnGen, size: col.size });
135352
+ // generator.baseColumnDataType = baseColumnDataType;
135353
+ return generator;
135354
+ }
135355
+ // ARRAY for studio
135356
+ if (col.columnType.match(/\[\w*]/g) !== null) {
135357
+ // remove dimensions from type
135358
+ const baseColumnType = col.columnType.replace(/\[\w*]/g, '');
135359
+ const baseColumn = {
135360
+ ...col,
135361
+ };
135362
+ baseColumn.columnType = baseColumnType;
135363
+ const baseColumnGen = selectGeneratorForPostgresColumn(table, baseColumn);
135364
+ if (baseColumnGen === undefined) {
135365
+ throw new Error(`column with type ${col.baseColumn.columnType} is not supported for now.`);
135366
+ }
135367
+ let generator = new generatorsMap.GenerateArray[0]({ baseColumnGen });
135368
+ for (let i = 0; i < col.typeParams.dimensions - 1; i++) {
135369
+ generator = new generatorsMap.GenerateArray[0]({ baseColumnGen: generator });
135370
+ }
135371
+ return generator;
135372
+ }
135373
+ // INT ------------------------------------------------------------------------------------------------------------
135374
+ if ((col.columnType.includes('serial')
135375
+ || col.columnType === 'integer'
135376
+ || col.columnType === 'smallint'
135377
+ || col.columnType.includes('bigint'))
135378
+ && table.primaryKeys.includes(col.name)) {
135379
+ const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
135380
+ return generator;
135381
+ }
135382
+ let minValue;
135383
+ let maxValue;
135384
+ if (col.columnType.includes('serial')) {
135385
+ minValue = 1;
135386
+ if (col.columnType === 'smallserial') {
135387
+ // 2^16 / 2 - 1, 2 bytes
135388
+ maxValue = 32767;
135389
+ }
135390
+ else if (col.columnType === 'serial') {
135391
+ // 2^32 / 2 - 1, 4 bytes
135392
+ maxValue = 2147483647;
135393
+ }
135394
+ else if (col.columnType === 'bigserial') {
135395
+ // 2^64 / 2 - 1, 8 bytes
135396
+ minValue = BigInt(1);
135397
+ maxValue = BigInt('9223372036854775807');
135398
+ }
135399
+ }
135400
+ else if (col.columnType.includes('int')) {
135401
+ if (col.columnType === 'smallint') {
135402
+ // 2^16 / 2 - 1, 2 bytes
135403
+ minValue = -32768;
135404
+ maxValue = 32767;
135405
+ }
135406
+ else if (col.columnType === 'integer') {
135407
+ // 2^32 / 2 - 1, 4 bytes
135408
+ minValue = -2147483648;
135409
+ maxValue = 2147483647;
135410
+ }
135411
+ else if (col.columnType.includes('bigint')) {
135412
+ if (col.dataType === 'bigint') {
135413
+ // 2^64 / 2 - 1, 8 bytes
135414
+ minValue = BigInt('-9223372036854775808');
135415
+ maxValue = BigInt('9223372036854775807');
135416
+ }
135417
+ else {
135418
+ // if (col.dataType === 'number')
135419
+ // if you’re expecting values above 2^31 but below 2^53
135420
+ minValue = -9007199254740991;
135421
+ maxValue = 9007199254740991;
135422
+ }
135423
+ }
135424
+ }
135425
+ if (col.columnType.includes('int')
135426
+ && !col.columnType.includes('interval')
135427
+ && !col.columnType.includes('point')) {
135428
+ const generator = new generatorsMap.GenerateInt[0]({
135429
+ minValue,
135430
+ maxValue,
135431
+ });
135432
+ return generator;
135433
+ }
135434
+ if (col.columnType.includes('serial')) {
135435
+ const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
135436
+ generator.maxValue = maxValue;
135437
+ return generator;
135438
+ }
135439
+ // NUMBER(real, double, decimal, numeric)
135440
+ if (col.columnType.startsWith('real')
135441
+ || col.columnType.startsWith('double precision')
135442
+ || col.columnType.startsWith('decimal')
135443
+ || col.columnType.startsWith('numeric')) {
135444
+ if (col.typeParams.precision !== undefined) {
135445
+ const precision = col.typeParams.precision;
135446
+ const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
135447
+ const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
135448
+ const generator = new generatorsMap.GenerateNumber[0]({
135449
+ minValue: -maxAbsoluteValue,
135450
+ maxValue: maxAbsoluteValue,
135451
+ precision: Math.pow(10, scale),
135452
+ });
135453
+ return generator;
135454
+ }
135455
+ const generator = new generatorsMap.GenerateNumber[0]();
135456
+ return generator;
135457
+ }
135458
+ // STRING
135459
+ if ((col.columnType === 'text'
135460
+ || col.columnType.startsWith('varchar')
135461
+ || col.columnType.startsWith('char'))
135462
+ && table.primaryKeys.includes(col.name)) {
135463
+ const generator = new generatorsMap.GenerateUniqueString[0]();
135464
+ return generator;
135465
+ }
135466
+ if ((col.columnType === 'text'
135467
+ || col.columnType.startsWith('varchar')
135468
+ || col.columnType.startsWith('char'))
135469
+ && col.name.toLowerCase().includes('name')) {
135470
+ const generator = new generatorsMap.GenerateFirstName[0]();
135471
+ return generator;
135472
+ }
135473
+ if ((col.columnType === 'text'
135474
+ || col.columnType.startsWith('varchar')
135475
+ || col.columnType.startsWith('char'))
135476
+ && col.name.toLowerCase().includes('email')) {
135477
+ const generator = new generatorsMap.GenerateEmail[0]();
135478
+ return generator;
135479
+ }
135480
+ if (col.columnType === 'text'
135481
+ || col.columnType.startsWith('varchar')
135482
+ || col.columnType.startsWith('char')) {
135483
+ const generator = new generatorsMap.GenerateString[0]();
135484
+ return generator;
135485
+ }
135486
+ // BIT
135487
+ if (col.columnType.startsWith('bit')) {
135488
+ const generator = new generatorsMap.GenerateBitString[0]();
135489
+ return generator;
135490
+ }
135491
+ // INET
135492
+ if (col.columnType === 'inet') {
135493
+ const generator = new generatorsMap.GenerateInet[0]();
135494
+ return generator;
135495
+ }
135496
+ // geometry(point)
135497
+ if (col.columnType.startsWith('geometry')) {
135498
+ const generator = new generatorsMap.GenerateGeometry[0]();
135499
+ return generator;
135500
+ }
135501
+ // vector
135502
+ if (col.columnType.startsWith('vector')) {
135503
+ const generator = new generatorsMap.GenerateVector[0]();
135504
+ return generator;
135505
+ }
135506
+ // UUID
135507
+ if (col.columnType === 'uuid') {
135508
+ const generator = new generatorsMap.GenerateUUID[0]();
135509
+ return generator;
135510
+ }
135511
+ // BOOLEAN
135512
+ if (col.columnType === 'boolean') {
135513
+ const generator = new generatorsMap.GenerateBoolean[0]();
135514
+ return generator;
135515
+ }
135516
+ // DATE, TIME, TIMESTAMP
135517
+ if (col.columnType.includes('date')) {
135518
+ const generator = new generatorsMap.GenerateDate[0]();
135519
+ return generator;
135520
+ }
135521
+ if (col.columnType === 'time') {
135522
+ const generator = new generatorsMap.GenerateTime[0]();
135523
+ return generator;
135524
+ }
135525
+ if (col.columnType.includes('timestamp')) {
135526
+ const generator = new generatorsMap.GenerateTimestamp[0]();
135527
+ return generator;
135528
+ }
135529
+ // JSON, JSONB
135530
+ if (col.columnType === 'json' || col.columnType === 'jsonb') {
135531
+ const generator = new generatorsMap.GenerateJson[0]();
135532
+ return generator;
135533
+ }
135534
+ // if (col.columnType === "jsonb") {
135535
+ // const generator = new GenerateJsonb({});
135536
+ // return generator;
135537
+ // }
135538
+ // ENUM
135539
+ if (col.enumValues !== undefined) {
135540
+ const generator = new generatorsMap.GenerateEnum[0]({
135541
+ enumValues: col.enumValues,
135542
+ });
135543
+ return generator;
135544
+ }
135545
+ // INTERVAL
135546
+ if (col.columnType.startsWith('interval')) {
135547
+ if (col.columnType === 'interval') {
135548
+ const generator = new generatorsMap.GenerateInterval[0]();
135549
+ return generator;
135550
+ }
135551
+ const fields = col.columnType.replace('interval ', '');
135552
+ const generator = new generatorsMap.GenerateInterval[0]({ fields });
135553
+ return generator;
135554
+ }
135555
+ // POINT, LINE
135556
+ if (col.columnType.includes('point')) {
135557
+ const generator = new generatorsMap.GeneratePoint[0]();
135558
+ return generator;
135559
+ }
135560
+ if (col.columnType.includes('line')) {
135561
+ const generator = new generatorsMap.GenerateLine[0]();
135562
+ return generator;
135563
+ }
135564
+ if (col.hasDefault && col.default !== undefined) {
135565
+ const generator = new generatorsMap.GenerateDefault[0]({
135566
+ defaultValue: col.default,
135567
+ });
135568
+ return generator;
135569
+ }
135570
+ return;
135571
+ };
135572
+ const generator = pickGenerator(table, col);
135573
+ if (generator !== undefined) {
135574
+ generator.isUnique = col.isUnique;
135575
+ generator.dataType = col.dataType;
135576
+ generator.typeParams = col.typeParams;
135577
+ // generator.stringLength = col.typeParams.length;
135578
+ }
135579
+ return generator;
135580
+ };
135581
+
135582
+ const selectGeneratorForSingleStoreColumn = (table, col) => {
135583
+ const pickGenerator = (table, col) => {
135584
+ // INT ------------------------------------------------------------------------------------------------------------
135585
+ if ((col.columnType.includes('serial') || col.columnType.includes('int'))
135586
+ && table.primaryKeys.includes(col.name)) {
135587
+ const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
135588
+ return generator;
135589
+ }
135590
+ let minValue;
135591
+ let maxValue;
135592
+ if (col.columnType === 'serial') {
135593
+ // 2^64 % 2 - 1, 8 bytes
135594
+ minValue = BigInt(0);
135595
+ maxValue = BigInt('9223372036854775807');
135596
+ }
135597
+ else if (col.columnType.includes('int')) {
135598
+ if (col.columnType === 'tinyint') {
135599
+ // 2^8 / 2 - 1, 1 bytes
135600
+ minValue = -128;
135601
+ maxValue = 127;
135602
+ }
135603
+ else if (col.columnType === 'smallint') {
135604
+ // 2^16 / 2 - 1, 2 bytes
135605
+ minValue = -32768;
135606
+ maxValue = 32767;
135607
+ }
135608
+ else if (col.columnType === 'mediumint') {
135609
+ // 2^16 / 2 - 1, 2 bytes
135610
+ minValue = -8388608;
135611
+ maxValue = 8388607;
135612
+ }
135613
+ else if (col.columnType === 'int') {
135614
+ // 2^32 / 2 - 1, 4 bytes
135615
+ minValue = -2147483648;
135616
+ maxValue = 2147483647;
135617
+ }
135618
+ else if (col.columnType === 'bigint') {
135619
+ // 2^64 / 2 - 1, 8 bytes
135620
+ minValue = BigInt('-9223372036854775808');
135621
+ maxValue = BigInt('9223372036854775807');
135622
+ }
135623
+ }
135624
+ if (col.columnType.includes('int')) {
135625
+ const generator = new generatorsMap.GenerateInt[0]({
135626
+ minValue,
135627
+ maxValue,
135628
+ });
135629
+ return generator;
135630
+ }
135631
+ if (col.columnType.includes('serial')) {
135632
+ const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
135633
+ generator.maxValue = maxValue;
135634
+ return generator;
135635
+ }
135636
+ // NUMBER(real, double, decimal, float)
135637
+ if (col.columnType.startsWith('real')
135638
+ || col.columnType.startsWith('double')
135639
+ || col.columnType.startsWith('decimal')
135640
+ || col.columnType.startsWith('float')
135641
+ || col.columnType.startsWith('numeric')) {
135642
+ if (col.typeParams.precision !== undefined) {
135643
+ const precision = col.typeParams.precision;
135644
+ const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
135645
+ const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
135646
+ const generator = new generatorsMap.GenerateNumber[0]({
135647
+ minValue: -maxAbsoluteValue,
135648
+ maxValue: maxAbsoluteValue,
135649
+ precision: Math.pow(10, scale),
135650
+ });
135651
+ return generator;
135652
+ }
135653
+ const generator = new generatorsMap.GenerateNumber[0]();
135654
+ return generator;
135655
+ }
135656
+ // STRING
135657
+ if ((col.columnType === 'tinytext'
135658
+ || col.columnType === 'mediumtext'
135659
+ || col.columnType === 'text'
135660
+ || col.columnType === 'longtext'
135661
+ || col.columnType === 'blob'
135662
+ || col.columnType.startsWith('char')
135663
+ || col.columnType.startsWith('varchar')
135664
+ || col.columnType.startsWith('binary')
135665
+ || col.columnType.startsWith('varbinary'))
135666
+ && table.primaryKeys.includes(col.name)) {
135667
+ const generator = new generatorsMap.GenerateUniqueString[0]();
135668
+ return generator;
135669
+ }
135670
+ if ((col.columnType === 'tinytext'
135671
+ || col.columnType === 'mediumtext'
135672
+ || col.columnType === 'text'
135673
+ || col.columnType === 'longtext'
135674
+ || col.columnType === 'blob'
135675
+ || col.columnType.startsWith('char')
135676
+ || col.columnType.startsWith('varchar')
135677
+ || col.columnType.startsWith('binary')
135678
+ || col.columnType.startsWith('varbinary'))
135679
+ && col.name.toLowerCase().includes('name')) {
135680
+ const generator = new generatorsMap.GenerateFirstName[0]();
135681
+ return generator;
135682
+ }
135683
+ if ((col.columnType === 'tinytext'
135684
+ || col.columnType === 'mediumtext'
135685
+ || col.columnType === 'text'
135686
+ || col.columnType === 'longtext'
135687
+ || col.columnType === 'blob'
135688
+ || col.columnType.startsWith('char')
135689
+ || col.columnType.startsWith('varchar')
135690
+ || col.columnType.startsWith('binary')
135691
+ || col.columnType.startsWith('varbinary'))
135692
+ && col.name.toLowerCase().includes('email')) {
135693
+ const generator = new generatorsMap.GenerateEmail[0]();
135694
+ return generator;
135695
+ }
135696
+ if (col.columnType === 'tinytext'
135697
+ || col.columnType === 'mediumtext'
135698
+ || col.columnType === 'text'
135699
+ || col.columnType === 'longtext'
135700
+ || col.columnType === 'blob'
135701
+ || col.columnType.startsWith('char')
135702
+ || col.columnType.startsWith('varchar')
135703
+ || col.columnType.startsWith('binary')
135704
+ || col.columnType.startsWith('varbinary')) {
135705
+ const generator = new generatorsMap.GenerateString[0]();
135706
+ return generator;
135707
+ }
135708
+ // BOOLEAN
135709
+ if (col.columnType === 'boolean') {
135710
+ const generator = new generatorsMap.GenerateBoolean[0]();
135711
+ return generator;
135712
+ }
135713
+ // DATE, TIME, TIMESTAMP, DATETIME, YEAR
135714
+ if (col.columnType.includes('datetime')) {
135715
+ const generator = new generatorsMap.GenerateDatetime[0]();
135716
+ return generator;
135717
+ }
135718
+ if (col.columnType.includes('date')) {
135719
+ const generator = new generatorsMap.GenerateDate[0]();
135720
+ return generator;
135721
+ }
135722
+ if (col.columnType === 'time') {
135723
+ const generator = new generatorsMap.GenerateTime[0]();
135724
+ return generator;
135725
+ }
135726
+ if (col.columnType.includes('timestamp')) {
135727
+ const generator = new generatorsMap.GenerateTimestamp[0]();
135728
+ return generator;
135729
+ }
135730
+ if (col.columnType === 'year') {
135731
+ const generator = new generatorsMap.GenerateYear[0]();
135732
+ return generator;
135733
+ }
135734
+ // JSON
135735
+ if (col.columnType === 'json') {
135736
+ const generator = new generatorsMap.GenerateJson[0]();
135737
+ return generator;
135738
+ }
135739
+ // ENUM
135740
+ if (col.enumValues !== undefined) {
135741
+ const generator = new generatorsMap.GenerateEnum[0]({
135742
+ enumValues: col.enumValues,
135743
+ });
135744
+ return generator;
135745
+ }
135746
+ // vector
135747
+ if (col.columnType.startsWith('vector')) {
135748
+ let minValue, maxValue, decimalPlaces;
135749
+ if (col.typeParams.vectorValueType === 'I8') {
135750
+ minValue = -128;
135751
+ maxValue = 127;
135752
+ decimalPlaces = 0;
135753
+ }
135754
+ else if (col.typeParams.vectorValueType === 'I16') {
135755
+ minValue = -32768;
135756
+ maxValue = 32767;
135757
+ decimalPlaces = 0;
135758
+ }
135759
+ else if (col.typeParams.vectorValueType === 'I32') {
135760
+ minValue = -2147483648;
135761
+ maxValue = 2147483647;
135762
+ decimalPlaces = 0;
135763
+ }
135764
+ else if (col.typeParams.vectorValueType === 'I64') {
135765
+ minValue = Number.MIN_SAFE_INTEGER;
135766
+ maxValue = Number.MAX_SAFE_INTEGER;
135767
+ // minValue = -BigInt('9223372036854775808');
135768
+ // maxValue = BigInt('9223372036854775807');
135769
+ decimalPlaces = 0;
135770
+ }
135771
+ else if (col.typeParams.vectorValueType === 'F32') {
135772
+ minValue = -2147483648;
135773
+ maxValue = 2147483647;
135774
+ decimalPlaces = 6;
135775
+ }
135776
+ else if (col.typeParams.vectorValueType === 'F64') {
135777
+ minValue = -524288;
135778
+ maxValue = 524287;
135779
+ decimalPlaces = 10;
135780
+ }
135781
+ const generator = new generatorsMap.GenerateVector[0]({ minValue, maxValue, decimalPlaces });
135782
+ return generator;
135783
+ }
135784
+ if (col.hasDefault && col.default !== undefined) {
135785
+ const generator = new generatorsMap.GenerateDefault[0]({
135786
+ defaultValue: col.default,
135787
+ });
135788
+ return generator;
135789
+ }
135790
+ return;
135791
+ };
135792
+ const generator = pickGenerator(table, col);
135793
+ return generator;
135794
+ };
135795
+
135796
+ const selectGeneratorForSqlite = (table, col) => {
135797
+ const pickGenerator = (table, col) => {
135798
+ // int section ---------------------------------------------------------------------------------------
135799
+ if ((col.columnType === 'integer' || col.columnType === 'numeric')
135800
+ && table.primaryKeys.includes(col.name)) {
135801
+ const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
135802
+ return generator;
135803
+ }
135804
+ if (col.columnType === 'integer' && col.dataType === 'boolean') {
135805
+ const generator = new generatorsMap.GenerateBoolean[0]();
135806
+ return generator;
135807
+ }
135808
+ if ((col.columnType === 'integer' && col.dataType === 'date')) {
135809
+ const generator = new generatorsMap.GenerateTimestamp[0]();
135810
+ return generator;
135811
+ }
135812
+ if (col.columnType === 'integer'
135813
+ || (col.dataType === 'bigint' && col.columnType === 'blob')) {
135814
+ const generator = new generatorsMap.GenerateInt[0]();
135815
+ return generator;
135816
+ }
135817
+ // number section ------------------------------------------------------------------------------------
135818
+ if (col.columnType.startsWith('real') || col.columnType.startsWith('numeric')) {
135819
+ if (col.typeParams.precision !== undefined) {
135820
+ const precision = col.typeParams.precision;
135821
+ const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
135822
+ const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
135823
+ const generator = new generatorsMap.GenerateNumber[0]({
135824
+ minValue: -maxAbsoluteValue,
135825
+ maxValue: maxAbsoluteValue,
135826
+ precision: Math.pow(10, scale),
135827
+ });
135828
+ return generator;
135829
+ }
135830
+ const generator = new generatorsMap.GenerateNumber[0]();
135831
+ return generator;
135832
+ }
135833
+ // string section ------------------------------------------------------------------------------------
135834
+ if ((col.columnType.startsWith('text')
135835
+ || col.columnType.startsWith('numeric')
135836
+ || col.columnType.startsWith('blob'))
135837
+ && table.primaryKeys.includes(col.name)) {
135838
+ const generator = new generatorsMap.GenerateUniqueString[0]();
135839
+ return generator;
135840
+ }
135841
+ if ((col.columnType.startsWith('text')
135842
+ || col.columnType.startsWith('numeric')
135843
+ || col.columnType.startsWith('blob'))
135844
+ && col.name.toLowerCase().includes('name')) {
135845
+ const generator = new generatorsMap.GenerateFirstName[0]();
135846
+ return generator;
135847
+ }
135848
+ if ((col.columnType.startsWith('text')
135849
+ || col.columnType.startsWith('numeric')
135850
+ || col.columnType.startsWith('blob'))
135851
+ && col.name.toLowerCase().includes('email')) {
135852
+ const generator = new generatorsMap.GenerateEmail[0]();
135853
+ return generator;
135854
+ }
135855
+ if (col.columnType.startsWith('text')
135856
+ || col.columnType.startsWith('numeric')
135857
+ || col.columnType.startsWith('blob')
135858
+ || col.columnType.startsWith('blobbuffer')) {
135859
+ const generator = new generatorsMap.GenerateString[0]();
135860
+ return generator;
135861
+ }
135862
+ if ((col.columnType.startsWith('text') && col.dataType === 'json')
135863
+ || (col.columnType.startsWith('blob') && col.dataType === 'json')) {
135864
+ const generator = new generatorsMap.GenerateJson[0]();
135865
+ return generator;
135866
+ }
135867
+ if (col.hasDefault && col.default !== undefined) {
135868
+ const generator = new generatorsMap.GenerateDefault[0]({
135869
+ defaultValue: col.default,
135870
+ });
135871
+ return generator;
135872
+ }
135873
+ return;
135874
+ };
135875
+ const generator = pickGenerator(table, col);
135876
+ return generator;
135877
+ };
135878
+
135879
+ const isRelationCyclic = (startRel) => {
135880
+ // self relation
135881
+ if (startRel.table === startRel.refTable)
135882
+ return false;
135883
+ // DFS
135884
+ const targetTable = startRel.table;
135885
+ const queue = [startRel];
135886
+ let path = [];
135887
+ while (queue.length !== 0) {
135888
+ const currRel = queue.shift();
135889
+ if (path.includes(currRel.table)) {
135890
+ const idx = path.indexOf(currRel.table);
135891
+ path = path.slice(0, idx);
135892
+ }
135893
+ path.push(currRel.table);
135894
+ for (const rel of currRel.refTableRels) {
135895
+ // self relation
135896
+ if (rel.table === rel.refTable)
135897
+ continue;
135898
+ if (rel.refTable === targetTable)
135899
+ return true;
135900
+ // found cycle, but not the one we are looking for
135901
+ if (path.includes(rel.refTable))
135902
+ continue;
135903
+ queue.unshift(rel);
135904
+ }
135905
+ }
135906
+ return false;
135907
+ };
135908
+ const generateHashFromString = (s) => {
135909
+ let hash = 0;
135910
+ // p and m are prime numbers
135911
+ const p = 53;
135912
+ const m = 28871271685163;
135913
+ for (let i = 0; i < s.length; i++) {
135914
+ hash += ((s.codePointAt(i) || 0) * Math.pow(p, i)) % m;
135915
+ }
135916
+ return hash;
135917
+ };
135918
+ const equalSets = (set1, set2) => {
135919
+ return set1.size === set2.size && [...set1].every((si) => set2.has(si));
135920
+ };
135921
+
134366
135922
  /* eslint-disable drizzle-internal/require-entity-kind */
134367
135923
  class SeedService {
134368
135924
  static entityKind = 'SeedService';
@@ -134373,6 +135929,7 @@ class SeedService {
134373
135929
  mysqlMaxParametersNumber = 100000;
134374
135930
  // SQLITE_MAX_VARIABLE_NUMBER, which by default equals to 999 for SQLite versions prior to 3.32.0 (2020-05-22) or 32766 for SQLite versions after 3.32.0.
134375
135931
  sqliteMaxParametersNumber = 32766;
135932
+ mssqlMaxParametersNumber = 2100;
134376
135933
  version;
134377
135934
  generatePossibleGenerators = (connectionType, tables, relations, refinements, options) => {
134378
135935
  let columnPossibleGenerator;
@@ -134412,7 +135969,6 @@ class SeedService {
134412
135969
  };
134413
135970
  }
134414
135971
  }
134415
- // handling refinements (count, with)
134416
135972
  if (refinements !== undefined && refinements[table.name] !== undefined) {
134417
135973
  if (refinements[table.name].count !== undefined) {
134418
135974
  tablesPossibleGenerators[i].count = refinements[table.name].count;
@@ -134468,29 +136024,17 @@ class SeedService {
134468
136024
  notNull: col.notNull,
134469
136025
  primary: col.primary,
134470
136026
  generatedIdentityType: col.generatedIdentityType,
136027
+ identity: col.identity,
134471
136028
  generator: undefined,
134472
136029
  isCyclic: false,
134473
136030
  wasDefinedBefore: false,
134474
136031
  wasRefined: false,
134475
136032
  };
134476
- // handling refinements (columnGenerator)
134477
136033
  if (refinements !== undefined
134478
136034
  && refinements[table.name] !== undefined
134479
136035
  && refinements[table.name].columns !== undefined
134480
136036
  && refinements[table.name].columns[col.name] !== undefined) {
134481
136037
  const genObj = refinements[table.name].columns[col.name];
134482
- if (genObj === false) {
134483
- if (col.notNull === true && col.hasDefault === false) {
134484
- throw new Error(`You cannot set the '${col.name}' column in the '${table.name}' table to false in your refinements.`
134485
- + `\nDoing so will result in a null value being inserted into the '${col.name}' column,`
134486
- + `\nwhich will cause an error because the column has a not null constraint and no default value.`);
134487
- }
134488
- // Generating undefined as a value for a column and then inserting it via drizzle-orm
134489
- // will result in the value not being inserted into that column.
134490
- columnPossibleGenerator.generator = new generatorsMap.GenerateDefault[0]({ defaultValue: undefined });
134491
- columnPossibleGenerator.wasRefined = true;
134492
- continue;
134493
- }
134494
136038
  if (col.columnType.match(/\[\w*]/g) !== null) {
134495
136039
  if ((col.baseColumn?.dataType === 'array' && col.baseColumn.columnType.match(/\[\w*]/g) !== null)
134496
136040
  // studio case
@@ -134536,17 +136080,27 @@ class SeedService {
134536
136080
  }
134537
136081
  } // TODO: rewrite pickGeneratorFor... using new col properties: isUnique and notNull
134538
136082
  else if (connectionType === 'postgresql') {
134539
- columnPossibleGenerator.generator = this.selectGeneratorForPostgresColumn(table, col);
136083
+ columnPossibleGenerator.generator = selectGeneratorForPostgresColumn(table, col);
134540
136084
  }
134541
136085
  else if (connectionType === 'mysql') {
134542
- columnPossibleGenerator.generator = this.selectGeneratorForMysqlColumn(table, col);
136086
+ columnPossibleGenerator.generator = selectGeneratorForMysqlColumn(table, col);
134543
136087
  }
134544
136088
  else if (connectionType === 'sqlite') {
134545
- columnPossibleGenerator.generator = this.selectGeneratorForSqlite(table, col);
136089
+ columnPossibleGenerator.generator = selectGeneratorForSqlite(table, col);
136090
+ }
136091
+ else if (connectionType === 'mssql') {
136092
+ columnPossibleGenerator.generator = selectGeneratorForMssqlColumn(table, col);
136093
+ }
136094
+ else if (connectionType === 'cockroach') {
136095
+ columnPossibleGenerator.generator = selectGeneratorForCockroachColumn(table, col);
136096
+ }
136097
+ else if (connectionType === 'singlestore') {
136098
+ columnPossibleGenerator.generator = selectGeneratorForSingleStoreColumn(table, col);
134546
136099
  }
134547
136100
  if (columnPossibleGenerator.generator === undefined) {
134548
136101
  throw new Error(`column with type ${col.columnType} is not supported for now.`);
134549
136102
  }
136103
+ columnPossibleGenerator.generator.typeParams = col.typeParams ?? columnPossibleGenerator.generator.typeParams;
134550
136104
  const arrayGen = columnPossibleGenerator.generator.replaceIfArray();
134551
136105
  if (arrayGen !== undefined) {
134552
136106
  columnPossibleGenerator.generator = arrayGen;
@@ -134561,7 +136115,7 @@ class SeedService {
134561
136115
  // TODO: for now only GenerateValuesFromArray support notNull property
134562
136116
  columnPossibleGenerator.generator.notNull = col.notNull;
134563
136117
  columnPossibleGenerator.generator.dataType = col.dataType;
134564
- columnPossibleGenerator.generator.stringLength = col.typeParams.length;
136118
+ // columnPossibleGenerator.generator.stringLength = col.typeParams.length;
134565
136119
  tablePossibleGenerators.columnsPossibleGenerators.push(columnPossibleGenerator);
134566
136120
  }
134567
136121
  }
@@ -134572,7 +136126,7 @@ class SeedService {
134572
136126
  if (entityKind === 'GenerateArray') {
134573
136127
  const oldBaseColumnGen = generator.params.baseColumnGen;
134574
136128
  const newBaseColumnGen = this.selectVersionOfGenerator(oldBaseColumnGen);
134575
- // newGenerator.baseColumnDataType = oldGenerator.baseColumnDataType;
136129
+ newBaseColumnGen.typeParams = oldBaseColumnGen.typeParams;
134576
136130
  generator.params.baseColumnGen = newBaseColumnGen;
134577
136131
  }
134578
136132
  const possibleGeneratorConstructors = generatorsMap[entityKind];
@@ -134588,7 +136142,8 @@ class SeedService {
134588
136142
  // TODO: for now only GenerateValuesFromArray support notNull property
134589
136143
  newGenerator.notNull = generator.notNull;
134590
136144
  newGenerator.dataType = generator.dataType;
134591
- newGenerator.stringLength = generator.stringLength;
136145
+ // newGenerator.stringLength = generator.stringLength;
136146
+ newGenerator.typeParams = generator.typeParams ?? newGenerator.typeParams;
134592
136147
  return newGenerator;
134593
136148
  };
134594
136149
  cyclicTablesCompare = (table1, table2, relation, reverseRelation) => {
@@ -134699,474 +136254,6 @@ class SeedService {
134699
136254
  }
134700
136255
  return weightedWithCount;
134701
136256
  };
134702
- // TODO: revise serial part generators
134703
- selectGeneratorForPostgresColumn = (table, col) => {
134704
- const pickGenerator = (table, col) => {
134705
- // ARRAY
134706
- if (col.columnType.match(/\[\w*]/g) !== null && col.baseColumn !== undefined) {
134707
- const baseColumnGen = this.selectGeneratorForPostgresColumn(table, col.baseColumn);
134708
- if (baseColumnGen === undefined) {
134709
- throw new Error(`column with type ${col.baseColumn.columnType} is not supported for now.`);
134710
- }
134711
- // const getBaseColumnDataType = (baseColumn: Column) => {
134712
- // if (baseColumn.baseColumn !== undefined) {
134713
- // return getBaseColumnDataType(baseColumn.baseColumn);
134714
- // }
134715
- // return baseColumn.dataType;
134716
- // };
134717
- // const baseColumnDataType = getBaseColumnDataType(col.baseColumn);
134718
- const generator = new generatorsMap.GenerateArray[0]({ baseColumnGen, size: col.size });
134719
- // generator.baseColumnDataType = baseColumnDataType;
134720
- return generator;
134721
- }
134722
- // ARRAY for studio
134723
- if (col.columnType.match(/\[\w*]/g) !== null) {
134724
- // remove dimensions from type
134725
- const baseColumnType = col.columnType.replace(/\[\w*]/g, '');
134726
- const baseColumn = {
134727
- ...col,
134728
- };
134729
- baseColumn.columnType = baseColumnType;
134730
- const baseColumnGen = this.selectGeneratorForPostgresColumn(table, baseColumn);
134731
- if (baseColumnGen === undefined) {
134732
- throw new Error(`column with type ${col.baseColumn.columnType} is not supported for now.`);
134733
- }
134734
- let generator = new generatorsMap.GenerateArray[0]({ baseColumnGen });
134735
- for (let i = 0; i < col.typeParams.dimensions - 1; i++) {
134736
- generator = new generatorsMap.GenerateArray[0]({ baseColumnGen: generator });
134737
- }
134738
- return generator;
134739
- }
134740
- // INT ------------------------------------------------------------------------------------------------------------
134741
- if ((['smallserial', 'serial', 'bigserial'].includes(col.columnType)
134742
- || ['smallint', 'integer', 'bigint'].includes(col.columnType))
134743
- && table.primaryKeys.includes(col.name)) {
134744
- const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
134745
- return generator;
134746
- }
134747
- let minValue;
134748
- let maxValue;
134749
- if (['smallserial', 'serial', 'bigserial'].includes(col.columnType)) {
134750
- minValue = 1;
134751
- if (col.columnType === 'smallserial') {
134752
- // 2^16 / 2 - 1, 2 bytes
134753
- maxValue = 32767;
134754
- }
134755
- else if (col.columnType === 'serial') {
134756
- // 2^32 / 2 - 1, 4 bytes
134757
- maxValue = 2147483647;
134758
- }
134759
- else if (col.columnType === 'bigserial') {
134760
- // 2^64 / 2 - 1, 8 bytes
134761
- minValue = BigInt(1);
134762
- maxValue = BigInt('9223372036854775807');
134763
- }
134764
- }
134765
- else if (['smallint', 'integer', 'bigint'].includes(col.columnType)) {
134766
- if (col.columnType === 'smallint') {
134767
- // 2^16 / 2 - 1, 2 bytes
134768
- minValue = -32768;
134769
- maxValue = 32767;
134770
- }
134771
- else if (col.columnType === 'integer') {
134772
- // 2^32 / 2 - 1, 4 bytes
134773
- minValue = -2147483648;
134774
- maxValue = 2147483647;
134775
- }
134776
- else if (col.columnType.includes('bigint')) {
134777
- if (col.dataType === 'bigint') {
134778
- // 2^64 / 2 - 1, 8 bytes
134779
- minValue = BigInt('-9223372036854775808');
134780
- maxValue = BigInt('9223372036854775807');
134781
- }
134782
- else {
134783
- // if (col.dataType === 'number')
134784
- // if you’re expecting values above 2^31 but below 2^53
134785
- minValue = -9007199254740991;
134786
- maxValue = 9007199254740991;
134787
- }
134788
- }
134789
- }
134790
- if (['smallint', 'integer', 'bigint'].includes(col.columnType)) {
134791
- const generator = new generatorsMap.GenerateInt[0]({
134792
- minValue,
134793
- maxValue,
134794
- });
134795
- return generator;
134796
- }
134797
- if (['smallserial', 'serial', 'bigserial'].includes(col.columnType)) {
134798
- const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
134799
- generator.maxValue = maxValue;
134800
- return generator;
134801
- }
134802
- // NUMBER(real, double, decimal, numeric)
134803
- if (col.columnType === 'real'
134804
- || col.columnType === 'double precision'
134805
- || col.columnType.match(/^decimal(\(\d{1,6}(, ?-?\d{0,5})?\))?$/) !== null
134806
- || col.columnType.match(/^numeric(\(\d{1,6}(, ?-?\d{0,5})?\))?$/) !== null) {
134807
- if (col.typeParams.precision !== undefined) {
134808
- const precision = col.typeParams.precision;
134809
- const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
134810
- const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
134811
- const generator = new generatorsMap.GenerateNumber[0]({
134812
- minValue: -maxAbsoluteValue,
134813
- maxValue: maxAbsoluteValue,
134814
- precision: Math.pow(10, scale),
134815
- });
134816
- return generator;
134817
- }
134818
- const generator = new generatorsMap.GenerateNumber[0]();
134819
- return generator;
134820
- }
134821
- // STRING
134822
- if ((col.columnType === 'text'
134823
- || col.columnType.match(/^varchar(\(\d+\))?$/) !== null
134824
- || col.columnType.match(/^char(\(\d+\))?$/) !== null)
134825
- && table.primaryKeys.includes(col.name)) {
134826
- const generator = new generatorsMap.GenerateUniqueString[0]();
134827
- return generator;
134828
- }
134829
- if ((col.columnType === 'text'
134830
- || col.columnType.match(/^varchar(\(\d+\))?$/) !== null
134831
- || col.columnType.match(/^char(\(\d+\))?$/) !== null)
134832
- && col.name.toLowerCase().includes('name')) {
134833
- const generator = new generatorsMap.GenerateFirstName[0]();
134834
- return generator;
134835
- }
134836
- if ((col.columnType === 'text'
134837
- || col.columnType.match(/^varchar(\(\d+\))?$/) !== null
134838
- || col.columnType.match(/^char(\(\d+\))?$/) !== null)
134839
- && col.name.toLowerCase().includes('email')) {
134840
- const generator = new generatorsMap.GenerateEmail[0]();
134841
- return generator;
134842
- }
134843
- if (col.columnType === 'text'
134844
- || col.columnType.match(/^varchar(\(\d+\))?$/) !== null
134845
- || col.columnType.match(/^char(\(\d+\))?$/) !== null) {
134846
- const generator = new generatorsMap.GenerateString[0]();
134847
- return generator;
134848
- }
134849
- // UUID
134850
- if (col.columnType === 'uuid') {
134851
- const generator = new generatorsMap.GenerateUUID[0]();
134852
- return generator;
134853
- }
134854
- // BOOLEAN
134855
- if (col.columnType === 'boolean') {
134856
- const generator = new generatorsMap.GenerateBoolean[0]();
134857
- return generator;
134858
- }
134859
- // DATE, TIME, TIMESTAMP
134860
- if (col.columnType === 'date') {
134861
- const generator = new generatorsMap.GenerateDate[0]();
134862
- return generator;
134863
- }
134864
- if (col.columnType.match(/^time((\(\d+\))|( with time zone))?$/) !== null) {
134865
- const generator = new generatorsMap.GenerateTime[0]();
134866
- return generator;
134867
- }
134868
- if (col.columnType.match(/^timestamp((\(\d+\))|( with time zone))?$/) !== null) {
134869
- const generator = new generatorsMap.GenerateTimestamp[0]();
134870
- return generator;
134871
- }
134872
- // JSON, JSONB
134873
- if (col.columnType === 'json' || col.columnType === 'jsonb') {
134874
- const generator = new generatorsMap.GenerateJson[0]();
134875
- return generator;
134876
- }
134877
- // if (col.columnType === "jsonb") {
134878
- // const generator = new GenerateJsonb({});
134879
- // return generator;
134880
- // }
134881
- // ENUM
134882
- if (col.enumValues !== undefined) {
134883
- const generator = new generatorsMap.GenerateEnum[0]({
134884
- enumValues: col.enumValues,
134885
- });
134886
- return generator;
134887
- }
134888
- // INTERVAL
134889
- if (col.columnType.match(/^interval( .+)?$/) !== null) {
134890
- if (col.columnType === 'interval') {
134891
- const generator = new generatorsMap.GenerateInterval[0]();
134892
- return generator;
134893
- }
134894
- const fields = col.columnType.replace('interval ', '');
134895
- const generator = new generatorsMap.GenerateInterval[0]({ fields });
134896
- return generator;
134897
- }
134898
- // POINT, LINE
134899
- if (col.columnType === 'point') {
134900
- const generator = new generatorsMap.GeneratePoint[0]();
134901
- return generator;
134902
- }
134903
- if (col.columnType === 'line') {
134904
- const generator = new generatorsMap.GenerateLine[0]();
134905
- return generator;
134906
- }
134907
- if (col.hasDefault && col.default !== undefined) {
134908
- const generator = new generatorsMap.GenerateDefault[0]({
134909
- defaultValue: col.default,
134910
- });
134911
- return generator;
134912
- }
134913
- return;
134914
- };
134915
- const generator = pickGenerator(table, col);
134916
- if (generator !== undefined) {
134917
- generator.isUnique = col.isUnique;
134918
- generator.dataType = col.dataType;
134919
- generator.stringLength = col.typeParams.length;
134920
- }
134921
- return generator;
134922
- };
134923
- selectGeneratorForMysqlColumn = (table, col) => {
134924
- const pickGenerator = (table, col) => {
134925
- // INT ------------------------------------------------------------------------------------------------------------
134926
- if ((col.columnType === 'serial'
134927
- || ['tinyint', 'smallint', 'mediumint', 'int', 'bigint'].includes(col.columnType))
134928
- && table.primaryKeys.includes(col.name)) {
134929
- const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
134930
- return generator;
134931
- }
134932
- let minValue;
134933
- let maxValue;
134934
- if (col.columnType === 'serial') {
134935
- // 2^64 % 2 - 1, 8 bytes
134936
- minValue = BigInt(0);
134937
- maxValue = BigInt('9223372036854775807');
134938
- }
134939
- else if (['tinyint', 'smallint', 'mediumint', 'int', 'bigint'].includes(col.columnType)) {
134940
- if (col.columnType === 'tinyint') {
134941
- // 2^8 / 2 - 1, 1 bytes
134942
- minValue = -128;
134943
- maxValue = 127;
134944
- }
134945
- else if (col.columnType === 'smallint') {
134946
- // 2^16 / 2 - 1, 2 bytes
134947
- minValue = -32768;
134948
- maxValue = 32767;
134949
- }
134950
- else if (col.columnType === 'mediumint') {
134951
- // 2^16 / 2 - 1, 2 bytes
134952
- minValue = -8388608;
134953
- maxValue = 8388607;
134954
- }
134955
- else if (col.columnType === 'int') {
134956
- // 2^32 / 2 - 1, 4 bytes
134957
- minValue = -2147483648;
134958
- maxValue = 2147483647;
134959
- }
134960
- else if (col.columnType === 'bigint') {
134961
- // 2^64 / 2 - 1, 8 bytes
134962
- minValue = BigInt('-9223372036854775808');
134963
- maxValue = BigInt('9223372036854775807');
134964
- }
134965
- }
134966
- if (['tinyint', 'smallint', 'mediumint', 'int', 'bigint'].includes(col.columnType)) {
134967
- const generator = new generatorsMap.GenerateInt[0]({
134968
- minValue,
134969
- maxValue,
134970
- });
134971
- return generator;
134972
- }
134973
- if (col.columnType === 'serial') {
134974
- const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
134975
- generator.maxValue = maxValue;
134976
- return generator;
134977
- }
134978
- // NUMBER(real, double, decimal, float)
134979
- if (col.columnType === 'real'
134980
- || col.columnType === 'double'
134981
- || col.columnType === 'float'
134982
- || col.columnType.startsWith('decimal')
134983
- || col.columnType.startsWith('numeric')) {
134984
- if (col.typeParams.precision !== undefined) {
134985
- const precision = col.typeParams.precision;
134986
- const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
134987
- const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
134988
- const generator = new generatorsMap.GenerateNumber[0]({
134989
- minValue: -maxAbsoluteValue,
134990
- maxValue: maxAbsoluteValue,
134991
- precision: Math.pow(10, scale),
134992
- });
134993
- return generator;
134994
- }
134995
- const generator = new generatorsMap.GenerateNumber[0]();
134996
- return generator;
134997
- }
134998
- // STRING
134999
- if ((col.columnType === 'text'
135000
- || col.columnType === 'blob'
135001
- || col.columnType.startsWith('char')
135002
- || col.columnType.startsWith('varchar')
135003
- || col.columnType.startsWith('binary')
135004
- || col.columnType.startsWith('varbinary'))
135005
- && table.primaryKeys.includes(col.name)) {
135006
- const generator = new generatorsMap.GenerateUniqueString[0]();
135007
- return generator;
135008
- }
135009
- if ((col.columnType === 'text'
135010
- || col.columnType === 'blob'
135011
- || col.columnType.startsWith('char')
135012
- || col.columnType.startsWith('varchar')
135013
- || col.columnType.startsWith('binary')
135014
- || col.columnType.startsWith('varbinary'))
135015
- && col.name.toLowerCase().includes('name')) {
135016
- const generator = new generatorsMap.GenerateFirstName[0]();
135017
- return generator;
135018
- }
135019
- if ((col.columnType === 'text'
135020
- || col.columnType === 'blob'
135021
- || col.columnType.startsWith('char')
135022
- || col.columnType.startsWith('varchar')
135023
- || col.columnType.startsWith('binary')
135024
- || col.columnType.startsWith('varbinary'))
135025
- && col.name.toLowerCase().includes('email')) {
135026
- const generator = new generatorsMap.GenerateEmail[0]();
135027
- return generator;
135028
- }
135029
- if (col.columnType === 'text'
135030
- || col.columnType === 'blob'
135031
- || col.columnType.startsWith('char')
135032
- || col.columnType.startsWith('varchar')
135033
- || col.columnType.startsWith('binary')
135034
- || col.columnType.startsWith('varbinary')) {
135035
- const generator = new generatorsMap.GenerateString[0]();
135036
- return generator;
135037
- }
135038
- // BOOLEAN
135039
- if (col.columnType === 'boolean') {
135040
- const generator = new generatorsMap.GenerateBoolean[0]();
135041
- return generator;
135042
- }
135043
- // DATE, TIME, TIMESTAMP, DATETIME, YEAR
135044
- if (col.columnType.startsWith('datetime')) {
135045
- const generator = new generatorsMap.GenerateDatetime[0]();
135046
- return generator;
135047
- }
135048
- if (col.columnType === 'date') {
135049
- const generator = new generatorsMap.GenerateDate[0]();
135050
- return generator;
135051
- }
135052
- if (col.columnType === 'time') {
135053
- const generator = new generatorsMap.GenerateTime[0]();
135054
- return generator;
135055
- }
135056
- if (col.columnType.startsWith('timestamp')) {
135057
- const generator = new generatorsMap.GenerateTimestamp[0]();
135058
- return generator;
135059
- }
135060
- if (col.columnType === 'year') {
135061
- const generator = new generatorsMap.GenerateYear[0]();
135062
- return generator;
135063
- }
135064
- // JSON
135065
- if (col.columnType === 'json') {
135066
- const generator = new generatorsMap.GenerateJson[0]();
135067
- return generator;
135068
- }
135069
- // ENUM
135070
- if (col.enumValues !== undefined) {
135071
- const generator = new generatorsMap.GenerateEnum[0]({
135072
- enumValues: col.enumValues,
135073
- });
135074
- return generator;
135075
- }
135076
- if (col.hasDefault && col.default !== undefined) {
135077
- const generator = new generatorsMap.GenerateDefault[0]({
135078
- defaultValue: col.default,
135079
- });
135080
- return generator;
135081
- }
135082
- return;
135083
- };
135084
- const generator = pickGenerator(table, col);
135085
- return generator;
135086
- };
135087
- selectGeneratorForSqlite = (table, col) => {
135088
- const pickGenerator = (table, col) => {
135089
- // int section ---------------------------------------------------------------------------------------
135090
- if ((col.columnType === 'integer' || col.columnType === 'numeric')
135091
- && table.primaryKeys.includes(col.name)) {
135092
- const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
135093
- return generator;
135094
- }
135095
- if (col.columnType === 'integer' && col.dataType === 'boolean') {
135096
- const generator = new generatorsMap.GenerateBoolean[0]();
135097
- return generator;
135098
- }
135099
- if ((col.columnType === 'integer' && col.dataType === 'date')) {
135100
- const generator = new generatorsMap.GenerateTimestamp[0]();
135101
- return generator;
135102
- }
135103
- if (col.columnType === 'integer'
135104
- || (col.dataType === 'bigint' && col.columnType === 'blob')) {
135105
- const generator = new generatorsMap.GenerateInt[0]();
135106
- return generator;
135107
- }
135108
- // number section ------------------------------------------------------------------------------------
135109
- if (col.columnType.startsWith('real')
135110
- || col.columnType.startsWith('numeric')) {
135111
- if (col.typeParams.precision !== undefined) {
135112
- const precision = col.typeParams.precision;
135113
- const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
135114
- const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
135115
- const generator = new generatorsMap.GenerateNumber[0]({
135116
- minValue: -maxAbsoluteValue,
135117
- maxValue: maxAbsoluteValue,
135118
- precision: Math.pow(10, scale),
135119
- });
135120
- return generator;
135121
- }
135122
- const generator = new generatorsMap.GenerateNumber[0]();
135123
- return generator;
135124
- }
135125
- // string section ------------------------------------------------------------------------------------
135126
- if ((col.columnType.startsWith('text')
135127
- || col.columnType.startsWith('numeric')
135128
- || col.columnType.startsWith('blob'))
135129
- && table.primaryKeys.includes(col.name)) {
135130
- const generator = new generatorsMap.GenerateUniqueString[0]();
135131
- return generator;
135132
- }
135133
- if ((col.columnType.startsWith('text')
135134
- || col.columnType.startsWith('numeric')
135135
- || col.columnType.startsWith('blob'))
135136
- && col.name.toLowerCase().includes('name')) {
135137
- const generator = new generatorsMap.GenerateFirstName[0]();
135138
- return generator;
135139
- }
135140
- if ((col.columnType.startsWith('text')
135141
- || col.columnType.startsWith('numeric')
135142
- || col.columnType.startsWith('blob'))
135143
- && col.name.toLowerCase().includes('email')) {
135144
- const generator = new generatorsMap.GenerateEmail[0]();
135145
- return generator;
135146
- }
135147
- if (col.columnType.startsWith('text')
135148
- || col.columnType.startsWith('numeric')
135149
- || col.columnType.startsWith('blob')
135150
- || col.columnType.startsWith('blobbuffer')) {
135151
- const generator = new generatorsMap.GenerateString[0]();
135152
- return generator;
135153
- }
135154
- if ((col.columnType.startsWith('text') && col.dataType === 'json')
135155
- || (col.columnType.startsWith('blob') && col.dataType === 'json')) {
135156
- const generator = new generatorsMap.GenerateJson[0]();
135157
- return generator;
135158
- }
135159
- if (col.hasDefault && col.default !== undefined) {
135160
- const generator = new generatorsMap.GenerateDefault[0]({
135161
- defaultValue: col.default,
135162
- });
135163
- return generator;
135164
- }
135165
- return;
135166
- };
135167
- const generator = pickGenerator(table, col);
135168
- return generator;
135169
- };
135170
136257
  filterCyclicTables = (tablesGenerators) => {
135171
136258
  const filteredTablesGenerators = tablesGenerators.filter((tableGen) => tableGen.columnsPossibleGenerators.some((columnGen) => columnGen.isCyclic === true && columnGen.wasDefinedBefore === true));
135172
136259
  const tablesUniqueNotNullColumn = {};
@@ -135178,7 +136265,8 @@ class SeedService {
135178
136265
  throw new Error(`Table '${tableGen.tableName}' does not have primary or (unique and notNull) column. Can't seed table with cyclic relation.`);
135179
136266
  }
135180
136267
  tablesUniqueNotNullColumn[tableGen.tableName] = { uniqueNotNullColName };
135181
- filteredTablesGenerators[idx].columnsPossibleGenerators = tableGen.columnsPossibleGenerators.filter((colGen) => (colGen.isCyclic === true && colGen.wasDefinedBefore === true) || colGen.columnName === uniqueNotNullColName).map((colGen) => {
136268
+ filteredTablesGenerators[idx].columnsPossibleGenerators = tableGen.columnsPossibleGenerators.filter((colGen) => (colGen.isCyclic === true && colGen.wasDefinedBefore === true) || colGen.columnName === uniqueNotNullColName)
136269
+ .map((colGen) => {
135182
136270
  const newColGen = { ...colGen };
135183
136271
  newColGen.wasDefinedBefore = false;
135184
136272
  return newColGen;
@@ -135272,7 +136360,9 @@ class SeedService {
135272
136360
  weightedCountSeed = table.withFromTable[rel.refTable].weightedCountSeed;
135273
136361
  }
135274
136362
  // TODO: revise maybe need to select version of generator here too
135275
- genObj = new generatorsMap.GenerateValuesFromArray[0]({ values: refColumnValues });
136363
+ genObj = new generatorsMap.GenerateValuesFromArray[0]({
136364
+ values: refColumnValues,
136365
+ });
135276
136366
  genObj.notNull = tableGenerators[rel.columns[colIdx]].notNull;
135277
136367
  genObj.weightedCountSeed = weightedCountSeed;
135278
136368
  genObj.maxRepeatedValuesCount = repeatedValuesCount;
@@ -135340,7 +136430,10 @@ class SeedService {
135340
136430
  for (const columnName of Object.keys(tableGenerators)) {
135341
136431
  columnsNumber += 1;
135342
136432
  columnGenerator = tableGenerators[columnName];
136433
+ // postgres identity columns
135343
136434
  override = tableGenerators[columnName]?.generatedIdentityType === 'always' ? true : override;
136435
+ // mssql identity columns
136436
+ override = tableGenerators[columnName]?.identity === true ? true : override;
135344
136437
  columnsGenerators[columnName] = columnGenerator.generator;
135345
136438
  columnsGenerators[columnName].init({
135346
136439
  count,
@@ -135365,10 +136458,13 @@ class SeedService {
135365
136458
  else if (drizzleOrm.is(db, (mysqlCore.MySqlDatabase))) {
135366
136459
  maxParametersNumber = this.mysqlMaxParametersNumber;
135367
136460
  }
135368
- else {
135369
- // is(db, BaseSQLiteDatabase<any, any>)
136461
+ else if (drizzleOrm.is(db, (sqliteCore.BaseSQLiteDatabase))) {
135370
136462
  maxParametersNumber = this.sqliteMaxParametersNumber;
135371
136463
  }
136464
+ else {
136465
+ // is(db, MsSqlDatabase<any, any>)
136466
+ maxParametersNumber = this.mssqlMaxParametersNumber;
136467
+ }
135372
136468
  const maxBatchSize = Math.floor(maxParametersNumber / columnsNumber);
135373
136469
  batchSize = batchSize > maxBatchSize ? maxBatchSize : batchSize;
135374
136470
  if ((insertDataInDb === true || updateDataInDb === true)
@@ -135453,249 +136549,726 @@ class SeedService {
135453
136549
  .insert(schema[tableName])
135454
136550
  .values(generatedValues);
135455
136551
  }
136552
+ else if (drizzleOrm.is(db, (mssqlCore.MsSqlDatabase))) {
136553
+ let schemaDbName;
136554
+ let tableDbName;
136555
+ if (override === true) {
136556
+ const tableConfig = mssqlCore.getTableConfig(schema[tableName]);
136557
+ schemaDbName = tableConfig.schema ?? 'dbo';
136558
+ tableDbName = tableConfig.name;
136559
+ await db.execute(drizzleOrm.sql.raw(`SET IDENTITY_INSERT [${schemaDbName}].[${tableDbName}] ON;`));
136560
+ }
136561
+ await db
136562
+ .insert(schema[tableName])
136563
+ .values(generatedValues);
136564
+ if (override === true) {
136565
+ await db.execute(drizzleOrm.sql.raw(`SET IDENTITY_INSERT [${schemaDbName}].[${tableDbName}] OFF;`));
136566
+ }
136567
+ }
136568
+ else if (drizzleOrm.is(db, (cockroachCore.CockroachDatabase))) {
136569
+ const query = db
136570
+ .insert(schema[tableName])
136571
+ .values(generatedValues);
136572
+ await query;
136573
+ }
136574
+ else if (drizzleOrm.is(db, (singlestoreCore.SingleStoreDatabase))) {
136575
+ const query = db
136576
+ .insert(schema[tableName])
136577
+ .values(generatedValues);
136578
+ await query;
136579
+ }
135456
136580
  };
135457
136581
  updateDb = async ({ generatedValues, db, schema, tableName, uniqueNotNullColName, }) => {
136582
+ let values = generatedValues[0];
136583
+ const uniqueNotNullColValue = values[uniqueNotNullColName];
136584
+ values = Object.fromEntries(Object.entries(values).filter(([colName]) => colName !== uniqueNotNullColName));
135458
136585
  if (drizzleOrm.is(db, (pgCore.PgDatabase))) {
135459
136586
  const table = schema[tableName];
135460
136587
  const uniqueNotNullCol = table[uniqueNotNullColName];
135461
- await db.update(table).set(generatedValues[0]).where(drizzleOrm.eq(uniqueNotNullCol, generatedValues[0][uniqueNotNullColName]));
136588
+ await db.update(table).set(values).where(drizzleOrm.eq(uniqueNotNullCol, uniqueNotNullColValue));
135462
136589
  }
135463
136590
  else if (drizzleOrm.is(db, (mysqlCore.MySqlDatabase))) {
135464
136591
  const table = schema[tableName];
135465
- await db.update(table).set(generatedValues[0]).where(drizzleOrm.eq(table[uniqueNotNullColName], generatedValues[0][uniqueNotNullColName]));
136592
+ await db.update(table).set(values).where(drizzleOrm.eq(table[uniqueNotNullColName], uniqueNotNullColValue));
135466
136593
  }
135467
136594
  else if (drizzleOrm.is(db, (sqliteCore.BaseSQLiteDatabase))) {
135468
136595
  const table = schema[tableName];
135469
- await db.update(table).set(generatedValues[0]).where(drizzleOrm.eq(table[uniqueNotNullColName], generatedValues[0][uniqueNotNullColName]));
136596
+ await db.update(table).set(values).where(drizzleOrm.eq(table[uniqueNotNullColName], uniqueNotNullColValue));
136597
+ }
136598
+ else if (drizzleOrm.is(db, (mssqlCore.MsSqlDatabase))) {
136599
+ const table = schema[tableName];
136600
+ await db.update(table).set(values).where(drizzleOrm.eq(table[uniqueNotNullColName], uniqueNotNullColValue));
136601
+ }
136602
+ else if (drizzleOrm.is(db, (cockroachCore.CockroachDatabase))) {
136603
+ const table = schema[tableName];
136604
+ await db.update(table).set(values).where(drizzleOrm.eq(table[uniqueNotNullColName], uniqueNotNullColValue));
136605
+ }
136606
+ else if (drizzleOrm.is(db, (singlestoreCore.SingleStoreDatabase))) {
136607
+ const table = schema[tableName];
136608
+ await db.update(table).set(values).where(drizzleOrm.eq(table[uniqueNotNullColName], uniqueNotNullColValue));
135470
136609
  }
135471
136610
  };
135472
136611
  }
135473
136612
 
135474
- /* eslint-disable drizzle-internal/require-entity-kind */
135475
- class SeedPromise {
135476
- db;
135477
- schema;
135478
- options;
135479
- static entityKind = 'SeedPromise';
135480
- [Symbol.toStringTag] = 'SeedPromise';
135481
- constructor(db, schema, options) {
135482
- this.db = db;
135483
- this.schema = schema;
135484
- this.options = options;
135485
- }
135486
- then(onfulfilled, onrejected) {
135487
- return seedFunc(this.db, this.schema, this.options).then(onfulfilled, onrejected);
135488
- }
135489
- catch(onrejected) {
135490
- return this.then(undefined, onrejected);
135491
- }
135492
- finally(onfinally) {
135493
- return this.then((value) => {
135494
- onfinally?.();
135495
- return value;
135496
- }, (reason) => {
135497
- onfinally?.();
135498
- throw reason;
136613
+ // Cockroach-----------------------------------------------------------------------------------------------------------
136614
+ const resetCockroach = async (db, cockroachTables) => {
136615
+ const tablesToTruncate = Object.entries(cockroachTables).map(([_, table]) => {
136616
+ const config = cockroachCore.getTableConfig(table);
136617
+ config.schema = config.schema === undefined ? 'public' : config.schema;
136618
+ return `"${config.schema}"."${config.name}"`;
136619
+ });
136620
+ await db.execute(drizzleOrm.sql.raw(`truncate ${tablesToTruncate.join(',')} cascade;`));
136621
+ };
136622
+ const filterCockroachSchema = (schema) => {
136623
+ const cockroachSchema = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], cockroachCore.CockroachTable) || drizzleOrm.is(keyValue[1], drizzleOrm.Relations)));
136624
+ const cockroachTables = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], cockroachCore.CockroachTable)));
136625
+ return { cockroachSchema, cockroachTables };
136626
+ };
136627
+ const seedCockroach = async (db, schema, options = {}, refinements) => {
136628
+ const seedService = new SeedService();
136629
+ const { cockroachSchema, cockroachTables } = filterCockroachSchema(schema);
136630
+ const { tables, relations } = getCockroachInfo(cockroachSchema, cockroachTables);
136631
+ const generatedTablesGenerators = seedService.generatePossibleGenerators('cockroach', tables, relations, refinements, options);
136632
+ const preserveCyclicTablesData = relations.some((rel) => rel.isCyclic === true);
136633
+ const tablesValues = await seedService.generateTablesValues(relations, generatedTablesGenerators, db, cockroachTables, { ...options, preserveCyclicTablesData });
136634
+ const { filteredTablesGenerators, tablesUniqueNotNullColumn } = seedService.filterCyclicTables(generatedTablesGenerators);
136635
+ const updateDataInDb = filteredTablesGenerators.length === 0 ? false : true;
136636
+ await seedService.generateTablesValues(relations, filteredTablesGenerators, db, cockroachTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
136637
+ };
136638
+ const getCockroachInfo = (cockroachSchema, cockroachTables) => {
136639
+ let tableConfig;
136640
+ let dbToTsColumnNamesMap;
136641
+ const dbToTsTableNamesMap = Object.fromEntries(Object.entries(cockroachTables).map(([key, value]) => [drizzleOrm.getTableName(value), key]));
136642
+ const tables = [];
136643
+ const relations = [];
136644
+ const dbToTsColumnNamesMapGlobal = {};
136645
+ const tableRelations = {};
136646
+ const getDbToTsColumnNamesMap = (table) => {
136647
+ let dbToTsColumnNamesMap = {};
136648
+ const tableName = drizzleOrm.getTableName(table);
136649
+ if (Object.hasOwn(dbToTsColumnNamesMapGlobal, tableName)) {
136650
+ dbToTsColumnNamesMap = dbToTsColumnNamesMapGlobal[tableName];
136651
+ return dbToTsColumnNamesMap;
136652
+ }
136653
+ const tableConfig = cockroachCore.getTableConfig(table);
136654
+ for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
136655
+ dbToTsColumnNamesMap[col.name] = tsCol;
136656
+ }
136657
+ dbToTsColumnNamesMapGlobal[tableName] = dbToTsColumnNamesMap;
136658
+ return dbToTsColumnNamesMap;
136659
+ };
136660
+ const transformFromDrizzleRelation = (schema, getDbToTsColumnNamesMap, tableRelations) => {
136661
+ const schemaConfig = drizzleOrm.extractTablesRelationalConfig(schema, drizzleOrm.createTableRelationsHelpers);
136662
+ const relations = [];
136663
+ for (const table of Object.values(schemaConfig.tables)) {
136664
+ if (table.relations === undefined)
136665
+ continue;
136666
+ for (const drizzleRel of Object.values(table.relations)) {
136667
+ if (!drizzleOrm.is(drizzleRel, drizzleOrm.One))
136668
+ continue;
136669
+ const tableConfig = cockroachCore.getTableConfig(drizzleRel.sourceTable);
136670
+ const tableDbSchema = tableConfig.schema ?? 'public';
136671
+ const tableDbName = tableConfig.name;
136672
+ const tableTsName = schemaConfig.tableNamesMap[`${tableDbSchema}.${tableDbName}`] ?? tableDbName;
136673
+ const dbToTsColumnNamesMap = getDbToTsColumnNamesMap(drizzleRel.sourceTable);
136674
+ const columns = drizzleRel.config?.fields.map((field) => dbToTsColumnNamesMap[field.name])
136675
+ ?? [];
136676
+ const refTableConfig = cockroachCore.getTableConfig(drizzleRel.referencedTable);
136677
+ const refTableDbSchema = refTableConfig.schema ?? 'public';
136678
+ const refTableDbName = refTableConfig.name;
136679
+ const refTableTsName = schemaConfig.tableNamesMap[`${refTableDbSchema}.${refTableDbName}`]
136680
+ ?? refTableDbName;
136681
+ const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(drizzleRel.referencedTable);
136682
+ const refColumns = drizzleRel.config?.references.map((ref) => dbToTsColumnNamesMapForRefTable[ref.name])
136683
+ ?? [];
136684
+ if (tableRelations[refTableTsName] === undefined) {
136685
+ tableRelations[refTableTsName] = [];
136686
+ }
136687
+ const relation = {
136688
+ table: tableTsName,
136689
+ columns,
136690
+ refTable: refTableTsName,
136691
+ refColumns,
136692
+ refTableRels: tableRelations[refTableTsName],
136693
+ type: 'one',
136694
+ };
136695
+ // do not add duplicate relation
136696
+ if (tableRelations[tableTsName]?.some((rel) => rel.table === relation.table
136697
+ && rel.refTable === relation.refTable)) {
136698
+ console.warn(`You are providing a one-to-many relation between the '${relation.refTable}' and '${relation.table}' tables,\n`
136699
+ + `while the '${relation.table}' table object already has foreign key constraint in the schema referencing '${relation.refTable}' table.\n`
136700
+ + `In this case, the foreign key constraint will be used.\n`);
136701
+ continue;
136702
+ }
136703
+ relations.push(relation);
136704
+ tableRelations[tableTsName].push(relation);
136705
+ }
136706
+ }
136707
+ return relations;
136708
+ };
136709
+ for (const table of Object.values(cockroachTables)) {
136710
+ tableConfig = cockroachCore.getTableConfig(table);
136711
+ dbToTsColumnNamesMap = {};
136712
+ for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
136713
+ dbToTsColumnNamesMap[col.name] = tsCol;
136714
+ }
136715
+ // might be empty list
136716
+ const newRelations = tableConfig.foreignKeys.map((fk) => {
136717
+ const table = dbToTsTableNamesMap[tableConfig.name];
136718
+ const refTable = dbToTsTableNamesMap[drizzleOrm.getTableName(fk.reference().foreignTable)];
136719
+ const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(fk.reference().foreignTable);
136720
+ if (tableRelations[refTable] === undefined) {
136721
+ tableRelations[refTable] = [];
136722
+ }
136723
+ return {
136724
+ table,
136725
+ columns: fk
136726
+ .reference()
136727
+ .columns.map((col) => dbToTsColumnNamesMap[col.name]),
136728
+ refTable,
136729
+ refColumns: fk
136730
+ .reference()
136731
+ .foreignColumns.map((fCol) => dbToTsColumnNamesMapForRefTable[fCol.name]),
136732
+ refTableRels: tableRelations[refTable],
136733
+ };
135499
136734
  });
135500
- }
135501
- async refine(callback) {
135502
- const refinements = this.options?.version === undefined || this.options.version === '2'
135503
- ? callback(generatorsFuncsV2)
135504
- : callback(generatorsFuncs);
135505
- await seedFunc(this.db, this.schema, this.options, refinements);
135506
- }
135507
- }
135508
- function getGeneratorsFunctions() {
135509
- return generatorsFuncs;
135510
- }
135511
- async function seedForDrizzleStudio({ sqlDialect, drizzleStudioObject, drizzleStudioRelations, schemasRefinements, options }) {
135512
- const generatedSchemas = {};
135513
- let tables, relations, refinements;
135514
- drizzleStudioRelations = drizzleStudioRelations.filter((rel) => rel.type === 'one');
135515
- for (const [schemaName, { tables: drizzleStudioTables }] of Object.entries(drizzleStudioObject)) {
135516
- tables = [];
135517
- for (const [tableName, table] of Object.entries(drizzleStudioTables)) {
135518
- const drizzleStudioColumns = Object.values(table.columns);
135519
- const columns = drizzleStudioColumns.map((col) => ({
135520
- name: col.name,
135521
- dataType: 'string',
135522
- columnType: col.type,
135523
- // TODO: revise later
135524
- typeParams: {},
135525
- default: col.default,
135526
- hasDefault: col.default === undefined ? false : true,
135527
- isUnique: col.isUnique === undefined ? false : col.isUnique,
135528
- notNull: col.notNull,
135529
- primary: col.primaryKey,
135530
- }));
135531
- tables.push({
135532
- name: tableName,
135533
- columns,
135534
- primaryKeys: drizzleStudioColumns.filter((col) => col.primaryKey === true).map((col) => col.name),
135535
- });
136735
+ relations.push(...newRelations);
136736
+ if (tableRelations[dbToTsTableNamesMap[tableConfig.name]] === undefined) {
136737
+ tableRelations[dbToTsTableNamesMap[tableConfig.name]] = [];
135536
136738
  }
135537
- relations = drizzleStudioRelations.filter((rel) => rel.schema === schemaName && rel.refSchema === schemaName);
135538
- const isCyclicRelations = relations.map((reli) => {
135539
- if (relations.some((relj) => reli.table === relj.refTable && reli.refTable === relj.table)) {
135540
- return { ...reli, isCyclic: true };
136739
+ tableRelations[dbToTsTableNamesMap[tableConfig.name]].push(...newRelations);
136740
+ const getAllBaseColumns = (baseColumn) => {
136741
+ const baseColumnResult = {
136742
+ name: baseColumn.name,
136743
+ columnType: baseColumn.getSQLType(),
136744
+ typeParams: getTypeParams(baseColumn.getSQLType()),
136745
+ dataType: baseColumn.dataType,
136746
+ size: baseColumn.size,
136747
+ hasDefault: baseColumn.hasDefault,
136748
+ enumValues: baseColumn.enumValues,
136749
+ default: baseColumn.default,
136750
+ isUnique: baseColumn.isUnique,
136751
+ notNull: baseColumn.notNull,
136752
+ primary: baseColumn.primary,
136753
+ baseColumn: baseColumn.baseColumn === undefined ? undefined : getAllBaseColumns(baseColumn.baseColumn),
136754
+ };
136755
+ return baseColumnResult;
136756
+ };
136757
+ const getTypeParams = (sqlType) => {
136758
+ // get type params
136759
+ const typeParams = {};
136760
+ // handle dimensions
136761
+ if (sqlType.includes('[')) {
136762
+ const match = sqlType.match(/\[\w*]/g);
136763
+ if (match) {
136764
+ typeParams['dimensions'] = match.length;
136765
+ }
135541
136766
  }
135542
- return { ...reli, isCyclic: false };
136767
+ if (sqlType.startsWith('numeric')
136768
+ || sqlType.startsWith('decimal')
136769
+ || sqlType.startsWith('double precision')
136770
+ || sqlType.startsWith('real')) {
136771
+ const match = sqlType.match(/\((\d+), *(\d+)\)/);
136772
+ if (match) {
136773
+ typeParams['precision'] = Number(match[1]);
136774
+ typeParams['scale'] = Number(match[2]);
136775
+ }
136776
+ }
136777
+ else if (sqlType.startsWith('varchar')
136778
+ || sqlType.startsWith('char')
136779
+ || sqlType.startsWith('bit')
136780
+ || sqlType.startsWith('vector')
136781
+ || sqlType.startsWith('time')
136782
+ || sqlType.startsWith('timestamp')
136783
+ || sqlType.startsWith('interval')) {
136784
+ const match = sqlType.match(/\((\d+)\)/);
136785
+ if (match) {
136786
+ typeParams['length'] = Number(match[1]);
136787
+ }
136788
+ }
136789
+ return typeParams;
136790
+ };
136791
+ // console.log(tableConfig.columns);
136792
+ tables.push({
136793
+ name: dbToTsTableNamesMap[tableConfig.name],
136794
+ columns: tableConfig.columns.map((column) => ({
136795
+ name: dbToTsColumnNamesMap[column.name],
136796
+ columnType: column.getSQLType(),
136797
+ typeParams: getTypeParams(column.getSQLType()),
136798
+ dataType: column.dataType,
136799
+ size: column.size,
136800
+ hasDefault: column.hasDefault,
136801
+ default: column.default,
136802
+ enumValues: column.enumValues,
136803
+ isUnique: column.isUnique,
136804
+ notNull: column.notNull,
136805
+ primary: column.primary,
136806
+ generatedIdentityType: column.generatedIdentity?.type,
136807
+ baseColumn: (column.baseColumn === undefined)
136808
+ ? undefined
136809
+ : getAllBaseColumns(column.baseColumn),
136810
+ })),
136811
+ primaryKeys: tableConfig.columns
136812
+ .filter((column) => column.primary)
136813
+ .map((column) => dbToTsColumnNamesMap[column.name]),
135543
136814
  });
135544
- refinements = schemasRefinements !== undefined && schemasRefinements[schemaName] !== undefined
135545
- ? schemasRefinements[schemaName]
135546
- : undefined;
135547
- const seedService = new SeedService();
135548
- const generatedTablesGenerators = seedService.generatePossibleGenerators(sqlDialect, tables, isCyclicRelations, refinements, options);
135549
- const generatedTables = await seedService.generateTablesValues(isCyclicRelations, generatedTablesGenerators, undefined, undefined, { ...options, preserveData: true, insertDataInDb: false });
135550
- generatedSchemas[schemaName] = { tables: generatedTables };
135551
- }
135552
- return generatedSchemas;
135553
- }
135554
- /**
135555
- * @param db - database you would like to seed.
135556
- * @param schema - object that contains all your database tables you would like to seed.
135557
- * @param options - object that contains properties `count` and `seed`:
135558
- *
135559
- * `count` - number of rows you want to generate.
135560
- *
135561
- * `seed` - a number that controls the state of generated data. (if the `seed` number is the same and nothing is changed in the seeding script, generated data will remain the same each time you seed database)
135562
- *
135563
- * @returns SeedPromise - a class object that has a refine method that is used to change generators for columns.
135564
- *
135565
- * @example
135566
- * ```ts
135567
- * // base seeding
135568
- * await seed(db, schema);
135569
- *
135570
- * // seeding with count specified
135571
- * await seed(db, schema, { count: 100000 });
135572
- *
135573
- * // seeding with count and seed specified
135574
- * await seed(db, schema, { count: 100000, seed: 1 });
135575
- *
135576
- * // seeding using refine
135577
- * await seed(db, schema, { count: 1000 }).refine((funcs) => ({
135578
- * users: {
135579
- * columns: {
135580
- * name: funcs.firstName({ isUnique: true }),
135581
- * email: funcs.email(),
135582
- * phone: funcs.phoneNumber({ template: "+380 99 ###-##-##" }),
135583
- * password: funcs.string({ isUnique: true }),
135584
- * },
135585
- * count: 100000,
135586
- * },
135587
- * posts: {
135588
- * columns: {
135589
- * title: funcs.valuesFromArray({
135590
- * values: ["Title1", "Title2", "Title3", "Title4", "Title5"],
135591
- * }),
135592
- * content: funcs.loremIpsum({ sentencesCount: 3 }),
135593
- * },
135594
- * },
135595
- * }));
135596
- *
135597
- * // seeding while ignoring column
135598
- * await seed(db, schema).refine((funcs) => ({
135599
- * users: {
135600
- * count: 5,
135601
- * columns: {
135602
- * name: funcs.fullName(),
135603
- * photo: false, // the photo column will not be seeded, allowing the database to use its default value.
135604
- * },
135605
- * },
135606
- * }));
135607
- *
135608
- * ```
135609
- */
135610
- function seed(db, schema, options) {
135611
- return new SeedPromise(db, schema, options);
135612
- }
135613
- const seedFunc = async (db, schema, options = {}, refinements) => {
135614
- let version;
135615
- if (options?.version !== undefined) {
135616
- version = Number(options?.version);
135617
- }
135618
- if (drizzleOrm.is(db, (pgCore.PgDatabase))) {
135619
- await seedPostgres(db, schema, { ...options, version }, refinements);
135620
- }
135621
- else if (drizzleOrm.is(db, (mysqlCore.MySqlDatabase))) {
135622
- await seedMySql(db, schema, { ...options, version }, refinements);
135623
136815
  }
135624
- else if (drizzleOrm.is(db, (sqliteCore.BaseSQLiteDatabase))) {
135625
- await seedSqlite(db, schema, { ...options, version }, refinements);
136816
+ const transformedDrizzleRelations = transformFromDrizzleRelation(cockroachSchema, getDbToTsColumnNamesMap, tableRelations);
136817
+ relations.push(...transformedDrizzleRelations);
136818
+ const isCyclicRelations = relations.map((relI) => {
136819
+ // if (relations.some((relj) => relI.table === relj.refTable && relI.refTable === relj.table)) {
136820
+ const tableRel = tableRelations[relI.table].find((relJ) => relJ.refTable === relI.refTable);
136821
+ if (isRelationCyclic(relI)) {
136822
+ tableRel['isCyclic'] = true;
136823
+ return { ...relI, isCyclic: true };
136824
+ }
136825
+ tableRel['isCyclic'] = false;
136826
+ return { ...relI, isCyclic: false };
136827
+ });
136828
+ return { tables, relations: isCyclicRelations, tableRelations };
136829
+ };
136830
+
136831
+ // MySql-----------------------------------------------------------------------------------------------------
136832
+ const resetMsSql = async (db, schema) => {
136833
+ const tablesToTruncate = Object.entries(schema).map(([_tsTableName, table]) => {
136834
+ const tableConfig = mssqlCore.getTableConfig(table);
136835
+ return { dbName: tableConfig.name, dbSchema: tableConfig.schema ?? 'dbo' };
136836
+ });
136837
+ const allFkConstraints = {};
136838
+ for (const table of tablesToTruncate) {
136839
+ const gatherTableRelatedFkConstraints = `
136840
+ DECLARE @objectId INT
136841
+ = OBJECT_ID( QUOTENAME('${table.dbSchema}') + '.' + QUOTENAME('${table.dbName}') );
136842
+
136843
+ SELECT
136844
+ fk.name AS fkName,
136845
+ OBJECT_SCHEMA_NAME(fk.parent_object_id) AS parentSchema,
136846
+ OBJECT_NAME(fk.parent_object_id) AS parentTable,
136847
+ OBJECT_SCHEMA_NAME(fk.referenced_object_id) AS referencedSchema,
136848
+ OBJECT_NAME(fk.referenced_object_id) AS referencedTable,
136849
+ -- fkc.constraint_column_id AS Column_Ordinal,
136850
+ pc.name AS parentColumn,
136851
+ rc.name AS referencedColumn,
136852
+ fk.delete_referential_action_desc AS onDeleteAction,
136853
+ fk.update_referential_action_desc AS onUpdateAction,
136854
+ CASE
136855
+ WHEN fk.parent_object_id = @objectId THEN 'outbound' -- your table → another table
136856
+ ELSE 'inbound' -- another table → your table
136857
+ END AS relation
136858
+ FROM sys.foreign_keys AS fk
136859
+ JOIN sys.foreign_key_columns fkc
136860
+ ON fk.object_id = fkc.constraint_object_id
136861
+ JOIN sys.columns pc
136862
+ ON fkc.parent_object_id = pc.object_id
136863
+ AND fkc.parent_column_id = pc.column_id
136864
+ JOIN sys.columns rc
136865
+ ON fkc.referenced_object_id = rc.object_id
136866
+ AND fkc.referenced_column_id = rc.column_id
136867
+ WHERE fk.parent_object_id = @objectId
136868
+ OR fk.referenced_object_id = @objectId
136869
+ ORDER BY relation, fkName;
136870
+ `;
136871
+ const rawRes = await db.execute(drizzleOrm.sql.raw(gatherTableRelatedFkConstraints));
136872
+ const res = rawRes.recordset;
136873
+ const tableRelatedFkConstraints = {};
136874
+ for (const fkInfo of res) {
136875
+ if (tableRelatedFkConstraints[fkInfo.fkName] === undefined) {
136876
+ const { parentColumn: _, referencedColumn: __, ...filteredFkInfo } = fkInfo;
136877
+ tableRelatedFkConstraints[fkInfo.fkName] = {
136878
+ ...filteredFkInfo,
136879
+ parentColumns: res.filter(({ fkName }) => fkName === fkInfo.fkName).map(({ parentColumn }) => parentColumn),
136880
+ referencedColumns: res.filter(({ fkName }) => fkName === fkInfo.fkName).map(({ referencedColumn }) => referencedColumn),
136881
+ };
136882
+ }
136883
+ }
136884
+ allFkConstraints[`${table.dbSchema}.${table.dbName}`] = tableRelatedFkConstraints;
136885
+ // drop all table related fk constraints
136886
+ for (const fkInfo of Object.values(tableRelatedFkConstraints)) {
136887
+ const dropFkConstraints = `ALTER TABLE [${fkInfo.parentSchema}].[${fkInfo.parentTable}] DROP CONSTRAINT [${fkInfo.fkName}];`;
136888
+ await db.execute(drizzleOrm.sql.raw(dropFkConstraints));
136889
+ }
136890
+ // truncating
136891
+ const truncateTable = `truncate table [${table.dbSchema}].[${table.dbName}];`;
136892
+ await db.execute(drizzleOrm.sql.raw(truncateTable));
135626
136893
  }
135627
- else {
135628
- throw new Error('The drizzle-seed package currently supports only PostgreSQL, MySQL, and SQLite databases. Please ensure your database is one of these supported types');
136894
+ // add all table related fk constraints
136895
+ for (const table of tablesToTruncate) {
136896
+ const tableRelatedFkConstraints = allFkConstraints[`${table.dbSchema}.${table.dbName}`];
136897
+ for (const fkInfo of Object.values(tableRelatedFkConstraints)) {
136898
+ const addFkConstraints = `
136899
+ ALTER TABLE [${fkInfo.parentSchema}].[${fkInfo.parentTable}]
136900
+ ADD CONSTRAINT [${fkInfo.fkName}]
136901
+ FOREIGN KEY(${fkInfo.parentColumns.map((colName) => `[${colName}]`).join(',')})
136902
+ REFERENCES [${fkInfo.referencedSchema}].[${fkInfo.referencedTable}] (${fkInfo.referencedColumns.map((colName) => `[${colName}]`).join(',')})
136903
+ ON DELETE ${fkInfo.onDeleteAction.split('_').join(' ')}
136904
+ ON UPDATE ${fkInfo.onUpdateAction.split('_').join(' ')};
136905
+ `;
136906
+ await db.execute(drizzleOrm.sql.raw(addFkConstraints));
136907
+ }
135629
136908
  }
135630
- return;
135631
136909
  };
135632
- /**
135633
- * deletes all data from specified tables
135634
- *
135635
- * @param db - database you would like to reset.
135636
- * @param schema - object that contains all your database tables you would like to delete data from.
135637
- *
135638
- * `If db is a PgDatabase object`, we will execute sql query and delete data from your tables the following way:
135639
- * ```sql
135640
- * truncate tableName1, tableName2, ... cascade;
135641
- * ```
135642
- *
135643
- * `If db is a MySqlDatabase object`, we will execute sql queries and delete data from your tables the following way:
135644
- * ```sql
135645
- * SET FOREIGN_KEY_CHECKS = 0;
135646
- * truncate tableName1;
135647
- * truncate tableName2;
135648
- * .
135649
- * .
135650
- * .
135651
- *
135652
- * SET FOREIGN_KEY_CHECKS = 1;
135653
- * ```
135654
- *
135655
- * `If db is a BaseSQLiteDatabase object`, we will execute sql queries and delete data from your tables the following way:
135656
- * ```sql
135657
- * PRAGMA foreign_keys = OFF;
135658
- * delete from tableName1;
135659
- * delete from tableName2;
135660
- * .
135661
- * .
135662
- * .
135663
- *
135664
- * PRAGMA foreign_keys = ON;
135665
- * ```
135666
- *
135667
- * @example
135668
- * ```ts
135669
- * await reset(db, schema);
135670
- *
135671
- * // Alternatively, you can provide an object containing your tables
135672
- * // as the `schema` parameter when calling `reset`.
135673
- * await reset(db, { users });
135674
- * ```
135675
- */
135676
- async function reset(db, schema) {
135677
- if (drizzleOrm.is(db, (pgCore.PgDatabase))) {
135678
- const { pgTables } = filterPgSchema(schema);
135679
- if (Object.entries(pgTables).length > 0) {
135680
- await resetPostgres(db, pgTables);
136910
+ const filterMsSqlTables = (schema) => {
136911
+ const mssqlSchema = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], mssqlCore.MsSqlTable) || drizzleOrm.is(keyValue[1], drizzleOrm.Relations)));
136912
+ const mssqlTables = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], mssqlCore.MsSqlTable)));
136913
+ return { mssqlSchema, mssqlTables };
136914
+ };
136915
+ const seedMsSql = async (db, schema, options = {}, refinements) => {
136916
+ const { mssqlSchema, mssqlTables } = filterMsSqlTables(schema);
136917
+ const { tables, relations } = getMsSqlInfo(mssqlSchema, mssqlTables);
136918
+ const seedService = new SeedService();
136919
+ const generatedTablesGenerators = seedService.generatePossibleGenerators('mssql', tables, relations, refinements, options);
136920
+ const preserveCyclicTablesData = relations.some((rel) => rel.isCyclic === true);
136921
+ const tablesValues = await seedService.generateTablesValues(relations, generatedTablesGenerators, db, mssqlTables, { ...options, preserveCyclicTablesData });
136922
+ const { filteredTablesGenerators, tablesUniqueNotNullColumn } = seedService.filterCyclicTables(generatedTablesGenerators);
136923
+ const updateDataInDb = filteredTablesGenerators.length === 0 ? false : true;
136924
+ await seedService.generateTablesValues(relations, filteredTablesGenerators, db, mssqlTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
136925
+ };
136926
+ const getMsSqlInfo = (mssqlSchema, mssqlTables) => {
136927
+ let tableConfig;
136928
+ let dbToTsColumnNamesMap;
136929
+ const dbToTsTableNamesMap = Object.fromEntries(Object.entries(mssqlTables).map(([key, value]) => [drizzleOrm.getTableName(value), key]));
136930
+ const tables = [];
136931
+ const relations = [];
136932
+ const dbToTsColumnNamesMapGlobal = {};
136933
+ const tableRelations = {};
136934
+ const getDbToTsColumnNamesMap = (table) => {
136935
+ let dbToTsColumnNamesMap = {};
136936
+ const tableName = drizzleOrm.getTableName(table);
136937
+ if (Object.hasOwn(dbToTsColumnNamesMapGlobal, tableName)) {
136938
+ dbToTsColumnNamesMap = dbToTsColumnNamesMapGlobal[tableName];
136939
+ return dbToTsColumnNamesMap;
135681
136940
  }
135682
- }
135683
- else if (drizzleOrm.is(db, (mysqlCore.MySqlDatabase))) {
135684
- const { mysqlTables } = filterMysqlTables(schema);
135685
- if (Object.entries(mysqlTables).length > 0) {
135686
- await resetMySql(db, mysqlTables);
136941
+ const tableConfig = mssqlCore.getTableConfig(table);
136942
+ for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
136943
+ dbToTsColumnNamesMap[col.name] = tsCol;
136944
+ }
136945
+ dbToTsColumnNamesMapGlobal[tableName] = dbToTsColumnNamesMap;
136946
+ return dbToTsColumnNamesMap;
136947
+ };
136948
+ const transformFromDrizzleRelation = (schema, getDbToTsColumnNamesMap, tableRelations) => {
136949
+ const schemaConfig = drizzleOrm.extractTablesRelationalConfig(schema, drizzleOrm.createTableRelationsHelpers);
136950
+ const relations = [];
136951
+ for (const table of Object.values(schemaConfig.tables)) {
136952
+ if (table.relations === undefined)
136953
+ continue;
136954
+ for (const drizzleRel of Object.values(table.relations)) {
136955
+ if (!drizzleOrm.is(drizzleRel, drizzleOrm.One))
136956
+ continue;
136957
+ const tableConfig = mssqlCore.getTableConfig(drizzleRel.sourceTable);
136958
+ const tableDbSchema = tableConfig.schema ?? 'public';
136959
+ const tableDbName = tableConfig.name;
136960
+ const tableTsName = schemaConfig.tableNamesMap[`${tableDbSchema}.${tableDbName}`] ?? tableDbName;
136961
+ const dbToTsColumnNamesMap = getDbToTsColumnNamesMap(drizzleRel.sourceTable);
136962
+ const columns = drizzleRel.config?.fields.map((field) => dbToTsColumnNamesMap[field.name])
136963
+ ?? [];
136964
+ const refTableConfig = mssqlCore.getTableConfig(drizzleRel.referencedTable);
136965
+ const refTableDbSchema = refTableConfig.schema ?? 'public';
136966
+ const refTableDbName = refTableConfig.name;
136967
+ const refTableTsName = schemaConfig.tableNamesMap[`${refTableDbSchema}.${refTableDbName}`]
136968
+ ?? refTableDbName;
136969
+ const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(drizzleRel.referencedTable);
136970
+ const refColumns = drizzleRel.config?.references.map((ref) => dbToTsColumnNamesMapForRefTable[ref.name])
136971
+ ?? [];
136972
+ if (tableRelations[refTableTsName] === undefined) {
136973
+ tableRelations[refTableTsName] = [];
136974
+ }
136975
+ const relation = {
136976
+ table: tableTsName,
136977
+ columns,
136978
+ refTable: refTableTsName,
136979
+ refColumns,
136980
+ refTableRels: tableRelations[refTableTsName],
136981
+ type: 'one',
136982
+ };
136983
+ // do not add duplicate relation
136984
+ if (tableRelations[tableTsName]?.some((rel) => rel.table === relation.table
136985
+ && rel.refTable === relation.refTable)) {
136986
+ console.warn(`You are providing a one-to-many relation between the '${relation.refTable}' and '${relation.table}' tables,\n`
136987
+ + `while the '${relation.table}' table object already has foreign key constraint in the schema referencing '${relation.refTable}' table.\n`
136988
+ + `In this case, the foreign key constraint will be used.\n`);
136989
+ continue;
136990
+ }
136991
+ relations.push(relation);
136992
+ tableRelations[tableTsName].push(relation);
136993
+ }
135687
136994
  }
136995
+ return relations;
136996
+ };
136997
+ for (const table of Object.values(mssqlTables)) {
136998
+ tableConfig = mssqlCore.getTableConfig(table);
136999
+ dbToTsColumnNamesMap = {};
137000
+ for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
137001
+ dbToTsColumnNamesMap[col.name] = tsCol;
137002
+ }
137003
+ const newRelations = tableConfig.foreignKeys.map((fk) => {
137004
+ const table = dbToTsTableNamesMap[tableConfig.name];
137005
+ const refTable = dbToTsTableNamesMap[drizzleOrm.getTableName(fk.reference().foreignTable)];
137006
+ const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(fk.reference().foreignTable);
137007
+ if (tableRelations[refTable] === undefined) {
137008
+ tableRelations[refTable] = [];
137009
+ }
137010
+ return {
137011
+ table,
137012
+ columns: fk
137013
+ .reference()
137014
+ .columns.map((col) => dbToTsColumnNamesMap[col.name]),
137015
+ refTable,
137016
+ refColumns: fk
137017
+ .reference()
137018
+ .foreignColumns.map((fCol) => dbToTsColumnNamesMapForRefTable[fCol.name]),
137019
+ refTableRels: tableRelations[refTable],
137020
+ };
137021
+ });
137022
+ relations.push(...newRelations);
137023
+ if (tableRelations[dbToTsTableNamesMap[tableConfig.name]] === undefined) {
137024
+ tableRelations[dbToTsTableNamesMap[tableConfig.name]] = [];
137025
+ }
137026
+ tableRelations[dbToTsTableNamesMap[tableConfig.name]].push(...newRelations);
137027
+ // TODO: rewrite
137028
+ const getTypeParams = (sqlType) => {
137029
+ // get type params and set only type
137030
+ const typeParams = {};
137031
+ if (sqlType.startsWith('decimal')
137032
+ || sqlType.startsWith('real')
137033
+ || sqlType.startsWith('float')) {
137034
+ const match = sqlType.match(/\((\d+), *(\d+)\)/);
137035
+ if (match) {
137036
+ typeParams['precision'] = Number(match[1]);
137037
+ typeParams['scale'] = Number(match[2]);
137038
+ }
137039
+ }
137040
+ else if (sqlType.startsWith('char')
137041
+ || sqlType.startsWith('varchar')
137042
+ || sqlType.startsWith('binary')
137043
+ || sqlType.startsWith('varbinary')) {
137044
+ const match = sqlType.match(/\((\d+)\)/);
137045
+ if (match) {
137046
+ typeParams['length'] = Number(match[1]);
137047
+ }
137048
+ }
137049
+ return typeParams;
137050
+ };
137051
+ tables.push({
137052
+ name: dbToTsTableNamesMap[tableConfig.name],
137053
+ columns: tableConfig.columns.map((column) => ({
137054
+ name: dbToTsColumnNamesMap[column.name],
137055
+ columnType: column.getSQLType(),
137056
+ typeParams: getTypeParams(column.getSQLType()),
137057
+ dataType: column.dataType,
137058
+ hasDefault: column.hasDefault,
137059
+ default: column.default,
137060
+ enumValues: column.enumValues,
137061
+ isUnique: column.isUnique,
137062
+ notNull: column.notNull,
137063
+ primary: column.primary,
137064
+ identity: column.identity ? true : false,
137065
+ })),
137066
+ primaryKeys: tableConfig.columns
137067
+ .filter((column) => column.primary)
137068
+ .map((column) => dbToTsColumnNamesMap[column.name]),
137069
+ });
135688
137070
  }
135689
- else if (drizzleOrm.is(db, (sqliteCore.BaseSQLiteDatabase))) {
135690
- const { sqliteTables } = filterSqliteTables(schema);
135691
- if (Object.entries(sqliteTables).length > 0) {
135692
- await resetSqlite(db, sqliteTables);
137071
+ const transformedDrizzleRelations = transformFromDrizzleRelation(mssqlSchema, getDbToTsColumnNamesMap, tableRelations);
137072
+ relations.push(...transformedDrizzleRelations);
137073
+ const modifiedRelations = relations.map((relI) => {
137074
+ const tableRel = tableRelations[relI.table].find((relJ) => relJ.refTable === relI.refTable);
137075
+ if (isRelationCyclic(relI)) {
137076
+ tableRel['isCyclic'] = true;
137077
+ return { ...relI, isCyclic: true };
135693
137078
  }
137079
+ tableRel['isCyclic'] = false;
137080
+ return { ...relI, isCyclic: false };
137081
+ });
137082
+ return { tables, relations: modifiedRelations, tableRelations };
137083
+ };
137084
+
137085
+ // MySql-----------------------------------------------------------------------------------------------------
137086
+ const resetMySql = async (db, schema) => {
137087
+ const tablesToTruncate = Object.entries(schema).map(([_tsTableName, table]) => {
137088
+ const dbTableName = drizzleOrm.getTableName(table);
137089
+ return dbTableName;
137090
+ });
137091
+ await db.execute(drizzleOrm.sql.raw('SET FOREIGN_KEY_CHECKS = 0;'));
137092
+ for (const tableName of tablesToTruncate) {
137093
+ const sqlQuery = `truncate \`${tableName}\`;`;
137094
+ await db.execute(drizzleOrm.sql.raw(sqlQuery));
135694
137095
  }
135695
- else {
135696
- throw new Error('The drizzle-seed package currently supports only PostgreSQL, MySQL, and SQLite databases. Please ensure your database is one of these supported types');
137096
+ await db.execute(drizzleOrm.sql.raw('SET FOREIGN_KEY_CHECKS = 1;'));
137097
+ };
137098
+ const filterMysqlTables = (schema) => {
137099
+ const mysqlSchema = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], mysqlCore.MySqlTable) || drizzleOrm.is(keyValue[1], drizzleOrm.Relations)));
137100
+ const mysqlTables = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], mysqlCore.MySqlTable)));
137101
+ return { mysqlSchema, mysqlTables };
137102
+ };
137103
+ const seedMySql = async (db, schema, options = {}, refinements) => {
137104
+ const { mysqlSchema, mysqlTables } = filterMysqlTables(schema);
137105
+ const { tables, relations } = getMySqlInfo(mysqlSchema, mysqlTables);
137106
+ const seedService = new SeedService();
137107
+ const generatedTablesGenerators = seedService.generatePossibleGenerators('mysql', tables, relations, refinements, options);
137108
+ const preserveCyclicTablesData = relations.some((rel) => rel.isCyclic === true);
137109
+ const tablesValues = await seedService.generateTablesValues(relations, generatedTablesGenerators, db, mysqlTables, { ...options, preserveCyclicTablesData });
137110
+ const { filteredTablesGenerators, tablesUniqueNotNullColumn } = seedService.filterCyclicTables(generatedTablesGenerators);
137111
+ const updateDataInDb = filteredTablesGenerators.length === 0 ? false : true;
137112
+ await seedService.generateTablesValues(relations, filteredTablesGenerators, db, mysqlTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
137113
+ };
137114
+ const getMySqlInfo = (mysqlSchema, mysqlTables) => {
137115
+ let tableConfig;
137116
+ let dbToTsColumnNamesMap;
137117
+ const dbToTsTableNamesMap = Object.fromEntries(Object.entries(mysqlTables).map(([key, value]) => [drizzleOrm.getTableName(value), key]));
137118
+ const tables = [];
137119
+ const relations = [];
137120
+ const dbToTsColumnNamesMapGlobal = {};
137121
+ const tableRelations = {};
137122
+ const getDbToTsColumnNamesMap = (table) => {
137123
+ let dbToTsColumnNamesMap = {};
137124
+ const tableName = drizzleOrm.getTableName(table);
137125
+ if (Object.hasOwn(dbToTsColumnNamesMapGlobal, tableName)) {
137126
+ dbToTsColumnNamesMap = dbToTsColumnNamesMapGlobal[tableName];
137127
+ return dbToTsColumnNamesMap;
137128
+ }
137129
+ const tableConfig = mysqlCore.getTableConfig(table);
137130
+ for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
137131
+ dbToTsColumnNamesMap[col.name] = tsCol;
137132
+ }
137133
+ dbToTsColumnNamesMapGlobal[tableName] = dbToTsColumnNamesMap;
137134
+ return dbToTsColumnNamesMap;
137135
+ };
137136
+ const transformFromDrizzleRelation = (schema, getDbToTsColumnNamesMap, tableRelations) => {
137137
+ const schemaConfig = drizzleOrm.extractTablesRelationalConfig(schema, drizzleOrm.createTableRelationsHelpers);
137138
+ const relations = [];
137139
+ for (const table of Object.values(schemaConfig.tables)) {
137140
+ if (table.relations === undefined)
137141
+ continue;
137142
+ for (const drizzleRel of Object.values(table.relations)) {
137143
+ if (!drizzleOrm.is(drizzleRel, drizzleOrm.One))
137144
+ continue;
137145
+ const tableConfig = mysqlCore.getTableConfig(drizzleRel.sourceTable);
137146
+ const tableDbSchema = tableConfig.schema ?? 'public';
137147
+ const tableDbName = tableConfig.name;
137148
+ const tableTsName = schemaConfig.tableNamesMap[`${tableDbSchema}.${tableDbName}`] ?? tableDbName;
137149
+ const dbToTsColumnNamesMap = getDbToTsColumnNamesMap(drizzleRel.sourceTable);
137150
+ const columns = drizzleRel.config?.fields.map((field) => dbToTsColumnNamesMap[field.name])
137151
+ ?? [];
137152
+ const refTableConfig = mysqlCore.getTableConfig(drizzleRel.referencedTable);
137153
+ const refTableDbSchema = refTableConfig.schema ?? 'public';
137154
+ const refTableDbName = refTableConfig.name;
137155
+ const refTableTsName = schemaConfig.tableNamesMap[`${refTableDbSchema}.${refTableDbName}`]
137156
+ ?? refTableDbName;
137157
+ const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(drizzleRel.referencedTable);
137158
+ const refColumns = drizzleRel.config?.references.map((ref) => dbToTsColumnNamesMapForRefTable[ref.name])
137159
+ ?? [];
137160
+ if (tableRelations[refTableTsName] === undefined) {
137161
+ tableRelations[refTableTsName] = [];
137162
+ }
137163
+ const relation = {
137164
+ table: tableTsName,
137165
+ columns,
137166
+ refTable: refTableTsName,
137167
+ refColumns,
137168
+ refTableRels: tableRelations[refTableTsName],
137169
+ type: 'one',
137170
+ };
137171
+ // do not add duplicate relation
137172
+ if (tableRelations[tableTsName]?.some((rel) => rel.table === relation.table
137173
+ && rel.refTable === relation.refTable)) {
137174
+ console.warn(`You are providing a one-to-many relation between the '${relation.refTable}' and '${relation.table}' tables,\n`
137175
+ + `while the '${relation.table}' table object already has foreign key constraint in the schema referencing '${relation.refTable}' table.\n`
137176
+ + `In this case, the foreign key constraint will be used.\n`);
137177
+ continue;
137178
+ }
137179
+ relations.push(relation);
137180
+ tableRelations[tableTsName].push(relation);
137181
+ }
137182
+ }
137183
+ return relations;
137184
+ };
137185
+ for (const table of Object.values(mysqlTables)) {
137186
+ tableConfig = mysqlCore.getTableConfig(table);
137187
+ dbToTsColumnNamesMap = {};
137188
+ for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
137189
+ dbToTsColumnNamesMap[col.name] = tsCol;
137190
+ }
137191
+ const newRelations = tableConfig.foreignKeys.map((fk) => {
137192
+ const table = dbToTsTableNamesMap[tableConfig.name];
137193
+ const refTable = dbToTsTableNamesMap[drizzleOrm.getTableName(fk.reference().foreignTable)];
137194
+ const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(fk.reference().foreignTable);
137195
+ if (tableRelations[refTable] === undefined) {
137196
+ tableRelations[refTable] = [];
137197
+ }
137198
+ return {
137199
+ table,
137200
+ columns: fk
137201
+ .reference()
137202
+ .columns.map((col) => dbToTsColumnNamesMap[col.name]),
137203
+ refTable,
137204
+ refColumns: fk
137205
+ .reference()
137206
+ .foreignColumns.map((fCol) => dbToTsColumnNamesMapForRefTable[fCol.name]),
137207
+ refTableRels: tableRelations[refTable],
137208
+ };
137209
+ });
137210
+ relations.push(...newRelations);
137211
+ if (tableRelations[dbToTsTableNamesMap[tableConfig.name]] === undefined) {
137212
+ tableRelations[dbToTsTableNamesMap[tableConfig.name]] = [];
137213
+ }
137214
+ tableRelations[dbToTsTableNamesMap[tableConfig.name]].push(...newRelations);
137215
+ const getTypeParams = (sqlType) => {
137216
+ // get type params and set only type
137217
+ const typeParams = {};
137218
+ if (sqlType.startsWith('decimal')
137219
+ || sqlType.startsWith('real')
137220
+ || sqlType.startsWith('double')
137221
+ || sqlType.startsWith('float')) {
137222
+ const match = sqlType.match(/\((\d+), *(\d+)\)/);
137223
+ if (match) {
137224
+ typeParams['precision'] = Number(match[1]);
137225
+ typeParams['scale'] = Number(match[2]);
137226
+ }
137227
+ }
137228
+ else if (sqlType.startsWith('char')
137229
+ || sqlType.startsWith('varchar')
137230
+ || sqlType.startsWith('binary')
137231
+ || sqlType.startsWith('varbinary')) {
137232
+ const match = sqlType.match(/\((\d+)\)/);
137233
+ if (match) {
137234
+ typeParams['length'] = Number(match[1]);
137235
+ }
137236
+ }
137237
+ return typeParams;
137238
+ };
137239
+ tables.push({
137240
+ name: dbToTsTableNamesMap[tableConfig.name],
137241
+ columns: tableConfig.columns.map((column) => ({
137242
+ name: dbToTsColumnNamesMap[column.name],
137243
+ columnType: column.getSQLType(),
137244
+ typeParams: getTypeParams(column.getSQLType()),
137245
+ dataType: column.dataType,
137246
+ hasDefault: column.hasDefault,
137247
+ default: column.default,
137248
+ enumValues: column.enumValues,
137249
+ isUnique: column.isUnique,
137250
+ notNull: column.notNull,
137251
+ primary: column.primary,
137252
+ })),
137253
+ primaryKeys: tableConfig.columns
137254
+ .filter((column) => column.primary)
137255
+ .map((column) => dbToTsColumnNamesMap[column.name]),
137256
+ });
135697
137257
  }
135698
- }
137258
+ const transformedDrizzleRelations = transformFromDrizzleRelation(mysqlSchema, getDbToTsColumnNamesMap, tableRelations);
137259
+ relations.push(...transformedDrizzleRelations);
137260
+ const isCyclicRelations = relations.map((relI) => {
137261
+ const tableRel = tableRelations[relI.table].find((relJ) => relJ.refTable === relI.refTable);
137262
+ if (isRelationCyclic(relI)) {
137263
+ tableRel['isCyclic'] = true;
137264
+ return { ...relI, isCyclic: true };
137265
+ }
137266
+ tableRel['isCyclic'] = false;
137267
+ return { ...relI, isCyclic: false };
137268
+ });
137269
+ return { tables, relations: isCyclicRelations, tableRelations };
137270
+ };
137271
+
135699
137272
  // Postgres-----------------------------------------------------------------------------------------------------------
135700
137273
  const resetPostgres = async (db, pgTables) => {
135701
137274
  const tablesToTruncate = Object.entries(pgTables).map(([_, table]) => {
@@ -135864,6 +137437,7 @@ const getPostgresInfo = (pgSchema, pgTables) => {
135864
137437
  || sqlType.startsWith('bpchar')
135865
137438
  || sqlType.startsWith('char')
135866
137439
  || sqlType.startsWith('bit')
137440
+ || sqlType.startsWith('vector')
135867
137441
  || sqlType.startsWith('time')
135868
137442
  || sqlType.startsWith('timestamp')
135869
137443
  || sqlType.startsWith('interval')) {
@@ -135913,37 +137487,9 @@ const getPostgresInfo = (pgSchema, pgTables) => {
135913
137487
  });
135914
137488
  return { tables, relations: isCyclicRelations, tableRelations };
135915
137489
  };
135916
- const isRelationCyclic = (startRel) => {
135917
- // self relation
135918
- if (startRel.table === startRel.refTable)
135919
- return false;
135920
- // DFS
135921
- const targetTable = startRel.table;
135922
- const queue = [startRel];
135923
- let path = [];
135924
- while (queue.length !== 0) {
135925
- const currRel = queue.shift();
135926
- if (path.includes(currRel.table)) {
135927
- const idx = path.indexOf(currRel.table);
135928
- path = path.slice(0, idx);
135929
- }
135930
- path.push(currRel.table);
135931
- for (const rel of currRel.refTableRels) {
135932
- // self relation
135933
- if (rel.table === rel.refTable)
135934
- continue;
135935
- if (rel.refTable === targetTable)
135936
- return true;
135937
- // found cycle, but not the one we are looking for
135938
- if (path.includes(rel.refTable))
135939
- continue;
135940
- queue.unshift(rel);
135941
- }
135942
- }
135943
- return false;
135944
- };
135945
- // MySql-----------------------------------------------------------------------------------------------------
135946
- const resetMySql = async (db, schema) => {
137490
+
137491
+ // SingleStore-----------------------------------------------------------------------------------------------------
137492
+ const resetSingleStore = async (db, schema) => {
135947
137493
  const tablesToTruncate = Object.entries(schema).map(([_tsTableName, table]) => {
135948
137494
  const dbTableName = drizzleOrm.getTableName(table);
135949
137495
  return dbTableName;
@@ -135955,26 +137501,26 @@ const resetMySql = async (db, schema) => {
135955
137501
  }
135956
137502
  await db.execute(drizzleOrm.sql.raw('SET FOREIGN_KEY_CHECKS = 1;'));
135957
137503
  };
135958
- const filterMysqlTables = (schema) => {
135959
- const mysqlSchema = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], mysqlCore.MySqlTable) || drizzleOrm.is(keyValue[1], drizzleOrm.Relations)));
135960
- const mysqlTables = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], mysqlCore.MySqlTable)));
135961
- return { mysqlSchema, mysqlTables };
137504
+ const filterSingleStoreTables = (schema) => {
137505
+ const singleStoreSchema = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], singlestoreCore.SingleStoreTable) || drizzleOrm.is(keyValue[1], drizzleOrm.Relations)));
137506
+ const singleStoreTables = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], singlestoreCore.SingleStoreTable)));
137507
+ return { singleStoreSchema, singleStoreTables };
135962
137508
  };
135963
- const seedMySql = async (db, schema, options = {}, refinements) => {
135964
- const { mysqlSchema, mysqlTables } = filterMysqlTables(schema);
135965
- const { tables, relations } = getMySqlInfo(mysqlSchema, mysqlTables);
137509
+ const seedSingleStore = async (db, schema, options = {}, refinements) => {
137510
+ const { singleStoreSchema, singleStoreTables } = filterSingleStoreTables(schema);
137511
+ const { tables, relations } = getSingleStoreInfo(singleStoreSchema, singleStoreTables);
135966
137512
  const seedService = new SeedService();
135967
- const generatedTablesGenerators = seedService.generatePossibleGenerators('mysql', tables, relations, refinements, options);
137513
+ const generatedTablesGenerators = seedService.generatePossibleGenerators('singlestore', tables, relations, refinements, options);
135968
137514
  const preserveCyclicTablesData = relations.some((rel) => rel.isCyclic === true);
135969
- const tablesValues = await seedService.generateTablesValues(relations, generatedTablesGenerators, db, mysqlTables, { ...options, preserveCyclicTablesData });
137515
+ const tablesValues = await seedService.generateTablesValues(relations, generatedTablesGenerators, db, singleStoreTables, { ...options, preserveCyclicTablesData });
135970
137516
  const { filteredTablesGenerators, tablesUniqueNotNullColumn } = seedService.filterCyclicTables(generatedTablesGenerators);
135971
137517
  const updateDataInDb = filteredTablesGenerators.length === 0 ? false : true;
135972
- await seedService.generateTablesValues(relations, filteredTablesGenerators, db, mysqlTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
137518
+ await seedService.generateTablesValues(relations, filteredTablesGenerators, db, singleStoreTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
135973
137519
  };
135974
- const getMySqlInfo = (mysqlSchema, mysqlTables) => {
137520
+ const getSingleStoreInfo = (singleStoreSchema, singleStoreTables) => {
135975
137521
  let tableConfig;
135976
137522
  let dbToTsColumnNamesMap;
135977
- const dbToTsTableNamesMap = Object.fromEntries(Object.entries(mysqlTables).map(([key, value]) => [drizzleOrm.getTableName(value), key]));
137523
+ const dbToTsTableNamesMap = Object.fromEntries(Object.entries(singleStoreTables).map(([key, value]) => [drizzleOrm.getTableName(value), key]));
135978
137524
  const tables = [];
135979
137525
  const relations = [];
135980
137526
  const dbToTsColumnNamesMapGlobal = {};
@@ -135986,7 +137532,7 @@ const getMySqlInfo = (mysqlSchema, mysqlTables) => {
135986
137532
  dbToTsColumnNamesMap = dbToTsColumnNamesMapGlobal[tableName];
135987
137533
  return dbToTsColumnNamesMap;
135988
137534
  }
135989
- const tableConfig = mysqlCore.getTableConfig(table);
137535
+ const tableConfig = singlestoreCore.getTableConfig(table);
135990
137536
  for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
135991
137537
  dbToTsColumnNamesMap[col.name] = tsCol;
135992
137538
  }
@@ -136002,14 +137548,14 @@ const getMySqlInfo = (mysqlSchema, mysqlTables) => {
136002
137548
  for (const drizzleRel of Object.values(table.relations)) {
136003
137549
  if (!drizzleOrm.is(drizzleRel, drizzleOrm.One))
136004
137550
  continue;
136005
- const tableConfig = mysqlCore.getTableConfig(drizzleRel.sourceTable);
137551
+ const tableConfig = singlestoreCore.getTableConfig(drizzleRel.sourceTable);
136006
137552
  const tableDbSchema = tableConfig.schema ?? 'public';
136007
137553
  const tableDbName = tableConfig.name;
136008
137554
  const tableTsName = schemaConfig.tableNamesMap[`${tableDbSchema}.${tableDbName}`] ?? tableDbName;
136009
137555
  const dbToTsColumnNamesMap = getDbToTsColumnNamesMap(drizzleRel.sourceTable);
136010
137556
  const columns = drizzleRel.config?.fields.map((field) => dbToTsColumnNamesMap[field.name])
136011
137557
  ?? [];
136012
- const refTableConfig = mysqlCore.getTableConfig(drizzleRel.referencedTable);
137558
+ const refTableConfig = singlestoreCore.getTableConfig(drizzleRel.referencedTable);
136013
137559
  const refTableDbSchema = refTableConfig.schema ?? 'public';
136014
137560
  const refTableDbName = refTableConfig.name;
136015
137561
  const refTableTsName = schemaConfig.tableNamesMap[`${refTableDbSchema}.${refTableDbName}`]
@@ -136042,36 +137588,42 @@ const getMySqlInfo = (mysqlSchema, mysqlTables) => {
136042
137588
  }
136043
137589
  return relations;
136044
137590
  };
136045
- for (const table of Object.values(mysqlTables)) {
136046
- tableConfig = mysqlCore.getTableConfig(table);
137591
+ for (const table of Object.values(singleStoreTables)) {
137592
+ tableConfig = singlestoreCore.getTableConfig(table);
136047
137593
  dbToTsColumnNamesMap = {};
136048
137594
  for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
136049
137595
  dbToTsColumnNamesMap[col.name] = tsCol;
136050
137596
  }
136051
- const newRelations = tableConfig.foreignKeys.map((fk) => {
136052
- const table = dbToTsTableNamesMap[tableConfig.name];
136053
- const refTable = dbToTsTableNamesMap[drizzleOrm.getTableName(fk.reference().foreignTable)];
136054
- const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(fk.reference().foreignTable);
136055
- if (tableRelations[refTable] === undefined) {
136056
- tableRelations[refTable] = [];
136057
- }
136058
- return {
136059
- table,
136060
- columns: fk
136061
- .reference()
136062
- .columns.map((col) => dbToTsColumnNamesMap[col.name]),
136063
- refTable,
136064
- refColumns: fk
136065
- .reference()
136066
- .foreignColumns.map((fCol) => dbToTsColumnNamesMapForRefTable[fCol.name]),
136067
- refTableRels: tableRelations[refTable],
136068
- };
136069
- });
136070
- relations.push(...newRelations);
137597
+ // const newRelations = tableConfig.foreignKeys.map((fk) => {
137598
+ // const table = dbToTsTableNamesMap[tableConfig.name] as string;
137599
+ // const refTable = dbToTsTableNamesMap[getTableName(fk.reference().foreignTable)] as string;
137600
+ // const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(
137601
+ // fk.reference().foreignTable,
137602
+ // );
137603
+ // if (tableRelations[refTable] === undefined) {
137604
+ // tableRelations[refTable] = [];
137605
+ // }
137606
+ // return {
137607
+ // table,
137608
+ // columns: fk
137609
+ // .reference()
137610
+ // .columns.map((col) => dbToTsColumnNamesMap[col.name] as string),
137611
+ // refTable,
137612
+ // refColumns: fk
137613
+ // .reference()
137614
+ // .foreignColumns.map(
137615
+ // (fCol) => dbToTsColumnNamesMapForRefTable[fCol.name] as string,
137616
+ // ),
137617
+ // refTableRels: tableRelations[refTable],
137618
+ // };
137619
+ // });
137620
+ // relations.push(
137621
+ // ...newRelations,
137622
+ // );
136071
137623
  if (tableRelations[dbToTsTableNamesMap[tableConfig.name]] === undefined) {
136072
137624
  tableRelations[dbToTsTableNamesMap[tableConfig.name]] = [];
136073
137625
  }
136074
- tableRelations[dbToTsTableNamesMap[tableConfig.name]].push(...newRelations);
137626
+ // tableRelations[dbToTsTableNamesMap[tableConfig.name] as string]!.push(...newRelations);
136075
137627
  const getTypeParams = (sqlType) => {
136076
137628
  // get type params and set only type
136077
137629
  const typeParams = {};
@@ -136094,6 +137646,13 @@ const getMySqlInfo = (mysqlSchema, mysqlTables) => {
136094
137646
  typeParams['length'] = Number(match[1]);
136095
137647
  }
136096
137648
  }
137649
+ else if (sqlType.startsWith('vector')) {
137650
+ const match = sqlType.match(/\((\d+),? ?((F|I)\d{1,2})?\)/);
137651
+ if (match) {
137652
+ typeParams['length'] = Number(match[1]);
137653
+ typeParams['vectorValueType'] = match[2];
137654
+ }
137655
+ }
136097
137656
  return typeParams;
136098
137657
  };
136099
137658
  tables.push({
@@ -136115,7 +137674,7 @@ const getMySqlInfo = (mysqlSchema, mysqlTables) => {
136115
137674
  .map((column) => dbToTsColumnNamesMap[column.name]),
136116
137675
  });
136117
137676
  }
136118
- const transformedDrizzleRelations = transformFromDrizzleRelation(mysqlSchema, getDbToTsColumnNamesMap, tableRelations);
137677
+ const transformedDrizzleRelations = transformFromDrizzleRelation(singleStoreSchema, getDbToTsColumnNamesMap, tableRelations);
136119
137678
  relations.push(...transformedDrizzleRelations);
136120
137679
  const isCyclicRelations = relations.map((relI) => {
136121
137680
  const tableRel = tableRelations[relI.table].find((relJ) => relJ.refTable === relI.refTable);
@@ -136128,6 +137687,7 @@ const getMySqlInfo = (mysqlSchema, mysqlTables) => {
136128
137687
  });
136129
137688
  return { tables, relations: isCyclicRelations, tableRelations };
136130
137689
  };
137690
+
136131
137691
  // Sqlite------------------------------------------------------------------------------------------------------------------------
136132
137692
  const resetSqlite = async (db, schema) => {
136133
137693
  const tablesToTruncate = Object.entries(schema).map(([_tsTableName, table]) => {
@@ -136310,7 +137870,243 @@ const getSqliteInfo = (sqliteSchema, sqliteTables) => {
136310
137870
  return { tables, relations: isCyclicRelations, tableRelations };
136311
137871
  };
136312
137872
 
136313
- exports.AbstractGenerator = AbstractGenerator;
137873
+ class SeedPromise {
137874
+ db;
137875
+ schema;
137876
+ options;
137877
+ static entityKind = 'SeedPromise';
137878
+ [Symbol.toStringTag] = 'SeedPromise';
137879
+ constructor(db, schema, options) {
137880
+ this.db = db;
137881
+ this.schema = schema;
137882
+ this.options = options;
137883
+ }
137884
+ then(onfulfilled, onrejected) {
137885
+ return seedFunc(this.db, this.schema, this.options).then(onfulfilled, onrejected);
137886
+ }
137887
+ catch(onrejected) {
137888
+ return this.then(undefined, onrejected);
137889
+ }
137890
+ finally(onfinally) {
137891
+ return this.then((value) => {
137892
+ onfinally?.();
137893
+ return value;
137894
+ }, (reason) => {
137895
+ onfinally?.();
137896
+ throw reason;
137897
+ });
137898
+ }
137899
+ async refine(callback) {
137900
+ const refinements = this.options?.version === undefined || this.options.version === '2'
137901
+ ? callback(generatorsFuncsV2)
137902
+ : callback(generatorsFuncs);
137903
+ await seedFunc(this.db, this.schema, this.options, refinements);
137904
+ }
137905
+ }
137906
+ function getGeneratorsFunctions() {
137907
+ return generatorsFuncs;
137908
+ }
137909
+ async function seedForDrizzleStudio({ sqlDialect, drizzleStudioObject, drizzleStudioRelations, schemasRefinements, options }) {
137910
+ const generatedSchemas = {};
137911
+ let tables, relations, refinements;
137912
+ drizzleStudioRelations = drizzleStudioRelations.filter((rel) => rel.type === 'one');
137913
+ for (const [schemaName, { tables: drizzleStudioTables }] of Object.entries(drizzleStudioObject)) {
137914
+ tables = [];
137915
+ for (const [tableName, table] of Object.entries(drizzleStudioTables)) {
137916
+ const drizzleStudioColumns = Object.values(table.columns);
137917
+ const columns = drizzleStudioColumns.map((col) => ({
137918
+ name: col.name,
137919
+ dataType: 'string',
137920
+ columnType: col.type,
137921
+ // TODO: revise later
137922
+ typeParams: {},
137923
+ default: col.default,
137924
+ hasDefault: col.default === undefined ? false : true,
137925
+ isUnique: col.isUnique === undefined ? false : col.isUnique,
137926
+ notNull: col.notNull,
137927
+ primary: col.primaryKey,
137928
+ }));
137929
+ tables.push({
137930
+ name: tableName,
137931
+ columns,
137932
+ primaryKeys: drizzleStudioColumns.filter((col) => col.primaryKey === true).map((col) => col.name),
137933
+ });
137934
+ }
137935
+ relations = drizzleStudioRelations.filter((rel) => rel.schema === schemaName && rel.refSchema === schemaName);
137936
+ const isCyclicRelations = relations.map((reli) => {
137937
+ if (relations.some((relj) => reli.table === relj.refTable && reli.refTable === relj.table)) {
137938
+ return { ...reli, isCyclic: true };
137939
+ }
137940
+ return { ...reli, isCyclic: false };
137941
+ });
137942
+ refinements = schemasRefinements !== undefined && schemasRefinements[schemaName] !== undefined
137943
+ ? schemasRefinements[schemaName]
137944
+ : undefined;
137945
+ const seedService = new SeedService();
137946
+ const generatedTablesGenerators = seedService.generatePossibleGenerators(sqlDialect, tables, isCyclicRelations, refinements, options);
137947
+ const generatedTables = await seedService.generateTablesValues(isCyclicRelations, generatedTablesGenerators, undefined, undefined, { ...options, preserveData: true, insertDataInDb: false });
137948
+ generatedSchemas[schemaName] = { tables: generatedTables };
137949
+ }
137950
+ return generatedSchemas;
137951
+ }
137952
+ /**
137953
+ * @param db - database you would like to seed.
137954
+ * @param schema - object that contains all your database tables you would like to seed.
137955
+ * @param options - object that contains properties `count` and `seed`:
137956
+ *
137957
+ * `count` - number of rows you want to generate.
137958
+ *
137959
+ * `seed` - a number that controls the state of generated data. (if the `seed` number is the same and nothing is changed in the seeding script, generated data will remain the same each time you seed database)
137960
+ *
137961
+ * @returns SeedPromise - a class object that has a refine method that is used to change generators for columns.
137962
+ *
137963
+ * @example
137964
+ * ```ts
137965
+ * // base seeding
137966
+ * await seed(db, schema);
137967
+ *
137968
+ * // seeding with count specified
137969
+ * await seed(db, schema, { count: 100000 });
137970
+ *
137971
+ * // seeding with count and seed specified
137972
+ * await seed(db, schema, { count: 100000, seed: 1 });
137973
+ *
137974
+ * //seeding using refine
137975
+ * await seed(db, schema, { count: 1000 }).refine((funcs) => ({
137976
+ * users: {
137977
+ * columns: {
137978
+ * name: funcs.firstName({ isUnique: true }),
137979
+ * email: funcs.email(),
137980
+ * phone: funcs.phoneNumber({ template: "+380 99 ###-##-##" }),
137981
+ * password: funcs.string({ isUnique: true }),
137982
+ * },
137983
+ * count: 100000,
137984
+ * },
137985
+ * posts: {
137986
+ * columns: {
137987
+ * title: funcs.valuesFromArray({
137988
+ * values: ["Title1", "Title2", "Title3", "Title4", "Title5"],
137989
+ * }),
137990
+ * content: funcs.loremIpsum({ sentencesCount: 3 }),
137991
+ * },
137992
+ * },
137993
+ * }));
137994
+ *
137995
+ * ```
137996
+ */
137997
+ function seed(db, schema, options) {
137998
+ return new SeedPromise(db, schema, options);
137999
+ }
138000
+ const seedFunc = async (db, schema, options = {}, refinements) => {
138001
+ let version;
138002
+ if (options?.version !== undefined) {
138003
+ version = Number(options?.version);
138004
+ }
138005
+ if (drizzleOrm.is(db, (pgCore.PgDatabase))) {
138006
+ await seedPostgres(db, schema, { ...options, version }, refinements);
138007
+ }
138008
+ else if (drizzleOrm.is(db, (mysqlCore.MySqlDatabase))) {
138009
+ await seedMySql(db, schema, { ...options, version }, refinements);
138010
+ }
138011
+ else if (drizzleOrm.is(db, (sqliteCore.BaseSQLiteDatabase))) {
138012
+ await seedSqlite(db, schema, { ...options, version }, refinements);
138013
+ }
138014
+ else if (drizzleOrm.is(db, (mssqlCore.MsSqlDatabase))) {
138015
+ await seedMsSql(db, schema, { ...options, version }, refinements);
138016
+ }
138017
+ else if (drizzleOrm.is(db, (cockroachCore.CockroachDatabase))) {
138018
+ await seedCockroach(db, schema, { ...options, version }, refinements);
138019
+ }
138020
+ else if (drizzleOrm.is(db, (singlestoreCore.SingleStoreDatabase))) {
138021
+ await seedSingleStore(db, schema, { ...options, version }, refinements);
138022
+ }
138023
+ else {
138024
+ throw new Error('The drizzle-seed package currently supports only PostgreSQL, MySQL, SQLite, Ms Sql, CockroachDB and SingleStore databases. Please ensure your database is one of these supported types');
138025
+ }
138026
+ return;
138027
+ };
138028
+ /**
138029
+ * deletes all data from specified tables
138030
+ *
138031
+ * @param db - database you would like to reset.
138032
+ * @param schema - object that contains all your database tables you would like to delete data from.
138033
+ *
138034
+ * `If db is a PgDatabase object`, we will execute sql query and delete data from your tables the following way:
138035
+ * ```sql
138036
+ * truncate tableName1, tableName2, ... cascade;
138037
+ * ```
138038
+ *
138039
+ * `If db is a MySqlDatabase object`, we will execute sql queries and delete data from your tables the following way:
138040
+ * ```sql
138041
+ * SET FOREIGN_KEY_CHECKS = 0;
138042
+ * truncate tableName1;
138043
+ * truncate tableName2;
138044
+ * .
138045
+ * .
138046
+ * .
138047
+ *
138048
+ * SET FOREIGN_KEY_CHECKS = 1;
138049
+ * ```
138050
+ *
138051
+ * `If db is a BaseSQLiteDatabase object`, we will execute sql queries and delete data from your tables the following way:
138052
+ * ```sql
138053
+ * PRAGMA foreign_keys = OFF;
138054
+ * delete from tableName1;
138055
+ * delete from tableName2;
138056
+ * .
138057
+ * .
138058
+ * .
138059
+ *
138060
+ * PRAGMA foreign_keys = ON;
138061
+ * ```
138062
+ *
138063
+ * @example
138064
+ * ```ts
138065
+ * await reset(db, schema);
138066
+ * ```
138067
+ */
138068
+ async function reset(db, schema) {
138069
+ if (drizzleOrm.is(db, (pgCore.PgDatabase))) {
138070
+ const { pgTables } = filterPgSchema(schema);
138071
+ if (Object.entries(pgTables).length > 0) {
138072
+ await resetPostgres(db, pgTables);
138073
+ }
138074
+ }
138075
+ else if (drizzleOrm.is(db, (mysqlCore.MySqlDatabase))) {
138076
+ const { mysqlTables } = filterMysqlTables(schema);
138077
+ if (Object.entries(mysqlTables).length > 0) {
138078
+ await resetMySql(db, mysqlTables);
138079
+ }
138080
+ }
138081
+ else if (drizzleOrm.is(db, (sqliteCore.BaseSQLiteDatabase))) {
138082
+ const { sqliteTables } = filterSqliteTables(schema);
138083
+ if (Object.entries(sqliteTables).length > 0) {
138084
+ await resetSqlite(db, sqliteTables);
138085
+ }
138086
+ }
138087
+ else if (drizzleOrm.is(db, (mssqlCore.MsSqlDatabase))) {
138088
+ const { mssqlTables } = filterMsSqlTables(schema);
138089
+ if (Object.entries(mssqlTables).length > 0) {
138090
+ await resetMsSql(db, mssqlTables);
138091
+ }
138092
+ }
138093
+ else if (drizzleOrm.is(db, (cockroachCore.CockroachDatabase))) {
138094
+ const { cockroachTables } = filterCockroachSchema(schema);
138095
+ if (Object.entries(cockroachTables).length > 0) {
138096
+ await resetCockroach(db, cockroachTables);
138097
+ }
138098
+ }
138099
+ else if (drizzleOrm.is(db, (singlestoreCore.SingleStoreDatabase))) {
138100
+ const { singleStoreTables } = filterSingleStoreTables(schema);
138101
+ if (Object.entries(singleStoreTables).length > 0) {
138102
+ await resetSingleStore(db, singleStoreTables);
138103
+ }
138104
+ }
138105
+ else {
138106
+ throw new Error('The drizzle-seed package currently supports only PostgreSQL, MySQL, SQLite, Ms Sql, CockroachDB and SingleStore databases. Please ensure your database is one of these supported types');
138107
+ }
138108
+ }
138109
+
136314
138110
  exports.SeedService = SeedService;
136315
138111
  exports.cities = cityNames;
136316
138112
  exports.countries = countries;