@snowtop/ent 0.1.0-alpha9 → 0.1.0-alpha91

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 (135) hide show
  1. package/action/action.d.ts +36 -31
  2. package/action/action.js +2 -6
  3. package/action/executor.d.ts +3 -3
  4. package/action/executor.js +2 -2
  5. package/action/experimental_action.d.ts +29 -22
  6. package/action/experimental_action.js +29 -6
  7. package/action/orchestrator.d.ts +38 -16
  8. package/action/orchestrator.js +223 -61
  9. package/action/privacy.d.ts +2 -2
  10. package/core/base.d.ts +45 -24
  11. package/core/base.js +7 -1
  12. package/core/clause.d.ts +83 -7
  13. package/core/clause.js +334 -63
  14. package/core/config.d.ts +8 -0
  15. package/core/config.js +5 -1
  16. package/core/context.d.ts +5 -3
  17. package/core/context.js +20 -2
  18. package/core/convert.d.ts +1 -1
  19. package/core/db.d.ts +2 -2
  20. package/core/db.js +6 -2
  21. package/core/ent.d.ts +79 -24
  22. package/core/ent.js +527 -176
  23. package/core/loaders/assoc_count_loader.d.ts +3 -2
  24. package/core/loaders/assoc_count_loader.js +14 -2
  25. package/core/loaders/assoc_edge_loader.d.ts +2 -2
  26. package/core/loaders/assoc_edge_loader.js +5 -1
  27. package/core/loaders/index.d.ts +1 -1
  28. package/core/loaders/index.js +1 -3
  29. package/core/loaders/index_loader.d.ts +2 -2
  30. package/core/loaders/loader.js +5 -5
  31. package/core/loaders/object_loader.d.ts +6 -5
  32. package/core/loaders/object_loader.js +67 -59
  33. package/core/loaders/query_loader.d.ts +6 -12
  34. package/core/loaders/query_loader.js +52 -11
  35. package/core/loaders/raw_count_loader.d.ts +2 -2
  36. package/core/loaders/raw_count_loader.js +5 -1
  37. package/core/logger.d.ts +1 -1
  38. package/core/logger.js +1 -0
  39. package/core/privacy.d.ts +26 -25
  40. package/core/privacy.js +21 -25
  41. package/core/query/assoc_query.d.ts +7 -6
  42. package/core/query/assoc_query.js +9 -1
  43. package/core/query/custom_clause_query.d.ts +26 -0
  44. package/core/query/custom_clause_query.js +78 -0
  45. package/core/query/custom_query.d.ts +20 -5
  46. package/core/query/custom_query.js +87 -12
  47. package/core/query/index.d.ts +1 -0
  48. package/core/query/index.js +3 -1
  49. package/core/query/query.d.ts +8 -4
  50. package/core/query/query.js +101 -53
  51. package/core/query/shared_assoc_test.d.ts +2 -1
  52. package/core/query/shared_assoc_test.js +34 -43
  53. package/core/query/shared_test.d.ts +8 -1
  54. package/core/query/shared_test.js +470 -236
  55. package/core/viewer.d.ts +3 -3
  56. package/core/viewer.js +1 -1
  57. package/graphql/graphql.js +16 -6
  58. package/graphql/query/edge_connection.d.ts +9 -9
  59. package/graphql/query/page_info.d.ts +1 -1
  60. package/graphql/query/shared_edge_connection.js +1 -15
  61. package/imports/index.js +5 -1
  62. package/index.d.ts +11 -5
  63. package/index.js +20 -7
  64. package/package.json +1 -1
  65. package/parse_schema/parse.d.ts +12 -3
  66. package/parse_schema/parse.js +70 -11
  67. package/schema/base_schema.js +3 -0
  68. package/schema/field.d.ts +44 -8
  69. package/schema/field.js +136 -10
  70. package/schema/index.d.ts +2 -2
  71. package/schema/index.js +5 -1
  72. package/schema/json_field.d.ts +13 -1
  73. package/schema/json_field.js +28 -1
  74. package/schema/schema.d.ts +66 -11
  75. package/schema/schema.js +18 -4
  76. package/schema/struct_field.d.ts +11 -1
  77. package/schema/struct_field.js +44 -5
  78. package/scripts/custom_compiler.js +10 -6
  79. package/scripts/custom_graphql.js +13 -4
  80. package/scripts/{transform_schema.d.ts → migrate_v0.1.d.ts} +0 -0
  81. package/scripts/migrate_v0.1.js +36 -0
  82. package/scripts/read_schema.js +20 -5
  83. package/testutils/builder.d.ts +31 -21
  84. package/testutils/builder.js +83 -29
  85. package/testutils/db/fixture.d.ts +10 -0
  86. package/testutils/db/fixture.js +26 -0
  87. package/testutils/db/{test_db.d.ts → temp_db.d.ts} +20 -7
  88. package/testutils/db/{test_db.js → temp_db.js} +102 -36
  89. package/testutils/db/value.d.ts +6 -0
  90. package/testutils/db/value.js +251 -0
  91. package/testutils/db_mock.js +3 -1
  92. package/testutils/db_time_zone.d.ts +4 -0
  93. package/testutils/db_time_zone.js +41 -0
  94. package/testutils/ent-graphql-tests/index.js +8 -1
  95. package/testutils/fake_data/const.d.ts +2 -1
  96. package/testutils/fake_data/const.js +3 -0
  97. package/testutils/fake_data/fake_contact.d.ts +7 -4
  98. package/testutils/fake_data/fake_contact.js +14 -6
  99. package/testutils/fake_data/fake_event.d.ts +5 -3
  100. package/testutils/fake_data/fake_event.js +8 -5
  101. package/testutils/fake_data/fake_tag.d.ts +35 -0
  102. package/testutils/fake_data/fake_tag.js +88 -0
  103. package/testutils/fake_data/fake_user.d.ts +6 -4
  104. package/testutils/fake_data/fake_user.js +16 -13
  105. package/testutils/fake_data/index.js +5 -1
  106. package/testutils/fake_data/internal.d.ts +2 -0
  107. package/testutils/fake_data/internal.js +7 -1
  108. package/testutils/fake_data/tag_query.d.ts +13 -0
  109. package/testutils/fake_data/tag_query.js +43 -0
  110. package/testutils/fake_data/test_helpers.d.ts +11 -4
  111. package/testutils/fake_data/test_helpers.js +28 -12
  112. package/testutils/fake_data/user_query.d.ts +13 -6
  113. package/testutils/fake_data/user_query.js +54 -22
  114. package/testutils/fake_log.d.ts +3 -3
  115. package/testutils/parse_sql.d.ts +6 -0
  116. package/testutils/parse_sql.js +16 -2
  117. package/testutils/test_edge_global_schema.d.ts +15 -0
  118. package/testutils/test_edge_global_schema.js +62 -0
  119. package/testutils/write.d.ts +2 -2
  120. package/testutils/write.js +33 -7
  121. package/tsc/ast.d.ts +44 -0
  122. package/tsc/ast.js +271 -0
  123. package/tsc/compilerOptions.d.ts +6 -0
  124. package/tsc/compilerOptions.js +45 -2
  125. package/tsc/move_generated.d.ts +1 -0
  126. package/tsc/move_generated.js +164 -0
  127. package/tsc/transform.d.ts +21 -0
  128. package/tsc/transform.js +171 -0
  129. package/tsc/transform_action.d.ts +22 -0
  130. package/tsc/transform_action.js +183 -0
  131. package/tsc/transform_ent.d.ts +17 -0
  132. package/tsc/transform_ent.js +59 -0
  133. package/tsc/transform_schema.d.ts +27 -0
  134. package/tsc/transform_schema.js +383 -0
  135. package/scripts/transform_schema.js +0 -445
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.writeFixture = void 0;
4
+ const schema_1 = require("../../schema");
5
+ const value_1 = require("./value");
6
+ const ent_1 = require("../../core/ent");
7
+ async function writeFixture(schema, opts) {
8
+ const fields = (0, schema_1.getFields)(schema);
9
+ const d = {};
10
+ for (const [fieldName, field] of fields) {
11
+ const col = (0, schema_1.getStorageKey)(field, fieldName);
12
+ const val = (0, value_1.getDefaultValue)(field, col);
13
+ d[col] = val;
14
+ }
15
+ if (opts.overrides) {
16
+ for (const k in opts.overrides) {
17
+ d[k] = opts.overrides[k];
18
+ }
19
+ }
20
+ const q = (0, ent_1.buildInsertQuery)({
21
+ tableName: opts.tableName,
22
+ fields: d,
23
+ });
24
+ await opts.client.query(q[0], q[1]);
25
+ }
26
+ exports.writeFixture = writeFixture;
@@ -1,6 +1,7 @@
1
1
  import { Client as PGClient } from "pg";
2
2
  import { Dialect } from "../../core/db";
3
3
  import { Database as SqliteDatabase } from "better-sqlite3";
4
+ import { Field } from "../../schema";
4
5
  import { BuilderSchema } from "../builder";
5
6
  import { Ent } from "../../core/base";
6
7
  interface SchemaItem {
@@ -12,6 +13,7 @@ interface Column extends SchemaItem {
12
13
  primaryKey?: boolean;
13
14
  unique?: boolean;
14
15
  default?: string;
16
+ index?: boolean | indexOptions;
15
17
  foreignKey?: {
16
18
  table: string;
17
19
  col: string;
@@ -20,22 +22,31 @@ interface Column extends SchemaItem {
20
22
  interface Constraint extends SchemaItem {
21
23
  generate(): string;
22
24
  }
25
+ interface Index extends SchemaItem {
26
+ generate(): string;
27
+ postCreate?(): boolean;
28
+ }
23
29
  export interface CoreConcept {
24
30
  name: string;
25
31
  create(): string;
32
+ postCreate?(): string[];
26
33
  drop(): string;
27
34
  }
28
35
  export interface Table extends CoreConcept {
29
36
  columns: Column[];
30
37
  constraints?: Constraint[];
31
38
  }
32
- declare type options = Pick<Column, "nullable" | "primaryKey" | "default" | "foreignKey" | "unique">;
39
+ declare type options = Pick<Column, "nullable" | "primaryKey" | "default" | "foreignKey" | "unique" | "index">;
33
40
  export declare function primaryKey(name: string, cols: string[]): Constraint;
34
41
  export declare function foreignKey(name: string, cols: string[], fkey: {
35
42
  table: string;
36
43
  cols: string[];
37
44
  }): Constraint;
38
- export declare function uniqueIndex(name: string): Constraint;
45
+ interface indexOptions {
46
+ type?: string;
47
+ unique?: boolean;
48
+ }
49
+ export declare function index(tableName: string, cols: string[], opts?: indexOptions): Index;
39
50
  export declare function uuid(name: string, opts?: options): Column;
40
51
  export declare function text(name: string, opts?: options): Column;
41
52
  export declare function enumCol(name: string, type: string): Column;
@@ -67,11 +78,12 @@ export declare class TempDB {
67
78
  private tables;
68
79
  private dialect;
69
80
  private sqlite;
70
- constructor(dialect: Dialect, tables?: CoreConcept[]);
71
- constructor(tables: CoreConcept[]);
81
+ private setTables;
82
+ constructor(dialect: Dialect, tables?: CoreConcept[] | (() => CoreConcept[]));
72
83
  getDialect(): Dialect;
73
- getTables(): Map<string, CoreConcept>;
84
+ __getTables(): Map<string, CoreConcept>;
74
85
  beforeAll(setupConnString?: boolean): Promise<void>;
86
+ createImpl(table: CoreConcept): Promise<void>;
75
87
  getSqliteClient(): SqliteDatabase;
76
88
  getPostgresClient(): PGClient;
77
89
  afterAll(): Promise<void>;
@@ -81,10 +93,11 @@ export declare class TempDB {
81
93
  create(...tables: CoreConcept[]): Promise<void>;
82
94
  }
83
95
  export declare function assoc_edge_config_table(): Table;
84
- export declare function assoc_edge_table(name: string): Table;
96
+ export declare function assoc_edge_table(name: string, global?: boolean): Table;
85
97
  interface sqliteSetupOptions {
86
98
  disableDeleteAfterEachTest?: boolean;
87
99
  }
88
- export declare function setupSqlite(connString: string, tables: () => Table[], opts?: sqliteSetupOptions): void;
100
+ export declare function setupSqlite(connString: string, tables: () => Table[], opts?: sqliteSetupOptions): TempDB;
89
101
  export declare function getSchemaTable(schema: BuilderSchema<Ent>, dialect: Dialect): Table;
102
+ export declare function getColumnFromField(fieldName: string, f: Field, dialect: Dialect): Column;
90
103
  export {};
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
@@ -22,7 +26,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
22
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
23
27
  };
24
28
  Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.getSchemaTable = exports.setupSqlite = exports.assoc_edge_table = exports.assoc_edge_config_table = exports.TempDB = exports.enumType = exports.table = exports.boolList = exports.dateList = exports.timetzList = exports.timeList = exports.timestamptzList = exports.timestampList = exports.uuidList = exports.integerList = exports.textList = exports.jsonb = exports.json = exports.float = exports.integer = exports.bool = exports.date = exports.timetz = exports.time = exports.timestamptz = exports.timestamp = exports.enumCol = exports.text = exports.uuid = exports.uniqueIndex = exports.foreignKey = exports.primaryKey = void 0;
29
+ exports.getColumnFromField = exports.getSchemaTable = exports.setupSqlite = exports.assoc_edge_table = exports.assoc_edge_config_table = exports.TempDB = exports.enumType = exports.table = exports.boolList = exports.dateList = exports.timetzList = exports.timeList = exports.timestamptzList = exports.timestampList = exports.uuidList = exports.integerList = exports.textList = exports.jsonb = exports.json = exports.float = exports.integer = exports.bool = exports.date = exports.timetz = exports.time = exports.timestamptz = exports.timestamp = exports.enumCol = exports.text = exports.uuid = exports.index = exports.foreignKey = exports.primaryKey = void 0;
26
30
  const pg_1 = require("pg");
27
31
  const db_1 = __importStar(require("../../core/db"));
28
32
  // this should only be used in tests so we expect to be able to import without shenanigans
@@ -32,6 +36,7 @@ const fs = __importStar(require("fs"));
32
36
  const schema_1 = require("../../schema");
33
37
  const snake_case_1 = require("snake-case");
34
38
  const builder_1 = require("../builder");
39
+ const test_edge_global_schema_1 = require("../test_edge_global_schema");
35
40
  function primaryKey(name, cols) {
36
41
  return {
37
42
  name: name,
@@ -50,15 +55,26 @@ function foreignKey(name, cols, fkey) {
50
55
  };
51
56
  }
52
57
  exports.foreignKey = foreignKey;
53
- function uniqueIndex(name) {
58
+ function isPostCreateIndex(s) {
59
+ return (s.postCreate !== undefined &&
60
+ s.postCreate());
61
+ }
62
+ function index(tableName, cols, opts) {
63
+ const name = `${tableName}_${cols.join("_")}_idx`;
54
64
  return {
55
- name: "",
65
+ name,
56
66
  generate() {
57
- return `UNIQUE (${name})`;
67
+ if (opts?.unique && db_1.Dialect.SQLite === db_1.default.getDialect()) {
68
+ return `UNIQUE (${cols.join(",")})`;
69
+ }
70
+ return `CREATE ${opts?.unique ? "UNIQUE " : ""}INDEX ${name} ON ${tableName} USING ${opts?.type || "btree"} (${cols.join(",")});`;
71
+ },
72
+ postCreate() {
73
+ return db_1.Dialect.Postgres === db_1.default.getDialect() && !!opts?.unique;
58
74
  },
59
75
  };
60
76
  }
61
- exports.uniqueIndex = uniqueIndex;
77
+ exports.index = index;
62
78
  function uuid(name, opts) {
63
79
  return {
64
80
  name,
@@ -248,9 +264,24 @@ exports.boolList = boolList;
248
264
  function table(name, ...items) {
249
265
  let cols = [];
250
266
  let constraints = [];
267
+ let indexes = [];
251
268
  for (const item of items) {
252
269
  if (item.datatype !== undefined) {
253
270
  const col = item;
271
+ if (col.index) {
272
+ let opts = {
273
+ type: "btree",
274
+ };
275
+ if (col.index === true) {
276
+ opts = {
277
+ type: "btree",
278
+ };
279
+ }
280
+ else {
281
+ opts = col.index;
282
+ }
283
+ indexes.push(index(name, [col.name], opts));
284
+ }
254
285
  // add it as a constraint
255
286
  if (col.foreignKey) {
256
287
  constraints.push(foreignKey(`${name}_${col.name}_fkey`, [col.name], {
@@ -261,7 +292,12 @@ function table(name, ...items) {
261
292
  cols.push(item);
262
293
  }
263
294
  else if (item.generate !== undefined) {
264
- constraints.push(item);
295
+ if (isPostCreateIndex(item) && item.postCreate()) {
296
+ indexes.push(item);
297
+ }
298
+ else {
299
+ constraints.push(item);
300
+ }
265
301
  }
266
302
  }
267
303
  return {
@@ -278,7 +314,12 @@ function table(name, ...items) {
278
314
  parts.push("PRIMARY KEY");
279
315
  }
280
316
  if (col.default !== undefined) {
281
- parts.push(`DEFAULT ${col.default}`);
317
+ if (db_1.Dialect.SQLite === db_1.default.getDialect()) {
318
+ parts.push(`DEFAULT "${col.default}"`);
319
+ }
320
+ else {
321
+ parts.push(`DEFAULT ${col.default}`);
322
+ }
282
323
  }
283
324
  if (col.unique) {
284
325
  parts.push("UNIQUE");
@@ -288,6 +329,9 @@ function table(name, ...items) {
288
329
  constraints.forEach((constraint) => schemaStr.push(constraint.generate()));
289
330
  return `CREATE TABLE IF NOT EXISTS ${name} (\n ${schemaStr})`;
290
331
  },
332
+ postCreate() {
333
+ return indexes.map((index) => index.generate());
334
+ },
291
335
  drop() {
292
336
  return `DROP TABLE IF EXISTS ${name}`;
293
337
  },
@@ -317,23 +361,15 @@ function isDialect(dialect) {
317
361
  class TempDB {
318
362
  constructor(dialect, tables) {
319
363
  this.tables = new Map();
320
- let tbles = [];
321
- if (isDialect(dialect)) {
322
- this.dialect = dialect;
323
- if (tables) {
324
- tbles = tables;
325
- }
326
- }
327
- else {
328
- this.dialect = db_1.Dialect.Postgres;
329
- tbles = dialect;
330
- }
331
- tbles.forEach((table) => this.tables.set(table.name, table));
364
+ this.dialect = dialect;
365
+ this.setTables = tables;
332
366
  }
333
367
  getDialect() {
334
368
  return this.dialect;
335
369
  }
336
- getTables() {
370
+ // NB: this won't be set until after beforeAll() is called since it depends on
371
+ // dialect being correctly set
372
+ __getTables() {
337
373
  return this.tables;
338
374
  }
339
375
  async beforeAll(setupConnString = true) {
@@ -355,6 +391,7 @@ class TempDB {
355
391
  else {
356
392
  process.env.DB_CONNECTION_STRING = `postgres://localhost/${this.db}?`;
357
393
  }
394
+ db_1.default.initDB();
358
395
  }
359
396
  else {
360
397
  // will probably be setup via loadConfig
@@ -375,12 +412,35 @@ class TempDB {
375
412
  const filePath = process.env.DB_CONNECTION_STRING.substr(10);
376
413
  this.sqlite = (0, better_sqlite3_1.default)(filePath);
377
414
  }
378
- for (const [_, table] of this.tables) {
379
- if (this.dialect == db_1.Dialect.Postgres) {
380
- await this.dbClient.query(table.create());
415
+ if (this.setTables) {
416
+ let tables = [];
417
+ if (typeof this.setTables === "function") {
418
+ tables = this.setTables();
381
419
  }
382
420
  else {
383
- this.sqlite.exec(table.create());
421
+ tables = this.setTables;
422
+ }
423
+ tables.forEach((table) => this.tables.set(table.name, table));
424
+ }
425
+ for (const [_, table] of this.tables) {
426
+ await this.createImpl(table);
427
+ }
428
+ }
429
+ async createImpl(table) {
430
+ if (this.dialect == db_1.Dialect.Postgres) {
431
+ await this.dbClient.query(table.create());
432
+ if (table.postCreate) {
433
+ for (const q of table.postCreate()) {
434
+ await this.dbClient.query(q);
435
+ }
436
+ }
437
+ }
438
+ else {
439
+ this.sqlite.exec(table.create());
440
+ if (table.postCreate) {
441
+ for (const q of table.postCreate()) {
442
+ this.sqlite.exec(q);
443
+ }
384
444
  }
385
445
  }
386
446
  }
@@ -431,12 +491,7 @@ class TempDB {
431
491
  if (this.tables.has(table.name)) {
432
492
  throw new Error(`table with name ${table.name} already exists`);
433
493
  }
434
- if (this.dialect === db_1.Dialect.Postgres) {
435
- await this.dbClient.query(table.create());
436
- }
437
- else {
438
- this.sqlite.exec(table.create());
439
- }
494
+ await this.createImpl(table);
440
495
  this.tables.set(table.name, table);
441
496
  }
442
497
  }
@@ -448,18 +503,26 @@ function assoc_edge_config_table() {
448
503
  text("edge_type", { primaryKey: true }), text("edge_name"), bool("symmetric_edge", { default: "FALSE" }), text("inverse_edge_type", { nullable: true }), text("edge_table"), timestamptz("created_at"), timestamptz("updated_at"));
449
504
  }
450
505
  exports.assoc_edge_config_table = assoc_edge_config_table;
451
- function assoc_edge_table(name) {
452
- return table(name, uuid("id1"), text("id1_type"),
506
+ // if global flag is true, add any column from testEdgeGlobalSchema
507
+ // up to caller to set/clear that as needed
508
+ function assoc_edge_table(name, global) {
509
+ const t = table(name, uuid("id1"), text("id1_type"),
453
510
  // same as in assoc_edge_config_table
454
511
  text("edge_type"), uuid("id2"), text("id2_type"), timestamptz("time"), text("data", { nullable: true }), primaryKey(`${name}_pkey`, ["id1", "id2", "edge_type"]));
512
+ if (global) {
513
+ for (const k in test_edge_global_schema_1.testEdgeGlobalSchema.extraEdgeFields) {
514
+ const col = getColumnFromField(k, test_edge_global_schema_1.testEdgeGlobalSchema.extraEdgeFields[k], db_1.Dialect.Postgres);
515
+ t.columns.push(col);
516
+ }
517
+ }
518
+ return t;
455
519
  }
456
520
  exports.assoc_edge_table = assoc_edge_table;
457
521
  function setupSqlite(connString, tables, opts) {
458
- let tdb;
522
+ let tdb = new TempDB(db_1.Dialect.SQLite, tables);
459
523
  beforeAll(async () => {
460
524
  process.env.DB_CONNECTION_STRING = connString;
461
525
  (0, config_1.loadConfig)();
462
- tdb = new TempDB(db_1.Dialect.SQLite, tables());
463
526
  await tdb.beforeAll();
464
527
  const conn = db_1.default.getInstance().getConnection();
465
528
  expect(conn.db.memory).toBe(false);
@@ -467,7 +530,7 @@ function setupSqlite(connString, tables, opts) {
467
530
  if (!opts?.disableDeleteAfterEachTest) {
468
531
  afterEach(async () => {
469
532
  const client = await db_1.default.getInstance().getNewClient();
470
- for (const [key, _] of tdb.getTables()) {
533
+ for (const [key, _] of tdb.__getTables()) {
471
534
  const query = `delete from ${key}`;
472
535
  if (isSyncClient(client))
473
536
  if (client.execSync) {
@@ -482,7 +545,9 @@ function setupSqlite(connString, tables, opts) {
482
545
  afterAll(async () => {
483
546
  await tdb.afterAll();
484
547
  fs.rmSync(tdb.getSqliteClient().name);
548
+ delete process.env.DB_CONNECTION_STRING;
485
549
  });
550
+ return tdb;
486
551
  }
487
552
  exports.setupSqlite = setupSqlite;
488
553
  function getSchemaTable(schema, dialect) {
@@ -549,6 +614,7 @@ function getColumnFromField(fieldName, f, dialect) {
549
614
  return getColumn(fieldName, f, fn);
550
615
  }
551
616
  }
617
+ exports.getColumnFromField = getColumnFromField;
552
618
  function getColumn(fieldName, f, col) {
553
619
  return col(storageKey(fieldName, f), buildOpts(f));
554
620
  }
@@ -0,0 +1,6 @@
1
+ import { Field, Schema } from "../../schema";
2
+ interface Info {
3
+ schema: Schema;
4
+ }
5
+ export declare function getDefaultValue(f: Field, col: string, infos?: Map<string, Info>): any;
6
+ export {};
@@ -0,0 +1,251 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getDefaultValue = void 0;
4
+ const uuid_1 = require("uuid");
5
+ const schema_1 = require("../../schema");
6
+ const schema_2 = require("../../schema");
7
+ function random() {
8
+ return Math.random().toString(16).substring(2);
9
+ }
10
+ function randomEmail(domain) {
11
+ domain = domain || "email.com";
12
+ return `test+${random()}@${domain}`;
13
+ }
14
+ function randomPhoneNumber() {
15
+ return `+1${Math.random().toString(10).substring(2, 11)}`;
16
+ }
17
+ function coinFlip() {
18
+ return Math.floor(Math.random() * 10) >= 5;
19
+ }
20
+ function specialType(typ, col) {
21
+ let list = m.get(typ.dbType);
22
+ if (list?.length) {
23
+ for (const l of list) {
24
+ let regex = [];
25
+ if (Array.isArray(l.regex)) {
26
+ regex = l.regex;
27
+ }
28
+ else {
29
+ regex = [l.regex];
30
+ }
31
+ for (const r of regex) {
32
+ if (r.test(col)) {
33
+ return l.newValue();
34
+ }
35
+ }
36
+ }
37
+ }
38
+ return undefined;
39
+ }
40
+ function getDefaultValue(f, col, infos) {
41
+ if (f.defaultValueOnCreate) {
42
+ // @ts-ignore
43
+ return f.defaultValueOnCreate();
44
+ }
45
+ // half the time, return null for nullable
46
+ if (f.nullable && coinFlip()) {
47
+ return null;
48
+ }
49
+ const specialVal = specialType(f.type, col);
50
+ if (specialVal !== undefined) {
51
+ return specialVal;
52
+ }
53
+ return getValueForType(f.type, f, infos);
54
+ }
55
+ exports.getDefaultValue = getDefaultValue;
56
+ function getValueForType(typ, f, infos) {
57
+ switch (typ.dbType) {
58
+ case schema_1.DBType.UUID:
59
+ return (0, uuid_1.v4)();
60
+ case schema_1.DBType.Boolean:
61
+ return coinFlip();
62
+ case schema_1.DBType.Date:
63
+ return (0, schema_2.DateType)().format(new Date());
64
+ case schema_1.DBType.Time:
65
+ return (0, schema_2.TimeType)().format(new Date());
66
+ case schema_1.DBType.Timetz:
67
+ return (0, schema_2.TimetzType)().format(new Date());
68
+ case schema_1.DBType.Timestamp:
69
+ return (0, schema_2.TimestampType)().format(new Date());
70
+ case schema_1.DBType.Timestamptz:
71
+ return (0, schema_2.TimestamptzType)().format(new Date());
72
+ case schema_1.DBType.String:
73
+ return random();
74
+ case schema_1.DBType.Int:
75
+ return Math.floor(Math.random() * 100000000);
76
+ case schema_1.DBType.Float:
77
+ return Math.random() * 100000000;
78
+ case schema_1.DBType.Enum:
79
+ case schema_1.DBType.StringEnum:
80
+ if (typ.values) {
81
+ const idx = Math.floor(Math.random() * typ.values.length);
82
+ return typ.values[idx];
83
+ }
84
+ if (typ.enumMap) {
85
+ const vals = Object.values(typ.enumMap);
86
+ const idx = Math.floor(Math.random() * vals.length);
87
+ return vals[idx];
88
+ }
89
+ if (f.foreignKey) {
90
+ const schema = f.foreignKey.schema;
91
+ const col = f.foreignKey.column;
92
+ if (!infos) {
93
+ throw new Error(`infos required for enum with foreignKey`);
94
+ }
95
+ const info = infos.get(schema);
96
+ if (!info) {
97
+ throw new Error(`couldn't load data for schema ${schema}`);
98
+ }
99
+ if (!info.schema.dbRows) {
100
+ throw new Error(`no dbRows for schema ${schema}`);
101
+ }
102
+ const idx = Math.floor(Math.random() * info.schema.dbRows.length);
103
+ return info.schema.dbRows[idx][col];
104
+ }
105
+ throw new Error("TODO: enum without values not currently supported");
106
+ case schema_1.DBType.IntEnum:
107
+ const vals = Object.values(typ.intEnumMap);
108
+ const idx = Math.floor(Math.random() * vals.length);
109
+ return vals[idx];
110
+ case schema_1.DBType.BigInt:
111
+ return BigInt(Math.floor(Math.random() * 100000000));
112
+ case schema_1.DBType.JSONB:
113
+ // type as list
114
+ if (typ.listElemType?.dbType === schema_1.DBType.JSONB) {
115
+ const values = [];
116
+ for (let i = 0; i < 10; i++) {
117
+ values.push(getValueForType(typ.listElemType, f, infos));
118
+ }
119
+ if (!f.format) {
120
+ throw new Error("invalid format");
121
+ }
122
+ return f.format(values);
123
+ }
124
+ return (0, schema_2.JSONBType)().format({});
125
+ case schema_1.DBType.JSON:
126
+ return (0, schema_2.JSONType)().format({});
127
+ case schema_1.DBType.List:
128
+ // just do 10
129
+ const values = [];
130
+ for (let i = 0; i < 10; i++) {
131
+ values.push(getValueForType(f.type.listElemType, f.__getElemField(), infos));
132
+ }
133
+ if (!f.format) {
134
+ throw new Error("invalid format");
135
+ }
136
+ return f.format(values);
137
+ default:
138
+ throw new Error(`unsupported type ${typ.dbType}`);
139
+ }
140
+ }
141
+ const emailType = {
142
+ dbType: schema_1.DBType.String,
143
+ newValue: () => {
144
+ return (0, schema_2.StringType)().format(randomEmail().toLowerCase());
145
+ },
146
+ regex: /^email(_address)|_email$/,
147
+ };
148
+ const pdt = (0, schema_2.StringType)();
149
+ const phoneType = {
150
+ dbType: schema_1.DBType.String,
151
+ newValue: () => {
152
+ return randomPhoneNumber();
153
+ },
154
+ regex: /^phone(_number)?|_phone$|_phone_number$/,
155
+ };
156
+ const passwordType = {
157
+ dbType: schema_1.DBType.String,
158
+ newValue: () => {
159
+ // we don't use password type because when we're generating so many rows, it's too slow...
160
+ return random();
161
+ },
162
+ regex: /^password/,
163
+ };
164
+ const firstNames = [
165
+ "Daenerys",
166
+ "Jon",
167
+ "Arya",
168
+ "Sansa",
169
+ "Eddard",
170
+ "Khal",
171
+ "Robb",
172
+ "Joffrey",
173
+ "Ramsay",
174
+ "Cersei",
175
+ "Bolton",
176
+ "Oberyn",
177
+ "Jojen",
178
+ "Petyr",
179
+ "Brienne",
180
+ "Ygritte",
181
+ "Missandei",
182
+ "Shae",
183
+ "Sandor",
184
+ "Theon",
185
+ "Catelyn",
186
+ "Gilly",
187
+ "Samwell",
188
+ "Jaime",
189
+ "Stannis",
190
+ "Tyene",
191
+ "Obara",
192
+ "Nymeria",
193
+ "Elia",
194
+ "Ellaria",
195
+ "Myrcella",
196
+ "Hodor",
197
+ "Osha",
198
+ "Meera",
199
+ "Davos",
200
+ "Gendry",
201
+ ];
202
+ const lastNames = [
203
+ "Stark",
204
+ "Targaryen",
205
+ "Lannister",
206
+ "Drogo",
207
+ "Baratheon",
208
+ "Reed",
209
+ "Martell",
210
+ "Tyrell",
211
+ "Clegane",
212
+ "Baelish",
213
+ "Greyjoy",
214
+ "Tarly",
215
+ "Sand",
216
+ "Snow",
217
+ "Bolton",
218
+ "Frey",
219
+ "Tarth",
220
+ "Payne",
221
+ "Seaworth",
222
+ ];
223
+ const firstNameType = {
224
+ dbType: schema_1.DBType.String,
225
+ newValue: () => {
226
+ let idx = Math.floor(firstNames.length * Math.random());
227
+ return firstNames[idx];
228
+ },
229
+ regex: /^first_?(name)?/,
230
+ };
231
+ const lastNameType = {
232
+ dbType: schema_1.DBType.String,
233
+ newValue: () => {
234
+ let idx = Math.floor(lastNames.length * Math.random());
235
+ return lastNames[idx];
236
+ },
237
+ regex: /^last_?(name)?/,
238
+ };
239
+ let types = [
240
+ phoneType,
241
+ emailType,
242
+ passwordType,
243
+ firstNameType,
244
+ lastNameType,
245
+ ];
246
+ let m = new Map();
247
+ for (const type of types) {
248
+ let list = m.get(type.dbType) || [];
249
+ list.push(type);
250
+ m.set(type.dbType, list);
251
+ }
@@ -185,7 +185,9 @@ class QueryRecorder {
185
185
  }
186
186
  }
187
187
  static mockPool(pool) {
188
- const mockedPool = (0, jest_mock_1.mocked)(pool, true);
188
+ const mockedPool = (0, jest_mock_1.mocked)(pool);
189
+ // @ts-ignore
190
+ // TODO what changed in mockImplementation?
189
191
  mockedPool.mockImplementation(() => {
190
192
  return {
191
193
  totalCount: 1,
@@ -0,0 +1,4 @@
1
+ export declare class DBTimeZone {
2
+ private static getVal;
3
+ static getDateOffset(d: Date): Promise<string>;
4
+ }
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DBTimeZone = void 0;
7
+ const luxon_1 = require("luxon");
8
+ const schema_1 = require("../schema");
9
+ const db_1 = __importDefault(require("../core/db"));
10
+ let dbCurrentZone = undefined;
11
+ class DBTimeZone {
12
+ static async getVal() {
13
+ if (dbCurrentZone !== undefined) {
14
+ return dbCurrentZone;
15
+ }
16
+ const r = await db_1.default.getInstance()
17
+ .getPool()
18
+ .query("SELECT current_setting('TIMEZONE');");
19
+ if (r.rows.length) {
20
+ dbCurrentZone = r.rows[0].current_setting;
21
+ }
22
+ else {
23
+ dbCurrentZone = null;
24
+ }
25
+ return dbCurrentZone;
26
+ }
27
+ static async getDateOffset(d) {
28
+ let zone = await DBTimeZone.getVal();
29
+ let dt = luxon_1.DateTime.fromJSDate(d);
30
+ if (zone) {
31
+ dt = dt.setZone(zone);
32
+ }
33
+ // use
34
+ const val = (0, schema_1.leftPad)(dt.get("offset") / 60);
35
+ if (val == "00") {
36
+ return "+00";
37
+ }
38
+ return val;
39
+ }
40
+ }
41
+ exports.DBTimeZone = DBTimeZone;