drizzle-seed 0.3.2-b5a9650 → 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 -35
  2. package/{services/SeedService.d.mts → SeedService.d.mts} +18 -35
  3. package/{services/SeedService.d.ts → SeedService.d.ts} +18 -35
  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 +2800 -1060
  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 -1072
  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 +6 -2
  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 -27
  70. package/services/utils.d.mts +0 -27
  71. package/services/utils.d.ts +0 -27
  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
1
  import { is, entityKind, sql, eq, Relations, getTableName, extractTablesRelationalConfig, createTableRelationsHelpers, One } from 'drizzle-orm';
2
- import { MySqlDatabase, MySqlTable, getTableConfig as getTableConfig$1 } from 'drizzle-orm/mysql-core';
3
- import { PgSmallInt, PgInteger, PgBigInt53, PgBigInt64, PgSmallSerial, PgSerial, PgBigSerial53, PgBigSerial64, PgDatabase, getTableConfig, PgTable } from 'drizzle-orm/pg-core';
4
- import { BaseSQLiteDatabase, SQLiteTable, getTableConfig as getTableConfig$2 } from 'drizzle-orm/sqlite-core';
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,23 +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
- };
131220
- const intMax = (args) => args.reduce((m, e) => e > m ? e : m);
131221
- const isPostgresColumnIntLike = (column) => {
131222
- return is(column, PgSmallInt)
131223
- || is(column, PgInteger)
131224
- || is(column, PgBigInt53)
131225
- || is(column, PgBigInt64)
131226
- || is(column, PgSmallSerial)
131227
- || is(column, PgSerial)
131228
- || is(column, PgBigSerial53)
131229
- || is(column, PgBigSerial64);
131230
- };
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();
131231
131270
 
131232
131271
  /* eslint-disable drizzle-internal/require-entity-kind */
131233
131272
  class AbstractGenerator {
@@ -131243,10 +131282,11 @@ class AbstractGenerator {
131243
131282
  arraySize;
131244
131283
  baseColumnDataType;
131245
131284
  // param for text-like generators
131246
- stringLength;
131285
+ // public stringLength?: number;
131247
131286
  // params for GenerateValuesFromArray
131248
131287
  weightedCountSeed;
131249
131288
  maxRepeatedValuesCount;
131289
+ typeParams = {};
131250
131290
  params;
131251
131291
  constructor(params) {
131252
131292
  this.params = params === undefined ? {} : params;
@@ -131278,6 +131318,7 @@ class AbstractGenerator {
131278
131318
  });
131279
131319
  uniqueGen.isUnique = this.isUnique;
131280
131320
  uniqueGen.dataType = this.dataType;
131321
+ uniqueGen.typeParams = this.typeParams;
131281
131322
  return uniqueGen;
131282
131323
  }
131283
131324
  return;
@@ -131288,10 +131329,13 @@ class AbstractGenerator {
131288
131329
  const uniqueGen = this.replaceIfUnique();
131289
131330
  const baseColumnGen = uniqueGen === undefined ? this : uniqueGen;
131290
131331
  baseColumnGen.dataType = this.baseColumnDataType;
131332
+ const { dimensions, ...rest } = baseColumnGen.typeParams;
131333
+ baseColumnGen.typeParams = rest;
131291
131334
  const arrayGen = new GenerateArray({
131292
131335
  baseColumnGen,
131293
131336
  size: this.arraySize,
131294
131337
  });
131338
+ arrayGen.typeParams = { dimensions };
131295
131339
  return arrayGen;
131296
131340
  }
131297
131341
  return;
@@ -131546,6 +131590,7 @@ class GenerateNumber extends AbstractGenerator {
131546
131590
  static entityKind = 'GenerateNumber';
131547
131591
  state;
131548
131592
  uniqueVersionOfGen = GenerateUniqueNumber;
131593
+ // TODO rewrite precision to decimalPlaces
131549
131594
  init({ count, seed }) {
131550
131595
  super.init({ count, seed });
131551
131596
  let { minValue, maxValue, precision } = this.params;
@@ -131799,20 +131844,13 @@ class GenerateDate extends AbstractGenerator {
131799
131844
  const rng = prand.xoroshiro128plus(seed);
131800
131845
  let { minDate, maxDate } = this.params;
131801
131846
  const anchorDate = new Date('2024-05-08');
131802
- // 4 years in milliseconds
131803
131847
  const deltaMilliseconds = 4 * 31536000000;
131804
131848
  if (typeof minDate === 'string') {
131805
131849
  minDate = new Date(minDate);
131806
131850
  }
131807
- if (typeof minDate === 'object' && !isValidDate(minDate)) {
131808
- throw new Error('Invalid Date was provided for the minDate parameter.');
131809
- }
131810
131851
  if (typeof maxDate === 'string') {
131811
131852
  maxDate = new Date(maxDate);
131812
131853
  }
131813
- if (typeof maxDate === 'object' && !isValidDate(maxDate)) {
131814
- throw new Error('Invalid Date was provided for the maxDate parameter.');
131815
- }
131816
131854
  if (minDate === undefined) {
131817
131855
  if (maxDate === undefined) {
131818
131856
  minDate = new Date(anchorDate.getTime() - deltaMilliseconds);
@@ -131825,9 +131863,6 @@ class GenerateDate extends AbstractGenerator {
131825
131863
  if (maxDate === undefined) {
131826
131864
  maxDate = new Date(minDate.getTime() + (2 * deltaMilliseconds));
131827
131865
  }
131828
- if (minDate > maxDate) {
131829
- throw new Error(`The minDate parameter must be less than or equal to the maxDate parameter.`);
131830
- }
131831
131866
  this.state = { rng, minDate, maxDate };
131832
131867
  }
131833
131868
  generate() {
@@ -131849,83 +131884,18 @@ class GenerateTime extends AbstractGenerator {
131849
131884
  init({ count, seed }) {
131850
131885
  super.init({ count, seed });
131851
131886
  const rng = prand.xoroshiro128plus(seed);
131852
- let { minTime, maxTime } = this.params;
131853
- if (minTime === undefined && maxTime === undefined) {
131854
- // TODO: maybe need to change in major version release
131855
- // This is required to ensure that this generator remains deterministic when used without minTime, maxTime parameters.
131856
- const oneDayInMilliseconds = 86400000;
131857
- minTime = new Date(new Date('2024-05-08T12:00:00.000Z').getTime() - oneDayInMilliseconds);
131858
- maxTime = new Date(new Date('2024-05-08T12:00:00.000Z').getTime() + oneDayInMilliseconds);
131859
- this.state = { rng, minTime, maxTime };
131860
- return;
131861
- }
131862
- if (minTime === undefined) {
131863
- if (maxTime === undefined) {
131864
- minTime = '00:00:00.000Z';
131865
- maxTime = '23:59:59.999Z';
131866
- }
131867
- else {
131868
- minTime = '00:00:00.000Z';
131869
- }
131870
- }
131871
- if (maxTime === undefined) {
131872
- maxTime = '23:59:59.999Z';
131873
- new Date().toISOString();
131874
- }
131875
- const anchorDate = new Date('2024-05-08');
131876
- const anchorDateString0 = anchorDate.toISOString().replace(/T\d{2}:\d{2}:\d{2}.\d{3}Z/, '');
131877
- if (typeof minTime === 'string') {
131878
- // const timeMatch0 = minTime.match(/^\d{2}:\d{2}:\d{2}.\d{1,3}Z?$/);
131879
- const timeMatch1 = minTime.match(/^\d{2}:\d{2}:\d{2}Z?$/);
131880
- const timeMatch2 = minTime.match(/^\d{2}:\d{2}Z?$/);
131881
- if (
131882
- // timeMatch0 === null
131883
- timeMatch1 === null
131884
- && timeMatch2 === null) {
131885
- throw new Error(`You're using the wrong format for the minTime parameter.`
131886
- + `\nPlease use one of these formats: 'HH:mm:ss', 'HH:mm' (with or without a trailing 'Z')`);
131887
- }
131888
- minTime = minTime.at(-1) === 'Z' ? minTime : minTime + 'Z';
131889
- minTime = new Date(anchorDate.toISOString().replace(/\d{2}:\d{2}:\d{2}.\d{3}Z/, minTime));
131890
- }
131891
- if (typeof minTime === 'object') {
131892
- if (!isValidDate(minTime)) {
131893
- throw new Error('Invalid Date was provided for the minTime parameter.');
131894
- }
131895
- minTime = new Date(minTime.toISOString().replace(/\d{4}-\d{2}-\d{2}/, anchorDateString0));
131896
- }
131897
- if (typeof maxTime === 'string') {
131898
- // const timeMatch0 = maxTime.match(/^\d{2}:\d{2}:\d{2}.\d{1,3}Z?$/);
131899
- const timeMatch1 = maxTime.match(/^\d{2}:\d{2}:\d{2}Z?$/);
131900
- const timeMatch2 = maxTime.match(/^\d{2}:\d{2}Z?$/);
131901
- if (
131902
- // timeMatch0 === null
131903
- timeMatch1 === null
131904
- && timeMatch2 === null) {
131905
- throw new Error(`You're using the wrong format for the maxTime parameter.`
131906
- + `\nPlease use one of these formats: 'HH:mm:ss', 'HH:mm' (with or without a trailing 'Z').`);
131907
- }
131908
- maxTime = maxTime.at(-1) === 'Z' ? maxTime : maxTime + 'Z';
131909
- maxTime = new Date(anchorDate.toISOString().replace(/\d{2}:\d{2}:\d{2}.\d{3}Z/, maxTime));
131910
- }
131911
- if (typeof maxTime === 'object') {
131912
- if (!isValidDate(maxTime)) {
131913
- throw new Error('Invalid Date was provided for the maxTime parameter.');
131914
- }
131915
- maxTime = new Date(maxTime.toISOString().replace(/\d{4}-\d{2}-\d{2}/, anchorDateString0));
131916
- }
131917
- if (minTime > maxTime) {
131918
- throw new Error(`The minTime parameter must be less than or equal to the maxTime parameter.`);
131919
- }
131920
- this.state = { rng, minTime, maxTime };
131887
+ this.state = { rng };
131921
131888
  }
131922
131889
  generate() {
131923
131890
  if (this.state === undefined) {
131924
131891
  throw new Error('state is not defined.');
131925
131892
  }
131893
+ const anchorDateTime = new Date('2024-05-08T12:00:00.000Z');
131894
+ const oneDayInMilliseconds = 86400000;
131895
+ let date = new Date();
131926
131896
  let milliseconds;
131927
- [milliseconds, this.state.rng] = prand.uniformIntDistribution(this.state.minTime.getTime(), this.state.maxTime.getTime(), this.state.rng);
131928
- 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));
131929
131899
  return date.toISOString().replace(/(\d{4}-\d{2}-\d{2}T)|(\.\d{3}Z)/g, '');
131930
131900
  }
131931
131901
  }
@@ -131935,46 +131905,18 @@ class GenerateTimestamp extends AbstractGenerator {
131935
131905
  init({ count, seed }) {
131936
131906
  super.init({ count, seed });
131937
131907
  const rng = prand.xoroshiro128plus(seed);
131938
- let { minTimestamp, maxTimestamp } = this.params;
131939
- const anchorDate = new Date('2024-05-08');
131940
- // 2 years in milliseconds
131941
- const deltaMilliseconds = 2 * 31536000000;
131942
- if (typeof minTimestamp === 'string') {
131943
- minTimestamp = new Date(minTimestamp);
131944
- }
131945
- if (typeof minTimestamp === 'object' && !isValidDate(minTimestamp)) {
131946
- throw new Error('Invalid Date was provided for the minTimestamp parameter.');
131947
- }
131948
- if (typeof maxTimestamp === 'string') {
131949
- maxTimestamp = new Date(maxTimestamp);
131950
- }
131951
- if (typeof maxTimestamp === 'object' && !isValidDate(maxTimestamp)) {
131952
- throw new Error('Invalid Date was provided for the maxTimestamp parameter.');
131953
- }
131954
- if (minTimestamp === undefined) {
131955
- if (maxTimestamp === undefined) {
131956
- minTimestamp = new Date(anchorDate.getTime() - deltaMilliseconds);
131957
- maxTimestamp = new Date(anchorDate.getTime() + deltaMilliseconds);
131958
- }
131959
- else {
131960
- minTimestamp = new Date(maxTimestamp.getTime() - (2 * deltaMilliseconds));
131961
- }
131962
- }
131963
- if (maxTimestamp === undefined) {
131964
- maxTimestamp = new Date(minTimestamp.getTime() + (2 * deltaMilliseconds));
131965
- }
131966
- if (minTimestamp > maxTimestamp) {
131967
- throw new Error(`The minTimestamp parameter must be less than or equal to the maxTimestamp parameter.`);
131968
- }
131969
- this.state = { rng, minTimestamp, maxTimestamp };
131908
+ this.state = { rng };
131970
131909
  }
131971
131910
  generate() {
131972
131911
  if (this.state === undefined) {
131973
131912
  throw new Error('state is not defined.');
131974
131913
  }
131914
+ const anchorTimestamp = new Date('2024-05-08');
131915
+ const twoYearsInMilliseconds = 2 * 31536000000;
131916
+ let date = new Date();
131975
131917
  let milliseconds;
131976
- [milliseconds, this.state.rng] = prand.uniformIntDistribution(this.state.minTimestamp.getTime(), this.state.maxTimestamp.getTime(), this.state.rng);
131977
- 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));
131978
131920
  if (this.dataType === 'string') {
131979
131921
  return date
131980
131922
  .toISOString()
@@ -131990,46 +131932,18 @@ class GenerateDatetime extends AbstractGenerator {
131990
131932
  init({ count, seed }) {
131991
131933
  super.init({ count, seed });
131992
131934
  const rng = prand.xoroshiro128plus(seed);
131993
- let { minDatetime, maxDatetime } = this.params;
131994
- const anchorDate = new Date('2024-05-08');
131995
- // 2 years in milliseconds
131996
- const deltaMilliseconds = 2 * 31536000000;
131997
- if (typeof minDatetime === 'string') {
131998
- minDatetime = new Date(minDatetime);
131999
- }
132000
- if (typeof minDatetime === 'object' && !isValidDate(minDatetime)) {
132001
- throw new Error('Invalid Date was provided for the minDatetime parameter.');
132002
- }
132003
- if (typeof maxDatetime === 'string') {
132004
- maxDatetime = new Date(maxDatetime);
132005
- }
132006
- if (typeof maxDatetime === 'object' && !isValidDate(maxDatetime)) {
132007
- throw new Error('Invalid Date was provided for the maxDatetime parameter.');
132008
- }
132009
- if (minDatetime === undefined) {
132010
- if (maxDatetime === undefined) {
132011
- minDatetime = new Date(anchorDate.getTime() - deltaMilliseconds);
132012
- maxDatetime = new Date(anchorDate.getTime() + deltaMilliseconds);
132013
- }
132014
- else {
132015
- minDatetime = new Date(maxDatetime.getTime() - (2 * deltaMilliseconds));
132016
- }
132017
- }
132018
- if (maxDatetime === undefined) {
132019
- maxDatetime = new Date(minDatetime.getTime() + (2 * deltaMilliseconds));
132020
- }
132021
- if (minDatetime > maxDatetime) {
132022
- throw new Error(`The minDatetime parameter must be less than or equal to the maxDatetime parameter.`);
132023
- }
132024
- this.state = { rng, minDatetime, maxDatetime };
131935
+ this.state = { rng };
132025
131936
  }
132026
131937
  generate() {
132027
131938
  if (this.state === undefined) {
132028
131939
  throw new Error('state is not defined.');
132029
131940
  }
131941
+ const anchorDate = new Date('2024-05-08');
131942
+ const twoYearsInMilliseconds = 2 * 31536000000;
131943
+ let date = new Date();
132030
131944
  let milliseconds;
132031
- [milliseconds, this.state.rng] = prand.uniformIntDistribution(this.state.minDatetime.getTime(), this.state.maxDatetime.getTime(), this.state.rng);
132032
- 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));
132033
131947
  if (this.dataType === 'string') {
132034
131948
  return date
132035
131949
  .toISOString()
@@ -132385,8 +132299,8 @@ class GenerateFirstName extends AbstractGenerator {
132385
132299
  init({ count, seed }) {
132386
132300
  super.init({ count, seed });
132387
132301
  const rng = prand.xoroshiro128plus(seed);
132388
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$5) {
132389
- 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}.`);
132390
132304
  }
132391
132305
  this.state = { rng };
132392
132306
  }
@@ -132409,8 +132323,8 @@ class GenerateUniqueFirstName extends AbstractGenerator {
132409
132323
  if (count > firstNames.length) {
132410
132324
  throw new Error('count exceeds max number of unique first names.');
132411
132325
  }
132412
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$5) {
132413
- 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}.`);
132414
132328
  }
132415
132329
  const genIndicesObj = new GenerateUniqueInt({ minValue: 0, maxValue: firstNames.length - 1 });
132416
132330
  genIndicesObj.init({ count, seed });
@@ -132433,8 +132347,8 @@ class GenerateLastName extends AbstractGenerator {
132433
132347
  init({ count, seed }) {
132434
132348
  super.init({ count, seed });
132435
132349
  const rng = prand.xoroshiro128plus(seed);
132436
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$3) {
132437
- 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}.`);
132438
132352
  }
132439
132353
  this.state = { rng };
132440
132354
  }
@@ -132455,8 +132369,8 @@ class GenerateUniqueLastName extends AbstractGenerator {
132455
132369
  if (count > lastNames.length) {
132456
132370
  throw new Error('count exceeds max number of unique last names.');
132457
132371
  }
132458
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$3) {
132459
- 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}.`);
132460
132374
  }
132461
132375
  const genIndicesObj = new GenerateUniqueInt({ minValue: 0, maxValue: lastNames.length - 1 });
132462
132376
  genIndicesObj.init({ count, seed });
@@ -132478,8 +132392,8 @@ class GenerateFullName extends AbstractGenerator {
132478
132392
  init({ count, seed }) {
132479
132393
  super.init({ count, seed });
132480
132394
  const rng = prand.xoroshiro128plus(seed);
132481
- if (this.stringLength !== undefined && this.stringLength < (maxStringLength$5 + maxStringLength$3 + 1)) {
132482
- 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}.`);
132483
132397
  }
132484
132398
  this.state = { rng };
132485
132399
  }
@@ -132507,8 +132421,8 @@ class GenerateUniqueFullName extends AbstractGenerator {
132507
132421
  if (count > maxUniqueFullNamesNumber) {
132508
132422
  throw new RangeError(`count exceeds max number of unique full names(${maxUniqueFullNamesNumber}).`);
132509
132423
  }
132510
- if (this.stringLength !== undefined && this.stringLength < (maxStringLength$5 + maxStringLength$3 + 1)) {
132511
- 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}.`);
132512
132426
  }
132513
132427
  const rng = prand.xoroshiro128plus(seed);
132514
132428
  const fullnameSet = new Set();
@@ -132551,8 +132465,8 @@ class GenerateEmail extends AbstractGenerator {
132551
132465
  throw new RangeError(`count exceeds max number of unique emails(${maxUniqueEmailsNumber}).`);
132552
132466
  }
132553
132467
  const maxEmailLength = maxStringLength$a + maxStringLength$5 + maxStringLength$6 + 2;
132554
- if (this.stringLength !== undefined && this.stringLength < maxEmailLength) {
132555
- 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}.`);
132556
132470
  }
132557
132471
  const arraysToGenerateFrom = [adjectivesArray, namesArray, domainsArray];
132558
132472
  const genIndicesObj = new GenerateUniqueInt({
@@ -132585,8 +132499,8 @@ class GeneratePhoneNumber extends AbstractGenerator {
132585
132499
  const { prefixes, template } = this.params;
132586
132500
  const rng = prand.xoroshiro128plus(seed);
132587
132501
  if (template !== undefined) {
132588
- if (this.stringLength !== undefined && this.stringLength < template.length) {
132589
- 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}.
132590
132504
  Set the maximum string length to at least ${template.length}.`);
132591
132505
  }
132592
132506
  const iterArray = [...template.matchAll(/#/g)];
@@ -132631,8 +132545,8 @@ class GeneratePhoneNumber extends AbstractGenerator {
132631
132545
  }
132632
132546
  const maxPrefixLength = Math.max(...prefixesArray.map((prefix) => prefix.length));
132633
132547
  const maxGeneratedDigits = Math.max(...generatedDigitsNumbers);
132634
- if (this.stringLength !== undefined && this.stringLength < (maxPrefixLength + maxGeneratedDigits)) {
132635
- 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}.`);
132636
132550
  }
132637
132551
  if (new Set(prefixesArray).size !== prefixesArray.length) {
132638
132552
  throw new Error('prefixes are not unique.');
@@ -132709,8 +132623,8 @@ class GenerateCountry extends AbstractGenerator {
132709
132623
  init({ count, seed }) {
132710
132624
  super.init({ count, seed });
132711
132625
  const rng = prand.xoroshiro128plus(seed);
132712
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$7) {
132713
- 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}.`);
132714
132628
  }
132715
132629
  this.state = { rng };
132716
132630
  }
@@ -132732,8 +132646,8 @@ class GenerateUniqueCountry extends AbstractGenerator {
132732
132646
  if (count > countries.length) {
132733
132647
  throw new Error('count exceeds max number of unique countries.');
132734
132648
  }
132735
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$7) {
132736
- 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}.`);
132737
132651
  }
132738
132652
  const genIndicesObj = new GenerateUniqueInt({ minValue: 0, maxValue: countries.length - 1 });
132739
132653
  genIndicesObj.init({ count, seed });
@@ -132754,8 +132668,8 @@ class GenerateJobTitle extends AbstractGenerator {
132754
132668
  init({ count, seed }) {
132755
132669
  super.init({ count, seed });
132756
132670
  const rng = prand.xoroshiro128plus(seed);
132757
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$4) {
132758
- 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}.`);
132759
132673
  }
132760
132674
  this.state = { rng };
132761
132675
  }
@@ -132777,8 +132691,8 @@ class GenerateStreetAddress extends AbstractGenerator {
132777
132691
  const rng = prand.xoroshiro128plus(seed);
132778
132692
  const possStreetNames = [firstNames, lastNames];
132779
132693
  const maxStreetAddressLength = 4 + Math.max(maxStringLength$5, maxStringLength$3) + 1 + maxStringLength;
132780
- if (this.stringLength !== undefined && this.stringLength < maxStreetAddressLength) {
132781
- 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}.`);
132782
132696
  }
132783
132697
  this.state = { rng, possStreetNames };
132784
132698
  }
@@ -132807,8 +132721,8 @@ class GenerateUniqueStreetAddress extends AbstractGenerator {
132807
132721
  throw new RangeError(`count exceeds max number of unique street names(${maxUniqueStreetnamesNumber}).`);
132808
132722
  }
132809
132723
  const maxStreetAddressLength = 4 + Math.max(maxStringLength$5, maxStringLength$3) + 1 + maxStringLength;
132810
- if (this.stringLength !== undefined && this.stringLength < maxStreetAddressLength) {
132811
- 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}.`);
132812
132726
  }
132813
132727
  const rng = prand.xoroshiro128plus(seed);
132814
132728
  // ["1", "2", ..., "999"]
@@ -132864,8 +132778,8 @@ class GenerateCity extends AbstractGenerator {
132864
132778
  init({ count, seed }) {
132865
132779
  super.init({ count, seed });
132866
132780
  const rng = prand.xoroshiro128plus(seed);
132867
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$9) {
132868
- 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}.`);
132869
132783
  }
132870
132784
  this.state = { rng };
132871
132785
  }
@@ -132886,8 +132800,8 @@ class GenerateUniqueCity extends AbstractGenerator {
132886
132800
  if (count > cityNames.length) {
132887
132801
  throw new Error('count exceeds max number of unique cities.');
132888
132802
  }
132889
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$9) {
132890
- 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}.`);
132891
132805
  }
132892
132806
  const genIndicesObj = new GenerateUniqueInt({ minValue: 0, maxValue: cityNames.length - 1 });
132893
132807
  genIndicesObj.init({ count, seed });
@@ -132911,8 +132825,8 @@ class GeneratePostcode extends AbstractGenerator {
132911
132825
  const rng = prand.xoroshiro128plus(seed);
132912
132826
  const templates = ['#####', '#####-####'];
132913
132827
  const maxPostcodeLength = Math.max(...templates.map((template) => template.length));
132914
- if (this.stringLength !== undefined && this.stringLength < maxPostcodeLength) {
132915
- 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}.`);
132916
132830
  }
132917
132831
  this.state = { rng, templates };
132918
132832
  }
@@ -132962,8 +132876,8 @@ class GenerateUniquePostcode extends AbstractGenerator {
132962
132876
  },
132963
132877
  ];
132964
132878
  const maxPostcodeLength = Math.max(...templates.map((template) => template.template.length));
132965
- if (this.stringLength !== undefined && this.stringLength < maxPostcodeLength) {
132966
- 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}.`);
132967
132881
  }
132968
132882
  for (const templateObj of templates) {
132969
132883
  templateObj.indicesGen.skipCheck = true;
@@ -132999,8 +132913,8 @@ class GenerateState extends AbstractGenerator {
132999
132913
  init({ count, seed }) {
133000
132914
  super.init({ count, seed });
133001
132915
  const rng = prand.xoroshiro128plus(seed);
133002
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$1) {
133003
- 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}.`);
133004
132918
  }
133005
132919
  this.state = { rng };
133006
132920
  }
@@ -133028,8 +132942,8 @@ class GenerateCompanyName extends AbstractGenerator {
133028
132942
  ];
133029
132943
  // max( { template: '#', placeholdersCount: 1 }, { template: '#, # and #', placeholdersCount: 3 } )
133030
132944
  const maxCompanyNameLength = Math.max(maxStringLength$3 + maxStringLength$8 + 1, 3 * maxStringLength$3 + 7);
133031
- if (this.stringLength !== undefined && this.stringLength < maxCompanyNameLength) {
133032
- 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}.`);
133033
132947
  }
133034
132948
  this.state = { rng, templates };
133035
132949
  }
@@ -133073,8 +132987,8 @@ class GenerateUniqueCompanyName extends AbstractGenerator {
133073
132987
  }
133074
132988
  // max( { template: '#', placeholdersCount: 1 }, { template: '#, # and #', placeholdersCount: 3 } )
133075
132989
  const maxCompanyNameLength = Math.max(maxStringLength$3 + maxStringLength$8 + 1, 3 * maxStringLength$3 + 7);
133076
- if (this.stringLength !== undefined && this.stringLength < maxCompanyNameLength) {
133077
- 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}.`);
133078
132992
  }
133079
132993
  const rng = prand.xoroshiro128plus(seed);
133080
132994
  // when count reach maxUniqueCompanyNameNumber template will be deleted from array
@@ -133150,8 +133064,8 @@ class GenerateLoremIpsum extends AbstractGenerator {
133150
133064
  this.params.sentencesCount = 1;
133151
133065
  const maxLoremIpsumSentencesLength = maxStringLength$2 * this.params.sentencesCount + this.params.sentencesCount
133152
133066
  - 1;
133153
- if (this.stringLength !== undefined && this.stringLength < maxLoremIpsumSentencesLength) {
133154
- 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}.`);
133155
133069
  }
133156
133070
  this.state = { rng };
133157
133071
  }
@@ -133257,6 +133171,7 @@ class GenerateUniquePoint extends AbstractGenerator {
133257
133171
  state;
133258
133172
  isUnique = true;
133259
133173
  init({ count, seed }) {
133174
+ // TODO: rewrite the unique generator to use fastCartesianProduct for generating unique points.
133260
133175
  const xCoordinateGen = new GenerateUniqueNumber({
133261
133176
  minValue: this.params.minXValue,
133262
133177
  maxValue: this.params.maxXValue,
@@ -133343,6 +133258,7 @@ class GenerateUniqueLine extends AbstractGenerator {
133343
133258
  state;
133344
133259
  isUnique = true;
133345
133260
  init({ count, seed }) {
133261
+ // TODO: rewrite the unique generator to use fastCartesianProduct for generating unique triplets(liens).
133346
133262
  const aCoefficientGen = new GenerateUniqueNumber({
133347
133263
  minValue: this.params.minAValue,
133348
133264
  maxValue: this.params.maxAValue,
@@ -133386,6 +133302,397 @@ class GenerateUniqueLine extends AbstractGenerator {
133386
133302
  }
133387
133303
  }
133388
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
+ }
133389
133696
 
133390
133697
  /* eslint-disable drizzle-internal/require-entity-kind */
133391
133698
  class GenerateUniqueIntervalV2 extends AbstractGenerator {
@@ -133472,8 +133779,8 @@ class GenerateStringV2 extends AbstractGenerator {
133472
133779
  super.init({ count, seed });
133473
133780
  let minStringLength = 7;
133474
133781
  let maxStringLength = 20;
133475
- if (this.stringLength !== undefined) {
133476
- maxStringLength = this.stringLength;
133782
+ if (this.typeParams?.length !== undefined) {
133783
+ maxStringLength = this.typeParams?.length;
133477
133784
  if (maxStringLength === 1)
133478
133785
  minStringLength = maxStringLength;
133479
133786
  if (maxStringLength < minStringLength)
@@ -133495,6 +133802,8 @@ class GenerateStringV2 extends AbstractGenerator {
133495
133802
  [idx, this.state.rng] = prand.uniformIntDistribution(0, stringChars.length - 1, this.state.rng);
133496
133803
  currStr += stringChars[idx];
133497
133804
  }
133805
+ if (this.dataType === 'buffer')
133806
+ return Buffer.from(currStr);
133498
133807
  return currStr;
133499
133808
  }
133500
133809
  }
@@ -133508,8 +133817,8 @@ class GenerateUniqueStringV2 extends AbstractGenerator {
133508
133817
  let minStringLength = 7;
133509
133818
  let maxStringLength = 20;
133510
133819
  // TODO: revise later
133511
- if (this.stringLength !== undefined) {
133512
- maxStringLength = this.stringLength;
133820
+ if (this.typeParams?.length !== undefined) {
133821
+ maxStringLength = this.typeParams?.length;
133513
133822
  if (maxStringLength === 1 || maxStringLength < minStringLength)
133514
133823
  minStringLength = maxStringLength;
133515
133824
  }
@@ -133702,8 +134011,6 @@ const generatorsFuncs = {
133702
134011
  date: createGenerator(GenerateDate),
133703
134012
  /**
133704
134013
  * generates time in 24 hours style.
133705
- * @param minTime - lower border of range.
133706
- * @param maxTime - upper border of range.
133707
134014
  * @param arraySize - number of elements in each one-dimensional array. (If specified, arrays will be generated.)
133708
134015
  *
133709
134016
  * @example
@@ -133711,7 +134018,7 @@ const generatorsFuncs = {
133711
134018
  * await seed(db, schema, { count: 1000 }).refine((funcs) => ({
133712
134019
  * users: {
133713
134020
  * columns: {
133714
- * birthTime: funcs.time({ minTime: "11:12:13.141", maxTime: "15:16:17.181" })
134021
+ * birthTime: funcs.time()
133715
134022
  * },
133716
134023
  * },
133717
134024
  * }));
@@ -133721,8 +134028,6 @@ const generatorsFuncs = {
133721
134028
  time: createGenerator(GenerateTime),
133722
134029
  /**
133723
134030
  * generates timestamps.
133724
- * @param minTimestamp - lower border of range.
133725
- * @param maxTimestamp - upper border of range.
133726
134031
  * @param arraySize - number of elements in each one-dimensional array. (If specified, arrays will be generated.)
133727
134032
  *
133728
134033
  * @example
@@ -133730,7 +134035,7 @@ const generatorsFuncs = {
133730
134035
  * await seed(db, schema, { count: 1000 }).refine((funcs) => ({
133731
134036
  * orders: {
133732
134037
  * columns: {
133733
- * shippedDate: funcs.timestamp({ minTimestamp: "2025-03-07T11:12:13.141", maxTimestamp: "2025-03-08T15:16:17.181" })
134038
+ * shippedDate: funcs.timestamp()
133734
134039
  * },
133735
134040
  * },
133736
134041
  * }));
@@ -133740,8 +134045,6 @@ const generatorsFuncs = {
133740
134045
  timestamp: createGenerator(GenerateTimestamp),
133741
134046
  /**
133742
134047
  * generates datetime objects.
133743
- * @param minDatetime - lower border of range.
133744
- * @param maxDatetime - upper border of range.
133745
134048
  * @param arraySize - number of elements in each one-dimensional array. (If specified, arrays will be generated.)
133746
134049
  *
133747
134050
  * @example
@@ -133749,7 +134052,7 @@ const generatorsFuncs = {
133749
134052
  * await seed(db, schema, { count: 1000 }).refine((funcs) => ({
133750
134053
  * orders: {
133751
134054
  * columns: {
133752
- * shippedDate: funcs.datetime({ minDatetime: "2025-03-07T11:12:13.141", maxDatetime: "2025-03-08T15:16:17.181" })
134055
+ * shippedDate: funcs.datetime()
133753
134056
  * },
133754
134057
  * },
133755
134058
  * }));
@@ -134209,8 +134512,132 @@ const generatorsFuncs = {
134209
134512
  * ```
134210
134513
  */
134211
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),
134212
134639
  };
134213
- // so far, version changes don’t change generator parameters.
134640
+ // so far, version changes don’t affect generator parameters.
134214
134641
  const generatorsFuncsV2 = {
134215
134642
  ...generatorsFuncs,
134216
134643
  };
@@ -134368,10 +134795,1128 @@ const generatorsMap = {
134368
134795
  GenerateWeightedCount: [
134369
134796
  GenerateWeightedCount,
134370
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;
134371
135038
  };
134372
135039
 
134373
135040
  const latestVersion = 2;
134374
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
+
134375
135920
  /* eslint-disable drizzle-internal/require-entity-kind */
134376
135921
  class SeedService {
134377
135922
  static entityKind = 'SeedService';
@@ -134382,6 +135927,7 @@ class SeedService {
134382
135927
  mysqlMaxParametersNumber = 100000;
134383
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.
134384
135929
  sqliteMaxParametersNumber = 32766;
135930
+ mssqlMaxParametersNumber = 2100;
134385
135931
  version;
134386
135932
  generatePossibleGenerators = (connectionType, tables, relations, refinements, options) => {
134387
135933
  let columnPossibleGenerator;
@@ -134421,7 +135967,6 @@ class SeedService {
134421
135967
  };
134422
135968
  }
134423
135969
  }
134424
- // handling refinements (count, with)
134425
135970
  if (refinements !== undefined && refinements[table.name] !== undefined) {
134426
135971
  if (refinements[table.name].count !== undefined) {
134427
135972
  tablesPossibleGenerators[i].count = refinements[table.name].count;
@@ -134477,29 +136022,17 @@ class SeedService {
134477
136022
  notNull: col.notNull,
134478
136023
  primary: col.primary,
134479
136024
  generatedIdentityType: col.generatedIdentityType,
136025
+ identity: col.identity,
134480
136026
  generator: undefined,
134481
136027
  isCyclic: false,
134482
136028
  wasDefinedBefore: false,
134483
136029
  wasRefined: false,
134484
136030
  };
134485
- // handling refinements (columnGenerator)
134486
136031
  if (refinements !== undefined
134487
136032
  && refinements[table.name] !== undefined
134488
136033
  && refinements[table.name].columns !== undefined
134489
136034
  && refinements[table.name].columns[col.name] !== undefined) {
134490
136035
  const genObj = refinements[table.name].columns[col.name];
134491
- if (genObj === false) {
134492
- if (col.notNull === true && col.hasDefault === false) {
134493
- throw new Error(`You cannot set the '${col.name}' column in the '${table.name}' table to false in your refinements.`
134494
- + `\nDoing so will result in a null value being inserted into the '${col.name}' column,`
134495
- + `\nwhich will cause an error because the column has a not null constraint and no default value.`);
134496
- }
134497
- // Generating undefined as a value for a column and then inserting it via drizzle-orm
134498
- // will result in the value not being inserted into that column.
134499
- columnPossibleGenerator.generator = new generatorsMap.GenerateDefault[0]({ defaultValue: undefined });
134500
- columnPossibleGenerator.wasRefined = true;
134501
- continue;
134502
- }
134503
136036
  if (col.columnType.match(/\[\w*]/g) !== null) {
134504
136037
  if ((col.baseColumn?.dataType === 'array' && col.baseColumn.columnType.match(/\[\w*]/g) !== null)
134505
136038
  // studio case
@@ -134545,17 +136078,27 @@ class SeedService {
134545
136078
  }
134546
136079
  } // TODO: rewrite pickGeneratorFor... using new col properties: isUnique and notNull
134547
136080
  else if (connectionType === 'postgresql') {
134548
- columnPossibleGenerator.generator = this.selectGeneratorForPostgresColumn(table, col);
136081
+ columnPossibleGenerator.generator = selectGeneratorForPostgresColumn(table, col);
134549
136082
  }
134550
136083
  else if (connectionType === 'mysql') {
134551
- columnPossibleGenerator.generator = this.selectGeneratorForMysqlColumn(table, col);
136084
+ columnPossibleGenerator.generator = selectGeneratorForMysqlColumn(table, col);
134552
136085
  }
134553
136086
  else if (connectionType === 'sqlite') {
134554
- 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);
134555
136097
  }
134556
136098
  if (columnPossibleGenerator.generator === undefined) {
134557
136099
  throw new Error(`column with type ${col.columnType} is not supported for now.`);
134558
136100
  }
136101
+ columnPossibleGenerator.generator.typeParams = col.typeParams ?? columnPossibleGenerator.generator.typeParams;
134559
136102
  const arrayGen = columnPossibleGenerator.generator.replaceIfArray();
134560
136103
  if (arrayGen !== undefined) {
134561
136104
  columnPossibleGenerator.generator = arrayGen;
@@ -134570,7 +136113,7 @@ class SeedService {
134570
136113
  // TODO: for now only GenerateValuesFromArray support notNull property
134571
136114
  columnPossibleGenerator.generator.notNull = col.notNull;
134572
136115
  columnPossibleGenerator.generator.dataType = col.dataType;
134573
- columnPossibleGenerator.generator.stringLength = col.typeParams.length;
136116
+ // columnPossibleGenerator.generator.stringLength = col.typeParams.length;
134574
136117
  tablePossibleGenerators.columnsPossibleGenerators.push(columnPossibleGenerator);
134575
136118
  }
134576
136119
  }
@@ -134581,7 +136124,7 @@ class SeedService {
134581
136124
  if (entityKind === 'GenerateArray') {
134582
136125
  const oldBaseColumnGen = generator.params.baseColumnGen;
134583
136126
  const newBaseColumnGen = this.selectVersionOfGenerator(oldBaseColumnGen);
134584
- // newGenerator.baseColumnDataType = oldGenerator.baseColumnDataType;
136127
+ newBaseColumnGen.typeParams = oldBaseColumnGen.typeParams;
134585
136128
  generator.params.baseColumnGen = newBaseColumnGen;
134586
136129
  }
134587
136130
  const possibleGeneratorConstructors = generatorsMap[entityKind];
@@ -134597,7 +136140,8 @@ class SeedService {
134597
136140
  // TODO: for now only GenerateValuesFromArray support notNull property
134598
136141
  newGenerator.notNull = generator.notNull;
134599
136142
  newGenerator.dataType = generator.dataType;
134600
- newGenerator.stringLength = generator.stringLength;
136143
+ // newGenerator.stringLength = generator.stringLength;
136144
+ newGenerator.typeParams = generator.typeParams ?? newGenerator.typeParams;
134601
136145
  return newGenerator;
134602
136146
  };
134603
136147
  cyclicTablesCompare = (table1, table2, relation, reverseRelation) => {
@@ -134708,474 +136252,6 @@ class SeedService {
134708
136252
  }
134709
136253
  return weightedWithCount;
134710
136254
  };
134711
- // TODO: revise serial part generators
134712
- selectGeneratorForPostgresColumn = (table, col) => {
134713
- const pickGenerator = (table, col) => {
134714
- // ARRAY
134715
- if (col.columnType.match(/\[\w*]/g) !== null && col.baseColumn !== undefined) {
134716
- const baseColumnGen = this.selectGeneratorForPostgresColumn(table, col.baseColumn);
134717
- if (baseColumnGen === undefined) {
134718
- throw new Error(`column with type ${col.baseColumn.columnType} is not supported for now.`);
134719
- }
134720
- // const getBaseColumnDataType = (baseColumn: Column) => {
134721
- // if (baseColumn.baseColumn !== undefined) {
134722
- // return getBaseColumnDataType(baseColumn.baseColumn);
134723
- // }
134724
- // return baseColumn.dataType;
134725
- // };
134726
- // const baseColumnDataType = getBaseColumnDataType(col.baseColumn);
134727
- const generator = new generatorsMap.GenerateArray[0]({ baseColumnGen, size: col.size });
134728
- // generator.baseColumnDataType = baseColumnDataType;
134729
- return generator;
134730
- }
134731
- // ARRAY for studio
134732
- if (col.columnType.match(/\[\w*]/g) !== null) {
134733
- // remove dimensions from type
134734
- const baseColumnType = col.columnType.replace(/\[\w*]/g, '');
134735
- const baseColumn = {
134736
- ...col,
134737
- };
134738
- baseColumn.columnType = baseColumnType;
134739
- const baseColumnGen = this.selectGeneratorForPostgresColumn(table, baseColumn);
134740
- if (baseColumnGen === undefined) {
134741
- throw new Error(`column with type ${col.baseColumn.columnType} is not supported for now.`);
134742
- }
134743
- let generator = new generatorsMap.GenerateArray[0]({ baseColumnGen });
134744
- for (let i = 0; i < col.typeParams.dimensions - 1; i++) {
134745
- generator = new generatorsMap.GenerateArray[0]({ baseColumnGen: generator });
134746
- }
134747
- return generator;
134748
- }
134749
- // INT ------------------------------------------------------------------------------------------------------------
134750
- if ((['smallserial', 'serial', 'bigserial'].includes(col.columnType)
134751
- || ['smallint', 'integer', 'bigint'].includes(col.columnType))
134752
- && table.primaryKeys.includes(col.name)) {
134753
- const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
134754
- return generator;
134755
- }
134756
- let minValue;
134757
- let maxValue;
134758
- if (['smallserial', 'serial', 'bigserial'].includes(col.columnType)) {
134759
- minValue = 1;
134760
- if (col.columnType === 'smallserial') {
134761
- // 2^16 / 2 - 1, 2 bytes
134762
- maxValue = 32767;
134763
- }
134764
- else if (col.columnType === 'serial') {
134765
- // 2^32 / 2 - 1, 4 bytes
134766
- maxValue = 2147483647;
134767
- }
134768
- else if (col.columnType === 'bigserial') {
134769
- // 2^64 / 2 - 1, 8 bytes
134770
- minValue = BigInt(1);
134771
- maxValue = BigInt('9223372036854775807');
134772
- }
134773
- }
134774
- else if (['smallint', 'integer', 'bigint'].includes(col.columnType)) {
134775
- if (col.columnType === 'smallint') {
134776
- // 2^16 / 2 - 1, 2 bytes
134777
- minValue = -32768;
134778
- maxValue = 32767;
134779
- }
134780
- else if (col.columnType === 'integer') {
134781
- // 2^32 / 2 - 1, 4 bytes
134782
- minValue = -2147483648;
134783
- maxValue = 2147483647;
134784
- }
134785
- else if (col.columnType.includes('bigint')) {
134786
- if (col.dataType === 'bigint') {
134787
- // 2^64 / 2 - 1, 8 bytes
134788
- minValue = BigInt('-9223372036854775808');
134789
- maxValue = BigInt('9223372036854775807');
134790
- }
134791
- else {
134792
- // if (col.dataType === 'number')
134793
- // if you’re expecting values above 2^31 but below 2^53
134794
- minValue = -9007199254740991;
134795
- maxValue = 9007199254740991;
134796
- }
134797
- }
134798
- }
134799
- if (['smallint', 'integer', 'bigint'].includes(col.columnType)) {
134800
- const generator = new generatorsMap.GenerateInt[0]({
134801
- minValue,
134802
- maxValue,
134803
- });
134804
- return generator;
134805
- }
134806
- if (['smallserial', 'serial', 'bigserial'].includes(col.columnType)) {
134807
- const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
134808
- generator.maxValue = maxValue;
134809
- return generator;
134810
- }
134811
- // NUMBER(real, double, decimal, numeric)
134812
- if (col.columnType === 'real'
134813
- || col.columnType === 'double precision'
134814
- || col.columnType.match(/^decimal(\(\d{1,6}(, ?-?\d{0,5})?\))?$/) !== null
134815
- || col.columnType.match(/^numeric(\(\d{1,6}(, ?-?\d{0,5})?\))?$/) !== null) {
134816
- if (col.typeParams.precision !== undefined) {
134817
- const precision = col.typeParams.precision;
134818
- const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
134819
- const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
134820
- const generator = new generatorsMap.GenerateNumber[0]({
134821
- minValue: -maxAbsoluteValue,
134822
- maxValue: maxAbsoluteValue,
134823
- precision: Math.pow(10, scale),
134824
- });
134825
- return generator;
134826
- }
134827
- const generator = new generatorsMap.GenerateNumber[0]();
134828
- return generator;
134829
- }
134830
- // STRING
134831
- if ((col.columnType === 'text'
134832
- || col.columnType.match(/^varchar(\(\d+\))?$/) !== null
134833
- || col.columnType.match(/^char(\(\d+\))?$/) !== null)
134834
- && table.primaryKeys.includes(col.name)) {
134835
- const generator = new generatorsMap.GenerateUniqueString[0]();
134836
- return generator;
134837
- }
134838
- if ((col.columnType === 'text'
134839
- || col.columnType.match(/^varchar(\(\d+\))?$/) !== null
134840
- || col.columnType.match(/^char(\(\d+\))?$/) !== null)
134841
- && col.name.toLowerCase().includes('name')) {
134842
- const generator = new generatorsMap.GenerateFirstName[0]();
134843
- return generator;
134844
- }
134845
- if ((col.columnType === 'text'
134846
- || col.columnType.match(/^varchar(\(\d+\))?$/) !== null
134847
- || col.columnType.match(/^char(\(\d+\))?$/) !== null)
134848
- && col.name.toLowerCase().includes('email')) {
134849
- const generator = new generatorsMap.GenerateEmail[0]();
134850
- return generator;
134851
- }
134852
- if (col.columnType === 'text'
134853
- || col.columnType.match(/^varchar(\(\d+\))?$/) !== null
134854
- || col.columnType.match(/^char(\(\d+\))?$/) !== null) {
134855
- const generator = new generatorsMap.GenerateString[0]();
134856
- return generator;
134857
- }
134858
- // UUID
134859
- if (col.columnType === 'uuid') {
134860
- const generator = new generatorsMap.GenerateUUID[0]();
134861
- return generator;
134862
- }
134863
- // BOOLEAN
134864
- if (col.columnType === 'boolean') {
134865
- const generator = new generatorsMap.GenerateBoolean[0]();
134866
- return generator;
134867
- }
134868
- // DATE, TIME, TIMESTAMP
134869
- if (col.columnType === 'date') {
134870
- const generator = new generatorsMap.GenerateDate[0]();
134871
- return generator;
134872
- }
134873
- if (col.columnType.match(/^time((\(\d+\))|( with time zone))?$/) !== null) {
134874
- const generator = new generatorsMap.GenerateTime[0]();
134875
- return generator;
134876
- }
134877
- if (col.columnType.match(/^timestamp((\(\d+\))|( with time zone))?$/) !== null) {
134878
- const generator = new generatorsMap.GenerateTimestamp[0]();
134879
- return generator;
134880
- }
134881
- // JSON, JSONB
134882
- if (col.columnType === 'json' || col.columnType === 'jsonb') {
134883
- const generator = new generatorsMap.GenerateJson[0]();
134884
- return generator;
134885
- }
134886
- // if (col.columnType === "jsonb") {
134887
- // const generator = new GenerateJsonb({});
134888
- // return generator;
134889
- // }
134890
- // ENUM
134891
- if (col.enumValues !== undefined) {
134892
- const generator = new generatorsMap.GenerateEnum[0]({
134893
- enumValues: col.enumValues,
134894
- });
134895
- return generator;
134896
- }
134897
- // INTERVAL
134898
- if (col.columnType.match(/^interval( .+)?$/) !== null) {
134899
- if (col.columnType === 'interval') {
134900
- const generator = new generatorsMap.GenerateInterval[0]();
134901
- return generator;
134902
- }
134903
- const fields = col.columnType.replace('interval ', '');
134904
- const generator = new generatorsMap.GenerateInterval[0]({ fields });
134905
- return generator;
134906
- }
134907
- // POINT, LINE
134908
- if (col.columnType === 'point') {
134909
- const generator = new generatorsMap.GeneratePoint[0]();
134910
- return generator;
134911
- }
134912
- if (col.columnType === 'line') {
134913
- const generator = new generatorsMap.GenerateLine[0]();
134914
- return generator;
134915
- }
134916
- if (col.hasDefault && col.default !== undefined) {
134917
- const generator = new generatorsMap.GenerateDefault[0]({
134918
- defaultValue: col.default,
134919
- });
134920
- return generator;
134921
- }
134922
- return;
134923
- };
134924
- const generator = pickGenerator(table, col);
134925
- if (generator !== undefined) {
134926
- generator.isUnique = col.isUnique;
134927
- generator.dataType = col.dataType;
134928
- generator.stringLength = col.typeParams.length;
134929
- }
134930
- return generator;
134931
- };
134932
- selectGeneratorForMysqlColumn = (table, col) => {
134933
- const pickGenerator = (table, col) => {
134934
- // INT ------------------------------------------------------------------------------------------------------------
134935
- if ((col.columnType === 'serial'
134936
- || ['tinyint', 'smallint', 'mediumint', 'int', 'bigint'].includes(col.columnType))
134937
- && table.primaryKeys.includes(col.name)) {
134938
- const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
134939
- return generator;
134940
- }
134941
- let minValue;
134942
- let maxValue;
134943
- if (col.columnType === 'serial') {
134944
- // 2^64 % 2 - 1, 8 bytes
134945
- minValue = BigInt(0);
134946
- maxValue = BigInt('9223372036854775807');
134947
- }
134948
- else if (['tinyint', 'smallint', 'mediumint', 'int', 'bigint'].includes(col.columnType)) {
134949
- if (col.columnType === 'tinyint') {
134950
- // 2^8 / 2 - 1, 1 bytes
134951
- minValue = -128;
134952
- maxValue = 127;
134953
- }
134954
- else if (col.columnType === 'smallint') {
134955
- // 2^16 / 2 - 1, 2 bytes
134956
- minValue = -32768;
134957
- maxValue = 32767;
134958
- }
134959
- else if (col.columnType === 'mediumint') {
134960
- // 2^16 / 2 - 1, 2 bytes
134961
- minValue = -8388608;
134962
- maxValue = 8388607;
134963
- }
134964
- else if (col.columnType === 'int') {
134965
- // 2^32 / 2 - 1, 4 bytes
134966
- minValue = -2147483648;
134967
- maxValue = 2147483647;
134968
- }
134969
- else if (col.columnType === 'bigint') {
134970
- // 2^64 / 2 - 1, 8 bytes
134971
- minValue = BigInt('-9223372036854775808');
134972
- maxValue = BigInt('9223372036854775807');
134973
- }
134974
- }
134975
- if (['tinyint', 'smallint', 'mediumint', 'int', 'bigint'].includes(col.columnType)) {
134976
- const generator = new generatorsMap.GenerateInt[0]({
134977
- minValue,
134978
- maxValue,
134979
- });
134980
- return generator;
134981
- }
134982
- if (col.columnType === 'serial') {
134983
- const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
134984
- generator.maxValue = maxValue;
134985
- return generator;
134986
- }
134987
- // NUMBER(real, double, decimal, float)
134988
- if (col.columnType === 'real'
134989
- || col.columnType === 'double'
134990
- || col.columnType === 'float'
134991
- || col.columnType.startsWith('decimal')
134992
- || col.columnType.startsWith('numeric')) {
134993
- if (col.typeParams.precision !== undefined) {
134994
- const precision = col.typeParams.precision;
134995
- const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
134996
- const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
134997
- const generator = new generatorsMap.GenerateNumber[0]({
134998
- minValue: -maxAbsoluteValue,
134999
- maxValue: maxAbsoluteValue,
135000
- precision: Math.pow(10, scale),
135001
- });
135002
- return generator;
135003
- }
135004
- const generator = new generatorsMap.GenerateNumber[0]();
135005
- return generator;
135006
- }
135007
- // STRING
135008
- if ((col.columnType === 'text'
135009
- || col.columnType === 'blob'
135010
- || col.columnType.startsWith('char')
135011
- || col.columnType.startsWith('varchar')
135012
- || col.columnType.startsWith('binary')
135013
- || col.columnType.startsWith('varbinary'))
135014
- && table.primaryKeys.includes(col.name)) {
135015
- const generator = new generatorsMap.GenerateUniqueString[0]();
135016
- return generator;
135017
- }
135018
- if ((col.columnType === 'text'
135019
- || col.columnType === 'blob'
135020
- || col.columnType.startsWith('char')
135021
- || col.columnType.startsWith('varchar')
135022
- || col.columnType.startsWith('binary')
135023
- || col.columnType.startsWith('varbinary'))
135024
- && col.name.toLowerCase().includes('name')) {
135025
- const generator = new generatorsMap.GenerateFirstName[0]();
135026
- return generator;
135027
- }
135028
- if ((col.columnType === 'text'
135029
- || col.columnType === 'blob'
135030
- || col.columnType.startsWith('char')
135031
- || col.columnType.startsWith('varchar')
135032
- || col.columnType.startsWith('binary')
135033
- || col.columnType.startsWith('varbinary'))
135034
- && col.name.toLowerCase().includes('email')) {
135035
- const generator = new generatorsMap.GenerateEmail[0]();
135036
- return generator;
135037
- }
135038
- if (col.columnType === 'text'
135039
- || col.columnType === 'blob'
135040
- || col.columnType.startsWith('char')
135041
- || col.columnType.startsWith('varchar')
135042
- || col.columnType.startsWith('binary')
135043
- || col.columnType.startsWith('varbinary')) {
135044
- const generator = new generatorsMap.GenerateString[0]();
135045
- return generator;
135046
- }
135047
- // BOOLEAN
135048
- if (col.columnType === 'boolean') {
135049
- const generator = new generatorsMap.GenerateBoolean[0]();
135050
- return generator;
135051
- }
135052
- // DATE, TIME, TIMESTAMP, DATETIME, YEAR
135053
- if (col.columnType.startsWith('datetime')) {
135054
- const generator = new generatorsMap.GenerateDatetime[0]();
135055
- return generator;
135056
- }
135057
- if (col.columnType === 'date') {
135058
- const generator = new generatorsMap.GenerateDate[0]();
135059
- return generator;
135060
- }
135061
- if (col.columnType === 'time') {
135062
- const generator = new generatorsMap.GenerateTime[0]();
135063
- return generator;
135064
- }
135065
- if (col.columnType.startsWith('timestamp')) {
135066
- const generator = new generatorsMap.GenerateTimestamp[0]();
135067
- return generator;
135068
- }
135069
- if (col.columnType === 'year') {
135070
- const generator = new generatorsMap.GenerateYear[0]();
135071
- return generator;
135072
- }
135073
- // JSON
135074
- if (col.columnType === 'json') {
135075
- const generator = new generatorsMap.GenerateJson[0]();
135076
- return generator;
135077
- }
135078
- // ENUM
135079
- if (col.enumValues !== undefined) {
135080
- const generator = new generatorsMap.GenerateEnum[0]({
135081
- enumValues: col.enumValues,
135082
- });
135083
- return generator;
135084
- }
135085
- if (col.hasDefault && col.default !== undefined) {
135086
- const generator = new generatorsMap.GenerateDefault[0]({
135087
- defaultValue: col.default,
135088
- });
135089
- return generator;
135090
- }
135091
- return;
135092
- };
135093
- const generator = pickGenerator(table, col);
135094
- return generator;
135095
- };
135096
- selectGeneratorForSqlite = (table, col) => {
135097
- const pickGenerator = (table, col) => {
135098
- // int section ---------------------------------------------------------------------------------------
135099
- if ((col.columnType === 'integer' || col.columnType === 'numeric')
135100
- && table.primaryKeys.includes(col.name)) {
135101
- const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
135102
- return generator;
135103
- }
135104
- if (col.columnType === 'integer' && col.dataType === 'boolean') {
135105
- const generator = new generatorsMap.GenerateBoolean[0]();
135106
- return generator;
135107
- }
135108
- if ((col.columnType === 'integer' && col.dataType === 'date')) {
135109
- const generator = new generatorsMap.GenerateTimestamp[0]();
135110
- return generator;
135111
- }
135112
- if (col.columnType === 'integer'
135113
- || (col.dataType === 'bigint' && col.columnType === 'blob')) {
135114
- const generator = new generatorsMap.GenerateInt[0]();
135115
- return generator;
135116
- }
135117
- // number section ------------------------------------------------------------------------------------
135118
- if (col.columnType.startsWith('real')
135119
- || col.columnType.startsWith('numeric')) {
135120
- if (col.typeParams.precision !== undefined) {
135121
- const precision = col.typeParams.precision;
135122
- const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
135123
- const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
135124
- const generator = new generatorsMap.GenerateNumber[0]({
135125
- minValue: -maxAbsoluteValue,
135126
- maxValue: maxAbsoluteValue,
135127
- precision: Math.pow(10, scale),
135128
- });
135129
- return generator;
135130
- }
135131
- const generator = new generatorsMap.GenerateNumber[0]();
135132
- return generator;
135133
- }
135134
- // string section ------------------------------------------------------------------------------------
135135
- if ((col.columnType.startsWith('text')
135136
- || col.columnType.startsWith('numeric')
135137
- || col.columnType.startsWith('blob'))
135138
- && table.primaryKeys.includes(col.name)) {
135139
- const generator = new generatorsMap.GenerateUniqueString[0]();
135140
- return generator;
135141
- }
135142
- if ((col.columnType.startsWith('text')
135143
- || col.columnType.startsWith('numeric')
135144
- || col.columnType.startsWith('blob'))
135145
- && col.name.toLowerCase().includes('name')) {
135146
- const generator = new generatorsMap.GenerateFirstName[0]();
135147
- return generator;
135148
- }
135149
- if ((col.columnType.startsWith('text')
135150
- || col.columnType.startsWith('numeric')
135151
- || col.columnType.startsWith('blob'))
135152
- && col.name.toLowerCase().includes('email')) {
135153
- const generator = new generatorsMap.GenerateEmail[0]();
135154
- return generator;
135155
- }
135156
- if (col.columnType.startsWith('text')
135157
- || col.columnType.startsWith('numeric')
135158
- || col.columnType.startsWith('blob')
135159
- || col.columnType.startsWith('blobbuffer')) {
135160
- const generator = new generatorsMap.GenerateString[0]();
135161
- return generator;
135162
- }
135163
- if ((col.columnType.startsWith('text') && col.dataType === 'json')
135164
- || (col.columnType.startsWith('blob') && col.dataType === 'json')) {
135165
- const generator = new generatorsMap.GenerateJson[0]();
135166
- return generator;
135167
- }
135168
- if (col.hasDefault && col.default !== undefined) {
135169
- const generator = new generatorsMap.GenerateDefault[0]({
135170
- defaultValue: col.default,
135171
- });
135172
- return generator;
135173
- }
135174
- return;
135175
- };
135176
- const generator = pickGenerator(table, col);
135177
- return generator;
135178
- };
135179
136255
  filterCyclicTables = (tablesGenerators) => {
135180
136256
  const filteredTablesGenerators = tablesGenerators.filter((tableGen) => tableGen.columnsPossibleGenerators.some((columnGen) => columnGen.isCyclic === true && columnGen.wasDefinedBefore === true));
135181
136257
  const tablesUniqueNotNullColumn = {};
@@ -135187,7 +136263,8 @@ class SeedService {
135187
136263
  throw new Error(`Table '${tableGen.tableName}' does not have primary or (unique and notNull) column. Can't seed table with cyclic relation.`);
135188
136264
  }
135189
136265
  tablesUniqueNotNullColumn[tableGen.tableName] = { uniqueNotNullColName };
135190
- 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) => {
135191
136268
  const newColGen = { ...colGen };
135192
136269
  newColGen.wasDefinedBefore = false;
135193
136270
  return newColGen;
@@ -135233,8 +136310,7 @@ class SeedService {
135233
136310
  };
135234
136311
  }
135235
136312
  // get values to generate columns with foreign key
135236
- // if table posts contains foreign key to table users, then rel.table === 'posts' and rel.refTable === 'users',
135237
- // because table posts has reference to table users.
136313
+ // if table posts contains foreign key to table users, then rel.table === 'posts' and rel.refTable === 'users', because table posts has reference to table users.
135238
136314
  if (filteredRelations.length !== 0) {
135239
136315
  for (const rel of filteredRelations) {
135240
136316
  if (table.withFromTable[rel.refTable] !== undefined
@@ -135282,7 +136358,9 @@ class SeedService {
135282
136358
  weightedCountSeed = table.withFromTable[rel.refTable].weightedCountSeed;
135283
136359
  }
135284
136360
  // TODO: revise maybe need to select version of generator here too
135285
- genObj = new generatorsMap.GenerateValuesFromArray[0]({ values: refColumnValues });
136361
+ genObj = new generatorsMap.GenerateValuesFromArray[0]({
136362
+ values: refColumnValues,
136363
+ });
135286
136364
  genObj.notNull = tableGenerators[rel.columns[colIdx]].notNull;
135287
136365
  genObj.weightedCountSeed = weightedCountSeed;
135288
136366
  genObj.maxRepeatedValuesCount = repeatedValuesCount;
@@ -135350,7 +136428,10 @@ class SeedService {
135350
136428
  for (const columnName of Object.keys(tableGenerators)) {
135351
136429
  columnsNumber += 1;
135352
136430
  columnGenerator = tableGenerators[columnName];
136431
+ // postgres identity columns
135353
136432
  override = tableGenerators[columnName]?.generatedIdentityType === 'always' ? true : override;
136433
+ // mssql identity columns
136434
+ override = tableGenerators[columnName]?.identity === true ? true : override;
135354
136435
  columnsGenerators[columnName] = columnGenerator.generator;
135355
136436
  columnsGenerators[columnName].init({
135356
136437
  count,
@@ -135365,25 +136446,6 @@ class SeedService {
135365
136446
  // columnsGenerators[columnName] = uniqueGen;
135366
136447
  // }
135367
136448
  }
135368
- // sequence updates will only be performed for PostgreSQL, since MySQL and SQLite already update their sequences correctly on their own.
135369
- const columnsToUpdateSeq = new Map();
135370
- if (count > 0 && is(db, PgDatabase) && schema !== undefined && tableName !== undefined
135371
- && schema[tableName] !== undefined) {
135372
- const tableConfig = getTableConfig(schema[tableName]);
135373
- for (const column of tableConfig.columns) {
135374
- // TODO should I filter only primary key columns?
135375
- // should I filter column by dataType or by column drizzle type?
135376
- // column.dataType === 'number' || column.dataType === 'bigint'
135377
- if (isPostgresColumnIntLike(column)) {
135378
- columnsToUpdateSeq.set(column.name, {
135379
- schemaName: tableConfig.schema,
135380
- tableName: tableConfig.name,
135381
- columnName: column.name,
135382
- valueToUpdate: undefined,
135383
- });
135384
- }
135385
- }
135386
- }
135387
136449
  let maxParametersNumber;
135388
136450
  if (is(db, (PgDatabase))) {
135389
136451
  // @ts-ignore
@@ -135394,10 +136456,13 @@ class SeedService {
135394
136456
  else if (is(db, (MySqlDatabase))) {
135395
136457
  maxParametersNumber = this.mysqlMaxParametersNumber;
135396
136458
  }
135397
- else {
135398
- // is(db, BaseSQLiteDatabase<any, any>)
136459
+ else if (is(db, (BaseSQLiteDatabase))) {
135399
136460
  maxParametersNumber = this.sqliteMaxParametersNumber;
135400
136461
  }
136462
+ else {
136463
+ // is(db, MsSqlDatabase<any, any>)
136464
+ maxParametersNumber = this.mssqlMaxParametersNumber;
136465
+ }
135401
136466
  const maxBatchSize = Math.floor(maxParametersNumber / columnsNumber);
135402
136467
  batchSize = batchSize > maxBatchSize ? maxBatchSize : batchSize;
135403
136468
  if ((insertDataInDb === true || updateDataInDb === true)
@@ -135415,12 +136480,6 @@ class SeedService {
135415
136480
  // | boolean;
135416
136481
  generatedValue = columnsGenerators[columnName].generate({ i });
135417
136482
  row[columnName] = generatedValue;
135418
- const colToUpdateSeq = columnsToUpdateSeq.get(columnName);
135419
- if (columnsToUpdateSeq.size !== 0 && colToUpdateSeq !== undefined) {
135420
- colToUpdateSeq.valueToUpdate = colToUpdateSeq?.valueToUpdate === undefined
135421
- ? generatedValue
135422
- : intMax([colToUpdateSeq.valueToUpdate, generatedValue]);
135423
- }
135424
136483
  }
135425
136484
  if ((insertDataInDb === true || updateDataInDb === true)
135426
136485
  && ((i + 1) % batchSize === 0 || i === count - 1)) {
@@ -135467,28 +136526,9 @@ class SeedService {
135467
136526
  }
135468
136527
  }
135469
136528
  }
135470
- const columnsToUpdateSeqFiltered = [...columnsToUpdateSeq.values()].filter((col) => col.valueToUpdate !== undefined);
135471
- if (i === count - 1
135472
- && columnsToUpdateSeqFiltered.length !== 0 && db !== undefined) {
135473
- for (const columnConfig of columnsToUpdateSeq.values()) {
135474
- if (columnConfig) {
135475
- await this.updateColumnSequence({ db, columnConfig });
135476
- }
135477
- }
135478
- }
135479
136529
  }
135480
136530
  return preserveData === true ? generatedValues : [];
135481
136531
  };
135482
- updateColumnSequence = async ({ db, columnConfig: { schemaName, tableName, columnName, valueToUpdate } }) => {
135483
- if (is(db, PgDatabase)) {
135484
- const fullTableName = schemaName ? `"${schemaName}"."${tableName}"` : `"${tableName}"`;
135485
- const rawQuery = `SELECT setval(pg_get_serial_sequence('${fullTableName}', '${columnName}'), ${(valueToUpdate ?? 'null').toString()}, true);`;
135486
- await db.execute(sql.raw(rawQuery));
135487
- }
135488
- // mysql updates auto_increment or serial column by itself
135489
- // sqlite updates autoincrement column by itself
135490
- return;
135491
- };
135492
136532
  insertInDb = async ({ generatedValues, db, schema, tableName, override, }) => {
135493
136533
  if (is(db, (PgDatabase))) {
135494
136534
  const query = db.insert(schema[tableName]);
@@ -135507,253 +136547,730 @@ class SeedService {
135507
136547
  .insert(schema[tableName])
135508
136548
  .values(generatedValues);
135509
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
+ }
135510
136578
  };
135511
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));
135512
136583
  if (is(db, (PgDatabase))) {
135513
136584
  const table = schema[tableName];
135514
136585
  const uniqueNotNullCol = table[uniqueNotNullColName];
135515
- await db.update(table).set(generatedValues[0]).where(eq(uniqueNotNullCol, generatedValues[0][uniqueNotNullColName]));
136586
+ await db.update(table).set(values).where(eq(uniqueNotNullCol, uniqueNotNullColValue));
135516
136587
  }
135517
136588
  else if (is(db, (MySqlDatabase))) {
135518
136589
  const table = schema[tableName];
135519
- 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));
135520
136591
  }
135521
136592
  else if (is(db, (BaseSQLiteDatabase))) {
135522
136593
  const table = schema[tableName];
135523
- 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));
135524
136607
  }
135525
136608
  };
135526
136609
  }
135527
136610
 
135528
- /* eslint-disable drizzle-internal/require-entity-kind */
135529
- class SeedPromise {
135530
- db;
135531
- schema;
135532
- options;
135533
- static entityKind = 'SeedPromise';
135534
- [Symbol.toStringTag] = 'SeedPromise';
135535
- constructor(db, schema, options) {
135536
- this.db = db;
135537
- this.schema = schema;
135538
- this.options = options;
135539
- }
135540
- then(onfulfilled, onrejected) {
135541
- return seedFunc(this.db, this.schema, this.options).then(onfulfilled, onrejected);
135542
- }
135543
- catch(onrejected) {
135544
- return this.then(undefined, onrejected);
135545
- }
135546
- finally(onfinally) {
135547
- return this.then((value) => {
135548
- onfinally?.();
135549
- return value;
135550
- }, (reason) => {
135551
- onfinally?.();
135552
- 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
+ };
135553
136732
  });
135554
- }
135555
- async refine(callback) {
135556
- const refinements = this.options?.version === undefined || this.options.version === '2'
135557
- ? callback(generatorsFuncsV2)
135558
- : callback(generatorsFuncs);
135559
- await seedFunc(this.db, this.schema, this.options, refinements);
135560
- }
135561
- }
135562
- function getGeneratorsFunctions() {
135563
- return generatorsFuncs;
135564
- }
135565
- async function seedForDrizzleStudio({ sqlDialect, drizzleStudioObject, drizzleStudioRelations, schemasRefinements, options }) {
135566
- const generatedSchemas = {};
135567
- let tables, relations, refinements;
135568
- drizzleStudioRelations = drizzleStudioRelations.filter((rel) => rel.type === 'one');
135569
- for (const [schemaName, { tables: drizzleStudioTables }] of Object.entries(drizzleStudioObject)) {
135570
- tables = [];
135571
- for (const [tableName, table] of Object.entries(drizzleStudioTables)) {
135572
- const drizzleStudioColumns = Object.values(table.columns);
135573
- const columns = drizzleStudioColumns.map((col) => ({
135574
- name: col.name,
135575
- dataType: 'string',
135576
- columnType: col.type,
135577
- // TODO: revise later
135578
- typeParams: {},
135579
- default: col.default,
135580
- hasDefault: col.default === undefined ? false : true,
135581
- isUnique: col.isUnique === undefined ? false : col.isUnique,
135582
- notNull: col.notNull,
135583
- primary: col.primaryKey,
135584
- }));
135585
- tables.push({
135586
- name: tableName,
135587
- columns,
135588
- primaryKeys: drizzleStudioColumns.filter((col) => col.primaryKey === true).map((col) => col.name),
135589
- });
136733
+ relations.push(...newRelations);
136734
+ if (tableRelations[dbToTsTableNamesMap[tableConfig.name]] === undefined) {
136735
+ tableRelations[dbToTsTableNamesMap[tableConfig.name]] = [];
135590
136736
  }
135591
- relations = drizzleStudioRelations.filter((rel) => rel.schema === schemaName && rel.refSchema === schemaName);
135592
- const isCyclicRelations = relations.map((reli) => {
135593
- if (relations.some((relj) => reli.table === relj.refTable && reli.refTable === relj.table)) {
135594
- 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
+ }
135595
136764
  }
135596
- 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]),
135597
136812
  });
135598
- refinements = schemasRefinements !== undefined && schemasRefinements[schemaName] !== undefined
135599
- ? schemasRefinements[schemaName]
135600
- : undefined;
135601
- const seedService = new SeedService();
135602
- const generatedTablesGenerators = seedService.generatePossibleGenerators(sqlDialect, tables, isCyclicRelations, refinements, options);
135603
- const generatedTables = await seedService.generateTablesValues(isCyclicRelations, generatedTablesGenerators, undefined, undefined, { ...options, preserveData: true, insertDataInDb: false });
135604
- generatedSchemas[schemaName] = { tables: generatedTables };
135605
136813
  }
135606
- return generatedSchemas;
135607
- }
135608
- /**
135609
- * @param db - database you would like to seed.
135610
- * @param schema - object that contains all your database tables you would like to seed.
135611
- * @param options - object that contains properties `count` and `seed`:
135612
- *
135613
- * `count` - number of rows you want to generate.
135614
- *
135615
- * `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)
135616
- *
135617
- * @returns SeedPromise - a class object that has a refine method that is used to change generators for columns.
135618
- *
135619
- * @example
135620
- * ```ts
135621
- * // base seeding
135622
- * await seed(db, schema);
135623
- *
135624
- * // seeding with count specified
135625
- * await seed(db, schema, { count: 100000 });
135626
- *
135627
- * // seeding with count and seed specified
135628
- * await seed(db, schema, { count: 100000, seed: 1 });
135629
- *
135630
- * // seeding using refine
135631
- * await seed(db, schema, { count: 1000 }).refine((funcs) => ({
135632
- * users: {
135633
- * columns: {
135634
- * name: funcs.firstName({ isUnique: true }),
135635
- * email: funcs.email(),
135636
- * phone: funcs.phoneNumber({ template: "+380 99 ###-##-##" }),
135637
- * password: funcs.string({ isUnique: true }),
135638
- * },
135639
- * count: 100000,
135640
- * },
135641
- * posts: {
135642
- * columns: {
135643
- * title: funcs.valuesFromArray({
135644
- * values: ["Title1", "Title2", "Title3", "Title4", "Title5"],
135645
- * }),
135646
- * content: funcs.loremIpsum({ sentencesCount: 3 }),
135647
- * },
135648
- * },
135649
- * }));
135650
- *
135651
- * // seeding while ignoring column
135652
- * await seed(db, schema).refine((funcs) => ({
135653
- * users: {
135654
- * count: 5,
135655
- * columns: {
135656
- * name: funcs.fullName(),
135657
- * photo: false, // the photo column will not be seeded, allowing the database to use its default value.
135658
- * },
135659
- * },
135660
- * }));
135661
- *
135662
- * ```
135663
- */
135664
- function seed(db, schema, options) {
135665
- return new SeedPromise(db, schema, options);
135666
- }
135667
- const seedFunc = async (db, schema, options = {}, refinements) => {
135668
- let version;
135669
- if (options?.version !== undefined) {
135670
- version = Number(options?.version);
135671
- }
135672
- if (is(db, (PgDatabase))) {
135673
- await seedPostgres(db, schema, { ...options, version }, refinements);
135674
- }
135675
- else if (is(db, (MySqlDatabase))) {
135676
- await seedMySql(db, schema, { ...options, version }, refinements);
135677
- }
135678
- else if (is(db, (BaseSQLiteDatabase))) {
135679
- 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));
135680
136891
  }
135681
- else {
135682
- 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
+ }
135683
136906
  }
135684
- return;
135685
136907
  };
135686
- /**
135687
- * deletes all data from specified tables
135688
- *
135689
- * @param db - database you would like to reset.
135690
- * @param schema - object that contains all your database tables you would like to delete data from.
135691
- *
135692
- * `If db is a PgDatabase object`, we will execute sql query and delete data from your tables the following way:
135693
- * ```sql
135694
- * truncate tableName1, tableName2, ... cascade;
135695
- * ```
135696
- *
135697
- * `If db is a MySqlDatabase object`, we will execute sql queries and delete data from your tables the following way:
135698
- * ```sql
135699
- * SET FOREIGN_KEY_CHECKS = 0;
135700
- * truncate tableName1;
135701
- * truncate tableName2;
135702
- * .
135703
- * .
135704
- * .
135705
- *
135706
- * SET FOREIGN_KEY_CHECKS = 1;
135707
- * ```
135708
- *
135709
- * `If db is a BaseSQLiteDatabase object`, we will execute sql queries and delete data from your tables the following way:
135710
- * ```sql
135711
- * PRAGMA foreign_keys = OFF;
135712
- * delete from tableName1;
135713
- * delete from tableName2;
135714
- * .
135715
- * .
135716
- * .
135717
- *
135718
- * PRAGMA foreign_keys = ON;
135719
- * ```
135720
- *
135721
- * @example
135722
- * ```ts
135723
- * await reset(db, schema);
135724
- *
135725
- * // Alternatively, you can provide an object containing your tables
135726
- * // as the `schema` parameter when calling `reset`.
135727
- * await reset(db, { users });
135728
- * ```
135729
- */
135730
- async function reset(db, schema) {
135731
- if (is(db, (PgDatabase))) {
135732
- const { pgTables } = filterPgSchema(schema);
135733
- if (Object.entries(pgTables).length > 0) {
135734
- 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;
135735
136938
  }
135736
- }
135737
- else if (is(db, (MySqlDatabase))) {
135738
- const { mysqlTables } = filterMysqlTables(schema);
135739
- if (Object.entries(mysqlTables).length > 0) {
135740
- 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;
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]] = [];
135741
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
+ });
135742
137068
  }
135743
- else if (is(db, (BaseSQLiteDatabase))) {
135744
- const { sqliteTables } = filterSqliteTables(schema);
135745
- if (Object.entries(sqliteTables).length > 0) {
135746
- 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 };
135747
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));
135748
137093
  }
135749
- else {
135750
- 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
+ });
135751
137255
  }
135752
- }
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
+
135753
137270
  // Postgres-----------------------------------------------------------------------------------------------------------
135754
137271
  const resetPostgres = async (db, pgTables) => {
135755
137272
  const tablesToTruncate = Object.entries(pgTables).map(([_, table]) => {
135756
- const config = getTableConfig(table);
137273
+ const config = getTableConfig$3(table);
135757
137274
  config.schema = config.schema === undefined ? 'public' : config.schema;
135758
137275
  return `"${config.schema}"."${config.name}"`;
135759
137276
  });
@@ -135790,7 +137307,7 @@ const getPostgresInfo = (pgSchema, pgTables) => {
135790
137307
  dbToTsColumnNamesMap = dbToTsColumnNamesMapGlobal[tableName];
135791
137308
  return dbToTsColumnNamesMap;
135792
137309
  }
135793
- const tableConfig = getTableConfig(table);
137310
+ const tableConfig = getTableConfig$3(table);
135794
137311
  for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
135795
137312
  dbToTsColumnNamesMap[col.name] = tsCol;
135796
137313
  }
@@ -135806,14 +137323,14 @@ const getPostgresInfo = (pgSchema, pgTables) => {
135806
137323
  for (const drizzleRel of Object.values(table.relations)) {
135807
137324
  if (!is(drizzleRel, One))
135808
137325
  continue;
135809
- const tableConfig = getTableConfig(drizzleRel.sourceTable);
137326
+ const tableConfig = getTableConfig$3(drizzleRel.sourceTable);
135810
137327
  const tableDbSchema = tableConfig.schema ?? 'public';
135811
137328
  const tableDbName = tableConfig.name;
135812
137329
  const tableTsName = schemaConfig.tableNamesMap[`${tableDbSchema}.${tableDbName}`] ?? tableDbName;
135813
137330
  const dbToTsColumnNamesMap = getDbToTsColumnNamesMap(drizzleRel.sourceTable);
135814
137331
  const columns = drizzleRel.config?.fields.map((field) => dbToTsColumnNamesMap[field.name])
135815
137332
  ?? [];
135816
- const refTableConfig = getTableConfig(drizzleRel.referencedTable);
137333
+ const refTableConfig = getTableConfig$3(drizzleRel.referencedTable);
135817
137334
  const refTableDbSchema = refTableConfig.schema ?? 'public';
135818
137335
  const refTableDbName = refTableConfig.name;
135819
137336
  const refTableTsName = schemaConfig.tableNamesMap[`${refTableDbSchema}.${refTableDbName}`]
@@ -135847,7 +137364,7 @@ const getPostgresInfo = (pgSchema, pgTables) => {
135847
137364
  return relations;
135848
137365
  };
135849
137366
  for (const table of Object.values(pgTables)) {
135850
- tableConfig = getTableConfig(table);
137367
+ tableConfig = getTableConfig$3(table);
135851
137368
  dbToTsColumnNamesMap = {};
135852
137369
  for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
135853
137370
  dbToTsColumnNamesMap[col.name] = tsCol;
@@ -135918,6 +137435,7 @@ const getPostgresInfo = (pgSchema, pgTables) => {
135918
137435
  || sqlType.startsWith('bpchar')
135919
137436
  || sqlType.startsWith('char')
135920
137437
  || sqlType.startsWith('bit')
137438
+ || sqlType.startsWith('vector')
135921
137439
  || sqlType.startsWith('time')
135922
137440
  || sqlType.startsWith('timestamp')
135923
137441
  || sqlType.startsWith('interval')) {
@@ -135967,37 +137485,9 @@ const getPostgresInfo = (pgSchema, pgTables) => {
135967
137485
  });
135968
137486
  return { tables, relations: isCyclicRelations, tableRelations };
135969
137487
  };
135970
- const isRelationCyclic = (startRel) => {
135971
- // self relation
135972
- if (startRel.table === startRel.refTable)
135973
- return false;
135974
- // DFS
135975
- const targetTable = startRel.table;
135976
- const queue = [startRel];
135977
- let path = [];
135978
- while (queue.length !== 0) {
135979
- const currRel = queue.shift();
135980
- if (path.includes(currRel.table)) {
135981
- const idx = path.indexOf(currRel.table);
135982
- path = path.slice(0, idx);
135983
- }
135984
- path.push(currRel.table);
135985
- for (const rel of currRel.refTableRels) {
135986
- // self relation
135987
- if (rel.table === rel.refTable)
135988
- continue;
135989
- if (rel.refTable === targetTable)
135990
- return true;
135991
- // found cycle, but not the one we are looking for
135992
- if (path.includes(rel.refTable))
135993
- continue;
135994
- queue.unshift(rel);
135995
- }
135996
- }
135997
- return false;
135998
- };
135999
- // MySql-----------------------------------------------------------------------------------------------------
136000
- const resetMySql = async (db, schema) => {
137488
+
137489
+ // SingleStore-----------------------------------------------------------------------------------------------------
137490
+ const resetSingleStore = async (db, schema) => {
136001
137491
  const tablesToTruncate = Object.entries(schema).map(([_tsTableName, table]) => {
136002
137492
  const dbTableName = getTableName(table);
136003
137493
  return dbTableName;
@@ -136009,26 +137499,26 @@ const resetMySql = async (db, schema) => {
136009
137499
  }
136010
137500
  await db.execute(sql.raw('SET FOREIGN_KEY_CHECKS = 1;'));
136011
137501
  };
136012
- const filterMysqlTables = (schema) => {
136013
- const mysqlSchema = Object.fromEntries(Object.entries(schema).filter((keyValue) => is(keyValue[1], MySqlTable) || is(keyValue[1], Relations)));
136014
- const mysqlTables = Object.fromEntries(Object.entries(schema).filter((keyValue) => is(keyValue[1], MySqlTable)));
136015
- 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 };
136016
137506
  };
136017
- const seedMySql = async (db, schema, options = {}, refinements) => {
136018
- const { mysqlSchema, mysqlTables } = filterMysqlTables(schema);
136019
- 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);
136020
137510
  const seedService = new SeedService();
136021
- const generatedTablesGenerators = seedService.generatePossibleGenerators('mysql', tables, relations, refinements, options);
137511
+ const generatedTablesGenerators = seedService.generatePossibleGenerators('singlestore', tables, relations, refinements, options);
136022
137512
  const preserveCyclicTablesData = relations.some((rel) => rel.isCyclic === true);
136023
- const tablesValues = await seedService.generateTablesValues(relations, generatedTablesGenerators, db, mysqlTables, { ...options, preserveCyclicTablesData });
137513
+ const tablesValues = await seedService.generateTablesValues(relations, generatedTablesGenerators, db, singleStoreTables, { ...options, preserveCyclicTablesData });
136024
137514
  const { filteredTablesGenerators, tablesUniqueNotNullColumn } = seedService.filterCyclicTables(generatedTablesGenerators);
136025
137515
  const updateDataInDb = filteredTablesGenerators.length === 0 ? false : true;
136026
- await seedService.generateTablesValues(relations, filteredTablesGenerators, db, mysqlTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
137516
+ await seedService.generateTablesValues(relations, filteredTablesGenerators, db, singleStoreTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
136027
137517
  };
136028
- const getMySqlInfo = (mysqlSchema, mysqlTables) => {
137518
+ const getSingleStoreInfo = (singleStoreSchema, singleStoreTables) => {
136029
137519
  let tableConfig;
136030
137520
  let dbToTsColumnNamesMap;
136031
- 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]));
136032
137522
  const tables = [];
136033
137523
  const relations = [];
136034
137524
  const dbToTsColumnNamesMapGlobal = {};
@@ -136040,7 +137530,7 @@ const getMySqlInfo = (mysqlSchema, mysqlTables) => {
136040
137530
  dbToTsColumnNamesMap = dbToTsColumnNamesMapGlobal[tableName];
136041
137531
  return dbToTsColumnNamesMap;
136042
137532
  }
136043
- const tableConfig = getTableConfig$1(table);
137533
+ const tableConfig = getTableConfig$4(table);
136044
137534
  for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
136045
137535
  dbToTsColumnNamesMap[col.name] = tsCol;
136046
137536
  }
@@ -136056,14 +137546,14 @@ const getMySqlInfo = (mysqlSchema, mysqlTables) => {
136056
137546
  for (const drizzleRel of Object.values(table.relations)) {
136057
137547
  if (!is(drizzleRel, One))
136058
137548
  continue;
136059
- const tableConfig = getTableConfig$1(drizzleRel.sourceTable);
137549
+ const tableConfig = getTableConfig$4(drizzleRel.sourceTable);
136060
137550
  const tableDbSchema = tableConfig.schema ?? 'public';
136061
137551
  const tableDbName = tableConfig.name;
136062
137552
  const tableTsName = schemaConfig.tableNamesMap[`${tableDbSchema}.${tableDbName}`] ?? tableDbName;
136063
137553
  const dbToTsColumnNamesMap = getDbToTsColumnNamesMap(drizzleRel.sourceTable);
136064
137554
  const columns = drizzleRel.config?.fields.map((field) => dbToTsColumnNamesMap[field.name])
136065
137555
  ?? [];
136066
- const refTableConfig = getTableConfig$1(drizzleRel.referencedTable);
137556
+ const refTableConfig = getTableConfig$4(drizzleRel.referencedTable);
136067
137557
  const refTableDbSchema = refTableConfig.schema ?? 'public';
136068
137558
  const refTableDbName = refTableConfig.name;
136069
137559
  const refTableTsName = schemaConfig.tableNamesMap[`${refTableDbSchema}.${refTableDbName}`]
@@ -136096,36 +137586,42 @@ const getMySqlInfo = (mysqlSchema, mysqlTables) => {
136096
137586
  }
136097
137587
  return relations;
136098
137588
  };
136099
- for (const table of Object.values(mysqlTables)) {
136100
- tableConfig = getTableConfig$1(table);
137589
+ for (const table of Object.values(singleStoreTables)) {
137590
+ tableConfig = getTableConfig$4(table);
136101
137591
  dbToTsColumnNamesMap = {};
136102
137592
  for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
136103
137593
  dbToTsColumnNamesMap[col.name] = tsCol;
136104
137594
  }
136105
- const newRelations = tableConfig.foreignKeys.map((fk) => {
136106
- const table = dbToTsTableNamesMap[tableConfig.name];
136107
- const refTable = dbToTsTableNamesMap[getTableName(fk.reference().foreignTable)];
136108
- const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(fk.reference().foreignTable);
136109
- if (tableRelations[refTable] === undefined) {
136110
- tableRelations[refTable] = [];
136111
- }
136112
- return {
136113
- table,
136114
- columns: fk
136115
- .reference()
136116
- .columns.map((col) => dbToTsColumnNamesMap[col.name]),
136117
- refTable,
136118
- refColumns: fk
136119
- .reference()
136120
- .foreignColumns.map((fCol) => dbToTsColumnNamesMapForRefTable[fCol.name]),
136121
- refTableRels: tableRelations[refTable],
136122
- };
136123
- });
136124
- 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
+ // );
136125
137621
  if (tableRelations[dbToTsTableNamesMap[tableConfig.name]] === undefined) {
136126
137622
  tableRelations[dbToTsTableNamesMap[tableConfig.name]] = [];
136127
137623
  }
136128
- tableRelations[dbToTsTableNamesMap[tableConfig.name]].push(...newRelations);
137624
+ // tableRelations[dbToTsTableNamesMap[tableConfig.name] as string]!.push(...newRelations);
136129
137625
  const getTypeParams = (sqlType) => {
136130
137626
  // get type params and set only type
136131
137627
  const typeParams = {};
@@ -136148,6 +137644,13 @@ const getMySqlInfo = (mysqlSchema, mysqlTables) => {
136148
137644
  typeParams['length'] = Number(match[1]);
136149
137645
  }
136150
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
+ }
136151
137654
  return typeParams;
136152
137655
  };
136153
137656
  tables.push({
@@ -136169,7 +137672,7 @@ const getMySqlInfo = (mysqlSchema, mysqlTables) => {
136169
137672
  .map((column) => dbToTsColumnNamesMap[column.name]),
136170
137673
  });
136171
137674
  }
136172
- const transformedDrizzleRelations = transformFromDrizzleRelation(mysqlSchema, getDbToTsColumnNamesMap, tableRelations);
137675
+ const transformedDrizzleRelations = transformFromDrizzleRelation(singleStoreSchema, getDbToTsColumnNamesMap, tableRelations);
136173
137676
  relations.push(...transformedDrizzleRelations);
136174
137677
  const isCyclicRelations = relations.map((relI) => {
136175
137678
  const tableRel = tableRelations[relI.table].find((relJ) => relJ.refTable === relI.refTable);
@@ -136182,6 +137685,7 @@ const getMySqlInfo = (mysqlSchema, mysqlTables) => {
136182
137685
  });
136183
137686
  return { tables, relations: isCyclicRelations, tableRelations };
136184
137687
  };
137688
+
136185
137689
  // Sqlite------------------------------------------------------------------------------------------------------------------------
136186
137690
  const resetSqlite = async (db, schema) => {
136187
137691
  const tablesToTruncate = Object.entries(schema).map(([_tsTableName, table]) => {
@@ -136226,7 +137730,7 @@ const getSqliteInfo = (sqliteSchema, sqliteTables) => {
136226
137730
  dbToTsColumnNamesMap = dbToTsColumnNamesMapGlobal[tableName];
136227
137731
  return dbToTsColumnNamesMap;
136228
137732
  }
136229
- const tableConfig = getTableConfig$2(table);
137733
+ const tableConfig = getTableConfig$5(table);
136230
137734
  for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
136231
137735
  dbToTsColumnNamesMap[col.name] = tsCol;
136232
137736
  }
@@ -136242,14 +137746,14 @@ const getSqliteInfo = (sqliteSchema, sqliteTables) => {
136242
137746
  for (const drizzleRel of Object.values(table.relations)) {
136243
137747
  if (!is(drizzleRel, One))
136244
137748
  continue;
136245
- const tableConfig = getTableConfig$2(drizzleRel.sourceTable);
137749
+ const tableConfig = getTableConfig$5(drizzleRel.sourceTable);
136246
137750
  const tableDbName = tableConfig.name;
136247
137751
  // TODO: tableNamesMap: have {public.customer: 'customer'} structure in sqlite
136248
137752
  const tableTsName = schemaConfig.tableNamesMap[`public.${tableDbName}`] ?? tableDbName;
136249
137753
  const dbToTsColumnNamesMap = getDbToTsColumnNamesMap(drizzleRel.sourceTable);
136250
137754
  const columns = drizzleRel.config?.fields.map((field) => dbToTsColumnNamesMap[field.name])
136251
137755
  ?? [];
136252
- const refTableConfig = getTableConfig$2(drizzleRel.referencedTable);
137756
+ const refTableConfig = getTableConfig$5(drizzleRel.referencedTable);
136253
137757
  const refTableDbName = refTableConfig.name;
136254
137758
  const refTableTsName = schemaConfig.tableNamesMap[`public.${refTableDbName}`]
136255
137759
  ?? refTableDbName;
@@ -136282,7 +137786,7 @@ const getSqliteInfo = (sqliteSchema, sqliteTables) => {
136282
137786
  return relations;
136283
137787
  };
136284
137788
  for (const table of Object.values(sqliteTables)) {
136285
- tableConfig = getTableConfig$2(table);
137789
+ tableConfig = getTableConfig$5(table);
136286
137790
  dbToTsColumnNamesMap = {};
136287
137791
  for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
136288
137792
  dbToTsColumnNamesMap[col.name] = tsCol;
@@ -136364,5 +137868,242 @@ const getSqliteInfo = (sqliteSchema, sqliteTables) => {
136364
137868
  return { tables, relations: isCyclicRelations, tableRelations };
136365
137869
  };
136366
137870
 
136367
- 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 };
136368
138109
  //# sourceMappingURL=index.mjs.map