@minatojs/driver-sqlite
Advanced tools
Comparing version 3.9.0 to 4.0.0-alpha.0
@@ -1,2 +0,3 @@ | ||
import { Database, Driver, Eval, Selection } from '@minatojs/core'; | ||
import { Dict } from 'cosmokit'; | ||
import { Driver, Eval, Field, Model, Selection, z } from 'minato'; | ||
import { Builder } from '@minatojs/sql-utils'; | ||
@@ -12,15 +13,23 @@ import init from '@minatojs/sql.js'; | ||
} | ||
export declare namespace SQLiteDriver { | ||
interface Config { | ||
path: string; | ||
} | ||
declare class SQLiteBuilder extends Builder { | ||
protected escapeMap: { | ||
"'": string; | ||
}; | ||
constructor(tables?: Dict<Model>); | ||
escape(value: any, field?: Field<any>): string; | ||
protected createElementQuery(key: string, value: any): string; | ||
protected jsonLength(value: string): string; | ||
protected jsonContains(obj: string, value: string): string; | ||
protected jsonUnquote(value: string, pure?: boolean): string; | ||
protected createAggr(expr: any, aggr: (value: string) => string, nonaggr?: (value: string) => string): string; | ||
protected groupArray(value: string): string; | ||
protected transformJsonField(obj: string, path: string): string; | ||
} | ||
export declare class SQLiteDriver extends Driver { | ||
export declare class SQLiteDriver extends Driver<SQLiteDriver.Config> { | ||
#private; | ||
config: SQLiteDriver.Config; | ||
static name: string; | ||
db: init.Database; | ||
sql: Builder; | ||
sql: SQLiteBuilder; | ||
beforeUnload?: () => void; | ||
private _transactionTask?; | ||
constructor(database: Database, config: SQLiteDriver.Config); | ||
/** synchronize table schema */ | ||
@@ -30,3 +39,4 @@ prepare(table: string, dropKeys?: string[]): Promise<void>; | ||
stop(): Promise<void>; | ||
drop(table?: string): Promise<any>; | ||
drop(table: string): Promise<void>; | ||
dropAll(): Promise<void>; | ||
stats(): Promise<Driver.Stats>; | ||
@@ -48,4 +58,10 @@ remove(sel: Selection.Mutable): Promise<{ | ||
upsert(sel: Selection.Mutable, data: any[], keys: string[]): Promise<{}>; | ||
withTransaction(callback: (session: Driver) => Promise<void>): Promise<void>; | ||
withTransaction(callback: (session: this) => Promise<void>): Promise<void>; | ||
} | ||
export declare namespace SQLiteDriver { | ||
interface Config { | ||
path: string; | ||
} | ||
const Config: z<Config>; | ||
} | ||
export default SQLiteDriver; |
@@ -57,8 +57,15 @@ "use strict"; | ||
var import_cosmokit = require("cosmokit"); | ||
var import_core = require("@minatojs/core"); | ||
var import_minato = require("minato"); | ||
var import_sql_utils = require("@minatojs/sql-utils"); | ||
var import_fs = require("fs"); | ||
var import_node_path = require("node:path"); | ||
var import_promises = require("node:fs/promises"); | ||
var import_sql = __toESM(require("@minatojs/sql.js")); | ||
var import_reggol = __toESM(require("reggol")); | ||
var logger = new import_reggol.default("sqlite"); | ||
// minato/packages/sqlite/src/locales/en-US.yml | ||
var en_US_default = { path: "Database path." }; | ||
// minato/packages/sqlite/src/locales/zh-CN.yml | ||
var zh_CN_default = { path: "数据库路径。" }; | ||
// minato/packages/sqlite/src/index.ts | ||
function getTypeDef({ type }) { | ||
@@ -160,3 +167,3 @@ switch (type) { | ||
const value = this.parseEval(expr, false); | ||
return `(select ${aggr((0, import_sql_utils.escapeId)("value"))} from json_each(${value}) ${(0, import_core.randomId)()})`; | ||
return `(select ${aggr((0, import_sql_utils.escapeId)("value"))} from json_each(${value}) ${(0, import_minato.randomId)()})`; | ||
} else { | ||
@@ -179,6 +186,5 @@ return super.createAggr(expr, aggr, nonaggr); | ||
var _joinKeys, joinKeys_fn, _exec, exec_fn, _all, all_fn, _get, get_fn, _export, export_fn, _run, run_fn, _update, update_fn, _create, create_fn; | ||
var _SQLiteDriver = class _SQLiteDriver extends import_core.Driver { | ||
constructor(database, config) { | ||
super(database); | ||
this.config = config; | ||
var SQLiteDriver = class extends import_minato.Driver { | ||
constructor() { | ||
super(...arguments); | ||
__privateAdd(this, _joinKeys); | ||
@@ -193,6 +199,5 @@ __privateAdd(this, _exec); | ||
__publicField(this, "db"); | ||
__publicField(this, "sql"); | ||
__publicField(this, "sql", new SQLiteBuilder()); | ||
__publicField(this, "beforeUnload"); | ||
__publicField(this, "_transactionTask"); | ||
this.sql = new SQLiteBuilder(); | ||
} | ||
@@ -248,3 +253,3 @@ /** synchronize table schema */ | ||
if (!columns.length) { | ||
logger.info("auto creating table %c", table); | ||
this.logger.info("auto creating table %c", table); | ||
__privateMethod(this, _run, run_fn).call(this, `CREATE TABLE ${(0, import_sql_utils.escapeId)(table)} (${[...columnDefs, ...indexDefs].join(", ")})`); | ||
@@ -266,3 +271,3 @@ } else if (shouldMigrate) { | ||
const fields = Object.keys(mapping).map(import_sql_utils.escapeId).join(", "); | ||
logger.info("auto migrating table %c", table); | ||
this.logger.info("auto migrating table %c", table); | ||
__privateMethod(this, _run, run_fn).call(this, `CREATE TABLE ${(0, import_sql_utils.escapeId)(temp)} (${[...columnDefs, ...indexDefs].join(", ")})`); | ||
@@ -278,3 +283,3 @@ try { | ||
} else if (alter.length) { | ||
logger.info("auto updating table %c", table); | ||
this.logger.info("auto updating table %c", table); | ||
for (const def of alter) { | ||
@@ -288,3 +293,3 @@ __privateMethod(this, _run, run_fn).call(this, `ALTER TABLE ${(0, import_sql_utils.escapeId)(table)} ${def}`); | ||
this.migrate(table, { | ||
error: logger.warn, | ||
error: this.logger.warn, | ||
before: (keys) => keys.every((key) => columns.some(({ name }) => name === key)), | ||
@@ -300,2 +305,5 @@ after: (keys) => dropKeys.push(...keys), | ||
async start() { | ||
if (this.config.path !== ":memory:") { | ||
this.config.path = (0, import_node_path.resolve)(this.ctx.baseDir, this.config.path); | ||
} | ||
const isBrowser = process.env.KOISHI_ENV === "browser"; | ||
@@ -308,3 +316,3 @@ const sqlite = await (0, import_sql.default)({ | ||
} else { | ||
const buffer = await import_fs.promises.readFile(this.config.path).catch(() => null); | ||
const buffer = await (0, import_promises.readFile)(this.config.path).catch(() => null); | ||
this.db = new sqlite.Database(this.config.path, buffer); | ||
@@ -324,3 +332,3 @@ if (isBrowser) { | ||
var _a; | ||
await new Promise((resolve) => setTimeout(resolve, 0)); | ||
await new Promise((resolve2) => setTimeout(resolve2, 0)); | ||
(_a = this.db) == null ? void 0 : _a.close(); | ||
@@ -333,7 +341,8 @@ if (this.beforeUnload) { | ||
async drop(table) { | ||
if (table) | ||
return __privateMethod(this, _run, run_fn).call(this, `DROP TABLE ${(0, import_sql_utils.escapeId)(table)}`); | ||
__privateMethod(this, _run, run_fn).call(this, `DROP TABLE ${(0, import_sql_utils.escapeId)(table)}`); | ||
} | ||
async dropAll() { | ||
const tables = Object.keys(this.database.tables); | ||
for (const table2 of tables) { | ||
__privateMethod(this, _run, run_fn).call(this, `DROP TABLE ${(0, import_sql_utils.escapeId)(table2)}`); | ||
for (const table of tables) { | ||
__privateMethod(this, _run, run_fn).call(this, `DROP TABLE ${(0, import_sql_utils.escapeId)(table)}`); | ||
} | ||
@@ -421,3 +430,3 @@ } | ||
} else { | ||
__privateMethod(this, _create, create_fn).call(this, table, (0, import_core.executeUpdate)(model.create(), item, ref)); | ||
__privateMethod(this, _create, create_fn).call(this, table, (0, import_minato.executeUpdate)(model.create(), item, ref)); | ||
result.inserted++; | ||
@@ -432,5 +441,5 @@ } | ||
await this._transactionTask; | ||
return this._transactionTask = new Promise((resolve, reject) => { | ||
return this._transactionTask = new Promise((resolve2, reject) => { | ||
__privateMethod(this, _run, run_fn).call(this, "BEGIN TRANSACTION"); | ||
callback(this).then(() => resolve(__privateMethod(this, _run, run_fn).call(this, "COMMIT")), (e) => (__privateMethod(this, _run, run_fn).call(this, "ROLLBACK"), reject(e))); | ||
callback(this).then(() => resolve2(__privateMethod(this, _run, run_fn).call(this, "COMMIT")), (e) => (__privateMethod(this, _run, run_fn).call(this, "ROLLBACK"), reject(e))); | ||
}); | ||
@@ -449,6 +458,6 @@ } | ||
stmt.free(); | ||
logger.debug("> %s", sql, params); | ||
this.logger.debug("> %s", sql, params); | ||
return result; | ||
} catch (e) { | ||
logger.warn("> %s", sql, params); | ||
this.logger.warn("> %s", sql, params); | ||
throw e; | ||
@@ -475,3 +484,3 @@ } | ||
const data = this.db.export(); | ||
import_fs.promises.writeFile(this.config.path, data); | ||
return (0, import_promises.writeFile)(this.config.path, data); | ||
}, "#export"); | ||
@@ -488,3 +497,3 @@ _run = new WeakSet(); | ||
const model = this.model(table); | ||
const modified = !(0, import_cosmokit.deepEqual)((0, import_cosmokit.clone)(data), (0, import_core.executeUpdate)(data, update, ref)); | ||
const modified = !(0, import_cosmokit.deepEqual)((0, import_cosmokit.clone)(data), (0, import_minato.executeUpdate)(data, update, ref)); | ||
if (!modified) | ||
@@ -513,4 +522,11 @@ return 0; | ||
}, "#create"); | ||
__name(_SQLiteDriver, "SQLiteDriver"); | ||
var SQLiteDriver = _SQLiteDriver; | ||
__publicField(SQLiteDriver, "name", "sqlite"); | ||
((SQLiteDriver2) => { | ||
SQLiteDriver2.Config = import_minato.z.object({ | ||
path: import_minato.z.string().role("path").required() | ||
}).i18n({ | ||
"en-US": en_US_default, | ||
"zh-CN": zh_CN_default | ||
}); | ||
})(SQLiteDriver || (SQLiteDriver = {})); | ||
var src_default = SQLiteDriver; | ||
@@ -517,0 +533,0 @@ // Annotate the CommonJS export names for ESM import in node: |
{ | ||
"name": "@minatojs/driver-sqlite", | ||
"version": "3.9.0", | ||
"version": "4.0.0-alpha.0", | ||
"description": "SQLite Driver for Minato", | ||
@@ -29,13 +29,12 @@ "main": "lib/index.js", | ||
"peerDependencies": { | ||
"@minatojs/core": "^2.9.0" | ||
"minato": "^3.0.0-alpha.0" | ||
}, | ||
"devDependencies": { | ||
"@minatojs/tests": "^1.9.0" | ||
"@minatojs/tests": "^2.0.0-alpha.0" | ||
}, | ||
"dependencies": { | ||
"@minatojs/sql-utils": "^4.3.0", | ||
"@minatojs/sql-utils": "^5.0.0-alpha.0", | ||
"@minatojs/sql.js": "^3.1.0", | ||
"cosmokit": "^1.5.2", | ||
"reggol": "^1.6.3" | ||
"cosmokit": "^1.5.2" | ||
} | ||
} |
import { clone, deepEqual, Dict, difference, isNullable, makeArray } from 'cosmokit' | ||
import { Database, Driver, Eval, executeUpdate, Field, Model, randomId, Selection } from '@minatojs/core' | ||
import { Driver, Eval, executeUpdate, Field, Model, randomId, Selection, z } from 'minato' | ||
import { Builder, escapeId } from '@minatojs/sql-utils' | ||
import { promises as fs } from 'fs' | ||
import { resolve } from 'node:path' | ||
import { readFile, writeFile } from 'node:fs/promises' | ||
import init from '@minatojs/sql.js' | ||
import Logger from 'reggol' | ||
import enUS from './locales/en-US.yml' | ||
import zhCN from './locales/zh-CN.yml' | ||
const logger = new Logger('sqlite') | ||
function getTypeDef({ type }: Field) { | ||
@@ -39,8 +39,2 @@ switch (type) { | ||
export namespace SQLiteDriver { | ||
export interface Config { | ||
path: string | ||
} | ||
} | ||
class SQLiteBuilder extends Builder { | ||
@@ -149,15 +143,11 @@ protected escapeMap = { | ||
export class SQLiteDriver extends Driver { | ||
export class SQLiteDriver extends Driver<SQLiteDriver.Config> { | ||
static name = 'sqlite' | ||
db!: init.Database | ||
sql: Builder | ||
sql = new SQLiteBuilder() | ||
beforeUnload?: () => void | ||
private _transactionTask? | ||
private _transactionTask?: Promise<void> | ||
constructor(database: Database, public config: SQLiteDriver.Config) { | ||
super(database) | ||
this.sql = new SQLiteBuilder() | ||
} | ||
/** synchronize table schema */ | ||
@@ -217,3 +207,3 @@ async prepare(table: string, dropKeys?: string[]) { | ||
if (!columns.length) { | ||
logger.info('auto creating table %c', table) | ||
this.logger.info('auto creating table %c', table) | ||
this.#run(`CREATE TABLE ${escapeId(table)} (${[...columnDefs, ...indexDefs].join(', ')})`) | ||
@@ -234,3 +224,3 @@ } else if (shouldMigrate) { | ||
const fields = Object.keys(mapping).map(escapeId).join(', ') | ||
logger.info('auto migrating table %c', table) | ||
this.logger.info('auto migrating table %c', table) | ||
this.#run(`CREATE TABLE ${escapeId(temp)} (${[...columnDefs, ...indexDefs].join(', ')})`) | ||
@@ -246,3 +236,3 @@ try { | ||
} else if (alter.length) { | ||
logger.info('auto updating table %c', table) | ||
this.logger.info('auto updating table %c', table) | ||
for (const def of alter) { | ||
@@ -256,3 +246,3 @@ this.#run(`ALTER TABLE ${escapeId(table)} ${def}`) | ||
this.migrate(table, { | ||
error: logger.warn, | ||
error: this.logger.warn, | ||
before: keys => keys.every(key => columns.some(({ name }) => name === key)), | ||
@@ -268,2 +258,5 @@ after: keys => dropKeys!.push(...keys), | ||
async start() { | ||
if (this.config.path !== ':memory:') { | ||
this.config.path = resolve(this.ctx.baseDir, this.config.path) | ||
} | ||
const isBrowser = process.env.KOISHI_ENV === 'browser' | ||
@@ -280,3 +273,3 @@ const sqlite = await init({ | ||
} else { | ||
const buffer = await fs.readFile(this.config.path).catch(() => null) | ||
const buffer = await readFile(this.config.path).catch(() => null) | ||
this.db = new sqlite.Database(this.config.path, buffer) | ||
@@ -313,6 +306,6 @@ if (isBrowser) { | ||
stmt.free() | ||
logger.debug('> %s', sql, params) | ||
this.logger.debug('> %s', sql, params) | ||
return result | ||
} catch (e) { | ||
logger.warn('> %s', sql, params) | ||
this.logger.warn('> %s', sql, params) | ||
throw e | ||
@@ -339,3 +332,3 @@ } | ||
const data = this.db.export() | ||
fs.writeFile(this.config.path, data) | ||
return writeFile(this.config.path, data) | ||
} | ||
@@ -349,4 +342,7 @@ | ||
async drop(table?: string) { | ||
if (table) return this.#run(`DROP TABLE ${escapeId(table)}`) | ||
async drop(table: string) { | ||
this.#run(`DROP TABLE ${escapeId(table)}`) | ||
} | ||
async dropAll() { | ||
const tables = Object.keys(this.database.tables) | ||
@@ -469,3 +465,3 @@ for (const table of tables) { | ||
async withTransaction(callback: (session: Driver) => Promise<void>) { | ||
async withTransaction(callback: (session: this) => Promise<void>) { | ||
if (this._transactionTask) await this._transactionTask | ||
@@ -479,2 +475,15 @@ return this._transactionTask = new Promise<void>((resolve, reject) => { | ||
export namespace SQLiteDriver { | ||
export interface Config { | ||
path: string | ||
} | ||
export const Config: z<Config> = z.object({ | ||
path: z.string().role('path').required(), | ||
}).i18n({ | ||
'en-US': enUS, | ||
'zh-CN': zhCN, | ||
}) | ||
} | ||
export default SQLiteDriver |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
55515
4
8
1005
4
2
+ Added@cordisjs/core@3.18.1(transitive)
+ Added@cordisjs/loader@0.13.1(transitive)
+ Added@cordisjs/logger@0.3.3(transitive)
+ Added@cordisjs/schema@0.1.1(transitive)
+ Added@cordisjs/timer@0.3.2(transitive)
+ Added@minatojs/sql-utils@5.5.0(transitive)
+ Addedargparse@2.0.1(transitive)
+ Addedcac@6.7.14(transitive)
+ Addedcordis@3.18.1(transitive)
+ Addeddotenv@16.4.5(transitive)
+ Addedjs-yaml@4.1.0(transitive)
+ Addedkleur@4.1.5(transitive)
+ Addedminato@3.6.1(transitive)
+ Addedschemastery@3.14.6(transitive)
- Removedreggol@^1.6.3
- Removed@minatojs/core@2.9.0(transitive)
- Removed@minatojs/sql-utils@4.3.0(transitive)