@@ -119,6 +119,7 @@ COMMIT;
119
119
// standard test suite.
120
120
121
121
test ('sync_local new query' , () {
122
+ // This is the query we're using now.
122
123
// This query only uses a single TEMP B-TREE for the GROUP BY operation,
123
124
// leading to fairly efficient execution.
124
125
@@ -134,27 +135,40 @@ COMMIT;
134
135
// |--USE TEMP B-TREE FOR GROUP BY
135
136
// `--CORRELATED SCALAR SUBQUERY 3
136
137
// `--SEARCH r USING INDEX ps_oplog_row (row_type=? AND row_id=?)
138
+ //
139
+ // For details on the max(r.op_id) clause, see:
140
+ // https://sqlite.org/lang_select.html#bare_columns_in_an_aggregate_query
141
+ // > If there is exactly one min() or max() aggregate in the query, then all bare columns in the result
142
+ // > set take values from an input row which also contains the minimum or maximum.
137
143
138
144
var timer = Stopwatch ()..start ();
139
145
final q = '''
146
+ -- 1. Filter oplog by the ops added but not applied yet (oplog b).
147
+ -- We do not do any DISTINCT operation here, since that introduces a temp b-tree.
148
+ -- We filter out duplicates using the GROUP BY below.
140
149
WITH updated_rows AS (
141
150
SELECT b.row_type, b.row_id FROM ps_buckets AS buckets
142
151
CROSS JOIN ps_oplog AS b ON b.bucket = buckets.id
143
152
AND (b.op_id > buckets.last_applied_op)
144
153
UNION ALL SELECT row_type, row_id FROM ps_updated_rows
145
154
)
146
155
156
+ -- 2. Find *all* current ops over different buckets for those objects (oplog r).
147
157
SELECT
148
158
b.row_type,
149
159
b.row_id,
150
160
(
161
+ -- 3. For each unique row, select the data from the latest oplog entry.
162
+ -- The max(r.op_id) clause is used to select the latest oplog entry.
163
+ -- The iif is to avoid the max(r.op_id) column ending up in the results.
151
164
SELECT iif(max(r.op_id), r.data, null)
152
165
FROM ps_oplog r
153
166
WHERE r.row_type = b.row_type
154
167
AND r.row_id = b.row_id
155
168
156
169
) as data
157
170
FROM updated_rows b
171
+ -- Group for (2)
158
172
GROUP BY b.row_type, b.row_id;
159
173
''' ;
160
174
db.select (q);
0 commit comments