Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add sql.js fallback for sqlite in wasm #614

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions .github/workflows/sqlite-wasm.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
name: Tests WASM

on:
push:
branches: [main]
pull_request:
types: [opened, synchronize, reopened, auto_merge_enabled]

# Allow parallel jobs on `main`, so that each commit is tested. For PRs, run only the latest commit.
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true

jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 5
name: Node.js ${{ matrix.node }}

strategy:
fail-fast: true
matrix:
node: [18]

steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
cache: 'npm'

- run: npm ci
# Remove better-sqlite3 to force switching to sql.js
- run: npm install sql.js && rm -rf node_modules/better-sqlite3/
- run: npm test -w sqlite -- --maxWorkers=1
env:
FORCE_COLOR: true
9 changes: 9 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 10 additions & 3 deletions sqlite/lib/SQLiteService.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
const { SQLService } = require('@cap-js/db-service')
const cds = require('@sap/cds/lib')
const sqlite = require('better-sqlite3')
let sqlite
try {
sqlite = require('better-sqlite3')
} catch (err) {
// When failing to load better-sqlite3 it fallsback to sql.js (wasm version of sqlite)
sqlite = require('./sql.js.js')
}
const $session = Symbol('dbc.session')
const convStrm = require('stream/consumers')
const { Readable } = require('stream')
Expand All @@ -20,9 +26,10 @@ class SQLiteService extends SQLService {
get factory() {
return {
options: { max: 1, ...this.options.pool },
create: tenant => {
create: async tenant => {
const database = this.url4(tenant)
const dbc = new sqlite(database)
await dbc.ready

const deterministic = { deterministic: true }
dbc.function('session_context', key => dbc[$session][key])
Expand Down Expand Up @@ -224,7 +231,7 @@ class SQLiteService extends SQLService {
// int64 is stored as native int64 for best comparison
// Reading int64 as string to not loose precision
Int64: expr => `CAST(${expr} as TEXT)`,

// Reading decimal as string to not loose precision
Decimal: expr => `CAST(${expr} as TEXT)`,

Expand Down
84 changes: 84 additions & 0 deletions sqlite/lib/sql.js.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
const initSqlJs = require('sql.js');

const init = initSqlJs({})

class WasmSqlite {
constructor(database) {

Check warning on line 6 in sqlite/lib/sql.js.js

View workflow job for this annotation

GitHub Actions / Node.js 18

'database' is defined but never used. Allowed unused args must match /lazy/u

Check warning on line 6 in sqlite/lib/sql.js.js

View workflow job for this annotation

GitHub Actions / HANA Node.js 18

'database' is defined but never used. Allowed unused args must match /lazy/u
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we get rid of this warning?

// TODO: load / store database file contents
this.ready = init
.then(SQL => { this.db = new SQL.Database() })

this.memory = true
this.gc = new FinalizationRegistry(stmt => { stmt.free() })
}

prepare(sql) {
const stmt = this.db.prepare(sql)
const ret = {
run: (params) => {
try {
stmt.bind(params)
stmt.step()
return { changes: this.db.getRowsModified(stmt) }
} catch (err) {
if (err.message.indexOf('NOT NULL constraint failed:') === 0) {
err.code = 'SQLITE_CONSTRAINT_NOTNULL'
}
throw err
}
},
get: (params) => {
const columns = stmt.getColumnNames()
stmt.bind(params)
stmt.step()
const row = stmt.get()
const ret = {}
for (let i = 0; i < columns.length; i++) {
ret[columns[i]] = row[i]
}
return ret
},
all: (params) => {
const columns = stmt.getColumnNames()
const ret = []
stmt.bind(params)
while (stmt.step()) {
const row = stmt.get()
const obj = {}
for (let i = 0; i < columns.length; i++) {
obj[columns[i]] = row[i]
}
ret.push(obj)
}
return ret
}
}
this.gc.register(ret, stmt)
return ret
}

exec(sql) {
try {
const { columns, values } = this.db.exec(sql)
return !Array.isArray(values) ? values : values.map(val => {
const ret = {}
for (let i = 0; i < columns.length; i++) {
ret[columns[i]] = val[i]
}
return ret
})
} catch (err) {
// REVISIT: address transaction errors
if (sql === 'BEGIN' || sql === 'ROLLBACK') { return }
throw err
}
}

function(name, config, func) {
this.db.create_function(name, func || config)
}

close() { this.db.close() }
}

module.exports = WasmSqlite
3 changes: 3 additions & 0 deletions sqlite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@
"@cap-js/db-service": "^1.7.0",
"better-sqlite3": "^9.3.0"
},
"optionalDependencies": {
"sql.js": "^1.10.3"
},
"peerDependencies": {
"@sap/cds": ">=7.6"
},
Expand Down