UNPKG

scyllinx

Version:

A modern TypeScript ORM for ScyllaDB and SQL databases with Laravel-inspired syntax

2 lines (1 loc) 6.08 kB
import{QueryGrammar as e,DatabaseDriver as t}from"./index.min.js";import"node-cache";import"redis";import"util";import"@faker-js/faker";import"reflect-metadata";class s extends e{compileSelect(e){const t=[];if(e.ctes?.length&&t.push(`WITH ${this.compileCtes(e.ctes)}`),t.push(e.columns?.length?`SELECT ${e.columns.join(", ")}`:"SELECT *"),e.from&&t.push(`FROM ${this.wrapTable(e.from)}`),e.joins?.length&&t.push(this.compileJoins(e.joins)),e.wheres?.length&&t.push(`WHERE ${this.compileWheres(e.wheres)}`),e.groups?.length&&t.push(`GROUP BY ${e.groups.map(e=>this.wrapColumn(e)).join(", ")}`),e.havings?.length&&t.push(`HAVING ${this.compileWheres(e.havings)}`),e.orders?.length){const s=e.orders.map(e=>`${this.wrapColumn(e.column)} ${e.direction.toUpperCase()}`).join(", ");t.push(`ORDER BY ${s}`)}return null!=e.limit&&t.push(`LIMIT ${e.limit}`),null!=e.offset&&t.push(`OFFSET ${e.offset}`),t.join(" ")}compileInsert(e){const t=this.wrapTable(e.table),s=Object.keys(e.values).map(e=>this.wrapColumn(e)),n=Object.values(e.values).map(()=>"?");let r=`INSERT INTO ${t} (${s.join(", ")}) VALUES (${n.join(", ")})`;return e.onConflict&&(r+=` ON CONFLICT ${e.onConflict}`),r}compileUpdate(e){let t=`UPDATE ${this.wrapTable(e.table)} SET ${Object.keys(e.values).map(e=>`${this.wrapColumn(e)} = ?`).join(", ")}`;return e.wheres?.length&&(t+=` WHERE ${this.compileWheres(e.wheres)}`),t}compileDelete(e){let t=`DELETE FROM ${this.wrapTable(e.table)}`;return e.wheres?.length&&(t+=` WHERE ${this.compileWheres(e.wheres)}`),t}compileWheres(e){return e.map((e,t)=>{const s=t>0?` ${e.boolean.toUpperCase()} `:"";switch(e.type){case"basic":return`${s}${this.wrapColumn(e.column)} ${e.operator} ?`;case"in":return`${s}${this.wrapColumn(e.column)} IN (${e.values.map(()=>"?").join(", ")})`;case"notIn":return`${s}${this.wrapColumn(e.column)} NOT IN (${e.values.map(()=>"?").join(", ")})`;case"between":return`${s}${this.wrapColumn(e.column)} BETWEEN ? AND ?`;case"null":return`${s}${this.wrapColumn(e.column)} IS NULL`;case"notNull":return`${s}${this.wrapColumn(e.column)} IS NOT NULL`;case"exists":return`${s}EXISTS (${e.query})`;case"notExists":return`${s}NOT EXISTS (${e.query})`;case"raw":return`${s}${e.sql}`;default:return""}}).join("")}compileJoins(e){return e.map(e=>`${e.type.toUpperCase()} JOIN ${this.wrapTable(e.table)} ON ${this.compileWheres(e.wheres)}`).join(" ")}compileCtes(e){return e.map(e=>`${e.name} AS (${e.query})`).join(", ")}wrapTable(e){return e.includes(".")?e.split(".").map(e=>`"${e}"`).join("."):`"${e}"`}wrapColumn(e){return"*"===e?e:e.includes(".")?e.split(".").map(e=>"*"===e?e:`"${e}"`).join("."):`"${e}"`}parameter(e){return"?"}getColumnType(e){switch(e.type){case"integer":case"boolean":return"INTEGER";case"string":case"text":case"date":case"dateTime":case"timestamp":case"json":case"uuid":default:return"TEXT";case"decimal":case"float":case"double":return"REAL";case"binary":return"BLOB"}}formatDefault(e){return"string"==typeof e?`"${e}"`:String(e)}compileColumnDefinition(e){let t=`${this.wrapColumn(e.name)} ${this.getColumnType(e)}`;return e.primary&&(t+=" PRIMARY KEY"),e.autoIncrement&&(t+=" AUTOINCREMENT"),!1===e.nullable&&(t+=" NOT NULL"),e.unique&&(t+=" UNIQUE"),void 0!==e.default&&(t+=` DEFAULT ${this.formatDefault(e.default)}`),t}compileCreateTable(e){return`CREATE TABLE ${this.wrapTable(e.name)} (${e.columns.map(e=>this.compileColumnDefinition(e)).join(", ")})`}compileAlterTable(e){if(!e.columns?.length)throw new Error("No columns provided for ALTER TABLE.");return`ALTER TABLE ${this.wrapTable(e.name)} ${e.columns.map(e=>{let t=`ADD COLUMN ${this.wrapColumn(e.name)} ${this.getColumnType(e)}`;return!1===e.nullable&&(t+=" NOT NULL"),void 0!==e.default&&(t+=` DEFAULT ${this.formatDefault(e.default)}`),e.unique&&(t+=" UNIQUE"),t}).join(", ")}`}compileTableExists(e){return`PRAGMA table_info(${this.wrapTable(e)})`}compileColumnExists(e,t){return this.compileTableExists(e)}async rename(e,t){const s=`ALTER TABLE ${this.wrapTable(e)} RENAME TO ${this.wrapTable(t)}`;throw new Error(`Execute SQL: ${s}`)}}class n extends t{sqliteModule;db=null;grammar;transactionLevel=0;constructor(e){super(e),this.grammar=new s}async connect(){this.sqliteModule=await import("better-sqlite3");const e=this.sqliteModule.default,t=this.config.database||":memory:";this.db=new e(t,{verbose:this.config.verbose?console.log:void 0,fileMustExist:this.config.fileMustExist||!1,timeout:this.config.timeout||5e3,readonly:this.config.readonly||!1,...this.config}),this.db.pragma("foreign_keys = ON"),this.db.pragma("journal_mode = WAL"),this.connection=this.db}async disconnect(){this.db&&(this.db.close(),this.connection=null)}async query(e,t=[]){if(!this.db)throw new Error("SQLite connection is not initialized");try{const s=this.db.prepare(e);if(e.trim().toLowerCase().startsWith("select")){const e=s.all(t||[]);return{rows:e,rowCount:e.length}}{const e=s.run(t||[]);return{rows:[],rowCount:e.changes,insertId:e.lastInsertRowid,affectedRows:e.changes}}}catch(e){throw new Error(`SQLite query failed: ${e.message}`)}}async prepare(e){return new r(this.db,e)}async beginTransaction(){0===this.transactionLevel&&this.db.exec("BEGIN TRANSACTION"),this.transactionLevel++,this.inTransaction=!0}async commit(){this.transactionLevel>0&&(this.transactionLevel--,0===this.transactionLevel&&(this.db.exec("COMMIT"),this.inTransaction=!1))}async rollback(){this.transactionLevel>0&&(this.db.exec("ROLLBACK"),this.transactionLevel=0,this.inTransaction=!1)}async getLastInsertId(){const e=this.db.prepare("SELECT last_insert_rowid() as id").get();return e?.id||""}escape(e){return null==e?"NULL":"string"==typeof e?`'${e.replace(/'/g,"''")}'`:"boolean"==typeof e?e?"1":"0":e instanceof Date?`'${e.toISOString()}'`:String(e)}getGrammar(){return this.grammar}supportsFeature(e){switch(e){case"returning":default:return!1;case"batch":case"prepared-statements":return!0}}}class r{stmt;constructor(e,t){this.stmt=e.prepare(t)}async execute(e){const t=this.stmt.run(e||[]);return{rows:[],rowCount:t.changes,affectedRows:t.changes}}async close(){}}export{n as SQLiteDriver};