Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
cybertim committed Oct 29, 2020
0 parents commit dffb67a
Show file tree
Hide file tree
Showing 5 changed files with 246 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.vscode
main.ts
test.db
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 cybertim

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
55 changes: 55 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Small SQLite ORM

Very small Object-relational mapper (bare essential) to quickly setup embedded database in SQLite Deno/Typescript/Web.

## Learn By Examples

```typescript
// extend SmallSQLiteTable on your model
// it will add an incremental id by default
export class User extends SmallSQLiteTable {
userName = "";
address = "";
active = false;
age = 18;
}

const orm = new SmallSQLiteORM("test.db", [User]);

const user = new User();

user.address = "Denoland 12";
user.userName = "Joe Deno";
user.active = true; // Make Joe active
orm.save(user);

console.log(user.id); // Joe now has an id of 1 in our DB

for (let i = 0; i < 5; i++) {
orm.save(new User()); // Add some more users...
}

console.log(
orm.count(User),
); // Shows 6 total users in the db

let i = 0;
for (const u of orm.findMany(User)) {
u.age = 18 + (i++);
orm.save(u); // Update the age of all our users
}

console.log(
orm.countBy(User, "age > ?", [21]),
); // Only 2 users are now older than 21

const users = orm.findMany(User, "active = ?", [true]);

console.log(
users[0].userName,
); // Joe Deno! is our only active user
```

## Extra Features
- Automatically CREATE TABLE when database file is initialized
- Automatically ALTER TABLE when model class is changed (only ADD COLUMN)
164 changes: 164 additions & 0 deletions lib/SmallSQLite.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
import { DB } from "https://deno.land/x/sqlite/mod.ts";

export class SmallSQLiteTable {
id = -1;
}

export class SmallSQLiteORM<T extends SmallSQLiteTable> {
public db: DB;

constructor(dbName: string, entities: (new () => T)[]) {
this.db = new DB(dbName);
for (const entity of entities) {
const obj = new entity();
this.createTable(obj); // create the table if it is not yet there
const names = Object.getOwnPropertyNames(obj);
// retrieve a list of all columns known in the sqlite db
const data: string[] = [];
for (
const [loc, col] of this.db.query(
"PRAGMA table_info(" + obj.constructor.name.toLowerCase() + ");",
)
) {
data.push(col);
}
// check if there are new properties in the model compared to the table in sqlite
const n = names.filter((item) => !data.includes(item));
if (n.length > 0) {
this.alterTable(obj, n);
}
}
}

private columnInfo<T extends SmallSQLiteTable>(table: T, column: string) {
const v = Object.getOwnPropertyDescriptor(table, column);
if (column === "id") {
return "integer PRIMARY KEY AUTOINCREMENT NOT NULL";
} else if (typeof v?.value === "boolean") {
return "boolean NOT NULL DEFAULT false";
} else if (typeof v?.value === "string") {
return 'varchar DEFAULT ""';
} else if (typeof v?.value === "number") {
return "integer NOT NULL DEFAULT -1";
}
return undefined;
}

private alterTable<T extends SmallSQLiteTable>(table: T, columns: string[]) {
for (const column of columns) {
const statement = 'ALTER TABLE "' + table.constructor.name.toLowerCase() +
'\" ADD COLUMN ' + column + " " +
this.columnInfo<SmallSQLiteTable>(table, column);
this.db.query(statement);
}
}

private createTable<T extends SmallSQLiteTable>(table: T) {
const names = Object.getOwnPropertyNames(table);
let statement = 'CREATE TABLE IF NOT EXISTS "' +
table.constructor.name.toLowerCase() +
'" (';
for (const p of names) {
if (!statement.endsWith("(")) statement += ", ";
statement += '"' + p + '" ' + this.columnInfo<SmallSQLiteTable>(table, p);
}
statement += ")";
this.db.query(statement);
}

private insertRecord<T extends SmallSQLiteTable>(table: T) {
const names = Object.getOwnPropertyNames(table);
names.splice(0, 1);
const statement = 'INSERT INTO "' +
table.constructor.name.toLowerCase() +
'" (' + names.join(", ") + ") VALUES (" +
(new Array(names.length).fill("?")).join(", ") + ")";
const data = [];
for (const p of names) {
const v = Object.getOwnPropertyDescriptor(table, p);
data.push(v?.value);
}
this.db.query(statement, data);
table.id = this.db.lastInsertRowId;
}

private updateRecord<T extends SmallSQLiteTable>(table: T) {
const names = Object.getOwnPropertyNames(table);
names.splice(0, 1);
let statement = 'UPDATE "' +
table.constructor.name.toLowerCase() +
'" SET ';
const data = [];
for (const p of names) {
const v = Object.getOwnPropertyDescriptor(table, p);
if (!statement.endsWith("SET ")) statement += ", ";
statement += p + " = ?";
data.push(v?.value);
}
statement += " WHERE id = ?";
data.push(table.id);
this.db.query(statement, data);
}

private find<T extends SmallSQLiteTable>(
table: (new () => T),
whereClause?: string,
valueClause?: (boolean | string | number)[],
countOnly?: boolean,
): { count: number; objects: T[] } {
let select = "*";
if (countOnly) select = "COUNT(*) AS total";
const obj = new table();
const rows = this.db.query(
"SELECT " + select + ' FROM "' + obj.constructor.name + '"' +
(whereClause ? (" WHERE " + whereClause) : ""),
valueClause,
);
if (!countOnly) {
const names = rows.columns()
.map((item) => item.name);
const list: T[] = [];
for (const row of rows) {
const nobj = new table();
for (let i = 0; i < names.length; i++) {
Object.defineProperty(nobj, names[i], {
value: row[i],
});
}
list.push(<T> nobj);
}
return { count: list.length, objects: list };
} else {
return { count: <number> rows.next().value[0], objects: [] };
}
}

public save<T extends SmallSQLiteTable>(obj: T) {
if (obj.id === -1) this.insertRecord(obj);
else this.updateRecord(obj);
}

public findOne<T extends SmallSQLiteTable>(table: (new () => T), id: number) {
return this.find(table, "id = ?", [id]).objects[0];
}

public findMany<T extends SmallSQLiteTable>(
table: (new () => T),
whereClause?: string,
valueClause?: (boolean | string | number)[],
) {
return this.find(table, whereClause, valueClause).objects;
}

public count<T extends SmallSQLiteTable>(table: (new () => T)) {
return this.find(table, undefined, [], true).count;
}

public countBy<T extends SmallSQLiteTable>(
table: (new () => T),
whereClause?: string,
valueClause?: (boolean | string | number)[],
) {
return this.find(table, whereClause, valueClause, true).count;
}
}
3 changes: 3 additions & 0 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { SmallSQLiteORM } from "./lib/SmallSQLite.ts";

export * from "./lib/SmallSQLite.ts";

0 comments on commit dffb67a

Please sign in to comment.