UNPKG

@keyv/postgres

Version:

PostgreSQL storage adapter for Keyv

153 lines (150 loc) 4.84 kB
// src/index.ts import EventEmitter from "events"; import Keyv from "keyv"; // src/pool.ts import pg from "pg"; var postgresPool; var globalUri; var pool = (uri, options = {}) => { if (globalUri !== uri) { postgresPool = void 0; globalUri = uri; } postgresPool ??= new pg.Pool({ connectionString: uri, ...options }); return postgresPool; }; var endPool = async () => { await postgresPool.end(); globalUri = void 0; }; // src/index.ts var KeyvPostgres = class extends EventEmitter { ttlSupport; opts; query; namespace; constructor(options) { super(); this.ttlSupport = false; if (typeof options === "string") { const uri = options; options = { dialect: "postgres", uri }; } else { options = { dialect: "postgres", uri: "postgresql://localhost:5432", ...options }; } const connect = async () => { const conn = pool(options.uri, options); return async (sql, values) => { const data = await conn.query(sql, values); return data.rows; }; }; this.opts = { table: "keyv", schema: "public", keySize: 255, ...options }; let createTable = `CREATE${this.opts.useUnloggedTable ? " UNLOGGED " : " "}TABLE IF NOT EXISTS ${this.opts.schema}.${this.opts.table}(key VARCHAR(${Number(this.opts.keySize)}) PRIMARY KEY, value TEXT )`; if (this.opts.schema !== "public") { createTable = `CREATE SCHEMA IF NOT EXISTS ${this.opts.schema}; ${createTable}`; } const connected = connect().then(async (query) => { try { await query(createTable); } catch (error) { if (error.code !== "23505") { this.emit("error", error); } return query; } return query; }).catch((error) => this.emit("error", error)); this.query = async (sqlString, values) => connected.then((query) => query(sqlString, values)); } async get(key) { const select = `SELECT * FROM ${this.opts.schema}.${this.opts.table} WHERE key = $1`; const rows = await this.query(select, [key]); const row = rows[0]; return row === void 0 ? void 0 : row.value; } async getMany(keys) { const getMany = `SELECT * FROM ${this.opts.schema}.${this.opts.table} WHERE key = ANY($1)`; const rows = await this.query(getMany, [keys]); const results = []; for (const key of keys) { const rowIndex = rows?.findIndex((row) => row.key === key); results.push(rowIndex > -1 ? rows[rowIndex].value : void 0); } return results; } async set(key, value) { const upsert = `INSERT INTO ${this.opts.schema}.${this.opts.table} (key, value) VALUES($1, $2) ON CONFLICT(key) DO UPDATE SET value=excluded.value;`; await this.query(upsert, [key, value]); } async delete(key) { const select = `SELECT * FROM ${this.opts.schema}.${this.opts.table} WHERE key = $1`; const del = `DELETE FROM ${this.opts.schema}.${this.opts.table} WHERE key = $1`; const rows = await this.query(select, [key]); if (rows[0] === void 0) { return false; } await this.query(del, [key]); return true; } async deleteMany(keys) { const select = `SELECT * FROM ${this.opts.schema}.${this.opts.table} WHERE key = ANY($1)`; const del = `DELETE FROM ${this.opts.schema}.${this.opts.table} WHERE key = ANY($1)`; const rows = await this.query(select, [keys]); if (rows[0] === void 0) { return false; } await this.query(del, [keys]); return true; } async clear() { const del = `DELETE FROM ${this.opts.schema}.${this.opts.table} WHERE key LIKE $1`; await this.query(del, [this.namespace ? `${this.namespace}:%` : "%"]); } async *iterator(namespace) { const limit = Number.parseInt(String(this.opts.iterationLimit), 10) || 10; async function* iterate(offset, options, query) { const select = `SELECT * FROM ${options.schema}.${options.table} WHERE key LIKE $1 LIMIT $2 OFFSET $3`; const entries = await query(select, [`${namespace ? namespace + ":" : ""}%`, limit, offset]); if (entries.length === 0) { return; } for (const entry of entries) { offset += 1; yield [entry.key, entry.value]; } yield* iterate(offset, options, query); } yield* iterate(0, this.opts, this.query); } async has(key) { const exists = `SELECT EXISTS ( SELECT * FROM ${this.opts.schema}.${this.opts.table} WHERE key = $1 )`; const rows = await this.query(exists, [key]); return rows[0].exists; } async disconnect() { await endPool(); } }; var createKeyv = (options) => new Keyv({ store: new KeyvPostgres(options) }); var index_default = KeyvPostgres; export { KeyvPostgres, createKeyv, index_default as default };