Helper class for generating SQL query for class creation in SQLite format.
Npm :
npm install https://github.com/Sylvaner/SQLite-TableGenerator
Yarn :
yarn add https://github.com/Sylvaner/SQLite-TableGenerator
import { CLASSIC_COLUMN_ID, TableGenerator } from "sqlite-tablegenerator";
// Simple id, name table
const homeGenerator = new TableauGenerator('home');
homeGenerator.addColumn('name', 'INTEGER');
console.log(homeGenerator.getCreateTableQuery(true));
Result
CREATE TABLE home (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT
);
import { CLASSIC_COLUMN_ID, TableGenerator } from "sqlite-tablegenerator";
const personGenerator = new TableGenerator('person');
personGenerator.setTableOptions({ifNotExists: true});
personGenerator.addClassicIdColumn();
personGenerator.addColumn('name', 'TEXT', {notNull: true, default: 'John'});
personGenerator.addColumn('home', 'INTEGER', {notNull: true});
personGenerator.addForeignKey({
column: 'home',
targetTable: 'home',
targetColumn: 'id',
onDelete: 'CASCADE'
});
console.log(personGenerator.getCreateTableQuery(true));
Result
CREATE TABLE IF NOT EXISTS person (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL DEFAULT "John",
home INTEGER NOT NULL,
FOREIGN KEY(home) REFERENCES home(id) ON DELETE CASCADE
);
import { CLASSIC_COLUMN_ID, TableGenerator } from "sqlite-tablegenerator";
const homeGenerator = TableGenerator.fromData({
name: 'home',
columns: [
CLASSIC_COLUMN_ID,
{
name: 'name',
type: 'TEXT'
}
]
});
Result
CREATE TABLE home (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT
);
import { CLASSIC_COLUMN_ID, TableGenerator } from "sqlite-tablegenerator";
const homeGenerator = TableGenerator.fromData({
name: 'person',
options: {
ifNotExists: true
},
columns: [
CLASSIC_COLUMN_ID,
{
name: 'name',
type: 'TEXT',
options: {
notNull: true,
default: 'John'
}
},
{
name: 'home',
type: 'INTEGER',
options: {
notNull: true
}
}
],
foreignKeys: [
{
column: 'home',
targetTable: 'home',
targetColumn: 'id',
onDelete: 'CASCADE'
}
]
});
console.log(homeGenerator.getCreateTableQuery(true));
Result
CREATE TABLE IF NOT EXISTS person (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL DEFAULT "John",
home INTEGER NOT NULL,
FOREIGN KEY(home) REFERENCES home(id) ON DELETE CASCADE
);
To execute sample code
npm run sample