jinaga-server 1.1.2 → 1.1.4

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.
@@ -0,0 +1,394 @@
1
+ There are two ways to generate SQL from a Jinaga specification.
2
+ One is used to populate feeds.
3
+ The other is used to project current state.
4
+ The goals are different enough to warrant separate code paths.
5
+
6
+ In this walkthrough, we will be using a complex specification that demonstrates all of the features of the language:
7
+
8
+ ```
9
+ (company: Company, user: Jinaga.User) {
10
+ project: Project [
11
+ project->department: Department->company: Company = company
12
+ !E {
13
+ deleted: Project.Deleted [
14
+ deleted->project: Project = project
15
+ !E {
16
+ restored: Project.Restored [
17
+ restored->deleted: Project.Deleted = deleted
18
+ ]
19
+ }
20
+ ]
21
+ }
22
+ E {
23
+ assignment: Project.Assignment [
24
+ assignment->project: Project = project
25
+ assignment->user: Jinaga.User = user
26
+ !E {
27
+ revoked: Project.Assignment.Revoked [
28
+ revoked->assignment: Project.Assignment = assignment
29
+ ]
30
+ }
31
+ ]
32
+ }
33
+ ]
34
+ deliverable: Deliverable [
35
+ deliverable->project: Project = project
36
+ ]
37
+ } => {
38
+ assignedTasks = {
39
+ task: Task [
40
+ task->deliverable: Deliverable = deliverable
41
+ E {
42
+ assignment: Task.Assignment [
43
+ assignment->task: Task = task
44
+ assignment->user: Jinaga.User = user
45
+ ]
46
+ }
47
+ ]
48
+ } => {
49
+ number = task.number
50
+ }
51
+ }
52
+ ```
53
+
54
+ The model for this specification looks like this:
55
+
56
+ ![Model](model.png)
57
+
58
+ The blue facts are givens.
59
+ The thick black facts are the top-level unknowns.
60
+
61
+ ## Projecting Current State
62
+
63
+ Jinaga projects current state when executing `j.query` or `j.watch`.
64
+ When `j.query` is called, it first fetches feeds from the remote replicator.
65
+ Then it projects the current state from the local database.
66
+ When `j.watch` is called, it does the same two operations in the opposite order.
67
+ It projects the current state first, and then modifies current state as it fetches from the replicator.
68
+
69
+ In either case, the current state is not concerned with the entire history.
70
+ It only accounts for facts that match the specification at the moment of execution.
71
+
72
+ The operation begins in [`postgres-store`](../../src/postgres/postgres-store.ts), `read`.
73
+ It first loads all of the fact type IDs and role IDs represented in the specification.
74
+ Not all of them might be present in the database.
75
+ Perhaps the specification includes types of facts that have never been created locally.
76
+ As we'll see later, missing fact type IDs and role IDs make a portion of the SQL query unsatisfiable.
77
+
78
+ The operation is then broken into three steps.
79
+ First it produces a tree of `ResultComposer`s, each of which has a SQL query and a mechanism for composing the projection objects.
80
+ Then it executes the SQL in the tree, producing a `ResultSetTree`.
81
+ Finally, the `ResultComposer`s compose that tree into an array of projections.
82
+
83
+ ### Generate SQL for a ResultComposer
84
+
85
+ The tree of `ResultComposer` objects mirrors the tree of specifications inside of projections.
86
+ The top-most specification has a projection with named elements.
87
+ If that element is a child specification, then it gets it's own child `ResultComposer`.
88
+ The composers match their results to their parent based on a list of fact IDs.
89
+
90
+ The tree is constructed in [`specification-result-sql`](../../src/postgres/specification-result-sql.ts), starting in the `resultSqlFromSpecification` function.
91
+ It uses `ResultDescriptionBuilder.buildDescription` to walk the specification.
92
+
93
+ It first creates an empty `QueryDescription`.
94
+ This is an immutable data structure.
95
+ As the builder visits parts of the specification, it will operate on the query description to create new, more complete query descriptions.
96
+
97
+ Next, the result description builder adds edges to the result description.
98
+ It calls `addEdges`, which walks the matches and conditions.
99
+ Conditions are either path conditions or existential conditions
100
+
101
+ #### Path conditions
102
+
103
+ A path condition connects an unknown on the left to a previously defined label on the right.
104
+ For each path condition, the builder calls `addPathCondition`.
105
+ The function first evaluates the label on the right.
106
+ If this represents a given that has not yet been added, it adds the input now.
107
+
108
+ In this example, the first path connects the unknown `project` to the given `company`.
109
+ It makes up just this part of the model:
110
+
111
+ ![First path](first-path.png)
112
+
113
+ The lavel `company` refers to a given that has not yet been added.
114
+ It therefore allocates the fact, input, and parameter, producing the following `QueryDescription`:
115
+
116
+ ```json
117
+ {
118
+ "inputs": [
119
+ {
120
+ "label": "company",
121
+ "factIndex": 1,
122
+ "factTypeParameter": 1,
123
+ "factHashParameter": 2
124
+ }
125
+ ],
126
+ "parameters": [
127
+ 1,
128
+ "fSS1hK7OGAeSX4ocN3acuFF87jvzCdPN3vLFUtcej0lOAsVV859UIYZLRcHUoMbyd/J31TdVn5QuE7094oqUPg=="
129
+ ],
130
+ "outputs": [],
131
+ "facts": [
132
+ {
133
+ "factIndex": 1,
134
+ "type": "Company"
135
+ }
136
+ ],
137
+ "edges": [],
138
+ "existentialConditions": []
139
+ }
140
+ ```
141
+
142
+ It then identifies the type and index of the right-hand label.
143
+ In this case, the type is "Company" and the index is 1.
144
+ Then, it walks up the predecessor roles on the right, adding edges as it goes.
145
+ In this case, there are no roles, so it adds no edges on this pass.
146
+
147
+ After walking up the right-hand side, the builder starts from the unknown and walks up the left-hand-side.
148
+ It records this walk so that it can reverse it to add edges.
149
+ The joins need to continue from where the right and left sides meet, and proceed backward toward the unknown.
150
+
151
+ In this case, the left-hand-side of the path condition is `project->department: Department->company: Company`.
152
+ The edges produced are:
153
+
154
+ ```json
155
+ [
156
+ {
157
+ "roleId": 1,
158
+ "declaringType": "Project"
159
+ },
160
+ {
161
+ "roleId": 2,
162
+ "declaringType": "Department"
163
+ }
164
+ ]
165
+ ```
166
+
167
+ It reverses that array of edges, then adds them to the query description.
168
+ For each one, it allocates a parameter for the role ID.
169
+ Then it allocates a new fact index if necessary, and then a new edge.
170
+
171
+ When it has finished with the edges, it adds the unknown as an output.
172
+ At this point, the example query description looks like this:
173
+
174
+ ```json
175
+ {
176
+ "inputs": [
177
+ {
178
+ "label": "company",
179
+ "factIndex": 1,
180
+ "factTypeParameter": 1,
181
+ "factHashParameter": 2
182
+ }
183
+ ],
184
+ "parameters": [
185
+ 1,
186
+ "fSS1hK7OGAeSX4ocN3acuFF87jvzCdPN3vLFUtcej0lOAsVV859UIYZLRcHUoMbyd/J31TdVn5QuE7094oqUPg==",
187
+ 2,
188
+ 1
189
+ ],
190
+ "outputs": [
191
+ {
192
+ "label": "project",
193
+ "type": "Project",
194
+ "factIndex": 3
195
+ }
196
+ ],
197
+ "facts": [
198
+ {
199
+ "factIndex": 1,
200
+ "type": "Company"
201
+ },
202
+ {
203
+ "factIndex": 2,
204
+ "type": "Department"
205
+ },
206
+ {
207
+ "factIndex": 3,
208
+ "type": "Project"
209
+ }
210
+ ],
211
+ "edges": [
212
+ {
213
+ "edgeIndex": 1,
214
+ "predecessorFactIndex": 1,
215
+ "successorFactIndex": 2,
216
+ "roleParameter": 3
217
+ },
218
+ {
219
+ "edgeIndex": 2,
220
+ "predecessorFactIndex": 2,
221
+ "successorFactIndex": 3,
222
+ "roleParameter": 4
223
+ }
224
+ ],
225
+ "existentialConditions": []
226
+ }
227
+ ```
228
+
229
+ This corresponds to the following SQL:
230
+
231
+ ```sql
232
+ SELECT f3.hash AS hash3, f3.fact_id AS id3, f3.data AS data3
233
+ FROM public.fact f1 -- company
234
+ JOIN public.edge e1 -- department->company
235
+ ON e1.predecessor_fact_id = f1.fact_id
236
+ AND e1.role_id = $3
237
+ JOIN public.fact f2 -- department
238
+ ON f2.fact_id = e1.successor_fact_id
239
+ JOIN public.edge e2 -- project->department
240
+ ON e2.predecessor_fact_id = f2.fact_id
241
+ AND e2.role_id = $4
242
+ JOIN public.fact f3 -- project
243
+ ON f3.fact_id = e2.successor_fact_id
244
+ WHERE f1.fact_type_id = $1
245
+ AND f1.hash = $2
246
+ ORDER BY f3.fact_id ASC
247
+ ```
248
+
249
+ #### Existential conditions
250
+
251
+ When the builder encounters an existential condition, it produces a WHERE NOT EXISTS clause.
252
+ It recursively constructs a query description for that sub select.
253
+
254
+ The way that it builds the existential condition is a little interesting.
255
+ It adds the existential condition to the query description, and then records the path to the one that it is working on.
256
+ This first existential condition is at index 0 of the top-level query description, so it is at path `[ 0 ]`.
257
+ When we get to the existential condition *inside* of this one, it will have path `[ 0, 0 ]`.
258
+
259
+ The reason for building the query definitions this way is that the parameters and facts all exist only at the top level.
260
+ We need one consistent set of indexes so that every alias in the SQL query is distinct.
261
+ We also need one consistent set of parameters to pass to the query.
262
+
263
+ By the time the builder has finished adding the edges for the existential condition, the query definition looks like this:
264
+
265
+ ```json
266
+ {
267
+ "inputs": [
268
+ {
269
+ "label": "company",
270
+ "factIndex": 1,
271
+ "factTypeParameter": 1,
272
+ "factHashParameter": 2
273
+ }
274
+ ],
275
+ "parameters": [
276
+ 1,
277
+ "fSS1hK7OGAeSX4ocN3acuFF87jvzCdPN3vLFUtcej0lOAsVV859UIYZLRcHUoMbyd/J31TdVn5QuE7094oqUPg==",
278
+ 2,
279
+ 1,
280
+ 3,
281
+ 4
282
+ ],
283
+ "outputs": [
284
+ {
285
+ "label": "project",
286
+ "type": "Project",
287
+ "factIndex": 3
288
+ }
289
+ ],
290
+ "facts": [
291
+ {
292
+ "factIndex": 1,
293
+ "type": "Company"
294
+ },
295
+ {
296
+ "factIndex": 2,
297
+ "type": "Department"
298
+ },
299
+ {
300
+ "factIndex": 3,
301
+ "type": "Project"
302
+ },
303
+ {
304
+ "factIndex": 4,
305
+ "type": "Project.Deleted"
306
+ },
307
+ {
308
+ "factIndex": 5,
309
+ "type": "Project.Restored"
310
+ }
311
+ ],
312
+ "edges": [
313
+ {
314
+ "edgeIndex": 1,
315
+ "predecessorFactIndex": 1,
316
+ "successorFactIndex": 2,
317
+ "roleParameter": 3
318
+ },
319
+ {
320
+ "edgeIndex": 2,
321
+ "predecessorFactIndex": 2,
322
+ "successorFactIndex": 3,
323
+ "roleParameter": 4
324
+ }
325
+ ],
326
+ "existentialConditions": [
327
+ {
328
+ "exists": false,
329
+ "inputs": [],
330
+ "edges": [
331
+ {
332
+ "edgeIndex": 3,
333
+ "predecessorFactIndex": 3,
334
+ "successorFactIndex": 4,
335
+ "roleParameter": 5
336
+ }
337
+ ],
338
+ "existentialConditions": [
339
+ {
340
+ "exists": false,
341
+ "inputs": [],
342
+ "edges": [
343
+ {
344
+ "edgeIndex": 4,
345
+ "predecessorFactIndex": 4,
346
+ "successorFactIndex": 5,
347
+ "roleParameter": 6
348
+ }
349
+ ],
350
+ "existentialConditions": []
351
+ }
352
+ ]
353
+ }
354
+ ]
355
+ }
356
+ ```
357
+
358
+ This corresponds to the following SQL:
359
+
360
+ ```sql
361
+ SELECT f3.hash AS hash3, f3.fact_id AS id3, f3.data AS data3
362
+ FROM public.fact f1 -- company
363
+ JOIN public.edge e1 -- department->company
364
+ ON e1.predecessor_fact_id = f1.fact_id
365
+ AND e1.role_id = $3
366
+ JOIN public.fact f2 -- department
367
+ ON f2.fact_id = e1.successor_fact_id
368
+ JOIN public.edge e2 -- project->department
369
+ ON e2.predecessor_fact_id = f2.fact_id
370
+ AND e2.role_id = $4
371
+ JOIN public.fact f3 -- project
372
+ ON f3.fact_id = e2.successor_fact_id
373
+ WHERE f1.fact_type_id = $1
374
+ AND f1.hash = $2
375
+ AND NOT EXISTS (
376
+ SELECT 1
377
+ FROM public.edge e3 -- deleted->project
378
+ JOIN public.fact f4 -- deleted
379
+ ON f4.fact_id = e3.successor_fact_id
380
+ WHERE e3.predecessor_fact_id = f3.fact_id
381
+ AND e3.role_id = $5
382
+ AND NOT EXISTS (
383
+ SELECT 1
384
+ FROM public.edge e4 -- restored->deleted
385
+ JOIN public.fact f5 -- restored
386
+ ON f5.fact_id = e4.successor_fact_id
387
+ WHERE e4.predecessor_fact_id = f4.fact_id
388
+ AND e4.role_id = $6
389
+ )
390
+ )
391
+ ORDER BY f3.fact_id ASC
392
+ ```
393
+
394
+ ### Compose projection
@@ -0,0 +1,49 @@
1
+ SELECT f4.hash AS hash4, f4.fact_id AS id4, f4.data AS data4
2
+ , f7.hash AS hash7, f7.fact_id AS id7, f7.data AS data7
3
+ , f9.hash AS hash9, f9.fact_id AS id9, f9.data AS data9
4
+ FROM public.fact f1
5
+ JOIN public.edge e1
6
+ ON e1.predecessor_fact_id = f1.fact_id
7
+ AND e1.role_id = $3
8
+ JOIN public.fact f3
9
+ ON f3.fact_id = e1.successor_fact_id
10
+ JOIN public.edge e2
11
+ ON e2.predecessor_fact_id = f3.fact_id
12
+ AND e2.role_id = $4
13
+ JOIN public.fact f4
14
+ ON f4.fact_id = e2.successor_fact_id
15
+ JOIN public.edge e5
16
+ ON e5.predecessor_fact_id = f4.fact_id
17
+ AND e5.role_id = $7
18
+ JOIN public.fact f7
19
+ ON f7.fact_id = e5.successor_fact_id
20
+ JOIN public.edge e6
21
+ ON e6.successor_fact_id = f7.fact_id
22
+ AND e6.role_id = $10
23
+ JOIN public.fact f2
24
+ ON f2.fact_id = e6.predecessor_fact_id
25
+ JOIN public.edge e8
26
+ ON e8.predecessor_fact_id = f4.fact_id
27
+ AND e8.role_id = $12
28
+ JOIN public.fact f9
29
+ ON f9.fact_id = e8.successor_fact_id
30
+ WHERE 1=1
31
+ AND f1.fact_type_id = $1
32
+ AND f1.hash = $2
33
+ AND f2.fact_type_id = $8
34
+ AND f2.hash = $9
35
+ AND NOT EXISTS (SELECT 1
36
+ FROM public.edge e3
37
+ JOIN public.fact f5
38
+ ON f5.fact_id = e3.successor_fact_id
39
+ WHERE 1=1
40
+ AND e3.predecessor_fact_id = f4.fact_id
41
+ AND e3.role_id = $5)
42
+ AND NOT EXISTS (SELECT 1
43
+ FROM public.edge e7
44
+ JOIN public.fact f8
45
+ ON f8.fact_id = e7.successor_fact_id
46
+ WHERE 1=1
47
+ AND e7.predecessor_fact_id = f7.fact_id
48
+ AND e7.role_id = $11)
49
+ ORDER BY f4.fact_id ASC, f7.fact_id ASC, f9.fact_id ASC
@@ -0,0 +1,9 @@
1
+ digraph {
2
+ rankdir=BT
3
+
4
+ Project -> Department -> Company [penwidth=2]
5
+
6
+ Company [penwidth=2, color=blue]
7
+
8
+ Project [penwidth=2]
9
+ }
Binary file
@@ -0,0 +1,20 @@
1
+ digraph {
2
+ rankdir=BT
3
+
4
+ Project -> Department -> Company [penwidth=2]
5
+ "Project.Assignment.Revoked" -> "Project.Assignment"
6
+ "Project.Assignment" -> Project
7
+ "Project.Assignment" -> "Jinaga.User"
8
+ "Project.Deleted" -> Project
9
+ "Project.Restored" -> "Project.Deleted"
10
+ Deliverable -> Project [penwidth=2]
11
+ Task -> Deliverable
12
+ "Task.Assigned" -> Task
13
+ "Task.Assigned" -> "Jinaga.User"
14
+
15
+ Company [penwidth=2, color=blue]
16
+ "Jinaga.User" [penwidth=2, color=blue]
17
+
18
+ Project [penwidth=2]
19
+ Deliverable [penwidth=2]
20
+ }
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jinaga-server",
3
- "version": "1.1.2",
3
+ "version": "1.1.4",
4
4
  "description": "Application-agnostic back end for web applications",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -20,6 +20,7 @@ import {
20
20
  Specification,
21
21
  Step,
22
22
  Storage,
23
+ TopologicalSorter,
23
24
  } from "jinaga";
24
25
  import { FactFeed } from "jinaga/dist/storage";
25
26
  import { PoolClient } from "pg";
@@ -431,7 +432,8 @@ export class PostgresStore implements Storage {
431
432
  emptyFactTypeMap()
432
433
  );
433
434
  this.factTypeMap = mergeFactTypes(this.factTypeMap, resultFactTypes);
434
- return result.rows.map((r) => {
435
+ const sorter = new TopologicalSorter<FactRecord>();
436
+ const records = result.rows.map((r) => {
435
437
  const { fields, predecessors }: { fields: {}, predecessors: PredecessorCollection } = r.data as any;
436
438
  return <FactRecord>{
437
439
  type: r.name,
@@ -440,6 +442,7 @@ export class PostgresStore implements Storage {
440
442
  predecessors
441
443
  }
442
444
  });
445
+ return sorter.sort(records, (p, r) => r);
443
446
  }
444
447
 
445
448
  private async loadFactTypesFromReferences(references: FactReference[]): Promise<FactTypeMap> {