drizzle-seed 0.3.2-f8a2f3c → 0.4.0-4ec2def

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 (77) hide show
  1. package/{services/SeedService.d.cts → SeedService.d.cts} +18 -26
  2. package/{services/SeedService.d.mts → SeedService.d.mts} +18 -26
  3. package/{services/SeedService.d.ts → SeedService.d.ts} +18 -26
  4. package/cockroach-core/index.d.cts +30 -0
  5. package/cockroach-core/index.d.mts +30 -0
  6. package/cockroach-core/index.d.ts +30 -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/common.d.cts +25 -0
  11. package/common.d.mts +25 -0
  12. package/common.d.ts +25 -0
  13. package/{services → generators}/GeneratorFuncs.d.cts +311 -35
  14. package/{services → generators}/GeneratorFuncs.d.mts +311 -35
  15. package/{services → generators}/GeneratorFuncs.d.ts +311 -35
  16. package/{services → generators}/Generators.d.cts +151 -25
  17. package/{services → generators}/Generators.d.mts +151 -25
  18. package/{services → generators}/Generators.d.ts +151 -25
  19. package/generators/utils.d.cts +38 -0
  20. package/generators/utils.d.mts +38 -0
  21. package/generators/utils.d.ts +38 -0
  22. package/{services → generators}/versioning/v2.d.cts +2 -2
  23. package/{services → generators}/versioning/v2.d.mts +2 -2
  24. package/{services → generators}/versioning/v2.d.ts +2 -2
  25. package/index.cjs +2604 -1354
  26. package/index.cjs.map +1 -1
  27. package/index.d.cts +94 -113
  28. package/index.d.mts +94 -113
  29. package/index.d.ts +94 -113
  30. package/index.mjs +2609 -1358
  31. package/index.mjs.map +1 -1
  32. package/mssql-core/index.d.cts +24 -0
  33. package/mssql-core/index.d.mts +24 -0
  34. package/mssql-core/index.d.ts +24 -0
  35. package/mssql-core/selectGensForColumn.d.cts +2 -0
  36. package/mssql-core/selectGensForColumn.d.mts +2 -0
  37. package/mssql-core/selectGensForColumn.d.ts +2 -0
  38. package/mysql-core/index.d.cts +30 -0
  39. package/mysql-core/index.d.mts +30 -0
  40. package/mysql-core/index.d.ts +30 -0
  41. package/mysql-core/selectGensForColumn.d.cts +2 -0
  42. package/mysql-core/selectGensForColumn.d.mts +2 -0
  43. package/mysql-core/selectGensForColumn.d.ts +2 -0
  44. package/package.json +13 -9
  45. package/pg-core/index.d.cts +30 -0
  46. package/pg-core/index.d.mts +30 -0
  47. package/pg-core/index.d.ts +30 -0
  48. package/pg-core/selectGensForColumn.d.cts +3 -0
  49. package/pg-core/selectGensForColumn.d.mts +3 -0
  50. package/pg-core/selectGensForColumn.d.ts +3 -0
  51. package/singlestore-core/index.d.cts +30 -0
  52. package/singlestore-core/index.d.mts +30 -0
  53. package/singlestore-core/index.d.ts +30 -0
  54. package/singlestore-core/selectGensForColumn.d.cts +2 -0
  55. package/singlestore-core/selectGensForColumn.d.mts +2 -0
  56. package/singlestore-core/selectGensForColumn.d.ts +2 -0
  57. package/sqlite-core/index.d.cts +30 -0
  58. package/sqlite-core/index.d.mts +30 -0
  59. package/sqlite-core/index.d.ts +30 -0
  60. package/sqlite-core/selectGensForColumn.d.cts +2 -0
  61. package/sqlite-core/selectGensForColumn.d.mts +2 -0
  62. package/sqlite-core/selectGensForColumn.d.ts +2 -0
  63. package/types/seedService.d.cts +12 -2
  64. package/types/seedService.d.mts +12 -2
  65. package/types/seedService.d.ts +12 -2
  66. package/types/tables.d.cts +17 -0
  67. package/types/tables.d.mts +17 -0
  68. package/types/tables.d.ts +17 -0
  69. package/utils.d.cts +4 -0
  70. package/utils.d.mts +4 -0
  71. package/utils.d.ts +4 -0
  72. package/services/utils.d.cts +0 -23
  73. package/services/utils.d.mts +0 -23
  74. package/services/utils.d.ts +0 -23
  75. /package/{services → generators}/apiVersion.d.cts +0 -0
  76. /package/{services → generators}/apiVersion.d.mts +0 -0
  77. /package/{services → generators}/apiVersion.d.ts +0 -0
package/index.cjs CHANGED
@@ -4,8 +4,187 @@ var drizzleOrm = require('drizzle-orm');
4
4
  var mysqlCore = require('drizzle-orm/mysql-core');
5
5
  var pgCore = require('drizzle-orm/pg-core');
6
6
  var sqliteCore = require('drizzle-orm/sqlite-core');
7
+ var mssqlCore = require('drizzle-orm/mssql-core');
8
+ var cockroachCore = require('drizzle-orm/cockroach-core');
9
+ var singlestoreCore = require('drizzle-orm/singlestore-core');
10
+ var _relations = require('drizzle-orm/_relations');
7
11
  var prand = require('pure-rand');
8
12
 
13
+ const isRelationCyclic = (startRel) => {
14
+ // self relation
15
+ if (startRel.table === startRel.refTable)
16
+ return false;
17
+ // DFS
18
+ const targetTable = startRel.table;
19
+ const queue = [startRel];
20
+ let path = [];
21
+ while (queue.length !== 0) {
22
+ const currRel = queue.shift();
23
+ if (path.includes(currRel.table)) {
24
+ const idx = path.indexOf(currRel.table);
25
+ path = path.slice(0, idx);
26
+ }
27
+ path.push(currRel.table);
28
+ for (const rel of currRel.refTableRels) {
29
+ // self relation
30
+ if (rel.table === rel.refTable)
31
+ continue;
32
+ if (rel.refTable === targetTable)
33
+ return true;
34
+ // found cycle, but not the one we are looking for
35
+ if (path.includes(rel.refTable))
36
+ continue;
37
+ queue.unshift(rel);
38
+ }
39
+ }
40
+ return false;
41
+ };
42
+ const generateHashFromString = (s) => {
43
+ let hash = 0;
44
+ // p and m are prime numbers
45
+ const p = 53;
46
+ const m = 28871271685163;
47
+ for (let i = 0; i < s.length; i++) {
48
+ hash += ((s.codePointAt(i) || 0) * Math.pow(p, i)) % m;
49
+ }
50
+ return hash;
51
+ };
52
+ const equalSets = (set1, set2) => {
53
+ return set1.size === set2.size && [...set1].every((si) => set2.has(si));
54
+ };
55
+
56
+ const getTableConfig = (table) => {
57
+ if (drizzleOrm.is(table, pgCore.PgTable))
58
+ return pgCore.getTableConfig(table);
59
+ else if (drizzleOrm.is(table, mysqlCore.MySqlTable))
60
+ return mysqlCore.getTableConfig(table);
61
+ else if (drizzleOrm.is(table, sqliteCore.SQLiteTable))
62
+ return sqliteCore.getTableConfig(table);
63
+ else if (drizzleOrm.is(table, cockroachCore.CockroachTable))
64
+ return cockroachCore.getTableConfig(table);
65
+ else if (drizzleOrm.is(table, mssqlCore.MsSqlTable))
66
+ return mssqlCore.getTableConfig(table);
67
+ else
68
+ return singlestoreCore.getTableConfig(table); // if (is(table, SingleStoreTable))
69
+ };
70
+ const transformFromDrizzleRelation = (schema, getDbToTsColumnNamesMap, tableRelations) => {
71
+ const schemaConfig = _relations.extractTablesRelationalConfig(schema, _relations.createTableRelationsHelpers);
72
+ const relations = [];
73
+ for (const table of Object.values(schemaConfig.tables)) {
74
+ if (table.relations === undefined)
75
+ continue;
76
+ for (const drizzleRel of Object.values(table.relations)) {
77
+ if (!drizzleOrm.is(drizzleRel, _relations.One))
78
+ continue;
79
+ const tableConfig = getTableConfig(drizzleRel.sourceTable);
80
+ const tableDbSchema = tableConfig.schema ?? 'public';
81
+ const tableDbName = tableConfig.name;
82
+ const tableTsName = schemaConfig.tableNamesMap[`${tableDbSchema}.${tableDbName}`] ?? tableDbName;
83
+ const dbToTsColumnNamesMap = getDbToTsColumnNamesMap(drizzleRel.sourceTable);
84
+ const columns = drizzleRel.config?.fields.map((field) => dbToTsColumnNamesMap[field.name])
85
+ ?? [];
86
+ const refTableConfig = getTableConfig(drizzleRel.referencedTable);
87
+ const refTableDbSchema = refTableConfig.schema ?? 'public';
88
+ const refTableDbName = refTableConfig.name;
89
+ const refTableTsName = schemaConfig.tableNamesMap[`${refTableDbSchema}.${refTableDbName}`]
90
+ ?? refTableDbName;
91
+ const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(drizzleRel.referencedTable);
92
+ const refColumns = drizzleRel.config?.references.map((ref) => dbToTsColumnNamesMapForRefTable[ref.name])
93
+ ?? [];
94
+ if (tableRelations[refTableTsName] === undefined) {
95
+ tableRelations[refTableTsName] = [];
96
+ }
97
+ const relation = {
98
+ table: tableTsName,
99
+ columns,
100
+ refTable: refTableTsName,
101
+ refColumns,
102
+ refTableRels: tableRelations[refTableTsName],
103
+ type: 'one',
104
+ };
105
+ // do not add duplicate relation
106
+ if (tableRelations[tableTsName]?.some((rel) => rel.table === relation.table
107
+ && rel.refTable === relation.refTable)) {
108
+ console.warn(`You are providing a one-to-many relation between the '${relation.refTable}' and '${relation.table}' tables,\n`
109
+ + `while the '${relation.table}' table object already has foreign key constraint in the schema referencing '${relation.refTable}' table.\n`
110
+ + `In this case, the foreign key constraint will be used.\n`);
111
+ continue;
112
+ }
113
+ relations.push(relation);
114
+ tableRelations[tableTsName].push(relation);
115
+ }
116
+ }
117
+ return relations;
118
+ };
119
+ const getSchemaInfo = (drizzleTablesAndRelations, drizzleTables, mapTable) => {
120
+ let tableConfig;
121
+ let dbToTsColumnNamesMap;
122
+ const dbToTsTableNamesMap = Object.fromEntries(Object.entries(drizzleTables).map(([key, value]) => [drizzleOrm.getTableName(value), key]));
123
+ const tables = [];
124
+ const relations = [];
125
+ const dbToTsColumnNamesMapGlobal = {};
126
+ const tableRelations = {};
127
+ const getDbToTsColumnNamesMap = (table) => {
128
+ let dbToTsColumnNamesMap = {};
129
+ const tableName = drizzleOrm.getTableName(table);
130
+ if (Object.hasOwn(dbToTsColumnNamesMapGlobal, tableName)) {
131
+ dbToTsColumnNamesMap = dbToTsColumnNamesMapGlobal[tableName];
132
+ return dbToTsColumnNamesMap;
133
+ }
134
+ const tableConfig = getTableConfig(table);
135
+ for (const [tsCol, col] of Object.entries(drizzleOrm.getColumnTable(tableConfig.columns[0]))) {
136
+ if (drizzleOrm.is(col, drizzleOrm.Column))
137
+ dbToTsColumnNamesMap[col.name] = tsCol;
138
+ }
139
+ dbToTsColumnNamesMapGlobal[tableName] = dbToTsColumnNamesMap;
140
+ return dbToTsColumnNamesMap;
141
+ };
142
+ for (const table of Object.values(drizzleTables)) {
143
+ tableConfig = getTableConfig(table);
144
+ dbToTsColumnNamesMap = getDbToTsColumnNamesMap(table);
145
+ // might be empty list
146
+ const newRelations = tableConfig.foreignKeys === undefined ? [] : tableConfig.foreignKeys.map((fk) => {
147
+ const table = dbToTsTableNamesMap[tableConfig.name];
148
+ const refTable = dbToTsTableNamesMap[drizzleOrm.getTableName(fk.reference().foreignTable)];
149
+ const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(fk.reference().foreignTable);
150
+ if (tableRelations[refTable] === undefined) {
151
+ tableRelations[refTable] = [];
152
+ }
153
+ return {
154
+ table,
155
+ columns: fk
156
+ .reference()
157
+ .columns.map((col) => dbToTsColumnNamesMap[col.name]),
158
+ refTable,
159
+ refColumns: fk
160
+ .reference()
161
+ .foreignColumns.map((fCol) => dbToTsColumnNamesMapForRefTable[fCol.name]),
162
+ refTableRels: tableRelations[refTable],
163
+ };
164
+ });
165
+ relations.push(...newRelations);
166
+ if (tableRelations[dbToTsTableNamesMap[tableConfig.name]] === undefined) {
167
+ tableRelations[dbToTsTableNamesMap[tableConfig.name]] = [];
168
+ }
169
+ tableRelations[dbToTsTableNamesMap[tableConfig.name]].push(...newRelations);
170
+ // console.log(tableConfig.columns);
171
+ tables.push(mapTable(tableConfig, dbToTsTableNamesMap, dbToTsColumnNamesMap));
172
+ }
173
+ const transformedDrizzleRelations = transformFromDrizzleRelation(drizzleTablesAndRelations, getDbToTsColumnNamesMap, tableRelations);
174
+ relations.push(...transformedDrizzleRelations);
175
+ const isCyclicRelations = relations.map((relI) => {
176
+ // if (relations.some((relj) => relI.table === relj.refTable && relI.refTable === relj.table)) {
177
+ const tableRel = tableRelations[relI.table].find((relJ) => relJ.refTable === relI.refTable);
178
+ if (isRelationCyclic(relI)) {
179
+ tableRel['isCyclic'] = true;
180
+ return { ...relI, isCyclic: true };
181
+ }
182
+ tableRel['isCyclic'] = false;
183
+ return { ...relI, isCyclic: false };
184
+ });
185
+ return { tables, relations: isCyclicRelations, tableRelations };
186
+ };
187
+
9
188
  /**
10
189
  * The original source for the Adjectives data was taken from https://www.kaggle.com/datasets/jordansiem/adjectives-list
11
190
  */
@@ -131132,18 +131311,60 @@ var streetSuffix = [
131132
131311
  ];
131133
131312
  const maxStringLength = 10;
131134
131313
 
131314
+ /* eslint-disable drizzle-internal/require-entity-kind */
131135
131315
  const fastCartesianProduct = (sets, index) => {
131136
131316
  const resultList = [];
131137
131317
  let currSet;
131138
131318
  let element;
131139
131319
  for (let i = sets.length - 1; i >= 0; i--) {
131140
131320
  currSet = sets[i];
131141
- element = currSet[index % currSet.length];
131321
+ element = currSet[index % Number(currSet.length)];
131322
+ resultList.unshift(element);
131323
+ index = Math.floor(index / Number(currSet.length));
131324
+ }
131325
+ return resultList;
131326
+ };
131327
+ const fastCartesianProductForBigint = (sets, index) => {
131328
+ const resultList = [];
131329
+ let currSet;
131330
+ let element;
131331
+ for (let i = sets.length - 1; i >= 0; i--) {
131332
+ currSet = sets[i];
131333
+ const remainder = index % BigInt(currSet.length);
131334
+ // TODO check how it works
131335
+ // remainder = remainder <= Number.MAX_SAFE_INTEGER ? Number(remainder) : remainder;
131336
+ element = currSet[remainder];
131142
131337
  resultList.unshift(element);
131143
- index = Math.floor(index / currSet.length);
131338
+ index = index / BigInt(currSet.length);
131144
131339
  }
131145
131340
  return resultList;
131146
131341
  };
131342
+ class OrderedNumberRange {
131343
+ min;
131344
+ max;
131345
+ step;
131346
+ length;
131347
+ constructor(min, max, step) {
131348
+ this.min = min;
131349
+ this.max = max;
131350
+ this.step = step;
131351
+ this.length = Math.floor((this.max - this.min) / this.step) + 1;
131352
+ const handler = {
131353
+ get(target, prop, receiver) {
131354
+ if (typeof prop === 'string' && /^\d+$/.test(prop)) {
131355
+ const idx = Number(prop);
131356
+ if (idx >= target.length)
131357
+ return undefined;
131358
+ return (target.min + idx * target.step);
131359
+ }
131360
+ // fallback to normal lookup (and TS knows this has the right signature)
131361
+ return Reflect.get(target, prop, receiver);
131362
+ },
131363
+ };
131364
+ return new Proxy(this, handler);
131365
+ }
131366
+ }
131367
+ const abs = (n) => (n < 0n) ? -n : n;
131147
131368
  const sumArray = (weights) => {
131148
131369
  const scale = 1e10;
131149
131370
  const scaledSum = weights.reduce((acc, currVal) => acc + Math.round(currVal * scale), 0);
@@ -131167,16 +131388,6 @@ const getWeightedIndices = (weights, accuracy = 100) => {
131167
131388
  }
131168
131389
  return weightedIndices;
131169
131390
  };
131170
- const generateHashFromString = (s) => {
131171
- let hash = 0;
131172
- // p and m are prime numbers
131173
- const p = 53;
131174
- const m = 28871271685163;
131175
- for (let i = 0; i < s.length; i++) {
131176
- hash += ((s.codePointAt(i) || 0) * Math.pow(p, i)) % m;
131177
- }
131178
- return hash;
131179
- };
131180
131391
  /**
131181
131392
  * @param param0.template example: "#####" or "#####-####"
131182
131393
  * @param param0.values example: ["3", "2", "h"]
@@ -131213,12 +131424,27 @@ const isObject = (value) => {
131213
131424
  return true;
131214
131425
  return false;
131215
131426
  };
131216
- const equalSets = (set1, set2) => {
131217
- return set1.size === set2.size && [...set1].every((si) => set2.has(si));
131218
- };
131219
- const isValidDate = (date) => {
131220
- return !Number.isNaN(date.getTime());
131221
- };
131427
+ // const main = () => {
131428
+ // console.time('range');
131429
+ // const range = new OrderedBigintRange(BigInt(-10), BigInt(10), BigInt(1));
131430
+ // console.log(range.length);
131431
+ // for (let i = 0; i < Number(range.length) + 1; i++) {
131432
+ // console.log(range[i]);
131433
+ // }
131434
+ // console.timeEnd('range');
131435
+ // const list = Array.from({ length: 2e6 + 1 }, (_, idx) => idx);
131436
+ // console.time('list');
131437
+ // console.log(list.length);
131438
+ // for (let i = 0; i < 2e6 + 1; i++) {
131439
+ // list[i];
131440
+ // }
131441
+ // console.timeEnd('list');
131442
+ // // const n = 5;
131443
+ // // for (let i = 0; i < n; i++) {
131444
+ // // console.log(fastCartesianProduct([[1, 2], [1, 2]], i));
131445
+ // // }
131446
+ // };
131447
+ // main();
131222
131448
 
131223
131449
  /* eslint-disable drizzle-internal/require-entity-kind */
131224
131450
  class AbstractGenerator {
@@ -131234,10 +131460,11 @@ class AbstractGenerator {
131234
131460
  arraySize;
131235
131461
  baseColumnDataType;
131236
131462
  // param for text-like generators
131237
- stringLength;
131463
+ // public stringLength?: number;
131238
131464
  // params for GenerateValuesFromArray
131239
131465
  weightedCountSeed;
131240
131466
  maxRepeatedValuesCount;
131467
+ typeParams = {};
131241
131468
  params;
131242
131469
  constructor(params) {
131243
131470
  this.params = params === undefined ? {} : params;
@@ -131269,6 +131496,7 @@ class AbstractGenerator {
131269
131496
  });
131270
131497
  uniqueGen.isUnique = this.isUnique;
131271
131498
  uniqueGen.dataType = this.dataType;
131499
+ uniqueGen.typeParams = this.typeParams;
131272
131500
  return uniqueGen;
131273
131501
  }
131274
131502
  return;
@@ -131279,10 +131507,13 @@ class AbstractGenerator {
131279
131507
  const uniqueGen = this.replaceIfUnique();
131280
131508
  const baseColumnGen = uniqueGen === undefined ? this : uniqueGen;
131281
131509
  baseColumnGen.dataType = this.baseColumnDataType;
131510
+ const { dimensions, ...rest } = baseColumnGen.typeParams;
131511
+ baseColumnGen.typeParams = rest;
131282
131512
  const arrayGen = new GenerateArray({
131283
131513
  baseColumnGen,
131284
131514
  size: this.arraySize,
131285
131515
  });
131516
+ arrayGen.typeParams = { dimensions };
131286
131517
  return arrayGen;
131287
131518
  }
131288
131519
  return;
@@ -131537,6 +131768,7 @@ class GenerateNumber extends AbstractGenerator {
131537
131768
  static entityKind = 'GenerateNumber';
131538
131769
  state;
131539
131770
  uniqueVersionOfGen = GenerateUniqueNumber;
131771
+ // TODO rewrite precision to decimalPlaces
131540
131772
  init({ count, seed }) {
131541
131773
  super.init({ count, seed });
131542
131774
  let { minValue, maxValue, precision } = this.params;
@@ -131790,20 +132022,13 @@ class GenerateDate extends AbstractGenerator {
131790
132022
  const rng = prand.xoroshiro128plus(seed);
131791
132023
  let { minDate, maxDate } = this.params;
131792
132024
  const anchorDate = new Date('2024-05-08');
131793
- // 4 years in milliseconds
131794
132025
  const deltaMilliseconds = 4 * 31536000000;
131795
132026
  if (typeof minDate === 'string') {
131796
132027
  minDate = new Date(minDate);
131797
132028
  }
131798
- if (typeof minDate === 'object' && !isValidDate(minDate)) {
131799
- throw new Error('Invalid Date was provided for the minDate parameter.');
131800
- }
131801
132029
  if (typeof maxDate === 'string') {
131802
132030
  maxDate = new Date(maxDate);
131803
132031
  }
131804
- if (typeof maxDate === 'object' && !isValidDate(maxDate)) {
131805
- throw new Error('Invalid Date was provided for the maxDate parameter.');
131806
- }
131807
132032
  if (minDate === undefined) {
131808
132033
  if (maxDate === undefined) {
131809
132034
  minDate = new Date(anchorDate.getTime() - deltaMilliseconds);
@@ -131816,9 +132041,6 @@ class GenerateDate extends AbstractGenerator {
131816
132041
  if (maxDate === undefined) {
131817
132042
  maxDate = new Date(minDate.getTime() + (2 * deltaMilliseconds));
131818
132043
  }
131819
- if (minDate > maxDate) {
131820
- throw new Error(`The minDate parameter must be less than or equal to the maxDate parameter.`);
131821
- }
131822
132044
  this.state = { rng, minDate, maxDate };
131823
132045
  }
131824
132046
  generate() {
@@ -131840,83 +132062,18 @@ class GenerateTime extends AbstractGenerator {
131840
132062
  init({ count, seed }) {
131841
132063
  super.init({ count, seed });
131842
132064
  const rng = prand.xoroshiro128plus(seed);
131843
- let { minTime, maxTime } = this.params;
131844
- if (minTime === undefined && maxTime === undefined) {
131845
- // TODO: maybe need to change in major version release
131846
- // This is required to ensure that this generator remains deterministic when used without minTime, maxTime parameters.
131847
- const oneDayInMilliseconds = 86400000;
131848
- minTime = new Date(new Date('2024-05-08T12:00:00.000Z').getTime() - oneDayInMilliseconds);
131849
- maxTime = new Date(new Date('2024-05-08T12:00:00.000Z').getTime() + oneDayInMilliseconds);
131850
- this.state = { rng, minTime, maxTime };
131851
- return;
131852
- }
131853
- if (minTime === undefined) {
131854
- if (maxTime === undefined) {
131855
- minTime = '00:00:00.000Z';
131856
- maxTime = '23:59:59.999Z';
131857
- }
131858
- else {
131859
- minTime = '00:00:00.000Z';
131860
- }
131861
- }
131862
- if (maxTime === undefined) {
131863
- maxTime = '23:59:59.999Z';
131864
- new Date().toISOString();
131865
- }
131866
- const anchorDate = new Date('2024-05-08');
131867
- const anchorDateString0 = anchorDate.toISOString().replace(/T\d{2}:\d{2}:\d{2}.\d{3}Z/, '');
131868
- if (typeof minTime === 'string') {
131869
- // const timeMatch0 = minTime.match(/^\d{2}:\d{2}:\d{2}.\d{1,3}Z?$/);
131870
- const timeMatch1 = minTime.match(/^\d{2}:\d{2}:\d{2}Z?$/);
131871
- const timeMatch2 = minTime.match(/^\d{2}:\d{2}Z?$/);
131872
- if (
131873
- // timeMatch0 === null
131874
- timeMatch1 === null
131875
- && timeMatch2 === null) {
131876
- throw new Error(`You're using the wrong format for the minTime parameter.`
131877
- + `\nPlease use one of these formats: 'HH:mm:ss', 'HH:mm' (with or without a trailing 'Z')`);
131878
- }
131879
- minTime = minTime.at(-1) === 'Z' ? minTime : minTime + 'Z';
131880
- minTime = new Date(anchorDate.toISOString().replace(/\d{2}:\d{2}:\d{2}.\d{3}Z/, minTime));
131881
- }
131882
- if (typeof minTime === 'object') {
131883
- if (!isValidDate(minTime)) {
131884
- throw new Error('Invalid Date was provided for the minTime parameter.');
131885
- }
131886
- minTime = new Date(minTime.toISOString().replace(/\d{4}-\d{2}-\d{2}/, anchorDateString0));
131887
- }
131888
- if (typeof maxTime === 'string') {
131889
- // const timeMatch0 = maxTime.match(/^\d{2}:\d{2}:\d{2}.\d{1,3}Z?$/);
131890
- const timeMatch1 = maxTime.match(/^\d{2}:\d{2}:\d{2}Z?$/);
131891
- const timeMatch2 = maxTime.match(/^\d{2}:\d{2}Z?$/);
131892
- if (
131893
- // timeMatch0 === null
131894
- timeMatch1 === null
131895
- && timeMatch2 === null) {
131896
- throw new Error(`You're using the wrong format for the maxTime parameter.`
131897
- + `\nPlease use one of these formats: 'HH:mm:ss', 'HH:mm' (with or without a trailing 'Z').`);
131898
- }
131899
- maxTime = maxTime.at(-1) === 'Z' ? maxTime : maxTime + 'Z';
131900
- maxTime = new Date(anchorDate.toISOString().replace(/\d{2}:\d{2}:\d{2}.\d{3}Z/, maxTime));
131901
- }
131902
- if (typeof maxTime === 'object') {
131903
- if (!isValidDate(maxTime)) {
131904
- throw new Error('Invalid Date was provided for the maxTime parameter.');
131905
- }
131906
- maxTime = new Date(maxTime.toISOString().replace(/\d{4}-\d{2}-\d{2}/, anchorDateString0));
131907
- }
131908
- if (minTime > maxTime) {
131909
- throw new Error(`The minTime parameter must be less than or equal to the maxTime parameter.`);
131910
- }
131911
- this.state = { rng, minTime, maxTime };
132065
+ this.state = { rng };
131912
132066
  }
131913
132067
  generate() {
131914
132068
  if (this.state === undefined) {
131915
132069
  throw new Error('state is not defined.');
131916
132070
  }
132071
+ const anchorDateTime = new Date('2024-05-08T12:00:00.000Z');
132072
+ const oneDayInMilliseconds = 86400000;
132073
+ let date = new Date();
131917
132074
  let milliseconds;
131918
- [milliseconds, this.state.rng] = prand.uniformIntDistribution(this.state.minTime.getTime(), this.state.maxTime.getTime(), this.state.rng);
131919
- const date = new Date(milliseconds);
132075
+ [milliseconds, this.state.rng] = prand.uniformIntDistribution(-oneDayInMilliseconds, oneDayInMilliseconds, this.state.rng);
132076
+ date = new Date(date.setTime(anchorDateTime.getTime() + milliseconds));
131920
132077
  return date.toISOString().replace(/(\d{4}-\d{2}-\d{2}T)|(\.\d{3}Z)/g, '');
131921
132078
  }
131922
132079
  }
@@ -131926,46 +132083,18 @@ class GenerateTimestamp extends AbstractGenerator {
131926
132083
  init({ count, seed }) {
131927
132084
  super.init({ count, seed });
131928
132085
  const rng = prand.xoroshiro128plus(seed);
131929
- let { minTimestamp, maxTimestamp } = this.params;
131930
- const anchorDate = new Date('2024-05-08');
131931
- // 2 years in milliseconds
131932
- const deltaMilliseconds = 2 * 31536000000;
131933
- if (typeof minTimestamp === 'string') {
131934
- minTimestamp = new Date(minTimestamp);
131935
- }
131936
- if (typeof minTimestamp === 'object' && !isValidDate(minTimestamp)) {
131937
- throw new Error('Invalid Date was provided for the minTimestamp parameter.');
131938
- }
131939
- if (typeof maxTimestamp === 'string') {
131940
- maxTimestamp = new Date(maxTimestamp);
131941
- }
131942
- if (typeof maxTimestamp === 'object' && !isValidDate(maxTimestamp)) {
131943
- throw new Error('Invalid Date was provided for the maxTimestamp parameter.');
131944
- }
131945
- if (minTimestamp === undefined) {
131946
- if (maxTimestamp === undefined) {
131947
- minTimestamp = new Date(anchorDate.getTime() - deltaMilliseconds);
131948
- maxTimestamp = new Date(anchorDate.getTime() + deltaMilliseconds);
131949
- }
131950
- else {
131951
- minTimestamp = new Date(maxTimestamp.getTime() - (2 * deltaMilliseconds));
131952
- }
131953
- }
131954
- if (maxTimestamp === undefined) {
131955
- maxTimestamp = new Date(minTimestamp.getTime() + (2 * deltaMilliseconds));
131956
- }
131957
- if (minTimestamp > maxTimestamp) {
131958
- throw new Error(`The minTimestamp parameter must be less than or equal to the maxTimestamp parameter.`);
131959
- }
131960
- this.state = { rng, minTimestamp, maxTimestamp };
132086
+ this.state = { rng };
131961
132087
  }
131962
132088
  generate() {
131963
132089
  if (this.state === undefined) {
131964
132090
  throw new Error('state is not defined.');
131965
132091
  }
132092
+ const anchorTimestamp = new Date('2024-05-08');
132093
+ const twoYearsInMilliseconds = 2 * 31536000000;
132094
+ let date = new Date();
131966
132095
  let milliseconds;
131967
- [milliseconds, this.state.rng] = prand.uniformIntDistribution(this.state.minTimestamp.getTime(), this.state.maxTimestamp.getTime(), this.state.rng);
131968
- const date = new Date(milliseconds);
132096
+ [milliseconds, this.state.rng] = prand.uniformIntDistribution(-twoYearsInMilliseconds, twoYearsInMilliseconds, this.state.rng);
132097
+ date = new Date(date.setTime(anchorTimestamp.getTime() + milliseconds));
131969
132098
  if (this.dataType === 'string') {
131970
132099
  return date
131971
132100
  .toISOString()
@@ -131981,46 +132110,18 @@ class GenerateDatetime extends AbstractGenerator {
131981
132110
  init({ count, seed }) {
131982
132111
  super.init({ count, seed });
131983
132112
  const rng = prand.xoroshiro128plus(seed);
131984
- let { minDatetime, maxDatetime } = this.params;
131985
- const anchorDate = new Date('2024-05-08');
131986
- // 2 years in milliseconds
131987
- const deltaMilliseconds = 2 * 31536000000;
131988
- if (typeof minDatetime === 'string') {
131989
- minDatetime = new Date(minDatetime);
131990
- }
131991
- if (typeof minDatetime === 'object' && !isValidDate(minDatetime)) {
131992
- throw new Error('Invalid Date was provided for the minDatetime parameter.');
131993
- }
131994
- if (typeof maxDatetime === 'string') {
131995
- maxDatetime = new Date(maxDatetime);
131996
- }
131997
- if (typeof maxDatetime === 'object' && !isValidDate(maxDatetime)) {
131998
- throw new Error('Invalid Date was provided for the maxDatetime parameter.');
131999
- }
132000
- if (minDatetime === undefined) {
132001
- if (maxDatetime === undefined) {
132002
- minDatetime = new Date(anchorDate.getTime() - deltaMilliseconds);
132003
- maxDatetime = new Date(anchorDate.getTime() + deltaMilliseconds);
132004
- }
132005
- else {
132006
- minDatetime = new Date(maxDatetime.getTime() - (2 * deltaMilliseconds));
132007
- }
132008
- }
132009
- if (maxDatetime === undefined) {
132010
- maxDatetime = new Date(minDatetime.getTime() + (2 * deltaMilliseconds));
132011
- }
132012
- if (minDatetime > maxDatetime) {
132013
- throw new Error(`The minDatetime parameter must be less than or equal to the maxDatetime parameter.`);
132014
- }
132015
- this.state = { rng, minDatetime, maxDatetime };
132113
+ this.state = { rng };
132016
132114
  }
132017
132115
  generate() {
132018
132116
  if (this.state === undefined) {
132019
132117
  throw new Error('state is not defined.');
132020
132118
  }
132119
+ const anchorDate = new Date('2024-05-08');
132120
+ const twoYearsInMilliseconds = 2 * 31536000000;
132121
+ let date = new Date();
132021
132122
  let milliseconds;
132022
- [milliseconds, this.state.rng] = prand.uniformIntDistribution(this.state.minDatetime.getTime(), this.state.maxDatetime.getTime(), this.state.rng);
132023
- const date = new Date(milliseconds);
132123
+ [milliseconds, this.state.rng] = prand.uniformIntDistribution(-twoYearsInMilliseconds, twoYearsInMilliseconds, this.state.rng);
132124
+ date = new Date(date.setTime(anchorDate.getTime() + milliseconds));
132024
132125
  if (this.dataType === 'string') {
132025
132126
  return date
132026
132127
  .toISOString()
@@ -132306,6 +132407,8 @@ class GenerateString extends AbstractGenerator {
132306
132407
  [idx, this.state.rng] = prand.uniformIntDistribution(0, stringChars.length - 1, this.state.rng);
132307
132408
  currStr += stringChars[idx];
132308
132409
  }
132410
+ if (this.dataType === 'object')
132411
+ return Buffer.from(currStr);
132309
132412
  return currStr;
132310
132413
  }
132311
132414
  }
@@ -132334,7 +132437,10 @@ class GenerateUniqueString extends AbstractGenerator {
132334
132437
  [idx, this.state.rng] = prand.uniformIntDistribution(0, stringChars.length - 1, this.state.rng);
132335
132438
  currStr += stringChars[idx];
132336
132439
  }
132337
- return currStr.slice(0, 4) + uniqueStr + currStr.slice(4);
132440
+ currStr = currStr.slice(0, 4) + uniqueStr + currStr.slice(4);
132441
+ if (this.dataType === 'object')
132442
+ return Buffer.from(currStr);
132443
+ return currStr;
132338
132444
  }
132339
132445
  }
132340
132446
  class GenerateUUID extends AbstractGenerator {
@@ -132376,8 +132482,8 @@ class GenerateFirstName extends AbstractGenerator {
132376
132482
  init({ count, seed }) {
132377
132483
  super.init({ count, seed });
132378
132484
  const rng = prand.xoroshiro128plus(seed);
132379
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$5) {
132380
- throw new Error(`You can't use first name generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$5}.`);
132485
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$5) {
132486
+ throw new Error(`You can't use first name generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$5}.`);
132381
132487
  }
132382
132488
  this.state = { rng };
132383
132489
  }
@@ -132400,8 +132506,8 @@ class GenerateUniqueFirstName extends AbstractGenerator {
132400
132506
  if (count > firstNames.length) {
132401
132507
  throw new Error('count exceeds max number of unique first names.');
132402
132508
  }
132403
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$5) {
132404
- throw new Error(`You can't use first name generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$5}.`);
132509
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$5) {
132510
+ throw new Error(`You can't use first name generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$5}.`);
132405
132511
  }
132406
132512
  const genIndicesObj = new GenerateUniqueInt({ minValue: 0, maxValue: firstNames.length - 1 });
132407
132513
  genIndicesObj.init({ count, seed });
@@ -132424,8 +132530,8 @@ class GenerateLastName extends AbstractGenerator {
132424
132530
  init({ count, seed }) {
132425
132531
  super.init({ count, seed });
132426
132532
  const rng = prand.xoroshiro128plus(seed);
132427
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$3) {
132428
- throw new Error(`You can't use last name generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$3}.`);
132533
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$3) {
132534
+ throw new Error(`You can't use last name generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$3}.`);
132429
132535
  }
132430
132536
  this.state = { rng };
132431
132537
  }
@@ -132446,8 +132552,8 @@ class GenerateUniqueLastName extends AbstractGenerator {
132446
132552
  if (count > lastNames.length) {
132447
132553
  throw new Error('count exceeds max number of unique last names.');
132448
132554
  }
132449
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$3) {
132450
- throw new Error(`You can't use last name generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$3}.`);
132555
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$3) {
132556
+ throw new Error(`You can't use last name generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$3}.`);
132451
132557
  }
132452
132558
  const genIndicesObj = new GenerateUniqueInt({ minValue: 0, maxValue: lastNames.length - 1 });
132453
132559
  genIndicesObj.init({ count, seed });
@@ -132469,8 +132575,8 @@ class GenerateFullName extends AbstractGenerator {
132469
132575
  init({ count, seed }) {
132470
132576
  super.init({ count, seed });
132471
132577
  const rng = prand.xoroshiro128plus(seed);
132472
- if (this.stringLength !== undefined && this.stringLength < (maxStringLength$5 + maxStringLength$3 + 1)) {
132473
- throw new Error(`You can't use full name generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$5 + maxStringLength$3 + 1}.`);
132578
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < (maxStringLength$5 + maxStringLength$3 + 1)) {
132579
+ throw new Error(`You can't use full name generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$5 + maxStringLength$3 + 1}.`);
132474
132580
  }
132475
132581
  this.state = { rng };
132476
132582
  }
@@ -132498,8 +132604,8 @@ class GenerateUniqueFullName extends AbstractGenerator {
132498
132604
  if (count > maxUniqueFullNamesNumber) {
132499
132605
  throw new RangeError(`count exceeds max number of unique full names(${maxUniqueFullNamesNumber}).`);
132500
132606
  }
132501
- if (this.stringLength !== undefined && this.stringLength < (maxStringLength$5 + maxStringLength$3 + 1)) {
132502
- throw new Error(`You can't use full name generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$5 + maxStringLength$3 + 1}.`);
132607
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < (maxStringLength$5 + maxStringLength$3 + 1)) {
132608
+ throw new Error(`You can't use full name generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$5 + maxStringLength$3 + 1}.`);
132503
132609
  }
132504
132610
  const rng = prand.xoroshiro128plus(seed);
132505
132611
  const fullnameSet = new Set();
@@ -132542,8 +132648,8 @@ class GenerateEmail extends AbstractGenerator {
132542
132648
  throw new RangeError(`count exceeds max number of unique emails(${maxUniqueEmailsNumber}).`);
132543
132649
  }
132544
132650
  const maxEmailLength = maxStringLength$a + maxStringLength$5 + maxStringLength$6 + 2;
132545
- if (this.stringLength !== undefined && this.stringLength < maxEmailLength) {
132546
- throw new Error(`You can't use email generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxEmailLength}.`);
132651
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxEmailLength) {
132652
+ throw new Error(`You can't use email generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxEmailLength}.`);
132547
132653
  }
132548
132654
  const arraysToGenerateFrom = [adjectivesArray, namesArray, domainsArray];
132549
132655
  const genIndicesObj = new GenerateUniqueInt({
@@ -132576,8 +132682,8 @@ class GeneratePhoneNumber extends AbstractGenerator {
132576
132682
  const { prefixes, template } = this.params;
132577
132683
  const rng = prand.xoroshiro128plus(seed);
132578
132684
  if (template !== undefined) {
132579
- if (this.stringLength !== undefined && this.stringLength < template.length) {
132580
- throw new Error(`Length of phone number template is shorter than db column length restriction: ${this.stringLength}.
132685
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < template.length) {
132686
+ throw new Error(`Length of phone number template is shorter than db column length restriction: ${this.typeParams?.length}.
132581
132687
  Set the maximum string length to at least ${template.length}.`);
132582
132688
  }
132583
132689
  const iterArray = [...template.matchAll(/#/g)];
@@ -132622,8 +132728,8 @@ class GeneratePhoneNumber extends AbstractGenerator {
132622
132728
  }
132623
132729
  const maxPrefixLength = Math.max(...prefixesArray.map((prefix) => prefix.length));
132624
132730
  const maxGeneratedDigits = Math.max(...generatedDigitsNumbers);
132625
- if (this.stringLength !== undefined && this.stringLength < (maxPrefixLength + maxGeneratedDigits)) {
132626
- throw new Error(`You can't use phone number generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxPrefixLength + maxGeneratedDigits}.`);
132731
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < (maxPrefixLength + maxGeneratedDigits)) {
132732
+ throw new Error(`You can't use phone number generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxPrefixLength + maxGeneratedDigits}.`);
132627
132733
  }
132628
132734
  if (new Set(prefixesArray).size !== prefixesArray.length) {
132629
132735
  throw new Error('prefixes are not unique.');
@@ -132700,8 +132806,8 @@ class GenerateCountry extends AbstractGenerator {
132700
132806
  init({ count, seed }) {
132701
132807
  super.init({ count, seed });
132702
132808
  const rng = prand.xoroshiro128plus(seed);
132703
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$7) {
132704
- throw new Error(`You can't use country generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$7}.`);
132809
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$7) {
132810
+ throw new Error(`You can't use country generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$7}.`);
132705
132811
  }
132706
132812
  this.state = { rng };
132707
132813
  }
@@ -132723,8 +132829,8 @@ class GenerateUniqueCountry extends AbstractGenerator {
132723
132829
  if (count > countries.length) {
132724
132830
  throw new Error('count exceeds max number of unique countries.');
132725
132831
  }
132726
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$7) {
132727
- throw new Error(`You can't use country generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$7}.`);
132832
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$7) {
132833
+ throw new Error(`You can't use country generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$7}.`);
132728
132834
  }
132729
132835
  const genIndicesObj = new GenerateUniqueInt({ minValue: 0, maxValue: countries.length - 1 });
132730
132836
  genIndicesObj.init({ count, seed });
@@ -132745,8 +132851,8 @@ class GenerateJobTitle extends AbstractGenerator {
132745
132851
  init({ count, seed }) {
132746
132852
  super.init({ count, seed });
132747
132853
  const rng = prand.xoroshiro128plus(seed);
132748
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$4) {
132749
- throw new Error(`You can't use job title generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$4}.`);
132854
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$4) {
132855
+ throw new Error(`You can't use job title generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$4}.`);
132750
132856
  }
132751
132857
  this.state = { rng };
132752
132858
  }
@@ -132768,8 +132874,8 @@ class GenerateStreetAddress extends AbstractGenerator {
132768
132874
  const rng = prand.xoroshiro128plus(seed);
132769
132875
  const possStreetNames = [firstNames, lastNames];
132770
132876
  const maxStreetAddressLength = 4 + Math.max(maxStringLength$5, maxStringLength$3) + 1 + maxStringLength;
132771
- if (this.stringLength !== undefined && this.stringLength < maxStreetAddressLength) {
132772
- throw new Error(`You can't use street address generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStreetAddressLength}.`);
132877
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStreetAddressLength) {
132878
+ throw new Error(`You can't use street address generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStreetAddressLength}.`);
132773
132879
  }
132774
132880
  this.state = { rng, possStreetNames };
132775
132881
  }
@@ -132798,8 +132904,8 @@ class GenerateUniqueStreetAddress extends AbstractGenerator {
132798
132904
  throw new RangeError(`count exceeds max number of unique street names(${maxUniqueStreetnamesNumber}).`);
132799
132905
  }
132800
132906
  const maxStreetAddressLength = 4 + Math.max(maxStringLength$5, maxStringLength$3) + 1 + maxStringLength;
132801
- if (this.stringLength !== undefined && this.stringLength < maxStreetAddressLength) {
132802
- throw new Error(`You can't use street address generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStreetAddressLength}.`);
132907
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStreetAddressLength) {
132908
+ throw new Error(`You can't use street address generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStreetAddressLength}.`);
132803
132909
  }
132804
132910
  const rng = prand.xoroshiro128plus(seed);
132805
132911
  // ["1", "2", ..., "999"]
@@ -132855,8 +132961,8 @@ class GenerateCity extends AbstractGenerator {
132855
132961
  init({ count, seed }) {
132856
132962
  super.init({ count, seed });
132857
132963
  const rng = prand.xoroshiro128plus(seed);
132858
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$9) {
132859
- throw new Error(`You can't use city generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$9}.`);
132964
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$9) {
132965
+ throw new Error(`You can't use city generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$9}.`);
132860
132966
  }
132861
132967
  this.state = { rng };
132862
132968
  }
@@ -132877,8 +132983,8 @@ class GenerateUniqueCity extends AbstractGenerator {
132877
132983
  if (count > cityNames.length) {
132878
132984
  throw new Error('count exceeds max number of unique cities.');
132879
132985
  }
132880
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$9) {
132881
- throw new Error(`You can't use city generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$9}.`);
132986
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$9) {
132987
+ throw new Error(`You can't use city generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$9}.`);
132882
132988
  }
132883
132989
  const genIndicesObj = new GenerateUniqueInt({ minValue: 0, maxValue: cityNames.length - 1 });
132884
132990
  genIndicesObj.init({ count, seed });
@@ -132902,8 +133008,8 @@ class GeneratePostcode extends AbstractGenerator {
132902
133008
  const rng = prand.xoroshiro128plus(seed);
132903
133009
  const templates = ['#####', '#####-####'];
132904
133010
  const maxPostcodeLength = Math.max(...templates.map((template) => template.length));
132905
- if (this.stringLength !== undefined && this.stringLength < maxPostcodeLength) {
132906
- throw new Error(`You can't use postcode generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxPostcodeLength}.`);
133011
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxPostcodeLength) {
133012
+ throw new Error(`You can't use postcode generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxPostcodeLength}.`);
132907
133013
  }
132908
133014
  this.state = { rng, templates };
132909
133015
  }
@@ -132953,8 +133059,8 @@ class GenerateUniquePostcode extends AbstractGenerator {
132953
133059
  },
132954
133060
  ];
132955
133061
  const maxPostcodeLength = Math.max(...templates.map((template) => template.template.length));
132956
- if (this.stringLength !== undefined && this.stringLength < maxPostcodeLength) {
132957
- throw new Error(`You can't use postcode generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxPostcodeLength}.`);
133062
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxPostcodeLength) {
133063
+ throw new Error(`You can't use postcode generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxPostcodeLength}.`);
132958
133064
  }
132959
133065
  for (const templateObj of templates) {
132960
133066
  templateObj.indicesGen.skipCheck = true;
@@ -132990,8 +133096,8 @@ class GenerateState extends AbstractGenerator {
132990
133096
  init({ count, seed }) {
132991
133097
  super.init({ count, seed });
132992
133098
  const rng = prand.xoroshiro128plus(seed);
132993
- if (this.stringLength !== undefined && this.stringLength < maxStringLength$1) {
132994
- throw new Error(`You can't use state generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxStringLength$1}.`);
133099
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$1) {
133100
+ throw new Error(`You can't use state generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$1}.`);
132995
133101
  }
132996
133102
  this.state = { rng };
132997
133103
  }
@@ -133019,8 +133125,8 @@ class GenerateCompanyName extends AbstractGenerator {
133019
133125
  ];
133020
133126
  // max( { template: '#', placeholdersCount: 1 }, { template: '#, # and #', placeholdersCount: 3 } )
133021
133127
  const maxCompanyNameLength = Math.max(maxStringLength$3 + maxStringLength$8 + 1, 3 * maxStringLength$3 + 7);
133022
- if (this.stringLength !== undefined && this.stringLength < maxCompanyNameLength) {
133023
- throw new Error(`You can't use company name generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxCompanyNameLength}.`);
133128
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxCompanyNameLength) {
133129
+ throw new Error(`You can't use company name generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxCompanyNameLength}.`);
133024
133130
  }
133025
133131
  this.state = { rng, templates };
133026
133132
  }
@@ -133064,8 +133170,8 @@ class GenerateUniqueCompanyName extends AbstractGenerator {
133064
133170
  }
133065
133171
  // max( { template: '#', placeholdersCount: 1 }, { template: '#, # and #', placeholdersCount: 3 } )
133066
133172
  const maxCompanyNameLength = Math.max(maxStringLength$3 + maxStringLength$8 + 1, 3 * maxStringLength$3 + 7);
133067
- if (this.stringLength !== undefined && this.stringLength < maxCompanyNameLength) {
133068
- throw new Error(`You can't use company name generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxCompanyNameLength}.`);
133173
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxCompanyNameLength) {
133174
+ throw new Error(`You can't use company name generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxCompanyNameLength}.`);
133069
133175
  }
133070
133176
  const rng = prand.xoroshiro128plus(seed);
133071
133177
  // when count reach maxUniqueCompanyNameNumber template will be deleted from array
@@ -133141,8 +133247,8 @@ class GenerateLoremIpsum extends AbstractGenerator {
133141
133247
  this.params.sentencesCount = 1;
133142
133248
  const maxLoremIpsumSentencesLength = maxStringLength$2 * this.params.sentencesCount + this.params.sentencesCount
133143
133249
  - 1;
133144
- if (this.stringLength !== undefined && this.stringLength < maxLoremIpsumSentencesLength) {
133145
- throw new Error(`You can't use lorem ipsum generator with a db column length restriction of ${this.stringLength}. Set the maximum string length to at least ${maxLoremIpsumSentencesLength}.`);
133250
+ if (this.typeParams?.length !== undefined && this.typeParams?.length < maxLoremIpsumSentencesLength) {
133251
+ throw new Error(`You can't use lorem ipsum generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxLoremIpsumSentencesLength}.`);
133146
133252
  }
133147
133253
  this.state = { rng };
133148
133254
  }
@@ -133231,7 +133337,7 @@ class GeneratePoint extends AbstractGenerator {
133231
133337
  }
133232
133338
  const x = this.state.xCoordinateGen.generate();
133233
133339
  const y = this.state.yCoordinateGen.generate();
133234
- if (this.dataType === 'json') {
133340
+ if (this.dataType === 'object') {
133235
133341
  return { x, y };
133236
133342
  }
133237
133343
  else if (this.dataType === 'string') {
@@ -133248,6 +133354,7 @@ class GenerateUniquePoint extends AbstractGenerator {
133248
133354
  state;
133249
133355
  isUnique = true;
133250
133356
  init({ count, seed }) {
133357
+ // TODO: rewrite the unique generator to use fastCartesianProduct for generating unique points.
133251
133358
  const xCoordinateGen = new GenerateUniqueNumber({
133252
133359
  minValue: this.params.minXValue,
133253
133360
  maxValue: this.params.maxXValue,
@@ -133268,7 +133375,7 @@ class GenerateUniquePoint extends AbstractGenerator {
133268
133375
  }
133269
133376
  const x = this.state.xCoordinateGen.generate();
133270
133377
  const y = this.state.yCoordinateGen.generate();
133271
- if (this.dataType === 'json') {
133378
+ if (this.dataType === 'object') {
133272
133379
  return { x, y };
133273
133380
  }
133274
133381
  else if (this.dataType === 'string') {
@@ -133317,7 +133424,7 @@ class GenerateLine extends AbstractGenerator {
133317
133424
  b = this.state.bCoefficientGen.generate();
133318
133425
  }
133319
133426
  const c = this.state.cCoefficientGen.generate();
133320
- if (this.dataType === 'json') {
133427
+ if (this.dataType === 'object') {
133321
133428
  return { a, b, c };
133322
133429
  }
133323
133430
  else if (this.dataType === 'string') {
@@ -133334,6 +133441,7 @@ class GenerateUniqueLine extends AbstractGenerator {
133334
133441
  state;
133335
133442
  isUnique = true;
133336
133443
  init({ count, seed }) {
133444
+ // TODO: rewrite the unique generator to use fastCartesianProduct for generating unique triplets(liens).
133337
133445
  const aCoefficientGen = new GenerateUniqueNumber({
133338
133446
  minValue: this.params.minAValue,
133339
133447
  maxValue: this.params.maxAValue,
@@ -133365,7 +133473,7 @@ class GenerateUniqueLine extends AbstractGenerator {
133365
133473
  b = this.state.bCoefficientGen.generate();
133366
133474
  }
133367
133475
  const c = this.state.cCoefficientGen.generate();
133368
- if (this.dataType === 'json') {
133476
+ if (this.dataType === 'object') {
133369
133477
  return { a, b, c };
133370
133478
  }
133371
133479
  else if (this.dataType === 'string') {
@@ -133377,6 +133485,397 @@ class GenerateUniqueLine extends AbstractGenerator {
133377
133485
  }
133378
133486
  }
133379
133487
  }
133488
+ class GenerateBitString extends AbstractGenerator {
133489
+ static entityKind = 'GenerateBitString';
133490
+ dimensions = 11;
133491
+ state;
133492
+ uniqueVersionOfGen = GenerateUniqueBitString;
133493
+ init({ count, seed }) {
133494
+ super.init({ count, seed });
133495
+ this.dimensions = this.params.dimensions ?? this.typeParams?.length ?? this.dimensions;
133496
+ let intGen;
133497
+ if (this.dimensions > 53) {
133498
+ const maxValue = (BigInt(2) ** BigInt(this.dimensions)) - BigInt(1);
133499
+ intGen = new GenerateInt({ minValue: BigInt(0), maxValue });
133500
+ }
133501
+ else {
133502
+ // dimensions <= 53
133503
+ const maxValue = Math.pow(2, this.dimensions) - 1;
133504
+ intGen = new GenerateInt({ minValue: 0, maxValue });
133505
+ }
133506
+ intGen.init({ count, seed });
133507
+ this.state = { intGen };
133508
+ }
133509
+ generate() {
133510
+ if (this.state === undefined) {
133511
+ throw new Error('state is not defined.');
133512
+ }
133513
+ const bitString = this.state.intGen.generate().toString(2);
133514
+ return bitString.padStart(this.dimensions, '0');
133515
+ }
133516
+ }
133517
+ class GenerateUniqueBitString extends AbstractGenerator {
133518
+ static entityKind = 'GenerateUniqueBitString';
133519
+ dimensions = 11;
133520
+ state;
133521
+ isUnique = true;
133522
+ init({ count, seed }) {
133523
+ this.dimensions = this.params.dimensions ?? this.typeParams?.length ?? this.dimensions;
133524
+ let intGen;
133525
+ if (this.dimensions > 53) {
133526
+ const maxValue = (BigInt(2) ** BigInt(this.dimensions)) - BigInt(1);
133527
+ intGen = new GenerateUniqueInt({ minValue: BigInt(0), maxValue });
133528
+ }
133529
+ else {
133530
+ // dimensions <= 53
133531
+ const maxValue = Math.pow(2, this.dimensions) - 1;
133532
+ intGen = new GenerateUniqueInt({ minValue: 0, maxValue });
133533
+ }
133534
+ intGen.init({ count, seed });
133535
+ this.state = { intGen };
133536
+ }
133537
+ generate() {
133538
+ if (this.state === undefined) {
133539
+ throw new Error('state is not defined.');
133540
+ }
133541
+ const bitString = this.state.intGen.generate().toString(2);
133542
+ return bitString.padStart(this.dimensions, '0');
133543
+ }
133544
+ }
133545
+ class GenerateInet extends AbstractGenerator {
133546
+ static entityKind = 'GenerateInet';
133547
+ ipAddress = 'ipv4';
133548
+ includeCidr = true;
133549
+ state;
133550
+ uniqueVersionOfGen = GenerateUniqueInet;
133551
+ init({ count, seed }) {
133552
+ super.init({ count, seed });
133553
+ this.ipAddress = this.params.ipAddress ?? this.ipAddress;
133554
+ this.includeCidr = this.params.includeCidr ?? this.includeCidr;
133555
+ const rng = prand.xoroshiro128plus(seed);
133556
+ this.state = { rng };
133557
+ }
133558
+ generate() {
133559
+ if (this.state === undefined) {
133560
+ throw new Error('state is not defined.');
133561
+ }
133562
+ let value;
133563
+ const values = [];
133564
+ let inetVal = '';
133565
+ if (this.ipAddress === 'ipv4') {
133566
+ for (let octet = 0; octet < 4; octet++) {
133567
+ [value, this.state.rng] = prand.uniformIntDistribution(0, 255, this.state.rng);
133568
+ values.push(value.toString());
133569
+ }
133570
+ inetVal += values.join('.');
133571
+ if (this.includeCidr) {
133572
+ [value, this.state.rng] = prand.uniformIntDistribution(0, 32, this.state.rng);
133573
+ inetVal += `/${value}`;
133574
+ }
133575
+ return inetVal;
133576
+ }
133577
+ else {
133578
+ // this.ipAddress === 'ipv6'
133579
+ for (let hextet = 0; hextet < 8; hextet++) {
133580
+ [value, this.state.rng] = prand.uniformIntDistribution(0, 65535, this.state.rng);
133581
+ values.push(value.toString(16));
133582
+ }
133583
+ inetVal += values.join(':');
133584
+ if (this.includeCidr) {
133585
+ [value, this.state.rng] = prand.uniformIntDistribution(0, 128, this.state.rng);
133586
+ inetVal += `/${value}`;
133587
+ }
133588
+ return inetVal;
133589
+ }
133590
+ }
133591
+ }
133592
+ // TODO: add defaults to js doc
133593
+ class GenerateUniqueInet extends AbstractGenerator {
133594
+ static entityKind = 'GenerateUniqueInet';
133595
+ ipAddress = 'ipv4';
133596
+ includeCidr = true;
133597
+ delimiter = '.';
133598
+ state;
133599
+ isUnique = true;
133600
+ init({ count, seed }) {
133601
+ this.ipAddress = this.params.ipAddress ?? this.ipAddress;
133602
+ this.delimiter = this.ipAddress === 'ipv4' ? '.' : ':';
133603
+ this.includeCidr = this.params.includeCidr ?? this.includeCidr;
133604
+ // maxValue - number of combinations for cartesian product: {0…255} × {0…255} × {0…255} × {0…255} × {0…32}
133605
+ // where pattern for ipv4 ip is {0–255}.{0–255}.{0–255}.{0–255}[/{0–32}?]
133606
+ // 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}
133607
+ // where pattern for ipv6 ip is {0-65535}:{0-65535}:{0-65535}:{0-65535}:{0-65535}:{0-65535}:{0-65535}:{0-65535}[/0-128?]
133608
+ let minValue, maxValue;
133609
+ if (this.ipAddress === 'ipv4') {
133610
+ minValue = 0;
133611
+ maxValue = 256 ** 4;
133612
+ if (this.includeCidr) {
133613
+ maxValue = maxValue * 33;
133614
+ }
133615
+ }
133616
+ else {
133617
+ // this.ipAddress === 'ipv6'
133618
+ minValue = BigInt(0);
133619
+ maxValue = BigInt(65535) ** BigInt(8);
133620
+ if (this.includeCidr) {
133621
+ maxValue = maxValue * BigInt(129);
133622
+ }
133623
+ }
133624
+ const indexGen = new GenerateUniqueInt({ minValue, maxValue });
133625
+ indexGen.init({ count, seed });
133626
+ const octetSet = Array.from({ length: 256 }, (_, i) => i.toString());
133627
+ const ipv4PrefixSet = Array.from({ length: 33 }, (_, i) => i.toString());
133628
+ const hextetSet = Array.from({ length: 65536 }, (_, i) => i.toString(16));
133629
+ const ipv6PrefixSet = Array.from({ length: 129 }, (_, i) => i.toString());
133630
+ this.state = { indexGen, octetSet, ipv4PrefixSet, hextetSet, ipv6PrefixSet };
133631
+ }
133632
+ generate() {
133633
+ if (this.state === undefined) {
133634
+ throw new Error('state is not defined.');
133635
+ }
133636
+ let inetVal = '';
133637
+ let tokens = [];
133638
+ if (this.ipAddress === 'ipv4') {
133639
+ const sets = Array.from({ length: 4 }).fill(this.state.octetSet);
133640
+ if (this.includeCidr)
133641
+ sets.push(this.state.ipv4PrefixSet);
133642
+ const index = this.state.indexGen.generate();
133643
+ tokens = fastCartesianProduct(sets, index);
133644
+ }
133645
+ else {
133646
+ // this.ipAddress === 'ipv6'
133647
+ const sets = Array.from({ length: 8 }).fill(this.state.hextetSet);
133648
+ if (this.includeCidr)
133649
+ sets.push(this.state.ipv6PrefixSet);
133650
+ const idx = this.state.indexGen.generate();
133651
+ tokens = fastCartesianProductForBigint(sets, idx);
133652
+ }
133653
+ inetVal = this.includeCidr
133654
+ ? tokens.slice(0, -1).join(this.delimiter) + `/${tokens.at(-1)}`
133655
+ : tokens.join(this.delimiter);
133656
+ return inetVal;
133657
+ }
133658
+ }
133659
+ class GenerateGeometry extends AbstractGenerator {
133660
+ static entityKind = 'GenerateGeometry';
133661
+ type = 'point';
133662
+ srid = 4326;
133663
+ decimalPlaces = 6;
133664
+ state;
133665
+ uniqueVersionOfGen = GenerateUniqueGeometry;
133666
+ init({ count, seed }) {
133667
+ super.init({ count, seed });
133668
+ this.type = this.params.type ?? this.type;
133669
+ this.srid = this.params.srid ?? this.srid;
133670
+ this.decimalPlaces = this.params.decimalPlaces ?? this.decimalPlaces;
133671
+ let minXValue, maxXValue, minYValue, maxYValue, denominator;
133672
+ if (this.type === 'point') {
133673
+ if (this.srid === 4326) {
133674
+ // Degrees (latitude / longitude)
133675
+ denominator = 10 ** this.decimalPlaces;
133676
+ minXValue = -180 * denominator;
133677
+ maxXValue = 180 * denominator;
133678
+ minYValue = -90 * denominator;
133679
+ maxYValue = 90 * denominator;
133680
+ }
133681
+ else {
133682
+ // this.srid === 3857
133683
+ // Meters (projected X / Y)
133684
+ denominator = 1;
133685
+ minXValue = -20026376;
133686
+ maxXValue = 20026376;
133687
+ minYValue = -20048966;
133688
+ maxYValue = 20048966;
133689
+ }
133690
+ }
133691
+ else {
133692
+ throw new Error('geometry generator currently supports only the point type.');
133693
+ }
133694
+ const rng = prand.xoroshiro128plus(seed);
133695
+ this.state = { rng, minXValue, maxXValue, minYValue, maxYValue, denominator };
133696
+ }
133697
+ generate() {
133698
+ if (this.state === undefined) {
133699
+ throw new Error('state is not defined.');
133700
+ }
133701
+ let x, y;
133702
+ [x, this.state.rng] = prand.uniformIntDistribution(this.state.minXValue, this.state.maxXValue, this.state.rng);
133703
+ x = x / this.state.denominator;
133704
+ [y, this.state.rng] = prand.uniformIntDistribution(this.state.minYValue, this.state.maxYValue, this.state.rng);
133705
+ y = y / this.state.denominator;
133706
+ if (this.dataType === 'array') {
133707
+ return [x, y];
133708
+ }
133709
+ // this.dataType === 'object'
133710
+ return { x, y };
133711
+ }
133712
+ }
133713
+ class GenerateUniqueGeometry extends AbstractGenerator {
133714
+ static entityKind = 'GenerateUniqueGeometry';
133715
+ type = 'point';
133716
+ srid = 4326;
133717
+ decimalPlaces = 6;
133718
+ state;
133719
+ isUnique = true;
133720
+ init({ count, seed }) {
133721
+ this.type = this.params.type ?? this.type;
133722
+ this.srid = this.params.srid ?? this.srid;
133723
+ this.decimalPlaces = this.params.decimalPlaces ?? this.decimalPlaces;
133724
+ let minXValue, maxXValue, minYValue, maxYValue, denominator;
133725
+ if (this.type === 'point') {
133726
+ if (this.srid === 4326) {
133727
+ // Degrees (latitude / longitude)
133728
+ denominator = 10 ** this.decimalPlaces;
133729
+ minXValue = -180 * denominator;
133730
+ maxXValue = 180 * denominator;
133731
+ minYValue = -90 * denominator;
133732
+ maxYValue = 90 * denominator;
133733
+ }
133734
+ else {
133735
+ // this.srid === 3857
133736
+ // Meters (projected X / Y)
133737
+ denominator = 1;
133738
+ minXValue = -20026376;
133739
+ maxXValue = 20026376;
133740
+ minYValue = -20048966;
133741
+ maxYValue = 20048966;
133742
+ }
133743
+ }
133744
+ else {
133745
+ throw new Error('geometry generator currently supports only the point type.');
133746
+ }
133747
+ const xRange = new OrderedNumberRange(minXValue, maxXValue, 1);
133748
+ const yRange = new OrderedNumberRange(minYValue, maxYValue, 1);
133749
+ const xySets = [xRange, yRange];
133750
+ const maxCombIdx = BigInt(maxXValue - minXValue + 1) * BigInt(maxYValue - minYValue + 1) - BigInt(1);
133751
+ const indexGen = maxCombIdx <= 2 ** 53
133752
+ ? new GenerateUniqueInt({ minValue: 0, maxValue: Number(maxCombIdx) })
133753
+ : new GenerateUniqueInt({ minValue: BigInt(0), maxValue: maxCombIdx });
133754
+ indexGen.init({ count, seed });
133755
+ this.state = { denominator, indexGen, xySets };
133756
+ }
133757
+ generate() {
133758
+ if (this.state === undefined) {
133759
+ throw new Error('state is not defined.');
133760
+ }
133761
+ const idx = this.state.indexGen.generate();
133762
+ let x, y;
133763
+ if (typeof idx === 'number') {
133764
+ [x, y] = fastCartesianProduct(this.state.xySets, idx);
133765
+ }
133766
+ else {
133767
+ // typeof idx === 'bigint'
133768
+ [x, y] = fastCartesianProductForBigint(this.state.xySets, idx);
133769
+ }
133770
+ if (this.dataType === 'array') {
133771
+ return [x, y];
133772
+ }
133773
+ // this.dataType === 'object'
133774
+ return { x, y };
133775
+ }
133776
+ }
133777
+ class GenerateVector extends AbstractGenerator {
133778
+ static entityKind = 'GenerateVector';
133779
+ // property below should be overridden in init
133780
+ dimensions = 3;
133781
+ minValue = -1000;
133782
+ maxValue = 1000;
133783
+ decimalPlaces = 2;
133784
+ state;
133785
+ uniqueVersionOfGen = GenerateUniqueVector;
133786
+ init({ count, seed }) {
133787
+ super.init({ count, seed });
133788
+ this.dimensions = this.params.dimensions ?? this.typeParams.length ?? this.dimensions;
133789
+ this.decimalPlaces = this.params.decimalPlaces ?? this.decimalPlaces;
133790
+ this.minValue = this.params.minValue ?? this.minValue;
133791
+ this.maxValue = this.params.maxValue ?? this.maxValue;
133792
+ if (this.minValue > this.maxValue) {
133793
+ throw new Error(`minValue ( ${this.minValue} ) cannot be greater than maxValue ( ${this.maxValue} ).\n`
133794
+ + `Did you forget to pass both minValue and maxValue to the generator's properties?`);
133795
+ }
133796
+ if (this.decimalPlaces < 0) {
133797
+ throw new Error(`decimalPlaces value must be greater than or equal to zero.`);
133798
+ }
133799
+ if (abs(BigInt(this.minValue) * BigInt(10 ** this.decimalPlaces)) > Number.MAX_SAFE_INTEGER
133800
+ || abs(BigInt(this.maxValue) * BigInt(10 ** this.decimalPlaces)) > Number.MAX_SAFE_INTEGER) {
133801
+ console.warn(`vector generator: minValue or maxValue multiplied by 10^decimalPlaces exceeds Number.MAX_SAFE_INTEGER (2^53 -1).\n`
133802
+ + `This overflow may result in less accurate values being generated.`);
133803
+ }
133804
+ // `numberGen` is initialized in the `init` method of `GenerateArray`
133805
+ const numberGen = new GenerateNumber({
133806
+ minValue: this.minValue,
133807
+ maxValue: this.maxValue,
133808
+ precision: 10 ** this.decimalPlaces,
133809
+ });
133810
+ const vectorGen = new GenerateArray({ baseColumnGen: numberGen, size: this.dimensions });
133811
+ vectorGen.init({ count, seed });
133812
+ this.state = { vectorGen };
133813
+ }
133814
+ generate() {
133815
+ if (this.state === undefined) {
133816
+ throw new Error('state is not defined.');
133817
+ }
133818
+ const vectorVal = this.state.vectorGen.generate();
133819
+ return vectorVal;
133820
+ }
133821
+ }
133822
+ class GenerateUniqueVector extends AbstractGenerator {
133823
+ static entityKind = 'GenerateUniqueVector';
133824
+ // property below should be overridden in init
133825
+ dimensions = 3;
133826
+ minValue = -1000;
133827
+ maxValue = 1000;
133828
+ decimalPlaces = 2;
133829
+ state;
133830
+ isUnique = true;
133831
+ init({ count, seed }) {
133832
+ this.dimensions = this.params.dimensions ?? this.typeParams.length ?? this.dimensions;
133833
+ this.decimalPlaces = this.params.decimalPlaces ?? this.decimalPlaces;
133834
+ const denominator = 10 ** this.decimalPlaces;
133835
+ this.minValue = this.params.minValue ?? this.minValue;
133836
+ this.maxValue = this.params.maxValue ?? this.maxValue;
133837
+ if (this.minValue > this.maxValue) {
133838
+ throw new Error(`minValue ( ${this.minValue} ) cannot be greater than maxValue ( ${this.maxValue} ).\n`
133839
+ + `Did you forget to pass both minValue and maxValue to the generator's properties?`);
133840
+ }
133841
+ if (this.decimalPlaces < 0) {
133842
+ throw new Error(`decimalPlaces value must be greater than or equal to zero.`);
133843
+ }
133844
+ if (abs(BigInt(this.minValue) * BigInt(denominator)) > Number.MAX_SAFE_INTEGER
133845
+ || abs(BigInt(this.maxValue) * BigInt(denominator)) > Number.MAX_SAFE_INTEGER) {
133846
+ console.warn(`vector generator: minValue or maxValue multiplied by 10^decimalPlaces exceeds Number.MAX_SAFE_INTEGER (2^53 -1).\n`
133847
+ + `This overflow may result in less accurate values being generated.`);
133848
+ }
133849
+ const dimensionRange = new OrderedNumberRange(this.minValue * denominator, this.maxValue * denominator, 1);
133850
+ const vectorSets = Array.from({ length: this.dimensions }).fill(dimensionRange);
133851
+ const maxCombIdx = vectorSets.reduce((acc, curr) => acc * BigInt(curr.length), BigInt(1)) - BigInt(1);
133852
+ const indexGen = maxCombIdx <= Number.MAX_SAFE_INTEGER
133853
+ ? new GenerateUniqueInt({ minValue: 0, maxValue: Number(maxCombIdx) })
133854
+ : new GenerateUniqueInt({ minValue: BigInt(0), maxValue: maxCombIdx });
133855
+ indexGen.init({ count, seed });
133856
+ const transformVector = denominator === 1
133857
+ ? (_vector, _denominator) => { }
133858
+ : (vector, denominator) => {
133859
+ for (let i = 0; i < vector.length; i++) {
133860
+ vector[i] = vector[i] / denominator;
133861
+ }
133862
+ return;
133863
+ };
133864
+ this.state = { indexGen, vectorSets, denominator, transformVector };
133865
+ }
133866
+ generate() {
133867
+ if (this.state === undefined) {
133868
+ throw new Error('state is not defined.');
133869
+ }
133870
+ const idx = this.state.indexGen.generate();
133871
+ const vector = typeof idx === 'number'
133872
+ ? fastCartesianProduct(this.state.vectorSets, idx)
133873
+ // typeof idx === 'bigint'
133874
+ : fastCartesianProductForBigint(this.state.vectorSets, idx);
133875
+ this.state.transformVector(vector, this.state.denominator);
133876
+ return vector;
133877
+ }
133878
+ }
133380
133879
 
133381
133880
  /* eslint-disable drizzle-internal/require-entity-kind */
133382
133881
  class GenerateUniqueIntervalV2 extends AbstractGenerator {
@@ -133463,8 +133962,8 @@ class GenerateStringV2 extends AbstractGenerator {
133463
133962
  super.init({ count, seed });
133464
133963
  let minStringLength = 7;
133465
133964
  let maxStringLength = 20;
133466
- if (this.stringLength !== undefined) {
133467
- maxStringLength = this.stringLength;
133965
+ if (this.typeParams?.length !== undefined) {
133966
+ maxStringLength = this.typeParams?.length;
133468
133967
  if (maxStringLength === 1)
133469
133968
  minStringLength = maxStringLength;
133470
133969
  if (maxStringLength < minStringLength)
@@ -133486,6 +133985,8 @@ class GenerateStringV2 extends AbstractGenerator {
133486
133985
  [idx, this.state.rng] = prand.uniformIntDistribution(0, stringChars.length - 1, this.state.rng);
133487
133986
  currStr += stringChars[idx];
133488
133987
  }
133988
+ if (this.dataType === 'object')
133989
+ return Buffer.from(currStr);
133489
133990
  return currStr;
133490
133991
  }
133491
133992
  }
@@ -133499,8 +134000,8 @@ class GenerateUniqueStringV2 extends AbstractGenerator {
133499
134000
  let minStringLength = 7;
133500
134001
  let maxStringLength = 20;
133501
134002
  // TODO: revise later
133502
- if (this.stringLength !== undefined) {
133503
- maxStringLength = this.stringLength;
134003
+ if (this.typeParams?.length !== undefined) {
134004
+ maxStringLength = this.typeParams?.length;
133504
134005
  if (maxStringLength === 1 || maxStringLength < minStringLength)
133505
134006
  minStringLength = maxStringLength;
133506
134007
  }
@@ -133524,6 +134025,8 @@ class GenerateUniqueStringV2 extends AbstractGenerator {
133524
134025
  [idx, this.state.rng] = prand.uniformIntDistribution(0, stringChars.length - 1, this.state.rng);
133525
134026
  currStr += stringChars[idx];
133526
134027
  }
134028
+ if (this.dataType === 'object')
134029
+ return Buffer.from(uniqueStr + currStr);
133527
134030
  return uniqueStr + currStr;
133528
134031
  }
133529
134032
  }
@@ -133693,8 +134196,6 @@ const generatorsFuncs = {
133693
134196
  date: createGenerator(GenerateDate),
133694
134197
  /**
133695
134198
  * generates time in 24 hours style.
133696
- * @param minTime - lower border of range.
133697
- * @param maxTime - upper border of range.
133698
134199
  * @param arraySize - number of elements in each one-dimensional array. (If specified, arrays will be generated.)
133699
134200
  *
133700
134201
  * @example
@@ -133702,7 +134203,7 @@ const generatorsFuncs = {
133702
134203
  * await seed(db, schema, { count: 1000 }).refine((funcs) => ({
133703
134204
  * users: {
133704
134205
  * columns: {
133705
- * birthTime: funcs.time({ minTime: "11:12:13.141", maxTime: "15:16:17.181" })
134206
+ * birthTime: funcs.time()
133706
134207
  * },
133707
134208
  * },
133708
134209
  * }));
@@ -133712,8 +134213,6 @@ const generatorsFuncs = {
133712
134213
  time: createGenerator(GenerateTime),
133713
134214
  /**
133714
134215
  * generates timestamps.
133715
- * @param minTimestamp - lower border of range.
133716
- * @param maxTimestamp - upper border of range.
133717
134216
  * @param arraySize - number of elements in each one-dimensional array. (If specified, arrays will be generated.)
133718
134217
  *
133719
134218
  * @example
@@ -133721,7 +134220,7 @@ const generatorsFuncs = {
133721
134220
  * await seed(db, schema, { count: 1000 }).refine((funcs) => ({
133722
134221
  * orders: {
133723
134222
  * columns: {
133724
- * shippedDate: funcs.timestamp({ minTimestamp: "2025-03-07T11:12:13.141", maxTimestamp: "2025-03-08T15:16:17.181" })
134223
+ * shippedDate: funcs.timestamp()
133725
134224
  * },
133726
134225
  * },
133727
134226
  * }));
@@ -133731,8 +134230,6 @@ const generatorsFuncs = {
133731
134230
  timestamp: createGenerator(GenerateTimestamp),
133732
134231
  /**
133733
134232
  * generates datetime objects.
133734
- * @param minDatetime - lower border of range.
133735
- * @param maxDatetime - upper border of range.
133736
134233
  * @param arraySize - number of elements in each one-dimensional array. (If specified, arrays will be generated.)
133737
134234
  *
133738
134235
  * @example
@@ -133740,7 +134237,7 @@ const generatorsFuncs = {
133740
134237
  * await seed(db, schema, { count: 1000 }).refine((funcs) => ({
133741
134238
  * orders: {
133742
134239
  * columns: {
133743
- * shippedDate: funcs.datetime({ minDatetime: "2025-03-07T11:12:13.141", maxDatetime: "2025-03-08T15:16:17.181" })
134240
+ * shippedDate: funcs.datetime()
133744
134241
  * },
133745
134242
  * },
133746
134243
  * }));
@@ -134200,8 +134697,132 @@ const generatorsFuncs = {
134200
134697
  * ```
134201
134698
  */
134202
134699
  weightedRandom: createGenerator(WeightedRandomGenerator),
134700
+ /**
134701
+ * generates bit strings based on specified parameters
134702
+ *
134703
+ * @param isUnique - property that controls if generated values gonna be unique or not.
134704
+ * @param arraySize - number of elements in each one-dimensional array (If specified, arrays will be generated).
134705
+ * @param dimensions - desired length of each bit string (e.g., `dimensions = 3` produces values like `'010'`).
134706
+ *
134707
+ * Defaults to the value of the database column bit-length.
134708
+ *
134709
+ * @example
134710
+ * ```ts
134711
+ * await seed(db, { bitStringTable: schema.bitStringTable }).refine((funcs) => ({
134712
+ * bitStringTable: {
134713
+ * count,
134714
+ * columns: {
134715
+ * bit: funcs.bitString({
134716
+ * dimensions: 12,
134717
+ * isUnique: true
134718
+ * }),
134719
+ * },
134720
+ * },
134721
+ * }));
134722
+ * ```
134723
+ */
134724
+ bitString: createGenerator(GenerateBitString),
134725
+ /**
134726
+ * generates ip addresses based on specified parameters
134727
+ *
134728
+ * @param isUnique - property that controls if generated values gonna be unique or not.
134729
+ * @param arraySize - number of elements in each one-dimensional array (If specified, arrays will be generated).
134730
+ * @param ipAddress - type of IP address to generate — either "ipv4" or "ipv6".
134731
+ *
134732
+ * Defaults to `'ipv4'`.
134733
+ * @param includeCidr - determines whether generated IPs include a CIDR suffix.
134734
+ *
134735
+ * Defaults to `true`.
134736
+ *
134737
+ * @example
134738
+ * ```ts
134739
+ * await seed(db, { inetTable: schema.inetTable }).refine((funcs) => ({
134740
+ * inetTable: {
134741
+ * count,
134742
+ * columns: {
134743
+ * inet: funcs.inet({
134744
+ * ipAddress: 'ipv4',
134745
+ * includeCidr: true,
134746
+ * isUnique: true
134747
+ * }),
134748
+ * },
134749
+ * },
134750
+ * }));
134751
+ * ```
134752
+ */
134753
+ inet: createGenerator(GenerateInet),
134754
+ /**
134755
+ * generates PostGIS geometry objects based on the given parameters.
134756
+ *
134757
+ * @param isUnique - property that controls if generated values gonna be unique or not.
134758
+ * @param arraySize - number of elements in each one-dimensional array (If specified, arrays will be generated).
134759
+ * @param type - geometry type to generate; currently only `'point'` is supported.
134760
+ *
134761
+ * Defaults to `'point'`.
134762
+ * @param srid - Spatial Reference System Identifier: determines what type of point will be generated - either `4326` or `3857`.
134763
+ *
134764
+ * Defaults to `4326`.
134765
+ * @param decimalPlaces - number of decimal places for points when `srid` is `4326` (e.g., `decimalPlaces = 3` produces values like `'point(30.723 46.482)'`).
134766
+ *
134767
+ * Defaults to `6`.
134768
+ *
134769
+ * @example
134770
+ * ```ts
134771
+ * await seed(db, { geometryTable: schema.geometryTable }).refine((funcs) => ({
134772
+ * geometryTable: {
134773
+ * count,
134774
+ * columns: {
134775
+ * geometryPointTuple: funcs.geometry({
134776
+ * type: 'point',
134777
+ * srid: 4326,
134778
+ * decimalPlaces: 5,
134779
+ * isUnique: true
134780
+ * })
134781
+ * },
134782
+ * },
134783
+ * }));
134784
+ * ```
134785
+ */
134786
+ geometry: createGenerator(GenerateGeometry),
134787
+ /**
134788
+ * generates vectors based on the provided parameters.
134789
+ *
134790
+ * @param isUnique - property that controls if generated values gonna be unique or not.
134791
+ * @param arraySize - number of elements in each one-dimensional array (If specified, arrays will be generated).
134792
+ * @param decimalPlaces - number of decimal places for each vector element (e.g., `decimalPlaces = 3` produces values like `1.123`).
134793
+ *
134794
+ * Defaults to `2`.
134795
+ * @param dimensions - number of elements in each generated vector (e.g., `dimensions = 3` produces values like `[1,2,3]`).
134796
+ *
134797
+ * Defaults to the value of the database column’s dimensions.
134798
+ * @param minValue - minimum allowed value for each vector element.
134799
+ *
134800
+ * Defaults to `-1000`.
134801
+ * @param maxValue - maximum allowed value for each vector element.
134802
+ *
134803
+ * Defaults to `1000`.
134804
+ *
134805
+ * @example
134806
+ * ```ts
134807
+ * await seed(db, { vectorTable: schema.vectorTable }).refine((funcs) => ({
134808
+ * vectorTable: {
134809
+ * count,
134810
+ * columns: {
134811
+ * vector: funcs.vector({
134812
+ * decimalPlaces: 5,
134813
+ * dimensions: 12,
134814
+ * minValue: -100,
134815
+ * maxValue: 100,
134816
+ * isUnique: true
134817
+ * }),
134818
+ * },
134819
+ * },
134820
+ * }));
134821
+ * ```
134822
+ */
134823
+ vector: createGenerator(GenerateVector),
134203
134824
  };
134204
- // so far, version changes don’t change generator parameters.
134825
+ // so far, version changes don’t affect generator parameters.
134205
134826
  const generatorsFuncsV2 = {
134206
134827
  ...generatorsFuncs,
134207
134828
  };
@@ -134359,10 +134980,1085 @@ const generatorsMap = {
134359
134980
  GenerateWeightedCount: [
134360
134981
  GenerateWeightedCount,
134361
134982
  ],
134983
+ GenerateBitString: [
134984
+ GenerateBitString,
134985
+ ],
134986
+ GenerateUniqueBitString: [
134987
+ GenerateUniqueBitString,
134988
+ ],
134989
+ GenerateInet: [
134990
+ GenerateInet,
134991
+ ],
134992
+ GenerateUniqueInet: [
134993
+ GenerateUniqueInet,
134994
+ ],
134995
+ GenerateGeometry: [
134996
+ GenerateGeometry,
134997
+ ],
134998
+ GenerateUniqueGeometry: [
134999
+ GenerateUniqueGeometry,
135000
+ ],
135001
+ GenerateVector: [
135002
+ GenerateVector,
135003
+ ],
135004
+ GenerateUniqueVector: [
135005
+ GenerateUniqueVector,
135006
+ ],
135007
+ };
135008
+
135009
+ // TODO: revise serial part generators
135010
+ const selectGeneratorForCockroachColumn = (table, col) => {
135011
+ const pickGenerator = (table, col) => {
135012
+ // ARRAY
135013
+ if (col.columnType.match(/\[\w*]/g) !== null && col.baseColumn !== undefined) {
135014
+ const baseColumnGen = selectGeneratorForCockroachColumn(table, col.baseColumn);
135015
+ if (baseColumnGen === undefined) {
135016
+ throw new Error(`column with type ${col.baseColumn.columnType} is not supported for now.`);
135017
+ }
135018
+ // const getBaseColumnDataType = (baseColumn: Column) => {
135019
+ // if (baseColumn.baseColumn !== undefined) {
135020
+ // return getBaseColumnDataType(baseColumn.baseColumn);
135021
+ // }
135022
+ // return baseColumn.dataType;
135023
+ // };
135024
+ // const baseColumnDataType = getBaseColumnDataType(col.baseColumn);
135025
+ const generator = new generatorsMap.GenerateArray[0]({ baseColumnGen, size: col.size });
135026
+ // generator.baseColumnDataType = baseColumnDataType;
135027
+ return generator;
135028
+ }
135029
+ // ARRAY for studio
135030
+ if (col.columnType.match(/\[\w*]/g) !== null) {
135031
+ // remove dimensions from type
135032
+ const baseColumnType = col.columnType.replace(/\[\w*]/g, '');
135033
+ const baseColumn = {
135034
+ ...col,
135035
+ };
135036
+ baseColumn.columnType = baseColumnType;
135037
+ const baseColumnGen = selectGeneratorForCockroachColumn(table, baseColumn);
135038
+ if (baseColumnGen === undefined) {
135039
+ throw new Error(`column with type ${col.baseColumn.columnType} is not supported for now.`);
135040
+ }
135041
+ let generator = new generatorsMap.GenerateArray[0]({ baseColumnGen });
135042
+ for (let i = 0; i < col.typeParams.dimensions - 1; i++) {
135043
+ generator = new generatorsMap.GenerateArray[0]({ baseColumnGen: generator });
135044
+ }
135045
+ return generator;
135046
+ }
135047
+ // INT ------------------------------------------------------------------------------------------------------------
135048
+ if ((col.columnType === 'int2'
135049
+ || col.columnType === 'int4'
135050
+ || col.columnType.includes('int8'))
135051
+ && table.primaryKeys.includes(col.name)) {
135052
+ const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
135053
+ return generator;
135054
+ }
135055
+ let minValue;
135056
+ let maxValue;
135057
+ if (col.columnType.startsWith('int')) {
135058
+ if (col.columnType === 'int2') {
135059
+ // 2^16 / 2 - 1, 2 bytes
135060
+ minValue = -32768;
135061
+ maxValue = 32767;
135062
+ }
135063
+ else if (col.columnType === 'int4') {
135064
+ // 2^32 / 2 - 1, 4 bytes
135065
+ minValue = -2147483648;
135066
+ maxValue = 2147483647;
135067
+ }
135068
+ else if (col.columnType.includes('int8')) {
135069
+ if (col.dataType === 'bigint') {
135070
+ // 2^64 / 2 - 1, 8 bytes
135071
+ minValue = BigInt('-9223372036854775808');
135072
+ maxValue = BigInt('9223372036854775807');
135073
+ }
135074
+ else {
135075
+ // if (col.dataType === 'number')
135076
+ // if you’re expecting values above 2^31 but below 2^53
135077
+ minValue = -9007199254740991;
135078
+ maxValue = 9007199254740991;
135079
+ }
135080
+ }
135081
+ }
135082
+ if (col.columnType.startsWith('int')
135083
+ && !col.columnType.includes('interval')) {
135084
+ const generator = new generatorsMap.GenerateInt[0]({
135085
+ minValue,
135086
+ maxValue,
135087
+ });
135088
+ return generator;
135089
+ }
135090
+ // NUMBER(real, double, decimal, numeric)
135091
+ if (col.columnType.startsWith('real')
135092
+ || col.columnType.startsWith('float')
135093
+ || col.columnType.startsWith('decimal')
135094
+ || col.columnType.startsWith('numeric')) {
135095
+ if (col.typeParams.precision !== undefined) {
135096
+ const precision = col.typeParams.precision;
135097
+ const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
135098
+ const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
135099
+ const generator = new generatorsMap.GenerateNumber[0]({
135100
+ minValue: -maxAbsoluteValue,
135101
+ maxValue: maxAbsoluteValue,
135102
+ precision: Math.pow(10, scale),
135103
+ });
135104
+ return generator;
135105
+ }
135106
+ const generator = new generatorsMap.GenerateNumber[0]();
135107
+ return generator;
135108
+ }
135109
+ // STRING
135110
+ if ((col.columnType === 'string'
135111
+ || col.columnType.startsWith('varchar')
135112
+ || col.columnType.startsWith('char'))
135113
+ && table.primaryKeys.includes(col.name)) {
135114
+ const generator = new generatorsMap.GenerateUniqueString[0]();
135115
+ return generator;
135116
+ }
135117
+ if ((col.columnType === 'string'
135118
+ || col.columnType.startsWith('varchar')
135119
+ || col.columnType.startsWith('char'))
135120
+ && col.name.toLowerCase().includes('name')) {
135121
+ const generator = new generatorsMap.GenerateFirstName[0]();
135122
+ return generator;
135123
+ }
135124
+ if ((col.columnType === 'string'
135125
+ || col.columnType.startsWith('varchar')
135126
+ || col.columnType.startsWith('char'))
135127
+ && col.name.toLowerCase().includes('email')) {
135128
+ const generator = new generatorsMap.GenerateEmail[0]();
135129
+ return generator;
135130
+ }
135131
+ if (col.columnType === 'string'
135132
+ || col.columnType.startsWith('varchar')
135133
+ || col.columnType.startsWith('char')) {
135134
+ const generator = new generatorsMap.GenerateString[0]();
135135
+ return generator;
135136
+ }
135137
+ // BIT
135138
+ if (col.columnType.startsWith('bit')) {
135139
+ const generator = new generatorsMap.GenerateBitString[0]();
135140
+ return generator;
135141
+ }
135142
+ // INET
135143
+ if (col.columnType === 'inet') {
135144
+ const generator = new generatorsMap.GenerateInet[0]();
135145
+ return generator;
135146
+ }
135147
+ // geometry(point)
135148
+ if (col.columnType.startsWith('geometry')) {
135149
+ const generator = new generatorsMap.GenerateGeometry[0]();
135150
+ return generator;
135151
+ }
135152
+ // vector
135153
+ if (col.columnType.startsWith('vector')) {
135154
+ const generator = new generatorsMap.GenerateVector[0]();
135155
+ return generator;
135156
+ }
135157
+ // UUID
135158
+ if (col.columnType === 'uuid') {
135159
+ const generator = new generatorsMap.GenerateUUID[0]();
135160
+ return generator;
135161
+ }
135162
+ // BOOL
135163
+ if (col.columnType === 'bool') {
135164
+ const generator = new generatorsMap.GenerateBoolean[0]();
135165
+ return generator;
135166
+ }
135167
+ // DATE, TIME, TIMESTAMP
135168
+ if (col.columnType.includes('date')) {
135169
+ const generator = new generatorsMap.GenerateDate[0]();
135170
+ return generator;
135171
+ }
135172
+ if (col.columnType === 'time') {
135173
+ const generator = new generatorsMap.GenerateTime[0]();
135174
+ return generator;
135175
+ }
135176
+ if (col.columnType.includes('timestamp')) {
135177
+ const generator = new generatorsMap.GenerateTimestamp[0]();
135178
+ return generator;
135179
+ }
135180
+ // JSON, JSONB
135181
+ if (col.columnType === 'json' || col.columnType === 'jsonb') {
135182
+ const generator = new generatorsMap.GenerateJson[0]();
135183
+ return generator;
135184
+ }
135185
+ // if (col.columnType === "jsonb") {
135186
+ // const generator = new GenerateJsonb({});
135187
+ // return generator;
135188
+ // }
135189
+ // ENUM
135190
+ if (col.enumValues !== undefined) {
135191
+ const generator = new generatorsMap.GenerateEnum[0]({
135192
+ enumValues: col.enumValues,
135193
+ });
135194
+ return generator;
135195
+ }
135196
+ // INTERVAL
135197
+ if (col.columnType.startsWith('interval')) {
135198
+ if (col.columnType === 'interval') {
135199
+ const generator = new generatorsMap.GenerateInterval[0]();
135200
+ return generator;
135201
+ }
135202
+ const fields = col.columnType.replace('interval ', '');
135203
+ const generator = new generatorsMap.GenerateInterval[0]({ fields });
135204
+ return generator;
135205
+ }
135206
+ if (col.hasDefault && col.default !== undefined) {
135207
+ const generator = new generatorsMap.GenerateDefault[0]({
135208
+ defaultValue: col.default,
135209
+ });
135210
+ return generator;
135211
+ }
135212
+ return;
135213
+ };
135214
+ const generator = pickGenerator(table, col);
135215
+ // set params for base column
135216
+ if (generator !== undefined) {
135217
+ generator.isUnique = col.isUnique;
135218
+ generator.dataType = col.dataType;
135219
+ // generator.stringLength = col.typeParams.length;
135220
+ generator.typeParams = col.typeParams;
135221
+ }
135222
+ return generator;
134362
135223
  };
134363
135224
 
134364
135225
  const latestVersion = 2;
134365
135226
 
135227
+ const selectGeneratorForMssqlColumn = (table, col) => {
135228
+ const pickGenerator = (table, col) => {
135229
+ // INT ------------------------------------------------------------------------------------------------------------
135230
+ if (col.columnType.includes('int') && table.primaryKeys.includes(col.name)) {
135231
+ const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
135232
+ return generator;
135233
+ }
135234
+ let minValue;
135235
+ let maxValue;
135236
+ if (col.columnType.includes('int')) {
135237
+ if (col.columnType === 'tinyint') {
135238
+ // 2^8 / 2 - 1, 1 bytes
135239
+ // more like unsigned tinyint
135240
+ minValue = 0;
135241
+ maxValue = 255;
135242
+ }
135243
+ else if (col.columnType === 'smallint') {
135244
+ // 2^16 / 2 - 1, 2 bytes
135245
+ minValue = -32768;
135246
+ maxValue = 32767;
135247
+ }
135248
+ else if (col.columnType === 'int') {
135249
+ // 2^32 / 2 - 1, 4 bytes
135250
+ minValue = -2147483648;
135251
+ maxValue = 2147483647;
135252
+ }
135253
+ else if (col.columnType === 'bigint') {
135254
+ // 2^64 / 2 - 1, 8 bytes
135255
+ minValue = BigInt('-9223372036854775808');
135256
+ maxValue = BigInt('9223372036854775807');
135257
+ }
135258
+ const generator = new generatorsMap.GenerateInt[0]({
135259
+ minValue,
135260
+ maxValue,
135261
+ });
135262
+ return generator;
135263
+ }
135264
+ // NUMBER(real, decimal, numeric, float)
135265
+ if (col.columnType.startsWith('real')
135266
+ || col.columnType.startsWith('decimal')
135267
+ || col.columnType.startsWith('float')
135268
+ || col.columnType.startsWith('numeric')) {
135269
+ if (col.typeParams.precision !== undefined) {
135270
+ const precision = col.typeParams.precision;
135271
+ const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
135272
+ const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
135273
+ const generator = new generatorsMap.GenerateNumber[0]({
135274
+ minValue: -maxAbsoluteValue,
135275
+ maxValue: maxAbsoluteValue,
135276
+ precision: Math.pow(10, scale),
135277
+ });
135278
+ return generator;
135279
+ }
135280
+ const generator = new generatorsMap.GenerateNumber[0]();
135281
+ return generator;
135282
+ }
135283
+ // STRING
135284
+ if ((col.columnType === 'text'
135285
+ || col.columnType.startsWith('char')
135286
+ || col.columnType.startsWith('varchar')
135287
+ || col.columnType.startsWith('binary')
135288
+ || col.columnType.startsWith('varbinary'))
135289
+ && table.primaryKeys.includes(col.name)) {
135290
+ const generator = new generatorsMap.GenerateUniqueString[0]();
135291
+ return generator;
135292
+ }
135293
+ if ((col.columnType === 'text'
135294
+ || col.columnType.startsWith('char')
135295
+ || col.columnType.startsWith('varchar')
135296
+ || col.columnType.startsWith('binary')
135297
+ || col.columnType.startsWith('varbinary'))
135298
+ && col.name.toLowerCase().includes('name')) {
135299
+ const generator = new generatorsMap.GenerateFirstName[0]();
135300
+ return generator;
135301
+ }
135302
+ if ((col.columnType === 'text'
135303
+ || col.columnType.startsWith('char')
135304
+ || col.columnType.startsWith('varchar')
135305
+ || col.columnType.startsWith('binary')
135306
+ || col.columnType.startsWith('varbinary'))
135307
+ && col.name.toLowerCase().includes('email')) {
135308
+ const generator = new generatorsMap.GenerateEmail[0]();
135309
+ return generator;
135310
+ }
135311
+ if (col.columnType === 'text'
135312
+ || col.columnType.startsWith('char')
135313
+ || col.columnType.startsWith('varchar')
135314
+ || col.columnType.startsWith('binary')
135315
+ || col.columnType.startsWith('varbinary')) {
135316
+ const generator = new generatorsMap.GenerateString[0]();
135317
+ return generator;
135318
+ }
135319
+ // bit
135320
+ if (col.columnType === 'bit') {
135321
+ const generator = new generatorsMap.GenerateBoolean[0]();
135322
+ return generator;
135323
+ }
135324
+ // DATE, TIME, TIMESTAMP, DATETIME, YEAR
135325
+ if (col.columnType.includes('datetime')) {
135326
+ const generator = new generatorsMap.GenerateDatetime[0]();
135327
+ return generator;
135328
+ }
135329
+ if (col.columnType.includes('date')) {
135330
+ const generator = new generatorsMap.GenerateDate[0]();
135331
+ return generator;
135332
+ }
135333
+ if (col.columnType === 'time') {
135334
+ const generator = new generatorsMap.GenerateTime[0]();
135335
+ return generator;
135336
+ }
135337
+ // JSON
135338
+ if (col.columnType === 'json') {
135339
+ const generator = new generatorsMap.GenerateJson[0]();
135340
+ return generator;
135341
+ }
135342
+ if (col.hasDefault && col.default !== undefined) {
135343
+ const generator = new generatorsMap.GenerateDefault[0]({
135344
+ defaultValue: col.default,
135345
+ });
135346
+ return generator;
135347
+ }
135348
+ return;
135349
+ };
135350
+ const generator = pickGenerator(table, col);
135351
+ return generator;
135352
+ };
135353
+
135354
+ const selectGeneratorForMysqlColumn = (table, col) => {
135355
+ const pickGenerator = (table, col) => {
135356
+ // INT ------------------------------------------------------------------------------------------------------------
135357
+ if ((col.columnType.includes('serial') || col.columnType.includes('int'))
135358
+ && table.primaryKeys.includes(col.name)) {
135359
+ const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
135360
+ return generator;
135361
+ }
135362
+ let minValue;
135363
+ let maxValue;
135364
+ if (col.columnType === 'serial') {
135365
+ // 2^64 % 2 - 1, 8 bytes
135366
+ minValue = BigInt(0);
135367
+ maxValue = BigInt('9223372036854775807');
135368
+ }
135369
+ else if (col.columnType.includes('int')) {
135370
+ if (col.columnType === 'tinyint') {
135371
+ // 2^8 / 2 - 1, 1 bytes
135372
+ minValue = -128;
135373
+ maxValue = 127;
135374
+ }
135375
+ else if (col.columnType === 'smallint') {
135376
+ // 2^16 / 2 - 1, 2 bytes
135377
+ minValue = -32768;
135378
+ maxValue = 32767;
135379
+ }
135380
+ else if (col.columnType === 'mediumint') {
135381
+ // 2^16 / 2 - 1, 2 bytes
135382
+ minValue = -8388608;
135383
+ maxValue = 8388607;
135384
+ }
135385
+ else if (col.columnType === 'int') {
135386
+ // 2^32 / 2 - 1, 4 bytes
135387
+ minValue = -2147483648;
135388
+ maxValue = 2147483647;
135389
+ }
135390
+ else if (col.columnType === 'bigint') {
135391
+ // 2^64 / 2 - 1, 8 bytes
135392
+ minValue = BigInt('-9223372036854775808');
135393
+ maxValue = BigInt('9223372036854775807');
135394
+ }
135395
+ }
135396
+ if (col.columnType.includes('int')) {
135397
+ const generator = new generatorsMap.GenerateInt[0]({
135398
+ minValue,
135399
+ maxValue,
135400
+ });
135401
+ return generator;
135402
+ }
135403
+ if (col.columnType.includes('serial')) {
135404
+ const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
135405
+ generator.maxValue = maxValue;
135406
+ return generator;
135407
+ }
135408
+ // NUMBER(real, double, decimal, float)
135409
+ if (col.columnType.startsWith('real')
135410
+ || col.columnType.startsWith('double')
135411
+ || col.columnType.startsWith('decimal')
135412
+ || col.columnType.startsWith('float')
135413
+ || col.columnType.startsWith('numeric')) {
135414
+ if (col.typeParams.precision !== undefined) {
135415
+ const precision = col.typeParams.precision;
135416
+ const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
135417
+ const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
135418
+ const generator = new generatorsMap.GenerateNumber[0]({
135419
+ minValue: -maxAbsoluteValue,
135420
+ maxValue: maxAbsoluteValue,
135421
+ precision: Math.pow(10, scale),
135422
+ });
135423
+ return generator;
135424
+ }
135425
+ const generator = new generatorsMap.GenerateNumber[0]();
135426
+ return generator;
135427
+ }
135428
+ // STRING
135429
+ if ((col.columnType === 'text'
135430
+ || col.columnType === 'blob'
135431
+ || col.columnType.startsWith('char')
135432
+ || col.columnType.startsWith('varchar')
135433
+ || col.columnType.startsWith('binary')
135434
+ || col.columnType.startsWith('varbinary'))
135435
+ && table.primaryKeys.includes(col.name)) {
135436
+ const generator = new generatorsMap.GenerateUniqueString[0]();
135437
+ return generator;
135438
+ }
135439
+ if ((col.columnType === 'text'
135440
+ || col.columnType === 'blob'
135441
+ || col.columnType.startsWith('char')
135442
+ || col.columnType.startsWith('varchar')
135443
+ || col.columnType.startsWith('binary')
135444
+ || col.columnType.startsWith('varbinary'))
135445
+ && col.name.toLowerCase().includes('name')) {
135446
+ const generator = new generatorsMap.GenerateFirstName[0]();
135447
+ return generator;
135448
+ }
135449
+ if ((col.columnType === 'text'
135450
+ || col.columnType === 'blob'
135451
+ || col.columnType.startsWith('char')
135452
+ || col.columnType.startsWith('varchar')
135453
+ || col.columnType.startsWith('binary')
135454
+ || col.columnType.startsWith('varbinary'))
135455
+ && col.name.toLowerCase().includes('email')) {
135456
+ const generator = new generatorsMap.GenerateEmail[0]();
135457
+ return generator;
135458
+ }
135459
+ if (col.columnType === 'text'
135460
+ || col.columnType === 'blob'
135461
+ || col.columnType.startsWith('char')
135462
+ || col.columnType.startsWith('varchar')
135463
+ || col.columnType.startsWith('binary')
135464
+ || col.columnType.startsWith('varbinary')) {
135465
+ const generator = new generatorsMap.GenerateString[0]();
135466
+ return generator;
135467
+ }
135468
+ // BOOLEAN
135469
+ if (col.columnType === 'boolean') {
135470
+ const generator = new generatorsMap.GenerateBoolean[0]();
135471
+ return generator;
135472
+ }
135473
+ // DATE, TIME, TIMESTAMP, DATETIME, YEAR
135474
+ if (col.columnType.includes('datetime')) {
135475
+ const generator = new generatorsMap.GenerateDatetime[0]();
135476
+ return generator;
135477
+ }
135478
+ if (col.columnType.includes('date')) {
135479
+ const generator = new generatorsMap.GenerateDate[0]();
135480
+ return generator;
135481
+ }
135482
+ if (col.columnType === 'time') {
135483
+ const generator = new generatorsMap.GenerateTime[0]();
135484
+ return generator;
135485
+ }
135486
+ if (col.columnType.includes('timestamp')) {
135487
+ const generator = new generatorsMap.GenerateTimestamp[0]();
135488
+ return generator;
135489
+ }
135490
+ if (col.columnType === 'year') {
135491
+ const generator = new generatorsMap.GenerateYear[0]();
135492
+ return generator;
135493
+ }
135494
+ // JSON
135495
+ if (col.columnType === 'json') {
135496
+ const generator = new generatorsMap.GenerateJson[0]();
135497
+ return generator;
135498
+ }
135499
+ // ENUM
135500
+ if (col.enumValues !== undefined) {
135501
+ const generator = new generatorsMap.GenerateEnum[0]({
135502
+ enumValues: col.enumValues,
135503
+ });
135504
+ return generator;
135505
+ }
135506
+ if (col.hasDefault && col.default !== undefined) {
135507
+ const generator = new generatorsMap.GenerateDefault[0]({
135508
+ defaultValue: col.default,
135509
+ });
135510
+ return generator;
135511
+ }
135512
+ return;
135513
+ };
135514
+ const generator = pickGenerator(table, col);
135515
+ return generator;
135516
+ };
135517
+
135518
+ // TODO: revise serial part generators
135519
+ const selectGeneratorForPostgresColumn = (table, col) => {
135520
+ const pickGenerator = (table, col) => {
135521
+ // ARRAY
135522
+ if (col.columnType.match(/\[\w*]/g) !== null && col.baseColumn !== undefined) {
135523
+ const baseColumnGen = selectGeneratorForPostgresColumn(table, col.baseColumn);
135524
+ if (baseColumnGen === undefined) {
135525
+ throw new Error(`column with type ${col.baseColumn.columnType} is not supported for now.`);
135526
+ }
135527
+ // const getBaseColumnDataType = (baseColumn: Column) => {
135528
+ // if (baseColumn.baseColumn !== undefined) {
135529
+ // return getBaseColumnDataType(baseColumn.baseColumn);
135530
+ // }
135531
+ // return baseColumn.dataType;
135532
+ // };
135533
+ // const baseColumnDataType = getBaseColumnDataType(col.baseColumn);
135534
+ const generator = new generatorsMap.GenerateArray[0]({ baseColumnGen, size: col.size });
135535
+ // generator.baseColumnDataType = baseColumnDataType;
135536
+ return generator;
135537
+ }
135538
+ // ARRAY for studio
135539
+ if (col.columnType.match(/\[\w*]/g) !== null) {
135540
+ // remove dimensions from type
135541
+ const baseColumnType = col.columnType.replace(/\[\w*]/g, '');
135542
+ const baseColumn = {
135543
+ ...col,
135544
+ };
135545
+ baseColumn.columnType = baseColumnType;
135546
+ const baseColumnGen = selectGeneratorForPostgresColumn(table, baseColumn);
135547
+ if (baseColumnGen === undefined) {
135548
+ throw new Error(`column with type ${col.baseColumn.columnType} is not supported for now.`);
135549
+ }
135550
+ let generator = new generatorsMap.GenerateArray[0]({ baseColumnGen });
135551
+ for (let i = 0; i < col.typeParams.dimensions - 1; i++) {
135552
+ generator = new generatorsMap.GenerateArray[0]({ baseColumnGen: generator });
135553
+ }
135554
+ return generator;
135555
+ }
135556
+ // INT ------------------------------------------------------------------------------------------------------------
135557
+ if ((col.columnType.includes('serial')
135558
+ || col.columnType === 'integer'
135559
+ || col.columnType === 'smallint'
135560
+ || col.columnType.includes('bigint'))
135561
+ && table.primaryKeys.includes(col.name)) {
135562
+ const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
135563
+ return generator;
135564
+ }
135565
+ let minValue;
135566
+ let maxValue;
135567
+ if (col.columnType.includes('serial')) {
135568
+ minValue = 1;
135569
+ if (col.columnType === 'smallserial') {
135570
+ // 2^16 / 2 - 1, 2 bytes
135571
+ maxValue = 32767;
135572
+ }
135573
+ else if (col.columnType === 'serial') {
135574
+ // 2^32 / 2 - 1, 4 bytes
135575
+ maxValue = 2147483647;
135576
+ }
135577
+ else if (col.columnType === 'bigserial') {
135578
+ // 2^64 / 2 - 1, 8 bytes
135579
+ minValue = BigInt(1);
135580
+ maxValue = BigInt('9223372036854775807');
135581
+ }
135582
+ }
135583
+ else if (col.columnType.includes('int')) {
135584
+ if (col.columnType === 'smallint') {
135585
+ // 2^16 / 2 - 1, 2 bytes
135586
+ minValue = -32768;
135587
+ maxValue = 32767;
135588
+ }
135589
+ else if (col.columnType === 'integer') {
135590
+ // 2^32 / 2 - 1, 4 bytes
135591
+ minValue = -2147483648;
135592
+ maxValue = 2147483647;
135593
+ }
135594
+ else if (col.columnType.includes('bigint')) {
135595
+ if (col.dataType === 'bigint') {
135596
+ // 2^64 / 2 - 1, 8 bytes
135597
+ minValue = BigInt('-9223372036854775808');
135598
+ maxValue = BigInt('9223372036854775807');
135599
+ }
135600
+ else {
135601
+ // if (col.dataType === 'number')
135602
+ // if you’re expecting values above 2^31 but below 2^53
135603
+ minValue = -9007199254740991;
135604
+ maxValue = 9007199254740991;
135605
+ }
135606
+ }
135607
+ }
135608
+ if (col.columnType.includes('int')
135609
+ && !col.columnType.includes('interval')
135610
+ && !col.columnType.includes('point')) {
135611
+ const generator = new generatorsMap.GenerateInt[0]({
135612
+ minValue,
135613
+ maxValue,
135614
+ });
135615
+ return generator;
135616
+ }
135617
+ if (col.columnType.includes('serial')) {
135618
+ const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
135619
+ generator.maxValue = maxValue;
135620
+ return generator;
135621
+ }
135622
+ // NUMBER(real, double, decimal, numeric)
135623
+ if (col.columnType.startsWith('real')
135624
+ || col.columnType.startsWith('double precision')
135625
+ || col.columnType.startsWith('decimal')
135626
+ || col.columnType.startsWith('numeric')) {
135627
+ if (col.typeParams.precision !== undefined) {
135628
+ const precision = col.typeParams.precision;
135629
+ const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
135630
+ const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
135631
+ const generator = new generatorsMap.GenerateNumber[0]({
135632
+ minValue: -maxAbsoluteValue,
135633
+ maxValue: maxAbsoluteValue,
135634
+ precision: Math.pow(10, scale),
135635
+ });
135636
+ return generator;
135637
+ }
135638
+ const generator = new generatorsMap.GenerateNumber[0]();
135639
+ return generator;
135640
+ }
135641
+ // STRING
135642
+ if ((col.columnType === 'text'
135643
+ || col.columnType.startsWith('varchar')
135644
+ || col.columnType.startsWith('char'))
135645
+ && table.primaryKeys.includes(col.name)) {
135646
+ const generator = new generatorsMap.GenerateUniqueString[0]();
135647
+ return generator;
135648
+ }
135649
+ if ((col.columnType === 'text'
135650
+ || col.columnType.startsWith('varchar')
135651
+ || col.columnType.startsWith('char'))
135652
+ && col.name.toLowerCase().includes('name')) {
135653
+ const generator = new generatorsMap.GenerateFirstName[0]();
135654
+ return generator;
135655
+ }
135656
+ if ((col.columnType === 'text'
135657
+ || col.columnType.startsWith('varchar')
135658
+ || col.columnType.startsWith('char'))
135659
+ && col.name.toLowerCase().includes('email')) {
135660
+ const generator = new generatorsMap.GenerateEmail[0]();
135661
+ return generator;
135662
+ }
135663
+ if (col.columnType === 'text'
135664
+ || col.columnType.startsWith('varchar')
135665
+ || col.columnType.startsWith('char')) {
135666
+ const generator = new generatorsMap.GenerateString[0]();
135667
+ return generator;
135668
+ }
135669
+ // BIT
135670
+ if (col.columnType.startsWith('bit')) {
135671
+ const generator = new generatorsMap.GenerateBitString[0]();
135672
+ return generator;
135673
+ }
135674
+ // INET
135675
+ if (col.columnType === 'inet') {
135676
+ const generator = new generatorsMap.GenerateInet[0]();
135677
+ return generator;
135678
+ }
135679
+ // geometry(point)
135680
+ if (col.columnType.startsWith('geometry')) {
135681
+ const generator = new generatorsMap.GenerateGeometry[0]();
135682
+ return generator;
135683
+ }
135684
+ // vector
135685
+ if (col.columnType.startsWith('vector')) {
135686
+ const generator = new generatorsMap.GenerateVector[0]();
135687
+ return generator;
135688
+ }
135689
+ // UUID
135690
+ if (col.columnType === 'uuid') {
135691
+ const generator = new generatorsMap.GenerateUUID[0]();
135692
+ return generator;
135693
+ }
135694
+ // BOOLEAN
135695
+ if (col.columnType === 'boolean') {
135696
+ const generator = new generatorsMap.GenerateBoolean[0]();
135697
+ return generator;
135698
+ }
135699
+ // DATE, TIME, TIMESTAMP
135700
+ if (col.columnType.includes('date')) {
135701
+ const generator = new generatorsMap.GenerateDate[0]();
135702
+ return generator;
135703
+ }
135704
+ if (col.columnType === 'time') {
135705
+ const generator = new generatorsMap.GenerateTime[0]();
135706
+ return generator;
135707
+ }
135708
+ if (col.columnType.includes('timestamp')) {
135709
+ const generator = new generatorsMap.GenerateTimestamp[0]();
135710
+ return generator;
135711
+ }
135712
+ // JSON, JSONB
135713
+ if (col.columnType === 'json' || col.columnType === 'jsonb') {
135714
+ const generator = new generatorsMap.GenerateJson[0]();
135715
+ return generator;
135716
+ }
135717
+ // if (col.columnType === "jsonb") {
135718
+ // const generator = new GenerateJsonb({});
135719
+ // return generator;
135720
+ // }
135721
+ // ENUM
135722
+ if (col.enumValues !== undefined) {
135723
+ const generator = new generatorsMap.GenerateEnum[0]({
135724
+ enumValues: col.enumValues,
135725
+ });
135726
+ return generator;
135727
+ }
135728
+ // INTERVAL
135729
+ if (col.columnType.startsWith('interval')) {
135730
+ if (col.columnType === 'interval') {
135731
+ const generator = new generatorsMap.GenerateInterval[0]();
135732
+ return generator;
135733
+ }
135734
+ const fields = col.columnType.replace('interval ', '');
135735
+ const generator = new generatorsMap.GenerateInterval[0]({ fields });
135736
+ return generator;
135737
+ }
135738
+ // POINT, LINE
135739
+ if (col.columnType.includes('point')) {
135740
+ const generator = new generatorsMap.GeneratePoint[0]();
135741
+ return generator;
135742
+ }
135743
+ if (col.columnType.includes('line')) {
135744
+ const generator = new generatorsMap.GenerateLine[0]();
135745
+ return generator;
135746
+ }
135747
+ if (col.hasDefault && col.default !== undefined) {
135748
+ const generator = new generatorsMap.GenerateDefault[0]({
135749
+ defaultValue: col.default,
135750
+ });
135751
+ return generator;
135752
+ }
135753
+ return;
135754
+ };
135755
+ const generator = pickGenerator(table, col);
135756
+ if (generator !== undefined) {
135757
+ generator.isUnique = col.isUnique;
135758
+ generator.dataType = col.dataType;
135759
+ generator.typeParams = col.typeParams;
135760
+ // generator.stringLength = col.typeParams.length;
135761
+ }
135762
+ return generator;
135763
+ };
135764
+
135765
+ const selectGeneratorForSingleStoreColumn = (table, col) => {
135766
+ const pickGenerator = (table, col) => {
135767
+ // INT ------------------------------------------------------------------------------------------------------------
135768
+ if ((col.columnType.includes('serial') || col.columnType.includes('int'))
135769
+ && table.primaryKeys.includes(col.name)) {
135770
+ const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
135771
+ return generator;
135772
+ }
135773
+ let minValue;
135774
+ let maxValue;
135775
+ if (col.columnType === 'serial') {
135776
+ // 2^64 % 2 - 1, 8 bytes
135777
+ minValue = BigInt(0);
135778
+ maxValue = BigInt('9223372036854775807');
135779
+ }
135780
+ else if (col.columnType.includes('int')) {
135781
+ if (col.columnType === 'tinyint') {
135782
+ // 2^8 / 2 - 1, 1 bytes
135783
+ minValue = -128;
135784
+ maxValue = 127;
135785
+ }
135786
+ else if (col.columnType === 'smallint') {
135787
+ // 2^16 / 2 - 1, 2 bytes
135788
+ minValue = -32768;
135789
+ maxValue = 32767;
135790
+ }
135791
+ else if (col.columnType === 'mediumint') {
135792
+ // 2^16 / 2 - 1, 2 bytes
135793
+ minValue = -8388608;
135794
+ maxValue = 8388607;
135795
+ }
135796
+ else if (col.columnType === 'int') {
135797
+ // 2^32 / 2 - 1, 4 bytes
135798
+ minValue = -2147483648;
135799
+ maxValue = 2147483647;
135800
+ }
135801
+ else if (col.columnType === 'bigint') {
135802
+ // 2^64 / 2 - 1, 8 bytes
135803
+ minValue = BigInt('-9223372036854775808');
135804
+ maxValue = BigInt('9223372036854775807');
135805
+ }
135806
+ }
135807
+ if (col.columnType.includes('int')) {
135808
+ const generator = new generatorsMap.GenerateInt[0]({
135809
+ minValue,
135810
+ maxValue,
135811
+ });
135812
+ return generator;
135813
+ }
135814
+ if (col.columnType.includes('serial')) {
135815
+ const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
135816
+ generator.maxValue = maxValue;
135817
+ return generator;
135818
+ }
135819
+ // NUMBER(real, double, decimal, float)
135820
+ if (col.columnType.startsWith('real')
135821
+ || col.columnType.startsWith('double')
135822
+ || col.columnType.startsWith('decimal')
135823
+ || col.columnType.startsWith('float')
135824
+ || col.columnType.startsWith('numeric')) {
135825
+ if (col.typeParams.precision !== undefined) {
135826
+ const precision = col.typeParams.precision;
135827
+ const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
135828
+ const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
135829
+ const generator = new generatorsMap.GenerateNumber[0]({
135830
+ minValue: -maxAbsoluteValue,
135831
+ maxValue: maxAbsoluteValue,
135832
+ precision: Math.pow(10, scale),
135833
+ });
135834
+ return generator;
135835
+ }
135836
+ const generator = new generatorsMap.GenerateNumber[0]();
135837
+ return generator;
135838
+ }
135839
+ // STRING
135840
+ if ((col.columnType === 'tinytext'
135841
+ || col.columnType === 'mediumtext'
135842
+ || col.columnType === 'text'
135843
+ || col.columnType === 'longtext'
135844
+ || col.columnType === 'blob'
135845
+ || col.columnType.startsWith('char')
135846
+ || col.columnType.startsWith('varchar')
135847
+ || col.columnType.startsWith('binary')
135848
+ || col.columnType.startsWith('varbinary'))
135849
+ && table.primaryKeys.includes(col.name)) {
135850
+ const generator = new generatorsMap.GenerateUniqueString[0]();
135851
+ return generator;
135852
+ }
135853
+ if ((col.columnType === 'tinytext'
135854
+ || col.columnType === 'mediumtext'
135855
+ || col.columnType === 'text'
135856
+ || col.columnType === 'longtext'
135857
+ || col.columnType === 'blob'
135858
+ || col.columnType.startsWith('char')
135859
+ || col.columnType.startsWith('varchar')
135860
+ || col.columnType.startsWith('binary')
135861
+ || col.columnType.startsWith('varbinary'))
135862
+ && col.name.toLowerCase().includes('name')) {
135863
+ const generator = new generatorsMap.GenerateFirstName[0]();
135864
+ return generator;
135865
+ }
135866
+ if ((col.columnType === 'tinytext'
135867
+ || col.columnType === 'mediumtext'
135868
+ || col.columnType === 'text'
135869
+ || col.columnType === 'longtext'
135870
+ || col.columnType === 'blob'
135871
+ || col.columnType.startsWith('char')
135872
+ || col.columnType.startsWith('varchar')
135873
+ || col.columnType.startsWith('binary')
135874
+ || col.columnType.startsWith('varbinary'))
135875
+ && col.name.toLowerCase().includes('email')) {
135876
+ const generator = new generatorsMap.GenerateEmail[0]();
135877
+ return generator;
135878
+ }
135879
+ if (col.columnType === 'tinytext'
135880
+ || col.columnType === 'mediumtext'
135881
+ || col.columnType === 'text'
135882
+ || col.columnType === 'longtext'
135883
+ || col.columnType === 'blob'
135884
+ || col.columnType.startsWith('char')
135885
+ || col.columnType.startsWith('varchar')
135886
+ || col.columnType.startsWith('binary')
135887
+ || col.columnType.startsWith('varbinary')) {
135888
+ const generator = new generatorsMap.GenerateString[0]();
135889
+ return generator;
135890
+ }
135891
+ // BOOLEAN
135892
+ if (col.columnType === 'boolean') {
135893
+ const generator = new generatorsMap.GenerateBoolean[0]();
135894
+ return generator;
135895
+ }
135896
+ // DATE, TIME, TIMESTAMP, DATETIME, YEAR
135897
+ if (col.columnType.includes('datetime')) {
135898
+ const generator = new generatorsMap.GenerateDatetime[0]();
135899
+ return generator;
135900
+ }
135901
+ if (col.columnType.includes('date')) {
135902
+ const generator = new generatorsMap.GenerateDate[0]();
135903
+ return generator;
135904
+ }
135905
+ if (col.columnType === 'time') {
135906
+ const generator = new generatorsMap.GenerateTime[0]();
135907
+ return generator;
135908
+ }
135909
+ if (col.columnType.includes('timestamp')) {
135910
+ const generator = new generatorsMap.GenerateTimestamp[0]();
135911
+ return generator;
135912
+ }
135913
+ if (col.columnType === 'year') {
135914
+ const generator = new generatorsMap.GenerateYear[0]();
135915
+ return generator;
135916
+ }
135917
+ // JSON
135918
+ if (col.columnType === 'json') {
135919
+ const generator = new generatorsMap.GenerateJson[0]();
135920
+ return generator;
135921
+ }
135922
+ // ENUM
135923
+ if (col.enumValues !== undefined) {
135924
+ const generator = new generatorsMap.GenerateEnum[0]({
135925
+ enumValues: col.enumValues,
135926
+ });
135927
+ return generator;
135928
+ }
135929
+ // vector
135930
+ if (col.columnType.startsWith('vector')) {
135931
+ let minValue, maxValue, decimalPlaces;
135932
+ if (col.typeParams.vectorValueType === 'I8') {
135933
+ minValue = -128;
135934
+ maxValue = 127;
135935
+ decimalPlaces = 0;
135936
+ }
135937
+ else if (col.typeParams.vectorValueType === 'I16') {
135938
+ minValue = -32768;
135939
+ maxValue = 32767;
135940
+ decimalPlaces = 0;
135941
+ }
135942
+ else if (col.typeParams.vectorValueType === 'I32') {
135943
+ minValue = -2147483648;
135944
+ maxValue = 2147483647;
135945
+ decimalPlaces = 0;
135946
+ }
135947
+ else if (col.typeParams.vectorValueType === 'I64') {
135948
+ minValue = Number.MIN_SAFE_INTEGER;
135949
+ maxValue = Number.MAX_SAFE_INTEGER;
135950
+ // minValue = -BigInt('9223372036854775808');
135951
+ // maxValue = BigInt('9223372036854775807');
135952
+ decimalPlaces = 0;
135953
+ }
135954
+ else if (col.typeParams.vectorValueType === 'F32') {
135955
+ minValue = -2147483648;
135956
+ maxValue = 2147483647;
135957
+ decimalPlaces = 6;
135958
+ }
135959
+ else if (col.typeParams.vectorValueType === 'F64') {
135960
+ minValue = -524288;
135961
+ maxValue = 524287;
135962
+ decimalPlaces = 10;
135963
+ }
135964
+ const generator = new generatorsMap.GenerateVector[0]({ minValue, maxValue, decimalPlaces });
135965
+ return generator;
135966
+ }
135967
+ if (col.hasDefault && col.default !== undefined) {
135968
+ const generator = new generatorsMap.GenerateDefault[0]({
135969
+ defaultValue: col.default,
135970
+ });
135971
+ return generator;
135972
+ }
135973
+ return;
135974
+ };
135975
+ const generator = pickGenerator(table, col);
135976
+ return generator;
135977
+ };
135978
+
135979
+ const selectGeneratorForSqlite = (table, col) => {
135980
+ const pickGenerator = (table, col) => {
135981
+ // int section ---------------------------------------------------------------------------------------
135982
+ if ((col.columnType === 'integer' || col.columnType === 'numeric')
135983
+ && table.primaryKeys.includes(col.name)) {
135984
+ const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
135985
+ return generator;
135986
+ }
135987
+ if (col.columnType === 'integer' && col.dataType === 'boolean') {
135988
+ const generator = new generatorsMap.GenerateBoolean[0]();
135989
+ return generator;
135990
+ }
135991
+ if ((col.columnType === 'integer' && col.dataType === 'object')) {
135992
+ const generator = new generatorsMap.GenerateTimestamp[0]();
135993
+ return generator;
135994
+ }
135995
+ if (col.columnType === 'integer'
135996
+ || (col.dataType === 'bigint' && col.columnType === 'blob')) {
135997
+ const generator = new generatorsMap.GenerateInt[0]();
135998
+ return generator;
135999
+ }
136000
+ // number section ------------------------------------------------------------------------------------
136001
+ if (col.columnType.startsWith('real') || col.columnType.startsWith('numeric')) {
136002
+ if (col.typeParams.precision !== undefined) {
136003
+ const precision = col.typeParams.precision;
136004
+ const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
136005
+ const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
136006
+ const generator = new generatorsMap.GenerateNumber[0]({
136007
+ minValue: -maxAbsoluteValue,
136008
+ maxValue: maxAbsoluteValue,
136009
+ precision: Math.pow(10, scale),
136010
+ });
136011
+ return generator;
136012
+ }
136013
+ const generator = new generatorsMap.GenerateNumber[0]();
136014
+ return generator;
136015
+ }
136016
+ // string section ------------------------------------------------------------------------------------
136017
+ if ((col.columnType.startsWith('text')
136018
+ || col.columnType.startsWith('numeric')
136019
+ || col.columnType.startsWith('blob'))
136020
+ && table.primaryKeys.includes(col.name)) {
136021
+ const generator = new generatorsMap.GenerateUniqueString[0]();
136022
+ return generator;
136023
+ }
136024
+ if ((col.columnType.startsWith('text')
136025
+ || col.columnType.startsWith('numeric')
136026
+ || col.columnType.startsWith('blob'))
136027
+ && col.name.toLowerCase().includes('name')) {
136028
+ const generator = new generatorsMap.GenerateFirstName[0]();
136029
+ return generator;
136030
+ }
136031
+ if ((col.columnType.startsWith('text')
136032
+ || col.columnType.startsWith('numeric')
136033
+ || col.columnType.startsWith('blob'))
136034
+ && col.name.toLowerCase().includes('email')) {
136035
+ const generator = new generatorsMap.GenerateEmail[0]();
136036
+ return generator;
136037
+ }
136038
+ if (col.columnType.startsWith('text')
136039
+ || col.columnType.startsWith('numeric')
136040
+ || col.columnType.startsWith('blob')
136041
+ || col.columnType.startsWith('blobbuffer')) {
136042
+ const generator = new generatorsMap.GenerateString[0]();
136043
+ return generator;
136044
+ }
136045
+ if ((col.columnType.startsWith('text') && col.dataType === 'json')
136046
+ || (col.columnType.startsWith('blob') && col.dataType === 'json')) {
136047
+ const generator = new generatorsMap.GenerateJson[0]();
136048
+ return generator;
136049
+ }
136050
+ if (col.hasDefault && col.default !== undefined) {
136051
+ const generator = new generatorsMap.GenerateDefault[0]({
136052
+ defaultValue: col.default,
136053
+ });
136054
+ return generator;
136055
+ }
136056
+ return;
136057
+ };
136058
+ const generator = pickGenerator(table, col);
136059
+ return generator;
136060
+ };
136061
+
134366
136062
  /* eslint-disable drizzle-internal/require-entity-kind */
134367
136063
  class SeedService {
134368
136064
  static entityKind = 'SeedService';
@@ -134373,6 +136069,7 @@ class SeedService {
134373
136069
  mysqlMaxParametersNumber = 100000;
134374
136070
  // SQLITE_MAX_VARIABLE_NUMBER, which by default equals to 999 for SQLite versions prior to 3.32.0 (2020-05-22) or 32766 for SQLite versions after 3.32.0.
134375
136071
  sqliteMaxParametersNumber = 32766;
136072
+ mssqlMaxParametersNumber = 2100;
134376
136073
  version;
134377
136074
  generatePossibleGenerators = (connectionType, tables, relations, refinements, options) => {
134378
136075
  let columnPossibleGenerator;
@@ -134412,7 +136109,6 @@ class SeedService {
134412
136109
  };
134413
136110
  }
134414
136111
  }
134415
- // handling refinements (count, with)
134416
136112
  if (refinements !== undefined && refinements[table.name] !== undefined) {
134417
136113
  if (refinements[table.name].count !== undefined) {
134418
136114
  tablesPossibleGenerators[i].count = refinements[table.name].count;
@@ -134468,29 +136164,17 @@ class SeedService {
134468
136164
  notNull: col.notNull,
134469
136165
  primary: col.primary,
134470
136166
  generatedIdentityType: col.generatedIdentityType,
136167
+ identity: col.identity,
134471
136168
  generator: undefined,
134472
136169
  isCyclic: false,
134473
136170
  wasDefinedBefore: false,
134474
136171
  wasRefined: false,
134475
136172
  };
134476
- // handling refinements (columnGenerator)
134477
136173
  if (refinements !== undefined
134478
136174
  && refinements[table.name] !== undefined
134479
136175
  && refinements[table.name].columns !== undefined
134480
136176
  && refinements[table.name].columns[col.name] !== undefined) {
134481
136177
  const genObj = refinements[table.name].columns[col.name];
134482
- if (genObj === false) {
134483
- if (col.notNull === true && col.hasDefault === false) {
134484
- throw new Error(`You cannot set the '${col.name}' column in the '${table.name}' table to false in your refinements.`
134485
- + `\nDoing so will result in a null value being inserted into the '${col.name}' column,`
134486
- + `\nwhich will cause an error because the column has a not null constraint and no default value.`);
134487
- }
134488
- // Generating undefined as a value for a column and then inserting it via drizzle-orm
134489
- // will result in the value not being inserted into that column.
134490
- columnPossibleGenerator.generator = new generatorsMap.GenerateDefault[0]({ defaultValue: undefined });
134491
- columnPossibleGenerator.wasRefined = true;
134492
- continue;
134493
- }
134494
136178
  if (col.columnType.match(/\[\w*]/g) !== null) {
134495
136179
  if ((col.baseColumn?.dataType === 'array' && col.baseColumn.columnType.match(/\[\w*]/g) !== null)
134496
136180
  // studio case
@@ -134536,17 +136220,27 @@ class SeedService {
134536
136220
  }
134537
136221
  } // TODO: rewrite pickGeneratorFor... using new col properties: isUnique and notNull
134538
136222
  else if (connectionType === 'postgresql') {
134539
- columnPossibleGenerator.generator = this.selectGeneratorForPostgresColumn(table, col);
136223
+ columnPossibleGenerator.generator = selectGeneratorForPostgresColumn(table, col);
134540
136224
  }
134541
136225
  else if (connectionType === 'mysql') {
134542
- columnPossibleGenerator.generator = this.selectGeneratorForMysqlColumn(table, col);
136226
+ columnPossibleGenerator.generator = selectGeneratorForMysqlColumn(table, col);
134543
136227
  }
134544
136228
  else if (connectionType === 'sqlite') {
134545
- columnPossibleGenerator.generator = this.selectGeneratorForSqlite(table, col);
136229
+ columnPossibleGenerator.generator = selectGeneratorForSqlite(table, col);
136230
+ }
136231
+ else if (connectionType === 'mssql') {
136232
+ columnPossibleGenerator.generator = selectGeneratorForMssqlColumn(table, col);
136233
+ }
136234
+ else if (connectionType === 'cockroach') {
136235
+ columnPossibleGenerator.generator = selectGeneratorForCockroachColumn(table, col);
136236
+ }
136237
+ else if (connectionType === 'singlestore') {
136238
+ columnPossibleGenerator.generator = selectGeneratorForSingleStoreColumn(table, col);
134546
136239
  }
134547
136240
  if (columnPossibleGenerator.generator === undefined) {
134548
136241
  throw new Error(`column with type ${col.columnType} is not supported for now.`);
134549
136242
  }
136243
+ columnPossibleGenerator.generator.typeParams = col.typeParams ?? columnPossibleGenerator.generator.typeParams;
134550
136244
  const arrayGen = columnPossibleGenerator.generator.replaceIfArray();
134551
136245
  if (arrayGen !== undefined) {
134552
136246
  columnPossibleGenerator.generator = arrayGen;
@@ -134561,7 +136255,7 @@ class SeedService {
134561
136255
  // TODO: for now only GenerateValuesFromArray support notNull property
134562
136256
  columnPossibleGenerator.generator.notNull = col.notNull;
134563
136257
  columnPossibleGenerator.generator.dataType = col.dataType;
134564
- columnPossibleGenerator.generator.stringLength = col.typeParams.length;
136258
+ // columnPossibleGenerator.generator.stringLength = col.typeParams.length;
134565
136259
  tablePossibleGenerators.columnsPossibleGenerators.push(columnPossibleGenerator);
134566
136260
  }
134567
136261
  }
@@ -134572,7 +136266,7 @@ class SeedService {
134572
136266
  if (entityKind === 'GenerateArray') {
134573
136267
  const oldBaseColumnGen = generator.params.baseColumnGen;
134574
136268
  const newBaseColumnGen = this.selectVersionOfGenerator(oldBaseColumnGen);
134575
- // newGenerator.baseColumnDataType = oldGenerator.baseColumnDataType;
136269
+ newBaseColumnGen.typeParams = oldBaseColumnGen.typeParams;
134576
136270
  generator.params.baseColumnGen = newBaseColumnGen;
134577
136271
  }
134578
136272
  const possibleGeneratorConstructors = generatorsMap[entityKind];
@@ -134588,7 +136282,8 @@ class SeedService {
134588
136282
  // TODO: for now only GenerateValuesFromArray support notNull property
134589
136283
  newGenerator.notNull = generator.notNull;
134590
136284
  newGenerator.dataType = generator.dataType;
134591
- newGenerator.stringLength = generator.stringLength;
136285
+ // newGenerator.stringLength = generator.stringLength;
136286
+ newGenerator.typeParams = generator.typeParams ?? newGenerator.typeParams;
134592
136287
  return newGenerator;
134593
136288
  };
134594
136289
  cyclicTablesCompare = (table1, table2, relation, reverseRelation) => {
@@ -134699,474 +136394,6 @@ class SeedService {
134699
136394
  }
134700
136395
  return weightedWithCount;
134701
136396
  };
134702
- // TODO: revise serial part generators
134703
- selectGeneratorForPostgresColumn = (table, col) => {
134704
- const pickGenerator = (table, col) => {
134705
- // ARRAY
134706
- if (col.columnType.match(/\[\w*]/g) !== null && col.baseColumn !== undefined) {
134707
- const baseColumnGen = this.selectGeneratorForPostgresColumn(table, col.baseColumn);
134708
- if (baseColumnGen === undefined) {
134709
- throw new Error(`column with type ${col.baseColumn.columnType} is not supported for now.`);
134710
- }
134711
- // const getBaseColumnDataType = (baseColumn: Column) => {
134712
- // if (baseColumn.baseColumn !== undefined) {
134713
- // return getBaseColumnDataType(baseColumn.baseColumn);
134714
- // }
134715
- // return baseColumn.dataType;
134716
- // };
134717
- // const baseColumnDataType = getBaseColumnDataType(col.baseColumn);
134718
- const generator = new generatorsMap.GenerateArray[0]({ baseColumnGen, size: col.size });
134719
- // generator.baseColumnDataType = baseColumnDataType;
134720
- return generator;
134721
- }
134722
- // ARRAY for studio
134723
- if (col.columnType.match(/\[\w*]/g) !== null) {
134724
- // remove dimensions from type
134725
- const baseColumnType = col.columnType.replace(/\[\w*]/g, '');
134726
- const baseColumn = {
134727
- ...col,
134728
- };
134729
- baseColumn.columnType = baseColumnType;
134730
- const baseColumnGen = this.selectGeneratorForPostgresColumn(table, baseColumn);
134731
- if (baseColumnGen === undefined) {
134732
- throw new Error(`column with type ${col.baseColumn.columnType} is not supported for now.`);
134733
- }
134734
- let generator = new generatorsMap.GenerateArray[0]({ baseColumnGen });
134735
- for (let i = 0; i < col.typeParams.dimensions - 1; i++) {
134736
- generator = new generatorsMap.GenerateArray[0]({ baseColumnGen: generator });
134737
- }
134738
- return generator;
134739
- }
134740
- // INT ------------------------------------------------------------------------------------------------------------
134741
- if ((['smallserial', 'serial', 'bigserial'].includes(col.columnType)
134742
- || ['smallint', 'integer', 'bigint'].includes(col.columnType))
134743
- && table.primaryKeys.includes(col.name)) {
134744
- const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
134745
- return generator;
134746
- }
134747
- let minValue;
134748
- let maxValue;
134749
- if (['smallserial', 'serial', 'bigserial'].includes(col.columnType)) {
134750
- minValue = 1;
134751
- if (col.columnType === 'smallserial') {
134752
- // 2^16 / 2 - 1, 2 bytes
134753
- maxValue = 32767;
134754
- }
134755
- else if (col.columnType === 'serial') {
134756
- // 2^32 / 2 - 1, 4 bytes
134757
- maxValue = 2147483647;
134758
- }
134759
- else if (col.columnType === 'bigserial') {
134760
- // 2^64 / 2 - 1, 8 bytes
134761
- minValue = BigInt(1);
134762
- maxValue = BigInt('9223372036854775807');
134763
- }
134764
- }
134765
- else if (['smallint', 'integer', 'bigint'].includes(col.columnType)) {
134766
- if (col.columnType === 'smallint') {
134767
- // 2^16 / 2 - 1, 2 bytes
134768
- minValue = -32768;
134769
- maxValue = 32767;
134770
- }
134771
- else if (col.columnType === 'integer') {
134772
- // 2^32 / 2 - 1, 4 bytes
134773
- minValue = -2147483648;
134774
- maxValue = 2147483647;
134775
- }
134776
- else if (col.columnType.includes('bigint')) {
134777
- if (col.dataType === 'bigint') {
134778
- // 2^64 / 2 - 1, 8 bytes
134779
- minValue = BigInt('-9223372036854775808');
134780
- maxValue = BigInt('9223372036854775807');
134781
- }
134782
- else {
134783
- // if (col.dataType === 'number')
134784
- // if you’re expecting values above 2^31 but below 2^53
134785
- minValue = -9007199254740991;
134786
- maxValue = 9007199254740991;
134787
- }
134788
- }
134789
- }
134790
- if (['smallint', 'integer', 'bigint'].includes(col.columnType)) {
134791
- const generator = new generatorsMap.GenerateInt[0]({
134792
- minValue,
134793
- maxValue,
134794
- });
134795
- return generator;
134796
- }
134797
- if (['smallserial', 'serial', 'bigserial'].includes(col.columnType)) {
134798
- const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
134799
- generator.maxValue = maxValue;
134800
- return generator;
134801
- }
134802
- // NUMBER(real, double, decimal, numeric)
134803
- if (col.columnType === 'real'
134804
- || col.columnType === 'double precision'
134805
- || col.columnType.match(/^decimal(\(\d{1,6}(, ?-?\d{0,5})?\))?$/) !== null
134806
- || col.columnType.match(/^numeric(\(\d{1,6}(, ?-?\d{0,5})?\))?$/) !== null) {
134807
- if (col.typeParams.precision !== undefined) {
134808
- const precision = col.typeParams.precision;
134809
- const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
134810
- const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
134811
- const generator = new generatorsMap.GenerateNumber[0]({
134812
- minValue: -maxAbsoluteValue,
134813
- maxValue: maxAbsoluteValue,
134814
- precision: Math.pow(10, scale),
134815
- });
134816
- return generator;
134817
- }
134818
- const generator = new generatorsMap.GenerateNumber[0]();
134819
- return generator;
134820
- }
134821
- // STRING
134822
- if ((col.columnType === 'text'
134823
- || col.columnType.match(/^varchar(\(\d+\))?$/) !== null
134824
- || col.columnType.match(/^char(\(\d+\))?$/) !== null)
134825
- && table.primaryKeys.includes(col.name)) {
134826
- const generator = new generatorsMap.GenerateUniqueString[0]();
134827
- return generator;
134828
- }
134829
- if ((col.columnType === 'text'
134830
- || col.columnType.match(/^varchar(\(\d+\))?$/) !== null
134831
- || col.columnType.match(/^char(\(\d+\))?$/) !== null)
134832
- && col.name.toLowerCase().includes('name')) {
134833
- const generator = new generatorsMap.GenerateFirstName[0]();
134834
- return generator;
134835
- }
134836
- if ((col.columnType === 'text'
134837
- || col.columnType.match(/^varchar(\(\d+\))?$/) !== null
134838
- || col.columnType.match(/^char(\(\d+\))?$/) !== null)
134839
- && col.name.toLowerCase().includes('email')) {
134840
- const generator = new generatorsMap.GenerateEmail[0]();
134841
- return generator;
134842
- }
134843
- if (col.columnType === 'text'
134844
- || col.columnType.match(/^varchar(\(\d+\))?$/) !== null
134845
- || col.columnType.match(/^char(\(\d+\))?$/) !== null) {
134846
- const generator = new generatorsMap.GenerateString[0]();
134847
- return generator;
134848
- }
134849
- // UUID
134850
- if (col.columnType === 'uuid') {
134851
- const generator = new generatorsMap.GenerateUUID[0]();
134852
- return generator;
134853
- }
134854
- // BOOLEAN
134855
- if (col.columnType === 'boolean') {
134856
- const generator = new generatorsMap.GenerateBoolean[0]();
134857
- return generator;
134858
- }
134859
- // DATE, TIME, TIMESTAMP
134860
- if (col.columnType === 'date') {
134861
- const generator = new generatorsMap.GenerateDate[0]();
134862
- return generator;
134863
- }
134864
- if (col.columnType.match(/^time((\(\d+\))|( with time zone))?$/) !== null) {
134865
- const generator = new generatorsMap.GenerateTime[0]();
134866
- return generator;
134867
- }
134868
- if (col.columnType.match(/^timestamp((\(\d+\))|( with time zone))?$/) !== null) {
134869
- const generator = new generatorsMap.GenerateTimestamp[0]();
134870
- return generator;
134871
- }
134872
- // JSON, JSONB
134873
- if (col.columnType === 'json' || col.columnType === 'jsonb') {
134874
- const generator = new generatorsMap.GenerateJson[0]();
134875
- return generator;
134876
- }
134877
- // if (col.columnType === "jsonb") {
134878
- // const generator = new GenerateJsonb({});
134879
- // return generator;
134880
- // }
134881
- // ENUM
134882
- if (col.enumValues !== undefined) {
134883
- const generator = new generatorsMap.GenerateEnum[0]({
134884
- enumValues: col.enumValues,
134885
- });
134886
- return generator;
134887
- }
134888
- // INTERVAL
134889
- if (col.columnType.match(/^interval( .+)?$/) !== null) {
134890
- if (col.columnType === 'interval') {
134891
- const generator = new generatorsMap.GenerateInterval[0]();
134892
- return generator;
134893
- }
134894
- const fields = col.columnType.replace('interval ', '');
134895
- const generator = new generatorsMap.GenerateInterval[0]({ fields });
134896
- return generator;
134897
- }
134898
- // POINT, LINE
134899
- if (col.columnType === 'point') {
134900
- const generator = new generatorsMap.GeneratePoint[0]();
134901
- return generator;
134902
- }
134903
- if (col.columnType === 'line') {
134904
- const generator = new generatorsMap.GenerateLine[0]();
134905
- return generator;
134906
- }
134907
- if (col.hasDefault && col.default !== undefined) {
134908
- const generator = new generatorsMap.GenerateDefault[0]({
134909
- defaultValue: col.default,
134910
- });
134911
- return generator;
134912
- }
134913
- return;
134914
- };
134915
- const generator = pickGenerator(table, col);
134916
- if (generator !== undefined) {
134917
- generator.isUnique = col.isUnique;
134918
- generator.dataType = col.dataType;
134919
- generator.stringLength = col.typeParams.length;
134920
- }
134921
- return generator;
134922
- };
134923
- selectGeneratorForMysqlColumn = (table, col) => {
134924
- const pickGenerator = (table, col) => {
134925
- // INT ------------------------------------------------------------------------------------------------------------
134926
- if ((col.columnType === 'serial'
134927
- || ['tinyint', 'smallint', 'mediumint', 'int', 'bigint'].includes(col.columnType))
134928
- && table.primaryKeys.includes(col.name)) {
134929
- const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
134930
- return generator;
134931
- }
134932
- let minValue;
134933
- let maxValue;
134934
- if (col.columnType === 'serial') {
134935
- // 2^64 % 2 - 1, 8 bytes
134936
- minValue = BigInt(0);
134937
- maxValue = BigInt('9223372036854775807');
134938
- }
134939
- else if (['tinyint', 'smallint', 'mediumint', 'int', 'bigint'].includes(col.columnType)) {
134940
- if (col.columnType === 'tinyint') {
134941
- // 2^8 / 2 - 1, 1 bytes
134942
- minValue = -128;
134943
- maxValue = 127;
134944
- }
134945
- else if (col.columnType === 'smallint') {
134946
- // 2^16 / 2 - 1, 2 bytes
134947
- minValue = -32768;
134948
- maxValue = 32767;
134949
- }
134950
- else if (col.columnType === 'mediumint') {
134951
- // 2^16 / 2 - 1, 2 bytes
134952
- minValue = -8388608;
134953
- maxValue = 8388607;
134954
- }
134955
- else if (col.columnType === 'int') {
134956
- // 2^32 / 2 - 1, 4 bytes
134957
- minValue = -2147483648;
134958
- maxValue = 2147483647;
134959
- }
134960
- else if (col.columnType === 'bigint') {
134961
- // 2^64 / 2 - 1, 8 bytes
134962
- minValue = BigInt('-9223372036854775808');
134963
- maxValue = BigInt('9223372036854775807');
134964
- }
134965
- }
134966
- if (['tinyint', 'smallint', 'mediumint', 'int', 'bigint'].includes(col.columnType)) {
134967
- const generator = new generatorsMap.GenerateInt[0]({
134968
- minValue,
134969
- maxValue,
134970
- });
134971
- return generator;
134972
- }
134973
- if (col.columnType === 'serial') {
134974
- const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
134975
- generator.maxValue = maxValue;
134976
- return generator;
134977
- }
134978
- // NUMBER(real, double, decimal, float)
134979
- if (col.columnType === 'real'
134980
- || col.columnType === 'double'
134981
- || col.columnType === 'float'
134982
- || col.columnType.startsWith('decimal')
134983
- || col.columnType.startsWith('numeric')) {
134984
- if (col.typeParams.precision !== undefined) {
134985
- const precision = col.typeParams.precision;
134986
- const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
134987
- const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
134988
- const generator = new generatorsMap.GenerateNumber[0]({
134989
- minValue: -maxAbsoluteValue,
134990
- maxValue: maxAbsoluteValue,
134991
- precision: Math.pow(10, scale),
134992
- });
134993
- return generator;
134994
- }
134995
- const generator = new generatorsMap.GenerateNumber[0]();
134996
- return generator;
134997
- }
134998
- // STRING
134999
- if ((col.columnType === 'text'
135000
- || col.columnType === 'blob'
135001
- || col.columnType.startsWith('char')
135002
- || col.columnType.startsWith('varchar')
135003
- || col.columnType.startsWith('binary')
135004
- || col.columnType.startsWith('varbinary'))
135005
- && table.primaryKeys.includes(col.name)) {
135006
- const generator = new generatorsMap.GenerateUniqueString[0]();
135007
- return generator;
135008
- }
135009
- if ((col.columnType === 'text'
135010
- || col.columnType === 'blob'
135011
- || col.columnType.startsWith('char')
135012
- || col.columnType.startsWith('varchar')
135013
- || col.columnType.startsWith('binary')
135014
- || col.columnType.startsWith('varbinary'))
135015
- && col.name.toLowerCase().includes('name')) {
135016
- const generator = new generatorsMap.GenerateFirstName[0]();
135017
- return generator;
135018
- }
135019
- if ((col.columnType === 'text'
135020
- || col.columnType === 'blob'
135021
- || col.columnType.startsWith('char')
135022
- || col.columnType.startsWith('varchar')
135023
- || col.columnType.startsWith('binary')
135024
- || col.columnType.startsWith('varbinary'))
135025
- && col.name.toLowerCase().includes('email')) {
135026
- const generator = new generatorsMap.GenerateEmail[0]();
135027
- return generator;
135028
- }
135029
- if (col.columnType === 'text'
135030
- || col.columnType === 'blob'
135031
- || col.columnType.startsWith('char')
135032
- || col.columnType.startsWith('varchar')
135033
- || col.columnType.startsWith('binary')
135034
- || col.columnType.startsWith('varbinary')) {
135035
- const generator = new generatorsMap.GenerateString[0]();
135036
- return generator;
135037
- }
135038
- // BOOLEAN
135039
- if (col.columnType === 'boolean') {
135040
- const generator = new generatorsMap.GenerateBoolean[0]();
135041
- return generator;
135042
- }
135043
- // DATE, TIME, TIMESTAMP, DATETIME, YEAR
135044
- if (col.columnType.startsWith('datetime')) {
135045
- const generator = new generatorsMap.GenerateDatetime[0]();
135046
- return generator;
135047
- }
135048
- if (col.columnType === 'date') {
135049
- const generator = new generatorsMap.GenerateDate[0]();
135050
- return generator;
135051
- }
135052
- if (col.columnType === 'time') {
135053
- const generator = new generatorsMap.GenerateTime[0]();
135054
- return generator;
135055
- }
135056
- if (col.columnType.startsWith('timestamp')) {
135057
- const generator = new generatorsMap.GenerateTimestamp[0]();
135058
- return generator;
135059
- }
135060
- if (col.columnType === 'year') {
135061
- const generator = new generatorsMap.GenerateYear[0]();
135062
- return generator;
135063
- }
135064
- // JSON
135065
- if (col.columnType === 'json') {
135066
- const generator = new generatorsMap.GenerateJson[0]();
135067
- return generator;
135068
- }
135069
- // ENUM
135070
- if (col.enumValues !== undefined) {
135071
- const generator = new generatorsMap.GenerateEnum[0]({
135072
- enumValues: col.enumValues,
135073
- });
135074
- return generator;
135075
- }
135076
- if (col.hasDefault && col.default !== undefined) {
135077
- const generator = new generatorsMap.GenerateDefault[0]({
135078
- defaultValue: col.default,
135079
- });
135080
- return generator;
135081
- }
135082
- return;
135083
- };
135084
- const generator = pickGenerator(table, col);
135085
- return generator;
135086
- };
135087
- selectGeneratorForSqlite = (table, col) => {
135088
- const pickGenerator = (table, col) => {
135089
- // int section ---------------------------------------------------------------------------------------
135090
- if ((col.columnType === 'integer' || col.columnType === 'numeric')
135091
- && table.primaryKeys.includes(col.name)) {
135092
- const generator = new generatorsMap.GenerateIntPrimaryKey[0]();
135093
- return generator;
135094
- }
135095
- if (col.columnType === 'integer' && col.dataType === 'boolean') {
135096
- const generator = new generatorsMap.GenerateBoolean[0]();
135097
- return generator;
135098
- }
135099
- if ((col.columnType === 'integer' && col.dataType === 'date')) {
135100
- const generator = new generatorsMap.GenerateTimestamp[0]();
135101
- return generator;
135102
- }
135103
- if (col.columnType === 'integer'
135104
- || (col.dataType === 'bigint' && col.columnType === 'blob')) {
135105
- const generator = new generatorsMap.GenerateInt[0]();
135106
- return generator;
135107
- }
135108
- // number section ------------------------------------------------------------------------------------
135109
- if (col.columnType.startsWith('real')
135110
- || col.columnType.startsWith('numeric')) {
135111
- if (col.typeParams.precision !== undefined) {
135112
- const precision = col.typeParams.precision;
135113
- const scale = col.typeParams.scale === undefined ? 0 : col.typeParams.scale;
135114
- const maxAbsoluteValue = Math.pow(10, precision - scale) - Math.pow(10, -scale);
135115
- const generator = new generatorsMap.GenerateNumber[0]({
135116
- minValue: -maxAbsoluteValue,
135117
- maxValue: maxAbsoluteValue,
135118
- precision: Math.pow(10, scale),
135119
- });
135120
- return generator;
135121
- }
135122
- const generator = new generatorsMap.GenerateNumber[0]();
135123
- return generator;
135124
- }
135125
- // string section ------------------------------------------------------------------------------------
135126
- if ((col.columnType.startsWith('text')
135127
- || col.columnType.startsWith('numeric')
135128
- || col.columnType.startsWith('blob'))
135129
- && table.primaryKeys.includes(col.name)) {
135130
- const generator = new generatorsMap.GenerateUniqueString[0]();
135131
- return generator;
135132
- }
135133
- if ((col.columnType.startsWith('text')
135134
- || col.columnType.startsWith('numeric')
135135
- || col.columnType.startsWith('blob'))
135136
- && col.name.toLowerCase().includes('name')) {
135137
- const generator = new generatorsMap.GenerateFirstName[0]();
135138
- return generator;
135139
- }
135140
- if ((col.columnType.startsWith('text')
135141
- || col.columnType.startsWith('numeric')
135142
- || col.columnType.startsWith('blob'))
135143
- && col.name.toLowerCase().includes('email')) {
135144
- const generator = new generatorsMap.GenerateEmail[0]();
135145
- return generator;
135146
- }
135147
- if (col.columnType.startsWith('text')
135148
- || col.columnType.startsWith('numeric')
135149
- || col.columnType.startsWith('blob')
135150
- || col.columnType.startsWith('blobbuffer')) {
135151
- const generator = new generatorsMap.GenerateString[0]();
135152
- return generator;
135153
- }
135154
- if ((col.columnType.startsWith('text') && col.dataType === 'json')
135155
- || (col.columnType.startsWith('blob') && col.dataType === 'json')) {
135156
- const generator = new generatorsMap.GenerateJson[0]();
135157
- return generator;
135158
- }
135159
- if (col.hasDefault && col.default !== undefined) {
135160
- const generator = new generatorsMap.GenerateDefault[0]({
135161
- defaultValue: col.default,
135162
- });
135163
- return generator;
135164
- }
135165
- return;
135166
- };
135167
- const generator = pickGenerator(table, col);
135168
- return generator;
135169
- };
135170
136397
  filterCyclicTables = (tablesGenerators) => {
135171
136398
  const filteredTablesGenerators = tablesGenerators.filter((tableGen) => tableGen.columnsPossibleGenerators.some((columnGen) => columnGen.isCyclic === true && columnGen.wasDefinedBefore === true));
135172
136399
  const tablesUniqueNotNullColumn = {};
@@ -135178,7 +136405,8 @@ class SeedService {
135178
136405
  throw new Error(`Table '${tableGen.tableName}' does not have primary or (unique and notNull) column. Can't seed table with cyclic relation.`);
135179
136406
  }
135180
136407
  tablesUniqueNotNullColumn[tableGen.tableName] = { uniqueNotNullColName };
135181
- filteredTablesGenerators[idx].columnsPossibleGenerators = tableGen.columnsPossibleGenerators.filter((colGen) => (colGen.isCyclic === true && colGen.wasDefinedBefore === true) || colGen.columnName === uniqueNotNullColName).map((colGen) => {
136408
+ filteredTablesGenerators[idx].columnsPossibleGenerators = tableGen.columnsPossibleGenerators.filter((colGen) => (colGen.isCyclic === true && colGen.wasDefinedBefore === true) || colGen.columnName === uniqueNotNullColName)
136409
+ .map((colGen) => {
135182
136410
  const newColGen = { ...colGen };
135183
136411
  newColGen.wasDefinedBefore = false;
135184
136412
  return newColGen;
@@ -135272,7 +136500,9 @@ class SeedService {
135272
136500
  weightedCountSeed = table.withFromTable[rel.refTable].weightedCountSeed;
135273
136501
  }
135274
136502
  // TODO: revise maybe need to select version of generator here too
135275
- genObj = new generatorsMap.GenerateValuesFromArray[0]({ values: refColumnValues });
136503
+ genObj = new generatorsMap.GenerateValuesFromArray[0]({
136504
+ values: refColumnValues,
136505
+ });
135276
136506
  genObj.notNull = tableGenerators[rel.columns[colIdx]].notNull;
135277
136507
  genObj.weightedCountSeed = weightedCountSeed;
135278
136508
  genObj.maxRepeatedValuesCount = repeatedValuesCount;
@@ -135340,7 +136570,10 @@ class SeedService {
135340
136570
  for (const columnName of Object.keys(tableGenerators)) {
135341
136571
  columnsNumber += 1;
135342
136572
  columnGenerator = tableGenerators[columnName];
136573
+ // postgres identity columns
135343
136574
  override = tableGenerators[columnName]?.generatedIdentityType === 'always' ? true : override;
136575
+ // mssql identity columns
136576
+ override = tableGenerators[columnName]?.identity === true ? true : override;
135344
136577
  columnsGenerators[columnName] = columnGenerator.generator;
135345
136578
  columnsGenerators[columnName].init({
135346
136579
  count,
@@ -135365,10 +136598,13 @@ class SeedService {
135365
136598
  else if (drizzleOrm.is(db, (mysqlCore.MySqlDatabase))) {
135366
136599
  maxParametersNumber = this.mysqlMaxParametersNumber;
135367
136600
  }
135368
- else {
135369
- // is(db, BaseSQLiteDatabase<any, any>)
136601
+ else if (drizzleOrm.is(db, (sqliteCore.BaseSQLiteDatabase))) {
135370
136602
  maxParametersNumber = this.sqliteMaxParametersNumber;
135371
136603
  }
136604
+ else {
136605
+ // is(db, MsSqlDatabase<any, any>)
136606
+ maxParametersNumber = this.mssqlMaxParametersNumber;
136607
+ }
135372
136608
  const maxBatchSize = Math.floor(maxParametersNumber / columnsNumber);
135373
136609
  batchSize = batchSize > maxBatchSize ? maxBatchSize : batchSize;
135374
136610
  if ((insertDataInDb === true || updateDataInDb === true)
@@ -135453,24 +136689,640 @@ class SeedService {
135453
136689
  .insert(schema[tableName])
135454
136690
  .values(generatedValues);
135455
136691
  }
136692
+ else if (drizzleOrm.is(db, (mssqlCore.MsSqlDatabase))) {
136693
+ let schemaDbName;
136694
+ let tableDbName;
136695
+ if (override === true) {
136696
+ const tableConfig = mssqlCore.getTableConfig(schema[tableName]);
136697
+ schemaDbName = tableConfig.schema ?? 'dbo';
136698
+ tableDbName = tableConfig.name;
136699
+ await db.execute(drizzleOrm.sql.raw(`SET IDENTITY_INSERT [${schemaDbName}].[${tableDbName}] ON;`));
136700
+ }
136701
+ await db
136702
+ .insert(schema[tableName])
136703
+ .values(generatedValues);
136704
+ if (override === true) {
136705
+ await db.execute(drizzleOrm.sql.raw(`SET IDENTITY_INSERT [${schemaDbName}].[${tableDbName}] OFF;`));
136706
+ }
136707
+ }
136708
+ else if (drizzleOrm.is(db, (cockroachCore.CockroachDatabase))) {
136709
+ const query = db
136710
+ .insert(schema[tableName])
136711
+ .values(generatedValues);
136712
+ await query;
136713
+ }
136714
+ else if (drizzleOrm.is(db, (singlestoreCore.SingleStoreDatabase))) {
136715
+ const query = db
136716
+ .insert(schema[tableName])
136717
+ .values(generatedValues);
136718
+ await query;
136719
+ }
135456
136720
  };
135457
136721
  updateDb = async ({ generatedValues, db, schema, tableName, uniqueNotNullColName, }) => {
136722
+ let values = generatedValues[0];
136723
+ const uniqueNotNullColValue = values[uniqueNotNullColName];
136724
+ values = Object.fromEntries(Object.entries(values).filter(([colName]) => colName !== uniqueNotNullColName));
135458
136725
  if (drizzleOrm.is(db, (pgCore.PgDatabase))) {
135459
136726
  const table = schema[tableName];
135460
136727
  const uniqueNotNullCol = table[uniqueNotNullColName];
135461
- await db.update(table).set(generatedValues[0]).where(drizzleOrm.eq(uniqueNotNullCol, generatedValues[0][uniqueNotNullColName]));
136728
+ await db.update(table).set(values).where(drizzleOrm.eq(uniqueNotNullCol, uniqueNotNullColValue));
135462
136729
  }
135463
136730
  else if (drizzleOrm.is(db, (mysqlCore.MySqlDatabase))) {
135464
136731
  const table = schema[tableName];
135465
- await db.update(table).set(generatedValues[0]).where(drizzleOrm.eq(table[uniqueNotNullColName], generatedValues[0][uniqueNotNullColName]));
136732
+ await db.update(table).set(values).where(drizzleOrm.eq(table[uniqueNotNullColName], uniqueNotNullColValue));
135466
136733
  }
135467
136734
  else if (drizzleOrm.is(db, (sqliteCore.BaseSQLiteDatabase))) {
135468
136735
  const table = schema[tableName];
135469
- await db.update(table).set(generatedValues[0]).where(drizzleOrm.eq(table[uniqueNotNullColName], generatedValues[0][uniqueNotNullColName]));
136736
+ await db.update(table).set(values).where(drizzleOrm.eq(table[uniqueNotNullColName], uniqueNotNullColValue));
136737
+ }
136738
+ else if (drizzleOrm.is(db, (mssqlCore.MsSqlDatabase))) {
136739
+ const table = schema[tableName];
136740
+ await db.update(table).set(values).where(drizzleOrm.eq(table[uniqueNotNullColName], uniqueNotNullColValue));
136741
+ }
136742
+ else if (drizzleOrm.is(db, (cockroachCore.CockroachDatabase))) {
136743
+ const table = schema[tableName];
136744
+ await db.update(table).set(values).where(drizzleOrm.eq(table[uniqueNotNullColName], uniqueNotNullColValue));
136745
+ }
136746
+ else if (drizzleOrm.is(db, (singlestoreCore.SingleStoreDatabase))) {
136747
+ const table = schema[tableName];
136748
+ await db.update(table).set(values).where(drizzleOrm.eq(table[uniqueNotNullColName], uniqueNotNullColValue));
135470
136749
  }
135471
136750
  };
135472
136751
  }
135473
136752
 
136753
+ // Cockroach-----------------------------------------------------------------------------------------------------------
136754
+ const resetCockroach = async (db, cockroachTables) => {
136755
+ const tablesToTruncate = Object.entries(cockroachTables).map(([_, table]) => {
136756
+ const config = cockroachCore.getTableConfig(table);
136757
+ config.schema = config.schema === undefined ? 'public' : config.schema;
136758
+ return `"${config.schema}"."${config.name}"`;
136759
+ });
136760
+ await db.execute(drizzleOrm.sql.raw(`truncate ${tablesToTruncate.join(',')} cascade;`));
136761
+ };
136762
+ const filterCockroachSchema = (schema) => {
136763
+ const cockroachSchema = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], cockroachCore.CockroachTable) || drizzleOrm.is(keyValue[1], _relations.Relations)));
136764
+ const cockroachTables = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], cockroachCore.CockroachTable)));
136765
+ return { cockroachSchema, cockroachTables };
136766
+ };
136767
+ const seedCockroach = async (db, schema, options = {}, refinements) => {
136768
+ const seedService = new SeedService();
136769
+ const { cockroachSchema, cockroachTables } = filterCockroachSchema(schema);
136770
+ const { tables, relations } = getSchemaInfo(cockroachSchema, cockroachTables, mapCockroachTable);
136771
+ const generatedTablesGenerators = seedService.generatePossibleGenerators('cockroach', tables, relations, refinements, options);
136772
+ const preserveCyclicTablesData = relations.some((rel) => rel.isCyclic === true);
136773
+ const tablesValues = await seedService.generateTablesValues(relations, generatedTablesGenerators, db, cockroachTables, { ...options, preserveCyclicTablesData });
136774
+ const { filteredTablesGenerators, tablesUniqueNotNullColumn } = seedService.filterCyclicTables(generatedTablesGenerators);
136775
+ const updateDataInDb = filteredTablesGenerators.length === 0 ? false : true;
136776
+ await seedService.generateTablesValues(relations, filteredTablesGenerators, db, cockroachTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
136777
+ };
136778
+ const mapCockroachTable = (tableConfig, dbToTsTableNamesMap, dbToTsColumnNamesMap) => {
136779
+ const getAllBaseColumns = (baseColumn) => {
136780
+ const baseColumnResult = {
136781
+ name: baseColumn.name,
136782
+ columnType: baseColumn.getSQLType(),
136783
+ typeParams: getTypeParams(baseColumn.getSQLType()),
136784
+ dataType: baseColumn.dataType.split(' ')[0],
136785
+ size: baseColumn.length,
136786
+ hasDefault: baseColumn.hasDefault,
136787
+ enumValues: baseColumn.enumValues,
136788
+ default: baseColumn.default,
136789
+ isUnique: baseColumn.isUnique,
136790
+ notNull: baseColumn.notNull,
136791
+ primary: baseColumn.primary,
136792
+ baseColumn: baseColumn.baseColumn === undefined ? undefined : getAllBaseColumns(baseColumn.baseColumn),
136793
+ };
136794
+ return baseColumnResult;
136795
+ };
136796
+ const getTypeParams = (sqlType) => {
136797
+ // get type params
136798
+ const typeParams = {};
136799
+ // handle dimensions
136800
+ if (sqlType.includes('[')) {
136801
+ const match = sqlType.match(/\[\w*]/g);
136802
+ if (match) {
136803
+ typeParams['dimensions'] = match.length;
136804
+ }
136805
+ }
136806
+ if (sqlType.startsWith('numeric')
136807
+ || sqlType.startsWith('decimal')
136808
+ || sqlType.startsWith('double precision')
136809
+ || sqlType.startsWith('real')) {
136810
+ const match = sqlType.match(/\((\d+), *(\d+)\)/);
136811
+ if (match) {
136812
+ typeParams['precision'] = Number(match[1]);
136813
+ typeParams['scale'] = Number(match[2]);
136814
+ }
136815
+ }
136816
+ else if (sqlType.startsWith('varchar')
136817
+ || sqlType.startsWith('char')
136818
+ || sqlType.startsWith('bit')
136819
+ || sqlType.startsWith('vector')
136820
+ || sqlType.startsWith('time')
136821
+ || sqlType.startsWith('timestamp')
136822
+ || sqlType.startsWith('interval')) {
136823
+ const match = sqlType.match(/\((\d+)\)/);
136824
+ if (match) {
136825
+ typeParams['length'] = Number(match[1]);
136826
+ }
136827
+ }
136828
+ return typeParams;
136829
+ };
136830
+ // console.log(tableConfig.columns);
136831
+ return {
136832
+ name: dbToTsTableNamesMap[tableConfig.name],
136833
+ columns: tableConfig.columns.map((column) => ({
136834
+ name: dbToTsColumnNamesMap[column.name],
136835
+ columnType: column.getSQLType(),
136836
+ typeParams: getTypeParams(column.getSQLType()),
136837
+ dataType: column.dataType.split(' ')[0],
136838
+ size: column.length,
136839
+ hasDefault: column.hasDefault,
136840
+ default: column.default,
136841
+ enumValues: column.enumValues,
136842
+ isUnique: column.isUnique,
136843
+ notNull: column.notNull,
136844
+ primary: column.primary,
136845
+ generatedIdentityType: column.generatedIdentity?.type,
136846
+ baseColumn: (column.baseColumn === undefined)
136847
+ ? undefined
136848
+ : getAllBaseColumns(column.baseColumn),
136849
+ })),
136850
+ primaryKeys: tableConfig.columns
136851
+ .filter((column) => column.primary)
136852
+ .map((column) => dbToTsColumnNamesMap[column.name]),
136853
+ };
136854
+ };
136855
+
136856
+ // MySql-----------------------------------------------------------------------------------------------------
136857
+ const resetMsSql = async (db, schema) => {
136858
+ const tablesToTruncate = Object.entries(schema).map(([_tsTableName, table]) => {
136859
+ const tableConfig = mssqlCore.getTableConfig(table);
136860
+ return { dbName: tableConfig.name, dbSchema: tableConfig.schema ?? 'dbo' };
136861
+ });
136862
+ const allFkConstraints = {};
136863
+ for (const table of tablesToTruncate) {
136864
+ const gatherTableRelatedFkConstraints = `
136865
+ DECLARE @objectId INT
136866
+ = OBJECT_ID( QUOTENAME('${table.dbSchema}') + '.' + QUOTENAME('${table.dbName}') );
136867
+
136868
+ SELECT
136869
+ fk.name AS fkName,
136870
+ OBJECT_SCHEMA_NAME(fk.parent_object_id) AS parentSchema,
136871
+ OBJECT_NAME(fk.parent_object_id) AS parentTable,
136872
+ OBJECT_SCHEMA_NAME(fk.referenced_object_id) AS referencedSchema,
136873
+ OBJECT_NAME(fk.referenced_object_id) AS referencedTable,
136874
+ -- fkc.constraint_column_id AS Column_Ordinal,
136875
+ pc.name AS parentColumn,
136876
+ rc.name AS referencedColumn,
136877
+ fk.delete_referential_action_desc AS onDeleteAction,
136878
+ fk.update_referential_action_desc AS onUpdateAction,
136879
+ CASE
136880
+ WHEN fk.parent_object_id = @objectId THEN 'outbound' -- your table → another table
136881
+ ELSE 'inbound' -- another table → your table
136882
+ END AS relation
136883
+ FROM sys.foreign_keys AS fk
136884
+ JOIN sys.foreign_key_columns fkc
136885
+ ON fk.object_id = fkc.constraint_object_id
136886
+ JOIN sys.columns pc
136887
+ ON fkc.parent_object_id = pc.object_id
136888
+ AND fkc.parent_column_id = pc.column_id
136889
+ JOIN sys.columns rc
136890
+ ON fkc.referenced_object_id = rc.object_id
136891
+ AND fkc.referenced_column_id = rc.column_id
136892
+ WHERE fk.parent_object_id = @objectId
136893
+ OR fk.referenced_object_id = @objectId
136894
+ ORDER BY relation, fkName;
136895
+ `;
136896
+ const rawRes = await db.execute(drizzleOrm.sql.raw(gatherTableRelatedFkConstraints));
136897
+ const res = rawRes.recordset;
136898
+ const tableRelatedFkConstraints = {};
136899
+ for (const fkInfo of res) {
136900
+ if (tableRelatedFkConstraints[fkInfo.fkName] === undefined) {
136901
+ const { parentColumn: _, referencedColumn: __, ...filteredFkInfo } = fkInfo;
136902
+ tableRelatedFkConstraints[fkInfo.fkName] = {
136903
+ ...filteredFkInfo,
136904
+ parentColumns: res.filter(({ fkName }) => fkName === fkInfo.fkName).map(({ parentColumn }) => parentColumn),
136905
+ referencedColumns: res.filter(({ fkName }) => fkName === fkInfo.fkName).map(({ referencedColumn }) => referencedColumn),
136906
+ };
136907
+ }
136908
+ }
136909
+ allFkConstraints[`${table.dbSchema}.${table.dbName}`] = tableRelatedFkConstraints;
136910
+ // drop all table related fk constraints
136911
+ for (const fkInfo of Object.values(tableRelatedFkConstraints)) {
136912
+ const dropFkConstraints = `ALTER TABLE [${fkInfo.parentSchema}].[${fkInfo.parentTable}] DROP CONSTRAINT [${fkInfo.fkName}];`;
136913
+ await db.execute(drizzleOrm.sql.raw(dropFkConstraints));
136914
+ }
136915
+ // truncating
136916
+ const truncateTable = `truncate table [${table.dbSchema}].[${table.dbName}];`;
136917
+ await db.execute(drizzleOrm.sql.raw(truncateTable));
136918
+ }
136919
+ // add all table related fk constraints
136920
+ for (const table of tablesToTruncate) {
136921
+ const tableRelatedFkConstraints = allFkConstraints[`${table.dbSchema}.${table.dbName}`];
136922
+ for (const fkInfo of Object.values(tableRelatedFkConstraints)) {
136923
+ const addFkConstraints = `
136924
+ ALTER TABLE [${fkInfo.parentSchema}].[${fkInfo.parentTable}]
136925
+ ADD CONSTRAINT [${fkInfo.fkName}]
136926
+ FOREIGN KEY(${fkInfo.parentColumns.map((colName) => `[${colName}]`).join(',')})
136927
+ REFERENCES [${fkInfo.referencedSchema}].[${fkInfo.referencedTable}] (${fkInfo.referencedColumns.map((colName) => `[${colName}]`).join(',')})
136928
+ ON DELETE ${fkInfo.onDeleteAction.split('_').join(' ')}
136929
+ ON UPDATE ${fkInfo.onUpdateAction.split('_').join(' ')};
136930
+ `;
136931
+ await db.execute(drizzleOrm.sql.raw(addFkConstraints));
136932
+ }
136933
+ }
136934
+ };
136935
+ const filterMsSqlTables = (schema) => {
136936
+ const mssqlSchema = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], mssqlCore.MsSqlTable) || drizzleOrm.is(keyValue[1], _relations.Relations)));
136937
+ const mssqlTables = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], mssqlCore.MsSqlTable)));
136938
+ return { mssqlSchema, mssqlTables };
136939
+ };
136940
+ const seedMsSql = async (db, schema, options = {}, refinements) => {
136941
+ const { mssqlSchema, mssqlTables } = filterMsSqlTables(schema);
136942
+ const { tables, relations } = getSchemaInfo(mssqlSchema, mssqlTables, mapMsSqlTable);
136943
+ const seedService = new SeedService();
136944
+ const generatedTablesGenerators = seedService.generatePossibleGenerators('mssql', tables, relations, refinements, options);
136945
+ const preserveCyclicTablesData = relations.some((rel) => rel.isCyclic === true);
136946
+ const tablesValues = await seedService.generateTablesValues(relations, generatedTablesGenerators, db, mssqlTables, { ...options, preserveCyclicTablesData });
136947
+ const { filteredTablesGenerators, tablesUniqueNotNullColumn } = seedService.filterCyclicTables(generatedTablesGenerators);
136948
+ const updateDataInDb = filteredTablesGenerators.length === 0 ? false : true;
136949
+ await seedService.generateTablesValues(relations, filteredTablesGenerators, db, mssqlTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
136950
+ };
136951
+ const mapMsSqlTable = (tableConfig, dbToTsTableNamesMap, dbToTsColumnNamesMap) => {
136952
+ // TODO: rewrite
136953
+ const getTypeParams = (sqlType) => {
136954
+ // get type params and set only type
136955
+ const typeParams = {};
136956
+ if (sqlType.startsWith('decimal')
136957
+ || sqlType.startsWith('real')
136958
+ || sqlType.startsWith('float')) {
136959
+ const match = sqlType.match(/\((\d+), *(\d+)\)/);
136960
+ if (match) {
136961
+ typeParams['precision'] = Number(match[1]);
136962
+ typeParams['scale'] = Number(match[2]);
136963
+ }
136964
+ }
136965
+ else if (sqlType.startsWith('char')
136966
+ || sqlType.startsWith('varchar')
136967
+ || sqlType.startsWith('binary')
136968
+ || sqlType.startsWith('varbinary')) {
136969
+ const match = sqlType.match(/\((\d+)\)/);
136970
+ if (match) {
136971
+ typeParams['length'] = Number(match[1]);
136972
+ }
136973
+ }
136974
+ return typeParams;
136975
+ };
136976
+ return {
136977
+ name: dbToTsTableNamesMap[tableConfig.name],
136978
+ columns: tableConfig.columns.map((column) => ({
136979
+ name: dbToTsColumnNamesMap[column.name],
136980
+ columnType: column.getSQLType(),
136981
+ typeParams: getTypeParams(column.getSQLType()),
136982
+ dataType: column.dataType.split(' ')[0],
136983
+ hasDefault: column.hasDefault,
136984
+ default: column.default,
136985
+ enumValues: column.enumValues,
136986
+ isUnique: column.isUnique,
136987
+ notNull: column.notNull,
136988
+ primary: column.primary,
136989
+ identity: column.identity ? true : false,
136990
+ })),
136991
+ primaryKeys: tableConfig.columns
136992
+ .filter((column) => column.primary)
136993
+ .map((column) => dbToTsColumnNamesMap[column.name]),
136994
+ };
136995
+ };
136996
+
136997
+ // MySql-----------------------------------------------------------------------------------------------------
136998
+ const resetMySql = async (db, schema) => {
136999
+ const tablesToTruncate = Object.entries(schema).map(([_tsTableName, table]) => {
137000
+ const dbTableName = drizzleOrm.getTableName(table);
137001
+ return dbTableName;
137002
+ });
137003
+ await db.execute(drizzleOrm.sql.raw('SET FOREIGN_KEY_CHECKS = 0;'));
137004
+ for (const tableName of tablesToTruncate) {
137005
+ const sqlQuery = `truncate \`${tableName}\`;`;
137006
+ await db.execute(drizzleOrm.sql.raw(sqlQuery));
137007
+ }
137008
+ await db.execute(drizzleOrm.sql.raw('SET FOREIGN_KEY_CHECKS = 1;'));
137009
+ };
137010
+ const filterMysqlTables = (schema) => {
137011
+ const mysqlSchema = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], mysqlCore.MySqlTable) || drizzleOrm.is(keyValue[1], _relations.Relations)));
137012
+ const mysqlTables = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], mysqlCore.MySqlTable)));
137013
+ return { mysqlSchema, mysqlTables };
137014
+ };
137015
+ const seedMySql = async (db, schema, options = {}, refinements) => {
137016
+ const { mysqlSchema, mysqlTables } = filterMysqlTables(schema);
137017
+ const { tables, relations } = getSchemaInfo(mysqlSchema, mysqlTables, mapMySqlTable);
137018
+ const seedService = new SeedService();
137019
+ const generatedTablesGenerators = seedService.generatePossibleGenerators('mysql', tables, relations, refinements, options);
137020
+ const preserveCyclicTablesData = relations.some((rel) => rel.isCyclic === true);
137021
+ const tablesValues = await seedService.generateTablesValues(relations, generatedTablesGenerators, db, mysqlTables, { ...options, preserveCyclicTablesData });
137022
+ const { filteredTablesGenerators, tablesUniqueNotNullColumn } = seedService.filterCyclicTables(generatedTablesGenerators);
137023
+ const updateDataInDb = filteredTablesGenerators.length === 0 ? false : true;
137024
+ await seedService.generateTablesValues(relations, filteredTablesGenerators, db, mysqlTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
137025
+ };
137026
+ const mapMySqlTable = (tableConfig, dbToTsTableNamesMap, dbToTsColumnNamesMap) => {
137027
+ const getTypeParams = (sqlType) => {
137028
+ // get type params and set only type
137029
+ const typeParams = {};
137030
+ if (sqlType.startsWith('decimal')
137031
+ || sqlType.startsWith('real')
137032
+ || sqlType.startsWith('double')
137033
+ || sqlType.startsWith('float')) {
137034
+ const match = sqlType.match(/\((\d+), *(\d+)\)/);
137035
+ if (match) {
137036
+ typeParams['precision'] = Number(match[1]);
137037
+ typeParams['scale'] = Number(match[2]);
137038
+ }
137039
+ }
137040
+ else if (sqlType.startsWith('char')
137041
+ || sqlType.startsWith('varchar')
137042
+ || sqlType.startsWith('binary')
137043
+ || sqlType.startsWith('varbinary')) {
137044
+ const match = sqlType.match(/\((\d+)\)/);
137045
+ if (match) {
137046
+ typeParams['length'] = Number(match[1]);
137047
+ }
137048
+ }
137049
+ return typeParams;
137050
+ };
137051
+ return {
137052
+ name: dbToTsTableNamesMap[tableConfig.name],
137053
+ columns: tableConfig.columns.map((column) => ({
137054
+ name: dbToTsColumnNamesMap[column.name],
137055
+ columnType: column.getSQLType(),
137056
+ typeParams: getTypeParams(column.getSQLType()),
137057
+ dataType: column.dataType.split(' ')[0],
137058
+ hasDefault: column.hasDefault,
137059
+ default: column.default,
137060
+ enumValues: column.enumValues,
137061
+ isUnique: column.isUnique,
137062
+ notNull: column.notNull,
137063
+ primary: column.primary,
137064
+ })),
137065
+ primaryKeys: tableConfig.columns
137066
+ .filter((column) => column.primary)
137067
+ .map((column) => dbToTsColumnNamesMap[column.name]),
137068
+ };
137069
+ };
137070
+
137071
+ // Postgres-----------------------------------------------------------------------------------------------------------
137072
+ const resetPostgres = async (db, pgTables) => {
137073
+ const tablesToTruncate = Object.entries(pgTables).map(([_, table]) => {
137074
+ const config = pgCore.getTableConfig(table);
137075
+ config.schema = config.schema === undefined ? 'public' : config.schema;
137076
+ return `"${config.schema}"."${config.name}"`;
137077
+ });
137078
+ await db.execute(drizzleOrm.sql.raw(`truncate ${tablesToTruncate.join(',')} cascade;`));
137079
+ };
137080
+ const filterPgSchema = (schema) => {
137081
+ const pgSchema = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], pgCore.PgTable) || drizzleOrm.is(keyValue[1], _relations.Relations)));
137082
+ const pgTables = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], pgCore.PgTable)));
137083
+ return { pgSchema, pgTables };
137084
+ };
137085
+ const seedPostgres = async (db, schema, options = {}, refinements) => {
137086
+ const seedService = new SeedService();
137087
+ const { pgSchema, pgTables } = filterPgSchema(schema);
137088
+ const { tables, relations } = getSchemaInfo(pgSchema, pgTables, mapPgTable);
137089
+ // const { tables, relations } = getPostgresInfo(pgSchema, pgTables);
137090
+ const generatedTablesGenerators = seedService.generatePossibleGenerators('postgresql', tables, relations, refinements, options);
137091
+ const preserveCyclicTablesData = relations.some((rel) => rel.isCyclic === true);
137092
+ const tablesValues = await seedService.generateTablesValues(relations, generatedTablesGenerators, db, pgTables, { ...options, preserveCyclicTablesData });
137093
+ const { filteredTablesGenerators, tablesUniqueNotNullColumn } = seedService.filterCyclicTables(generatedTablesGenerators);
137094
+ const updateDataInDb = filteredTablesGenerators.length === 0 ? false : true;
137095
+ await seedService.generateTablesValues(relations, filteredTablesGenerators, db, pgTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
137096
+ };
137097
+ const mapPgTable = (tableConfig, dbToTsTableNamesMap, dbToTsColumnNamesMap) => {
137098
+ const getAllBaseColumns = (baseColumn) => {
137099
+ const baseColumnResult = {
137100
+ name: baseColumn.name,
137101
+ columnType: baseColumn.getSQLType(),
137102
+ typeParams: getTypeParams(baseColumn.getSQLType()),
137103
+ dataType: baseColumn.dataType.split(' ')[0],
137104
+ size: baseColumn.length,
137105
+ hasDefault: baseColumn.hasDefault,
137106
+ enumValues: baseColumn.enumValues,
137107
+ default: baseColumn.default,
137108
+ isUnique: baseColumn.isUnique,
137109
+ notNull: baseColumn.notNull,
137110
+ primary: baseColumn.primary,
137111
+ baseColumn: baseColumn.baseColumn === undefined ? undefined : getAllBaseColumns(baseColumn.baseColumn),
137112
+ };
137113
+ return baseColumnResult;
137114
+ };
137115
+ const getTypeParams = (sqlType) => {
137116
+ // get type params
137117
+ const typeParams = {};
137118
+ // handle dimensions
137119
+ if (sqlType.includes('[')) {
137120
+ const match = sqlType.match(/\[\w*]/g);
137121
+ if (match) {
137122
+ typeParams['dimensions'] = match.length;
137123
+ }
137124
+ }
137125
+ if (sqlType.startsWith('numeric')
137126
+ || sqlType.startsWith('decimal')
137127
+ || sqlType.startsWith('double precision')
137128
+ || sqlType.startsWith('real')) {
137129
+ const match = sqlType.match(/\((\d+), *(\d+)\)/);
137130
+ if (match) {
137131
+ typeParams['precision'] = Number(match[1]);
137132
+ typeParams['scale'] = Number(match[2]);
137133
+ }
137134
+ }
137135
+ else if (sqlType.startsWith('varchar')
137136
+ || sqlType.startsWith('bpchar')
137137
+ || sqlType.startsWith('char')
137138
+ || sqlType.startsWith('bit')
137139
+ || sqlType.startsWith('vector')
137140
+ || sqlType.startsWith('time')
137141
+ || sqlType.startsWith('timestamp')
137142
+ || sqlType.startsWith('interval')) {
137143
+ const match = sqlType.match(/\((\d+)\)/);
137144
+ if (match) {
137145
+ typeParams['length'] = Number(match[1]);
137146
+ }
137147
+ }
137148
+ return typeParams;
137149
+ };
137150
+ return {
137151
+ name: dbToTsTableNamesMap[tableConfig.name],
137152
+ columns: tableConfig.columns.map((column) => ({
137153
+ name: dbToTsColumnNamesMap[column.name],
137154
+ columnType: column.getSQLType(),
137155
+ typeParams: getTypeParams(column.getSQLType()),
137156
+ dataType: column.dataType.split(' ')[0],
137157
+ size: column.length,
137158
+ hasDefault: column.hasDefault,
137159
+ default: column.default,
137160
+ enumValues: column.enumValues,
137161
+ isUnique: column.isUnique,
137162
+ notNull: column.notNull,
137163
+ primary: column.primary,
137164
+ generatedIdentityType: column.generatedIdentity?.type,
137165
+ baseColumn: (column.baseColumn === undefined)
137166
+ ? undefined
137167
+ : getAllBaseColumns(column.baseColumn),
137168
+ })),
137169
+ primaryKeys: tableConfig.columns
137170
+ .filter((column) => column.primary)
137171
+ .map((column) => dbToTsColumnNamesMap[column.name]),
137172
+ };
137173
+ };
137174
+
137175
+ // SingleStore-----------------------------------------------------------------------------------------------------
137176
+ const resetSingleStore = async (db, schema) => {
137177
+ const tablesToTruncate = Object.entries(schema).map(([_tsTableName, table]) => {
137178
+ const dbTableName = drizzleOrm.getTableName(table);
137179
+ return dbTableName;
137180
+ });
137181
+ await db.execute(drizzleOrm.sql.raw('SET FOREIGN_KEY_CHECKS = 0;'));
137182
+ for (const tableName of tablesToTruncate) {
137183
+ const sqlQuery = `truncate \`${tableName}\`;`;
137184
+ await db.execute(drizzleOrm.sql.raw(sqlQuery));
137185
+ }
137186
+ await db.execute(drizzleOrm.sql.raw('SET FOREIGN_KEY_CHECKS = 1;'));
137187
+ };
137188
+ const filterSingleStoreTables = (schema) => {
137189
+ const singleStoreSchema = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], singlestoreCore.SingleStoreTable) || drizzleOrm.is(keyValue[1], _relations.Relations)));
137190
+ const singleStoreTables = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], singlestoreCore.SingleStoreTable)));
137191
+ return { singleStoreSchema, singleStoreTables };
137192
+ };
137193
+ const seedSingleStore = async (db, schema, options = {}, refinements) => {
137194
+ const { singleStoreSchema, singleStoreTables } = filterSingleStoreTables(schema);
137195
+ const { tables, relations } = getSchemaInfo(singleStoreSchema, singleStoreTables, mapSingleStoreTable);
137196
+ const seedService = new SeedService();
137197
+ const generatedTablesGenerators = seedService.generatePossibleGenerators('singlestore', tables, relations, refinements, options);
137198
+ const preserveCyclicTablesData = relations.some((rel) => rel.isCyclic === true);
137199
+ const tablesValues = await seedService.generateTablesValues(relations, generatedTablesGenerators, db, singleStoreTables, { ...options, preserveCyclicTablesData });
137200
+ const { filteredTablesGenerators, tablesUniqueNotNullColumn } = seedService.filterCyclicTables(generatedTablesGenerators);
137201
+ const updateDataInDb = filteredTablesGenerators.length === 0 ? false : true;
137202
+ await seedService.generateTablesValues(relations, filteredTablesGenerators, db, singleStoreTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
137203
+ };
137204
+ const mapSingleStoreTable = (tableConfig, dbToTsTableNamesMap, dbToTsColumnNamesMap) => {
137205
+ const getTypeParams = (sqlType) => {
137206
+ // get type params and set only type
137207
+ const typeParams = {};
137208
+ if (sqlType.startsWith('decimal')
137209
+ || sqlType.startsWith('real')
137210
+ || sqlType.startsWith('double')
137211
+ || sqlType.startsWith('float')) {
137212
+ const match = sqlType.match(/\((\d+), *(\d+)\)/);
137213
+ if (match) {
137214
+ typeParams['precision'] = Number(match[1]);
137215
+ typeParams['scale'] = Number(match[2]);
137216
+ }
137217
+ }
137218
+ else if (sqlType.startsWith('char')
137219
+ || sqlType.startsWith('varchar')
137220
+ || sqlType.startsWith('binary')
137221
+ || sqlType.startsWith('varbinary')) {
137222
+ const match = sqlType.match(/\((\d+)\)/);
137223
+ if (match) {
137224
+ typeParams['length'] = Number(match[1]);
137225
+ }
137226
+ }
137227
+ else if (sqlType.startsWith('vector')) {
137228
+ const match = sqlType.match(/\((\d+),? ?((F|I)\d{1,2})?\)/);
137229
+ if (match) {
137230
+ typeParams['length'] = Number(match[1]);
137231
+ typeParams['vectorValueType'] = match[2];
137232
+ }
137233
+ }
137234
+ return typeParams;
137235
+ };
137236
+ return {
137237
+ name: dbToTsTableNamesMap[tableConfig.name],
137238
+ columns: tableConfig.columns.map((column) => ({
137239
+ name: dbToTsColumnNamesMap[column.name],
137240
+ columnType: column.getSQLType(),
137241
+ typeParams: getTypeParams(column.getSQLType()),
137242
+ dataType: column.dataType.split(' ')[0],
137243
+ hasDefault: column.hasDefault,
137244
+ default: column.default,
137245
+ enumValues: column.enumValues,
137246
+ isUnique: column.isUnique,
137247
+ notNull: column.notNull,
137248
+ primary: column.primary,
137249
+ })),
137250
+ primaryKeys: tableConfig.columns
137251
+ .filter((column) => column.primary)
137252
+ .map((column) => dbToTsColumnNamesMap[column.name]),
137253
+ };
137254
+ };
137255
+
137256
+ // Sqlite------------------------------------------------------------------------------------------------------------------------
137257
+ const resetSqlite = async (db, schema) => {
137258
+ const tablesToTruncate = Object.entries(schema).map(([_tsTableName, table]) => {
137259
+ const dbTableName = drizzleOrm.getTableName(table);
137260
+ return dbTableName;
137261
+ });
137262
+ await db.run(drizzleOrm.sql.raw('PRAGMA foreign_keys = OFF'));
137263
+ for (const tableName of tablesToTruncate) {
137264
+ const sqlQuery = `delete from \`${tableName}\`;`;
137265
+ await db.run(drizzleOrm.sql.raw(sqlQuery));
137266
+ }
137267
+ await db.run(drizzleOrm.sql.raw('PRAGMA foreign_keys = ON'));
137268
+ };
137269
+ const filterSqliteTables = (schema) => {
137270
+ const sqliteSchema = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], sqliteCore.SQLiteTable) || drizzleOrm.is(keyValue[1], _relations.Relations)));
137271
+ const sqliteTables = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], sqliteCore.SQLiteTable)));
137272
+ return { sqliteSchema, sqliteTables };
137273
+ };
137274
+ const seedSqlite = async (db, schema, options = {}, refinements) => {
137275
+ const { sqliteSchema, sqliteTables } = filterSqliteTables(schema);
137276
+ const { tables, relations } = getSchemaInfo(sqliteSchema, sqliteTables, mapSqliteTable);
137277
+ const seedService = new SeedService();
137278
+ const generatedTablesGenerators = seedService.generatePossibleGenerators('sqlite', tables, relations, refinements, options);
137279
+ const preserveCyclicTablesData = relations.some((rel) => rel.isCyclic === true);
137280
+ const tablesValues = await seedService.generateTablesValues(relations, generatedTablesGenerators, db, sqliteTables, { ...options, preserveCyclicTablesData });
137281
+ const { filteredTablesGenerators, tablesUniqueNotNullColumn } = seedService.filterCyclicTables(generatedTablesGenerators);
137282
+ const updateDataInDb = filteredTablesGenerators.length === 0 ? false : true;
137283
+ await seedService.generateTablesValues(relations, filteredTablesGenerators, db, sqliteTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
137284
+ };
137285
+ const mapSqliteTable = (tableConfig, dbToTsTableNamesMap, dbToTsColumnNamesMap) => {
137286
+ const getTypeParams = (sqlType) => {
137287
+ // get type params and set only type
137288
+ const typeParams = {};
137289
+ if (sqlType.startsWith('decimal')) {
137290
+ const match = sqlType.match(/\((\d+), *(\d+)\)/);
137291
+ if (match) {
137292
+ typeParams['precision'] = Number(match[1]);
137293
+ typeParams['scale'] = Number(match[2]);
137294
+ }
137295
+ }
137296
+ else if (sqlType.startsWith('char')
137297
+ || sqlType.startsWith('varchar')
137298
+ || sqlType.startsWith('text')) {
137299
+ const match = sqlType.match(/\((\d+)\)/);
137300
+ if (match) {
137301
+ typeParams['length'] = Number(match[1]);
137302
+ }
137303
+ }
137304
+ return typeParams;
137305
+ };
137306
+ return {
137307
+ name: dbToTsTableNamesMap[tableConfig.name],
137308
+ columns: tableConfig.columns.map((column) => ({
137309
+ name: dbToTsColumnNamesMap[column.name],
137310
+ columnType: column.getSQLType(),
137311
+ typeParams: getTypeParams(column.getSQLType()),
137312
+ dataType: column.dataType.split(' ')[0],
137313
+ hasDefault: column.hasDefault,
137314
+ default: column.default,
137315
+ enumValues: column.enumValues,
137316
+ isUnique: column.isUnique,
137317
+ notNull: column.notNull,
137318
+ primary: column.primary,
137319
+ })),
137320
+ primaryKeys: tableConfig.columns
137321
+ .filter((column) => column.primary)
137322
+ .map((column) => dbToTsColumnNamesMap[column.name]),
137323
+ };
137324
+ };
137325
+
135474
137326
  /* eslint-disable drizzle-internal/require-entity-kind */
135475
137327
  class SeedPromise {
135476
137328
  db;
@@ -135573,7 +137425,7 @@ async function seedForDrizzleStudio({ sqlDialect, drizzleStudioObject, drizzleSt
135573
137425
  * // seeding with count and seed specified
135574
137426
  * await seed(db, schema, { count: 100000, seed: 1 });
135575
137427
  *
135576
- * // seeding using refine
137428
+ * //seeding using refine
135577
137429
  * await seed(db, schema, { count: 1000 }).refine((funcs) => ({
135578
137430
  * users: {
135579
137431
  * columns: {
@@ -135594,17 +137446,6 @@ async function seedForDrizzleStudio({ sqlDialect, drizzleStudioObject, drizzleSt
135594
137446
  * },
135595
137447
  * }));
135596
137448
  *
135597
- * // seeding while ignoring column
135598
- * await seed(db, schema).refine((funcs) => ({
135599
- * users: {
135600
- * count: 5,
135601
- * columns: {
135602
- * name: funcs.fullName(),
135603
- * photo: false, // the photo column will not be seeded, allowing the database to use its default value.
135604
- * },
135605
- * },
135606
- * }));
135607
- *
135608
137449
  * ```
135609
137450
  */
135610
137451
  function seed(db, schema, options) {
@@ -135624,8 +137465,17 @@ const seedFunc = async (db, schema, options = {}, refinements) => {
135624
137465
  else if (drizzleOrm.is(db, (sqliteCore.BaseSQLiteDatabase))) {
135625
137466
  await seedSqlite(db, schema, { ...options, version }, refinements);
135626
137467
  }
137468
+ else if (drizzleOrm.is(db, (mssqlCore.MsSqlDatabase))) {
137469
+ await seedMsSql(db, schema, { ...options, version }, refinements);
137470
+ }
137471
+ else if (drizzleOrm.is(db, (cockroachCore.CockroachDatabase))) {
137472
+ await seedCockroach(db, schema, { ...options, version }, refinements);
137473
+ }
137474
+ else if (drizzleOrm.is(db, (singlestoreCore.SingleStoreDatabase))) {
137475
+ await seedSingleStore(db, schema, { ...options, version }, refinements);
137476
+ }
135627
137477
  else {
135628
- throw new Error('The drizzle-seed package currently supports only PostgreSQL, MySQL, and SQLite databases. Please ensure your database is one of these supported types');
137478
+ 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');
135629
137479
  }
135630
137480
  return;
135631
137481
  };
@@ -135667,10 +137517,6 @@ const seedFunc = async (db, schema, options = {}, refinements) => {
135667
137517
  * @example
135668
137518
  * ```ts
135669
137519
  * await reset(db, schema);
135670
- *
135671
- * // Alternatively, you can provide an object containing your tables
135672
- * // as the `schema` parameter when calling `reset`.
135673
- * await reset(db, { users });
135674
137520
  * ```
135675
137521
  */
135676
137522
  async function reset(db, schema) {
@@ -135692,625 +137538,29 @@ async function reset(db, schema) {
135692
137538
  await resetSqlite(db, sqliteTables);
135693
137539
  }
135694
137540
  }
135695
- else {
135696
- throw new Error('The drizzle-seed package currently supports only PostgreSQL, MySQL, and SQLite databases. Please ensure your database is one of these supported types');
135697
- }
135698
- }
135699
- // Postgres-----------------------------------------------------------------------------------------------------------
135700
- const resetPostgres = async (db, pgTables) => {
135701
- const tablesToTruncate = Object.entries(pgTables).map(([_, table]) => {
135702
- const config = pgCore.getTableConfig(table);
135703
- config.schema = config.schema === undefined ? 'public' : config.schema;
135704
- return `"${config.schema}"."${config.name}"`;
135705
- });
135706
- await db.execute(drizzleOrm.sql.raw(`truncate ${tablesToTruncate.join(',')} cascade;`));
135707
- };
135708
- const filterPgSchema = (schema) => {
135709
- const pgSchema = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], pgCore.PgTable) || drizzleOrm.is(keyValue[1], drizzleOrm.Relations)));
135710
- const pgTables = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], pgCore.PgTable)));
135711
- return { pgSchema, pgTables };
135712
- };
135713
- const seedPostgres = async (db, schema, options = {}, refinements) => {
135714
- const seedService = new SeedService();
135715
- const { pgSchema, pgTables } = filterPgSchema(schema);
135716
- const { tables, relations } = getPostgresInfo(pgSchema, pgTables);
135717
- const generatedTablesGenerators = seedService.generatePossibleGenerators('postgresql', tables, relations, refinements, options);
135718
- const preserveCyclicTablesData = relations.some((rel) => rel.isCyclic === true);
135719
- const tablesValues = await seedService.generateTablesValues(relations, generatedTablesGenerators, db, pgTables, { ...options, preserveCyclicTablesData });
135720
- const { filteredTablesGenerators, tablesUniqueNotNullColumn } = seedService.filterCyclicTables(generatedTablesGenerators);
135721
- const updateDataInDb = filteredTablesGenerators.length === 0 ? false : true;
135722
- await seedService.generateTablesValues(relations, filteredTablesGenerators, db, pgTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
135723
- };
135724
- const getPostgresInfo = (pgSchema, pgTables) => {
135725
- let tableConfig;
135726
- let dbToTsColumnNamesMap;
135727
- const dbToTsTableNamesMap = Object.fromEntries(Object.entries(pgTables).map(([key, value]) => [drizzleOrm.getTableName(value), key]));
135728
- const tables = [];
135729
- const relations = [];
135730
- const dbToTsColumnNamesMapGlobal = {};
135731
- const tableRelations = {};
135732
- const getDbToTsColumnNamesMap = (table) => {
135733
- let dbToTsColumnNamesMap = {};
135734
- const tableName = drizzleOrm.getTableName(table);
135735
- if (Object.hasOwn(dbToTsColumnNamesMapGlobal, tableName)) {
135736
- dbToTsColumnNamesMap = dbToTsColumnNamesMapGlobal[tableName];
135737
- return dbToTsColumnNamesMap;
135738
- }
135739
- const tableConfig = pgCore.getTableConfig(table);
135740
- for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
135741
- dbToTsColumnNamesMap[col.name] = tsCol;
135742
- }
135743
- dbToTsColumnNamesMapGlobal[tableName] = dbToTsColumnNamesMap;
135744
- return dbToTsColumnNamesMap;
135745
- };
135746
- const transformFromDrizzleRelation = (schema, getDbToTsColumnNamesMap, tableRelations) => {
135747
- const schemaConfig = drizzleOrm.extractTablesRelationalConfig(schema, drizzleOrm.createTableRelationsHelpers);
135748
- const relations = [];
135749
- for (const table of Object.values(schemaConfig.tables)) {
135750
- if (table.relations === undefined)
135751
- continue;
135752
- for (const drizzleRel of Object.values(table.relations)) {
135753
- if (!drizzleOrm.is(drizzleRel, drizzleOrm.One))
135754
- continue;
135755
- const tableConfig = pgCore.getTableConfig(drizzleRel.sourceTable);
135756
- const tableDbSchema = tableConfig.schema ?? 'public';
135757
- const tableDbName = tableConfig.name;
135758
- const tableTsName = schemaConfig.tableNamesMap[`${tableDbSchema}.${tableDbName}`] ?? tableDbName;
135759
- const dbToTsColumnNamesMap = getDbToTsColumnNamesMap(drizzleRel.sourceTable);
135760
- const columns = drizzleRel.config?.fields.map((field) => dbToTsColumnNamesMap[field.name])
135761
- ?? [];
135762
- const refTableConfig = pgCore.getTableConfig(drizzleRel.referencedTable);
135763
- const refTableDbSchema = refTableConfig.schema ?? 'public';
135764
- const refTableDbName = refTableConfig.name;
135765
- const refTableTsName = schemaConfig.tableNamesMap[`${refTableDbSchema}.${refTableDbName}`]
135766
- ?? refTableDbName;
135767
- const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(drizzleRel.referencedTable);
135768
- const refColumns = drizzleRel.config?.references.map((ref) => dbToTsColumnNamesMapForRefTable[ref.name])
135769
- ?? [];
135770
- if (tableRelations[refTableTsName] === undefined) {
135771
- tableRelations[refTableTsName] = [];
135772
- }
135773
- const relation = {
135774
- table: tableTsName,
135775
- columns,
135776
- refTable: refTableTsName,
135777
- refColumns,
135778
- refTableRels: tableRelations[refTableTsName],
135779
- type: 'one',
135780
- };
135781
- // do not add duplicate relation
135782
- if (tableRelations[tableTsName]?.some((rel) => rel.table === relation.table
135783
- && rel.refTable === relation.refTable)) {
135784
- console.warn(`You are providing a one-to-many relation between the '${relation.refTable}' and '${relation.table}' tables,\n`
135785
- + `while the '${relation.table}' table object already has foreign key constraint in the schema referencing '${relation.refTable}' table.\n`
135786
- + `In this case, the foreign key constraint will be used.\n`);
135787
- continue;
135788
- }
135789
- relations.push(relation);
135790
- tableRelations[tableTsName].push(relation);
135791
- }
135792
- }
135793
- return relations;
135794
- };
135795
- for (const table of Object.values(pgTables)) {
135796
- tableConfig = pgCore.getTableConfig(table);
135797
- dbToTsColumnNamesMap = {};
135798
- for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
135799
- dbToTsColumnNamesMap[col.name] = tsCol;
135800
- }
135801
- // might be empty list
135802
- const newRelations = tableConfig.foreignKeys.map((fk) => {
135803
- const table = dbToTsTableNamesMap[tableConfig.name];
135804
- const refTable = dbToTsTableNamesMap[drizzleOrm.getTableName(fk.reference().foreignTable)];
135805
- const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(fk.reference().foreignTable);
135806
- if (tableRelations[refTable] === undefined) {
135807
- tableRelations[refTable] = [];
135808
- }
135809
- return {
135810
- table,
135811
- columns: fk
135812
- .reference()
135813
- .columns.map((col) => dbToTsColumnNamesMap[col.name]),
135814
- refTable,
135815
- refColumns: fk
135816
- .reference()
135817
- .foreignColumns.map((fCol) => dbToTsColumnNamesMapForRefTable[fCol.name]),
135818
- refTableRels: tableRelations[refTable],
135819
- };
135820
- });
135821
- relations.push(...newRelations);
135822
- if (tableRelations[dbToTsTableNamesMap[tableConfig.name]] === undefined) {
135823
- tableRelations[dbToTsTableNamesMap[tableConfig.name]] = [];
135824
- }
135825
- tableRelations[dbToTsTableNamesMap[tableConfig.name]].push(...newRelations);
135826
- const getAllBaseColumns = (baseColumn) => {
135827
- const baseColumnResult = {
135828
- name: baseColumn.name,
135829
- columnType: baseColumn.getSQLType(),
135830
- typeParams: getTypeParams(baseColumn.getSQLType()),
135831
- dataType: baseColumn.dataType,
135832
- size: baseColumn.size,
135833
- hasDefault: baseColumn.hasDefault,
135834
- enumValues: baseColumn.enumValues,
135835
- default: baseColumn.default,
135836
- isUnique: baseColumn.isUnique,
135837
- notNull: baseColumn.notNull,
135838
- primary: baseColumn.primary,
135839
- baseColumn: baseColumn.baseColumn === undefined ? undefined : getAllBaseColumns(baseColumn.baseColumn),
135840
- };
135841
- return baseColumnResult;
135842
- };
135843
- const getTypeParams = (sqlType) => {
135844
- // get type params
135845
- const typeParams = {};
135846
- // handle dimensions
135847
- if (sqlType.includes('[')) {
135848
- const match = sqlType.match(/\[\w*]/g);
135849
- if (match) {
135850
- typeParams['dimensions'] = match.length;
135851
- }
135852
- }
135853
- if (sqlType.startsWith('numeric')
135854
- || sqlType.startsWith('decimal')
135855
- || sqlType.startsWith('double precision')
135856
- || sqlType.startsWith('real')) {
135857
- const match = sqlType.match(/\((\d+), *(\d+)\)/);
135858
- if (match) {
135859
- typeParams['precision'] = Number(match[1]);
135860
- typeParams['scale'] = Number(match[2]);
135861
- }
135862
- }
135863
- else if (sqlType.startsWith('varchar')
135864
- || sqlType.startsWith('bpchar')
135865
- || sqlType.startsWith('char')
135866
- || sqlType.startsWith('bit')
135867
- || sqlType.startsWith('time')
135868
- || sqlType.startsWith('timestamp')
135869
- || sqlType.startsWith('interval')) {
135870
- const match = sqlType.match(/\((\d+)\)/);
135871
- if (match) {
135872
- typeParams['length'] = Number(match[1]);
135873
- }
135874
- }
135875
- return typeParams;
135876
- };
135877
- // console.log(tableConfig.columns);
135878
- tables.push({
135879
- name: dbToTsTableNamesMap[tableConfig.name],
135880
- columns: tableConfig.columns.map((column) => ({
135881
- name: dbToTsColumnNamesMap[column.name],
135882
- columnType: column.getSQLType(),
135883
- typeParams: getTypeParams(column.getSQLType()),
135884
- dataType: column.dataType,
135885
- size: column.size,
135886
- hasDefault: column.hasDefault,
135887
- default: column.default,
135888
- enumValues: column.enumValues,
135889
- isUnique: column.isUnique,
135890
- notNull: column.notNull,
135891
- primary: column.primary,
135892
- generatedIdentityType: column.generatedIdentity?.type,
135893
- baseColumn: (column.baseColumn === undefined)
135894
- ? undefined
135895
- : getAllBaseColumns(column.baseColumn),
135896
- })),
135897
- primaryKeys: tableConfig.columns
135898
- .filter((column) => column.primary)
135899
- .map((column) => dbToTsColumnNamesMap[column.name]),
135900
- });
135901
- }
135902
- const transformedDrizzleRelations = transformFromDrizzleRelation(pgSchema, getDbToTsColumnNamesMap, tableRelations);
135903
- relations.push(...transformedDrizzleRelations);
135904
- const isCyclicRelations = relations.map((relI) => {
135905
- // if (relations.some((relj) => relI.table === relj.refTable && relI.refTable === relj.table)) {
135906
- const tableRel = tableRelations[relI.table].find((relJ) => relJ.refTable === relI.refTable);
135907
- if (isRelationCyclic(relI)) {
135908
- tableRel['isCyclic'] = true;
135909
- return { ...relI, isCyclic: true };
135910
- }
135911
- tableRel['isCyclic'] = false;
135912
- return { ...relI, isCyclic: false };
135913
- });
135914
- return { tables, relations: isCyclicRelations, tableRelations };
135915
- };
135916
- const isRelationCyclic = (startRel) => {
135917
- // self relation
135918
- if (startRel.table === startRel.refTable)
135919
- return false;
135920
- // DFS
135921
- const targetTable = startRel.table;
135922
- const queue = [startRel];
135923
- let path = [];
135924
- while (queue.length !== 0) {
135925
- const currRel = queue.shift();
135926
- if (path.includes(currRel.table)) {
135927
- const idx = path.indexOf(currRel.table);
135928
- path = path.slice(0, idx);
135929
- }
135930
- path.push(currRel.table);
135931
- for (const rel of currRel.refTableRels) {
135932
- // self relation
135933
- if (rel.table === rel.refTable)
135934
- continue;
135935
- if (rel.refTable === targetTable)
135936
- return true;
135937
- // found cycle, but not the one we are looking for
135938
- if (path.includes(rel.refTable))
135939
- continue;
135940
- queue.unshift(rel);
137541
+ else if (drizzleOrm.is(db, (mssqlCore.MsSqlDatabase))) {
137542
+ const { mssqlTables } = filterMsSqlTables(schema);
137543
+ if (Object.entries(mssqlTables).length > 0) {
137544
+ await resetMsSql(db, mssqlTables);
135941
137545
  }
135942
137546
  }
135943
- return false;
135944
- };
135945
- // MySql-----------------------------------------------------------------------------------------------------
135946
- const resetMySql = async (db, schema) => {
135947
- const tablesToTruncate = Object.entries(schema).map(([_tsTableName, table]) => {
135948
- const dbTableName = drizzleOrm.getTableName(table);
135949
- return dbTableName;
135950
- });
135951
- await db.execute(drizzleOrm.sql.raw('SET FOREIGN_KEY_CHECKS = 0;'));
135952
- for (const tableName of tablesToTruncate) {
135953
- const sqlQuery = `truncate \`${tableName}\`;`;
135954
- await db.execute(drizzleOrm.sql.raw(sqlQuery));
135955
- }
135956
- await db.execute(drizzleOrm.sql.raw('SET FOREIGN_KEY_CHECKS = 1;'));
135957
- };
135958
- const filterMysqlTables = (schema) => {
135959
- const mysqlSchema = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], mysqlCore.MySqlTable) || drizzleOrm.is(keyValue[1], drizzleOrm.Relations)));
135960
- const mysqlTables = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], mysqlCore.MySqlTable)));
135961
- return { mysqlSchema, mysqlTables };
135962
- };
135963
- const seedMySql = async (db, schema, options = {}, refinements) => {
135964
- const { mysqlSchema, mysqlTables } = filterMysqlTables(schema);
135965
- const { tables, relations } = getMySqlInfo(mysqlSchema, mysqlTables);
135966
- const seedService = new SeedService();
135967
- const generatedTablesGenerators = seedService.generatePossibleGenerators('mysql', tables, relations, refinements, options);
135968
- const preserveCyclicTablesData = relations.some((rel) => rel.isCyclic === true);
135969
- const tablesValues = await seedService.generateTablesValues(relations, generatedTablesGenerators, db, mysqlTables, { ...options, preserveCyclicTablesData });
135970
- const { filteredTablesGenerators, tablesUniqueNotNullColumn } = seedService.filterCyclicTables(generatedTablesGenerators);
135971
- const updateDataInDb = filteredTablesGenerators.length === 0 ? false : true;
135972
- await seedService.generateTablesValues(relations, filteredTablesGenerators, db, mysqlTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
135973
- };
135974
- const getMySqlInfo = (mysqlSchema, mysqlTables) => {
135975
- let tableConfig;
135976
- let dbToTsColumnNamesMap;
135977
- const dbToTsTableNamesMap = Object.fromEntries(Object.entries(mysqlTables).map(([key, value]) => [drizzleOrm.getTableName(value), key]));
135978
- const tables = [];
135979
- const relations = [];
135980
- const dbToTsColumnNamesMapGlobal = {};
135981
- const tableRelations = {};
135982
- const getDbToTsColumnNamesMap = (table) => {
135983
- let dbToTsColumnNamesMap = {};
135984
- const tableName = drizzleOrm.getTableName(table);
135985
- if (Object.hasOwn(dbToTsColumnNamesMapGlobal, tableName)) {
135986
- dbToTsColumnNamesMap = dbToTsColumnNamesMapGlobal[tableName];
135987
- return dbToTsColumnNamesMap;
137547
+ else if (drizzleOrm.is(db, (cockroachCore.CockroachDatabase))) {
137548
+ const { cockroachTables } = filterCockroachSchema(schema);
137549
+ if (Object.entries(cockroachTables).length > 0) {
137550
+ await resetCockroach(db, cockroachTables);
135988
137551
  }
135989
- const tableConfig = mysqlCore.getTableConfig(table);
135990
- for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
135991
- dbToTsColumnNamesMap[col.name] = tsCol;
135992
- }
135993
- dbToTsColumnNamesMapGlobal[tableName] = dbToTsColumnNamesMap;
135994
- return dbToTsColumnNamesMap;
135995
- };
135996
- const transformFromDrizzleRelation = (schema, getDbToTsColumnNamesMap, tableRelations) => {
135997
- const schemaConfig = drizzleOrm.extractTablesRelationalConfig(schema, drizzleOrm.createTableRelationsHelpers);
135998
- const relations = [];
135999
- for (const table of Object.values(schemaConfig.tables)) {
136000
- if (table.relations === undefined)
136001
- continue;
136002
- for (const drizzleRel of Object.values(table.relations)) {
136003
- if (!drizzleOrm.is(drizzleRel, drizzleOrm.One))
136004
- continue;
136005
- const tableConfig = mysqlCore.getTableConfig(drizzleRel.sourceTable);
136006
- const tableDbSchema = tableConfig.schema ?? 'public';
136007
- const tableDbName = tableConfig.name;
136008
- const tableTsName = schemaConfig.tableNamesMap[`${tableDbSchema}.${tableDbName}`] ?? tableDbName;
136009
- const dbToTsColumnNamesMap = getDbToTsColumnNamesMap(drizzleRel.sourceTable);
136010
- const columns = drizzleRel.config?.fields.map((field) => dbToTsColumnNamesMap[field.name])
136011
- ?? [];
136012
- const refTableConfig = mysqlCore.getTableConfig(drizzleRel.referencedTable);
136013
- const refTableDbSchema = refTableConfig.schema ?? 'public';
136014
- const refTableDbName = refTableConfig.name;
136015
- const refTableTsName = schemaConfig.tableNamesMap[`${refTableDbSchema}.${refTableDbName}`]
136016
- ?? refTableDbName;
136017
- const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(drizzleRel.referencedTable);
136018
- const refColumns = drizzleRel.config?.references.map((ref) => dbToTsColumnNamesMapForRefTable[ref.name])
136019
- ?? [];
136020
- if (tableRelations[refTableTsName] === undefined) {
136021
- tableRelations[refTableTsName] = [];
136022
- }
136023
- const relation = {
136024
- table: tableTsName,
136025
- columns,
136026
- refTable: refTableTsName,
136027
- refColumns,
136028
- refTableRels: tableRelations[refTableTsName],
136029
- type: 'one',
136030
- };
136031
- // do not add duplicate relation
136032
- if (tableRelations[tableTsName]?.some((rel) => rel.table === relation.table
136033
- && rel.refTable === relation.refTable)) {
136034
- console.warn(`You are providing a one-to-many relation between the '${relation.refTable}' and '${relation.table}' tables,\n`
136035
- + `while the '${relation.table}' table object already has foreign key constraint in the schema referencing '${relation.refTable}' table.\n`
136036
- + `In this case, the foreign key constraint will be used.\n`);
136037
- continue;
136038
- }
136039
- relations.push(relation);
136040
- tableRelations[tableTsName].push(relation);
136041
- }
136042
- }
136043
- return relations;
136044
- };
136045
- for (const table of Object.values(mysqlTables)) {
136046
- tableConfig = mysqlCore.getTableConfig(table);
136047
- dbToTsColumnNamesMap = {};
136048
- for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
136049
- dbToTsColumnNamesMap[col.name] = tsCol;
136050
- }
136051
- const newRelations = tableConfig.foreignKeys.map((fk) => {
136052
- const table = dbToTsTableNamesMap[tableConfig.name];
136053
- const refTable = dbToTsTableNamesMap[drizzleOrm.getTableName(fk.reference().foreignTable)];
136054
- const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(fk.reference().foreignTable);
136055
- if (tableRelations[refTable] === undefined) {
136056
- tableRelations[refTable] = [];
136057
- }
136058
- return {
136059
- table,
136060
- columns: fk
136061
- .reference()
136062
- .columns.map((col) => dbToTsColumnNamesMap[col.name]),
136063
- refTable,
136064
- refColumns: fk
136065
- .reference()
136066
- .foreignColumns.map((fCol) => dbToTsColumnNamesMapForRefTable[fCol.name]),
136067
- refTableRels: tableRelations[refTable],
136068
- };
136069
- });
136070
- relations.push(...newRelations);
136071
- if (tableRelations[dbToTsTableNamesMap[tableConfig.name]] === undefined) {
136072
- tableRelations[dbToTsTableNamesMap[tableConfig.name]] = [];
136073
- }
136074
- tableRelations[dbToTsTableNamesMap[tableConfig.name]].push(...newRelations);
136075
- const getTypeParams = (sqlType) => {
136076
- // get type params and set only type
136077
- const typeParams = {};
136078
- if (sqlType.startsWith('decimal')
136079
- || sqlType.startsWith('real')
136080
- || sqlType.startsWith('double')
136081
- || sqlType.startsWith('float')) {
136082
- const match = sqlType.match(/\((\d+), *(\d+)\)/);
136083
- if (match) {
136084
- typeParams['precision'] = Number(match[1]);
136085
- typeParams['scale'] = Number(match[2]);
136086
- }
136087
- }
136088
- else if (sqlType.startsWith('char')
136089
- || sqlType.startsWith('varchar')
136090
- || sqlType.startsWith('binary')
136091
- || sqlType.startsWith('varbinary')) {
136092
- const match = sqlType.match(/\((\d+)\)/);
136093
- if (match) {
136094
- typeParams['length'] = Number(match[1]);
136095
- }
136096
- }
136097
- return typeParams;
136098
- };
136099
- tables.push({
136100
- name: dbToTsTableNamesMap[tableConfig.name],
136101
- columns: tableConfig.columns.map((column) => ({
136102
- name: dbToTsColumnNamesMap[column.name],
136103
- columnType: column.getSQLType(),
136104
- typeParams: getTypeParams(column.getSQLType()),
136105
- dataType: column.dataType,
136106
- hasDefault: column.hasDefault,
136107
- default: column.default,
136108
- enumValues: column.enumValues,
136109
- isUnique: column.isUnique,
136110
- notNull: column.notNull,
136111
- primary: column.primary,
136112
- })),
136113
- primaryKeys: tableConfig.columns
136114
- .filter((column) => column.primary)
136115
- .map((column) => dbToTsColumnNamesMap[column.name]),
136116
- });
136117
137552
  }
136118
- const transformedDrizzleRelations = transformFromDrizzleRelation(mysqlSchema, getDbToTsColumnNamesMap, tableRelations);
136119
- relations.push(...transformedDrizzleRelations);
136120
- const isCyclicRelations = relations.map((relI) => {
136121
- const tableRel = tableRelations[relI.table].find((relJ) => relJ.refTable === relI.refTable);
136122
- if (isRelationCyclic(relI)) {
136123
- tableRel['isCyclic'] = true;
136124
- return { ...relI, isCyclic: true };
137553
+ else if (drizzleOrm.is(db, (singlestoreCore.SingleStoreDatabase))) {
137554
+ const { singleStoreTables } = filterSingleStoreTables(schema);
137555
+ if (Object.entries(singleStoreTables).length > 0) {
137556
+ await resetSingleStore(db, singleStoreTables);
136125
137557
  }
136126
- tableRel['isCyclic'] = false;
136127
- return { ...relI, isCyclic: false };
136128
- });
136129
- return { tables, relations: isCyclicRelations, tableRelations };
136130
- };
136131
- // Sqlite------------------------------------------------------------------------------------------------------------------------
136132
- const resetSqlite = async (db, schema) => {
136133
- const tablesToTruncate = Object.entries(schema).map(([_tsTableName, table]) => {
136134
- const dbTableName = drizzleOrm.getTableName(table);
136135
- return dbTableName;
136136
- });
136137
- await db.run(drizzleOrm.sql.raw('PRAGMA foreign_keys = OFF'));
136138
- for (const tableName of tablesToTruncate) {
136139
- const sqlQuery = `delete from \`${tableName}\`;`;
136140
- await db.run(drizzleOrm.sql.raw(sqlQuery));
136141
137558
  }
136142
- await db.run(drizzleOrm.sql.raw('PRAGMA foreign_keys = ON'));
136143
- };
136144
- const filterSqliteTables = (schema) => {
136145
- const sqliteSchema = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], sqliteCore.SQLiteTable) || drizzleOrm.is(keyValue[1], drizzleOrm.Relations)));
136146
- const sqliteTables = Object.fromEntries(Object.entries(schema).filter((keyValue) => drizzleOrm.is(keyValue[1], sqliteCore.SQLiteTable)));
136147
- return { sqliteSchema, sqliteTables };
136148
- };
136149
- const seedSqlite = async (db, schema, options = {}, refinements) => {
136150
- const { sqliteSchema, sqliteTables } = filterSqliteTables(schema);
136151
- const { tables, relations } = getSqliteInfo(sqliteSchema, sqliteTables);
136152
- const seedService = new SeedService();
136153
- const generatedTablesGenerators = seedService.generatePossibleGenerators('sqlite', tables, relations, refinements, options);
136154
- const preserveCyclicTablesData = relations.some((rel) => rel.isCyclic === true);
136155
- const tablesValues = await seedService.generateTablesValues(relations, generatedTablesGenerators, db, sqliteTables, { ...options, preserveCyclicTablesData });
136156
- const { filteredTablesGenerators, tablesUniqueNotNullColumn } = seedService.filterCyclicTables(generatedTablesGenerators);
136157
- const updateDataInDb = filteredTablesGenerators.length === 0 ? false : true;
136158
- await seedService.generateTablesValues(relations, filteredTablesGenerators, db, sqliteTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
136159
- };
136160
- const getSqliteInfo = (sqliteSchema, sqliteTables) => {
136161
- let tableConfig;
136162
- let dbToTsColumnNamesMap;
136163
- const dbToTsTableNamesMap = Object.fromEntries(Object.entries(sqliteTables).map(([key, value]) => [drizzleOrm.getTableName(value), key]));
136164
- const tables = [];
136165
- const relations = [];
136166
- const dbToTsColumnNamesMapGlobal = {};
136167
- const tableRelations = {};
136168
- const getDbToTsColumnNamesMap = (table) => {
136169
- let dbToTsColumnNamesMap = {};
136170
- const tableName = drizzleOrm.getTableName(table);
136171
- if (Object.hasOwn(dbToTsColumnNamesMapGlobal, tableName)) {
136172
- dbToTsColumnNamesMap = dbToTsColumnNamesMapGlobal[tableName];
136173
- return dbToTsColumnNamesMap;
136174
- }
136175
- const tableConfig = sqliteCore.getTableConfig(table);
136176
- for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
136177
- dbToTsColumnNamesMap[col.name] = tsCol;
136178
- }
136179
- dbToTsColumnNamesMapGlobal[tableName] = dbToTsColumnNamesMap;
136180
- return dbToTsColumnNamesMap;
136181
- };
136182
- const transformFromDrizzleRelation = (schema, getDbToTsColumnNamesMap, tableRelations) => {
136183
- const schemaConfig = drizzleOrm.extractTablesRelationalConfig(schema, drizzleOrm.createTableRelationsHelpers);
136184
- const relations = [];
136185
- for (const table of Object.values(schemaConfig.tables)) {
136186
- if (table.relations === undefined)
136187
- continue;
136188
- for (const drizzleRel of Object.values(table.relations)) {
136189
- if (!drizzleOrm.is(drizzleRel, drizzleOrm.One))
136190
- continue;
136191
- const tableConfig = sqliteCore.getTableConfig(drizzleRel.sourceTable);
136192
- const tableDbName = tableConfig.name;
136193
- // TODO: tableNamesMap: have {public.customer: 'customer'} structure in sqlite
136194
- const tableTsName = schemaConfig.tableNamesMap[`public.${tableDbName}`] ?? tableDbName;
136195
- const dbToTsColumnNamesMap = getDbToTsColumnNamesMap(drizzleRel.sourceTable);
136196
- const columns = drizzleRel.config?.fields.map((field) => dbToTsColumnNamesMap[field.name])
136197
- ?? [];
136198
- const refTableConfig = sqliteCore.getTableConfig(drizzleRel.referencedTable);
136199
- const refTableDbName = refTableConfig.name;
136200
- const refTableTsName = schemaConfig.tableNamesMap[`public.${refTableDbName}`]
136201
- ?? refTableDbName;
136202
- const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(drizzleRel.referencedTable);
136203
- const refColumns = drizzleRel.config?.references.map((ref) => dbToTsColumnNamesMapForRefTable[ref.name])
136204
- ?? [];
136205
- if (tableRelations[refTableTsName] === undefined) {
136206
- tableRelations[refTableTsName] = [];
136207
- }
136208
- const relation = {
136209
- table: tableTsName,
136210
- columns,
136211
- refTable: refTableTsName,
136212
- refColumns,
136213
- refTableRels: tableRelations[refTableTsName],
136214
- type: 'one',
136215
- };
136216
- // do not add duplicate relation
136217
- if (tableRelations[tableTsName]?.some((rel) => rel.table === relation.table
136218
- && rel.refTable === relation.refTable)) {
136219
- console.warn(`You are providing a one-to-many relation between the '${relation.refTable}' and '${relation.table}' tables,\n`
136220
- + `while the '${relation.table}' table object already has foreign key constraint in the schema referencing '${relation.refTable}' table.\n`
136221
- + `In this case, the foreign key constraint will be used.\n`);
136222
- continue;
136223
- }
136224
- relations.push(relation);
136225
- tableRelations[tableTsName].push(relation);
136226
- }
136227
- }
136228
- return relations;
136229
- };
136230
- for (const table of Object.values(sqliteTables)) {
136231
- tableConfig = sqliteCore.getTableConfig(table);
136232
- dbToTsColumnNamesMap = {};
136233
- for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
136234
- dbToTsColumnNamesMap[col.name] = tsCol;
136235
- }
136236
- const newRelations = tableConfig.foreignKeys.map((fk) => {
136237
- const table = dbToTsTableNamesMap[tableConfig.name];
136238
- const refTable = dbToTsTableNamesMap[drizzleOrm.getTableName(fk.reference().foreignTable)];
136239
- const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(fk.reference().foreignTable);
136240
- if (tableRelations[refTable] === undefined) {
136241
- tableRelations[refTable] = [];
136242
- }
136243
- return {
136244
- table,
136245
- columns: fk
136246
- .reference()
136247
- .columns.map((col) => dbToTsColumnNamesMap[col.name]),
136248
- refTable,
136249
- refColumns: fk
136250
- .reference()
136251
- .foreignColumns.map((fCol) => dbToTsColumnNamesMapForRefTable[fCol.name]),
136252
- refTableRels: tableRelations[refTable],
136253
- };
136254
- });
136255
- relations.push(...newRelations);
136256
- if (tableRelations[dbToTsTableNamesMap[tableConfig.name]] === undefined) {
136257
- tableRelations[dbToTsTableNamesMap[tableConfig.name]] = [];
136258
- }
136259
- tableRelations[dbToTsTableNamesMap[tableConfig.name]].push(...newRelations);
136260
- const getTypeParams = (sqlType) => {
136261
- // get type params and set only type
136262
- const typeParams = {};
136263
- if (sqlType.startsWith('decimal')) {
136264
- const match = sqlType.match(/\((\d+), *(\d+)\)/);
136265
- if (match) {
136266
- typeParams['precision'] = Number(match[1]);
136267
- typeParams['scale'] = Number(match[2]);
136268
- }
136269
- }
136270
- else if (sqlType.startsWith('char')
136271
- || sqlType.startsWith('varchar')
136272
- || sqlType.startsWith('text')) {
136273
- const match = sqlType.match(/\((\d+)\)/);
136274
- if (match) {
136275
- typeParams['length'] = Number(match[1]);
136276
- }
136277
- }
136278
- return typeParams;
136279
- };
136280
- tables.push({
136281
- name: dbToTsTableNamesMap[tableConfig.name],
136282
- columns: tableConfig.columns.map((column) => ({
136283
- name: dbToTsColumnNamesMap[column.name],
136284
- columnType: column.getSQLType(),
136285
- typeParams: getTypeParams(column.getSQLType()),
136286
- dataType: column.dataType,
136287
- hasDefault: column.hasDefault,
136288
- default: column.default,
136289
- enumValues: column.enumValues,
136290
- isUnique: column.isUnique,
136291
- notNull: column.notNull,
136292
- primary: column.primary,
136293
- })),
136294
- primaryKeys: tableConfig.columns
136295
- .filter((column) => column.primary)
136296
- .map((column) => dbToTsColumnNamesMap[column.name]),
136297
- });
137559
+ else {
137560
+ 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');
136298
137561
  }
136299
- const transformedDrizzleRelations = transformFromDrizzleRelation(sqliteSchema, getDbToTsColumnNamesMap, tableRelations);
136300
- relations.push(...transformedDrizzleRelations);
136301
- const isCyclicRelations = relations.map((relI) => {
136302
- const tableRel = tableRelations[relI.table].find((relJ) => relJ.refTable === relI.refTable);
136303
- if (isRelationCyclic(relI)) {
136304
- tableRel['isCyclic'] = true;
136305
- return { ...relI, isCyclic: true };
136306
- }
136307
- tableRel['isCyclic'] = false;
136308
- return { ...relI, isCyclic: false };
136309
- });
136310
- return { tables, relations: isCyclicRelations, tableRelations };
136311
- };
137562
+ }
136312
137563
 
136313
- exports.AbstractGenerator = AbstractGenerator;
136314
137564
  exports.SeedService = SeedService;
136315
137565
  exports.cities = cityNames;
136316
137566
  exports.countries = countries;