sqlike
v0.0.78
Published
Simplification of SQLite with strong typing of table fields (taking advantage on TypeScript typing)
Downloads
8
Readme
This package simplifies SQLite usage and ties your TS classes and tables together, so you don't have to create tables or care if your Table Class fields and their types match the corresponding SQLite table - the SQLike will do it for you automatically! And still, you have access to the raw SQL queries when you need these.
Installation
npm i sqlike -S
Usage
/**
* this is a "typed table" object. The class name is used as a table name
* and its fields - as columns.
*/
class User extends STable {
/** @idx decorator defines that the index will be created for this
* field in SQLite */
@idx user = ``;/** must init with an empty string, to let the SQLike
know this is of a TEXT type */
age = 0;/** must init with an number, to let the SQLike know this
is of a REAL type */
blueEyes = false;
email = ``;
@uniq passportNumber = ``;/** using "@uniq" to let the system know
this is a UNIQUE fields in SQLite */
notUsed!: string;/** if you don't init the property - it will
NOT become a field in the table */
greetings=()=>`Hello, I am ${this.user}, ${this.age} y.o,
my ID is ${this.passportNumber}`
}
/// opening database. Will create if none:
const like = await SQLike.open(`./testDb.sqlite`);
/// opening table "User". Will create new if no table exists.
/// note: a class name "User" becomes a table name in SQLite database
const users = await like.table<User>(User);
/// let`s create and insert one user
const user = new User();
user.user = `John`;
user.age = 22;
user.blueEyes = true;
user.passportNumber = `` + Math.random();
await users.insertOne(user);
/// now let`s select one
const someone = await users.selectOne(`age=?`, 22);
/// "users.select()" will create an instance of a "User" class,
/// so all its defined methods are callable:
/// prints "Hello, my name is John, 22 y.o., my ID is 0.3493947247"
console.log(someone.greetings())
/// let`s change and update:
someone.email = `hi.${Math.random()}@example.com`;
const randAge = Math.random() * 20 + 10;
someone.age = randAge;
await users.updateOne(someone);
/// now let`s check if it did actually update:
const somebody = await users.selectOne(`email = ?`, someone.email);
/// prints "Hello, my name is John, 18.94728437 y.o., my ID is 0.3493947247"
console.log(someone.greetings())
That simple. No "sequential", no need to track if your field names in strings match your fields - here you take advantage on static TypeScript typing.