-
Notifications
You must be signed in to change notification settings - Fork 102
Handle pushed down predicates in Electric collection #618
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kevin-dp
wants to merge
16
commits into
main
Choose a base branch
from
kevin/pred-pushdown-to-sync-electric-coll
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,279
−17
Open
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
f678672
Compile IR to SQL
kevin-dp 347a3c6
Use the stream's requestSnapshot method
kevin-dp 5a024b5
Remove todo
kevin-dp 7dec8d6
Modify output format of SQL compiler and serialize the values into PG…
kevin-dp 61da277
Fixes to electric collection + unit test
kevin-dp e3a7d5d
Fix unit test for loading more data via requestSnapshot in the Electr…
kevin-dp 310bd65
Remove debug logging in electric collection
kevin-dp 6df040c
Update type name
kevin-dp 3f6dc70
Upgrade electric client version
kevin-dp dd337d8
Changeset
kevin-dp a118a66
Update lockfile
kevin-dp 044760b
syncMode config
samwillis dc29552
Merge branch 'main' into kevin/pred-pushdown-to-sync-electric-coll
samwillis 2629fe4
docs: Add notes about known unhandled rejection warnings in timeout t…
samwillis 8a09cb8
default to offset=now for on-demand mode
samwillis c9a8721
better handle setting ready under the differnet modes
samwillis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
"@tanstack/electric-db-collection": patch | ||
--- | ||
|
||
Handle predicates that are pushed down. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
export function serialize(value: unknown): string { | ||
if (typeof value === `string`) { | ||
return `'${value}'` | ||
} | ||
|
||
if (typeof value === `number`) { | ||
return value.toString() | ||
} | ||
|
||
if (value === null || value === undefined) { | ||
return `NULL` | ||
} | ||
|
||
if (typeof value === `boolean`) { | ||
return value ? `true` : `false` | ||
} | ||
|
||
if (value instanceof Date) { | ||
return `'${value.toISOString()}'` | ||
} | ||
|
||
if (Array.isArray(value)) { | ||
return `ARRAY[${value.map(serialize).join(`,`)}]` | ||
} | ||
|
||
throw new Error(`Cannot serialize value: ${JSON.stringify(value)}`) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,163 @@ | ||
import { serialize } from "./pg-serializer" | ||
import type { SubsetParams } from "@electric-sql/client" | ||
import type { IR, OnLoadMoreOptions } from "@tanstack/db" | ||
|
||
export type CompiledSqlRecord = Omit<SubsetParams, `params`> & { | ||
params?: Array<unknown> | ||
} | ||
|
||
export function compileSQL<T>(options: OnLoadMoreOptions): SubsetParams { | ||
const { where, orderBy, limit } = options | ||
|
||
const params: Array<T> = [] | ||
const compiledSQL: CompiledSqlRecord = { params } | ||
|
||
if (where) { | ||
// TODO: this only works when the where expression's PropRefs directly reference a column of the collection | ||
// doesn't work if it goes through aliases because then we need to know the entire query to be able to follow the reference until the base collection (cf. followRef function) | ||
compiledSQL.where = compileBasicExpression(where, params) | ||
} | ||
|
||
if (orderBy) { | ||
compiledSQL.orderBy = compileOrderBy(orderBy, params) | ||
} | ||
|
||
if (limit) { | ||
compiledSQL.limit = limit | ||
} | ||
|
||
// Serialize the values in the params array into PG formatted strings | ||
// and transform the array into a Record<string, string> | ||
const paramsRecord = params.reduce( | ||
(acc, param, index) => { | ||
acc[`${index + 1}`] = serialize(param) | ||
return acc | ||
}, | ||
{} as Record<string, string> | ||
) | ||
|
||
return { | ||
...compiledSQL, | ||
params: paramsRecord, | ||
} | ||
} | ||
|
||
/** | ||
* Compiles the expression to a SQL string and mutates the params array with the values. | ||
* @param exp - The expression to compile | ||
* @param params - The params array | ||
* @returns The compiled SQL string | ||
*/ | ||
function compileBasicExpression( | ||
exp: IR.BasicExpression<unknown>, | ||
params: Array<unknown> | ||
): string { | ||
switch (exp.type) { | ||
case `val`: | ||
params.push(exp.value) | ||
return `$${params.length}` | ||
case `ref`: | ||
// TODO: doesn't yet support JSON(B) values which could be accessed with nested props | ||
if (exp.path.length !== 1) { | ||
throw new Error( | ||
`Compiler can't handle nested properties: ${exp.path.join(`.`)}` | ||
) | ||
} | ||
return exp.path[0]! | ||
case `func`: | ||
return compileFunction(exp, params) | ||
default: | ||
throw new Error(`Unknown expression type`) | ||
} | ||
} | ||
|
||
function compileOrderBy(orderBy: IR.OrderBy, params: Array<unknown>): string { | ||
const compiledOrderByClauses = orderBy.map((clause: IR.OrderByClause) => | ||
compileOrderByClause(clause, params) | ||
) | ||
return compiledOrderByClauses.join(`,`) | ||
} | ||
|
||
function compileOrderByClause( | ||
clause: IR.OrderByClause, | ||
params: Array<unknown> | ||
): string { | ||
// TODO: what to do with stringSort and locale? | ||
// Correctly supporting them is tricky as it depends on Postgres' collation | ||
const { expression, compareOptions } = clause | ||
let sql = compileBasicExpression(expression, params) | ||
|
||
if (compareOptions.direction === `desc`) { | ||
sql = `${sql} DESC` | ||
} | ||
|
||
if (compareOptions.nulls === `first`) { | ||
sql = `${sql} NULLS FIRST` | ||
} | ||
|
||
if (compareOptions.nulls === `last`) { | ||
sql = `${sql} NULLS LAST` | ||
} | ||
|
||
return sql | ||
} | ||
|
||
function compileFunction( | ||
exp: IR.Func<unknown>, | ||
params: Array<unknown> = [] | ||
): string { | ||
const { name, args } = exp | ||
|
||
const opName = getOpName(name) | ||
|
||
const compiledArgs = args.map((arg: IR.BasicExpression) => | ||
compileBasicExpression(arg, params) | ||
) | ||
|
||
if (isBinaryOp(name)) { | ||
if (compiledArgs.length !== 2) { | ||
throw new Error(`Binary operator ${name} expects 2 arguments`) | ||
} | ||
const [lhs, rhs] = compiledArgs | ||
return `${lhs} ${opName} ${rhs}` | ||
} | ||
|
||
return `${opName}(${compiledArgs.join(`,`)})` | ||
} | ||
|
||
function isBinaryOp(name: string): boolean { | ||
const binaryOps = [`eq`, `gt`, `gte`, `lt`, `lte`, `and`, `or`] | ||
return binaryOps.includes(name) | ||
} | ||
|
||
function getOpName(name: string): string { | ||
const opNames = { | ||
eq: `=`, | ||
gt: `>`, | ||
gte: `>=`, | ||
lt: `<`, | ||
lte: `<=`, | ||
add: `+`, | ||
and: `AND`, | ||
or: `OR`, | ||
not: `NOT`, | ||
isUndefined: `IS NULL`, | ||
isNull: `IS NULL`, | ||
in: `IN`, | ||
like: `LIKE`, | ||
ilike: `ILIKE`, | ||
upper: `UPPER`, | ||
lower: `LOWER`, | ||
length: `LENGTH`, | ||
concat: `CONCAT`, | ||
coalesce: `COALESCE`, | ||
} | ||
|
||
const opName = opNames[name as keyof typeof opNames] | ||
|
||
if (!opName) { | ||
throw new Error(`Unknown operator/function: ${name}`) | ||
} | ||
|
||
return opName | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This raises the question on if we have the wrong default in DB, should we default to lexical sort?