Skip to content

Commit

Permalink
switch out sqlite_native for sqlite3
Browse files Browse the repository at this point in the history
  • Loading branch information
andykais committed Oct 30, 2023
1 parent b54402e commit 1d4db41
Show file tree
Hide file tree
Showing 6 changed files with 92 additions and 34 deletions.
4 changes: 2 additions & 2 deletions deno.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"tasks": {
"test": "deno test --unstable --check --allow-read --allow-write --allow-ffi --allow-env=HOME --allow-net --import-map=test/import_map.json test",
"test:watch": "deno test --unstable --check --allow-read --allow-write --allow-ffi --allow-env=HOME --allow-net --import-map=test/import_map.json --watch test"
"test": "deno test --unstable --check --allow-read --allow-write --allow-ffi --allow-env=HOME,DENO_DIR,XDG_CACHE_HOME --allow-net --import-map=test/import_map.json test",
"test:watch": "deno test --unstable --check --allow-read --allow-write --allow-ffi --allow-env=HOME,DENO_DIR,XDG_CACHE_HOME --allow-net --import-map=test/import_map.json --watch test"
},
"lint": {
"rules": {
Expand Down
77 changes: 64 additions & 13 deletions deno.lock

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

36 changes: 21 additions & 15 deletions drivers/sqlite.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as sqlite_native from 'https://deno.land/x/sqlite_native@1.0.5/mod.ts'
import * as sqlite3 from 'https://deno.land/x/sqlite3@0.9.1/mod.ts'
import type { OptionalOnEmpty } from '../src/util.ts'
import { Vars, type SchemaGeneric } from '../src/schema.ts'
import { ModelBase, WithStaticSchema } from '../src/model.ts'
import { StatementBase } from '../src/statement.ts'
import { StatementBase, type RawRowData } from '../src/statement.ts'
import { TormBase, type SchemasModel, type InitOptions } from '../src/torm.ts'
import { MigrationBase, type MigrationClass } from '../src/migration.ts'
import { field } from '../src/mod.ts'
Expand All @@ -11,18 +11,24 @@ import { field } from '../src/mod.ts'
class Statement<
Params extends SchemaGeneric,
Result extends SchemaGeneric
> extends StatementBase<sqlite_native.PreparedStatement, Params, Result> {
> extends StatementBase<sqlite3.Statement, Params, Result> {

public one = (...[params]: OptionalOnEmpty<Params>): Result | undefined => {
const row = this.stmt.one(this.encode_params(params))
const row = this.stmt.get<RawRowData>(this.encode_params(params))
if (row) return this.decode_result(row)
// throw new Error('undefined one() is unimplemented')
}

public all = (...[params]: OptionalOnEmpty<Params>) => this.stmt.all(this.encode_params(params)).map(this.decode_result)


public exec = (...[params]: OptionalOnEmpty<Params>) => this.stmt.exec(this.encode_params(params))
public exec = (...[params]: OptionalOnEmpty<Params>) => {
const changes = this.stmt.run(this.encode_params(params))
return {
changes,
last_insert_row_id: this.driver.lastInsertRowId
}
}

protected prepare = (sql: string) => this.driver.prepare(sql)

Expand All @@ -41,11 +47,11 @@ const Model = WithStaticSchema(TempModelNonAbstract)
abstract class Migration extends MigrationBase {
protected create_stmt = Statement.create

static create(version: string, arg: string | ((driver: sqlite_native.Database) => void)): MigrationClass {
static create(version: string, arg: string | ((driver: sqlite3.Database) => void)): MigrationClass {
return class InlineMigration extends Migration {
version = version
call = () => {
if (typeof arg === 'string') this.driver.exec(arg)
if (typeof arg === 'string') this.driver.run(arg)
else arg(this.driver)
}
}
Expand All @@ -58,17 +64,17 @@ class SqliteMasterModel extends Model('sqlite_master', {
}) {}
class InitializeTormMetadata extends Migration {
version = '0.1.0'
call(driver?: sqlite_native.Database) {
call(driver?: sqlite3.Database) {
if (!driver) throw new Error('Cannot initialize torm metadata without passing driver')
driver.exec(`
driver.run(`
CREATE TABLE IF NOT EXISTS __torm_metadata__ (
singleton INTEGER NOT NULL UNIQUE DEFAULT 1 CHECK (singleton = 1), -- ensure only a single row can exist
torm_version TEXT NOT NULL,
version TEXT,
updated_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),
created_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW'))
)`)
driver.prepare(`INSERT INTO __torm_metadata__ (torm_version) VALUES (:torm_version)`).exec({
driver.prepare(`INSERT INTO __torm_metadata__ (torm_version) VALUES (:torm_version)`).run({
torm_version: this.version
})
}
Expand Down Expand Up @@ -159,14 +165,14 @@ ${columns.join('\n ')}
}
}

class Torm extends TormBase<sqlite_native.Database> {
public constructor(private db_path: string, private options: sqlite_native.DatabaseOptions = {}) {
class Torm extends TormBase<sqlite3.Database> {
public constructor(private db_path: string, private options: sqlite3.DatabaseOpenOptions = {}) {
super()
}

public async init(options?: InitOptions) {
const driver = new sqlite_native.Database(this.db_path, this.options)
await driver.connect()
const driver = new sqlite3.Database(this.db_path, this.options)
// await driver.connect()
this._init(driver, options)
this.schemas.version()
}
Expand All @@ -184,7 +190,7 @@ export {
Migration,
}

type Database = sqlite_native.Database
type Database = sqlite3.Database
export type { Database as Driver }
export { field }
export { Vars }
2 changes: 1 addition & 1 deletion src/statement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export type StatementResult<T extends SqlTemplateArg[]> =


type ColumnValue = string | number | bigint | Uint8Array | null;
interface RawRowData {
export interface RawRowData {
[field_name: string]: ColumnValue
}

Expand Down
5 changes: 3 additions & 2 deletions src/util.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Driver as SQLiteNativeDriver } from '../drivers/sqlite.ts'
import type { Driver as SQLite3Driver } from '../drivers/sqlite.ts'

type AllKeys<T> = T extends any ? keyof T : never;
type PickType<T, K extends AllKeys<T>> = T extends { [k in K]?: any }
Expand All @@ -15,7 +15,8 @@ export type ValueOf<T> = T[keyof T]
export type Constructor<T = {}> = new (...args: any[]) => T;

export type Driver =
| SQLiteNativeDriver
// | SQLiteNativeDriver
| SQLite3Driver


type TNullProperties<T> = {
Expand Down
2 changes: 1 addition & 1 deletion test/alias.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class Tag extends Model('tag', {
id INTEGER NOT NULL PRIMARY KEY,
name TEXT NOT NULL,
tag_group_id INTEGER NOT NULL,
FOREIGN KEY(tag_group_id) REFERENCES tag(tag_group_id)
FOREIGN KEY(tag_group_id) REFERENCES tag_group(id)
)`)
}

Expand Down

0 comments on commit 1d4db41

Please sign in to comment.