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