sqlite.js
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sqliteQuery = sqliteQuery;
exports.sqliteWriteQuery = sqliteWriteQuery;
exports.sqliteTables = sqliteTables;
exports.sqliteSchema = sqliteSchema;
const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
function sqliteQuery(dbPath, sql, maxRows) {
const db = new better_sqlite3_1.default(dbPath, { readonly: true });
try {
const stmt = db.prepare(sql);
const rows = stmt.all();
const columns = rows.length > 0 ? Object.keys(rows[0]) : [];
const truncated = rows.length > maxRows;
return {
columns,
rows: rows.slice(0, maxRows).map(r => columns.map(c => r[c])),
rowCount: rows.length,
truncated,
};
}
finally {
db.close();
}
}
function sqliteWriteQuery(dbPath, sql) {
const db = new better_sqlite3_1.default(dbPath);
try {
const result = db.prepare(sql).run();
return { changes: result.changes, lastInsertRowid: result.lastInsertRowid };
}
finally {
db.close();
}
}
function sqliteTables(dbPath) {
const db = new better_sqlite3_1.default(dbPath, { readonly: true });
try {
const rows = db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all();
return rows.map(r => r.name);
}
finally {
db.close();
}
}
function sqliteSchema(dbPath, tableName) {
const db = new better_sqlite3_1.default(dbPath, { readonly: true });
try {
const cols = db.prepare(`PRAGMA table_info(${tableName})`).all();
return {
name: tableName,
columns: cols.map(c => ({ name: c.name, type: c.type, notnull: c.notnull === 1, pk: c.pk === 1 })),
};
}
finally {
db.close();
}
}