@snowtop/ent 0.1.0-alpha54 → 0.1.0-alpha59

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 (38) hide show
  1. package/action/orchestrator.js +21 -0
  2. package/core/base.d.ts +1 -1
  3. package/core/clause.d.ts +36 -7
  4. package/core/clause.js +133 -32
  5. package/core/config.d.ts +5 -2
  6. package/core/ent.d.ts +16 -3
  7. package/core/ent.js +147 -35
  8. package/core/loaders/assoc_count_loader.js +6 -1
  9. package/core/query/shared_assoc_test.d.ts +1 -1
  10. package/core/query/shared_assoc_test.js +17 -5
  11. package/core/query/shared_test.d.ts +3 -0
  12. package/core/query/shared_test.js +95 -17
  13. package/index.d.ts +5 -5
  14. package/index.js +7 -6
  15. package/package.json +1 -1
  16. package/parse_schema/parse.d.ts +8 -2
  17. package/parse_schema/parse.js +35 -2
  18. package/schema/index.d.ts +1 -1
  19. package/schema/schema.d.ts +20 -1
  20. package/scripts/custom_graphql.js +2 -0
  21. package/scripts/read_schema.js +10 -1
  22. package/testutils/db/{test_db.d.ts → temp_db.d.ts} +15 -3
  23. package/testutils/db/{test_db.js → temp_db.js} +62 -15
  24. package/testutils/fake_data/fake_contact.d.ts +1 -1
  25. package/testutils/fake_data/fake_contact.js +2 -2
  26. package/testutils/fake_data/fake_event.d.ts +1 -1
  27. package/testutils/fake_data/fake_event.js +3 -3
  28. package/testutils/fake_data/fake_user.d.ts +1 -1
  29. package/testutils/fake_data/fake_user.js +2 -2
  30. package/testutils/fake_data/test_helpers.d.ts +2 -2
  31. package/testutils/fake_data/test_helpers.js +5 -5
  32. package/testutils/parse_sql.js +4 -0
  33. package/testutils/test_edge_global_schema.d.ts +15 -0
  34. package/testutils/test_edge_global_schema.js +58 -0
  35. package/testutils/write.d.ts +2 -2
  36. package/testutils/write.js +3 -3
  37. package/tsc/ast.d.ts +1 -0
  38. package/tsc/ast.js +3 -0
package/core/ent.js CHANGED
@@ -22,13 +22,15 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
22
22
  return (mod && mod.__esModule) ? mod : { "default": mod };
23
23
  };
24
24
  Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.getEdgeTypeInGroup = exports.applyPrivacyPolicyForRows = exports.applyPrivacyPolicyForRowX = exports.applyPrivacyPolicyForRow = exports.loadNodesByEdge = exports.loadEdgeForID2 = exports.loadRawEdgeCountX = exports.loadUniqueNode = exports.loadUniqueEdge = exports.loadCustomEdges = exports.loadEdges = exports.defaultEdgeQueryOptions = exports.DefaultLimit = exports.loadEdgeDatas = exports.loadEdgeData = exports.assocEdgeLoader = exports.AssocEdgeData = exports.getCursor = exports.AssocEdge = exports.DeleteNodeOperation = exports.deleteRowsSync = exports.deleteRows = exports.editRowSync = exports.editRow = exports.buildUpdateQuery = exports.createRowSync = exports.createRow = exports.buildInsertQuery = exports.EdgeOperation = exports.EditNodeOperation = exports.buildGroupQuery = exports.buildQuery = exports.loadRows = exports.performRawQuery = exports.loadRow = exports.loadRowX = exports.loadDerivedEntX = exports.loadDerivedEnt = exports.loadCustomData = exports.loadCustomEnts = exports.loadEntsFromClause = exports.loadEntsList = exports.loadEnts = exports.loadEntXFromClause = exports.loadEntFromClause = exports.loadEntXViaKey = exports.loadEntX = exports.loadEntViaKey = exports.loadEnt = void 0;
25
+ exports.applyPrivacyPolicyForRow = exports.loadNodesByEdge = exports.loadEdgeForID2 = exports.loadRawEdgeCountX = exports.loadUniqueNode = exports.loadUniqueEdge = exports.loadCustomEdges = exports.getEdgeClauseAndFields = exports.loadEdges = exports.defaultEdgeQueryOptions = exports.DefaultLimit = exports.loadEdgeDatas = exports.loadEdgeData = exports.assocEdgeLoader = exports.AssocEdgeData = exports.getCursor = exports.AssocEdge = exports.DeleteNodeOperation = exports.deleteRowsSync = exports.deleteRows = exports.editRowSync = exports.editRow = exports.buildUpdateQuery = exports.createRowSync = exports.createRow = exports.buildInsertQuery = exports.EdgeOperation = exports.__hasGlobalSchema = exports.clearGlobalSchema = exports.setGlobalSchema = exports.EditNodeOperation = exports.buildGroupQuery = exports.buildQuery = exports.loadRows = exports.performRawQuery = exports.loadRow = exports.loadRowX = exports.loadDerivedEntX = exports.loadDerivedEnt = exports.loadCustomData = exports.loadCustomEnts = exports.loadEntsFromClause = exports.loadEntsList = exports.loadEnts = exports.loadEntXFromClause = exports.loadEntFromClause = exports.loadEntXViaKey = exports.loadEntX = exports.loadEntViaKey = exports.loadEnt = void 0;
26
+ exports.getEdgeTypeInGroup = exports.applyPrivacyPolicyForRows = exports.applyPrivacyPolicyForRowX = void 0;
26
27
  const db_1 = __importStar(require("./db"));
27
28
  const privacy_1 = require("./privacy");
28
29
  const clause = __importStar(require("./clause"));
29
30
  const action_1 = require("../action");
30
31
  const logger_1 = require("./logger");
31
32
  const dataloader_1 = __importDefault(require("dataloader"));
33
+ const schema_1 = require("../schema/");
32
34
  // TODO kill this and createDataLoader
33
35
  class cacheMap {
34
36
  constructor(options) {
@@ -473,7 +475,7 @@ class EditNodeOperation {
473
475
  if (this.hasData(options.fields)) {
474
476
  // even this with returning * may not always work if transformed...
475
477
  // we can have a transformed flag to see if it should be returned?
476
- this.row = await editRow(queryer, options, this.existingEnt.id, "RETURNING *");
478
+ this.row = await editRow(queryer, options, "RETURNING *");
477
479
  }
478
480
  else {
479
481
  // @ts-ignore
@@ -523,7 +525,7 @@ class EditNodeOperation {
523
525
  };
524
526
  if (this.existingEnt) {
525
527
  if (this.hasData(this.options.fields)) {
526
- editRowSync(queryer, options, this.existingEnt.id, "RETURNING *");
528
+ editRowSync(queryer, options, "RETURNING *");
527
529
  this.reloadRow(queryer, this.existingEnt.id, options);
528
530
  }
529
531
  else {
@@ -548,8 +550,23 @@ class EditNodeOperation {
548
550
  }
549
551
  }
550
552
  exports.EditNodeOperation = EditNodeOperation;
553
+ let globalSchema;
554
+ function setGlobalSchema(val) {
555
+ globalSchema = val;
556
+ }
557
+ exports.setGlobalSchema = setGlobalSchema;
558
+ function clearGlobalSchema() {
559
+ globalSchema = undefined;
560
+ }
561
+ exports.clearGlobalSchema = clearGlobalSchema;
562
+ // used by tests. no guarantee will always exist
563
+ function __hasGlobalSchema() {
564
+ return globalSchema !== undefined;
565
+ }
566
+ exports.__hasGlobalSchema = __hasGlobalSchema;
551
567
  class EdgeOperation {
552
- constructor(edgeInput, options) {
568
+ constructor(builder, edgeInput, options) {
569
+ this.builder = builder;
553
570
  this.edgeInput = edgeInput;
554
571
  this.options = options;
555
572
  }
@@ -585,7 +602,31 @@ class EdgeOperation {
585
602
  }
586
603
  }
587
604
  getDeleteRowParams(edgeData, edge, context) {
605
+ let transformed = null;
606
+ let op = schema_1.SQLStatementOperation.Delete;
607
+ let updateData = null;
608
+ // TODO respect disableTransformations
609
+ if (globalSchema?.transformEdgeWrite) {
610
+ transformed = globalSchema.transformEdgeWrite({
611
+ op: schema_1.SQLStatementOperation.Delete,
612
+ edge,
613
+ });
614
+ if (transformed) {
615
+ op = transformed.op;
616
+ if (transformed.op === schema_1.SQLStatementOperation.Insert) {
617
+ throw new Error(`cannot currently transform a delete into an insert`);
618
+ }
619
+ if (transformed.op === schema_1.SQLStatementOperation.Update) {
620
+ if (!transformed.data) {
621
+ throw new Error(`cannot transform a delete into an update without providing data`);
622
+ }
623
+ updateData = transformed.data;
624
+ }
625
+ }
626
+ }
588
627
  return {
628
+ op,
629
+ updateData,
589
630
  options: {
590
631
  tableName: edgeData.edgeTable,
591
632
  context,
@@ -595,11 +636,35 @@ class EdgeOperation {
595
636
  }
596
637
  async performDeleteWrite(q, edgeData, edge, context) {
597
638
  const params = this.getDeleteRowParams(edgeData, edge, context);
598
- return deleteRows(q, params.options, params.clause);
639
+ if (params.op === schema_1.SQLStatementOperation.Delete) {
640
+ return deleteRows(q, params.options, params.clause);
641
+ }
642
+ else {
643
+ if (params.op !== schema_1.SQLStatementOperation.Update) {
644
+ throw new Error(`invalid operation ${params.op}`);
645
+ }
646
+ await editRow(q, {
647
+ tableName: params.options.tableName,
648
+ whereClause: params.clause,
649
+ fields: params.updateData,
650
+ });
651
+ }
599
652
  }
600
653
  performDeleteWriteSync(q, edgeData, edge, context) {
601
654
  const params = this.getDeleteRowParams(edgeData, edge, context);
602
- return deleteRowsSync(q, params.options, params.clause);
655
+ if (params.op === schema_1.SQLStatementOperation.Delete) {
656
+ return deleteRowsSync(q, params.options, params.clause);
657
+ }
658
+ else {
659
+ if (params.op !== schema_1.SQLStatementOperation.Update) {
660
+ throw new Error(`invalid operation ${params.op}`);
661
+ }
662
+ editRowSync(q, {
663
+ tableName: params.options.tableName,
664
+ whereClause: params.clause,
665
+ fields: params.updateData,
666
+ });
667
+ }
603
668
  }
604
669
  getInsertRowParams(edgeData, edge, context) {
605
670
  const fields = {
@@ -618,6 +683,30 @@ class EdgeOperation {
618
683
  // maybe when actions exist?
619
684
  fields["time"] = new Date().toISOString();
620
685
  }
686
+ const onConflictFields = ["data"];
687
+ if (globalSchema?.extraEdgeFields) {
688
+ for (const name in globalSchema.extraEdgeFields) {
689
+ const f = globalSchema.extraEdgeFields[name];
690
+ if (f.defaultValueOnCreate) {
691
+ const storageKey = (0, schema_1.getStorageKey)(f, name);
692
+ fields[storageKey] = f.defaultValueOnCreate(this.builder, {});
693
+ // onconflict make sure we override the default values
694
+ // e.g. setting deleted_at = null for soft delete
695
+ onConflictFields.push(storageKey);
696
+ }
697
+ }
698
+ }
699
+ // TODO respect disableTransformations
700
+ let transformed = null;
701
+ if (globalSchema?.transformEdgeWrite) {
702
+ transformed = globalSchema.transformEdgeWrite({
703
+ op: schema_1.SQLStatementOperation.Insert,
704
+ edge,
705
+ });
706
+ if (transformed) {
707
+ throw new Error(`transforming an insert edge not currently supported`);
708
+ }
709
+ }
621
710
  return [
622
711
  {
623
712
  tableName: edgeData.edgeTable,
@@ -625,7 +714,9 @@ class EdgeOperation {
625
714
  fieldsToLog: fields,
626
715
  context,
627
716
  },
628
- "ON CONFLICT(id1, edge_type, id2) DO UPDATE SET data = EXCLUDED.data",
717
+ `ON CONFLICT(id1, edge_type, id2) DO UPDATE SET ${onConflictFields
718
+ .map((f) => `${f} = EXCLUDED.${f}`)
719
+ .join(", ")}`,
629
720
  ];
630
721
  }
631
722
  async performInsertWrite(q, edgeData, edge, context) {
@@ -662,7 +753,7 @@ class EdgeOperation {
662
753
  }
663
754
  }
664
755
  symmetricEdge() {
665
- return new EdgeOperation({
756
+ return new EdgeOperation(this.builder, {
666
757
  id1: this.edgeInput.id2,
667
758
  id1Type: this.edgeInput.id2Type,
668
759
  id2: this.edgeInput.id1,
@@ -678,7 +769,7 @@ class EdgeOperation {
678
769
  });
679
770
  }
680
771
  inverseEdge(edgeData) {
681
- return new EdgeOperation({
772
+ return new EdgeOperation(this.builder, {
682
773
  id1: this.edgeInput.id2,
683
774
  id1Type: this.edgeInput.id2Type,
684
775
  id2: this.edgeInput.id1,
@@ -746,7 +837,7 @@ class EdgeOperation {
746
837
  if (data) {
747
838
  edge.data = data;
748
839
  }
749
- return new EdgeOperation(edge, {
840
+ return new EdgeOperation(builder, edge, {
750
841
  operation: action_1.WriteOperation.Insert,
751
842
  id2Placeholder,
752
843
  id1Placeholder,
@@ -767,7 +858,7 @@ class EdgeOperation {
767
858
  if (data) {
768
859
  edge.data = data;
769
860
  }
770
- return new EdgeOperation(edge, {
861
+ return new EdgeOperation(builder, edge, {
771
862
  operation: action_1.WriteOperation.Insert,
772
863
  id1Placeholder,
773
864
  id2Placeholder,
@@ -785,7 +876,7 @@ class EdgeOperation {
785
876
  id2Type: "",
786
877
  id1Type: "",
787
878
  };
788
- return new EdgeOperation(edge, {
879
+ return new EdgeOperation(builder, edge, {
789
880
  operation: action_1.WriteOperation.Delete,
790
881
  });
791
882
  }
@@ -800,7 +891,7 @@ class EdgeOperation {
800
891
  id2Type: "",
801
892
  id1Type: "",
802
893
  };
803
- return new EdgeOperation(edge, {
894
+ return new EdgeOperation(builder, edge, {
804
895
  operation: action_1.WriteOperation.Delete,
805
896
  });
806
897
  }
@@ -897,43 +988,42 @@ function createRowSync(queryer, options, suffix) {
897
988
  return null;
898
989
  }
899
990
  exports.createRowSync = createRowSync;
900
- function buildUpdateQuery(options, id, suffix) {
991
+ function buildUpdateQuery(options, suffix) {
901
992
  let valsString = [];
902
993
  let values = [];
903
994
  let logValues = [];
904
995
  const dialect = db_1.default.getDialect();
905
996
  let idx = 1;
906
997
  for (const key in options.fields) {
907
- values.push(options.fields[key]);
998
+ const val = options.fields[key];
999
+ values.push(val);
908
1000
  if (options.fieldsToLog) {
909
1001
  logValues.push(options.fieldsToLog[key]);
910
1002
  }
1003
+ // TODO would be nice to use clause here. need update version of the queries so that
1004
+ // we don't have to handle dialect specifics here
1005
+ // can't use clause because of IS NULL
1006
+ // valsString.push(clause.Eq(key, val).clause(idx));
911
1007
  if (dialect === db_1.Dialect.Postgres) {
912
1008
  valsString.push(`${key} = $${idx}`);
913
- idx++;
914
1009
  }
915
1010
  else {
916
1011
  valsString.push(`${key} = ?`);
917
1012
  }
1013
+ idx++;
918
1014
  }
919
1015
  const vals = valsString.join(", ");
920
1016
  let query = `UPDATE ${options.tableName} SET ${vals} WHERE `;
921
- if (dialect === db_1.Dialect.Postgres) {
922
- query = query + `${options.key} = $${idx}`;
923
- }
924
- else {
925
- query = query + `${options.key} = ?`;
926
- }
1017
+ query = query + options.whereClause.clause(idx);
1018
+ values.push(...options.whereClause.values());
927
1019
  if (suffix) {
928
1020
  query = query + " " + suffix;
929
1021
  }
930
1022
  return [query, values, logValues];
931
1023
  }
932
1024
  exports.buildUpdateQuery = buildUpdateQuery;
933
- async function editRow(queryer, options, id, suffix) {
934
- const [query, values, logValues] = buildUpdateQuery(options, id, suffix);
935
- // add id as value to prepared query
936
- values.push(id);
1025
+ async function editRow(queryer, options, suffix) {
1026
+ const [query, values, logValues] = buildUpdateQuery(options, suffix);
937
1027
  const res = await mutateRow(queryer, query, values, logValues, options);
938
1028
  if (res?.rowCount == 1) {
939
1029
  // for now assume id primary key
@@ -944,10 +1034,8 @@ async function editRow(queryer, options, id, suffix) {
944
1034
  return null;
945
1035
  }
946
1036
  exports.editRow = editRow;
947
- function editRowSync(queryer, options, id, suffix) {
948
- const [query, values, logValues] = buildUpdateQuery(options, id, suffix);
949
- // add id as value to prepared query
950
- values.push(id);
1037
+ function editRowSync(queryer, options, suffix) {
1038
+ const [query, values, logValues] = buildUpdateQuery(options, suffix);
951
1039
  const res = mutateRowSync(queryer, query, values, logValues, options);
952
1040
  if (res?.rowCount == 1) {
953
1041
  // for now assume id primary key
@@ -998,6 +1086,12 @@ class AssocEdge {
998
1086
  this.edgeType = data.edge_type;
999
1087
  this.time = data.time;
1000
1088
  this.data = data.data;
1089
+ this.rawData = data;
1090
+ }
1091
+ __getRawData() {
1092
+ // incase there's extra db fields. useful for tests
1093
+ // in production, a subclass of this should be in use so we won't need this...
1094
+ return this.rawData;
1001
1095
  }
1002
1096
  getCursor() {
1003
1097
  return getCursor({
@@ -1104,6 +1198,21 @@ async function loadEdges(options) {
1104
1198
  return loadCustomEdges({ ...options, ctr: AssocEdge });
1105
1199
  }
1106
1200
  exports.loadEdges = loadEdges;
1201
+ function getEdgeClauseAndFields(cls, options) {
1202
+ let fields = edgeFields;
1203
+ if (globalSchema?.transformEdgeRead) {
1204
+ const transformClause = globalSchema.transformEdgeRead();
1205
+ if (!options.disableTransformations) {
1206
+ cls = clause.And(cls, transformClause);
1207
+ }
1208
+ fields = edgeFields.concat(transformClause.columns());
1209
+ }
1210
+ return {
1211
+ cls,
1212
+ fields,
1213
+ };
1214
+ }
1215
+ exports.getEdgeClauseAndFields = getEdgeClauseAndFields;
1107
1216
  async function loadCustomEdges(options) {
1108
1217
  const { id1, edgeType, context } = options;
1109
1218
  const edgeData = await loadEdgeData(edgeType);
@@ -1115,10 +1224,11 @@ async function loadCustomEdges(options) {
1115
1224
  if (options.queryOptions?.clause) {
1116
1225
  cls = clause.And(cls, options.queryOptions.clause);
1117
1226
  }
1227
+ const { cls: actualClause, fields } = getEdgeClauseAndFields(cls, options);
1118
1228
  const rows = await loadRows({
1119
1229
  tableName: edgeData.edgeTable,
1120
- fields: edgeFields,
1121
- clause: cls,
1230
+ fields: fields,
1231
+ clause: actualClause,
1122
1232
  orderby: options.queryOptions?.orderby || defaultOptions.orderby,
1123
1233
  limit: options.queryOptions?.limit || defaultOptions.limit,
1124
1234
  context,
@@ -1134,10 +1244,11 @@ async function loadUniqueEdge(options) {
1134
1244
  if (!edgeData) {
1135
1245
  throw new Error(`error loading edge data for ${edgeType}`);
1136
1246
  }
1247
+ const { cls, fields } = getEdgeClauseAndFields(clause.And(clause.Eq("id1", id1), clause.Eq("edge_type", edgeType)), options);
1137
1248
  const row = await loadRow({
1138
1249
  tableName: edgeData.edgeTable,
1139
- fields: edgeFields,
1140
- clause: clause.And(clause.Eq("id1", id1), clause.Eq("edge_type", edgeType)),
1250
+ fields: fields,
1251
+ clause: cls,
1141
1252
  context,
1142
1253
  });
1143
1254
  if (!row) {
@@ -1164,11 +1275,12 @@ async function loadRawEdgeCountX(options) {
1164
1275
  if (!edgeData) {
1165
1276
  throw new Error(`error loading edge data for ${edgeType}`);
1166
1277
  }
1278
+ const { cls } = getEdgeClauseAndFields(clause.And(clause.Eq("id1", id1), clause.Eq("edge_type", edgeType)), options);
1167
1279
  const row = await loadRowX({
1168
1280
  tableName: edgeData.edgeTable,
1169
1281
  // sqlite needs as count otherwise it returns count(1)
1170
1282
  fields: ["count(1) as count"],
1171
- clause: clause.And(clause.Eq("id1", id1), clause.Eq("edge_type", edgeType)),
1283
+ clause: cls,
1172
1284
  context,
1173
1285
  });
1174
1286
  return parseInt(row["count"], 10) || 0;
@@ -41,10 +41,15 @@ class AssocEdgeCountLoader {
41
41
  if (!edgeData) {
42
42
  throw new Error(`error loading edge data for ${this.edgeType}`);
43
43
  }
44
+ const { cls } = (0, ent_1.getEdgeClauseAndFields)(clause.Eq("edge_type", this.edgeType), {
45
+ // don't need this..
46
+ id1: "1",
47
+ edgeType: this.edgeType,
48
+ });
44
49
  this.loader = (0, raw_count_loader_1.createCountDataLoader)({
45
50
  tableName: edgeData.edgeTable,
46
51
  groupCol: "id1",
47
- clause: clause.Eq("edge_type", this.edgeType),
52
+ clause: cls,
48
53
  });
49
54
  return this.loader;
50
55
  }
@@ -1 +1 @@
1
- export declare function assocTests(): void;
1
+ export declare function assocTests(global?: boolean): void;
@@ -27,7 +27,7 @@ const jest_date_mock_1 = require("jest-date-mock");
27
27
  const index_1 = require("../../testutils/fake_data/index");
28
28
  const test_helpers_1 = require("../../testutils/fake_data/test_helpers");
29
29
  const db_1 = __importStar(require("../db"));
30
- function assocTests() {
30
+ function assocTests(global = false) {
31
31
  describe("custom edge", () => {
32
32
  let user1, user2;
33
33
  beforeEach(async () => {
@@ -76,9 +76,16 @@ function assocTests() {
76
76
  for (let i = 0; i < numQueries; i++) {
77
77
  const query = queries[i];
78
78
  let expLimit = disablePaginationBump ? limit : limit + 1;
79
- expect(query.qs?.whereClause, `${i}`).toBe(
80
- // default limit
81
- `id1 = $1 AND edge_type = $2 ORDER BY time DESC LIMIT ${expLimit}`);
79
+ if (global) {
80
+ expect(query.qs?.whereClause, `${i}`).toBe(
81
+ // default limit
82
+ `id1 = $1 AND edge_type = $2 AND deleted_at IS NULL ORDER BY time DESC LIMIT ${expLimit}`);
83
+ }
84
+ else {
85
+ expect(query.qs?.whereClause, `${i}`).toBe(
86
+ // default limit
87
+ `id1 = $1 AND edge_type = $2 ORDER BY time DESC LIMIT ${expLimit}`);
88
+ }
82
89
  }
83
90
  }
84
91
  function verifyCountQuery({ length = 1, numQueries = 1 }) {
@@ -89,7 +96,12 @@ function assocTests() {
89
96
  expect(queries.length).toBe(length);
90
97
  for (let i = 0; i < numQueries; i++) {
91
98
  const query = queries[i];
92
- expect(query.qs?.whereClause).toBe(`id1 = $1 AND edge_type = $2`);
99
+ if (global) {
100
+ expect(query.qs?.whereClause).toBe(`id1 = $1 AND edge_type = $2 AND deleted_at IS NULL`);
101
+ }
102
+ else {
103
+ expect(query.qs?.whereClause).toBe(`id1 = $1 AND edge_type = $2`);
104
+ }
93
105
  }
94
106
  }
95
107
  // TODO need to test multi-ids with id1s that aren't visible...
@@ -4,11 +4,14 @@ import { EdgeQuery } from "./query";
4
4
  interface options<TData extends Data> {
5
5
  newQuery: (v: Viewer, user: FakeUser) => EdgeQuery<FakeUser, FakeContact, TData>;
6
6
  tableName: string;
7
+ uniqKey: string;
7
8
  entsLength?: number;
8
9
  where: string;
9
10
  sortCol: string;
10
11
  livePostgresDB?: boolean;
11
12
  sqlite?: boolean;
13
+ globalSchema?: boolean;
14
+ rawDataVerify?(user: FakeUser): Promise<void>;
12
15
  }
13
16
  export declare const commonTests: <TData extends Data>(opts: options<TData>) => void;
14
17
  export {};
@@ -6,9 +6,12 @@ const ent_1 = require("../ent");
6
6
  const viewer_1 = require("../viewer");
7
7
  const index_1 = require("../../testutils/fake_data/index");
8
8
  const test_helpers_1 = require("../../testutils/fake_data/test_helpers");
9
- const test_db_1 = require("../../testutils/db/test_db");
9
+ const temp_db_1 = require("../../testutils/db/temp_db");
10
10
  const test_context_1 = require("../../testutils/context/test_context");
11
11
  const logger_1 = require("../logger");
12
+ const test_edge_global_schema_1 = require("../../testutils/test_edge_global_schema");
13
+ const builder_1 = require("../../testutils/builder");
14
+ const action_1 = require("../../action");
12
15
  class TestQueryFilter {
13
16
  constructor(filter, newQuery, ents, defaultViewer) {
14
17
  this.filter = filter;
@@ -37,19 +40,19 @@ class TestQueryFilter {
37
40
  expect(ids).toEqual(this.filteredContacts.map((contact) => contact.id));
38
41
  }
39
42
  // rawCount isn't affected by filters...
40
- async testRawCount() {
43
+ async testRawCount(expectedCount) {
41
44
  const count = await this.getQuery().queryRawCount();
42
- this.verifyRawCount(count);
45
+ this.verifyRawCount(count, expectedCount);
43
46
  }
44
- verifyRawCount(count) {
45
- expect(count).toBe(test_helpers_1.inputs.length);
47
+ verifyRawCount(count, expectedCount) {
48
+ expect(count).toBe(expectedCount ?? test_helpers_1.inputs.length);
46
49
  }
47
- async testCount() {
50
+ async testCount(expectedCount) {
48
51
  const count = await this.getQuery().queryCount();
49
- this.verifyCount(count);
52
+ this.verifyCount(count, expectedCount);
50
53
  }
51
- verifyCount(count) {
52
- expect(count).toBe(this.filteredContacts.length);
54
+ verifyCount(count, expectedCount) {
55
+ expect(count).toBe(expectedCount ?? this.filteredContacts.length);
53
56
  }
54
57
  async testEdges() {
55
58
  const edges = await this.getQuery().queryEdges();
@@ -72,7 +75,7 @@ class TestQueryFilter {
72
75
  verifyEnts(ents) {
73
76
  (0, test_helpers_1.verifyUserToContacts)(this.user, ents, this.filteredContacts);
74
77
  }
75
- async testAll() {
78
+ async testAll(expectedCount) {
76
79
  const query = this.getQuery(new viewer_1.IDViewer(this.user.id));
77
80
  const [edges, count, ids, rawCount, ents] = await Promise.all([
78
81
  query.queryEdges(),
@@ -81,10 +84,10 @@ class TestQueryFilter {
81
84
  query.queryRawCount(),
82
85
  query.queryEnts(),
83
86
  ]);
84
- this.verifyCount(count);
87
+ this.verifyCount(count, expectedCount);
85
88
  this.verifyEdges(edges);
86
89
  this.verifyIDs(ids);
87
- this.verifyRawCount(rawCount);
90
+ this.verifyRawCount(rawCount, expectedCount);
88
91
  this.verifyEnts(ents);
89
92
  }
90
93
  }
@@ -125,7 +128,19 @@ const commonTests = (opts) => {
125
128
  expect(queries.length).toBe(length);
126
129
  const query = queries[0];
127
130
  const result = [...opts.where.matchAll(preparedVar)];
128
- expect(query.qs?.whereClause).toBe(`${opts.where} AND ${opts.sortCol} < $${result.length + 1} ORDER BY ${opts.sortCol} DESC LIMIT 4`);
131
+ let parts = opts.where.split(" AND ");
132
+ if (parts[parts.length - 1] === "deleted_at IS NULL") {
133
+ parts = parts
134
+ .slice(0, parts.length - 1)
135
+ .concat([
136
+ `${opts.sortCol} < $${result.length + 1}`,
137
+ "deleted_at IS NULL",
138
+ ]);
139
+ }
140
+ else {
141
+ parts.push(`${opts.sortCol} < $${result.length + 1}`);
142
+ }
143
+ expect(query.qs?.whereClause).toBe(`${parts.join(" AND ")} ORDER BY ${opts.sortCol} DESC LIMIT 4`);
129
144
  }
130
145
  function verifyLastBeforeCursorQuery(length = 1) {
131
146
  if (opts.livePostgresDB || opts.sqlite) {
@@ -135,9 +150,21 @@ const commonTests = (opts) => {
135
150
  expect(queries.length).toBe(length);
136
151
  const query = queries[0];
137
152
  const result = [...opts.where.matchAll(preparedVar)];
153
+ let parts = opts.where.split(" AND ");
154
+ if (parts[parts.length - 1] === "deleted_at IS NULL") {
155
+ parts = parts
156
+ .slice(0, parts.length - 1)
157
+ .concat([
158
+ `${opts.sortCol} > $${result.length + 1}`,
159
+ "deleted_at IS NULL",
160
+ ]);
161
+ }
162
+ else {
163
+ parts.push(`${opts.sortCol} > $${result.length + 1}`);
164
+ }
138
165
  expect(query.qs?.whereClause).toBe(
139
166
  // extra fetched for pagination
140
- `${opts.where} AND ${opts.sortCol} > $${result.length + 1} ORDER BY ${opts.sortCol} ASC LIMIT 4`);
167
+ `${parts.join(" AND ")} ORDER BY ${opts.sortCol} ASC LIMIT 4`);
141
168
  }
142
169
  function getViewer() {
143
170
  // live db, let's do context because we're testing complicated paths
@@ -171,10 +198,12 @@ const commonTests = (opts) => {
171
198
  cursorKey: opts.sortCol,
172
199
  });
173
200
  }
201
+ if (opts.globalSchema) {
202
+ (0, ent_1.setGlobalSchema)(test_edge_global_schema_1.testEdgeGlobalSchema);
203
+ }
174
204
  let tdb;
175
205
  if (opts.sqlite) {
176
- // tableName just to make it unique
177
- (0, test_db_1.setupSqlite)(`sqlite:///shared_test+${opts.tableName}.db`, test_helpers_1.tempDBTables);
206
+ (0, temp_db_1.setupSqlite)(`sqlite:///shared_test+${opts.uniqKey}.db`, () => (0, test_helpers_1.tempDBTables)(opts.globalSchema));
178
207
  }
179
208
  beforeAll(async () => {
180
209
  // want error on by default in tests?
@@ -196,7 +225,7 @@ const commonTests = (opts) => {
196
225
  });
197
226
  describe("simple queries", () => {
198
227
  const filter = new TestQueryFilter((q) => {
199
- // no filterzs
228
+ // no filters
200
229
  return q;
201
230
  }, opts.newQuery, (contacts) => {
202
231
  // nothing to do here
@@ -230,6 +259,55 @@ const commonTests = (opts) => {
230
259
  await filter.testAll();
231
260
  });
232
261
  });
262
+ describe("after delete", () => {
263
+ const filter = new TestQueryFilter((q) => {
264
+ // no filters
265
+ return q;
266
+ }, opts.newQuery, (contacts) => {
267
+ // nothing expected since deleted
268
+ return [];
269
+ }, getViewer());
270
+ beforeEach(async () => {
271
+ await filter.beforeEach();
272
+ const action = new builder_1.SimpleAction(filter.user.viewer, index_1.FakeUserSchema, new Map(), action_1.WriteOperation.Edit, filter.user);
273
+ await Promise.all(filter.allContacts.map(async (contact) => {
274
+ action.builder.orchestrator.removeOutboundEdge(contact.id, index_1.EdgeType.UserToContacts);
275
+ const action2 = new builder_1.SimpleAction(filter.user.viewer, index_1.FakeContactSchema, new Map(), action_1.WriteOperation.Delete, contact);
276
+ await action2.save();
277
+ }));
278
+ await action.save();
279
+ db_mock_1.QueryRecorder.clearQueries();
280
+ });
281
+ test("ids", async () => {
282
+ await filter.testIDs();
283
+ verifyQuery({});
284
+ });
285
+ test("rawCount", async () => {
286
+ await filter.testRawCount(0);
287
+ verifyCountQuery({});
288
+ });
289
+ test("count", async () => {
290
+ await filter.testCount(0);
291
+ verifyQuery({});
292
+ });
293
+ test("edges", async () => {
294
+ await filter.testEdges();
295
+ verifyQuery({});
296
+ });
297
+ test("ents", async () => {
298
+ await filter.testEnts();
299
+ // no ents so no subsequent query. just the edge query
300
+ verifyQuery({ length: 1 });
301
+ });
302
+ test("all", async () => {
303
+ await filter.testAll(0);
304
+ });
305
+ test("raw_data", async () => {
306
+ if (opts.rawDataVerify) {
307
+ await opts.rawDataVerify(filter.user);
308
+ }
309
+ });
310
+ });
233
311
  describe("first. no cursor", () => {
234
312
  const N = 2;
235
313
  const filter = new TestQueryFilter((q) => {
package/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export * from "./core/base";
2
- export { loadEnt, loadCustomData, loadCustomEnts, loadEntX, loadEnts, CustomQuery, loadDerivedEnt, loadDerivedEntX, loadEntViaKey, loadEntXViaKey, performRawQuery, loadRowX, loadRow, loadRows, DataOperation, EditNodeOptions, EditNodeOperation, EdgeOperation, DeleteNodeOperation, AssocEdge, AssocEdgeInputOptions, AssocEdgeInput, AssocEdgeData, loadEdgeData, loadEdgeDatas, loadEdges, loadUniqueEdge, loadUniqueNode, loadRawEdgeCountX, loadEdgeForID2, loadNodesByEdge, getEdgeTypeInGroup, } from "./core/ent";
2
+ export { loadEnt, loadCustomData, loadCustomEnts, loadEntX, loadEnts, CustomQuery, loadDerivedEnt, loadDerivedEntX, loadEntViaKey, loadEntXViaKey, performRawQuery, loadRowX, loadRow, loadRows, DataOperation, EditNodeOptions, EditNodeOperation, EdgeOperation, DeleteNodeOperation, AssocEdge, AssocEdgeInputOptions, AssocEdgeInput, AssocEdgeData, loadEdgeData, loadEdgeDatas, loadEdges, loadUniqueEdge, loadUniqueNode, loadRawEdgeCountX, loadEdgeForID2, loadNodesByEdge, getEdgeTypeInGroup, setGlobalSchema, } from "./core/ent";
3
3
  import DB from "./core/db";
4
4
  export * from "./core/loaders";
5
5
  export { DB };
@@ -20,10 +20,10 @@ declare const query: {
20
20
  LessEq: typeof q.LessEq;
21
21
  ArrayEq: typeof q.ArrayEq;
22
22
  ArrayNotEq: typeof q.ArrayNotEq;
23
- ArrayGreater: typeof q.ArrayGreater;
24
- ArrayLess: typeof q.ArrayLess;
25
- ArrayGreaterEq: typeof q.ArrayGreaterEq;
26
- ArrayLessEq: typeof q.ArrayLessEq;
23
+ PostgresArrayContainsValue: typeof q.PostgresArrayContainsValue;
24
+ PostgresArrayContains: typeof q.PostgresArrayContains;
25
+ PostgresArrayNotContainsValue: typeof q.PostgresArrayNotContainsValue;
26
+ PostgresArrayNotContains: typeof q.PostgresArrayNotContains;
27
27
  TsQuery: typeof q.TsQuery;
28
28
  PlainToTsQuery: typeof q.PlainToTsQuery;
29
29
  PhraseToTsQuery: typeof q.PhraseToTsQuery;