MIRROR: javascript for 馃悳's, a tiny runtime with big ambitions
1import { sqlite3 } from './sqlite3';
2import { alloc, callback, FFIType } from 'ant:ffi';
3
4const dbPtrPtr = alloc(8);
5const result = sqlite3.call('sqlite3_open', ':memory:', dbPtrPtr);
6
7if (result !== 0) {
8 console.log('Failed to open database');
9 dbPtrPtr.free();
10 process.exit(0);
11}
12
13const db = dbPtrPtr.read(FFIType.pointer);
14dbPtrPtr.free();
15
16sqlite3.call('sqlite3_exec', db, 'CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)', null, null, null);
17sqlite3.call('sqlite3_exec', db, "INSERT INTO users (name, age) VALUES ('Alice', 30)", null, null, null);
18sqlite3.call('sqlite3_exec', db, "INSERT INTO users (name, age) VALUES ('Bob', 25)", null, null, null);
19sqlite3.call('sqlite3_exec', db, "INSERT INTO users (name, age) VALUES ('Charlie', 35)", null, null, null);
20
21console.log('\nQuerying users with callback:');
22
23const rowCallback = callback(
24 function (_, argc, argv, colNames) {
25 let row = '';
26 for (let i = 0; i < argc; i++) {
27 const colNamePtr = colNames.offset(i * 8).read(FFIType.pointer);
28 const valuePtr = argv.offset(i * 8).read(FFIType.pointer);
29 const colName = colNamePtr ? colNamePtr.read(FFIType.string) : 'NULL';
30 const value = valuePtr ? valuePtr.read(FFIType.string) : 'NULL';
31 row += `${colName}=${value} `;
32 }
33 console.log(` Row: ${row}`);
34 return 0;
35 },
36 {
37 args: [FFIType.pointer, FFIType.int, FFIType.pointer, FFIType.pointer],
38 returns: FFIType.int
39 }
40);
41
42const execResult = sqlite3.call('sqlite3_exec', db, 'SELECT * FROM users', rowCallback, null, null);
43
44if (execResult !== 0) {
45 console.log(`Query error: ${sqlite3.call('sqlite3_errmsg', db)}`);
46}
47
48rowCallback.close();
49sqlite3.call('sqlite3_close', db);
50console.log('\nDatabase closed.');