Skip to content

Instantly share code, notes, and snippets.

@leafac
Created April 20, 2021 10:50
Show Gist options
  • Save leafac/2f3f579c1c52d2675a2cdcc9be68acd1 to your computer and use it in GitHub Desktop.
Save leafac/2f3f579c1c52d2675a2cdcc9be68acd1 to your computer and use it in GitHub Desktop.
const { Database, sql } = require("@leafac/sqlite");
const database = new Database("my-application.db");
const migrations = [
() => {
database.execute(
sql`
CREATE TABLE "users" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"name" TEXT NOT NULL,
"age" INTEGER NOT NULL
);
`
);
},
() => {
database.execute(
sql`
CREATE TABLE "threads" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"title" TEXT NOT NULL,
"user" INTEGER NOT NULL REFERENCES "users" ON DELETE CASCADE
);
`
);
},
() => {
database.execute(
sql`
DROP TABLE "threads";
`
);
},
];
database.executeTransaction(() => {
for (const migration of migrations.slice(
database.pragma("user_version", { simple: true })
))
migration();
database.pragma(`user_version = ${migrations.length}`);
});
// better-sqlite3 way
// const statement = database.prepare(`INSERT INTO "users" ("name") VALUES (:name)`);
// statement.run({name: "Leandro Facchinetti"});
// @leafac/sqlite
// database.run(
// sql`INSERT INTO "users" ("name") VALUES (${"Leandro Facchinetti"})`
// );
// const userId = 1;
// const user = database.get(sql`SELECT "name" FROM "users" WHERE "id" = ${userId}`);
// console.log(user);
// const users = database.all(sql`SELECT "name" FROM "users"`);
// console.log(users);
// better-sqlite3 way
// const transaction = database.transaction(() => {
// database.run(
// sql`INSERT INTO "users" ("name") VALUES (${"Leandro Facchinetti"})`
// );
// const users = database.all(sql`SELECT "name" FROM "users"`);
// console.log(users);
// });
// transaction();
// @leafac/sqlite
// database.executeTransaction(() => {
// database.run(
// sql`INSERT INTO "users" ("name") VALUES (${"Leandro Facchinetti"})`
// );
// const users = database.all(sql`SELECT "name" FROM "users"`);
// console.log(users);
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment