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: @quipodb/sqlite #4

Merged
merged 1 commit into from
Oct 17, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
25 changes: 25 additions & 0 deletions packages/sqlite/dist/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import sqlite from "better-sqlite3";
interface sqliteConstructor {
path: String;
primaryKey: any;
}
interface document {
[key: string]: string | number | Object | Array<any> | any;
}
export default class Sqlite {
sqlite: sqlite.Database;
private options;
private collectionName;
primaryKey: any;
constructor(options: sqliteConstructor);
createCollectionProvider(collectionName: String, cb?: Function): void;
private createColumnProvider;
createDocProvider(data: document, cb?: Function): any;
deleteCollectionProvider(collectionName: String, cb?: Function): void;
deleteDocProvider(data: document, cb?: Function): void;
getCollectionProvider(collectionName: String, cb?: Function): any[];
getDocProvider(data: document, cb?: Function): any;
getCollectionsProvider(cb?: Function): any[];
updateDocProvider(refData: document, data: document, cb?: Function): void;
}
export {};
114 changes: 114 additions & 0 deletions packages/sqlite/dist/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import sqlite from "better-sqlite3";
import fs from "fs-extra";
export default class Sqlite {
sqlite;
options;
collectionName;
primaryKey;
constructor(options) {
this.options = options;
this.options.path ??= "./databases/index.sqlite";
this.primaryKey = this.options.primaryKey;
if (!this.primaryKey)
throw new QuipodbSqliteError("PRIMARY KEY is expected", "@quipodb/sqlite -> Missing property");
try {
fs.ensureFileSync(`${this.options.path}`);
}
catch { }
this.sqlite = new sqlite(`${this.options.path}`, { fileMustExist: false });
}
createCollectionProvider(collectionName, cb = () => { }) {
this.collectionName = collectionName;
try {
this.sqlite.prepare(`CREATE TABLE IF NOT EXISTS ${collectionName} (${this.primaryKey} NONE PRIMARY KEY NOT NULL)`).run();
}
catch { }
}
createColumnProvider(columnName, dataType = "NONE") {
try {
this.sqlite.prepare(`ALTER TABLE ${this.collectionName} ADD ${columnName} ${dataType}`).run();
}
catch { }
}
createDocProvider(data, cb = () => { }) {
const KEYS = Object.keys(data);
let result;
const VALUES = Object.values(data).map((v) => JSON.stringify(v));
const COLUMNS = this.sqlite.prepare(`PRAGMA table_info(${this.collectionName})`).all();
KEYS.forEach(async (key) => {
if (!COLUMNS.map((v) => v.name).includes(key))
this.createColumnProvider(key, "NONE");
});
try {
if (!this.getDocProvider(data)) {
this.sqlite.prepare(`INSERT INTO ${this.collectionName} (${KEYS.join(", ")}) VALUES (${VALUES.map((v) => (v = "(?)")).join(",")})`).run(...VALUES);
}
else {
this.updateDocProvider(this.getDocProvider(data), data);
result = this.getDocProvider(data);
}
}
catch { }
cb(result);
return result;
}
deleteCollectionProvider(collectionName, cb = () => { }) {
this.sqlite.prepare(`DROP TABLE ${collectionName}`);
cb();
return;
}
deleteDocProvider(data, cb = () => { }) {
this.sqlite.prepare(`DELETE FROM ${this.collectionName} WHERE ${this.primaryKey} = (?)`).run(this.getDocProvider(data)[this.primaryKey]);
cb();
return;
}
getCollectionProvider(collectionName, cb = () => { }) {
const data = this.sqlite.prepare(`SELECT * FROM ${collectionName}`).all();
cb(data);
return data;
}
getDocProvider(data, cb = () => { }) {
const KEYS = Object.keys(data);
const VALUES = Object.values(data).map((v) => JSON.stringify(v));
const result = this.sqlite.prepare(`SELECT * from ${this.collectionName} WHERE ${KEYS.map((k, i) => (k += ` = (?)`))}`).get(...VALUES);
try {
Object.values(result).forEach((val, index) => {
result[Object.keys(result)[index]] = JSON.parse(val);
});
}
catch (e) {
console.log(e);
}
cb(result);
return result;
}
getCollectionsProvider(cb = () => { }) {
cb();
return this.sqlite
.prepare(`SELECT name FROM sqlite_master WHERE type='table'`)
.all()
.map((c) => c.name);
}
updateDocProvider(refData, data, cb = () => { }) {
const KEYS = Object.keys(data);
const VALUES = Object.values(data).map((v) => JSON.stringify(v));
const COLUMNS = this.sqlite.prepare(`PRAGMA table_info(${this.collectionName})`).all();
KEYS.forEach(async (key) => {
if (!COLUMNS.map((v) => v.name).includes(key))
this.createColumnProvider(key, "NONE");
});
const args = KEYS.map((v, i) => (v += ` = (?)`)).join(", ");
try {
this.sqlite.prepare(`UPDATE ${this.collectionName} SET ${args} WHERE ${this.primaryKey} = ${refData[`${this.primaryKey}`]}`).run(...VALUES);
}
catch { }
}
}
class QuipodbSqliteError extends Error {
constructor(message, name = null) {
super();
Error.captureStackTrace(this, this.constructor);
this.name = name ?? "@quipodb/sqlite";
this.message = message;
}
}
124 changes: 124 additions & 0 deletions packages/sqlite/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import sqlite from "better-sqlite3";
import fs from "fs-extra";

interface sqliteConstructor {
path: String;
primaryKey: any;
}
type fn = (data: Object[] | Object) => void;
interface document {
[key: string]: string | number | Object | Array<any> | any;
}
interface storage {
[collectioName: string]: document[];
}

export default class Sqlite {
public sqlite: sqlite.Database;
private options: sqliteConstructor;
private collectionName: String;
primaryKey: any;
constructor(options: sqliteConstructor) {
this.options = options;
this.options.path ??= "./databases/index.sqlite";
this.primaryKey = this.options.primaryKey;
if (!this.primaryKey) throw new QuipodbSqliteError("PRIMARY KEY is expected", "@quipodb/sqlite -> Missing property");

try {
fs.ensureFileSync(`${this.options.path}`);
} catch {}
this.sqlite = new sqlite(`${this.options.path}`, { fileMustExist: false });
}
createCollectionProvider(collectionName: String, cb: Function = () => {}) {
this.collectionName = collectionName;
try {
this.sqlite.prepare(`CREATE TABLE IF NOT EXISTS ${collectionName} (${this.primaryKey} NONE PRIMARY KEY NOT NULL)`).run();
} catch {}
}
private createColumnProvider(columnName: string, dataType: "TEXT" | "REAL" | "INTEGER" | "BLOB" | "NULL" | "NONE" = "NONE") {
try {
this.sqlite.prepare(`ALTER TABLE ${this.collectionName} ADD ${columnName} ${dataType}`).run();
} catch {}
}
createDocProvider(data: document, cb: Function = () => {}) {
const KEYS = Object.keys(data);
let result: any;
const VALUES = Object.values(data).map((v) => JSON.stringify(v));
const COLUMNS = this.sqlite.prepare(`PRAGMA table_info(${this.collectionName})`).all();
KEYS.forEach(async (key) => {
if (!COLUMNS.map((v: any) => v.name).includes(key)) this.createColumnProvider(key, "NONE");
});
try {
if (!this.getDocProvider(data)) {
this.sqlite.prepare(`INSERT INTO ${this.collectionName} (${KEYS.join(", ")}) VALUES (${VALUES.map((v) => (v = "(?)")).join(",")})`).run(...VALUES);
} else {
this.updateDocProvider(this.getDocProvider(data), data);
result = this.getDocProvider(data);
}
} catch {}

cb(result);

return result;
}
deleteCollectionProvider(collectionName: String, cb: Function = () => {}) {
this.sqlite.prepare(`DROP TABLE ${collectionName}`);
cb();
return;
}
deleteDocProvider(data: document, cb: Function = () => {}) {
this.sqlite.prepare(`DELETE FROM ${this.collectionName} WHERE ${this.primaryKey} = (?)`).run(this.getDocProvider(data)[this.primaryKey]);
cb();
return;
}
getCollectionProvider(collectionName: String, cb: Function = () => {}) {
const data = this.sqlite.prepare(`SELECT * FROM ${collectionName}`).all();
cb(data);
return data;
}
getDocProvider(data: document, cb: Function = () => {}) {
const KEYS = Object.keys(data);
const VALUES = Object.values(data).map((v) => JSON.stringify(v));
const result = this.sqlite.prepare(`SELECT * from ${this.collectionName} WHERE ${KEYS.map((k, i) => (k += ` = (?)`))}`).get(...VALUES);
try {
Object.values(result).forEach((val: any, index) => {
result[Object.keys(result)[index]] = JSON.parse(val);
});
} catch (e) {
console.log(e);
}

cb(result);

return result;
}
getCollectionsProvider(cb: Function = () => {}) {
cb();
return this.sqlite
.prepare(`SELECT name FROM sqlite_master WHERE type='table'`)
.all()
.map((c) => c.name);
}
updateDocProvider(refData: document, data: document, cb: Function = () => {}) {
const KEYS = Object.keys(data);
const VALUES = Object.values(data).map((v) => JSON.stringify(v));
const COLUMNS = this.sqlite.prepare(`PRAGMA table_info(${this.collectionName})`).all();
KEYS.forEach(async (key) => {
if (!COLUMNS.map((v: any) => v.name).includes(key)) this.createColumnProvider(key, "NONE");
});
const args = KEYS.map((v, i) => (v += ` = (?)`)).join(", ");

try {
this.sqlite.prepare(`UPDATE ${this.collectionName} SET ${args} WHERE ${this.primaryKey} = ${refData[`${this.primaryKey}`]}`).run(...VALUES);
} catch {}
}
}

class QuipodbSqliteError extends Error {
constructor(message: any, name: any = null) {
super();
Error.captureStackTrace(this, this.constructor);
this.name = name ?? "@quipodb/sqlite";
this.message = message;
}
}
39 changes: 39 additions & 0 deletions packages/sqlite/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"name": "@quipodb/sqlite",
"version": "1.0.0-beta.1",
"description": "Sqlite provider for this package",
"type": "module",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"scripts": {
"build": "tsc index.ts -t esnext -m esnext -d --allowSyntheticDefaultImports --moduleResolution node --outDir ./dist",
"publish-beta-public": "npm publish --tag beta --registry=https://registry.npmjs.com",
"publish-beta-private": "npm publish --tag beta",
"publish-public": "npm publish --registry=https://registry.npmjs.com",
"publish-private": "npm publish"
},
"keywords": [
"sqlite",
"quipodb",
"db",
"database",
"provider"
],
"author": {
"name": "Rajaneesh R",
"email": "rajaneeshr@proton.me",
"url": "https://r-rajaneesh.vercel.app"
},
"license": "ISC",
"dependencies": {
"better-sqlite3": "^7.6.2",
"fs-extra": "^10.1.0"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.0",
"@types/fs-extra": "^9.0.13",
"@types/lodash": "^4.14.182",
"@types/node": "^18.6.1",
"typescript": "^4.8.3"
}
}