@powersync/common 1.33.2 → 1.35.0

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 (42) hide show
  1. package/dist/bundle.cjs +5 -5
  2. package/dist/bundle.mjs +3 -3
  3. package/lib/client/AbstractPowerSyncDatabase.d.ts +58 -13
  4. package/lib/client/AbstractPowerSyncDatabase.js +107 -50
  5. package/lib/client/ConnectionManager.d.ts +4 -4
  6. package/lib/client/CustomQuery.d.ts +22 -0
  7. package/lib/client/CustomQuery.js +42 -0
  8. package/lib/client/Query.d.ts +97 -0
  9. package/lib/client/Query.js +1 -0
  10. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +2 -2
  11. package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +1 -3
  12. package/lib/client/sync/bucket/SqliteBucketStorage.js +15 -17
  13. package/lib/client/sync/stream/AbstractRemote.d.ts +1 -10
  14. package/lib/client/sync/stream/AbstractRemote.js +31 -35
  15. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +13 -8
  16. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +112 -82
  17. package/lib/client/sync/stream/streaming-sync-types.d.ts +4 -0
  18. package/lib/client/watched/GetAllQuery.d.ts +32 -0
  19. package/lib/client/watched/GetAllQuery.js +24 -0
  20. package/lib/client/watched/WatchedQuery.d.ts +98 -0
  21. package/lib/client/watched/WatchedQuery.js +12 -0
  22. package/lib/client/watched/processors/AbstractQueryProcessor.d.ts +67 -0
  23. package/lib/client/watched/processors/AbstractQueryProcessor.js +135 -0
  24. package/lib/client/watched/processors/DifferentialQueryProcessor.d.ts +121 -0
  25. package/lib/client/watched/processors/DifferentialQueryProcessor.js +166 -0
  26. package/lib/client/watched/processors/OnChangeQueryProcessor.d.ts +33 -0
  27. package/lib/client/watched/processors/OnChangeQueryProcessor.js +76 -0
  28. package/lib/client/watched/processors/comparators.d.ts +30 -0
  29. package/lib/client/watched/processors/comparators.js +34 -0
  30. package/lib/db/schema/RawTable.d.ts +61 -0
  31. package/lib/db/schema/RawTable.js +32 -0
  32. package/lib/db/schema/Schema.d.ts +14 -0
  33. package/lib/db/schema/Schema.js +20 -1
  34. package/lib/index.d.ts +8 -0
  35. package/lib/index.js +8 -0
  36. package/lib/utils/BaseObserver.d.ts +3 -4
  37. package/lib/utils/BaseObserver.js +3 -0
  38. package/lib/utils/MetaBaseObserver.d.ts +29 -0
  39. package/lib/utils/MetaBaseObserver.js +50 -0
  40. package/lib/utils/async.d.ts +0 -1
  41. package/lib/utils/async.js +0 -10
  42. package/package.json +1 -1
@@ -0,0 +1,135 @@
1
+ import { MetaBaseObserver } from '../../../utils/MetaBaseObserver.js';
2
+ /**
3
+ * Performs underlying watching and yields a stream of results.
4
+ * @internal
5
+ */
6
+ export class AbstractQueryProcessor extends MetaBaseObserver {
7
+ options;
8
+ state;
9
+ abortController;
10
+ initialized;
11
+ _closed;
12
+ disposeListeners;
13
+ get closed() {
14
+ return this._closed;
15
+ }
16
+ constructor(options) {
17
+ super();
18
+ this.options = options;
19
+ this.abortController = new AbortController();
20
+ this._closed = false;
21
+ this.state = this.constructInitialState();
22
+ this.disposeListeners = null;
23
+ this.initialized = this.init();
24
+ }
25
+ constructInitialState() {
26
+ return {
27
+ isLoading: true,
28
+ isFetching: this.reportFetching, // Only set to true if we will report updates in future
29
+ error: null,
30
+ lastUpdated: null,
31
+ data: this.options.placeholderData
32
+ };
33
+ }
34
+ get reportFetching() {
35
+ return this.options.watchOptions.reportFetching ?? true;
36
+ }
37
+ /**
38
+ * Updates the underlying query.
39
+ */
40
+ async updateSettings(settings) {
41
+ await this.initialized;
42
+ if (!this.state.isFetching && this.reportFetching) {
43
+ await this.updateState({
44
+ isFetching: true
45
+ });
46
+ }
47
+ this.options.watchOptions = settings;
48
+ this.abortController.abort();
49
+ this.abortController = new AbortController();
50
+ await this.runWithReporting(() => this.linkQuery({
51
+ abortSignal: this.abortController.signal,
52
+ settings
53
+ }));
54
+ }
55
+ async updateState(update) {
56
+ if (typeof update.error !== 'undefined') {
57
+ await this.iterateAsyncListenersWithError(async (l) => l.onError?.(update.error));
58
+ // An error always stops for the current fetching state
59
+ update.isFetching = false;
60
+ update.isLoading = false;
61
+ }
62
+ Object.assign(this.state, { lastUpdated: new Date() }, update);
63
+ if (typeof update.data !== 'undefined') {
64
+ await this.iterateAsyncListenersWithError(async (l) => l.onData?.(this.state.data));
65
+ }
66
+ await this.iterateAsyncListenersWithError(async (l) => l.onStateChange?.(this.state));
67
+ }
68
+ /**
69
+ * Configures base DB listeners and links the query to listeners.
70
+ */
71
+ async init() {
72
+ const { db } = this.options;
73
+ const disposeCloseListener = db.registerListener({
74
+ closing: async () => {
75
+ await this.close();
76
+ }
77
+ });
78
+ // Wait for the schema to be set before listening to changes
79
+ await db.waitForReady();
80
+ const disposeSchemaListener = db.registerListener({
81
+ schemaChanged: async () => {
82
+ await this.runWithReporting(async () => {
83
+ await this.updateSettings(this.options.watchOptions);
84
+ });
85
+ }
86
+ });
87
+ this.disposeListeners = () => {
88
+ disposeCloseListener();
89
+ disposeSchemaListener();
90
+ };
91
+ // Initial setup
92
+ this.runWithReporting(async () => {
93
+ await this.updateSettings(this.options.watchOptions);
94
+ });
95
+ }
96
+ async close() {
97
+ await this.initialized;
98
+ this.abortController.abort();
99
+ this.disposeListeners?.();
100
+ this.disposeListeners = null;
101
+ this._closed = true;
102
+ this.iterateListeners((l) => l.closed?.());
103
+ this.listeners.clear();
104
+ }
105
+ /**
106
+ * Runs a callback and reports errors to the error listeners.
107
+ */
108
+ async runWithReporting(callback) {
109
+ try {
110
+ await callback();
111
+ }
112
+ catch (error) {
113
+ // This will update the error on the state and iterate error listeners
114
+ await this.updateState({ error });
115
+ }
116
+ }
117
+ /**
118
+ * Iterate listeners and reports errors to onError handlers.
119
+ */
120
+ async iterateAsyncListenersWithError(callback) {
121
+ try {
122
+ await this.iterateAsyncListeners(async (l) => callback(l));
123
+ }
124
+ catch (error) {
125
+ try {
126
+ await this.iterateAsyncListeners(async (l) => l.onError?.(error));
127
+ }
128
+ catch (error) {
129
+ // Errors here are ignored
130
+ // since we are already in an error state
131
+ this.options.db.logger.error('Watched query error handler threw an Error', error);
132
+ }
133
+ }
134
+ }
135
+ }
@@ -0,0 +1,121 @@
1
+ import { WatchCompatibleQuery, WatchedQuery, WatchedQueryListener, WatchedQueryOptions } from '../WatchedQuery.js';
2
+ import { AbstractQueryProcessor, AbstractQueryProcessorOptions, LinkQueryOptions } from './AbstractQueryProcessor.js';
3
+ /**
4
+ * Represents an updated row in a differential watched query.
5
+ * It contains both the current and previous state of the row.
6
+ */
7
+ export interface WatchedQueryRowDifferential<RowType> {
8
+ readonly current: RowType;
9
+ readonly previous: RowType;
10
+ }
11
+ /**
12
+ * Represents the result of a watched query that has been diffed.
13
+ * {@link DifferentialWatchedQueryState#diff} is of the {@link WatchedQueryDifferential} form.
14
+ */
15
+ export interface WatchedQueryDifferential<RowType> {
16
+ readonly added: ReadonlyArray<Readonly<RowType>>;
17
+ /**
18
+ * The entire current result set.
19
+ * Array item object references are preserved between updates if the item is unchanged.
20
+ *
21
+ * e.g. In the query
22
+ * ```sql
23
+ * SELECT name, make FROM assets ORDER BY make ASC;
24
+ * ```
25
+ *
26
+ * If a previous result set contains an item (A) `{name: 'pc', make: 'Cool PC'}` and
27
+ * an update has been made which adds another item (B) to the result set (the item A is unchanged) - then
28
+ * the updated result set will be contain the same object reference, to item A, as the previous result set.
29
+ * This is regardless of the item A's position in the updated result set.
30
+ */
31
+ readonly all: ReadonlyArray<Readonly<RowType>>;
32
+ readonly removed: ReadonlyArray<Readonly<RowType>>;
33
+ readonly updated: ReadonlyArray<WatchedQueryRowDifferential<Readonly<RowType>>>;
34
+ readonly unchanged: ReadonlyArray<Readonly<RowType>>;
35
+ }
36
+ /**
37
+ * Row comparator for differentially watched queries which keys and compares items in the result set.
38
+ */
39
+ export interface DifferentialWatchedQueryComparator<RowType> {
40
+ /**
41
+ * Generates a unique key for the item.
42
+ */
43
+ keyBy: (item: RowType) => string;
44
+ /**
45
+ * Generates a token for comparing items with matching keys.
46
+ */
47
+ compareBy: (item: RowType) => string;
48
+ }
49
+ /**
50
+ * Options for building a differential watched query with the {@link Query} builder.
51
+ */
52
+ export interface DifferentialWatchedQueryOptions<RowType> extends WatchedQueryOptions {
53
+ /**
54
+ * Initial result data which is presented while the initial loading is executing.
55
+ */
56
+ placeholderData?: RowType[];
57
+ /**
58
+ * Row comparator used to identify and compare rows in the result set.
59
+ * If not provided, the default comparator will be used which keys items by their `id` property if available,
60
+ * otherwise it uses JSON stringification of the entire item for keying and comparison.
61
+ * @defaultValue {@link DEFAULT_ROW_COMPARATOR}
62
+ */
63
+ rowComparator?: DifferentialWatchedQueryComparator<RowType>;
64
+ }
65
+ /**
66
+ * Settings for differential incremental watched queries using.
67
+ */
68
+ export interface DifferentialWatchedQuerySettings<RowType> extends DifferentialWatchedQueryOptions<RowType> {
69
+ /**
70
+ * The query here must return an array of items that can be differentiated.
71
+ */
72
+ query: WatchCompatibleQuery<RowType[]>;
73
+ }
74
+ export interface DifferentialWatchedQueryListener<RowType> extends WatchedQueryListener<ReadonlyArray<Readonly<RowType>>> {
75
+ onDiff?: (diff: WatchedQueryDifferential<RowType>) => void | Promise<void>;
76
+ }
77
+ export type DifferentialWatchedQuery<RowType> = WatchedQuery<ReadonlyArray<Readonly<RowType>>, DifferentialWatchedQuerySettings<RowType>, DifferentialWatchedQueryListener<RowType>>;
78
+ /**
79
+ * @internal
80
+ */
81
+ export interface DifferentialQueryProcessorOptions<RowType> extends AbstractQueryProcessorOptions<RowType[], DifferentialWatchedQuerySettings<RowType>> {
82
+ rowComparator?: DifferentialWatchedQueryComparator<RowType>;
83
+ }
84
+ type DataHashMap<RowType> = Map<string, {
85
+ hash: string;
86
+ item: RowType;
87
+ }>;
88
+ /**
89
+ * An empty differential result set.
90
+ * This is used as the initial state for differential incrementally watched queries.
91
+ */
92
+ export declare const EMPTY_DIFFERENTIAL: {
93
+ added: never[];
94
+ all: never[];
95
+ removed: never[];
96
+ updated: never[];
97
+ unchanged: never[];
98
+ };
99
+ /**
100
+ * Default implementation of the {@link DifferentialWatchedQueryComparator} for watched queries.
101
+ * It keys items by their `id` property if available, alternatively it uses JSON stringification
102
+ * of the entire item for the key and comparison.
103
+ */
104
+ export declare const DEFAULT_ROW_COMPARATOR: DifferentialWatchedQueryComparator<any>;
105
+ /**
106
+ * Uses the PowerSync onChange event to trigger watched queries.
107
+ * Results are emitted on every change of the relevant tables.
108
+ * @internal
109
+ */
110
+ export declare class DifferentialQueryProcessor<RowType> extends AbstractQueryProcessor<ReadonlyArray<Readonly<RowType>>, DifferentialWatchedQuerySettings<RowType>> implements DifferentialWatchedQuery<RowType> {
111
+ protected options: DifferentialQueryProcessorOptions<RowType>;
112
+ protected comparator: DifferentialWatchedQueryComparator<RowType>;
113
+ constructor(options: DifferentialQueryProcessorOptions<RowType>);
114
+ protected differentiate(current: RowType[], previousMap: DataHashMap<RowType>): {
115
+ diff: WatchedQueryDifferential<RowType>;
116
+ map: DataHashMap<RowType>;
117
+ hasChanged: boolean;
118
+ };
119
+ protected linkQuery(options: LinkQueryOptions<WatchedQueryDifferential<RowType>>): Promise<void>;
120
+ }
121
+ export {};
@@ -0,0 +1,166 @@
1
+ import { AbstractQueryProcessor } from './AbstractQueryProcessor.js';
2
+ /**
3
+ * An empty differential result set.
4
+ * This is used as the initial state for differential incrementally watched queries.
5
+ */
6
+ export const EMPTY_DIFFERENTIAL = {
7
+ added: [],
8
+ all: [],
9
+ removed: [],
10
+ updated: [],
11
+ unchanged: []
12
+ };
13
+ /**
14
+ * Default implementation of the {@link DifferentialWatchedQueryComparator} for watched queries.
15
+ * It keys items by their `id` property if available, alternatively it uses JSON stringification
16
+ * of the entire item for the key and comparison.
17
+ */
18
+ export const DEFAULT_ROW_COMPARATOR = {
19
+ keyBy: (item) => {
20
+ if (item && typeof item == 'object' && typeof item['id'] == 'string') {
21
+ return item['id'];
22
+ }
23
+ return JSON.stringify(item);
24
+ },
25
+ compareBy: (item) => JSON.stringify(item)
26
+ };
27
+ /**
28
+ * Uses the PowerSync onChange event to trigger watched queries.
29
+ * Results are emitted on every change of the relevant tables.
30
+ * @internal
31
+ */
32
+ export class DifferentialQueryProcessor extends AbstractQueryProcessor {
33
+ options;
34
+ comparator;
35
+ constructor(options) {
36
+ super(options);
37
+ this.options = options;
38
+ this.comparator = options.rowComparator ?? DEFAULT_ROW_COMPARATOR;
39
+ }
40
+ /*
41
+ * @returns If the sets are equal
42
+ */
43
+ differentiate(current, previousMap) {
44
+ const { keyBy, compareBy } = this.comparator;
45
+ let hasChanged = false;
46
+ const currentMap = new Map();
47
+ const removedTracker = new Set(previousMap.keys());
48
+ // Allow mutating to populate the data temporarily.
49
+ const diff = {
50
+ all: [],
51
+ added: [],
52
+ removed: [],
53
+ updated: [],
54
+ unchanged: []
55
+ };
56
+ /**
57
+ * Looping over the current result set array is important to preserve
58
+ * the ordering of the result set.
59
+ * We can replace items in the current array with previous object references if they are equal.
60
+ */
61
+ for (const item of current) {
62
+ const key = keyBy(item);
63
+ const hash = compareBy(item);
64
+ currentMap.set(key, { hash, item });
65
+ const previousItem = previousMap.get(key);
66
+ if (!previousItem) {
67
+ // New item
68
+ hasChanged = true;
69
+ diff.added.push(item);
70
+ diff.all.push(item);
71
+ }
72
+ else {
73
+ // Existing item
74
+ if (hash == previousItem.hash) {
75
+ diff.unchanged.push(previousItem.item);
76
+ // Use the previous object reference
77
+ diff.all.push(previousItem.item);
78
+ // update the map to preserve the reference
79
+ currentMap.set(key, previousItem);
80
+ }
81
+ else {
82
+ hasChanged = true;
83
+ diff.updated.push({ current: item, previous: previousItem.item });
84
+ // Use the new reference
85
+ diff.all.push(item);
86
+ }
87
+ }
88
+ // The item is present, we don't consider it removed
89
+ removedTracker.delete(key);
90
+ }
91
+ diff.removed = Array.from(removedTracker).map((key) => previousMap.get(key).item);
92
+ hasChanged = hasChanged || diff.removed.length > 0;
93
+ return {
94
+ diff,
95
+ hasChanged,
96
+ map: currentMap
97
+ };
98
+ }
99
+ async linkQuery(options) {
100
+ const { db, watchOptions } = this.options;
101
+ const { abortSignal } = options;
102
+ const compiledQuery = watchOptions.query.compile();
103
+ const tables = await db.resolveTables(compiledQuery.sql, compiledQuery.parameters, {
104
+ tables: options.settings.triggerOnTables
105
+ });
106
+ let currentMap = new Map();
107
+ // populate the currentMap from the placeholder data
108
+ this.state.data.forEach((item) => {
109
+ currentMap.set(this.comparator.keyBy(item), {
110
+ hash: this.comparator.compareBy(item),
111
+ item
112
+ });
113
+ });
114
+ db.onChangeWithCallback({
115
+ onChange: async () => {
116
+ if (this.closed) {
117
+ return;
118
+ }
119
+ // This fires for each change of the relevant tables
120
+ try {
121
+ if (this.reportFetching && !this.state.isFetching) {
122
+ await this.updateState({ isFetching: true });
123
+ }
124
+ const partialStateUpdate = {};
125
+ // Always run the query if an underlying table has changed
126
+ const result = await watchOptions.query.execute({
127
+ sql: compiledQuery.sql,
128
+ // Allows casting from ReadOnlyArray[unknown] to Array<unknown>
129
+ // This allows simpler compatibility with PowerSync queries
130
+ parameters: [...compiledQuery.parameters],
131
+ db: this.options.db
132
+ });
133
+ if (this.reportFetching) {
134
+ partialStateUpdate.isFetching = false;
135
+ }
136
+ if (this.state.isLoading) {
137
+ partialStateUpdate.isLoading = false;
138
+ }
139
+ const { diff, hasChanged, map } = this.differentiate(result, currentMap);
140
+ // Update for future comparisons
141
+ currentMap = map;
142
+ if (hasChanged) {
143
+ await this.iterateAsyncListenersWithError((l) => l.onDiff?.(diff));
144
+ Object.assign(partialStateUpdate, {
145
+ data: diff.all
146
+ });
147
+ }
148
+ if (Object.keys(partialStateUpdate).length > 0) {
149
+ await this.updateState(partialStateUpdate);
150
+ }
151
+ }
152
+ catch (error) {
153
+ await this.updateState({ error });
154
+ }
155
+ },
156
+ onError: async (error) => {
157
+ await this.updateState({ error });
158
+ }
159
+ }, {
160
+ signal: abortSignal,
161
+ tables,
162
+ throttleMs: watchOptions.throttleMs,
163
+ triggerImmediate: true // used to emit the initial state
164
+ });
165
+ }
166
+ }
@@ -0,0 +1,33 @@
1
+ import { WatchCompatibleQuery, WatchedQuery, WatchedQueryOptions } from '../WatchedQuery.js';
2
+ import { AbstractQueryProcessor, AbstractQueryProcessorOptions, LinkQueryOptions } from './AbstractQueryProcessor.js';
3
+ import { WatchedQueryComparator } from './comparators.js';
4
+ /**
5
+ * Settings for {@link WatchedQuery} instances created via {@link Query#watch}.
6
+ */
7
+ export interface WatchedQuerySettings<DataType> extends WatchedQueryOptions {
8
+ query: WatchCompatibleQuery<DataType>;
9
+ }
10
+ /**
11
+ * {@link WatchedQuery} returned from {@link Query#watch}.
12
+ */
13
+ export type StandardWatchedQuery<DataType> = WatchedQuery<DataType, WatchedQuerySettings<DataType>>;
14
+ /**
15
+ * @internal
16
+ */
17
+ export interface OnChangeQueryProcessorOptions<Data> extends AbstractQueryProcessorOptions<Data, WatchedQuerySettings<Data>> {
18
+ comparator?: WatchedQueryComparator<Data>;
19
+ }
20
+ /**
21
+ * Uses the PowerSync onChange event to trigger watched queries.
22
+ * Results are emitted on every change of the relevant tables.
23
+ * @internal
24
+ */
25
+ export declare class OnChangeQueryProcessor<Data> extends AbstractQueryProcessor<Data, WatchedQuerySettings<Data>> {
26
+ protected options: OnChangeQueryProcessorOptions<Data>;
27
+ constructor(options: OnChangeQueryProcessorOptions<Data>);
28
+ /**
29
+ * @returns If the sets are equal
30
+ */
31
+ protected checkEquality(current: Data, previous: Data): boolean;
32
+ protected linkQuery(options: LinkQueryOptions<Data>): Promise<void>;
33
+ }
@@ -0,0 +1,76 @@
1
+ import { AbstractQueryProcessor } from './AbstractQueryProcessor.js';
2
+ /**
3
+ * Uses the PowerSync onChange event to trigger watched queries.
4
+ * Results are emitted on every change of the relevant tables.
5
+ * @internal
6
+ */
7
+ export class OnChangeQueryProcessor extends AbstractQueryProcessor {
8
+ options;
9
+ constructor(options) {
10
+ super(options);
11
+ this.options = options;
12
+ }
13
+ /**
14
+ * @returns If the sets are equal
15
+ */
16
+ checkEquality(current, previous) {
17
+ // Use the provided comparator if available. Assume values are unique if not available.
18
+ return this.options.comparator?.checkEquality?.(current, previous) ?? false;
19
+ }
20
+ async linkQuery(options) {
21
+ const { db, watchOptions } = this.options;
22
+ const { abortSignal } = options;
23
+ const compiledQuery = watchOptions.query.compile();
24
+ const tables = await db.resolveTables(compiledQuery.sql, compiledQuery.parameters, {
25
+ tables: options.settings.triggerOnTables
26
+ });
27
+ db.onChangeWithCallback({
28
+ onChange: async () => {
29
+ if (this.closed) {
30
+ return;
31
+ }
32
+ // This fires for each change of the relevant tables
33
+ try {
34
+ if (this.reportFetching && !this.state.isFetching) {
35
+ await this.updateState({ isFetching: true });
36
+ }
37
+ const partialStateUpdate = {};
38
+ // Always run the query if an underlying table has changed
39
+ const result = await watchOptions.query.execute({
40
+ sql: compiledQuery.sql,
41
+ // Allows casting from ReadOnlyArray[unknown] to Array<unknown>
42
+ // This allows simpler compatibility with PowerSync queries
43
+ parameters: [...compiledQuery.parameters],
44
+ db: this.options.db
45
+ });
46
+ if (this.reportFetching) {
47
+ partialStateUpdate.isFetching = false;
48
+ }
49
+ if (this.state.isLoading) {
50
+ partialStateUpdate.isLoading = false;
51
+ }
52
+ // Check if the result has changed
53
+ if (!this.checkEquality(result, this.state.data)) {
54
+ Object.assign(partialStateUpdate, {
55
+ data: result
56
+ });
57
+ }
58
+ if (Object.keys(partialStateUpdate).length > 0) {
59
+ await this.updateState(partialStateUpdate);
60
+ }
61
+ }
62
+ catch (error) {
63
+ await this.updateState({ error });
64
+ }
65
+ },
66
+ onError: async (error) => {
67
+ await this.updateState({ error });
68
+ }
69
+ }, {
70
+ signal: abortSignal,
71
+ tables,
72
+ throttleMs: watchOptions.throttleMs,
73
+ triggerImmediate: true // used to emit the initial state
74
+ });
75
+ }
76
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * A basic comparator for incrementally watched queries. This performs a single comparison which
3
+ * determines if the result set has changed. The {@link WatchedQuery} will only emit the new result
4
+ * if a change has been detected.
5
+ */
6
+ export interface WatchedQueryComparator<Data> {
7
+ checkEquality: (current: Data, previous: Data) => boolean;
8
+ }
9
+ /**
10
+ * Options for {@link ArrayComparator}
11
+ */
12
+ export type ArrayComparatorOptions<ItemType> = {
13
+ /**
14
+ * Returns a string to uniquely identify an item in the array.
15
+ */
16
+ compareBy: (item: ItemType) => string;
17
+ };
18
+ /**
19
+ * An efficient comparator for {@link WatchedQuery} created with {@link Query#watch}. This has the ability to determine if a query
20
+ * result has changes without necessarily processing all items in the result.
21
+ */
22
+ export declare class ArrayComparator<ItemType> implements WatchedQueryComparator<ItemType[]> {
23
+ protected options: ArrayComparatorOptions<ItemType>;
24
+ constructor(options: ArrayComparatorOptions<ItemType>);
25
+ checkEquality(current: ItemType[], previous: ItemType[]): boolean;
26
+ }
27
+ /**
28
+ * Watched query comparator that always reports changed result sets.
29
+ */
30
+ export declare const FalsyComparator: WatchedQueryComparator<unknown>;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * An efficient comparator for {@link WatchedQuery} created with {@link Query#watch}. This has the ability to determine if a query
3
+ * result has changes without necessarily processing all items in the result.
4
+ */
5
+ export class ArrayComparator {
6
+ options;
7
+ constructor(options) {
8
+ this.options = options;
9
+ }
10
+ checkEquality(current, previous) {
11
+ if (current.length === 0 && previous.length === 0) {
12
+ return true;
13
+ }
14
+ if (current.length !== previous.length) {
15
+ return false;
16
+ }
17
+ const { compareBy } = this.options;
18
+ // At this point the lengths are equal
19
+ for (let i = 0; i < current.length; i++) {
20
+ const currentItem = compareBy(current[i]);
21
+ const previousItem = compareBy(previous[i]);
22
+ if (currentItem !== previousItem) {
23
+ return false;
24
+ }
25
+ }
26
+ return true;
27
+ }
28
+ }
29
+ /**
30
+ * Watched query comparator that always reports changed result sets.
31
+ */
32
+ export const FalsyComparator = {
33
+ checkEquality: () => false // Default comparator that always returns false
34
+ };
@@ -0,0 +1,61 @@
1
+ /**
2
+ * A pending variant of a {@link RawTable} that doesn't have a name (because it would be inferred when creating the
3
+ * schema).
4
+ */
5
+ export type RawTableType = {
6
+ /**
7
+ * The statement to run when PowerSync detects that a row needs to be inserted or updated.
8
+ */
9
+ put: PendingStatement;
10
+ /**
11
+ * The statement to run when PowerSync detects that a row needs to be deleted.
12
+ */
13
+ delete: PendingStatement;
14
+ };
15
+ /**
16
+ * A parameter to use as part of {@link PendingStatement}.
17
+ *
18
+ * For delete statements, only the `"Id"` value is supported - the sync client will replace it with the id of the row to
19
+ * be synced.
20
+ *
21
+ * For insert and replace operations, the values of columns in the table are available as parameters through
22
+ * `{Column: 'name'}`.
23
+ */
24
+ export type PendingStatementParameter = 'Id' | {
25
+ Column: string;
26
+ };
27
+ /**
28
+ * A statement that the PowerSync client should use to insert or delete data into a table managed by the user.
29
+ */
30
+ export type PendingStatement = {
31
+ sql: string;
32
+ params: PendingStatementParameter[];
33
+ };
34
+ /**
35
+ * Instructs PowerSync to sync data into a "raw" table.
36
+ *
37
+ * Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow
38
+ * using client-side table and column constraints.
39
+ *
40
+ * To collect local writes to raw tables with PowerSync, custom triggers are required. See
41
+ * {@link https://docs.powersync.com/usage/use-case-examples/raw-tables the documentation} for details and an example on
42
+ * using raw tables.
43
+ *
44
+ * Note that raw tables are only supported when using the new `SyncClientImplementation.rust` sync client.
45
+ *
46
+ * @experimental Please note that this feature is experimental at the moment, and not covered by PowerSync semver or
47
+ * stability guarantees.
48
+ */
49
+ export declare class RawTable implements RawTableType {
50
+ /**
51
+ * The name of the table.
52
+ *
53
+ * This does not have to match the actual table name in the schema - {@link put} and {@link delete} are free to use
54
+ * another table. Instead, this name is used by the sync client to recognize that operations on this table (as it
55
+ * appears in the source / backend database) are to be handled specially.
56
+ */
57
+ name: string;
58
+ put: PendingStatement;
59
+ delete: PendingStatement;
60
+ constructor(name: string, type: RawTableType);
61
+ }