tanstack-db-pglite 1.0.5 → 1.1.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.
package/dist/drizzle.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import type { CollectionConfig, DeleteMutationFnParams, InsertMutationFnParams, SyncConfig, UpdateMutationFnParams } from '@tanstack/db';
2
2
  import type { IndexColumn, PgTable } from 'drizzle-orm/pg-core';
3
3
  import type { PgliteDatabase } from 'drizzle-orm/pglite';
4
- export declare function drizzleCollectionOptions<Table extends PgTable, SyncParams extends Parameters<SyncConfig<Table['$inferSelect'], string>['sync']>[0] = Parameters<SyncConfig<Table['$inferSelect'], string>['sync']>[0]>({ startSync, ...config }: {
4
+ import type { CreateSelectSchema } from 'drizzle-zod';
5
+ type SyncParams<Table extends PgTable> = Parameters<SyncConfig<Table['$inferSelect'], string>['sync']>[0];
6
+ export declare function drizzleCollectionOptions<Table extends PgTable>({ startSync, ...config }: {
5
7
  db: PgliteDatabase<any>;
6
8
  table: Table;
7
9
  primaryColumn: IndexColumn;
@@ -10,9 +12,8 @@ export declare function drizzleCollectionOptions<Table extends PgTable, SyncPara
10
12
  onDelete?: (params: DeleteMutationFnParams<Table['$inferSelect'], string>) => Promise<void>;
11
13
  startSync?: boolean;
12
14
  prepare?: () => Promise<unknown> | unknown;
13
- sync?: (params: Pick<SyncParams, 'write' | 'collection'>) => Promise<void>;
14
- }): CollectionConfig<Table['$inferSelect'], string> & {
15
- utils: {
16
- runSync: () => Promise<void>;
17
- };
18
- };
15
+ sync?: (params: Pick<SyncParams<Table>, 'write' | 'collection'>) => Promise<void>;
16
+ }): CollectionConfig<Table['$inferSelect'], string, ReturnType<CreateSelectSchema<Table['$inferSelect']>>, {
17
+ runSync: () => Promise<void>;
18
+ }>;
19
+ export {};
package/dist/drizzle.js CHANGED
@@ -6,32 +6,48 @@ export function drizzleCollectionOptions({ startSync = true, ...config }) {
6
6
  // eslint-disable-next-line ts/no-explicit-any
7
7
  async function onDrizzleInsert(data, tx) {
8
8
  // @ts-expect-error drizzle types
9
- await (tx || config.db).insert(config.table).values(data);
9
+ await (tx || config.db).insert(config.table).values(data).catch((e) => {
10
+ if (e instanceof Error && e.cause) {
11
+ throw e.cause;
12
+ }
13
+ throw e;
14
+ });
10
15
  }
11
16
  // eslint-disable-next-line ts/no-explicit-any
12
17
  async function onDrizzleUpdate(id, changes, tx) {
13
- await (tx || config.db).update(config.table).set(changes).where(eq(config.primaryColumn, id));
18
+ await (tx || config.db).update(config.table).set(changes).where(eq(config.primaryColumn, id)).catch((e) => {
19
+ if (e instanceof Error && e.cause) {
20
+ throw e.cause;
21
+ }
22
+ throw e;
23
+ });
14
24
  }
15
25
  // eslint-disable-next-line ts/no-explicit-any
16
26
  async function onDrizzleDelete(ids, tx) {
17
- await (tx || config.db).delete(config.table).where(inArray(config.primaryColumn, ids));
27
+ await (tx || config.db).delete(config.table).where(inArray(config.primaryColumn, ids)).catch((e) => {
28
+ if (e instanceof Error && e.cause) {
29
+ throw e.cause;
30
+ }
31
+ throw e;
32
+ });
18
33
  }
19
34
  const getSyncParams = async () => {
20
35
  const params = await syncParams;
21
36
  return {
22
- write: async (p) => {
37
+ write: async (message) => {
23
38
  params.begin();
24
39
  try {
25
- if (p.type === 'insert') {
26
- await onDrizzleInsert([p.value]);
40
+ if (message.type === 'insert') {
41
+ await onDrizzleInsert([message.value]);
27
42
  }
28
- else if (p.type === 'update') {
29
- await onDrizzleUpdate(params.collection.getKeyFromItem(p.value), p.value);
43
+ else if (message.type === 'update') {
44
+ await onDrizzleUpdate(params.collection.getKeyFromItem(message.value), message.value);
30
45
  }
31
- else if (p.type === 'delete') {
32
- await onDrizzleDelete([params.collection.getKeyFromItem(p.value)]);
46
+ else if (message.type === 'delete') {
47
+ const key = 'key' in message ? message.key : params.collection.getKeyFromItem(message.value);
48
+ await onDrizzleDelete([key]);
33
49
  }
34
- params.write(p);
50
+ params.write(message);
35
51
  }
36
52
  finally {
37
53
  params.commit();
@@ -45,7 +61,12 @@ export function drizzleCollectionOptions({ startSync = true, ...config }) {
45
61
  const { begin, write, commit } = await syncParams;
46
62
  begin();
47
63
  mutations.forEach((m) => {
48
- write({ type: m.type, value: m.modified });
64
+ if (m.type === 'delete') {
65
+ write({ type: 'delete', key: m.key });
66
+ }
67
+ else {
68
+ write({ type: m.type, value: m.modified });
69
+ }
49
70
  });
50
71
  commit();
51
72
  }
package/dist/index.d.ts CHANGED
@@ -1 +1,2 @@
1
1
  export * from './drizzle';
2
+ export * from './sql';
package/dist/index.js CHANGED
@@ -1 +1,2 @@
1
1
  export * from './drizzle';
2
+ export * from './sql';
package/dist/sql.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ import type { PGlite } from '@electric-sql/pglite';
2
+ import type { StandardSchemaV1 } from '@standard-schema/spec';
3
+ import type { CollectionConfig, DeleteMutationFnParams, InsertMutationFnParams, SyncConfig, UpdateMutationFnParams } from '@tanstack/db';
4
+ type Output<T extends StandardSchemaV1> = StandardSchemaV1.InferOutput<T>;
5
+ type SyncParams<ItemType extends Record<string, unknown>> = Parameters<SyncConfig<ItemType, string>['sync']>[0];
6
+ export declare function sqlCollectionOptions<Schema extends StandardSchemaV1<Record<string, unknown>>>({ startSync, ...config }: {
7
+ db: PGlite;
8
+ tableName: string;
9
+ primaryKeyColumn: Extract<keyof Output<Schema>, string>;
10
+ schema: Schema;
11
+ getKey?: (row: Output<Schema>) => string;
12
+ onInsert?: (params: InsertMutationFnParams<Output<Schema>, string>) => Promise<void>;
13
+ onUpdate?: (params: UpdateMutationFnParams<Output<Schema>, string>) => Promise<void>;
14
+ onDelete?: (params: DeleteMutationFnParams<Output<Schema>, string>) => Promise<void>;
15
+ startSync?: boolean;
16
+ prepare?: () => Promise<unknown> | unknown;
17
+ sync?: (params: Pick<SyncParams<Output<Schema>>, 'write' | 'collection'>) => Promise<void>;
18
+ }): CollectionConfig<Output<Schema>, string, Schema, {
19
+ runSync: () => Promise<void>;
20
+ }> & {
21
+ schema: Schema;
22
+ };
23
+ export {};
package/dist/sql.js ADDED
@@ -0,0 +1,141 @@
1
+ function quoteId(name) {
2
+ // eslint-disable-next-line e18e/prefer-static-regex
3
+ return `"${String(name).replace(/"/g, '""')}"`;
4
+ }
5
+ export function sqlCollectionOptions({ startSync = true, ...config }) {
6
+ const table = quoteId(config.tableName);
7
+ const primaryKey = quoteId(config.primaryKeyColumn);
8
+ const getKey = config.getKey ?? ((row) => String(row[config.primaryKeyColumn]));
9
+ const { promise: syncParams, resolve: resolveSyncParams } = Promise.withResolvers();
10
+ async function runSelect(client) {
11
+ const result = await client.query(`SELECT * FROM ${table}`);
12
+ return (result.rows ?? []);
13
+ }
14
+ async function runInsert(client, rows) {
15
+ for (const row of rows) {
16
+ const cols = Object.keys(row).filter(k => row[k] !== undefined);
17
+ if (cols.length === 0)
18
+ continue;
19
+ const columns = cols.map(quoteId).join(', ');
20
+ const placeholders = cols.map((_, i) => `$${i + 1}`).join(', ');
21
+ const values = cols.map(c => row[c]);
22
+ await client.query(`INSERT INTO ${table} (${columns}) VALUES (${placeholders})`, values);
23
+ }
24
+ }
25
+ async function runUpdate(client, id, changes) {
26
+ const entries = Object.entries(changes).filter(([, v]) => v !== undefined);
27
+ if (entries.length === 0)
28
+ return;
29
+ const setClause = entries.map(([k], i) => `${quoteId(k)} = $${i + 1}`).join(', ');
30
+ const params = [...entries.map(([, v]) => v), id];
31
+ await client.query(`UPDATE ${table} SET ${setClause} WHERE ${primaryKey} = $${params.length}`, params);
32
+ }
33
+ async function runDelete(client, ids) {
34
+ if (ids.length === 0)
35
+ return;
36
+ await client.query(`DELETE FROM ${table} WHERE ${primaryKey} = ANY($1)`, [ids]);
37
+ }
38
+ const getSyncParams = async () => {
39
+ const params = await syncParams;
40
+ return {
41
+ write: async (p) => {
42
+ params.begin();
43
+ try {
44
+ if (p.type === 'insert') {
45
+ await runInsert(config.db, [p.value]);
46
+ }
47
+ else if (p.type === 'update') {
48
+ await runUpdate(config.db, params.collection.getKeyFromItem(p.value), p.value);
49
+ }
50
+ else if (p.type === 'delete') {
51
+ const key = 'key' in p ? p.key : params.collection.getKeyFromItem(p.value);
52
+ await runDelete(config.db, [key]);
53
+ }
54
+ params.write(p);
55
+ }
56
+ finally {
57
+ params.commit();
58
+ }
59
+ },
60
+ collection: params.collection,
61
+ };
62
+ };
63
+ async function runMutations(mutations) {
64
+ const { begin, write, commit } = await syncParams;
65
+ begin();
66
+ mutations.forEach((m) => {
67
+ if (m.type === 'delete') {
68
+ write({ type: 'delete', key: m.key });
69
+ }
70
+ else {
71
+ write({ type: m.type, value: m.modified });
72
+ }
73
+ });
74
+ commit();
75
+ }
76
+ return {
77
+ startSync,
78
+ sync: {
79
+ sync: (params) => {
80
+ resolveSyncParams(params);
81
+ (async () => {
82
+ try {
83
+ await config.prepare?.();
84
+ params.begin();
85
+ const rows = await runSelect(config.db);
86
+ rows.forEach((row) => {
87
+ params.write({ type: 'insert', value: row });
88
+ });
89
+ params.commit();
90
+ if (config.sync && startSync) {
91
+ await config.sync(await getSyncParams());
92
+ }
93
+ }
94
+ finally {
95
+ params.markReady();
96
+ }
97
+ })();
98
+ },
99
+ },
100
+ gcTime: 0,
101
+ schema: config.schema,
102
+ getKey,
103
+ onInsert: async (params) => {
104
+ await config.db.transaction(async (tx) => {
105
+ await runInsert(tx, params.transaction.mutations.map(m => m.modified));
106
+ if (config.onInsert) {
107
+ await config.onInsert(params);
108
+ }
109
+ });
110
+ await runMutations(params.transaction.mutations);
111
+ },
112
+ onUpdate: async (params) => {
113
+ await config.db.transaction(async (tx) => {
114
+ await Promise.all(params.transaction.mutations.map(m => runUpdate(tx, m.key, m.changes)));
115
+ if (config.onUpdate) {
116
+ await config.onUpdate(params);
117
+ }
118
+ });
119
+ await runMutations(params.transaction.mutations);
120
+ },
121
+ onDelete: async (params) => {
122
+ await config.db.transaction(async (tx) => {
123
+ await runDelete(tx, params.transaction.mutations.map(m => m.key));
124
+ if (config.onDelete) {
125
+ await config.onDelete(params);
126
+ }
127
+ });
128
+ await runMutations(params.transaction.mutations);
129
+ },
130
+ utils: {
131
+ runSync: async () => {
132
+ if (!config.sync) {
133
+ throw new Error('Sync is not defined');
134
+ }
135
+ const params = await getSyncParams();
136
+ await params.collection.stateWhenReady();
137
+ await config.sync(params);
138
+ },
139
+ },
140
+ };
141
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tanstack-db-pglite",
3
- "version": "1.0.5",
4
- "packageManager": "pnpm@10.22.0",
3
+ "version": "1.1.0",
4
+ "packageManager": "pnpm@10.32.1",
5
5
  "description": "",
6
6
  "author": "Valerii Strilets",
7
7
  "license": "MIT",
@@ -25,19 +25,28 @@
25
25
  "prepublishOnly": "pnpm build",
26
26
  "build": "tsc",
27
27
  "lint": "eslint .",
28
- "lint:fix": "eslint . --fix"
28
+ "lint:fix": "eslint . --fix",
29
+ "update": "taze -r -I major"
29
30
  },
30
31
  "peerDependencies": {
32
+ "@electric-sql/pglite": ">=0.3.0",
31
33
  "@tanstack/db": ">=0.5.0",
32
- "drizzle-orm": ">=0.44.0"
34
+ "drizzle-orm": ">=0.45.0"
35
+ },
36
+ "peerDependenciesMeta": {
37
+ "drizzle-orm": {
38
+ "optional": true
39
+ }
33
40
  },
34
41
  "dependencies": {
35
42
  "drizzle-zod": "^0.8.3"
36
43
  },
37
44
  "devDependencies": {
38
- "@antfu/eslint-config": "^6.2.0",
39
- "eslint": "^9.39.1",
45
+ "@antfu/eslint-config": "^7.7.2",
46
+ "@standard-schema/spec": "^1.1.0",
47
+ "eslint": "^10.0.3",
40
48
  "jiti": "^2.6.1",
49
+ "taze": "^19.10.0",
41
50
  "typescript": "^5.9.3"
42
51
  }
43
52
  }
@@ -1,20 +0,0 @@
1
- import type { CollectionConfig, DeleteMutationFnParams, InsertMutationFnParams, SyncConfig, UpdateMutationFnParams } from '@tanstack/db';
2
- import type { IndexColumn, PgTable } from 'drizzle-orm/pg-core';
3
- import type { PgliteDatabase } from 'drizzle-orm/pglite';
4
- export declare function drizzleCollectionOptions<Table extends PgTable>({ startSync, ...config }: {
5
- db: PgliteDatabase<any>;
6
- table: Table;
7
- primaryColumn: IndexColumn;
8
- onInsert?: (params: InsertMutationFnParams<Table['$inferSelect'], string>) => Promise<void>;
9
- onUpdate?: (params: UpdateMutationFnParams<Table['$inferSelect'], string>) => Promise<void>;
10
- onDelete?: (params: DeleteMutationFnParams<Table['$inferSelect'], string>) => Promise<void>;
11
- startSync?: boolean;
12
- sync: {
13
- prepare?: () => Promise<any> | any;
14
- sync: (params: Pick<Parameters<SyncConfig<Table['$inferSelect'], string>['sync']>[0], 'write' | 'collection'>) => Promise<void>;
15
- };
16
- }): CollectionConfig<Table['$inferSelect'], string> & {
17
- utils: {
18
- runSync: () => Promise<void>;
19
- };
20
- };
@@ -1,106 +0,0 @@
1
- import { eq, inArray } from 'drizzle-orm';
2
- import { createSelectSchema } from 'drizzle-zod';
3
- export function drizzleCollectionOptions({ startSync = true, ...config }) {
4
- // Sync params can be null while running PGLite migrations
5
- const { promise: syncParams, resolve: resolveSyncParams } = Promise.withResolvers();
6
- async function runMutations(mutations) {
7
- const { begin, write, commit } = await syncParams;
8
- begin();
9
- mutations.forEach((m) => {
10
- write({ type: m.type, value: m.modified });
11
- });
12
- commit();
13
- }
14
- async function onDrizzleInsert(data) {
15
- // @ts-expect-error drizzle types
16
- await config.db.insert(config.table).values(data);
17
- }
18
- async function onDrizzleUpdate(id, changes) {
19
- await config.db
20
- .update(config.table)
21
- .set(changes)
22
- .where(eq(config.primaryColumn, id));
23
- }
24
- async function onDrizzleDelete(ids) {
25
- await config.db
26
- .delete(config.table)
27
- .where(inArray(config.primaryColumn, ids));
28
- }
29
- const getSyncParams = async () => {
30
- const params = await syncParams;
31
- return {
32
- write: async (p) => {
33
- params.begin();
34
- try {
35
- if (p.type === 'insert') {
36
- await onDrizzleInsert([p.value]);
37
- }
38
- else if (p.type === 'update') {
39
- await onDrizzleUpdate(params.collection.getKeyFromItem(p.value), p.value);
40
- }
41
- else if (p.type === 'delete') {
42
- await onDrizzleDelete([params.collection.getKeyFromItem(p.value)]);
43
- }
44
- params.write(p);
45
- }
46
- finally {
47
- params.commit();
48
- }
49
- },
50
- collection: params.collection,
51
- };
52
- };
53
- return {
54
- startSync: true,
55
- sync: {
56
- sync: async (params) => {
57
- try {
58
- resolveSyncParams(params);
59
- await config.sync.prepare?.();
60
- params.begin();
61
- // @ts-expect-error drizzle types
62
- const dbs = await config.db.select().from(config.table);
63
- dbs.forEach((db) => {
64
- params.write({ type: 'insert', value: db });
65
- });
66
- params.commit();
67
- if (config.sync && startSync) {
68
- await config.sync.sync(await getSyncParams());
69
- }
70
- }
71
- finally {
72
- params.markReady();
73
- }
74
- },
75
- },
76
- gcTime: 0,
77
- schema: createSelectSchema(config.table),
78
- getKey: t => t[config.primaryColumn.name],
79
- onDelete: async (params) => {
80
- await onDrizzleDelete(params.transaction.mutations.map(m => m.key));
81
- const result = await config.onDelete?.(params);
82
- await runMutations(params.transaction.mutations);
83
- return result;
84
- },
85
- onInsert: async (params) => {
86
- await onDrizzleInsert(params.transaction.mutations.map(m => m.modified));
87
- const result = await config.onInsert?.(params);
88
- await runMutations(params.transaction.mutations);
89
- return result;
90
- },
91
- onUpdate: async (params) => {
92
- await Promise.all(params.transaction.mutations.map(m => onDrizzleUpdate(m.key, m.changes)));
93
- const result = await config.onUpdate?.(params);
94
- await runMutations(params.transaction.mutations);
95
- return result;
96
- },
97
- utils: {
98
- runSync: async () => {
99
- const params = await getSyncParams();
100
- // To wait the first sync
101
- await params.collection.stateWhenReady();
102
- await config.sync.sync(params);
103
- },
104
- },
105
- };
106
- }