Skip to content

Commit fe46920

Browse files
committed
feat: custom function
1 parent b21e06f commit fe46920

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

playground/src/worker.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,22 @@
11
import url from 'wa-sqlite/dist/wa-sqlite.wasm?url'
2-
import { initSQLite, isOpfsSupported } from '../../src'
2+
import { def, initSQLite, isOpfsSupported } from '../../src'
33
import { useOpfsStorage } from '../../src/vfs/opfs'
44
import { runSQLStream } from './runSQL'
55

66
onmessage = async () => {
77
if (!await isOpfsSupported()) {
88
return
99
}
10-
const { run, stream, lastInsertRowId, changes } = await initSQLite(useOpfsStorage(
10+
const { run, stream, lastInsertRowId, changes, sqlite, db } = await initSQLite(useOpfsStorage(
1111
'test',
1212
{ url },
1313
// 'https://cdn.jsdelivr.net/gh/rhashimoto/wa-sqlite@v0.9.9/dist/wa-sqlite.wasm',
1414
))
1515
await runSQLStream(run, stream, data => postMessage(data))
1616
console.log(lastInsertRowId(), changes())
17+
def(sqlite, db, 'testtest', (a: number, b: number) => a + b)
18+
console.log(
19+
await run('select testtest(1,2)'),
20+
)
1721
postMessage('done')
1822
}

src/utils.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { SQLITE_DETERMINISTIC, SQLITE_DIRECTONLY, SQLITE_UTF8 } from 'wa-sqlite'
2+
13
/**
24
* check if IndexedDB and Web Locks API supported
35
*/
@@ -82,4 +84,38 @@ export function isModuleWorkerSupport(): boolean {
8284
}
8385
}
8486

87+
export function def<N extends string, T extends SQLiteCompatibleType[]>(
88+
sqlite: SQLiteAPI,
89+
db: number,
90+
fnName: N,
91+
fn: N extends '' ? never : (...args: T) => (SQLiteCompatibleType | number[]) | null,
92+
option: {
93+
deterministic?: boolean
94+
directOnly?: boolean
95+
varargs?: boolean
96+
} = {},
97+
): void {
98+
let flags = SQLITE_UTF8
99+
if (option.deterministic) {
100+
flags |= SQLITE_DETERMINISTIC
101+
}
102+
if (option.directOnly) {
103+
flags |= SQLITE_DIRECTONLY
104+
}
105+
sqlite.create_function(
106+
db,
107+
fnName,
108+
(option.varargs || fn.length === 0) ? -1 : fn.length,
109+
flags,
110+
0,
111+
(ctx, value) => {
112+
const args = [] as unknown as T
113+
for (let i = 0; i < fn.length; i++) {
114+
args.push(sqlite.value(value[i]))
115+
}
116+
return sqlite.result(ctx, fn(...args))
117+
},
118+
)
119+
}
120+
85121
// todo: import/export

0 commit comments

Comments
 (0)