test: add openTestSqliteDatabase helper to fix native binding mismatch

Centralise the better-sqlite3 native-binding selection for tests in
tests/helpers/sqlite.mts so test files consistently use the CLI-side
binding (apps/cli/native/better_sqlite3.node) rather than the default
one, which may be compiled for a different Node.js ABI.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
diguaandClaude Sonnet 4.6 committed 2026-06-23 14:18:32 +08:00
1 parent 39393cf38d
commit 7df673f62f
2 files changed
+43 -1

No files matched your search

@@ -13,6 +13,7 @@ import assert from 'node:assert/strict'
import Database from 'better-sqlite3'
import { CoreDataProvider } from './core-data-provider'
import type { DatabaseAdapter, PreparedStatement, RunResult } from '@openchatlab/core'
import { openTestSqliteDatabase } from '../../../../tests/helpers/sqlite.mts'
class Stmt implements PreparedStatement {
readonly?: boolean
@@ -57,7 +58,7 @@ describe('CoreDataProvider keyword search', () => {
let provider: CoreDataProvider
beforeEach(() => {
raw = new Database(':memory:')
raw = openTestSqliteDatabase()
raw.exec(`
CREATE TABLE member (
id INTEGER PRIMARY KEY, platform_id TEXT, account_name TEXT,
+41
View File
@@ -0,0 +1,41 @@
import { existsSync } from 'node:fs'
import { resolve } from 'node:path'
import { spawnSync } from 'node:child_process'
import Database from 'better-sqlite3'
export const testSqliteNativeBinding = resolve('apps/cli/native/better_sqlite3.node')
function assertTestSqliteNativeBinding(): string {
if (!existsSync(testSqliteNativeBinding)) {
throw new Error(
`Missing test better-sqlite3 native binding: ${testSqliteNativeBinding}. ` +
'Run `pnpm --filter chatlab-cli run ensure-native` first.'
)
}
// 先用当前 Node 进程验证 ABI,避免 better-sqlite3 抛出难读的默认绑定错误。
const result = spawnSync(
process.execPath,
['-e', 'require(process.argv[1]); process.stdout.write(process.versions.modules)', testSqliteNativeBinding],
{ encoding: 'utf8' }
)
if (result.status !== 0) {
const detail = (result.stderr || result.stdout || result.error?.message || 'native binding failed to load').trim()
throw new Error(
`Invalid test better-sqlite3 native binding: ${testSqliteNativeBinding}. ${detail}. ` +
'Run `pnpm --filter chatlab-cli run ensure-native` to rebuild it for the current Node.js.'
)
}
return testSqliteNativeBinding
}
export function openTestSqliteDatabase(
filename: string = ':memory:',
options?: Omit<Database.Options, 'nativeBinding'>
) {
return new Database(filename, {
...options,
nativeBinding: assertTestSqliteNativeBinding(),
})
}