All files / database/src/adapters sqlite.js

53.04% Statements 61/115
43.2% Branches 35/81
59.45% Functions 22/37
53.04% Lines 61/115

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387                        32x 32x                 32x 32x   32x 32x                               32x   32x 32x 32x       32x         32x     32x     32x   32x                                   251x                             251x 251x       251x 120x 120x 7x   113x   120x     131x 131x     131x                                                                                                                                                                                                                       15x 15x 15x       15x   15x         29x 1x   28x       12x     12x 12x 12x                   3x     3x 3x       15x                 30x 30x     30x 30x     30x                     2x 2x                 32x 32x       32x 32x     32x 32x                                             32x 32x 32x                                                           32x                             32x    
/**
 * SQLite Database Adapter for Coherent.js
 * 
 * @fileoverview SQLite adapter implementation with connection pooling and transaction support.
 */
 
/**
 * Create a new SQLite adapter instance
 * 
 * @returns {Object} SQLite adapter instance with database operations
 */
export function createSQLiteAdapter() {
  let sqlite3 = null;
  let db = null;
 
  /**
   * Initialize SQLite module
   * 
   * @private
   * @returns {Promise<void>}
   */
  async function initializeSQLite() {
    Eif (!sqlite3) {
      try {
        // Try to import sqlite3 (peer dependency)
        const sqlite3Module = await import('sqlite3');
        sqlite3 = sqlite3Module.default || sqlite3Module;
      } catch {
        throw new Error('Failed to load sqlite3 module. Make sure to install it: npm install sqlite3');
      }
    }
  }
 
  /**
   * Connect to the database
   * 
   * @param {Object} config - Database configuration
   * @param {string} config.database - Path to the SQLite database file
   * @param {boolean} [config.readonly=false] - Open the database in read-only mode
   * @returns {Promise<Object>} The database adapter instance
   */
  async function connect(config) {
    await initializeSQLite();
    
    return new Promise((resolve, reject) => {
      try {
        db = new sqlite3.Database(
          config.database,
          config.readonly ? sqlite3.OPEN_READONLY : sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE,
          (err) => {
            Iif (err) {
              return reject(new Error(`Failed to connect to SQLite database: ${err.message}`));
            }
            
            // Enable foreign keys by default
            db.run('PRAGMA foreign_keys = ON');
            
            // Enable WAL mode for better concurrency
            db.run('PRAGMA journal_mode = WAL');
            
            // Set busy timeout to handle concurrent write operations
            db.run('PRAGMA busy_timeout = 5000');
            
            resolve(instance);
          }
        );
      } catch (_error) {
        reject(new Error(`Failed to connect to SQLite database: ${_error.message}`));
      }
    });
  }
 
  /**
   * Whether a statement produces rows (and must go through `db.all`) rather than a
   * change count (`db.run`, which reports `lastID` / `changes`).
   *
   * @private
   * @param {string} sql - SQL statement
   * @returns {boolean}
   */
  function returnsRows(sql) {
    return /^\s*(SELECT|PRAGMA|WITH|EXPLAIN|VALUES)\b/i.test(sql) || /\bRETURNING\b/i.test(sql);
  }
 
  /**
   * Execute a SQL query
   *
   * Row-returning statements resolve to `{ rows, rowCount }`. Other statements resolve
   * to `{ rows: [], rowCount, affectedRows, insertId }`, where `affectedRows` is the
   * number of changed rows and `insertId` the rowid of an INSERT (null otherwise).
   *
   * @param {string} sql - SQL query string
   * @param {Array} [params=[]] - Query parameters
   * @returns {Promise<{rows: Array<Object>, rowCount: number, affectedRows?: number, insertId?: number|null}>} Query result
   */
  function query(sql, params = []) {
    return new Promise((resolve, reject) => {
      Iif (!db) {
        return reject(new Error('Database connection not established. Call connect() first.'));
      }
 
      if (returnsRows(sql)) {
        db.all(sql, params, (err, rows) => {
          if (err) {
            return reject(new Error(`SQLite query error: ${err.message}`));
          }
          resolve({ rows, rowCount: rows.length });
        });
        return;
      }
 
      db.run(sql, params, function(err) {
        Iif (err) {
          return reject(new Error(`SQLite query error: ${err.message}`));
        }
        resolve({
          rows: [],
          rowCount: this.changes,
          affectedRows: this.changes,
          insertId: /^\s*(INSERT|REPLACE)\b/i.test(sql) ? this.lastID : null
        });
      });
    });
  }
 
  /**
   * Execute a SQL statement
   * 
   * @param {string} sql - SQL statement
   * @param {Array} [params=[]] - Statement parameters
   * @returns {Promise<{affectedRows: number, insertId: number}>} Execution result
   */
  function execute(sql, params = []) {
    return new Promise((resolve, reject) => {
      if (!db) {
        return reject(new Error('Database connection not established. Call connect() first.'));
      }
      
      db.run(sql, params, function(err) {
        if (err) {
          return reject(new Error(`SQLite execute error: ${err.message}`));
        }
        
        resolve({
          affectedRows: this.changes,
          insertId: this.lastID
        });
      });
    });
  }
 
  /**
   * Begin a transaction
   * 
   * @returns {Promise<void>}
   */
  function beginTransaction() {
    return new Promise((resolve, reject) => {
      if (!db) {
        return reject(new Error('Database connection not established. Call connect() first.'));
      }
      
      db.run('BEGIN TRANSACTION', (err) => {
        if (err) {
          return reject(new Error(`Failed to begin transaction: ${err.message}`));
        }
        resolve();
      });
    });
  }
 
  /**
   * Commit a transaction
   * 
   * @returns {Promise<void>}
   */
  function commit() {
    return new Promise((resolve, reject) => {
      if (!db) {
        return reject(new Error('Database connection not established. Call connect() first.'));
      }
      
      db.run('COMMIT', (err) => {
        if (err) {
          return reject(new Error(`Failed to commit transaction: ${err.message}`));
        }
        resolve();
      });
    });
  }
 
  /**
   * Rollback a transaction
   * 
   * @returns {Promise<void>}
   */
  function rollback() {
    return new Promise((resolve, reject) => {
      if (!db) {
        return reject(new Error('Database connection not established. Call connect() first.'));
      }
      
      db.run('ROLLBACK', (err) => {
        if (err) {
          return reject(new Error(`Failed to rollback transaction: ${err.message}`));
        }
        resolve();
      });
    });
  }
 
  /**
   * Start a transaction on the connection (the DatabaseManager transaction contract)
   *
   * SQLite has a single connection here: a second transaction started before the first
   * one finishes fails with "cannot start a transaction within a transaction".
   *
   * @param {Object} [_pool] - Unused; the adapter instance is its own pool
   * @param {Object} [options={}] - Transaction options
   * @param {'DEFERRED'|'IMMEDIATE'|'EXCLUSIVE'} [options.mode] - SQLite locking mode
   * @returns {Promise<Object>} Transaction with query, commit and rollback
   */
  async function transaction(_pool, options = {}) {
    const modes = ['DEFERRED', 'IMMEDIATE', 'EXCLUSIVE'];
    const mode = options.mode === undefined ? null : String(options.mode).toUpperCase();
    Iif (mode !== null && !modes.includes(mode)) {
      throw new Error(`Invalid SQLite transaction mode: ${options.mode}. Use one of ${modes.join(', ')}`);
    }
 
    await run(mode ? `BEGIN ${mode} TRANSACTION` : 'BEGIN TRANSACTION', 'begin transaction');
 
    const tx = {
      isCommitted: false,
      isRolledBack: false,
 
      async query(sql, params) {
        if (tx.isCommitted || tx.isRolledBack) {
          throw new Error('Cannot execute query on completed transaction');
        }
        return query(sql, params);
      },
 
      async commit() {
        Iif (tx.isCommitted || tx.isRolledBack) {
          throw new Error('Transaction already completed');
        }
        try {
          await run('COMMIT', 'commit transaction');
          tx.isCommitted = true;
        } catch (commitError) {
          // Leave the connection usable: a failed COMMIT keeps the transaction open.
          await run('ROLLBACK', 'rollback transaction').catch(() => {});
          tx.isRolledBack = true;
          throw commitError;
        }
      },
 
      async rollback() {
        Iif (tx.isCommitted || tx.isRolledBack) {
          throw new Error('Transaction already completed');
        }
        tx.isRolledBack = true;
        await run('ROLLBACK', 'rollback transaction');
      }
    };
 
    return tx;
  }
 
  /**
   * Run a control statement (BEGIN / COMMIT / ROLLBACK)
   *
   * @private
   */
  function run(sql, action) {
    return new Promise((resolve, reject) => {
      Iif (!db) {
        return reject(new Error('Database connection not established. Call connect() first.'));
      }
      db.run(sql, (err) => {
        Iif (err) {
          return reject(new Error(`Failed to ${action}: ${err.message}`));
        }
        resolve();
      });
    });
  }
 
  /**
   * Connection statistics (the DatabaseManager getStats contract)
   *
   * @returns {{total: number, available: number, acquired: number, waiting: number}}
   */
  function getPoolStats() {
    const open = db ? 1 : 0;
    return { total: open, available: open, acquired: 0, waiting: 0 };
  }
 
  /**
   * Disconnect from the database
   * 
   * @returns {Promise<void>}
   */
  function disconnect() {
    return new Promise((resolve, reject) => {
      Iif (!db) {
        return resolve();
      }
      
      db.close((err) => {
        Iif (err) {
          return reject(new Error(`Failed to close database connection: ${err.message}`));
        }
        db = null;
        resolve();
      });
    });
  }
 
  /**
   * Get the underlying database connection
   * 
   * @returns {Object} The database connection
   */
  function getConnection() {
    if (!db) {
      throw new Error('Database connection not established. Call connect() first.');
    }
    return db;
  }
 
  /**
   * Ping the database to check if connection is alive
   * 
   * @returns {Promise<boolean>} True if connection is alive
   */
  async function ping() {
    try {
      await query('SELECT 1');
      return true;
    } catch {
      return false;
    }
  }
 
  /**
   * Escape a value for SQL queries
   * 
   * @param {*} value - Value to escape
   * @returns {string} Escaped value
   */
  function escape(value) {
    if (value === null || value === undefined) {
      return 'NULL';
    }
    
    if (typeof value === 'boolean') {
      return value ? '1' : '0';
    }
    
    if (typeof value === 'number') {
      return String(value);
    }
    
    // Escape single quotes by doubling them
    return `'${String(value).replace(/'/g, "''")}'`;
  }
 
  // Public API
  const instance = {
    connect,
    query,
    execute,
    beginTransaction,
    commit,
    rollback,
    transaction,
    getPoolStats,
    disconnect,
    getConnection,
    ping,
    escape
  };
 
  return instance;
}