Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/calm-ducks-report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@electric-sql/pglite-react': patch
---

Expose live query initialization errors through an optional `onError` callback.
6 changes: 6 additions & 0 deletions .changeset/live-query-options.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@electric-sql/pglite': patch
'@electric-sql/pglite-react': patch
---

Allow `live.query` and React's `useLiveQuery` hook to accept query options such as `rowMode: 'array'`.
87 changes: 83 additions & 4 deletions packages/pglite-react/src/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import type { LiveQuery, LiveQueryResults } from '@electric-sql/pglite/live'
import type { QueryOptions } from '@electric-sql/pglite'
import { query as buildQuery } from '@electric-sql/pglite/template'
import { useEffect, useRef, useState } from 'react'
import { usePGlite } from './provider'

export interface UseLiveQueryOptions extends QueryOptions {
/** Called when the initial live query setup rejects. */
onError?: (error: Error) => void
}

function paramsEqual(
a1: unknown[] | undefined | null,
a2: unknown[] | undefined | null,
Expand All @@ -17,13 +23,56 @@ function paramsEqual(
return true
}

function shallowRecordsEqual(a: object | undefined, b: object | undefined) {
if (!a && !b) return true
if (!a || !b) return false
const aRecord = a as Record<PropertyKey, unknown>
const bRecord = b as Record<PropertyKey, unknown>
const aKeys = Reflect.ownKeys(a)
const bKeys = Reflect.ownKeys(b)
return (
aKeys.length === bKeys.length &&
aKeys.every((key) => Object.is(aRecord[key], bRecord[key]))
)
}

function queryOptionsEqual(
a: QueryOptions | undefined,
b: QueryOptions | undefined,
) {
if (!a && !b) return true
if (!a || !b) return false
return (
a.rowMode === b.rowMode &&
shallowRecordsEqual(a.parsers, b.parsers) &&
shallowRecordsEqual(a.serializers, b.serializers) &&
Object.is(a.blob, b.blob) &&
Object.is(a.onNotice, b.onNotice) &&
paramsEqual(a.paramTypes, b.paramTypes)
)
}

function getQueryOptions(
options: UseLiveQueryOptions | undefined,
): QueryOptions | undefined {
if (!options) return undefined
const queryOptions = { ...options }
delete queryOptions.onError
return Reflect.ownKeys(queryOptions).length > 0 ? queryOptions : undefined
}

function useLiveQueryImpl<T = { [key: string]: unknown }>(
query: string | LiveQuery<T> | Promise<LiveQuery<T>>,
params: unknown[] | undefined | null,
key?: string,
options?: UseLiveQueryOptions,
): Omit<LiveQueryResults<T>, 'affectedRows'> | undefined {
const db = usePGlite()
const paramsRef = useRef(params)
const queryOptions = getQueryOptions(options)
const optionsRef = useRef(queryOptions)
const onErrorRef = useRef(options?.onError)
onErrorRef.current = options?.onError
const liveQueryRef = useRef<LiveQuery<T> | undefined>(undefined)
let liveQuery: LiveQuery<T> | undefined
let liveQueryChanged = false
Expand All @@ -42,6 +91,12 @@ function useLiveQueryImpl<T = { [key: string]: unknown }>(
currentParams = params
}

let currentOptions = optionsRef.current
if (!queryOptionsEqual(optionsRef.current, queryOptions)) {
optionsRef.current = queryOptions
currentOptions = queryOptions
}

/* eslint-disable @eslint-react/hooks-extra/no-direct-set-state-in-use-effect */
useEffect(() => {
let cancelled = false
Expand All @@ -50,14 +105,36 @@ function useLiveQueryImpl<T = { [key: string]: unknown }>(
setResults(results)
}
if (typeof query === 'string') {
let unsubscribe: (() => Promise<void>) | undefined
const ret =
key !== undefined
? db.live.incrementalQuery<T>(query, currentParams, key, cb)
: db.live.query<T>(query, currentParams, cb)
: currentOptions
? db.live.query<T>(query, currentParams, currentOptions, cb)
: db.live.query<T>(query, currentParams, cb)

void ret.then(
({ unsubscribe: resolvedUnsubscribe }) => {
if (cancelled) {
void resolvedUnsubscribe()
return
}
unsubscribe = resolvedUnsubscribe
},
(error: Error) => {
if (cancelled) return
const onError = onErrorRef.current
if (onError) {
onError(error)
} else {
throw error
}
},
)

return () => {
cancelled = true
ret.then(({ unsubscribe }) => unsubscribe())
void unsubscribe?.()
}
} else if (query instanceof Promise) {
query.then((liveQuery) => {
Expand All @@ -80,7 +157,7 @@ function useLiveQueryImpl<T = { [key: string]: unknown }>(
} else {
throw new Error('Should never happen')
}
}, [db, key, query, currentParams, liveQuery])
}, [db, key, query, currentParams, currentOptions, liveQuery])
/* eslint-enable @eslint-react/hooks-extra/no-direct-set-state-in-use-effect */

if (liveQueryChanged && liveQuery) {
Expand All @@ -101,6 +178,7 @@ function useLiveQueryImpl<T = { [key: string]: unknown }>(
export function useLiveQuery<T = { [key: string]: unknown }>(
query: string,
params?: unknown[] | null,
options?: UseLiveQueryOptions,
): LiveQueryResults<T> | undefined

export function useLiveQuery<T = { [key: string]: unknown }>(
Expand All @@ -114,8 +192,9 @@ export function useLiveQuery<T = { [key: string]: unknown }>(
export function useLiveQuery<T = { [key: string]: unknown }>(
query: string | LiveQuery<T> | Promise<LiveQuery<T>>,
params?: unknown[] | null,
options?: UseLiveQueryOptions,
): LiveQueryResults<T> | undefined {
return useLiveQueryImpl<T>(query, params)
return useLiveQueryImpl<T>(query, params, undefined, options)
}

useLiveQuery.sql = function <T = { [key: string]: unknown }>(
Expand Down
94 changes: 94 additions & 0 deletions packages/pglite-react/test/hooks-options.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { act, renderHook } from '@testing-library/react'
import { waitFor } from '@testing-library/dom'
import { describe, expect, it, vi } from 'vitest'
import type { LiveQueryResults } from '@electric-sql/pglite/live'
import { useLiveQuery } from '../src/hooks'

const { usePGliteMock } = vi.hoisted(() => ({
usePGliteMock: vi.fn(),
}))

vi.mock('../src/provider', () => ({
usePGlite: usePGliteMock,
}))

describe('useLiveQuery query options', () => {
it('passes options to live.query for initial and updated results', async () => {
type Row = [number, string]
let callback: ((results: LiveQueryResults<Row>) => void) | undefined
const initialResults: LiveQueryResults<Row> = {
rows: [[1, 'initial']],
fields: [
{ name: 'id', dataTypeID: 23 },
{ name: 'name', dataTypeID: 25 },
],
}
const query = vi.fn(async (...args: unknown[]) => {
callback = args.find(
(arg): arg is (results: LiveQueryResults<Row>) => void =>
typeof arg === 'function',
)
callback?.(initialResults)
return {
initialResults,
subscribe: vi.fn(),
unsubscribe: vi.fn(),
refresh: vi.fn(),
}
})
usePGliteMock.mockReturnValue({ live: { query } })

const { result } = renderHook(() =>
useLiveQuery<Row>('SELECT id, name FROM test', [], {
rowMode: 'array',
}),
)

await waitFor(() => expect(result.current).toEqual(initialResults))
expect(query).toHaveBeenCalledTimes(1)
expect(query).toHaveBeenCalledWith(
'SELECT id, name FROM test',
[],
{ rowMode: 'array' },
expect.any(Function),
)

act(() => {
callback?.({
...initialResults,
rows: [
[1, 'initial'],
[2, 'updated'],
],
})
})

expect(result.current?.rows).toEqual([
[1, 'initial'],
[2, 'updated'],
])
})

it('reports query initialization errors through onError', async () => {
const queryError = new Error('syntax error at or near "table"')
const onError = vi.fn()
const query = vi.fn(() => Promise.reject(queryError))
usePGliteMock.mockReturnValue({ live: { query } })

const { unmount } = renderHook(() =>
useLiveQuery('SELECT FROM table', [], { onError }),
)

await waitFor(() => expect(onError).toHaveBeenCalledOnce())
expect(onError).toHaveBeenCalledWith(queryError)
expect(query).toHaveBeenCalledWith(
'SELECT FROM table',
[],
expect.any(Function),
)

unmount()
await Promise.resolve()
expect(onError).toHaveBeenCalledOnce()
})
})
26 changes: 26 additions & 0 deletions packages/pglite-react/test/hooks.test-d.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { describe, it, expectTypeOf } from 'vitest'
import type { QueryOptions } from '@electric-sql/pglite'
import type { LiveQueryOptions } from '@electric-sql/pglite/live'
import { useLiveQuery } from '../src'

describe('useLiveQuery types', () => {
it('accepts exported query options in object and positional APIs', () => {
const queryOptions: QueryOptions = { rowMode: 'array' }
const liveOptions: LiveQueryOptions<[number, string]> = {
query: 'SELECT id, name FROM test',
...queryOptions,
}

expectTypeOf(liveOptions.rowMode).toEqualTypeOf<QueryOptions['rowMode']>()
;() =>
useLiveQuery<[number, string]>(
'SELECT id, name FROM test',
[],
queryOptions,
)
;() =>
useLiveQuery('SELECT FROM table', [], {
onError: (error) => expectTypeOf(error).toEqualTypeOf<Error>(),
})
})
})
Loading