64 lines
2.2 KiB
JavaScript
64 lines
2.2 KiB
JavaScript
import { readFileSync } from 'fs';
|
|
import { dirname, join } from 'path';
|
|
import { fileURLToPath } from 'url';
|
|
function getDirname() {
|
|
if (typeof __dirname !== 'undefined' && __dirname) {
|
|
return __dirname;
|
|
}
|
|
const stack = new Error().stack || '';
|
|
for (const line of stack.split('\n')) {
|
|
const match = line.match(/(file:\/\/\/[^\s)]+)/);
|
|
if (match) {
|
|
try {
|
|
return dirname(fileURLToPath(match[1]));
|
|
}
|
|
catch (_a) {
|
|
// continue searching
|
|
}
|
|
}
|
|
}
|
|
throw new Error('Could not determine sql-loader directory path');
|
|
}
|
|
const currentDir = getDirname();
|
|
/**
|
|
* Loads a migration's SQL from its `.sql` file — the portable source of truth
|
|
* shared with the Elixir/Python ports. Results are cached after the first read.
|
|
*
|
|
* The `.sql` files live next to this module under `migrations/`. The published
|
|
* build copies them alongside the compiled output (a `copy:sql` build step,
|
|
* analogous to how the Lua scripts are bundled), so the same relative lookup
|
|
* works at runtime.
|
|
*/
|
|
const MIGRATIONS_DIR = join(currentDir, 'migrations');
|
|
/**
|
|
* Runtime queries live under `commands/`. Each `.sql` file is one parameterized
|
|
* statement (a `SELECT fn(...)` for the PL/pgSQL operations, or a direct
|
|
* query). They contain NO schema/namespace references — the connection's
|
|
* `search_path` selects the schema — so they are portable verbatim to the
|
|
* Python/Elixir/PHP/Rust ports (mirroring how the Redis backend's `.lua`
|
|
* scripts never hardcode the key prefix).
|
|
*/
|
|
const COMMANDS_DIR = join(currentDir, 'commands');
|
|
const migrationCache = new Map();
|
|
const commandCache = new Map();
|
|
export function loadMigrationSql(file) {
|
|
let sql = migrationCache.get(file);
|
|
if (sql === undefined) {
|
|
sql = readFileSync(join(MIGRATIONS_DIR, file), 'utf8');
|
|
migrationCache.set(file, sql);
|
|
}
|
|
return sql;
|
|
}
|
|
/**
|
|
* Loads a runtime command's SQL by name (without the `.sql` extension), cached
|
|
* after the first read.
|
|
*/
|
|
export function loadCommandSql(name) {
|
|
let sql = commandCache.get(name);
|
|
if (sql === undefined) {
|
|
sql = readFileSync(join(COMMANDS_DIR, `${name}.sql`), 'utf8');
|
|
commandCache.set(name, sql);
|
|
}
|
|
return sql;
|
|
}
|