bettersqlkeza 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +115 -0
  3. package/dist/bettersql.d.ts +107 -0
  4. package/dist/bettersql.d.ts.map +1 -0
  5. package/dist/bettersql.js +181 -0
  6. package/dist/bettersql.js.map +1 -0
  7. package/dist/delete-builder.d.ts +58 -0
  8. package/dist/delete-builder.d.ts.map +1 -0
  9. package/dist/delete-builder.js +129 -0
  10. package/dist/delete-builder.js.map +1 -0
  11. package/dist/index.d.ts +67 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +77 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/insert-builder.d.ts +62 -0
  16. package/dist/insert-builder.d.ts.map +1 -0
  17. package/dist/insert-builder.js +136 -0
  18. package/dist/insert-builder.js.map +1 -0
  19. package/dist/model.d.ts +185 -0
  20. package/dist/model.d.ts.map +1 -0
  21. package/dist/model.js +404 -0
  22. package/dist/model.js.map +1 -0
  23. package/dist/query-builder.d.ts +140 -0
  24. package/dist/query-builder.d.ts.map +1 -0
  25. package/dist/query-builder.js +298 -0
  26. package/dist/query-builder.js.map +1 -0
  27. package/dist/raw-query-builder.d.ts +70 -0
  28. package/dist/raw-query-builder.d.ts.map +1 -0
  29. package/dist/raw-query-builder.js +118 -0
  30. package/dist/raw-query-builder.js.map +1 -0
  31. package/dist/result-proxy.d.ts +63 -0
  32. package/dist/result-proxy.d.ts.map +1 -0
  33. package/dist/result-proxy.js +166 -0
  34. package/dist/result-proxy.js.map +1 -0
  35. package/dist/types.d.ts +87 -0
  36. package/dist/types.d.ts.map +1 -0
  37. package/dist/types.js +6 -0
  38. package/dist/types.js.map +1 -0
  39. package/dist/update-builder.d.ts +59 -0
  40. package/dist/update-builder.d.ts.map +1 -0
  41. package/dist/update-builder.js +136 -0
  42. package/dist/update-builder.js.map +1 -0
  43. package/dist/where-builder.d.ts +18 -0
  44. package/dist/where-builder.d.ts.map +1 -0
  45. package/dist/where-builder.js +117 -0
  46. package/dist/where-builder.js.map +1 -0
  47. package/package.json +48 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 αѕтяσ
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,115 @@
1
+ # @keza/BetterSQL
2
+
3
+ A minimal high performance ORM for Node.js using better-sqlite3.
4
+
5
+ Thin and SQL first with no decorators, no reflection, no runtime magic. Built directly on better-sqlite3 with cached prepared statements, transaction support, and strong TypeScript inference.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @keza/bettersql better-sqlite3
11
+ ```
12
+
13
+ ## Quick Start
14
+
15
+ ```typescript
16
+ import { BetterSQL } from '@keza/bettersql'
17
+
18
+ const ql = new BetterSQL({ filename: ':memory:' })
19
+
20
+ const User = ql.define('user', {
21
+ id: { type: 'INTEGER', primary: true, autoIncrement: true },
22
+ email: { type: 'TEXT', unique: true },
23
+ username: { type: 'TEXT' },
24
+ created_at: { type: 'INTEGER' }
25
+ })
26
+
27
+ // Insert a new user
28
+ const user = User.insert({
29
+ email: 'alice@example.com',
30
+ username: 'alice',
31
+ created_at: Date.now()
32
+ })
33
+
34
+ // Query users
35
+ const found = User.find({ email: 'alice@example.com' }).first()
36
+ const all = User.find().all()
37
+ const byId = User.findById(1)
38
+
39
+ // Fluent query builder
40
+ const active = User.query().where('status', '=', 'active').orderBy('created_at', 'DESC').limit(10).all()
41
+
42
+ // Chainable methods on results
43
+ const contact = User.query().where('id', '=', 1).first()
44
+ contact?.delete()
45
+ contact?.update({ username: 'new_name' })
46
+
47
+ // Raw SQL queries
48
+ const results = User.query("SELECT * FROM user WHERE status = 'active'")
49
+ const paramResults = User.query('SELECT * FROM user WHERE id = ?', [1])
50
+ ```
51
+
52
+ ## Features
53
+
54
+ - **Type-safe**: Full TypeScript support with inferred types
55
+ - **Fluent API**: Chainable query builders for SELECT, INSERT, UPDATE, DELETE
56
+ - **Cached statements**: Prepared statements are automatically cached
57
+ - **Transactions**: Full transaction support with automatic rollback
58
+ - **Result proxies**: Query results have chainable methods like `.delete()`, `.update()`
59
+ - **WAL mode**: Enabled by default for better concurrent performance
60
+
61
+ ## API Reference
62
+
63
+ ### BetterSQL
64
+
65
+ ```typescript
66
+ const ql = new BetterSQL({
67
+ filename: string, // Database file path or ":memory:"
68
+ wal?: boolean, // Enable WAL mode (default: true)
69
+ });
70
+
71
+ ql.define(tableName, schema) // Define a model
72
+ ql.getModel(tableName) // Get existing model
73
+ ql.exec(sql) // Execute raw SQL
74
+ ql.query(sql, params?) // Query with results
75
+ ql.transaction(callback) // Run in transaction
76
+ ql.close() // Close connection
77
+ ```
78
+
79
+ ### Model
80
+
81
+ ```typescript
82
+ Model.insert(data) // Insert record
83
+ Model.insertBuilder(data) // Fluent insert builder
84
+ Model.find(where?) // Query builder
85
+ Model.findById(id) // Find by primary key
86
+ Model.update(where, data) // Update records
87
+ Model.delete(where) // Delete records
88
+ Model.count(where?) // Count records
89
+ Model.all() // Get all records
90
+ Model.upsert(data) // Insert or replace
91
+ ```
92
+
93
+ ### Query Builder
94
+
95
+ ```typescript
96
+ Model.find()
97
+ .where(conditions) // AND conditions
98
+ .where(col, op, val) // Comparison operator
99
+ .orWhere(conditions) // OR conditions
100
+ .orderBy(column, direction) // ORDER BY
101
+ .limit(count) // LIMIT
102
+ .offset(count) // OFFSET
103
+ .select(...columns) // Select columns
104
+ .distinct() // DISTINCT
105
+ .groupBy(...columns) // GROUP BY
106
+ .having(conditions) // HAVING
107
+ .all() // Execute and get all
108
+ .first() // Get first result
109
+ .count() // Get count
110
+ .exists() // Check existence
111
+ ```
112
+
113
+ ## License
114
+
115
+ MIT
@@ -0,0 +1,107 @@
1
+ import Database from 'better-sqlite3';
2
+ import type { BetterSQLConfig, SchemaDefinition, SQLQueryBindings, TransactionCallback } from './types';
3
+ import { Model } from './model';
4
+ /**
5
+ * BetterSQL - A minimal high performance ORM for Node.js using better-sqlite3
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import { BetterSQL } from "@keza/bettersql";
10
+ *
11
+ * const ql = new BetterSQL({ filename: ":memory:" });
12
+ *
13
+ * const User = ql.define("user", {
14
+ * id: { type: "INTEGER", primary: true, autoIncrement: true },
15
+ * email: { type: "TEXT", unique: true },
16
+ * username: { type: "TEXT" },
17
+ * created_at: { type: "INTEGER" }
18
+ * });
19
+ *
20
+ * const user = User.insert({ email: "a@mail.com", username: "alice", created_at: Date.now() });
21
+ * const found = User.find({ email: "a@mail.com" }).first();
22
+ * ```
23
+ */
24
+ export declare class BetterSQL {
25
+ private db;
26
+ private config;
27
+ private statementCache;
28
+ private models;
29
+ constructor(config: BetterSQLConfig);
30
+ /**
31
+ * Define a new model/table with the given schema
32
+ * Automatically creates the table if it doesn't exist
33
+ */
34
+ define<S extends SchemaDefinition>(tableName: string, schema: S): Model<S>;
35
+ /**
36
+ * Get a previously defined model by table name
37
+ */
38
+ getModel<S extends SchemaDefinition>(tableName: string): Model<S> | undefined;
39
+ /**
40
+ * Execute a raw SQL query
41
+ */
42
+ exec(sql: string): void;
43
+ /**
44
+ * Execute a raw SQL query with parameters and return results
45
+ */
46
+ query<T = unknown>(sql: string, params?: SQLQueryBindings[]): T[];
47
+ /**
48
+ * Execute a raw SQL query with parameters and return the first result
49
+ */
50
+ queryOne<T = unknown>(sql: string, params?: SQLQueryBindings[]): T | null;
51
+ /**
52
+ * Execute operations within a transaction
53
+ * Automatically commits on success, rolls back on error
54
+ */
55
+ transaction<R>(callback: TransactionCallback<R>): R;
56
+ /**
57
+ * Begin a manual transaction
58
+ */
59
+ beginTransaction(): void;
60
+ /**
61
+ * Commit the current transaction
62
+ */
63
+ commit(): void;
64
+ /**
65
+ * Rollback the current transaction
66
+ */
67
+ rollback(): void;
68
+ /**
69
+ * Get the underlying better-sqlite3 Database instance
70
+ */
71
+ getDatabase(): Database.Database;
72
+ /**
73
+ * Close the database connection and clear caches
74
+ */
75
+ close(): void;
76
+ /**
77
+ * Check if the database connection is open
78
+ */
79
+ isOpen(): boolean;
80
+ /**
81
+ * Check if currently in a transaction
82
+ */
83
+ inTransaction(): boolean;
84
+ /**
85
+ * Create a deferred transaction function
86
+ * Uses "BEGIN DEFERRED" - locks are acquired lazily
87
+ */
88
+ transactionDeferred<R>(callback: TransactionCallback<R>): R;
89
+ /**
90
+ * Create an immediate transaction function
91
+ * Uses "BEGIN IMMEDIATE" - write lock is acquired immediately
92
+ */
93
+ transactionImmediate<R>(callback: TransactionCallback<R>): R;
94
+ /**
95
+ * Create an exclusive transaction function
96
+ * Uses "BEGIN EXCLUSIVE" - exclusive lock, no other connections can read or write
97
+ */
98
+ transactionExclusive<R>(callback: TransactionCallback<R>): R;
99
+ /**
100
+ * Get database statistics
101
+ */
102
+ stats(): {
103
+ tables: number;
104
+ cachedStatements: number;
105
+ };
106
+ }
107
+ //# s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OAEG;IACH,MAAM,IAAI,IAAI;IAId;;OAEG;IACH,QAAQ,IAAI,IAAI;IAIhB;;OAEG;IACH,WAAW,IAAI,QAAQ,CAAC,QAAQ;IAIhC;;OAEG;IACH,KAAK,IAAI,IAAI;IAMb;;OAEG;IACH,MAAM,IAAI,OAAO;IAIjB;;OAEG;IACH,aAAa,IAAI,OAAO;IAIxB;;;OAGG;IACH,mBAAmB,CAAC,CAAC,EAAE,QAAQ,EAAE,mBAAmB,CAAC,CAAC,CAAC,GAAG,CAAC;IAK3D;;;OAGG;IACH,oBAAoB,CAAC,CAAC,EAAE,QAAQ,EAAE,mBAAmB,CAAC,CAAC,CAAC,GAAG,CAAC;IAK5D;;;OAGG;IACH,oBAAoB,CAAC,CAAC,EAAE,QAAQ,EAAE,mBAAmB,CAAC,CAAC,CAAC,GAAG,CAAC;IAK5D;;OAEG;IACH,KAAK,IAAI;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,gBAAgB,EAAE,MAAM,CAAA;KAAE;CAMtD"}
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.BetterSQL = void 0;
7
+ const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
8
+ const model_1 = require("./model");
9
+ /**
10
+ * BetterSQL - A minimal high performance ORM for Node.js using better-sqlite3
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * import { BetterSQL } from "@keza/bettersql";
15
+ *
16
+ * const ql = new BetterSQL({ filename: ":memory:" });
17
+ *
18
+ * const User = ql.define("user", {
19
+ * id: { type: "INTEGER", primary: true, autoIncrement: true },
20
+ * email: { type: "TEXT", unique: true },
21
+ * username: { type: "TEXT" },
22
+ * created_at: { type: "INTEGER" }
23
+ * });
24
+ *
25
+ * const user = User.insert({ email: "a@mail.com", username: "alice", created_at: Date.now() });
26
+ * const found = User.find({ email: "a@mail.com" }).first();
27
+ * ```
28
+ */
29
+ class BetterSQL {
30
+ db;
31
+ config;
32
+ statementCache;
33
+ models;
34
+ constructor(config) {
35
+ this.config = {
36
+ wal: true,
37
+ ...config
38
+ };
39
+ // Create database connection
40
+ this.db = new better_sqlite3_1.default(this.config.filename);
41
+ // Enable WAL mode for better concurrent performance
42
+ if (this.config.wal) {
43
+ this.db.pragma('journal_mode = WAL');
44
+ }
45
+ // Initialize caches
46
+ this.statementCache = new Map();
47
+ this.models = new Map();
48
+ }
49
+ /**
50
+ * Define a new model/table with the given schema
51
+ * Automatically creates the table if it doesn't exist
52
+ */
53
+ define(tableName, schema) {
54
+ // Generate and execute CREATE TABLE SQL
55
+ const createSQL = (0, model_1.generateCreateTableSQL)(tableName, schema);
56
+ this.db.exec(createSQL);
57
+ // Create and cache the model
58
+ const model = new model_1.Model(this.db, tableName, schema, this.statementCache);
59
+ this.models.set(tableName, model);
60
+ return model;
61
+ }
62
+ /**
63
+ * Get a previously defined model by table name
64
+ */
65
+ getModel(tableName) {
66
+ return this.models.get(tableName);
67
+ }
68
+ /**
69
+ * Execute a raw SQL query
70
+ */
71
+ exec(sql) {
72
+ this.db.exec(sql);
73
+ }
74
+ /**
75
+ * Execute a raw SQL query with parameters and return results
76
+ */
77
+ query(sql, params) {
78
+ const stmt = this.db.prepare(sql);
79
+ if (params && params.length > 0) {
80
+ return stmt.all(...params);
81
+ }
82
+ return stmt.all();
83
+ }
84
+ /**
85
+ * Execute a raw SQL query with parameters and return the first result
86
+ */
87
+ queryOne(sql, params) {
88
+ const stmt = this.db.prepare(sql);
89
+ if (params && params.length > 0) {
90
+ return stmt.get(...params) || null;
91
+ }
92
+ return stmt.get() || null;
93
+ }
94
+ /**
95
+ * Execute operations within a transaction
96
+ * Automatically commits on success, rolls back on error
97
+ */
98
+ transaction(callback) {
99
+ const transaction = this.db.transaction(callback);
100
+ return transaction();
101
+ }
102
+ /**
103
+ * Begin a manual transaction
104
+ */
105
+ beginTransaction() {
106
+ this.db.exec('BEGIN TRANSACTION');
107
+ }
108
+ /**
109
+ * Commit the current transaction
110
+ */
111
+ commit() {
112
+ this.db.exec('COMMIT');
113
+ }
114
+ /**
115
+ * Rollback the current transaction
116
+ */
117
+ rollback() {
118
+ this.db.exec('ROLLBACK');
119
+ }
120
+ /**
121
+ * Get the underlying better-sqlite3 Database instance
122
+ */
123
+ getDatabase() {
124
+ return this.db;
125
+ }
126
+ /**
127
+ * Close the database connection and clear caches
128
+ */
129
+ close() {
130
+ this.statementCache.clear();
131
+ this.models.clear();
132
+ this.db.close();
133
+ }
134
+ /**
135
+ * Check if the database connection is open
136
+ */
137
+ isOpen() {
138
+ return this.db.open;
139
+ }
140
+ /**
141
+ * Check if currently in a transaction
142
+ */
143
+ inTransaction() {
144
+ return this.db.inTransaction;
145
+ }
146
+ /**
147
+ * Create a deferred transaction function
148
+ * Uses "BEGIN DEFERRED" - locks are acquired lazily
149
+ */
150
+ transactionDeferred(callback) {
151
+ const transaction = this.db.transaction(callback);
152
+ return transaction.deferred();
153
+ }
154
+ /**
155
+ * Create an immediate transaction function
156
+ * Uses "BEGIN IMMEDIATE" - write lock is acquired immediately
157
+ */
158
+ transactionImmediate(callback) {
159
+ const transaction = this.db.transaction(callback);
160
+ return transaction.immediate();
161
+ }
162
+ /**
163
+ * Create an exclusive transaction function
164
+ * Uses "BEGIN EXCLUSIVE" - exclusive lock, no other connections can read or write
165
+ */
166
+ transactionExclusive(callback) {
167
+ const transaction = this.db.transaction(callback);
168
+ return transaction.exclusive();
169
+ }
170
+ /**
171
+ * Get database statistics
172
+ */
173
+ stats() {
174
+ return {
175
+ tables: this.models.size,
176
+ cachedStatements: this.statementCache.size
177
+ };
178
+ }
179
+ }
180
+ exports.BetterSQL = BetterSQL;
181
+ //# sourceMappingURL=bettersql.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bettersql.js","sourceRoot":"","sources":["../src/bettersql.ts"],"names":[],"mappings":";;;;;;AAAA,oEAAq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O,IAAI,CAAC,EAAE,CAAA;IAChB,CAAC;IAED;;OAEG;IACH,KAAK;QACH,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,CAAA;QAC3B,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;QACnB,IAAI,CAAC,EAAE,CAAC,KAAK,EAAE,CAAA;IACjB,CAAC;IAED;;OAEG;IACH,MAAM;QACJ,OAAO,IAAI,CAAC,EAAE,CAAC,IAAI,CAAA;IACrB,CAAC;IAED;;OAEG;IACH,aAAa;QACX,OAAO,IAAI,CAAC,EAAE,CAAC,aAAa,CAAA;IAC9B,CAAC;IAED;;;OAGG;IACH,mBAAmB,CAAI,QAAgC;QACrD,MAAM,WAAW,GAAG,IAAI,CAAC,EAAE,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAA;QACjD,OAAO,WAAW,CAAC,QAAQ,EAAE,CAAA;IAC/B,CAAC;IAED;;;OAGG;IACH,oBAAoB,CAAI,QAAgC;QACtD,MAAM,WAAW,GAAG,IAAI,CAAC,EAAE,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAA;QACjD,OAAO,WAAW,CAAC,SAAS,EAAE,CAAA;IAChC,CAAC;IAED;;;OAGG;IACH,oBAAoB,CAAI,QAAgC;QACtD,MAAM,WAAW,GAAG,IAAI,CAAC,EAAE,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAA;QACjD,OAAO,WAAW,CAAC,SAAS,EAAE,CAAA;IAChC,CAAC;IAED;;OAEG;IACH,KAAK;QACH,OAAO;YACL,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,IAAI;YACxB,gBAAgB,EAAE,IAAI,CAAC,cAAc,CAAC,IAAI;SAC3C,CAAA;IACH,CAAC;CACF;AA9KD,8BA8KC"}
@@ -0,0 +1,58 @@
1
+ import type Database from 'better-sqlite3';
2
+ import type { ComparisonOperator, OrderDirection, SQLQueryBindings, WhereCondition } from './types';
3
+ /**
4
+ * DeleteBuilder<T> - A fluent query builder for constructing DELETE queries
5
+ * Queries are only executed when .run() is called
6
+ */
7
+ export declare class DeleteBuilder<T> {
8
+ private db;
9
+ private tableName;
10
+ private _where;
11
+ private _orConditions;
12
+ private _orderBy;
13
+ private _limit?;
14
+ private statementCache;
15
+ constructor(db: Database.Database, tableName: string, statementCache: Map<string, Database.Statement>, initialWhere?: WhereCondition<T>);
16
+ /**
17
+ * Add WHERE conditions to the query (AND)
18
+ * @overload where(conditions) - Add conditions object
19
+ * @overload where(column, operator, value) - Add single condition with operator
20
+ */
21
+ where(conditions: WhereCondition<T>): DeleteBuilder<T>;
22
+ where<K extends keyof T>(column: K, operator: ComparisonOperator, value: T[K]): DeleteBuilder<T>;
23
+ /**
24
+ * Add OR conditions to the query
25
+ * @overload orWhere(conditions) - Add conditions object
26
+ * @overload orWhere(column, operator, value) - Add single condition with operator
27
+ */
28
+ orWhere(conditions: WhereCondition<T>): DeleteBuilder<T>;
29
+ orWhere<K extends keyof T>(column: K, operator: ComparisonOperator, value: T[K]): DeleteBuilder<T>;
30
+ /**
31
+ * Add ORDER BY clause to the query (SQLite supports ORDER BY in DELETE with LIMIT)
32
+ */
33
+ orderBy(column: keyof T, direction?: OrderDirection): DeleteBuilder<T>;
34
+ /**
35
+ * Set LIMIT for the query (SQLite supports LIMIT in DELETE)
36
+ */
37
+ limit(count: number): DeleteBuilder<T>;
38
+ /**
39
+ * Build the SQL query and parameters
40
+ */
41
+ private buildQuery;
42
+ /**
43
+ * Get or create a cached prepared statement
44
+ */
45
+ private getStatement;
46
+ /**
47
+ * Execute the DELETE query and return the number of deleted records
48
+ */
49
+ run(): number;
50
+ /**
51
+ * Get the SQL string for debugging
52
+ */
53
+ toSQL(): {
54
+ sql: string;
55
+ params: SQLQueryBindings[];
56
+ };
57
+ }
58
+ //# sourceMappingURL=delete-builder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delete-builder.d.ts","sourceRoot":"","sources":["../src/delete-builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,QAAQ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IACH,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,CAAC,CAAC,CAAC;IAKtC;;OAEG;IACH,OAAO,CAAC,UAAU;IAsClB;;OAEG;IACH,OAAO,CAAC,YAAY;IASpB;;OAEG;IACH,GAAG,IAAI,MAAM;IASb;;OAEG;IACH,KAAK,IAAI;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,gBAAgB,EAAE,CAAA;KAAE;CAGrD"}
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DeleteBuilder = void 0;
4
+ const where_builder_1 = require("./where-builder");
5
+ /**
6
+ * DeleteBuilder<T> - A fluent query builder for constructing DELETE queries
7
+ * Queries are only executed when .run() is called
8
+ */
9
+ class DeleteBuilder {
10
+ db;
11
+ tableName;
12
+ _where = {};
13
+ _orConditions = [];
14
+ _orderBy = [];
15
+ _limit;
16
+ statementCache;
17
+ constructor(db, tableName, statementCache, initialWhere) {
18
+ this.db = db;
19
+ this.tableName = tableName;
20
+ this.statementCache = statementCache;
21
+ if (initialWhere) {
22
+ this._where = { ...initialWhere };
23
+ }
24
+ }
25
+ where(conditionsOrColumn, operator, value) {
26
+ if (typeof conditionsOrColumn === 'string' && operator !== undefined && value !== undefined) {
27
+ // Called as where(column, operator, value)
28
+ const condition = (0, where_builder_1.operatorToCondition)(operator, value);
29
+ this._where = { ...this._where, [conditionsOrColumn]: condition };
30
+ }
31
+ else {
32
+ // Called as where(conditions)
33
+ this._where = { ...this._where, ...conditionsOrColumn };
34
+ }
35
+ return this;
36
+ }
37
+ orWhere(conditionsOrColumn, operator, value) {
38
+ if (typeof conditionsOrColumn === 'string' && operator !== undefined && value !== undefined) {
39
+ // Called as orWhere(column, operator, value)
40
+ const condition = (0, where_builder_1.operatorToCondition)(operator, value);
41
+ this._orConditions.push({ [conditionsOrColumn]: condition });
42
+ }
43
+ else {
44
+ // Called as orWhere(conditions)
45
+ this._orConditions.push(conditionsOrColumn);
46
+ }
47
+ return this;
48
+ }
49
+ /**
50
+ * Add ORDER BY clause to the query (SQLite supports ORDER BY in DELETE with LIMIT)
51
+ */
52
+ orderBy(column, direction = 'ASC') {
53
+ this._orderBy.push({ column, direction });
54
+ return this;
55
+ }
56
+ /**
57
+ * Set LIMIT for the query (SQLite supports LIMIT in DELETE)
58
+ */
59
+ limit(count) {
60
+ this._limit = count;
61
+ return this;
62
+ }
63
+ /**
64
+ * Build the SQL query and parameters
65
+ */
66
+ buildQuery() {
67
+ const params = [];
68
+ let sql = `DELETE FROM "${this.tableName}"`;
69
+ // WHERE clause
70
+ const whereClause = (0, where_builder_1.buildWhereClause)(this._where, params);
71
+ const orClauses = this._orConditions.map((orCond) => {
72
+ const orParams = [];
73
+ const clause = (0, where_builder_1.buildWhereClause)(orCond, orParams);
74
+ params.push(...orParams);
75
+ return `(${clause})`;
76
+ });
77
+ if (whereClause || orClauses.length > 0) {
78
+ if (whereClause && orClauses.length > 0) {
79
+ // Combine AND conditions with OR conditions: (AND conditions) OR (OR condition 1) OR (OR condition 2)
80
+ sql += ` WHERE (${whereClause}) OR ${orClauses.join(' OR ')}`;
81
+ }
82
+ else if (orClauses.length > 0) {
83
+ sql += ` WHERE ${orClauses.join(' OR ')}`;
84
+ }
85
+ else {
86
+ sql += ` WHERE ${whereClause}`;
87
+ }
88
+ }
89
+ // ORDER BY clause (SQLite supports this with LIMIT)
90
+ if (this._orderBy.length > 0) {
91
+ const orderClauses = this._orderBy.map((o) => `"${String(o.column)}" ${o.direction || 'ASC'}`);
92
+ sql += ` ORDER BY ${orderClauses.join(', ')}`;
93
+ }
94
+ // LIMIT clause
95
+ if (this._limit !== undefined) {
96
+ sql += ` LIMIT ${this._limit}`;
97
+ }
98
+ return { sql, params };
99
+ }
100
+ /**
101
+ * Get or create a cached prepared statement
102
+ */
103
+ getStatement(sql) {
104
+ let stmt = this.statementCache.get(sql);
105
+ if (!stmt) {
106
+ stmt = this.db.prepare(sql);
107
+ this.statementCache.set(sql, stmt);
108
+ }
109
+ return stmt;
110
+ }
111
+ /**
112
+ * Execute the DELETE query and return the number of deleted records
113
+ */
114
+ run() {
115
+ const { sql, params } = this.buildQuery();
116
+ const stmt = this.getStatement(sql);
117
+ const info = stmt.run(...params);
118
+ // Use the changes from stmt.run() return value (more efficient)
119
+ return info.changes;
120
+ }
121
+ /**
122
+ * Get the SQL string for debugging
123
+ */
124
+ toSQL() {
125
+ return this.buildQuery();
126
+ }
127
+ }
128
+ exports.DeleteBuilder = DeleteBuilder;
129
+ //# sourceMappingURL=delete-builder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delete-builder.js","sourceRoot":"","sources":["../src/delete-builder.ts"],"names":[],"mappings":";;;AASA,mDAAuE;AAEvE;;;GAGG;AACH,MAAa,aAAa;IAChB,EAAE,CAAmB;IACrB,SAAS,CAAQ;IACjB,MAAM,GAAsB,EAAE,CAAA;IAC9B,aAAa,GAAwB,EAAE,CAAA;IACvC,QAAQ,GAAiB,EAAE,CAAA;IAC3B,MAAM,CAAS;IACf,cAAc,CAAiC;IAEvD,YACE,EAAqB,EACrB,SAAiB,EACjB,cAA+C,EAC/C,YAAgC;QAEhC,IAAI,CAAC,EAAE,GAAG,EAAE,CAAA;QACZ,IAAI,CAAC,SAAS,GAAG,SAAS,CAAA;QAC1B,IAAI,CAAC,cAAc,GAAG,cAAc,CAAA;QACpC,IAAI,YAAY,EAAE,CAAC;YACjB,IAAI,CAAC,MAAM,GAAG,EAAE,GAAG,YAAY,EAAE,CAAA;QACnC,CAAC;IACH,CAAC;IASD,KAAK,CACH,kBAAyC,EACzC,QAA6B,EAC7B,KAAY;QAEZ,IAAI,OAAO,kBAAkB,KAAK,QAAQ,IAAI,QAAQ,KAAK,SAAS,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YAC5F,2CAA2C;YAC3C,MAAM,SAAS,GAAG,IAAA,mCAAmB,EAAC,QAAQ,EAAE,KAAK,CAAC,CAAA;YACtD,IAAI,CAA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