@snowtop/ent 0.1.0-alpha10 → 0.1.0-alpha101

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 (158) hide show
  1. package/action/action.d.ts +37 -31
  2. package/action/action.js +22 -7
  3. package/action/executor.d.ts +3 -3
  4. package/action/executor.js +8 -3
  5. package/action/experimental_action.d.ts +32 -22
  6. package/action/experimental_action.js +35 -9
  7. package/action/index.d.ts +2 -0
  8. package/action/index.js +7 -1
  9. package/action/orchestrator.d.ts +40 -16
  10. package/action/orchestrator.js +230 -62
  11. package/action/privacy.d.ts +2 -2
  12. package/action/relative_value.d.ts +47 -0
  13. package/action/relative_value.js +125 -0
  14. package/action/transaction.d.ts +10 -0
  15. package/action/transaction.js +23 -0
  16. package/auth/auth.d.ts +1 -1
  17. package/core/base.d.ts +49 -26
  18. package/core/base.js +7 -1
  19. package/core/clause.d.ts +88 -7
  20. package/core/clause.js +355 -63
  21. package/core/config.d.ts +12 -1
  22. package/core/config.js +7 -1
  23. package/core/context.d.ts +5 -3
  24. package/core/context.js +20 -2
  25. package/core/convert.d.ts +1 -1
  26. package/core/date.js +1 -5
  27. package/core/db.d.ts +11 -8
  28. package/core/db.js +20 -8
  29. package/core/ent.d.ts +81 -25
  30. package/core/ent.js +636 -193
  31. package/core/loaders/assoc_count_loader.d.ts +3 -2
  32. package/core/loaders/assoc_count_loader.js +10 -2
  33. package/core/loaders/assoc_edge_loader.d.ts +2 -2
  34. package/core/loaders/assoc_edge_loader.js +8 -11
  35. package/core/loaders/index.d.ts +1 -1
  36. package/core/loaders/index.js +1 -3
  37. package/core/loaders/index_loader.d.ts +2 -2
  38. package/core/loaders/loader.js +5 -5
  39. package/core/loaders/object_loader.d.ts +6 -5
  40. package/core/loaders/object_loader.js +67 -59
  41. package/core/loaders/query_loader.d.ts +6 -12
  42. package/core/loaders/query_loader.js +52 -11
  43. package/core/loaders/raw_count_loader.d.ts +2 -2
  44. package/core/loaders/raw_count_loader.js +5 -1
  45. package/core/logger.d.ts +1 -1
  46. package/core/logger.js +1 -0
  47. package/core/privacy.d.ts +25 -24
  48. package/core/privacy.js +21 -25
  49. package/core/query/assoc_query.d.ts +7 -6
  50. package/core/query/assoc_query.js +9 -1
  51. package/core/query/custom_clause_query.d.ts +26 -0
  52. package/core/query/custom_clause_query.js +78 -0
  53. package/core/query/custom_query.d.ts +20 -5
  54. package/core/query/custom_query.js +87 -12
  55. package/core/query/index.d.ts +1 -0
  56. package/core/query/index.js +3 -1
  57. package/core/query/query.d.ts +8 -4
  58. package/core/query/query.js +101 -53
  59. package/core/query/shared_assoc_test.d.ts +2 -1
  60. package/core/query/shared_assoc_test.js +35 -45
  61. package/core/query/shared_test.d.ts +8 -1
  62. package/core/query/shared_test.js +469 -236
  63. package/core/viewer.d.ts +3 -3
  64. package/core/viewer.js +1 -1
  65. package/graphql/graphql.d.ts +14 -7
  66. package/graphql/graphql.js +23 -7
  67. package/graphql/index.d.ts +0 -1
  68. package/graphql/index.js +1 -4
  69. package/graphql/query/connection_type.d.ts +9 -9
  70. package/graphql/query/edge_connection.d.ts +9 -9
  71. package/graphql/query/page_info.d.ts +1 -1
  72. package/graphql/query/shared_assoc_test.js +1 -1
  73. package/graphql/query/shared_edge_connection.js +1 -19
  74. package/imports/index.d.ts +6 -1
  75. package/imports/index.js +19 -4
  76. package/index.d.ts +12 -5
  77. package/index.js +20 -7
  78. package/package.json +17 -16
  79. package/parse_schema/parse.d.ts +29 -9
  80. package/parse_schema/parse.js +118 -11
  81. package/schema/base_schema.d.ts +5 -3
  82. package/schema/base_schema.js +5 -0
  83. package/schema/field.d.ts +74 -20
  84. package/schema/field.js +174 -69
  85. package/schema/index.d.ts +2 -2
  86. package/schema/index.js +5 -1
  87. package/schema/json_field.d.ts +13 -1
  88. package/schema/json_field.js +28 -1
  89. package/schema/schema.d.ts +81 -18
  90. package/schema/schema.js +24 -17
  91. package/schema/struct_field.d.ts +11 -1
  92. package/schema/struct_field.js +57 -21
  93. package/scripts/custom_compiler.js +10 -6
  94. package/scripts/custom_graphql.js +117 -30
  95. package/scripts/{transform_code.d.ts → migrate_v0.1.d.ts} +0 -0
  96. package/scripts/migrate_v0.1.js +36 -0
  97. package/scripts/{transform_schema.d.ts → move_types.d.ts} +0 -0
  98. package/scripts/move_types.js +117 -0
  99. package/scripts/read_schema.js +20 -5
  100. package/testutils/action/complex_schemas.d.ts +69 -0
  101. package/testutils/action/complex_schemas.js +398 -0
  102. package/testutils/builder.d.ts +46 -47
  103. package/testutils/builder.js +108 -65
  104. package/testutils/db/fixture.d.ts +10 -0
  105. package/testutils/db/fixture.js +26 -0
  106. package/testutils/db/{test_db.d.ts → temp_db.d.ts} +24 -8
  107. package/testutils/db/{test_db.js → temp_db.js} +179 -44
  108. package/testutils/db/value.d.ts +7 -0
  109. package/testutils/db/value.js +251 -0
  110. package/testutils/db_mock.d.ts +16 -4
  111. package/testutils/db_mock.js +51 -6
  112. package/testutils/db_time_zone.d.ts +4 -0
  113. package/testutils/db_time_zone.js +41 -0
  114. package/testutils/ent-graphql-tests/index.d.ts +7 -1
  115. package/testutils/ent-graphql-tests/index.js +27 -8
  116. package/testutils/fake_data/const.d.ts +2 -1
  117. package/testutils/fake_data/const.js +3 -0
  118. package/testutils/fake_data/fake_contact.d.ts +7 -3
  119. package/testutils/fake_data/fake_contact.js +15 -8
  120. package/testutils/fake_data/fake_event.d.ts +5 -2
  121. package/testutils/fake_data/fake_event.js +9 -7
  122. package/testutils/fake_data/fake_tag.d.ts +36 -0
  123. package/testutils/fake_data/fake_tag.js +89 -0
  124. package/testutils/fake_data/fake_user.d.ts +7 -4
  125. package/testutils/fake_data/fake_user.js +18 -16
  126. package/testutils/fake_data/index.js +5 -1
  127. package/testutils/fake_data/internal.d.ts +2 -0
  128. package/testutils/fake_data/internal.js +7 -1
  129. package/testutils/fake_data/tag_query.d.ts +13 -0
  130. package/testutils/fake_data/tag_query.js +43 -0
  131. package/testutils/fake_data/test_helpers.d.ts +11 -4
  132. package/testutils/fake_data/test_helpers.js +28 -12
  133. package/testutils/fake_data/user_query.d.ts +13 -6
  134. package/testutils/fake_data/user_query.js +54 -22
  135. package/testutils/fake_log.d.ts +3 -3
  136. package/testutils/parse_sql.d.ts +6 -0
  137. package/testutils/parse_sql.js +16 -2
  138. package/testutils/test_edge_global_schema.d.ts +15 -0
  139. package/testutils/test_edge_global_schema.js +62 -0
  140. package/testutils/write.d.ts +2 -2
  141. package/testutils/write.js +33 -7
  142. package/tsc/ast.d.ts +26 -2
  143. package/tsc/ast.js +163 -17
  144. package/tsc/compilerOptions.d.ts +2 -1
  145. package/tsc/compilerOptions.js +11 -2
  146. package/tsc/move_generated.d.ts +1 -0
  147. package/tsc/move_generated.js +164 -0
  148. package/tsc/transform.d.ts +22 -0
  149. package/tsc/transform.js +181 -0
  150. package/tsc/transform_action.d.ts +22 -0
  151. package/tsc/transform_action.js +183 -0
  152. package/tsc/transform_ent.d.ts +17 -0
  153. package/tsc/transform_ent.js +59 -0
  154. package/tsc/transform_schema.d.ts +27 -0
  155. package/{scripts → tsc}/transform_schema.js +145 -119
  156. package/graphql/enums.d.ts +0 -3
  157. package/graphql/enums.js +0 -25
  158. package/scripts/transform_code.js +0 -114
package/core/ent.js CHANGED
@@ -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,13 +26,15 @@ 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.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;
29
+ exports.loadUniqueNode = exports.loadUniqueEdge = exports.loadCustomEdges = exports.getEdgeClauseAndFields = exports.loadEdges = 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.RawQueryOperation = exports.buildGroupQuery = exports.buildQuery = exports.loadRows = exports.performRawQuery = exports.___setLogQueryErrorWithError = exports.loadRow = exports.loadRowX = exports.logQuery = exports.loadDerivedEntX = exports.loadDerivedEnt = exports.loadCustomCount = exports.loadCustomData = exports.loadCustomEnts = exports.loadEntsFromClause = exports.loadEntsList = exports.loadEnts = exports.loadEntXFromClause = exports.loadEntFromClause = exports.loadEntXViaKey = exports.loadEntX = exports.loadEntViaKey = exports.loadEnt = exports.getEntKey = void 0;
30
+ exports.getEdgeTypeInGroup = exports.applyPrivacyPolicyForRows = exports.applyPrivacyPolicyForRow = exports.loadNodesByEdge = exports.loadEdgeForID2 = exports.loadRawEdgeCountX = void 0;
26
31
  const db_1 = __importStar(require("./db"));
27
32
  const privacy_1 = require("./privacy");
28
33
  const clause = __importStar(require("./clause"));
29
34
  const action_1 = require("../action");
30
35
  const logger_1 = require("./logger");
31
36
  const dataloader_1 = __importDefault(require("dataloader"));
37
+ const schema_1 = require("../schema/");
32
38
  // TODO kill this and createDataLoader
33
39
  class cacheMap {
34
40
  constructor(options) {
@@ -38,7 +44,7 @@ class cacheMap {
38
44
  get(key) {
39
45
  const ret = this.m.get(key);
40
46
  if (ret) {
41
- (0, logger_1.log)("query", {
47
+ (0, logger_1.log)("cache", {
42
48
  "dataloader-cache-hit": key,
43
49
  "tableName": this.options.tableName,
44
50
  });
@@ -55,12 +61,41 @@ class cacheMap {
55
61
  return this.m.clear();
56
62
  }
57
63
  }
64
+ class entCacheMap {
65
+ constructor(viewer, options) {
66
+ this.viewer = viewer;
67
+ this.options = options;
68
+ this.m = new Map();
69
+ this.logEnabled = false;
70
+ this.logEnabled = (0, logger_1.logEnabled)("cache");
71
+ }
72
+ get(id) {
73
+ const ret = this.m.get(id);
74
+ if (this.logEnabled && ret) {
75
+ const key = getEntKey(this.viewer, id, this.options);
76
+ (0, logger_1.log)("cache", {
77
+ "ent-cache-hit": key,
78
+ });
79
+ }
80
+ return ret;
81
+ }
82
+ set(key, value) {
83
+ return this.m.set(key, value);
84
+ }
85
+ delete(key) {
86
+ return this.m.delete(key);
87
+ }
88
+ clear() {
89
+ return this.m.clear();
90
+ }
91
+ }
58
92
  function createDataLoader(options) {
59
93
  const loaderOptions = {};
60
94
  // if query logging is enabled, we should log what's happening with loader
61
95
  if ((0, logger_1.logEnabled)("query")) {
62
96
  loaderOptions.cacheMap = new cacheMap(options);
63
97
  }
98
+ // something here brokwn with strict:true
64
99
  return new dataloader_1.default(async (ids) => {
65
100
  if (!ids.length) {
66
101
  return [];
@@ -84,28 +119,151 @@ function createDataLoader(options) {
84
119
  return result;
85
120
  }, loaderOptions);
86
121
  }
87
- // Ent accessors
122
+ // used to wrap errors that would eventually be thrown in ents
123
+ // not an Error because DataLoader automatically rejects that
124
+ class ErrorWrapper {
125
+ constructor(error) {
126
+ this.error = error;
127
+ }
128
+ }
129
+ function createEntLoader(viewer, options, map) {
130
+ // share the cache across loaders even if we create a new instance
131
+ const loaderOptions = {};
132
+ loaderOptions.cacheMap = map;
133
+ return new dataloader_1.default(async (ids) => {
134
+ if (!ids.length) {
135
+ return [];
136
+ }
137
+ let result = [];
138
+ const tableName = options.loaderFactory.options?.tableName;
139
+ const loader = options.loaderFactory.createLoader(viewer.context);
140
+ const rows = await loader.loadMany(ids);
141
+ // this is a loader which should return the same order based on passed-in ids
142
+ // so let's depend on that...
143
+ for (let idx = 0; idx < rows.length; idx++) {
144
+ const row = rows[idx];
145
+ // db error
146
+ if (row instanceof Error) {
147
+ result[idx] = row;
148
+ continue;
149
+ }
150
+ else if (!row) {
151
+ if (tableName) {
152
+ result[idx] = new ErrorWrapper(new Error(`couldn't find row for value ${ids[idx]} in table ${tableName}`));
153
+ }
154
+ else {
155
+ result[idx] = new ErrorWrapper(new Error(`couldn't find row for value ${ids[idx]}`));
156
+ }
157
+ }
158
+ else {
159
+ const r = await applyPrivacyPolicyForRowImpl(viewer, options, row);
160
+ if (r instanceof Error) {
161
+ result[idx] = new ErrorWrapper(r);
162
+ }
163
+ else {
164
+ result[idx] = r;
165
+ }
166
+ }
167
+ }
168
+ return result;
169
+ }, loaderOptions);
170
+ }
171
+ class EntLoader {
172
+ constructor(viewer, options) {
173
+ this.viewer = viewer;
174
+ this.options = options;
175
+ this.map = new entCacheMap(viewer, options);
176
+ this.loader = createEntLoader(this.viewer, this.options, this.map);
177
+ }
178
+ getMap() {
179
+ return this.map;
180
+ }
181
+ async load(id) {
182
+ return this.loader.load(id);
183
+ }
184
+ async loadMany(ids) {
185
+ return this.loader.loadMany(ids);
186
+ }
187
+ prime(id, ent) {
188
+ this.loader.prime(id, ent);
189
+ }
190
+ clear(id) {
191
+ this.loader.clear(id);
192
+ }
193
+ clearAll() {
194
+ this.loader.clearAll();
195
+ }
196
+ }
197
+ function getEntLoader(viewer, options) {
198
+ if (!viewer.context?.cache) {
199
+ return new EntLoader(viewer, options);
200
+ }
201
+ const name = `ent-loader:${viewer.instanceKey()}:${options.loaderFactory.name}`;
202
+ return viewer.context.cache.getLoaderWithLoadMany(name, () => new EntLoader(viewer, options));
203
+ }
204
+ function getEntKey(viewer, id, options) {
205
+ return `${viewer.instanceKey()}:${options.loaderFactory.name}:${id}`;
206
+ }
207
+ exports.getEntKey = getEntKey;
88
208
  async function loadEnt(viewer, id, options) {
89
- const row = await options.loaderFactory.createLoader(viewer.context).load(id);
90
- return await applyPrivacyPolicyForRow(viewer, options, row);
209
+ if (typeof id !== "string" &&
210
+ typeof id !== "number" &&
211
+ typeof id !== "bigint") {
212
+ throw new Error(`invalid id ${id} passed to loadEnt`);
213
+ }
214
+ const r = await getEntLoader(viewer, options).load(id);
215
+ return r instanceof ErrorWrapper ? null : r;
91
216
  }
92
217
  exports.loadEnt = loadEnt;
218
+ async function applyPrivacyPolicyForRowAndStoreInEntLoader(viewer, row, options,
219
+ // can pass in loader when calling this for multi-id cases...
220
+ loader) {
221
+ if (!loader) {
222
+ loader = getEntLoader(viewer, options);
223
+ }
224
+ // TODO every row.id needs to be audited...
225
+ // https://github.com/lolopinto/ent/issues/1064
226
+ const id = row.id;
227
+ // we should check the ent loader cache to see if this is already there
228
+ // TODO hmm... we eventually need a custom data-loader for this too so that it's all done correctly if there's a complicated fetch deep down in graphql
229
+ const result = loader.getMap().get(id);
230
+ if (result !== undefined) {
231
+ return result;
232
+ }
233
+ const r = await applyPrivacyPolicyForRowImpl(viewer, options, row);
234
+ if (r instanceof Error) {
235
+ loader.prime(id, new ErrorWrapper(r));
236
+ return new ErrorWrapper(r);
237
+ }
238
+ else {
239
+ loader.prime(id, r);
240
+ return r;
241
+ }
242
+ }
93
243
  // this is the same implementation-wise (right now) as loadEnt. it's just clearer that it's not loaded via ID.
94
244
  // used for load via email address etc
95
245
  async function loadEntViaKey(viewer, key, options) {
96
246
  const row = await options.loaderFactory
97
247
  .createLoader(viewer.context)
98
248
  .load(key);
99
- return await applyPrivacyPolicyForRow(viewer, options, row);
249
+ if (!row) {
250
+ return null;
251
+ }
252
+ const r = await applyPrivacyPolicyForRowAndStoreInEntLoader(viewer, row, options);
253
+ return r instanceof ErrorWrapper ? null : r;
100
254
  }
101
255
  exports.loadEntViaKey = loadEntViaKey;
102
256
  async function loadEntX(viewer, id, options) {
103
- const row = await options.loaderFactory.createLoader(viewer.context).load(id);
104
- if (!row) {
105
- // todo make this better
106
- throw new Error(`${options.loaderFactory.name}: couldn't find row for value ${id}`);
257
+ if (typeof id !== "string" &&
258
+ typeof id !== "number" &&
259
+ typeof id !== "bigint") {
260
+ throw new Error(`invalid id ${id} passed to loadEntX`);
107
261
  }
108
- return await applyPrivacyPolicyForRowX(viewer, options, row);
262
+ const r = await getEntLoader(viewer, options).load(id);
263
+ if (r instanceof ErrorWrapper) {
264
+ throw r.error;
265
+ }
266
+ return r;
109
267
  }
110
268
  exports.loadEntX = loadEntX;
111
269
  async function loadEntXViaKey(viewer, key, options) {
@@ -116,9 +274,16 @@ async function loadEntXViaKey(viewer, key, options) {
116
274
  // todo make this better
117
275
  throw new Error(`${options.loaderFactory.name}: couldn't find row for value ${key}`);
118
276
  }
119
- return await applyPrivacyPolicyForRowX(viewer, options, row);
277
+ const r = await applyPrivacyPolicyForRowAndStoreInEntLoader(viewer, row, options);
278
+ if (r instanceof ErrorWrapper) {
279
+ throw r.error;
280
+ }
281
+ return r;
120
282
  }
121
283
  exports.loadEntXViaKey = loadEntXViaKey;
284
+ /**
285
+ * @deprecated use loadCustomEnts
286
+ */
122
287
  async function loadEntFromClause(viewer, options, clause) {
123
288
  const rowOptions = {
124
289
  ...options,
@@ -126,12 +291,18 @@ async function loadEntFromClause(viewer, options, clause) {
126
291
  context: viewer.context,
127
292
  };
128
293
  const row = await loadRow(rowOptions);
129
- return await applyPrivacyPolicyForRow(viewer, options, row);
294
+ if (row === null) {
295
+ return null;
296
+ }
297
+ return applyPrivacyPolicyForRow(viewer, options, row);
130
298
  }
131
299
  exports.loadEntFromClause = loadEntFromClause;
132
300
  // same as loadEntFromClause
133
301
  // only works for ents where primary key is "id"
134
302
  // use loadEnt with a loaderFactory if different
303
+ /**
304
+ * @deprecated use loadCustomEnts
305
+ */
135
306
  async function loadEntXFromClause(viewer, options, clause) {
136
307
  const rowOptions = {
137
308
  ...options,
@@ -146,37 +317,19 @@ async function loadEnts(viewer, options, ...ids) {
146
317
  if (!ids.length) {
147
318
  return new Map();
148
319
  }
149
- let loaded = false;
150
- let rows = [];
151
- // TODO loadMany everywhere
152
- const l = options.loaderFactory.createLoader(viewer.context);
153
- if (l.loadMany) {
154
- loaded = true;
155
- rows = await l.loadMany(ids);
156
- }
157
- // TODO rewrite all of this
320
+ // result
158
321
  let m = new Map();
159
- if (loaded) {
160
- let rows2 = [];
161
- for (const row of rows) {
162
- if (!row) {
163
- continue;
164
- }
165
- if (row instanceof Error) {
166
- throw row;
167
- }
168
- rows2.push(row);
322
+ const ret = await getEntLoader(viewer, options).loadMany(ids);
323
+ for (const r of ret) {
324
+ if (r instanceof Error) {
325
+ throw r;
169
326
  }
170
- m = await applyPrivacyPolicyForRows(viewer, rows2, options);
171
- }
172
- else {
173
- m = await loadEntsFromClause(viewer,
174
- // this is always "id" if not using an ObjectLoaderFactory
175
- clause.In("id", ...ids), options);
327
+ if (r instanceof ErrorWrapper) {
328
+ continue;
329
+ }
330
+ m.set(r.id, r);
176
331
  }
177
332
  return m;
178
- // TODO do we want to change this to be a map not a list so that it's easy to check for existence?
179
- // TODO eventually this should be doing a cache then db queyr and maybe depend on dataloader to get all the results at once
180
333
  }
181
334
  exports.loadEnts = loadEnts;
182
335
  // calls loadEnts and returns the results sorted in the order they were passed in
@@ -195,6 +348,9 @@ async function loadEntsList(viewer, options, ...ids) {
195
348
  exports.loadEntsList = loadEntsList;
196
349
  // we return a map here so that any sorting for queries that exist
197
350
  // can be done in O(N) time
351
+ /**
352
+ * @deperecated use loadCustomEnts
353
+ */
198
354
  async function loadEntsFromClause(viewer, clause, options) {
199
355
  const rowOptions = {
200
356
  ...options,
@@ -202,65 +358,135 @@ async function loadEntsFromClause(viewer, clause, options) {
202
358
  context: viewer.context,
203
359
  };
204
360
  const rows = await loadRows(rowOptions);
205
- return await applyPrivacyPolicyForRows(viewer, rows, options);
361
+ return applyPrivacyPolicyForRowsDeprecated(viewer, rows, options);
206
362
  }
207
363
  exports.loadEntsFromClause = loadEntsFromClause;
208
364
  async function loadCustomEnts(viewer, options, query) {
209
365
  const rows = await loadCustomData(options, query, viewer.context);
210
- const result = new Array(rows.length);
211
- await Promise.all(rows.map(async (row, idx) => {
212
- const ent = new options.ent(viewer, row);
213
- let privacyEnt = await applyPrivacyPolicyForEnt(viewer, ent, row, options);
214
- if (privacyEnt) {
215
- result[idx] = privacyEnt;
216
- }
217
- }));
218
- // filter ents that aren't visible because of privacy
219
- return result.filter((r) => r !== undefined);
366
+ return applyPrivacyPolicyForRows(viewer, rows, options);
220
367
  }
221
368
  exports.loadCustomEnts = loadCustomEnts;
222
369
  function isClause(opts) {
223
370
  const cls = opts;
224
371
  return cls.clause !== undefined && cls.values !== undefined;
225
372
  }
226
- function isRawQuery(opts) {
373
+ function isParameterizedQuery(opts) {
227
374
  return opts.query !== undefined;
228
375
  }
376
+ /**
377
+ * Note that if there's default read transformations (e.g. soft delete) and a clause is passed in
378
+ * either as Clause or QueryDataOptions without {disableTransformations: true}, the default transformation
379
+ * (e.g. soft delete) is applied.
380
+ *
381
+ * Passing a full SQL string or Paramterized SQL string doesn't apply it and the given string is sent to the
382
+ * database as written.
383
+ *
384
+ * e.g.
385
+ * Foo.loadCustom(opts, 'SELECT * FROM foo') // doesn't change the query
386
+ * Foo.loadCustom(opts, { query: 'SELECT * FROM foo WHERE id = ?', values: [1]}) // doesn't change the query
387
+ * Foo.loadCustom(opts, query.Eq('time', Date.now())) // changes the query
388
+ * Foo.loadCustom(opts, {
389
+ * clause: query.LessEq('time', Date.now()),
390
+ * limit: 100,
391
+ * orderby: 'time',
392
+ * }) // changes the query
393
+ * Foo.loadCustom(opts, {
394
+ * clause: query.LessEq('time', Date.now()),
395
+ * limit: 100,
396
+ * orderby: 'time',
397
+ * disableTransformations: false
398
+ * }) // doesn't change the query
399
+ */
229
400
  async function loadCustomData(options, query, context) {
401
+ const rows = await loadCustomDataImpl(options, query, context);
402
+ // prime the data so that subsequent fetches of the row with this id are a cache hit.
403
+ if (options.prime) {
404
+ const loader = options.loaderFactory.createLoader(context);
405
+ if (isPrimableLoader(loader) && loader.primeAll !== undefined) {
406
+ for (const row of rows) {
407
+ loader.primeAll(row);
408
+ }
409
+ }
410
+ }
411
+ return rows;
412
+ }
413
+ exports.loadCustomData = loadCustomData;
414
+ // NOTE: if you use a raw query or paramterized query with this,
415
+ // you should use `SELECT count(*) as count...`
416
+ async function loadCustomCount(options, query, context) {
417
+ // TODO also need to loaderify this in case we're querying for this a lot...
418
+ const rows = await loadCustomDataImpl({
419
+ ...options,
420
+ fields: ["count(1) as count"],
421
+ }, query, context);
422
+ if (rows.length) {
423
+ return parseInt(rows[0].count);
424
+ }
425
+ return 0;
426
+ }
427
+ exports.loadCustomCount = loadCustomCount;
428
+ function isPrimableLoader(loader) {
429
+ return loader != undefined;
430
+ }
431
+ async function loadCustomDataImpl(options, query, context) {
432
+ function getClause(cls) {
433
+ let optClause = options.loaderFactory?.options?.clause;
434
+ if (typeof optClause === "function") {
435
+ optClause = optClause();
436
+ }
437
+ if (!optClause) {
438
+ return cls;
439
+ }
440
+ return clause.And(cls, optClause);
441
+ }
230
442
  if (typeof query === "string") {
231
443
  // no caching, perform raw query
232
- return await performRawQuery(query, [], []);
444
+ return performRawQuery(query, [], []);
233
445
  }
234
446
  else if (isClause(query)) {
447
+ // if a Clause is passed in and we have a default clause
448
+ // associated with the query, pass that in
449
+ // if we want to disableTransformations, need to indicate that with
450
+ // disableTransformations option
235
451
  // this will have rudimentary caching but nothing crazy
236
- return await loadRows({
452
+ return loadRows({
237
453
  ...options,
238
- clause: query,
454
+ clause: getClause(query),
239
455
  context: context,
240
456
  });
241
457
  }
242
- else if (isRawQuery(query)) {
458
+ else if (isParameterizedQuery(query)) {
243
459
  // no caching, perform raw query
244
- return await performRawQuery(query.query, query.values || [], query.logValues);
460
+ return performRawQuery(query.query, query.values || [], query.logValues);
245
461
  }
246
462
  else {
463
+ let cls = query.clause;
464
+ if (!query.disableTransformations) {
465
+ cls = getClause(cls);
466
+ }
247
467
  // this will have rudimentary caching but nothing crazy
248
- return await loadRows({
468
+ return loadRows({
249
469
  ...query,
250
470
  ...options,
251
471
  context: context,
472
+ clause: cls,
252
473
  });
253
474
  }
254
475
  }
255
- exports.loadCustomData = loadCustomData;
256
476
  // Derived ents
477
+ // no ent caching
257
478
  async function loadDerivedEnt(viewer, data, loader) {
258
479
  const ent = new loader(viewer, data);
259
- return await applyPrivacyPolicyForEnt(viewer, ent, data, {
480
+ const r = await applyPrivacyPolicyForEnt(viewer, ent, data, {
260
481
  ent: loader,
261
482
  });
483
+ if (r instanceof Error) {
484
+ return null;
485
+ }
486
+ return r;
262
487
  }
263
488
  exports.loadDerivedEnt = loadDerivedEnt;
489
+ // won't have caching yet either
264
490
  async function loadDerivedEntX(viewer, data, loader) {
265
491
  const ent = new loader(viewer, data);
266
492
  return await applyPrivacyPolicyForEntX(viewer, ent, data, { ent: loader });
@@ -269,19 +495,21 @@ exports.loadDerivedEntX = loadDerivedEntX;
269
495
  // everything calls into this two so should be fine
270
496
  // TODO is there a smarter way to not instantiate two objects here?
271
497
  async function applyPrivacyPolicyForEnt(viewer, ent, data, fieldPrivacyOptions) {
272
- if (ent) {
273
- const visible = await (0, privacy_1.applyPrivacyPolicy)(viewer, ent.getPrivacyPolicy(), ent);
274
- if (!visible) {
275
- return null;
276
- }
498
+ const error = await (0, privacy_1.applyPrivacyPolicyImpl)(viewer, ent.getPrivacyPolicy(), ent);
499
+ if (error === null) {
277
500
  return doFieldPrivacy(viewer, ent, data, fieldPrivacyOptions);
278
501
  }
279
- return null;
502
+ return error;
280
503
  }
281
504
  async function applyPrivacyPolicyForEntX(viewer, ent, data, options) {
282
- // this will throw
283
- await (0, privacy_1.applyPrivacyPolicyX)(viewer, ent.getPrivacyPolicy(), ent);
284
- return doFieldPrivacy(viewer, ent, data, options);
505
+ const r = await applyPrivacyPolicyForEnt(viewer, ent, data, options);
506
+ if (r instanceof Error) {
507
+ throw r;
508
+ }
509
+ if (r === null) {
510
+ throw new Error(`couldn't apply privacyPoliy for ent ${ent.id}`);
511
+ }
512
+ return r;
285
513
  }
286
514
  async function doFieldPrivacy(viewer, ent, data, options) {
287
515
  if (!options.fieldPrivacy) {
@@ -289,13 +517,16 @@ async function doFieldPrivacy(viewer, ent, data, options) {
289
517
  }
290
518
  const promises = [];
291
519
  let somethingChanged = false;
520
+ const origData = {
521
+ ...data,
522
+ };
292
523
  for (const [k, policy] of options.fieldPrivacy) {
524
+ const curr = data[k];
525
+ if (curr === null || curr === undefined) {
526
+ continue;
527
+ }
293
528
  promises.push((async () => {
294
529
  // don't do anything if key is null or for some reason missing
295
- const curr = data[k];
296
- if (curr === null || curr === undefined) {
297
- return;
298
- }
299
530
  const r = await (0, privacy_1.applyPrivacyPolicy)(viewer, policy, ent);
300
531
  if (!r) {
301
532
  data[k] = null;
@@ -306,8 +537,11 @@ async function doFieldPrivacy(viewer, ent, data, options) {
306
537
  await Promise.all(promises);
307
538
  if (somethingChanged) {
308
539
  // have to create new instance
309
- return new options.ent(viewer, data);
540
+ const ent = new options.ent(viewer, data);
541
+ ent.__setRawDBData(origData);
542
+ return ent;
310
543
  }
544
+ ent.__setRawDBData(origData);
311
545
  return ent;
312
546
  }
313
547
  function logQuery(query, logValues) {
@@ -317,6 +551,7 @@ function logQuery(query, logValues) {
317
551
  });
318
552
  (0, logger_1.logTrace)();
319
553
  }
554
+ exports.logQuery = logQuery;
320
555
  // TODO long term figure out if this API should be exposed
321
556
  async function loadRowX(options) {
322
557
  const result = await loadRow(options);
@@ -339,29 +574,26 @@ async function loadRow(options) {
339
574
  }
340
575
  const query = buildQuery(options);
341
576
  logQuery(query, options.clause.logValues());
342
- try {
343
- const pool = db_1.default.getInstance().getPool();
344
- const res = await pool.query(query, options.clause.values());
345
- if (res.rowCount != 1) {
346
- if (res.rowCount > 1) {
347
- (0, logger_1.log)("error", "got more than one row for query " + query);
348
- }
349
- return null;
350
- }
351
- // put the row in the cache...
352
- if (cache) {
353
- cache.primeCache(options, res.rows[0]);
577
+ const pool = db_1.default.getInstance().getPool();
578
+ const res = await pool.query(query, options.clause.values());
579
+ if (res.rowCount != 1) {
580
+ if (res.rowCount > 1) {
581
+ (0, logger_1.log)("error", "got more than one row for query " + query);
354
582
  }
355
- return res.rows[0];
356
- }
357
- catch (e) {
358
- // an example of an error being suppressed
359
- // another one. TODO https://github.com/lolopinto/ent/issues/862
360
- (0, logger_1.log)("error", e);
361
583
  return null;
362
584
  }
585
+ // put the row in the cache...
586
+ if (cache) {
587
+ cache.primeCache(options, res.rows[0]);
588
+ }
589
+ return res.rows[0];
363
590
  }
364
591
  exports.loadRow = loadRow;
592
+ var _logQueryWithError = false;
593
+ function ___setLogQueryErrorWithError(val) {
594
+ _logQueryWithError = val || false;
595
+ }
596
+ exports.___setLogQueryErrorWithError = ___setLogQueryErrorWithError;
365
597
  // this always goes to the db, no cache, nothing
366
598
  async function performRawQuery(query, values, logValues) {
367
599
  const pool = db_1.default.getInstance().getPool();
@@ -371,9 +603,11 @@ async function performRawQuery(query, values, logValues) {
371
603
  return res.rows;
372
604
  }
373
605
  catch (e) {
374
- // TODO need to change every query to catch an error!
375
- (0, logger_1.log)("error", e);
376
- return [];
606
+ if (_logQueryWithError) {
607
+ const msg = e.message;
608
+ throw new Error(`error \`${msg}\` running query: \`${query}\``);
609
+ }
610
+ throw e;
377
611
  }
378
612
  }
379
613
  exports.performRawQuery = performRawQuery;
@@ -432,10 +666,41 @@ function buildGroupQuery(options) {
432
666
  ];
433
667
  }
434
668
  exports.buildGroupQuery = buildGroupQuery;
669
+ class RawQueryOperation {
670
+ constructor(queries) {
671
+ this.queries = queries;
672
+ }
673
+ async performWrite(queryer, context) {
674
+ for (const q of this.queries) {
675
+ if (typeof q === "string") {
676
+ logQuery(q, []);
677
+ await queryer.query(q);
678
+ }
679
+ else {
680
+ logQuery(q.query, q.logValues || []);
681
+ await queryer.query(q.query, q.values);
682
+ }
683
+ }
684
+ }
685
+ performWriteSync(queryer, context) {
686
+ for (const q of this.queries) {
687
+ if (typeof q === "string") {
688
+ logQuery(q, []);
689
+ queryer.execSync(q);
690
+ }
691
+ else {
692
+ logQuery(q.query, q.logValues || []);
693
+ queryer.execSync(q.query, q.values);
694
+ }
695
+ }
696
+ }
697
+ }
698
+ exports.RawQueryOperation = RawQueryOperation;
435
699
  class EditNodeOperation {
436
700
  constructor(options, existingEnt = null) {
437
701
  this.options = options;
438
702
  this.existingEnt = existingEnt;
703
+ this.row = null;
439
704
  this.placeholderID = options.placeholderID;
440
705
  }
441
706
  resolve(executor) {
@@ -471,9 +736,10 @@ class EditNodeOperation {
471
736
  if (this.hasData(options.fields)) {
472
737
  // even this with returning * may not always work if transformed...
473
738
  // we can have a transformed flag to see if it should be returned?
474
- this.row = await editRow(queryer, options, this.existingEnt.id, "RETURNING *");
739
+ this.row = await editRow(queryer, options, "RETURNING *");
475
740
  }
476
741
  else {
742
+ // @ts-ignore
477
743
  this.row = this.existingEnt["data"];
478
744
  }
479
745
  }
@@ -496,7 +762,7 @@ class EditNodeOperation {
496
762
  optionClause = opts.clause;
497
763
  }
498
764
  if (optionClause) {
499
- cls = clause.And(optionClause, cls);
765
+ cls = clause.And(cls, optionClause);
500
766
  }
501
767
  }
502
768
  const query = buildQuery({
@@ -520,10 +786,11 @@ class EditNodeOperation {
520
786
  };
521
787
  if (this.existingEnt) {
522
788
  if (this.hasData(this.options.fields)) {
523
- editRowSync(queryer, options, this.existingEnt.id, "RETURNING *");
789
+ editRowSync(queryer, options, "RETURNING *");
524
790
  this.reloadRow(queryer, this.existingEnt.id, options);
525
791
  }
526
792
  else {
793
+ // @ts-ignore
527
794
  this.row = this.existingEnt["data"];
528
795
  }
529
796
  }
@@ -544,8 +811,23 @@ class EditNodeOperation {
544
811
  }
545
812
  }
546
813
  exports.EditNodeOperation = EditNodeOperation;
814
+ let globalSchema;
815
+ function setGlobalSchema(val) {
816
+ globalSchema = val;
817
+ }
818
+ exports.setGlobalSchema = setGlobalSchema;
819
+ function clearGlobalSchema() {
820
+ globalSchema = undefined;
821
+ }
822
+ exports.clearGlobalSchema = clearGlobalSchema;
823
+ // used by tests. no guarantee will always exist
824
+ function __hasGlobalSchema() {
825
+ return globalSchema !== undefined;
826
+ }
827
+ exports.__hasGlobalSchema = __hasGlobalSchema;
547
828
  class EdgeOperation {
548
- constructor(edgeInput, options) {
829
+ constructor(builder, edgeInput, options) {
830
+ this.builder = builder;
549
831
  this.edgeInput = edgeInput;
550
832
  this.options = options;
551
833
  }
@@ -581,7 +863,31 @@ class EdgeOperation {
581
863
  }
582
864
  }
583
865
  getDeleteRowParams(edgeData, edge, context) {
866
+ let transformed = null;
867
+ let op = schema_1.SQLStatementOperation.Delete;
868
+ let updateData = null;
869
+ // TODO respect disableTransformations
870
+ if (globalSchema?.transformEdgeWrite) {
871
+ transformed = globalSchema.transformEdgeWrite({
872
+ op: schema_1.SQLStatementOperation.Delete,
873
+ edge,
874
+ });
875
+ if (transformed) {
876
+ op = transformed.op;
877
+ if (transformed.op === schema_1.SQLStatementOperation.Insert) {
878
+ throw new Error(`cannot currently transform a delete into an insert`);
879
+ }
880
+ if (transformed.op === schema_1.SQLStatementOperation.Update) {
881
+ if (!transformed.data) {
882
+ throw new Error(`cannot transform a delete into an update without providing data`);
883
+ }
884
+ updateData = transformed.data;
885
+ }
886
+ }
887
+ }
584
888
  return {
889
+ op,
890
+ updateData,
585
891
  options: {
586
892
  tableName: edgeData.edgeTable,
587
893
  context,
@@ -591,11 +897,36 @@ class EdgeOperation {
591
897
  }
592
898
  async performDeleteWrite(q, edgeData, edge, context) {
593
899
  const params = this.getDeleteRowParams(edgeData, edge, context);
594
- return deleteRows(q, params.options, params.clause);
900
+ if (params.op === schema_1.SQLStatementOperation.Delete) {
901
+ return deleteRows(q, params.options, params.clause);
902
+ }
903
+ else {
904
+ if (params.op !== schema_1.SQLStatementOperation.Update) {
905
+ throw new Error(`invalid operation ${params.op}`);
906
+ }
907
+ await editRow(q, {
908
+ tableName: params.options.tableName,
909
+ whereClause: params.clause,
910
+ fields: params.updateData,
911
+ fieldsToLog: params.updateData,
912
+ });
913
+ }
595
914
  }
596
915
  performDeleteWriteSync(q, edgeData, edge, context) {
597
916
  const params = this.getDeleteRowParams(edgeData, edge, context);
598
- return deleteRowsSync(q, params.options, params.clause);
917
+ if (params.op === schema_1.SQLStatementOperation.Delete) {
918
+ return deleteRowsSync(q, params.options, params.clause);
919
+ }
920
+ else {
921
+ if (params.op !== schema_1.SQLStatementOperation.Update) {
922
+ throw new Error(`invalid operation ${params.op}`);
923
+ }
924
+ editRowSync(q, {
925
+ tableName: params.options.tableName,
926
+ whereClause: params.clause,
927
+ fields: params.updateData,
928
+ });
929
+ }
599
930
  }
600
931
  getInsertRowParams(edgeData, edge, context) {
601
932
  const fields = {
@@ -614,6 +945,30 @@ class EdgeOperation {
614
945
  // maybe when actions exist?
615
946
  fields["time"] = new Date().toISOString();
616
947
  }
948
+ const onConflictFields = ["data"];
949
+ if (globalSchema?.extraEdgeFields) {
950
+ for (const name in globalSchema.extraEdgeFields) {
951
+ const f = globalSchema.extraEdgeFields[name];
952
+ if (f.defaultValueOnCreate) {
953
+ const storageKey = (0, schema_1.getStorageKey)(f, name);
954
+ fields[storageKey] = f.defaultValueOnCreate(this.builder, {});
955
+ // onconflict make sure we override the default values
956
+ // e.g. setting deleted_at = null for soft delete
957
+ onConflictFields.push(storageKey);
958
+ }
959
+ }
960
+ }
961
+ // TODO respect disableTransformations
962
+ let transformed = null;
963
+ if (globalSchema?.transformEdgeWrite) {
964
+ transformed = globalSchema.transformEdgeWrite({
965
+ op: schema_1.SQLStatementOperation.Insert,
966
+ edge,
967
+ });
968
+ if (transformed) {
969
+ throw new Error(`transforming an insert edge not currently supported`);
970
+ }
971
+ }
617
972
  return [
618
973
  {
619
974
  tableName: edgeData.edgeTable,
@@ -621,7 +976,9 @@ class EdgeOperation {
621
976
  fieldsToLog: fields,
622
977
  context,
623
978
  },
624
- "ON CONFLICT(id1, edge_type, id2) DO UPDATE SET data = EXCLUDED.data",
979
+ `ON CONFLICT(id1, edge_type, id2) DO UPDATE SET ${onConflictFields
980
+ .map((f) => `${f} = EXCLUDED.${f}`)
981
+ .join(", ")}`,
625
982
  ];
626
983
  }
627
984
  async performInsertWrite(q, edgeData, edge, context) {
@@ -658,7 +1015,7 @@ class EdgeOperation {
658
1015
  }
659
1016
  }
660
1017
  symmetricEdge() {
661
- return new EdgeOperation({
1018
+ return new EdgeOperation(this.builder, {
662
1019
  id1: this.edgeInput.id2,
663
1020
  id1Type: this.edgeInput.id2Type,
664
1021
  id2: this.edgeInput.id1,
@@ -674,7 +1031,7 @@ class EdgeOperation {
674
1031
  });
675
1032
  }
676
1033
  inverseEdge(edgeData) {
677
- return new EdgeOperation({
1034
+ return new EdgeOperation(this.builder, {
678
1035
  id1: this.edgeInput.id2,
679
1036
  id1Type: this.edgeInput.id2Type,
680
1037
  id2: this.edgeInput.id1,
@@ -742,7 +1099,7 @@ class EdgeOperation {
742
1099
  if (data) {
743
1100
  edge.data = data;
744
1101
  }
745
- return new EdgeOperation(edge, {
1102
+ return new EdgeOperation(builder, edge, {
746
1103
  operation: action_1.WriteOperation.Insert,
747
1104
  id2Placeholder,
748
1105
  id1Placeholder,
@@ -763,7 +1120,7 @@ class EdgeOperation {
763
1120
  if (data) {
764
1121
  edge.data = data;
765
1122
  }
766
- return new EdgeOperation(edge, {
1123
+ return new EdgeOperation(builder, edge, {
767
1124
  operation: action_1.WriteOperation.Insert,
768
1125
  id1Placeholder,
769
1126
  id2Placeholder,
@@ -781,7 +1138,7 @@ class EdgeOperation {
781
1138
  id2Type: "",
782
1139
  id1Type: "",
783
1140
  };
784
- return new EdgeOperation(edge, {
1141
+ return new EdgeOperation(builder, edge, {
785
1142
  operation: action_1.WriteOperation.Delete,
786
1143
  });
787
1144
  }
@@ -796,7 +1153,7 @@ class EdgeOperation {
796
1153
  id2Type: "",
797
1154
  id1Type: "",
798
1155
  };
799
- return new EdgeOperation(edge, {
1156
+ return new EdgeOperation(builder, edge, {
800
1157
  operation: action_1.WriteOperation.Delete,
801
1158
  });
802
1159
  }
@@ -808,24 +1165,26 @@ function isSyncQueryer(queryer) {
808
1165
  async function mutateRow(queryer, query, values, logValues, options) {
809
1166
  logQuery(query, logValues);
810
1167
  let cache = options.context?.cache;
1168
+ let res;
811
1169
  try {
812
- let res;
813
1170
  if (isSyncQueryer(queryer)) {
814
1171
  res = queryer.execSync(query, values);
815
1172
  }
816
1173
  else {
817
1174
  res = await queryer.exec(query, values);
818
1175
  }
819
- if (cache) {
820
- cache.clearCache();
1176
+ }
1177
+ catch (e) {
1178
+ if (_logQueryWithError) {
1179
+ const msg = e.message;
1180
+ throw new Error(`error \`${msg}\` running query: \`${query}\``);
821
1181
  }
822
- return res;
1182
+ throw e;
823
1183
  }
824
- catch (err) {
825
- // TODO:::why is this not rethrowing?
826
- (0, logger_1.log)("error", err);
827
- throw err;
1184
+ if (cache) {
1185
+ cache.clearCache();
828
1186
  }
1187
+ return res;
829
1188
  }
830
1189
  function mutateRowSync(queryer, query, values, logValues, options) {
831
1190
  logQuery(query, logValues);
@@ -837,10 +1196,12 @@ function mutateRowSync(queryer, query, values, logValues, options) {
837
1196
  }
838
1197
  return res;
839
1198
  }
840
- catch (err) {
841
- // TODO:::why is this not rethrowing?
842
- (0, logger_1.log)("error", err);
843
- throw err;
1199
+ catch (e) {
1200
+ if (_logQueryWithError) {
1201
+ const msg = e.message;
1202
+ throw new Error(`error \`${msg}\` running query: \`${query}\``);
1203
+ }
1204
+ throw e;
844
1205
  }
845
1206
  }
846
1207
  function buildInsertQuery(options, suffix) {
@@ -893,32 +1254,47 @@ function createRowSync(queryer, options, suffix) {
893
1254
  return null;
894
1255
  }
895
1256
  exports.createRowSync = createRowSync;
896
- function buildUpdateQuery(options, id, suffix) {
1257
+ function buildUpdateQuery(options, suffix) {
897
1258
  let valsString = [];
898
1259
  let values = [];
899
1260
  let logValues = [];
900
1261
  const dialect = db_1.default.getDialect();
901
1262
  let idx = 1;
902
1263
  for (const key in options.fields) {
903
- values.push(options.fields[key]);
904
- if (options.fieldsToLog) {
905
- logValues.push(options.fieldsToLog[key]);
906
- }
907
- if (dialect === db_1.Dialect.Postgres) {
908
- valsString.push(`${key} = $${idx}`);
909
- idx++;
1264
+ if (options.expressions && options.expressions.has(key)) {
1265
+ const cls = options.expressions.get(key);
1266
+ valsString.push(`${key} = ${cls.clause(idx)}`);
1267
+ // TODO need to test a clause with more than one value...
1268
+ const newVals = cls.values();
1269
+ idx += newVals.length;
1270
+ values.push(...newVals);
1271
+ logValues.push(...cls.logValues());
910
1272
  }
911
1273
  else {
912
- valsString.push(`${key} = ?`);
1274
+ const val = options.fields[key];
1275
+ values.push(val);
1276
+ if (options.fieldsToLog) {
1277
+ logValues.push(options.fieldsToLog[key]);
1278
+ }
1279
+ // TODO would be nice to use clause here. need update version of the queries so that
1280
+ // we don't have to handle dialect specifics here
1281
+ // can't use clause because of IS NULL
1282
+ // valsString.push(clause.Eq(key, val).clause(idx));
1283
+ if (dialect === db_1.Dialect.Postgres) {
1284
+ valsString.push(`${key} = $${idx}`);
1285
+ }
1286
+ else {
1287
+ valsString.push(`${key} = ?`);
1288
+ }
1289
+ idx++;
913
1290
  }
914
1291
  }
915
1292
  const vals = valsString.join(", ");
916
1293
  let query = `UPDATE ${options.tableName} SET ${vals} WHERE `;
917
- if (dialect === db_1.Dialect.Postgres) {
918
- query = query + `${options.key} = $${idx}`;
919
- }
920
- else {
921
- query = query + `${options.key} = ?`;
1294
+ query = query + options.whereClause.clause(idx);
1295
+ values.push(...options.whereClause.values());
1296
+ if (options.fieldsToLog) {
1297
+ logValues.push(...options.whereClause.logValues());
922
1298
  }
923
1299
  if (suffix) {
924
1300
  query = query + " " + suffix;
@@ -926,10 +1302,8 @@ function buildUpdateQuery(options, id, suffix) {
926
1302
  return [query, values, logValues];
927
1303
  }
928
1304
  exports.buildUpdateQuery = buildUpdateQuery;
929
- async function editRow(queryer, options, id, suffix) {
930
- const [query, values, logValues] = buildUpdateQuery(options, id, suffix);
931
- // add id as value to prepared query
932
- values.push(id);
1305
+ async function editRow(queryer, options, suffix) {
1306
+ const [query, values, logValues] = buildUpdateQuery(options, suffix);
933
1307
  const res = await mutateRow(queryer, query, values, logValues, options);
934
1308
  if (res?.rowCount == 1) {
935
1309
  // for now assume id primary key
@@ -940,10 +1314,8 @@ async function editRow(queryer, options, id, suffix) {
940
1314
  return null;
941
1315
  }
942
1316
  exports.editRow = editRow;
943
- function editRowSync(queryer, options, id, suffix) {
944
- const [query, values, logValues] = buildUpdateQuery(options, id, suffix);
945
- // add id as value to prepared query
946
- values.push(id);
1317
+ function editRowSync(queryer, options, suffix) {
1318
+ const [query, values, logValues] = buildUpdateQuery(options, suffix);
947
1319
  const res = mutateRowSync(queryer, query, values, logValues, options);
948
1320
  if (res?.rowCount == 1) {
949
1321
  // for now assume id primary key
@@ -994,21 +1366,22 @@ class AssocEdge {
994
1366
  this.edgeType = data.edge_type;
995
1367
  this.time = data.time;
996
1368
  this.data = data.data;
1369
+ this.rawData = data;
1370
+ }
1371
+ __getRawData() {
1372
+ // incase there's extra db fields. useful for tests
1373
+ // in production, a subclass of this should be in use so we won't need this...
1374
+ return this.rawData;
997
1375
  }
998
1376
  getCursor() {
999
1377
  return getCursor({
1000
1378
  row: this,
1001
- col: "time",
1002
- conv: (t) => {
1003
- if (typeof t === "string") {
1004
- return Date.parse(t);
1005
- }
1006
- return t.getTime();
1007
- },
1379
+ col: "id2",
1008
1380
  });
1009
1381
  }
1010
1382
  }
1011
1383
  exports.AssocEdge = AssocEdge;
1384
+ // TODO eventually update this for sortCol time unique keys
1012
1385
  function getCursor(opts) {
1013
1386
  const { row, col, conv } = opts;
1014
1387
  // row: Data, col: string, conv?: (any) => any) {
@@ -1088,52 +1461,79 @@ const edgeFields = [
1088
1461
  ];
1089
1462
  exports.DefaultLimit = 1000;
1090
1463
  // TODO default limit from somewhere
1091
- function defaultEdgeQueryOptions(id1, edgeType) {
1464
+ function defaultEdgeQueryOptions(id1, edgeType, id2) {
1465
+ let cls = clause.And(clause.Eq("id1", id1), clause.Eq("edge_type", edgeType));
1466
+ if (id2) {
1467
+ cls = clause.And(cls, clause.Eq("id2", id2));
1468
+ }
1092
1469
  return {
1093
- clause: clause.And(clause.Eq("id1", id1), clause.Eq("edge_type", edgeType)),
1470
+ clause: cls,
1094
1471
  orderby: "time DESC",
1095
1472
  limit: exports.DefaultLimit,
1096
1473
  };
1097
1474
  }
1098
- exports.defaultEdgeQueryOptions = defaultEdgeQueryOptions;
1099
1475
  async function loadEdges(options) {
1100
1476
  return loadCustomEdges({ ...options, ctr: AssocEdge });
1101
1477
  }
1102
1478
  exports.loadEdges = loadEdges;
1479
+ function getEdgeClauseAndFields(cls, options) {
1480
+ let fields = edgeFields;
1481
+ if (globalSchema?.transformEdgeRead) {
1482
+ const transformClause = globalSchema.transformEdgeRead();
1483
+ if (!options.disableTransformations) {
1484
+ cls = clause.And(cls, transformClause);
1485
+ }
1486
+ fields = edgeFields.concat(transformClause.columns());
1487
+ }
1488
+ return {
1489
+ cls,
1490
+ fields,
1491
+ };
1492
+ }
1493
+ exports.getEdgeClauseAndFields = getEdgeClauseAndFields;
1103
1494
  async function loadCustomEdges(options) {
1104
- const { id1, edgeType, context } = options;
1495
+ const { cls: actualClause, fields, defaultOptions, tableName, } = await loadEgesInfo(options);
1496
+ const rows = await loadRows({
1497
+ tableName,
1498
+ fields: fields,
1499
+ clause: actualClause,
1500
+ orderby: options.queryOptions?.orderby || defaultOptions.orderby,
1501
+ limit: options.queryOptions?.limit || defaultOptions.limit,
1502
+ context: options.context,
1503
+ });
1504
+ return rows.map((row) => {
1505
+ return new options.ctr(row);
1506
+ });
1507
+ }
1508
+ exports.loadCustomEdges = loadCustomEdges;
1509
+ async function loadEgesInfo(options, id2) {
1510
+ const { id1, edgeType } = options;
1105
1511
  const edgeData = await loadEdgeData(edgeType);
1106
1512
  if (!edgeData) {
1107
1513
  throw new Error(`error loading edge data for ${edgeType}`);
1108
1514
  }
1109
- const defaultOptions = defaultEdgeQueryOptions(id1, edgeType);
1515
+ const defaultOptions = defaultEdgeQueryOptions(id1, edgeType, id2);
1110
1516
  let cls = defaultOptions.clause;
1111
1517
  if (options.queryOptions?.clause) {
1112
1518
  cls = clause.And(cls, options.queryOptions.clause);
1113
1519
  }
1114
- const rows = await loadRows({
1520
+ return {
1521
+ ...getEdgeClauseAndFields(cls, options),
1522
+ defaultOptions,
1115
1523
  tableName: edgeData.edgeTable,
1116
- fields: edgeFields,
1117
- clause: cls,
1118
- orderby: options.queryOptions?.orderby || defaultOptions.orderby,
1119
- limit: options.queryOptions?.limit || defaultOptions.limit,
1120
- context,
1121
- });
1122
- return rows.map((row) => {
1123
- return new options.ctr(row);
1124
- });
1524
+ };
1125
1525
  }
1126
- exports.loadCustomEdges = loadCustomEdges;
1127
1526
  async function loadUniqueEdge(options) {
1128
1527
  const { id1, edgeType, context } = options;
1129
1528
  const edgeData = await loadEdgeData(edgeType);
1130
1529
  if (!edgeData) {
1131
1530
  throw new Error(`error loading edge data for ${edgeType}`);
1132
1531
  }
1532
+ const { cls, fields } = getEdgeClauseAndFields(clause.And(clause.Eq("id1", id1), clause.Eq("edge_type", edgeType)), options);
1133
1533
  const row = await loadRow({
1134
1534
  tableName: edgeData.edgeTable,
1135
- fields: edgeFields,
1136
- clause: clause.And(clause.Eq("id1", id1), clause.Eq("edge_type", edgeType)),
1535
+ fields: fields,
1536
+ clause: cls,
1137
1537
  context,
1138
1538
  });
1139
1539
  if (!row) {
@@ -1160,21 +1560,28 @@ async function loadRawEdgeCountX(options) {
1160
1560
  if (!edgeData) {
1161
1561
  throw new Error(`error loading edge data for ${edgeType}`);
1162
1562
  }
1563
+ const { cls } = getEdgeClauseAndFields(clause.And(clause.Eq("id1", id1), clause.Eq("edge_type", edgeType)), options);
1163
1564
  const row = await loadRowX({
1164
1565
  tableName: edgeData.edgeTable,
1165
1566
  // sqlite needs as count otherwise it returns count(1)
1166
1567
  fields: ["count(1) as count"],
1167
- clause: clause.And(clause.Eq("id1", id1), clause.Eq("edge_type", edgeType)),
1568
+ clause: cls,
1168
1569
  context,
1169
1570
  });
1170
1571
  return parseInt(row["count"], 10) || 0;
1171
1572
  }
1172
1573
  exports.loadRawEdgeCountX = loadRawEdgeCountX;
1173
1574
  async function loadEdgeForID2(options) {
1174
- // TODO at some point, same as in go, we can be smart about this and have heuristics to determine if we fetch everything here or not
1175
- // we're assuming a cache here but not always true and this can be expensive if not...
1176
- const edges = await loadCustomEdges(options);
1177
- return edges.find((edge) => edge.id2 == options.id2);
1575
+ const { cls: actualClause, fields, tableName, } = await loadEgesInfo(options, options.id2);
1576
+ const row = await loadRow({
1577
+ tableName,
1578
+ fields: fields,
1579
+ clause: actualClause,
1580
+ context: options.context,
1581
+ });
1582
+ if (row) {
1583
+ return new options.ctr(row);
1584
+ }
1178
1585
  }
1179
1586
  exports.loadEdgeForID2 = loadEdgeForID2;
1180
1587
  async function loadNodesByEdge(viewer, id1, edgeType, options) {
@@ -1190,19 +1597,20 @@ async function loadNodesByEdge(viewer, id1, edgeType, options) {
1190
1597
  }
1191
1598
  exports.loadNodesByEdge = loadNodesByEdge;
1192
1599
  async function applyPrivacyPolicyForRow(viewer, options, row) {
1193
- if (!row) {
1194
- return null;
1195
- }
1196
- const ent = new options.ent(viewer, row);
1197
- return await applyPrivacyPolicyForEnt(viewer, ent, row, options);
1600
+ const r = await applyPrivacyPolicyForRowImpl(viewer, options, row);
1601
+ return r instanceof Error ? null : r;
1198
1602
  }
1199
1603
  exports.applyPrivacyPolicyForRow = applyPrivacyPolicyForRow;
1604
+ async function applyPrivacyPolicyForRowImpl(viewer, options, row) {
1605
+ const ent = new options.ent(viewer, row);
1606
+ return applyPrivacyPolicyForEnt(viewer, ent, row, options);
1607
+ }
1200
1608
  async function applyPrivacyPolicyForRowX(viewer, options, row) {
1201
1609
  const ent = new options.ent(viewer, row);
1202
1610
  return await applyPrivacyPolicyForEntX(viewer, ent, row, options);
1203
1611
  }
1204
- exports.applyPrivacyPolicyForRowX = applyPrivacyPolicyForRowX;
1205
- async function applyPrivacyPolicyForRows(viewer, rows, options) {
1612
+ // deprecated. doesn't use entcache
1613
+ async function applyPrivacyPolicyForRowsDeprecated(viewer, rows, options) {
1206
1614
  let m = new Map();
1207
1615
  // apply privacy logic
1208
1616
  await Promise.all(rows.map(async (row) => {
@@ -1213,27 +1621,62 @@ async function applyPrivacyPolicyForRows(viewer, rows, options) {
1213
1621
  }));
1214
1622
  return m;
1215
1623
  }
1216
- exports.applyPrivacyPolicyForRows = applyPrivacyPolicyForRows;
1217
- async function loadEdgeWithConst(viewer, id1, id2, edgeEnum, edgeType) {
1218
- const edge = await loadEdgeForID2({
1219
- id1: id1,
1220
- id2: id2,
1221
- edgeType: edgeType,
1222
- context: viewer.context,
1223
- ctr: AssocEdge,
1224
- });
1225
- return [edgeEnum, edge];
1624
+ async function applyPrivacyPolicyForRows(viewer, rows, options) {
1625
+ const result = new Array(rows.length);
1626
+ if (!rows.length) {
1627
+ return [];
1628
+ }
1629
+ const entLoader = getEntLoader(viewer, options);
1630
+ await Promise.all(rows.map(async (row, idx) => {
1631
+ const r = await applyPrivacyPolicyForRowAndStoreInEntLoader(viewer, row, options, entLoader);
1632
+ if (r instanceof ErrorWrapper) {
1633
+ return;
1634
+ }
1635
+ result[idx] = r;
1636
+ }));
1637
+ // filter ents that aren't visible because of privacy
1638
+ return result.filter((r) => r !== undefined);
1226
1639
  }
1640
+ exports.applyPrivacyPolicyForRows = applyPrivacyPolicyForRows;
1227
1641
  // given a viewer, an id pair, and a map of edgeEnum to EdgeType
1228
1642
  // return the edgeEnum that's set in the group
1229
1643
  async function getEdgeTypeInGroup(viewer, id1, id2, m) {
1230
1644
  let promises = [];
1231
- for (const [k, v] of m) {
1232
- promises.push(loadEdgeWithConst(viewer, id1, id2, k, v));
1645
+ const edgeDatas = await loadEdgeDatas(...Array.from(m.values()));
1646
+ let tableToEdgeEnumMap = new Map();
1647
+ for (const [edgeEnum, edgeType] of m) {
1648
+ const edgeData = edgeDatas.get(edgeType);
1649
+ if (!edgeData) {
1650
+ throw new Error(`could not load edge data for '${edgeType}'`);
1651
+ }
1652
+ const l = tableToEdgeEnumMap.get(edgeData.edgeTable) ?? [];
1653
+ l.push(edgeEnum);
1654
+ tableToEdgeEnumMap.set(edgeData.edgeTable, l);
1233
1655
  }
1656
+ tableToEdgeEnumMap.forEach((edgeEnums, tableName) => {
1657
+ promises.push((async () => {
1658
+ const edgeTypes = edgeEnums.map((edgeEnum) => m.get(edgeEnum));
1659
+ const { cls, fields } = getEdgeClauseAndFields(clause.And(clause.Eq("id1", id1), clause.In("edge_type", edgeTypes), clause.Eq("id2", id2)), {});
1660
+ const rows = await loadRows({
1661
+ tableName,
1662
+ fields,
1663
+ clause: cls,
1664
+ context: viewer.context,
1665
+ });
1666
+ const row = rows[0];
1667
+ if (row) {
1668
+ const edgeType = row.edge_type;
1669
+ for (const [k, v] of m) {
1670
+ if (v === edgeType) {
1671
+ return [k, new AssocEdge(row)];
1672
+ }
1673
+ }
1674
+ }
1675
+ })());
1676
+ });
1234
1677
  const results = await Promise.all(promises);
1235
1678
  for (const res of results) {
1236
- if (res[1]) {
1679
+ if (res && res[1]) {
1237
1680
  return [res[0], res[1]];
1238
1681
  }
1239
1682
  }