@korajs/tauri 0.3.1
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/index.cjs +254 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +136 -0
- package/dist/index.d.ts +136 -0
- package/dist/index.js +215 -0
- package/dist/index.js.map +1 -0
- package/package.json +53 -0
- package/plugin/Cargo.toml +19 -0
- package/plugin/build.rs +5 -0
- package/plugin/permissions/default.toml +11 -0
- package/plugin/src/commands.rs +244 -0
- package/plugin/src/error.rs +27 -0
- package/plugin/src/lib.rs +56 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
TauriAdapterError: () => TauriAdapterError,
|
|
34
|
+
TauriSqliteAdapter: () => TauriSqliteAdapter,
|
|
35
|
+
TauriStoreNotOpenError: () => TauriStoreNotOpenError
|
|
36
|
+
});
|
|
37
|
+
module.exports = __toCommonJS(index_exports);
|
|
38
|
+
|
|
39
|
+
// src/tauri-sqlite-adapter.ts
|
|
40
|
+
var import_core = require("@korajs/core");
|
|
41
|
+
var TauriAdapterError = class extends Error {
|
|
42
|
+
code;
|
|
43
|
+
context;
|
|
44
|
+
constructor(message, context) {
|
|
45
|
+
super(message);
|
|
46
|
+
this.name = "TauriAdapterError";
|
|
47
|
+
this.code = "TAURI_ADAPTER_ERROR";
|
|
48
|
+
this.context = context;
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
var TauriStoreNotOpenError = class extends Error {
|
|
52
|
+
code;
|
|
53
|
+
constructor() {
|
|
54
|
+
super("Store is not open. Call adapter.open() before performing operations.");
|
|
55
|
+
this.name = "TauriStoreNotOpenError";
|
|
56
|
+
this.code = "STORE_NOT_OPEN";
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
var AsyncMutex = class {
|
|
60
|
+
queue = [];
|
|
61
|
+
locked = false;
|
|
62
|
+
async acquire() {
|
|
63
|
+
if (!this.locked) {
|
|
64
|
+
this.locked = true;
|
|
65
|
+
return () => this.release();
|
|
66
|
+
}
|
|
67
|
+
return new Promise((resolve) => {
|
|
68
|
+
this.queue.push(() => {
|
|
69
|
+
resolve(() => this.release());
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
release() {
|
|
74
|
+
const next = this.queue.shift();
|
|
75
|
+
if (next) {
|
|
76
|
+
next();
|
|
77
|
+
} else {
|
|
78
|
+
this.locked = false;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
async function resolveDefaultInvoke() {
|
|
83
|
+
try {
|
|
84
|
+
const { invoke } = await import("@tauri-apps/api/core");
|
|
85
|
+
return invoke;
|
|
86
|
+
} catch {
|
|
87
|
+
throw new TauriAdapterError(
|
|
88
|
+
"Failed to import @tauri-apps/api/core. Ensure @tauri-apps/api is installed and you are running inside a Tauri application."
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
var PLUGIN_PREFIX = "plugin:kora-sqlite|";
|
|
93
|
+
var TauriSqliteAdapter = class {
|
|
94
|
+
opened = false;
|
|
95
|
+
invoker;
|
|
96
|
+
dbPath;
|
|
97
|
+
txMutex = new AsyncMutex();
|
|
98
|
+
inTransaction = false;
|
|
99
|
+
constructor(options) {
|
|
100
|
+
this.dbPath = options?.path ?? "kora.db";
|
|
101
|
+
this.invoker = options?.invoke ?? null;
|
|
102
|
+
}
|
|
103
|
+
async getInvoke() {
|
|
104
|
+
if (!this.invoker) {
|
|
105
|
+
this.invoker = await resolveDefaultInvoke();
|
|
106
|
+
}
|
|
107
|
+
return this.invoker;
|
|
108
|
+
}
|
|
109
|
+
async invoke(cmd, args) {
|
|
110
|
+
const invokeFn = await this.getInvoke();
|
|
111
|
+
return invokeFn(`${PLUGIN_PREFIX}${cmd}`, args);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Open or create the database. Generates DDL from the schema and sends it
|
|
115
|
+
* to the Rust plugin for execution. The plugin configures WAL mode,
|
|
116
|
+
* foreign keys, and other pragmas before running the DDL.
|
|
117
|
+
*/
|
|
118
|
+
async open(schema) {
|
|
119
|
+
const statements = (0, import_core.generateFullDDL)(schema);
|
|
120
|
+
await this.invoke("open", { path: this.dbPath, statements });
|
|
121
|
+
this.opened = true;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Close the database and release resources.
|
|
125
|
+
*/
|
|
126
|
+
async close() {
|
|
127
|
+
if (this.opened) {
|
|
128
|
+
await this.invoke("close", { path: this.dbPath });
|
|
129
|
+
this.opened = false;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Execute a write query (INSERT, UPDATE, DELETE).
|
|
134
|
+
*/
|
|
135
|
+
async execute(sql, params) {
|
|
136
|
+
this.ensureOpen();
|
|
137
|
+
try {
|
|
138
|
+
await this.invoke("execute", {
|
|
139
|
+
path: this.dbPath,
|
|
140
|
+
sql,
|
|
141
|
+
params: params ?? []
|
|
142
|
+
});
|
|
143
|
+
} catch (error) {
|
|
144
|
+
throw new TauriAdapterError(`Execute failed: ${error.message}`, {
|
|
145
|
+
sql,
|
|
146
|
+
params
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Execute a read query (SELECT).
|
|
152
|
+
*/
|
|
153
|
+
async query(sql, params) {
|
|
154
|
+
this.ensureOpen();
|
|
155
|
+
try {
|
|
156
|
+
return await this.invoke("query", {
|
|
157
|
+
path: this.dbPath,
|
|
158
|
+
sql,
|
|
159
|
+
params: params ?? []
|
|
160
|
+
});
|
|
161
|
+
} catch (error) {
|
|
162
|
+
throw new TauriAdapterError(`Query failed: ${error.message}`, {
|
|
163
|
+
sql,
|
|
164
|
+
params
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Execute multiple operations atomically within a transaction.
|
|
170
|
+
*
|
|
171
|
+
* Uses a mutex to prevent interleaving of concurrent transactions.
|
|
172
|
+
* The transaction is committed on success or rolled back on error.
|
|
173
|
+
*/
|
|
174
|
+
async transaction(fn) {
|
|
175
|
+
this.ensureOpen();
|
|
176
|
+
const release = await this.txMutex.acquire();
|
|
177
|
+
try {
|
|
178
|
+
this.inTransaction = true;
|
|
179
|
+
await this.invoke("execute", { path: this.dbPath, sql: "BEGIN", params: [] });
|
|
180
|
+
try {
|
|
181
|
+
const tx = {
|
|
182
|
+
execute: async (sql, params) => {
|
|
183
|
+
try {
|
|
184
|
+
await this.invoke("execute", {
|
|
185
|
+
path: this.dbPath,
|
|
186
|
+
sql,
|
|
187
|
+
params: params ?? []
|
|
188
|
+
});
|
|
189
|
+
} catch (error) {
|
|
190
|
+
throw new TauriAdapterError(
|
|
191
|
+
`Transaction execute failed: ${error.message}`,
|
|
192
|
+
{ sql, params }
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
},
|
|
196
|
+
query: async (sql, params) => {
|
|
197
|
+
try {
|
|
198
|
+
return await this.invoke("query", {
|
|
199
|
+
path: this.dbPath,
|
|
200
|
+
sql,
|
|
201
|
+
params: params ?? []
|
|
202
|
+
});
|
|
203
|
+
} catch (error) {
|
|
204
|
+
throw new TauriAdapterError(
|
|
205
|
+
`Transaction query failed: ${error.message}`,
|
|
206
|
+
{ sql, params }
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
await fn(tx);
|
|
212
|
+
await this.invoke("execute", { path: this.dbPath, sql: "COMMIT", params: [] });
|
|
213
|
+
} catch (error) {
|
|
214
|
+
try {
|
|
215
|
+
await this.invoke("execute", { path: this.dbPath, sql: "ROLLBACK", params: [] });
|
|
216
|
+
} catch {
|
|
217
|
+
}
|
|
218
|
+
throw error;
|
|
219
|
+
}
|
|
220
|
+
} finally {
|
|
221
|
+
this.inTransaction = false;
|
|
222
|
+
release();
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Apply a schema migration within a transaction.
|
|
227
|
+
*/
|
|
228
|
+
async migrate(from, to, migration) {
|
|
229
|
+
this.ensureOpen();
|
|
230
|
+
try {
|
|
231
|
+
await this.invoke("migrate", {
|
|
232
|
+
path: this.dbPath,
|
|
233
|
+
statements: migration.statements
|
|
234
|
+
});
|
|
235
|
+
} catch (error) {
|
|
236
|
+
throw new TauriAdapterError(
|
|
237
|
+
`Migration from v${from} to v${to} failed: ${error.message}`,
|
|
238
|
+
{ from, to }
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
ensureOpen() {
|
|
243
|
+
if (!this.opened) {
|
|
244
|
+
throw new TauriStoreNotOpenError();
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
249
|
+
0 && (module.exports = {
|
|
250
|
+
TauriAdapterError,
|
|
251
|
+
TauriSqliteAdapter,
|
|
252
|
+
TauriStoreNotOpenError
|
|
253
|
+
});
|
|
254
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/tauri-sqlite-adapter.ts"],"sourcesContent":["export {\n\tTauriSqliteAdapter,\n\tTauriAdapterError,\n\tTauriStoreNotOpenError,\n\ttype TauriSqliteOptions,\n\ttype InvokeFn,\n\ttype StorageAdapter,\n\ttype Transaction,\n\ttype MigrationPlan,\n} from './tauri-sqlite-adapter'\n","import { generateFullDDL } from '@korajs/core'\nimport type { SchemaDefinition } from '@korajs/core'\n\n/**\n * Transaction interface for executing multiple operations atomically.\n * Mirrors @korajs/store's Transaction type to avoid a runtime dependency.\n */\nexport interface Transaction {\n\texecute(sql: string, params?: unknown[]): Promise<void>\n\tquery<T>(sql: string, params?: unknown[]): Promise<T[]>\n}\n\n/**\n * Migration plan containing SQL statements and optional data transforms.\n * Mirrors @korajs/store's MigrationPlan type.\n */\nexport interface MigrationPlan {\n\tstatements: string[]\n\ttransforms?: Array<(row: Record<string, unknown>) => Record<string, unknown>>\n}\n\n/**\n * Storage adapter interface. Mirrors @korajs/store's StorageAdapter.\n * Redeclared here to avoid a runtime dependency on @korajs/store.\n */\nexport interface StorageAdapter {\n\topen(schema: SchemaDefinition): Promise<void>\n\tclose(): Promise<void>\n\texecute(sql: string, params?: unknown[]): Promise<void>\n\tquery<T>(sql: string, params?: unknown[]): Promise<T[]>\n\ttransaction(fn: (tx: Transaction) => Promise<void>): Promise<void>\n\tmigrate(from: number, to: number, migration: MigrationPlan): Promise<void>\n}\n\n/**\n * Function signature for Tauri's invoke IPC call.\n * Matches `invoke` from `@tauri-apps/api/core`.\n */\nexport type InvokeFn = <T>(cmd: string, args?: Record<string, unknown>) => Promise<T>\n\n/**\n * Configuration options for the Tauri SQLite adapter.\n */\nexport interface TauriSqliteOptions {\n\t/**\n\t * Database file path relative to the app's data directory.\n\t * Defaults to 'kora.db'.\n\t */\n\tpath?: string\n\n\t/**\n\t * Custom invoke function. Defaults to Tauri's `invoke` from `@tauri-apps/api/core`.\n\t * Useful for testing — inject a mock invoke to test without a Tauri runtime.\n\t */\n\tinvoke?: InvokeFn\n}\n\n/**\n * Thrown when a storage adapter operation fails in the Tauri plugin.\n */\nexport class TauriAdapterError extends Error {\n\tpublic readonly code: string\n\tpublic readonly context?: Record<string, unknown>\n\n\tconstructor(message: string, context?: Record<string, unknown>) {\n\t\tsuper(message)\n\t\tthis.name = 'TauriAdapterError'\n\t\tthis.code = 'TAURI_ADAPTER_ERROR'\n\t\tthis.context = context\n\t}\n}\n\n/**\n * Thrown when an operation is attempted on an adapter that has not been opened.\n */\nexport class TauriStoreNotOpenError extends Error {\n\tpublic readonly code: string\n\n\tconstructor() {\n\t\tsuper('Store is not open. Call adapter.open() before performing operations.')\n\t\tthis.name = 'TauriStoreNotOpenError'\n\t\tthis.code = 'STORE_NOT_OPEN'\n\t}\n}\n\n// Mutex for serializing transactions over async IPC\nclass AsyncMutex {\n\tprivate queue: Array<() => void> = []\n\tprivate locked = false\n\n\tasync acquire(): Promise<() => void> {\n\t\tif (!this.locked) {\n\t\t\tthis.locked = true\n\t\t\treturn () => this.release()\n\t\t}\n\t\treturn new Promise<() => void>((resolve) => {\n\t\t\tthis.queue.push(() => {\n\t\t\t\tresolve(() => this.release())\n\t\t\t})\n\t\t})\n\t}\n\n\tprivate release(): void {\n\t\tconst next = this.queue.shift()\n\t\tif (next) {\n\t\t\tnext()\n\t\t} else {\n\t\t\tthis.locked = false\n\t\t}\n\t}\n}\n\n/**\n * Resolves the default Tauri invoke function by dynamically importing `@tauri-apps/api/core`.\n * Returns null if not in a Tauri environment.\n */\nasync function resolveDefaultInvoke(): Promise<InvokeFn> {\n\ttry {\n\t\tconst { invoke } = await import('@tauri-apps/api/core')\n\t\treturn invoke as InvokeFn\n\t} catch {\n\t\tthrow new TauriAdapterError(\n\t\t\t'Failed to import @tauri-apps/api/core. Ensure @tauri-apps/api is installed and you are running inside a Tauri application.',\n\t\t)\n\t}\n}\n\nconst PLUGIN_PREFIX = 'plugin:kora-sqlite|'\n\n/**\n * Storage adapter backed by native SQLite via a Tauri plugin.\n *\n * Uses Tauri IPC to communicate with the `tauri-plugin-kora` Rust plugin,\n * which provides native SQLite access with WAL mode, foreign keys, and\n * proper connection management — zero WASM overhead.\n *\n * @example\n * ```typescript\n * import { TauriSqliteAdapter } from '@korajs/tauri'\n *\n * const adapter = new TauriSqliteAdapter({ path: 'my-app.db' })\n * ```\n *\n * @example\n * ```typescript\n * // With createApp (auto-detected in Tauri environments)\n * import { createApp, defineSchema, t } from 'korajs'\n *\n * const app = createApp({\n * schema: defineSchema({\n * version: 1,\n * collections: {\n * todos: { fields: { title: t.string(), completed: t.boolean().default(false) } }\n * }\n * })\n * })\n * ```\n */\nexport class TauriSqliteAdapter implements StorageAdapter {\n\tprivate opened = false\n\tprivate invoker: InvokeFn | null\n\tprivate readonly dbPath: string\n\tprivate readonly txMutex = new AsyncMutex()\n\tprivate inTransaction = false\n\n\tconstructor(options?: TauriSqliteOptions) {\n\t\tthis.dbPath = options?.path ?? 'kora.db'\n\t\tthis.invoker = options?.invoke ?? null\n\t}\n\n\tprivate async getInvoke(): Promise<InvokeFn> {\n\t\tif (!this.invoker) {\n\t\t\tthis.invoker = await resolveDefaultInvoke()\n\t\t}\n\t\treturn this.invoker\n\t}\n\n\tprivate async invoke<T>(cmd: string, args?: Record<string, unknown>): Promise<T> {\n\t\tconst invokeFn = await this.getInvoke()\n\t\treturn invokeFn<T>(`${PLUGIN_PREFIX}${cmd}`, args)\n\t}\n\n\t/**\n\t * Open or create the database. Generates DDL from the schema and sends it\n\t * to the Rust plugin for execution. The plugin configures WAL mode,\n\t * foreign keys, and other pragmas before running the DDL.\n\t */\n\tasync open(schema: SchemaDefinition): Promise<void> {\n\t\tconst statements = generateFullDDL(schema)\n\t\tawait this.invoke('open', { path: this.dbPath, statements })\n\t\tthis.opened = true\n\t}\n\n\t/**\n\t * Close the database and release resources.\n\t */\n\tasync close(): Promise<void> {\n\t\tif (this.opened) {\n\t\t\tawait this.invoke('close', { path: this.dbPath })\n\t\t\tthis.opened = false\n\t\t}\n\t}\n\n\t/**\n\t * Execute a write query (INSERT, UPDATE, DELETE).\n\t */\n\tasync execute(sql: string, params?: unknown[]): Promise<void> {\n\t\tthis.ensureOpen()\n\t\ttry {\n\t\t\tawait this.invoke('execute', {\n\t\t\t\tpath: this.dbPath,\n\t\t\t\tsql,\n\t\t\t\tparams: params ?? [],\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthrow new TauriAdapterError(`Execute failed: ${(error as Error).message}`, {\n\t\t\t\tsql,\n\t\t\t\tparams,\n\t\t\t})\n\t\t}\n\t}\n\n\t/**\n\t * Execute a read query (SELECT).\n\t */\n\tasync query<T>(sql: string, params?: unknown[]): Promise<T[]> {\n\t\tthis.ensureOpen()\n\t\ttry {\n\t\t\treturn await this.invoke<T[]>('query', {\n\t\t\t\tpath: this.dbPath,\n\t\t\t\tsql,\n\t\t\t\tparams: params ?? [],\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthrow new TauriAdapterError(`Query failed: ${(error as Error).message}`, {\n\t\t\t\tsql,\n\t\t\t\tparams,\n\t\t\t})\n\t\t}\n\t}\n\n\t/**\n\t * Execute multiple operations atomically within a transaction.\n\t *\n\t * Uses a mutex to prevent interleaving of concurrent transactions.\n\t * The transaction is committed on success or rolled back on error.\n\t */\n\tasync transaction(fn: (tx: Transaction) => Promise<void>): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tconst release = await this.txMutex.acquire()\n\t\ttry {\n\t\t\tthis.inTransaction = true\n\t\t\tawait this.invoke('execute', { path: this.dbPath, sql: 'BEGIN', params: [] })\n\t\t\ttry {\n\t\t\t\tconst tx: Transaction = {\n\t\t\t\t\texecute: async (sql: string, params?: unknown[]): Promise<void> => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait this.invoke('execute', {\n\t\t\t\t\t\t\t\tpath: this.dbPath,\n\t\t\t\t\t\t\t\tsql,\n\t\t\t\t\t\t\t\tparams: params ?? [],\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tthrow new TauriAdapterError(\n\t\t\t\t\t\t\t\t`Transaction execute failed: ${(error as Error).message}`,\n\t\t\t\t\t\t\t\t{ sql, params },\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tquery: async <T>(sql: string, params?: unknown[]): Promise<T[]> => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn await this.invoke<T[]>('query', {\n\t\t\t\t\t\t\t\tpath: this.dbPath,\n\t\t\t\t\t\t\t\tsql,\n\t\t\t\t\t\t\t\tparams: params ?? [],\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tthrow new TauriAdapterError(\n\t\t\t\t\t\t\t\t`Transaction query failed: ${(error as Error).message}`,\n\t\t\t\t\t\t\t\t{ sql, params },\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tawait fn(tx)\n\t\t\t\tawait this.invoke('execute', { path: this.dbPath, sql: 'COMMIT', params: [] })\n\t\t\t} catch (error) {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.invoke('execute', { path: this.dbPath, sql: 'ROLLBACK', params: [] })\n\t\t\t\t} catch {\n\t\t\t\t\t// Rollback failed — connection may be in a bad state, but we still throw the original error\n\t\t\t\t}\n\t\t\t\tthrow error\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.inTransaction = false\n\t\t\trelease()\n\t\t}\n\t}\n\n\t/**\n\t * Apply a schema migration within a transaction.\n\t */\n\tasync migrate(from: number, to: number, migration: MigrationPlan): Promise<void> {\n\t\tthis.ensureOpen()\n\t\ttry {\n\t\t\tawait this.invoke('migrate', {\n\t\t\t\tpath: this.dbPath,\n\t\t\t\tstatements: migration.statements,\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthrow new TauriAdapterError(\n\t\t\t\t`Migration from v${from} to v${to} failed: ${(error as Error).message}`,\n\t\t\t\t{ from, to },\n\t\t\t)\n\t\t}\n\t}\n\n\tprivate ensureOpen(): void {\n\t\tif (!this.opened) {\n\t\t\tthrow new TauriStoreNotOpenError()\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,kBAAgC;AA4DzB,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAC5B;AAAA,EACA;AAAA,EAEhB,YAAY,SAAiB,SAAmC;AAC/D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,EAChB;AACD;AAKO,IAAM,yBAAN,cAAqC,MAAM;AAAA,EACjC;AAAA,EAEhB,cAAc;AACb,UAAM,sEAAsE;AAC5E,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACb;AACD;AAGA,IAAM,aAAN,MAAiB;AAAA,EACR,QAA2B,CAAC;AAAA,EAC5B,SAAS;AAAA,EAEjB,MAAM,UAA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E,MAAM,GAAG;AAAA,MACZ;AAAA,IACD;AAAA,EACD;AAAA,EAEQ,aAAmB;AAC1B,QAAI,CAAC,KAAK,QAAQ;AACjB,YAAM,IAAI,uBAAuB;AAAA,IAClC;AAAA,EACD;AACD;","names":[]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { SchemaDefinition } from '@korajs/core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Transaction interface for executing multiple operations atomically.
|
|
5
|
+
* Mirrors @korajs/store's Transaction type to avoid a runtime dependency.
|
|
6
|
+
*/
|
|
7
|
+
interface Transaction {
|
|
8
|
+
execute(sql: string, params?: unknown[]): Promise<void>;
|
|
9
|
+
query<T>(sql: string, params?: unknown[]): Promise<T[]>;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Migration plan containing SQL statements and optional data transforms.
|
|
13
|
+
* Mirrors @korajs/store's MigrationPlan type.
|
|
14
|
+
*/
|
|
15
|
+
interface MigrationPlan {
|
|
16
|
+
statements: string[];
|
|
17
|
+
transforms?: Array<(row: Record<string, unknown>) => Record<string, unknown>>;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Storage adapter interface. Mirrors @korajs/store's StorageAdapter.
|
|
21
|
+
* Redeclared here to avoid a runtime dependency on @korajs/store.
|
|
22
|
+
*/
|
|
23
|
+
interface StorageAdapter {
|
|
24
|
+
open(schema: SchemaDefinition): Promise<void>;
|
|
25
|
+
close(): Promise<void>;
|
|
26
|
+
execute(sql: string, params?: unknown[]): Promise<void>;
|
|
27
|
+
query<T>(sql: string, params?: unknown[]): Promise<T[]>;
|
|
28
|
+
transaction(fn: (tx: Transaction) => Promise<void>): Promise<void>;
|
|
29
|
+
migrate(from: number, to: number, migration: MigrationPlan): Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Function signature for Tauri's invoke IPC call.
|
|
33
|
+
* Matches `invoke` from `@tauri-apps/api/core`.
|
|
34
|
+
*/
|
|
35
|
+
type InvokeFn = <T>(cmd: string, args?: Record<string, unknown>) => Promise<T>;
|
|
36
|
+
/**
|
|
37
|
+
* Configuration options for the Tauri SQLite adapter.
|
|
38
|
+
*/
|
|
39
|
+
interface TauriSqliteOptions {
|
|
40
|
+
/**
|
|
41
|
+
* Database file path relative to the app's data directory.
|
|
42
|
+
* Defaults to 'kora.db'.
|
|
43
|
+
*/
|
|
44
|
+
path?: string;
|
|
45
|
+
/**
|
|
46
|
+
* Custom invoke function. Defaults to Tauri's `invoke` from `@tauri-apps/api/core`.
|
|
47
|
+
* Useful for testing — inject a mock invoke to test without a Tauri runtime.
|
|
48
|
+
*/
|
|
49
|
+
invoke?: InvokeFn;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Thrown when a storage adapter operation fails in the Tauri plugin.
|
|
53
|
+
*/
|
|
54
|
+
declare class TauriAdapterError extends Error {
|
|
55
|
+
readonly code: string;
|
|
56
|
+
readonly context?: Record<string, unknown>;
|
|
57
|
+
constructor(message: string, context?: Record<string, unknown>);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Thrown when an operation is attempted on an adapter that has not been opened.
|
|
61
|
+
*/
|
|
62
|
+
declare class TauriStoreNotOpenError extends Error {
|
|
63
|
+
readonly code: string;
|
|
64
|
+
constructor();
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Storage adapter backed by native SQLite via a Tauri plugin.
|
|
68
|
+
*
|
|
69
|
+
* Uses Tauri IPC to communicate with the `tauri-plugin-kora` Rust plugin,
|
|
70
|
+
* which provides native SQLite access with WAL mode, foreign keys, and
|
|
71
|
+
* proper connection management — zero WASM overhead.
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* ```typescript
|
|
75
|
+
* import { TauriSqliteAdapter } from '@korajs/tauri'
|
|
76
|
+
*
|
|
77
|
+
* const adapter = new TauriSqliteAdapter({ path: 'my-app.db' })
|
|
78
|
+
* ```
|
|
79
|
+
*
|
|
80
|
+
* @example
|
|
81
|
+
* ```typescript
|
|
82
|
+
* // With createApp (auto-detected in Tauri environments)
|
|
83
|
+
* import { createApp, defineSchema, t } from 'korajs'
|
|
84
|
+
*
|
|
85
|
+
* const app = createApp({
|
|
86
|
+
* schema: defineSchema({
|
|
87
|
+
* version: 1,
|
|
88
|
+
* collections: {
|
|
89
|
+
* todos: { fields: { title: t.string(), completed: t.boolean().default(false) } }
|
|
90
|
+
* }
|
|
91
|
+
* })
|
|
92
|
+
* })
|
|
93
|
+
* ```
|
|
94
|
+
*/
|
|
95
|
+
declare class TauriSqliteAdapter implements StorageAdapter {
|
|
96
|
+
private opened;
|
|
97
|
+
private invoker;
|
|
98
|
+
private readonly dbPath;
|
|
99
|
+
private readonly txMutex;
|
|
100
|
+
private inTransaction;
|
|
101
|
+
constructor(options?: TauriSqliteOptions);
|
|
102
|
+
private getInvoke;
|
|
103
|
+
private invoke;
|
|
104
|
+
/**
|
|
105
|
+
* Open or create the database. Generates DDL from the schema and sends it
|
|
106
|
+
* to the Rust plugin for execution. The plugin configures WAL mode,
|
|
107
|
+
* foreign keys, and other pragmas before running the DDL.
|
|
108
|
+
*/
|
|
109
|
+
open(schema: SchemaDefinition): Promise<void>;
|
|
110
|
+
/**
|
|
111
|
+
* Close the database and release resources.
|
|
112
|
+
*/
|
|
113
|
+
close(): Promise<void>;
|
|
114
|
+
/**
|
|
115
|
+
* Execute a write query (INSERT, UPDATE, DELETE).
|
|
116
|
+
*/
|
|
117
|
+
execute(sql: string, params?: unknown[]): Promise<void>;
|
|
118
|
+
/**
|
|
119
|
+
* Execute a read query (SELECT).
|
|
120
|
+
*/
|
|
121
|
+
query<T>(sql: string, params?: unknown[]): Promise<T[]>;
|
|
122
|
+
/**
|
|
123
|
+
* Execute multiple operations atomically within a transaction.
|
|
124
|
+
*
|
|
125
|
+
* Uses a mutex to prevent interleaving of concurrent transactions.
|
|
126
|
+
* The transaction is committed on success or rolled back on error.
|
|
127
|
+
*/
|
|
128
|
+
transaction(fn: (tx: Transaction) => Promise<void>): Promise<void>;
|
|
129
|
+
/**
|
|
130
|
+
* Apply a schema migration within a transaction.
|
|
131
|
+
*/
|
|
132
|
+
migrate(from: number, to: number, migration: MigrationPlan): Promise<void>;
|
|
133
|
+
private ensureOpen;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export { type InvokeFn, type MigrationPlan, type StorageAdapter, TauriAdapterError, TauriSqliteAdapter, type TauriSqliteOptions, TauriStoreNotOpenError, type Transaction };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { SchemaDefinition } from '@korajs/core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Transaction interface for executing multiple operations atomically.
|
|
5
|
+
* Mirrors @korajs/store's Transaction type to avoid a runtime dependency.
|
|
6
|
+
*/
|
|
7
|
+
interface Transaction {
|
|
8
|
+
execute(sql: string, params?: unknown[]): Promise<void>;
|
|
9
|
+
query<T>(sql: string, params?: unknown[]): Promise<T[]>;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Migration plan containing SQL statements and optional data transforms.
|
|
13
|
+
* Mirrors @korajs/store's MigrationPlan type.
|
|
14
|
+
*/
|
|
15
|
+
interface MigrationPlan {
|
|
16
|
+
statements: string[];
|
|
17
|
+
transforms?: Array<(row: Record<string, unknown>) => Record<string, unknown>>;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Storage adapter interface. Mirrors @korajs/store's StorageAdapter.
|
|
21
|
+
* Redeclared here to avoid a runtime dependency on @korajs/store.
|
|
22
|
+
*/
|
|
23
|
+
interface StorageAdapter {
|
|
24
|
+
open(schema: SchemaDefinition): Promise<void>;
|
|
25
|
+
close(): Promise<void>;
|
|
26
|
+
execute(sql: string, params?: unknown[]): Promise<void>;
|
|
27
|
+
query<T>(sql: string, params?: unknown[]): Promise<T[]>;
|
|
28
|
+
transaction(fn: (tx: Transaction) => Promise<void>): Promise<void>;
|
|
29
|
+
migrate(from: number, to: number, migration: MigrationPlan): Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Function signature for Tauri's invoke IPC call.
|
|
33
|
+
* Matches `invoke` from `@tauri-apps/api/core`.
|
|
34
|
+
*/
|
|
35
|
+
type InvokeFn = <T>(cmd: string, args?: Record<string, unknown>) => Promise<T>;
|
|
36
|
+
/**
|
|
37
|
+
* Configuration options for the Tauri SQLite adapter.
|
|
38
|
+
*/
|
|
39
|
+
interface TauriSqliteOptions {
|
|
40
|
+
/**
|
|
41
|
+
* Database file path relative to the app's data directory.
|
|
42
|
+
* Defaults to 'kora.db'.
|
|
43
|
+
*/
|
|
44
|
+
path?: string;
|
|
45
|
+
/**
|
|
46
|
+
* Custom invoke function. Defaults to Tauri's `invoke` from `@tauri-apps/api/core`.
|
|
47
|
+
* Useful for testing — inject a mock invoke to test without a Tauri runtime.
|
|
48
|
+
*/
|
|
49
|
+
invoke?: InvokeFn;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Thrown when a storage adapter operation fails in the Tauri plugin.
|
|
53
|
+
*/
|
|
54
|
+
declare class TauriAdapterError extends Error {
|
|
55
|
+
readonly code: string;
|
|
56
|
+
readonly context?: Record<string, unknown>;
|
|
57
|
+
constructor(message: string, context?: Record<string, unknown>);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Thrown when an operation is attempted on an adapter that has not been opened.
|
|
61
|
+
*/
|
|
62
|
+
declare class TauriStoreNotOpenError extends Error {
|
|
63
|
+
readonly code: string;
|
|
64
|
+
constructor();
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Storage adapter backed by native SQLite via a Tauri plugin.
|
|
68
|
+
*
|
|
69
|
+
* Uses Tauri IPC to communicate with the `tauri-plugin-kora` Rust plugin,
|
|
70
|
+
* which provides native SQLite access with WAL mode, foreign keys, and
|
|
71
|
+
* proper connection management — zero WASM overhead.
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* ```typescript
|
|
75
|
+
* import { TauriSqliteAdapter } from '@korajs/tauri'
|
|
76
|
+
*
|
|
77
|
+
* const adapter = new TauriSqliteAdapter({ path: 'my-app.db' })
|
|
78
|
+
* ```
|
|
79
|
+
*
|
|
80
|
+
* @example
|
|
81
|
+
* ```typescript
|
|
82
|
+
* // With createApp (auto-detected in Tauri environments)
|
|
83
|
+
* import { createApp, defineSchema, t } from 'korajs'
|
|
84
|
+
*
|
|
85
|
+
* const app = createApp({
|
|
86
|
+
* schema: defineSchema({
|
|
87
|
+
* version: 1,
|
|
88
|
+
* collections: {
|
|
89
|
+
* todos: { fields: { title: t.string(), completed: t.boolean().default(false) } }
|
|
90
|
+
* }
|
|
91
|
+
* })
|
|
92
|
+
* })
|
|
93
|
+
* ```
|
|
94
|
+
*/
|
|
95
|
+
declare class TauriSqliteAdapter implements StorageAdapter {
|
|
96
|
+
private opened;
|
|
97
|
+
private invoker;
|
|
98
|
+
private readonly dbPath;
|
|
99
|
+
private readonly txMutex;
|
|
100
|
+
private inTransaction;
|
|
101
|
+
constructor(options?: TauriSqliteOptions);
|
|
102
|
+
private getInvoke;
|
|
103
|
+
private invoke;
|
|
104
|
+
/**
|
|
105
|
+
* Open or create the database. Generates DDL from the schema and sends it
|
|
106
|
+
* to the Rust plugin for execution. The plugin configures WAL mode,
|
|
107
|
+
* foreign keys, and other pragmas before running the DDL.
|
|
108
|
+
*/
|
|
109
|
+
open(schema: SchemaDefinition): Promise<void>;
|
|
110
|
+
/**
|
|
111
|
+
* Close the database and release resources.
|
|
112
|
+
*/
|
|
113
|
+
close(): Promise<void>;
|
|
114
|
+
/**
|
|
115
|
+
* Execute a write query (INSERT, UPDATE, DELETE).
|
|
116
|
+
*/
|
|
117
|
+
execute(sql: string, params?: unknown[]): Promise<void>;
|
|
118
|
+
/**
|
|
119
|
+
* Execute a read query (SELECT).
|
|
120
|
+
*/
|
|
121
|
+
query<T>(sql: string, params?: unknown[]): Promise<T[]>;
|
|
122
|
+
/**
|
|
123
|
+
* Execute multiple operations atomically within a transaction.
|
|
124
|
+
*
|
|
125
|
+
* Uses a mutex to prevent interleaving of concurrent transactions.
|
|
126
|
+
* The transaction is committed on success or rolled back on error.
|
|
127
|
+
*/
|
|
128
|
+
transaction(fn: (tx: Transaction) => Promise<void>): Promise<void>;
|
|
129
|
+
/**
|
|
130
|
+
* Apply a schema migration within a transaction.
|
|
131
|
+
*/
|
|
132
|
+
migrate(from: number, to: number, migration: MigrationPlan): Promise<void>;
|
|
133
|
+
private ensureOpen;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export { type InvokeFn, type MigrationPlan, type StorageAdapter, TauriAdapterError, TauriSqliteAdapter, type TauriSqliteOptions, TauriStoreNotOpenError, type Transaction };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
// src/tauri-sqlite-adapter.ts
|
|
2
|
+
import { generateFullDDL } from "@korajs/core";
|
|
3
|
+
var TauriAdapterError = class extends Error {
|
|
4
|
+
code;
|
|
5
|
+
context;
|
|
6
|
+
constructor(message, context) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = "TauriAdapterError";
|
|
9
|
+
this.code = "TAURI_ADAPTER_ERROR";
|
|
10
|
+
this.context = context;
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
var TauriStoreNotOpenError = class extends Error {
|
|
14
|
+
code;
|
|
15
|
+
constructor() {
|
|
16
|
+
super("Store is not open. Call adapter.open() before performing operations.");
|
|
17
|
+
this.name = "TauriStoreNotOpenError";
|
|
18
|
+
this.code = "STORE_NOT_OPEN";
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
var AsyncMutex = class {
|
|
22
|
+
queue = [];
|
|
23
|
+
locked = false;
|
|
24
|
+
async acquire() {
|
|
25
|
+
if (!this.locked) {
|
|
26
|
+
this.locked = true;
|
|
27
|
+
return () => this.release();
|
|
28
|
+
}
|
|
29
|
+
return new Promise((resolve) => {
|
|
30
|
+
this.queue.push(() => {
|
|
31
|
+
resolve(() => this.release());
|
|
32
|
+
});
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
release() {
|
|
36
|
+
const next = this.queue.shift();
|
|
37
|
+
if (next) {
|
|
38
|
+
next();
|
|
39
|
+
} else {
|
|
40
|
+
this.locked = false;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
async function resolveDefaultInvoke() {
|
|
45
|
+
try {
|
|
46
|
+
const { invoke } = await import("@tauri-apps/api/core");
|
|
47
|
+
return invoke;
|
|
48
|
+
} catch {
|
|
49
|
+
throw new TauriAdapterError(
|
|
50
|
+
"Failed to import @tauri-apps/api/core. Ensure @tauri-apps/api is installed and you are running inside a Tauri application."
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
var PLUGIN_PREFIX = "plugin:kora-sqlite|";
|
|
55
|
+
var TauriSqliteAdapter = class {
|
|
56
|
+
opened = false;
|
|
57
|
+
invoker;
|
|
58
|
+
dbPath;
|
|
59
|
+
txMutex = new AsyncMutex();
|
|
60
|
+
inTransaction = false;
|
|
61
|
+
constructor(options) {
|
|
62
|
+
this.dbPath = options?.path ?? "kora.db";
|
|
63
|
+
this.invoker = options?.invoke ?? null;
|
|
64
|
+
}
|
|
65
|
+
async getInvoke() {
|
|
66
|
+
if (!this.invoker) {
|
|
67
|
+
this.invoker = await resolveDefaultInvoke();
|
|
68
|
+
}
|
|
69
|
+
return this.invoker;
|
|
70
|
+
}
|
|
71
|
+
async invoke(cmd, args) {
|
|
72
|
+
const invokeFn = await this.getInvoke();
|
|
73
|
+
return invokeFn(`${PLUGIN_PREFIX}${cmd}`, args);
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Open or create the database. Generates DDL from the schema and sends it
|
|
77
|
+
* to the Rust plugin for execution. The plugin configures WAL mode,
|
|
78
|
+
* foreign keys, and other pragmas before running the DDL.
|
|
79
|
+
*/
|
|
80
|
+
async open(schema) {
|
|
81
|
+
const statements = generateFullDDL(schema);
|
|
82
|
+
await this.invoke("open", { path: this.dbPath, statements });
|
|
83
|
+
this.opened = true;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Close the database and release resources.
|
|
87
|
+
*/
|
|
88
|
+
async close() {
|
|
89
|
+
if (this.opened) {
|
|
90
|
+
await this.invoke("close", { path: this.dbPath });
|
|
91
|
+
this.opened = false;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Execute a write query (INSERT, UPDATE, DELETE).
|
|
96
|
+
*/
|
|
97
|
+
async execute(sql, params) {
|
|
98
|
+
this.ensureOpen();
|
|
99
|
+
try {
|
|
100
|
+
await this.invoke("execute", {
|
|
101
|
+
path: this.dbPath,
|
|
102
|
+
sql,
|
|
103
|
+
params: params ?? []
|
|
104
|
+
});
|
|
105
|
+
} catch (error) {
|
|
106
|
+
throw new TauriAdapterError(`Execute failed: ${error.message}`, {
|
|
107
|
+
sql,
|
|
108
|
+
params
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Execute a read query (SELECT).
|
|
114
|
+
*/
|
|
115
|
+
async query(sql, params) {
|
|
116
|
+
this.ensureOpen();
|
|
117
|
+
try {
|
|
118
|
+
return await this.invoke("query", {
|
|
119
|
+
path: this.dbPath,
|
|
120
|
+
sql,
|
|
121
|
+
params: params ?? []
|
|
122
|
+
});
|
|
123
|
+
} catch (error) {
|
|
124
|
+
throw new TauriAdapterError(`Query failed: ${error.message}`, {
|
|
125
|
+
sql,
|
|
126
|
+
params
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Execute multiple operations atomically within a transaction.
|
|
132
|
+
*
|
|
133
|
+
* Uses a mutex to prevent interleaving of concurrent transactions.
|
|
134
|
+
* The transaction is committed on success or rolled back on error.
|
|
135
|
+
*/
|
|
136
|
+
async transaction(fn) {
|
|
137
|
+
this.ensureOpen();
|
|
138
|
+
const release = await this.txMutex.acquire();
|
|
139
|
+
try {
|
|
140
|
+
this.inTransaction = true;
|
|
141
|
+
await this.invoke("execute", { path: this.dbPath, sql: "BEGIN", params: [] });
|
|
142
|
+
try {
|
|
143
|
+
const tx = {
|
|
144
|
+
execute: async (sql, params) => {
|
|
145
|
+
try {
|
|
146
|
+
await this.invoke("execute", {
|
|
147
|
+
path: this.dbPath,
|
|
148
|
+
sql,
|
|
149
|
+
params: params ?? []
|
|
150
|
+
});
|
|
151
|
+
} catch (error) {
|
|
152
|
+
throw new TauriAdapterError(
|
|
153
|
+
`Transaction execute failed: ${error.message}`,
|
|
154
|
+
{ sql, params }
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
},
|
|
158
|
+
query: async (sql, params) => {
|
|
159
|
+
try {
|
|
160
|
+
return await this.invoke("query", {
|
|
161
|
+
path: this.dbPath,
|
|
162
|
+
sql,
|
|
163
|
+
params: params ?? []
|
|
164
|
+
});
|
|
165
|
+
} catch (error) {
|
|
166
|
+
throw new TauriAdapterError(
|
|
167
|
+
`Transaction query failed: ${error.message}`,
|
|
168
|
+
{ sql, params }
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
await fn(tx);
|
|
174
|
+
await this.invoke("execute", { path: this.dbPath, sql: "COMMIT", params: [] });
|
|
175
|
+
} catch (error) {
|
|
176
|
+
try {
|
|
177
|
+
await this.invoke("execute", { path: this.dbPath, sql: "ROLLBACK", params: [] });
|
|
178
|
+
} catch {
|
|
179
|
+
}
|
|
180
|
+
throw error;
|
|
181
|
+
}
|
|
182
|
+
} finally {
|
|
183
|
+
this.inTransaction = false;
|
|
184
|
+
release();
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Apply a schema migration within a transaction.
|
|
189
|
+
*/
|
|
190
|
+
async migrate(from, to, migration) {
|
|
191
|
+
this.ensureOpen();
|
|
192
|
+
try {
|
|
193
|
+
await this.invoke("migrate", {
|
|
194
|
+
path: this.dbPath,
|
|
195
|
+
statements: migration.statements
|
|
196
|
+
});
|
|
197
|
+
} catch (error) {
|
|
198
|
+
throw new TauriAdapterError(
|
|
199
|
+
`Migration from v${from} to v${to} failed: ${error.message}`,
|
|
200
|
+
{ from, to }
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
ensureOpen() {
|
|
205
|
+
if (!this.opened) {
|
|
206
|
+
throw new TauriStoreNotOpenError();
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
export {
|
|
211
|
+
TauriAdapterError,
|
|
212
|
+
TauriSqliteAdapter,
|
|
213
|
+
TauriStoreNotOpenError
|
|
214
|
+
};
|
|
215
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/tauri-sqlite-adapter.ts"],"sourcesContent":["import { generateFullDDL } from '@korajs/core'\nimport type { SchemaDefinition } from '@korajs/core'\n\n/**\n * Transaction interface for executing multiple operations atomically.\n * Mirrors @korajs/store's Transaction type to avoid a runtime dependency.\n */\nexport interface Transaction {\n\texecute(sql: string, params?: unknown[]): Promise<void>\n\tquery<T>(sql: string, params?: unknown[]): Promise<T[]>\n}\n\n/**\n * Migration plan containing SQL statements and optional data transforms.\n * Mirrors @korajs/store's MigrationPlan type.\n */\nexport interface MigrationPlan {\n\tstatements: string[]\n\ttransforms?: Array<(row: Record<string, unknown>) => Record<string, unknown>>\n}\n\n/**\n * Storage adapter interface. Mirrors @korajs/store's StorageAdapter.\n * Redeclared here to avoid a runtime dependency on @korajs/store.\n */\nexport interface StorageAdapter {\n\topen(schema: SchemaDefinition): Promise<void>\n\tclose(): Promise<void>\n\texecute(sql: string, params?: unknown[]): Promise<void>\n\tquery<T>(sql: string, params?: unknown[]): Promise<T[]>\n\ttransaction(fn: (tx: Transaction) => Promise<void>): Promise<void>\n\tmigrate(from: number, to: number, migration: MigrationPlan): Promise<void>\n}\n\n/**\n * Function signature for Tauri's invoke IPC call.\n * Matches `invoke` from `@tauri-apps/api/core`.\n */\nexport type InvokeFn = <T>(cmd: string, args?: Record<string, unknown>) => Promise<T>\n\n/**\n * Configuration options for the Tauri SQLite adapter.\n */\nexport interface TauriSqliteOptions {\n\t/**\n\t * Database file path relative to the app's data directory.\n\t * Defaults to 'kora.db'.\n\t */\n\tpath?: string\n\n\t/**\n\t * Custom invoke function. Defaults to Tauri's `invoke` from `@tauri-apps/api/core`.\n\t * Useful for testing — inject a mock invoke to test without a Tauri runtime.\n\t */\n\tinvoke?: InvokeFn\n}\n\n/**\n * Thrown when a storage adapter operation fails in the Tauri plugin.\n */\nexport class TauriAdapterError extends Error {\n\tpublic readonly code: string\n\tpublic readonly context?: Record<string, unknown>\n\n\tconstructor(message: string, context?: Record<string, unknown>) {\n\t\tsuper(message)\n\t\tthis.name = 'TauriAdapterError'\n\t\tthis.code = 'TAURI_ADAPTER_ERROR'\n\t\tthis.context = context\n\t}\n}\n\n/**\n * Thrown when an operation is attempted on an adapter that has not been opened.\n */\nexport class TauriStoreNotOpenError extends Error {\n\tpublic readonly code: string\n\n\tconstructor() {\n\t\tsuper('Store is not open. Call adapter.open() before performing operations.')\n\t\tthis.name = 'TauriStoreNotOpenError'\n\t\tthis.code = 'STORE_NOT_OPEN'\n\t}\n}\n\n// Mutex for serializing transactions over async IPC\nclass AsyncMutex {\n\tprivate queue: Array<() => void> = []\n\tprivate locked = false\n\n\tasync acquire(): Promise<() => void> {\n\t\tif (!this.locked) {\n\t\t\tthis.locked = true\n\t\t\treturn () => this.release()\n\t\t}\n\t\treturn new Promise<() => void>((resolve) => {\n\t\t\tthis.queue.push(() => {\n\t\t\t\tresolve(() => this.release())\n\t\t\t})\n\t\t})\n\t}\n\n\tprivate release(): void {\n\t\tconst next = this.queue.shift()\n\t\tif (next) {\n\t\t\tnext()\n\t\t} else {\n\t\t\tthis.locked = false\n\t\t}\n\t}\n}\n\n/**\n * Resolves the default Tauri invoke function by dynamically importing `@tauri-apps/api/core`.\n * Returns null if not in a Tauri environment.\n */\nasync function resolveDefaultInvoke(): Promise<InvokeFn> {\n\ttry {\n\t\tconst { invoke } = await import('@tauri-apps/api/core')\n\t\treturn invoke as InvokeFn\n\t} catch {\n\t\tthrow new TauriAdapterError(\n\t\t\t'Failed to import @tauri-apps/api/core. Ensure @tauri-apps/api is installed and you are running inside a Tauri application.',\n\t\t)\n\t}\n}\n\nconst PLUGIN_PREFIX = 'plugin:kora-sqlite|'\n\n/**\n * Storage adapter backed by native SQLite via a Tauri plugin.\n *\n * Uses Tauri IPC to communicate with the `tauri-plugin-kora` Rust plugin,\n * which provides native SQLite access with WAL mode, foreign keys, and\n * proper connection management — zero WASM overhead.\n *\n * @example\n * ```typescript\n * import { TauriSqliteAdapter } from '@korajs/tauri'\n *\n * const adapter = new TauriSqliteAdapter({ path: 'my-app.db' })\n * ```\n *\n * @example\n * ```typescript\n * // With createApp (auto-detected in Tauri environments)\n * import { createApp, defineSchema, t } from 'korajs'\n *\n * const app = createApp({\n * schema: defineSchema({\n * version: 1,\n * collections: {\n * todos: { fields: { title: t.string(), completed: t.boolean().default(false) } }\n * }\n * })\n * })\n * ```\n */\nexport class TauriSqliteAdapter implements StorageAdapter {\n\tprivate opened = false\n\tprivate invoker: InvokeFn | null\n\tprivate readonly dbPath: string\n\tprivate readonly txMutex = new AsyncMutex()\n\tprivate inTransaction = false\n\n\tconstructor(options?: TauriSqliteOptions) {\n\t\tthis.dbPath = options?.path ?? 'kora.db'\n\t\tthis.invoker = options?.invoke ?? null\n\t}\n\n\tprivate async getInvoke(): Promise<InvokeFn> {\n\t\tif (!this.invoker) {\n\t\t\tthis.invoker = await resolveDefaultInvoke()\n\t\t}\n\t\treturn this.invoker\n\t}\n\n\tprivate async invoke<T>(cmd: string, args?: Record<string, unknown>): Promise<T> {\n\t\tconst invokeFn = await this.getInvoke()\n\t\treturn invokeFn<T>(`${PLUGIN_PREFIX}${cmd}`, args)\n\t}\n\n\t/**\n\t * Open or create the database. Generates DDL from the schema and sends it\n\t * to the Rust plugin for execution. The plugin configures WAL mode,\n\t * foreign keys, and other pragmas before running the DDL.\n\t */\n\tasync open(schema: SchemaDefinition): Promise<void> {\n\t\tconst statements = generateFullDDL(schema)\n\t\tawait this.invoke('open', { path: this.dbPath, statements })\n\t\tthis.opened = true\n\t}\n\n\t/**\n\t * Close the database and release resources.\n\t */\n\tasync close(): Promise<void> {\n\t\tif (this.opened) {\n\t\t\tawait this.invoke('close', { path: this.dbPath })\n\t\t\tthis.opened = false\n\t\t}\n\t}\n\n\t/**\n\t * Execute a write query (INSERT, UPDATE, DELETE).\n\t */\n\tasync execute(sql: string, params?: unknown[]): Promise<void> {\n\t\tthis.ensureOpen()\n\t\ttry {\n\t\t\tawait this.invoke('execute', {\n\t\t\t\tpath: this.dbPath,\n\t\t\t\tsql,\n\t\t\t\tparams: params ?? [],\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthrow new TauriAdapterError(`Execute failed: ${(error as Error).message}`, {\n\t\t\t\tsql,\n\t\t\t\tparams,\n\t\t\t})\n\t\t}\n\t}\n\n\t/**\n\t * Execute a read query (SELECT).\n\t */\n\tasync query<T>(sql: string, params?: unknown[]): Promise<T[]> {\n\t\tthis.ensureOpen()\n\t\ttry {\n\t\t\treturn await this.invoke<T[]>('query', {\n\t\t\t\tpath: this.dbPath,\n\t\t\t\tsql,\n\t\t\t\tparams: params ?? [],\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthrow new TauriAdapterError(`Query failed: ${(error as Error).message}`, {\n\t\t\t\tsql,\n\t\t\t\tparams,\n\t\t\t})\n\t\t}\n\t}\n\n\t/**\n\t * Execute multiple operations atomically within a transaction.\n\t *\n\t * Uses a mutex to prevent interleaving of concurrent transactions.\n\t * The transaction is committed on success or rolled back on error.\n\t */\n\tasync transaction(fn: (tx: Transaction) => Promise<void>): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tconst release = await this.txMutex.acquire()\n\t\ttry {\n\t\t\tthis.inTransaction = true\n\t\t\tawait this.invoke('execute', { path: this.dbPath, sql: 'BEGIN', params: [] })\n\t\t\ttry {\n\t\t\t\tconst tx: Transaction = {\n\t\t\t\t\texecute: async (sql: string, params?: unknown[]): Promise<void> => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait this.invoke('execute', {\n\t\t\t\t\t\t\t\tpath: this.dbPath,\n\t\t\t\t\t\t\t\tsql,\n\t\t\t\t\t\t\t\tparams: params ?? [],\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tthrow new TauriAdapterError(\n\t\t\t\t\t\t\t\t`Transaction execute failed: ${(error as Error).message}`,\n\t\t\t\t\t\t\t\t{ sql, params },\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tquery: async <T>(sql: string, params?: unknown[]): Promise<T[]> => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn await this.invoke<T[]>('query', {\n\t\t\t\t\t\t\t\tpath: this.dbPath,\n\t\t\t\t\t\t\t\tsql,\n\t\t\t\t\t\t\t\tparams: params ?? [],\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tthrow new TauriAdapterError(\n\t\t\t\t\t\t\t\t`Transaction query failed: ${(error as Error).message}`,\n\t\t\t\t\t\t\t\t{ sql, params },\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tawait fn(tx)\n\t\t\t\tawait this.invoke('execute', { path: this.dbPath, sql: 'COMMIT', params: [] })\n\t\t\t} catch (error) {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.invoke('execute', { path: this.dbPath, sql: 'ROLLBACK', params: [] })\n\t\t\t\t} catch {\n\t\t\t\t\t// Rollback failed — connection may be in a bad state, but we still throw the original error\n\t\t\t\t}\n\t\t\t\tthrow error\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.inTransaction = false\n\t\t\trelease()\n\t\t}\n\t}\n\n\t/**\n\t * Apply a schema migration within a transaction.\n\t */\n\tasync migrate(from: number, to: number, migration: MigrationPlan): Promise<void> {\n\t\tthis.ensureOpen()\n\t\ttry {\n\t\t\tawait this.invoke('migrate', {\n\t\t\t\tpath: this.dbPath,\n\t\t\t\tstatements: migration.statements,\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthrow new TauriAdapterError(\n\t\t\t\t`Migration from v${from} to v${to} failed: ${(error as Error).message}`,\n\t\t\t\t{ from, to },\n\t\t\t)\n\t\t}\n\t}\n\n\tprivate ensureOpen(): void {\n\t\tif (!this.opened) {\n\t\t\tthrow new TauriStoreNotOpenError()\n\t\t}\n\t}\n}\n"],"mappings":";AAAA,SAAS,uBAAuB;AA4DzB,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAC5B;AAAA,EACA;AAAA,EAEhB,YAAY,SAAiB,SAAmC;AAC/D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,EAChB;AACD;AAKO,IAAM,yBAAN,cAAqC,MAAM;AAAA,EACjC;AAAA,EAEhB,cAAc;AACb,UAAM,sEAAsE;AAC5E,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACb;AACD;AAGA,IAAM,aAAN,MAAiB;AAAA,EACR,QAA2B,CAAC;AAAA,EAC5B,SAAS;AAAA,EAEjB,MAAM,UAA+B;AACpC,QAAI,CAAC,KAAK,QAAQ;AACjB,WAAK,SAAS;AACd,aAAO,MAAM,KAAK,QAAQ;AAAA,IAC3B;AACA,WAAO,IAAI,QAAoB,CAAC,YAAY;AAC3C,WAAK,MAAM,KAAK,MAAM;AACrB,gBAAQ,MAAM,KAAK,QAAQ,CAAC;AAAA,MAC7B,CAAC;AAAA,IACF,CAAC;AAAA,EACF;AAAA,EA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version": "0.3.1",
|
|
4
|
+
"description": "Tauri storage adapter for Kora.js — native SQLite with zero WASM overhead",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.cjs",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"import": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"require": {
|
|
16
|
+
"types": "./dist/index.d.cts",
|
|
17
|
+
"default": "./dist/index.cjs"
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"dist",
|
|
23
|
+
"plugin"
|
|
24
|
+
],
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"@korajs/core": "0.3.1"
|
|
27
|
+
},
|
|
28
|
+
"peerDependencies": {
|
|
29
|
+
"@tauri-apps/api": "^2.0.0"
|
|
30
|
+
},
|
|
31
|
+
"peerDependenciesMeta": {
|
|
32
|
+
"@tauri-apps/api": {
|
|
33
|
+
"optional": true
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@types/better-sqlite3": "^7.6.13",
|
|
38
|
+
"better-sqlite3": "^12.8.0",
|
|
39
|
+
"tsup": "^8.3.6",
|
|
40
|
+
"typescript": "^5.7.3",
|
|
41
|
+
"vitest": "^3.0.4",
|
|
42
|
+
"@korajs/store": "0.3.1"
|
|
43
|
+
},
|
|
44
|
+
"license": "MIT",
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "tsup",
|
|
47
|
+
"dev": "tsup --watch",
|
|
48
|
+
"test": "vitest run",
|
|
49
|
+
"test:watch": "vitest",
|
|
50
|
+
"typecheck": "tsc --noEmit",
|
|
51
|
+
"clean": "rm -rf dist .turbo coverage"
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
[package]
|
|
2
|
+
name = "tauri-plugin-kora"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
edition = "2021"
|
|
5
|
+
description = "Tauri plugin providing native SQLite storage for Kora.js applications"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
repository = "https://github.com/nicholasgriffintn/kora"
|
|
8
|
+
|
|
9
|
+
[dependencies]
|
|
10
|
+
tauri = { version = "2", features = [] }
|
|
11
|
+
tauri-plugin = { version = "2" }
|
|
12
|
+
serde = { version = "1", features = ["derive"] }
|
|
13
|
+
serde_json = "1"
|
|
14
|
+
thiserror = "2"
|
|
15
|
+
rusqlite = { version = "0.32", features = ["bundled"] }
|
|
16
|
+
log = "0.4"
|
|
17
|
+
|
|
18
|
+
[build-dependencies]
|
|
19
|
+
tauri-plugin = { version = "2", features = ["build"] }
|
package/plugin/build.rs
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"$schema" = "schemas/schema.json"
|
|
2
|
+
|
|
3
|
+
[default]
|
|
4
|
+
description = "Default permissions for the Kora SQLite storage plugin. Grants access to all database operations."
|
|
5
|
+
permissions = [
|
|
6
|
+
"allow-open",
|
|
7
|
+
"allow-close",
|
|
8
|
+
"allow-execute",
|
|
9
|
+
"allow-query",
|
|
10
|
+
"allow-migrate",
|
|
11
|
+
]
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
use std::collections::HashMap;
|
|
2
|
+
use std::sync::Mutex;
|
|
3
|
+
|
|
4
|
+
use rusqlite::{params_from_iter, Connection};
|
|
5
|
+
use serde_json::Value as JsonValue;
|
|
6
|
+
use tauri::{AppHandle, Manager, Runtime, State};
|
|
7
|
+
|
|
8
|
+
use crate::error::Error;
|
|
9
|
+
|
|
10
|
+
/// Managed state holding open database connections.
|
|
11
|
+
/// Each database is identified by its file path.
|
|
12
|
+
pub struct DbState {
|
|
13
|
+
pub connections: Mutex<HashMap<String, Connection>>,
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
impl Default for DbState {
|
|
17
|
+
fn default() -> Self {
|
|
18
|
+
Self {
|
|
19
|
+
connections: Mutex::new(HashMap::new()),
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/// Convert a JSON value to a rusqlite parameter.
|
|
25
|
+
fn json_to_param(value: &JsonValue) -> Box<dyn rusqlite::types::ToSql> {
|
|
26
|
+
match value {
|
|
27
|
+
JsonValue::Null => Box::new(rusqlite::types::Null),
|
|
28
|
+
JsonValue::Bool(b) => Box::new(if *b { 1i64 } else { 0i64 }),
|
|
29
|
+
JsonValue::Number(n) => {
|
|
30
|
+
if let Some(i) = n.as_i64() {
|
|
31
|
+
Box::new(i)
|
|
32
|
+
} else if let Some(f) = n.as_f64() {
|
|
33
|
+
Box::new(f)
|
|
34
|
+
} else {
|
|
35
|
+
Box::new(rusqlite::types::Null)
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
JsonValue::String(s) => Box::new(s.clone()),
|
|
39
|
+
// Arrays and objects are stored as JSON text
|
|
40
|
+
_ => Box::new(value.to_string()),
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/// Open a database and execute DDL statements.
|
|
45
|
+
/// Configures WAL mode, foreign keys, and other pragmas.
|
|
46
|
+
#[tauri::command]
|
|
47
|
+
pub fn open<R: Runtime>(
|
|
48
|
+
app: AppHandle<R>,
|
|
49
|
+
state: State<'_, DbState>,
|
|
50
|
+
path: String,
|
|
51
|
+
statements: Vec<String>,
|
|
52
|
+
) -> Result<(), Error> {
|
|
53
|
+
let mut connections = state
|
|
54
|
+
.connections
|
|
55
|
+
.lock()
|
|
56
|
+
.map_err(|e| Error::Plugin(format!("Failed to acquire lock: {}", e)))?;
|
|
57
|
+
|
|
58
|
+
// Resolve the database path relative to the app's data directory
|
|
59
|
+
let db_path = if path == ":memory:" {
|
|
60
|
+
path.clone()
|
|
61
|
+
} else {
|
|
62
|
+
let data_dir = app
|
|
63
|
+
.path()
|
|
64
|
+
.app_data_dir()
|
|
65
|
+
.map_err(|e| Error::Plugin(format!("Failed to get app data dir: {}", e)))?;
|
|
66
|
+
std::fs::create_dir_all(&data_dir)?;
|
|
67
|
+
data_dir
|
|
68
|
+
.join(&path)
|
|
69
|
+
.to_string_lossy()
|
|
70
|
+
.into_owned()
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
let conn = Connection::open(&db_path)?;
|
|
74
|
+
|
|
75
|
+
// Configure SQLite for optimal performance and correctness
|
|
76
|
+
conn.pragma_update(None, "journal_mode", "WAL")?;
|
|
77
|
+
conn.pragma_update(None, "foreign_keys", "ON")?;
|
|
78
|
+
conn.pragma_update(None, "synchronous", "NORMAL")?;
|
|
79
|
+
conn.pragma_update(None, "busy_timeout", "5000")?;
|
|
80
|
+
|
|
81
|
+
// Execute DDL statements from the schema
|
|
82
|
+
for sql in &statements {
|
|
83
|
+
if sql.starts_with("--kora:safe-alter") {
|
|
84
|
+
// Safe ALTER TABLE — ignore "duplicate column name" errors
|
|
85
|
+
let clean_sql = sql.replace("--kora:safe-alter\n", "");
|
|
86
|
+
match conn.execute_batch(&clean_sql) {
|
|
87
|
+
Ok(_) => {}
|
|
88
|
+
Err(e) => {
|
|
89
|
+
let msg = e.to_string();
|
|
90
|
+
if !msg.contains("duplicate column name") {
|
|
91
|
+
return Err(Error::Sqlite(e));
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
} else {
|
|
96
|
+
conn.execute_batch(sql)?;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
log::info!("Opened Kora database: {}", db_path);
|
|
101
|
+
connections.insert(path, conn);
|
|
102
|
+
Ok(())
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/// Close a database connection.
|
|
106
|
+
#[tauri::command]
|
|
107
|
+
pub fn close(state: State<'_, DbState>, path: String) -> Result<(), Error> {
|
|
108
|
+
let mut connections = state
|
|
109
|
+
.connections
|
|
110
|
+
.lock()
|
|
111
|
+
.map_err(|e| Error::Plugin(format!("Failed to acquire lock: {}", e)))?;
|
|
112
|
+
|
|
113
|
+
if connections.remove(&path).is_some() {
|
|
114
|
+
log::info!("Closed Kora database: {}", path);
|
|
115
|
+
}
|
|
116
|
+
Ok(())
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/// Execute a write query (INSERT, UPDATE, DELETE, or DDL like BEGIN/COMMIT/ROLLBACK).
|
|
120
|
+
#[tauri::command]
|
|
121
|
+
pub fn execute(
|
|
122
|
+
state: State<'_, DbState>,
|
|
123
|
+
path: String,
|
|
124
|
+
sql: String,
|
|
125
|
+
params: Vec<JsonValue>,
|
|
126
|
+
) -> Result<(), Error> {
|
|
127
|
+
let connections = state
|
|
128
|
+
.connections
|
|
129
|
+
.lock()
|
|
130
|
+
.map_err(|e| Error::Plugin(format!("Failed to acquire lock: {}", e)))?;
|
|
131
|
+
|
|
132
|
+
let conn = connections
|
|
133
|
+
.get(&path)
|
|
134
|
+
.ok_or_else(|| Error::DatabaseNotLoaded(path.clone()))?;
|
|
135
|
+
|
|
136
|
+
if params.is_empty() {
|
|
137
|
+
// For statements without parameters (BEGIN, COMMIT, ROLLBACK, DDL)
|
|
138
|
+
conn.execute_batch(&sql)?;
|
|
139
|
+
} else {
|
|
140
|
+
let param_refs: Vec<Box<dyn rusqlite::types::ToSql>> =
|
|
141
|
+
params.iter().map(json_to_param).collect();
|
|
142
|
+
let param_slice: Vec<&dyn rusqlite::types::ToSql> =
|
|
143
|
+
param_refs.iter().map(|p| p.as_ref()).collect();
|
|
144
|
+
conn.execute(&sql, param_slice.as_slice())?;
|
|
145
|
+
}
|
|
146
|
+
Ok(())
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/// Execute a read query (SELECT) and return results as JSON.
|
|
150
|
+
#[tauri::command]
|
|
151
|
+
pub fn query(
|
|
152
|
+
state: State<'_, DbState>,
|
|
153
|
+
path: String,
|
|
154
|
+
sql: String,
|
|
155
|
+
params: Vec<JsonValue>,
|
|
156
|
+
) -> Result<Vec<HashMap<String, JsonValue>>, Error> {
|
|
157
|
+
let connections = state
|
|
158
|
+
.connections
|
|
159
|
+
.lock()
|
|
160
|
+
.map_err(|e| Error::Plugin(format!("Failed to acquire lock: {}", e)))?;
|
|
161
|
+
|
|
162
|
+
let conn = connections
|
|
163
|
+
.get(&path)
|
|
164
|
+
.ok_or_else(|| Error::DatabaseNotLoaded(path.clone()))?;
|
|
165
|
+
|
|
166
|
+
let param_refs: Vec<Box<dyn rusqlite::types::ToSql>> =
|
|
167
|
+
params.iter().map(json_to_param).collect();
|
|
168
|
+
let param_slice: Vec<&dyn rusqlite::types::ToSql> =
|
|
169
|
+
param_refs.iter().map(|p| p.as_ref()).collect();
|
|
170
|
+
|
|
171
|
+
let mut stmt = conn.prepare(&sql)?;
|
|
172
|
+
let column_names: Vec<String> = stmt
|
|
173
|
+
.column_names()
|
|
174
|
+
.iter()
|
|
175
|
+
.map(|s| s.to_string())
|
|
176
|
+
.collect();
|
|
177
|
+
|
|
178
|
+
let rows = stmt.query_map(param_slice.as_slice(), |row| {
|
|
179
|
+
let mut map = HashMap::new();
|
|
180
|
+
for (i, name) in column_names.iter().enumerate() {
|
|
181
|
+
let value: JsonValue = match row.get_ref(i) {
|
|
182
|
+
Ok(rusqlite::types::ValueRef::Null) => JsonValue::Null,
|
|
183
|
+
Ok(rusqlite::types::ValueRef::Integer(n)) => JsonValue::Number(n.into()),
|
|
184
|
+
Ok(rusqlite::types::ValueRef::Real(f)) => {
|
|
185
|
+
match serde_json::Number::from_f64(f) {
|
|
186
|
+
Some(n) => JsonValue::Number(n),
|
|
187
|
+
None => JsonValue::Null,
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
Ok(rusqlite::types::ValueRef::Text(s)) => {
|
|
191
|
+
JsonValue::String(String::from_utf8_lossy(s).into_owned())
|
|
192
|
+
}
|
|
193
|
+
Ok(rusqlite::types::ValueRef::Blob(b)) => {
|
|
194
|
+
// Encode blobs as hex strings for transport
|
|
195
|
+
let hex: String = b.iter().map(|byte| format!("{:02x}", byte)).collect();
|
|
196
|
+
JsonValue::String(hex)
|
|
197
|
+
}
|
|
198
|
+
Err(_) => JsonValue::Null,
|
|
199
|
+
};
|
|
200
|
+
map.insert(name.clone(), value);
|
|
201
|
+
}
|
|
202
|
+
Ok(map)
|
|
203
|
+
})?;
|
|
204
|
+
|
|
205
|
+
let mut results = Vec::new();
|
|
206
|
+
for row in rows {
|
|
207
|
+
results.push(row?);
|
|
208
|
+
}
|
|
209
|
+
Ok(results)
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/// Apply a migration within a transaction.
|
|
213
|
+
#[tauri::command]
|
|
214
|
+
pub fn migrate(
|
|
215
|
+
state: State<'_, DbState>,
|
|
216
|
+
path: String,
|
|
217
|
+
statements: Vec<String>,
|
|
218
|
+
) -> Result<(), Error> {
|
|
219
|
+
let connections = state
|
|
220
|
+
.connections
|
|
221
|
+
.lock()
|
|
222
|
+
.map_err(|e| Error::Plugin(format!("Failed to acquire lock: {}", e)))?;
|
|
223
|
+
|
|
224
|
+
let conn = connections
|
|
225
|
+
.get(&path)
|
|
226
|
+
.ok_or_else(|| Error::DatabaseNotLoaded(path.clone()))?;
|
|
227
|
+
|
|
228
|
+
conn.execute_batch("BEGIN")?;
|
|
229
|
+
match (|| -> Result<(), Error> {
|
|
230
|
+
for sql in &statements {
|
|
231
|
+
conn.execute_batch(sql)?;
|
|
232
|
+
}
|
|
233
|
+
Ok(())
|
|
234
|
+
})() {
|
|
235
|
+
Ok(_) => {
|
|
236
|
+
conn.execute_batch("COMMIT")?;
|
|
237
|
+
Ok(())
|
|
238
|
+
}
|
|
239
|
+
Err(e) => {
|
|
240
|
+
let _ = conn.execute_batch("ROLLBACK");
|
|
241
|
+
Err(e)
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
use serde::Serialize;
|
|
2
|
+
|
|
3
|
+
/// Errors that can occur in the Kora SQLite plugin.
|
|
4
|
+
#[derive(Debug, thiserror::Error)]
|
|
5
|
+
pub enum Error {
|
|
6
|
+
#[error("Database not loaded: {0}")]
|
|
7
|
+
DatabaseNotLoaded(String),
|
|
8
|
+
|
|
9
|
+
#[error("SQLite error: {0}")]
|
|
10
|
+
Sqlite(#[from] rusqlite::Error),
|
|
11
|
+
|
|
12
|
+
#[error("IO error: {0}")]
|
|
13
|
+
Io(#[from] std::io::Error),
|
|
14
|
+
|
|
15
|
+
#[error("Plugin error: {0}")]
|
|
16
|
+
Plugin(String),
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Tauri requires errors to implement Serialize to send them across the IPC boundary.
|
|
20
|
+
impl Serialize for Error {
|
|
21
|
+
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
|
22
|
+
where
|
|
23
|
+
S: serde::ser::Serializer,
|
|
24
|
+
{
|
|
25
|
+
serializer.serialize_str(self.to_string().as_ref())
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
//! # tauri-plugin-kora
|
|
2
|
+
//!
|
|
3
|
+
//! Tauri plugin providing native SQLite storage for Kora.js applications.
|
|
4
|
+
//!
|
|
5
|
+
//! This plugin exposes SQLite operations via Tauri IPC commands, configured with
|
|
6
|
+
//! WAL mode, foreign keys, and proper pragmas for optimal offline-first performance.
|
|
7
|
+
//!
|
|
8
|
+
//! ## Setup
|
|
9
|
+
//!
|
|
10
|
+
//! Add the plugin to your Tauri app:
|
|
11
|
+
//!
|
|
12
|
+
//! ```rust,no_run
|
|
13
|
+
//! fn main() {
|
|
14
|
+
//! tauri::Builder::default()
|
|
15
|
+
//! .plugin(tauri_plugin_kora::init())
|
|
16
|
+
//! .run(tauri::generate_context!())
|
|
17
|
+
//! .expect("error while running tauri application");
|
|
18
|
+
//! }
|
|
19
|
+
//! ```
|
|
20
|
+
//!
|
|
21
|
+
//! Then add the permissions to your `capabilities/default.json`:
|
|
22
|
+
//!
|
|
23
|
+
//! ```json
|
|
24
|
+
//! {
|
|
25
|
+
//! "permissions": ["kora-sqlite:default"]
|
|
26
|
+
//! }
|
|
27
|
+
//! ```
|
|
28
|
+
|
|
29
|
+
mod commands;
|
|
30
|
+
mod error;
|
|
31
|
+
|
|
32
|
+
use commands::DbState;
|
|
33
|
+
use tauri::{
|
|
34
|
+
plugin::{Builder as PluginBuilder, TauriPlugin},
|
|
35
|
+
Manager, Runtime,
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/// Initialize the Kora SQLite plugin.
|
|
39
|
+
///
|
|
40
|
+
/// Registers IPC command handlers for database operations and manages
|
|
41
|
+
/// the lifecycle of SQLite connections.
|
|
42
|
+
pub fn init<R: Runtime>() -> TauriPlugin<R> {
|
|
43
|
+
PluginBuilder::new("kora-sqlite")
|
|
44
|
+
.setup(|app, _api| {
|
|
45
|
+
app.manage(DbState::default());
|
|
46
|
+
Ok(())
|
|
47
|
+
})
|
|
48
|
+
.invoke_handler(tauri::generate_handler![
|
|
49
|
+
commands::open,
|
|
50
|
+
commands::close,
|
|
51
|
+
commands::execute,
|
|
52
|
+
commands::query,
|
|
53
|
+
commands::migrate,
|
|
54
|
+
])
|
|
55
|
+
.build()
|
|
56
|
+
}
|