const sqlite = require('sqlite');
async function setup() {
const db = await sqlite.open('./mydb.sqlite');
await db.migrate({force: 'last'});
const people = await db.all('SELECT * FROM person');
console.log('ALL PEOPLE', JSON.stringify(people, null, 2));
const vehicles = await db.all('SELECT * FROM vehicle');
console.log('ALL VEHICLES', JSON.stringify(vehicles, null, 2));
}
setup();
Fix sqlite
database-test.js
constsqlite3=require('sqlite3');constsqlite=require('sqlite');asyncfunctionopenDb() {returnsqlite.open({ filename:'./mydb.sqlite', driver:sqlite3.Database, });}asyncfunctionsetup() {constdb=awaitopenDb();constpeople=awaitdb.all('SELECT * FROM Person');console.log('all person',JSON.stringify(people,null,2));constvehicle=awaitdb.all(`SELECT a.*, b.* FROM Person as a LEFT JOIN Vehicle as b ON a.id = b.ownerId`);console.log('all vehicles',JSON.stringify(vehicle,null,2));}setup();
Hoặc nếu để trong folder data
data\database-test.js
constsqlite3=require('sqlite3');constsqlite=require('sqlite');asyncfunctionopenDb() {returnsqlite.open({ filename:'./data/mydb.sqlite', driver:sqlite3.Database, });}asyncfunctionsetup() {constdb=awaitopenDb();constpeople=awaitdb.all('SELECT * FROM Person');console.log('all person',JSON.stringify(people,null,2));constvehicle=awaitdb.all(`SELECT a.*, b.* FROM Person as a LEFT JOIN Vehicle as b ON a.id = b.ownerId`);console.log('all vehicles',JSON.stringify(vehicle,null,2));}setup();
-- Up
CREATE TABLE Person (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
email TEXT
);
CREATE TABLE Vehicle (
id INTEGER PRIMARY KEY AUTOINCREMENT,
brand TEXT,
model TEXT,
ownerId INTEGER REFERENCES Person(id)
);
INSERT INTO Person (name, email) values ('bruno', 'phamngoctuong1805@gmail.com');
INSERT INTO Person (name, email) values ('jack', 'jack@antunes.pt');
INSERT INTO Vehicle (brand, model, ownerId) values('audi', 'R8', 1);
INSERT INTO Vehicle (brand, model, ownerId) values('audi', 'R6', 1);
INSERT INTO Vehicle (brand, model, ownerId) values('mercedes', 'benz', 2);
-- Down
DROP TABLE Person;
DROP TABLE Vehicle;