@suger-tdy/electron-sqlite3
Version:
Personal electron sqlite3 Utils For Electron
85 lines (83 loc) • 2.13 kB
JavaScript
// src/db.ts
import path2 from "path";
import { existsSync, mkdirSync } from "fs";
import SqliteDatabase from "better-sqlite3";
import Logger from "electron-log";
import { knex } from "knex";
// src/constant.ts
import path from "path";
import { app } from "electron";
var USER_DATA_DIR = app.getPath("userData");
var USER_DB_DIR = path.join(USER_DATA_DIR, "teddy_db");
var USER_STORE_DIR = path.join(USER_DATA_DIR, "teddy_storage");
var DB_LIST = {
IMAGE_LINK: "i_link"
};
// src/db.ts
var SqliteBuilder = class {
constructor(_options) {
this.sqliteDB = null;
this.knexInstance = null;
this._init(_options);
}
static getInstance(options = {
dbName: DB_LIST.IMAGE_LINK
}) {
if (!this.instance)
this.instance = new SqliteBuilder(options);
return this.instance;
}
_dbPath(name) {
if (!existsSync(USER_DB_DIR))
mkdirSync(USER_DB_DIR, { recursive: true });
return path2.join(USER_DB_DIR, `${name}.db`);
}
_init(opt) {
this.initDB(opt.dbName);
this.initSqlParser();
}
initDB(dbName) {
const absDbPath = this._dbPath(dbName);
this.sqliteDB = new SqliteDatabase(absDbPath);
Logger.info(`[DB] init database ${absDbPath} completed`);
return this.sqliteDB;
}
db(name = DB_LIST.IMAGE_LINK) {
if (!this.sqliteDB)
this.initDB(name);
return this.sqliteDB;
}
initSqlParser() {
const config = {
client: "better-sqlite3",
connection: {
filename: ":memory:"
},
useNullAsDefault: true
};
this.knexInstance = knex(config);
}
sqlParser() {
if (!this.knexInstance) {
const config = {
client: "better-sqlite3",
connection: {
filename: ":memory:"
},
useNullAsDefault: true
};
this.knexInstance = knex(config);
}
return this.knexInstance;
}
async dispose() {
var _a, _b;
(_a = this.sqliteDB) == null ? void 0 : _a.close();
await ((_b = this.knexInstance) == null ? void 0 : _b.destroy());
}
};
var db_default = SqliteBuilder;
export {
db_default as SqliteBuilder
};
//# sourceMappingURL=index.mjs.map