quicklite
Version:
A lightweight ORM toolkit for SQLite in Node.js applications
76 lines • 2.77 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseEntity = void 0;
/**
* Base entity class that all entity models extend
*/
class BaseEntity {
/**
* Returns information about the database table for this entity
* @returns Table information
*/
static getTableInfo() {
throw new Error('Subclasses must implement getTableInfo method');
}
/**
* Generates a SQL statement to create the table for this entity
* @returns SQL CREATE TABLE statement
*/
static getCreateTableSQL() {
const tableInfo = this.getTableInfo();
const statements = [];
// Build column definitions
const columnDefs = tableInfo.columns.map(col => {
let definition = `${col.name} ${col.type}`;
if (col.primaryKey) {
definition += ' PRIMARY KEY';
if (col.autoIncrement) {
definition += ' AUTOINCREMENT';
}
}
if (col.notNull) {
definition += ' NOT NULL';
}
if (col.unique) {
definition += ' UNIQUE';
}
if (col.default !== undefined) {
if (typeof col.default === 'string') {
definition += ` DEFAULT '${col.default}'`;
}
else {
definition += ` DEFAULT ${col.default}`;
}
}
return definition;
});
// Add foreign key constraints
const foreignKeyDefs = tableInfo.columns
.filter(col => col.foreignKey)
.map(col => {
const fk = col.foreignKey;
let fkDef = `FOREIGN KEY(${col.name}) REFERENCES ${fk.table}(${fk.column})`;
if (fk.onDelete) {
fkDef += ` ON DELETE ${fk.onDelete}`;
}
if (fk.onUpdate) {
fkDef += ` ON UPDATE ${fk.onUpdate}`;
}
return fkDef;
});
// Combine column and foreign key definitions
const allDefs = [...columnDefs, ...foreignKeyDefs];
// Create main table
statements.push(`CREATE TABLE IF NOT EXISTS ${tableInfo.name} (${allDefs.join(', ')})`);
// Create indices
if (tableInfo.indices && tableInfo.indices.length > 0) {
for (const idx of tableInfo.indices) {
const uniqueClause = idx.unique ? 'UNIQUE ' : '';
statements.push(`CREATE ${uniqueClause}INDEX IF NOT EXISTS ${idx.name} ON ${tableInfo.name} (${idx.columns.join(', ')})`);
}
}
return statements.join(';\n');
}
}
exports.BaseEntity = BaseEntity;
//# sourceMappingURL=BaseEntity.js.map