@postgresx/noredis 0.1.0 → 0.6.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.
@@ -0,0 +1,239 @@
1
+ import {
2
+ indexName,
3
+ quoteQualifiedName
4
+ } from "./chunk-RWRM5RVO.js";
5
+
6
+ // src/list.ts
7
+ var DEFAULT_TABLE_NAME = "pgredis_list";
8
+ var DEFAULT_NAMESPACE = "default";
9
+ function jsonValue(value) {
10
+ return JSON.stringify(value);
11
+ }
12
+ function parseValue(value) {
13
+ if (typeof value !== "string") return value;
14
+ try {
15
+ return JSON.parse(value);
16
+ } catch {
17
+ return value;
18
+ }
19
+ }
20
+ var PgList = class {
21
+ namespace;
22
+ tableName;
23
+ quotedTableName;
24
+ sql;
25
+ now;
26
+ constructor(options) {
27
+ this.sql = options.sql;
28
+ this.namespace = options.namespace || DEFAULT_NAMESPACE;
29
+ this.tableName = options.tableName || DEFAULT_TABLE_NAME;
30
+ this.quotedTableName = quoteQualifiedName(this.tableName);
31
+ this.now = options.now || Date.now;
32
+ }
33
+ async ensureSchema(options = {}) {
34
+ const persistence = options.unlogged === false ? "" : "UNLOGGED ";
35
+ await this.sql.unsafe(`
36
+ CREATE ${persistence}TABLE IF NOT EXISTS ${this.quotedTableName} (
37
+ id BIGSERIAL PRIMARY KEY,
38
+ namespace TEXT NOT NULL,
39
+ key TEXT NOT NULL,
40
+ position DOUBLE PRECISION NOT NULL,
41
+ value JSONB NOT NULL,
42
+ expires_at TIMESTAMPTZ,
43
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
44
+ )
45
+ `);
46
+ await this.sql.unsafe(`
47
+ ALTER TABLE ${this.quotedTableName}
48
+ ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ
49
+ `);
50
+ await this.sql.unsafe(`
51
+ CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "position")}
52
+ ON ${this.quotedTableName} (namespace, key, position ASC, id ASC)
53
+ `);
54
+ await this.sql.unsafe(`
55
+ CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "expires_at")}
56
+ ON ${this.quotedTableName} (expires_at)
57
+ WHERE expires_at IS NOT NULL
58
+ `);
59
+ }
60
+ async lpush(key, ...values) {
61
+ return this.push(key, values, "left");
62
+ }
63
+ async rpush(key, ...values) {
64
+ return this.push(key, values, "right");
65
+ }
66
+ async lpop(key, count = 1) {
67
+ return this.pop(key, count, "ASC");
68
+ }
69
+ async rpop(key, count = 1) {
70
+ return this.pop(key, count, "DESC");
71
+ }
72
+ async blpop(keys, options = {}) {
73
+ return this.blockingPop(keys, "left", options);
74
+ }
75
+ async brpop(keys, options = {}) {
76
+ return this.blockingPop(keys, "right", options);
77
+ }
78
+ async lrange(key, start = 0, stop = -1) {
79
+ const limit = stop < 0 ? null : Math.max(0, stop - start + 1);
80
+ const rows = await this.sql.unsafe(
81
+ `SELECT value
82
+ FROM ${this.quotedTableName}
83
+ WHERE namespace = $1 AND key = $2
84
+ AND (expires_at IS NULL OR expires_at > NOW())
85
+ ORDER BY position ASC, id ASC
86
+ OFFSET $3
87
+ LIMIT COALESCE($4::bigint, 9223372036854775807)`,
88
+ [this.namespace, key, Math.max(0, start), limit]
89
+ );
90
+ return rows.map((row) => parseValue(row.value));
91
+ }
92
+ async llen(key) {
93
+ const rows = await this.sql.unsafe(
94
+ `SELECT COUNT(*)::bigint AS count
95
+ FROM ${this.quotedTableName}
96
+ WHERE namespace = $1 AND key = $2
97
+ AND (expires_at IS NULL OR expires_at > NOW())`,
98
+ [this.namespace, key]
99
+ );
100
+ return Number(rows[0]?.count ?? 0);
101
+ }
102
+ async lclear(key) {
103
+ const rows = await this.sql.unsafe(
104
+ `DELETE FROM ${this.quotedTableName}
105
+ WHERE namespace = $1 AND key = $2
106
+ RETURNING id`,
107
+ [this.namespace, key]
108
+ );
109
+ return rows.length;
110
+ }
111
+ async push(key, values, side) {
112
+ if (values.length === 0) return this.llen(key);
113
+ const base = this.now();
114
+ const params = [];
115
+ const groups = values.map((value, index) => {
116
+ const position = side === "left" ? -(base + values.length - index) : base + index;
117
+ const paramIndex = index * 4;
118
+ params.push(this.namespace, key, position, jsonValue(value));
119
+ return `($${paramIndex + 1}, $${paramIndex + 2}, $${paramIndex + 3}, $${paramIndex + 4}::jsonb, (SELECT MAX(expires_at) FROM ${this.quotedTableName} WHERE namespace = $${paramIndex + 1} AND key = $${paramIndex + 2}), NOW())`;
120
+ }).join(", ");
121
+ await this.sql.unsafe(
122
+ `INSERT INTO ${this.quotedTableName} (namespace, key, position, value, expires_at, created_at)
123
+ VALUES ${groups}`,
124
+ params
125
+ );
126
+ return this.llen(key);
127
+ }
128
+ async pop(key, count, direction) {
129
+ const limit = Math.max(1, Math.floor(count));
130
+ const rows = await this.sql.unsafe(
131
+ `WITH picked AS (
132
+ SELECT id, value, position
133
+ FROM ${this.quotedTableName}
134
+ WHERE namespace = $1 AND key = $2
135
+ AND (expires_at IS NULL OR expires_at > NOW())
136
+ ORDER BY position ${direction}, id ${direction}
137
+ LIMIT $3
138
+ ), deleted AS (
139
+ DELETE FROM ${this.quotedTableName} target
140
+ USING picked
141
+ WHERE target.id = picked.id
142
+ RETURNING picked.value, picked.position
143
+ )
144
+ SELECT value
145
+ FROM deleted
146
+ ORDER BY position ${direction}`,
147
+ [this.namespace, key, limit]
148
+ );
149
+ return rows.map((row) => parseValue(row.value));
150
+ }
151
+ async blockingPop(keys, side, options) {
152
+ const listKeys = typeof keys === "string" ? [keys] : [...keys];
153
+ if (listKeys.length === 0) return null;
154
+ const timeoutMs = options.timeoutMs ?? 0;
155
+ const pollIntervalMs = Math.max(1, Math.floor(options.pollIntervalMs ?? 100));
156
+ const deadline = timeoutMs <= 0 ? null : this.now() + timeoutMs;
157
+ while (true) {
158
+ for (const key of listKeys) {
159
+ const values = side === "left" ? await this.lpop(key, 1) : await this.rpop(key, 1);
160
+ if (values.length > 0) return { key, value: values[0] };
161
+ }
162
+ if (deadline !== null && this.now() >= deadline) return null;
163
+ const delayMs = deadline === null ? pollIntervalMs : Math.min(pollIntervalMs, Math.max(0, deadline - this.now()));
164
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
165
+ }
166
+ }
167
+ async lscan(key, cursor = null, count = 100) {
168
+ const limit = Math.max(1, Math.floor(count));
169
+ const rows = await this.sql.unsafe(
170
+ `SELECT position, value
171
+ FROM ${this.quotedTableName}
172
+ WHERE namespace = $1
173
+ AND key = $2
174
+ AND position > COALESCE($3::double precision, '-Infinity'::double precision)
175
+ AND (expires_at IS NULL OR expires_at > NOW())
176
+ ORDER BY position ASC, id ASC
177
+ LIMIT $4`,
178
+ [this.namespace, key, cursor, limit]
179
+ );
180
+ return {
181
+ cursor: rows.length === limit ? Number(rows[rows.length - 1].position) : null,
182
+ values: rows.map((row) => parseValue(row.value))
183
+ };
184
+ }
185
+ async expire(key, ttlMs) {
186
+ const rows = await this.sql.unsafe(
187
+ `UPDATE ${this.quotedTableName}
188
+ SET expires_at = NOW() + ($3::bigint * INTERVAL '1 millisecond')
189
+ WHERE namespace = $1 AND key = $2
190
+ RETURNING id`,
191
+ [this.namespace, key, Math.max(0, Math.floor(ttlMs))]
192
+ );
193
+ return rows.length;
194
+ }
195
+ async persist(key) {
196
+ const rows = await this.sql.unsafe(
197
+ `UPDATE ${this.quotedTableName}
198
+ SET expires_at = NULL
199
+ WHERE namespace = $1 AND key = $2
200
+ RETURNING id`,
201
+ [this.namespace, key]
202
+ );
203
+ return rows.length;
204
+ }
205
+ async ttl(key) {
206
+ const rows = await this.sql.unsafe(
207
+ `SELECT CASE
208
+ WHEN MAX(expires_at) IS NULL THEN NULL
209
+ ELSE GREATEST(0, FLOOR(EXTRACT(EPOCH FROM (MAX(expires_at) - NOW())) * 1000))::bigint
210
+ END AS ttl_ms
211
+ FROM ${this.quotedTableName}
212
+ WHERE namespace = $1 AND key = $2`,
213
+ [this.namespace, key]
214
+ );
215
+ return rows[0]?.ttl_ms === null || rows[0]?.ttl_ms === void 0 ? null : Number(rows[0].ttl_ms);
216
+ }
217
+ async cleanupExpired(limit = 1e3) {
218
+ const rows = await this.sql.unsafe(
219
+ `DELETE FROM ${this.quotedTableName}
220
+ WHERE ctid IN (
221
+ SELECT ctid
222
+ FROM ${this.quotedTableName}
223
+ WHERE expires_at IS NOT NULL AND expires_at <= NOW()
224
+ LIMIT $1
225
+ )
226
+ RETURNING id`,
227
+ [Math.max(1, Math.floor(limit))]
228
+ );
229
+ return rows.length;
230
+ }
231
+ };
232
+ function createPgList(options) {
233
+ return new PgList(options);
234
+ }
235
+
236
+ export {
237
+ PgList,
238
+ createPgList
239
+ };
@@ -0,0 +1,101 @@
1
+ // src/pubsub.ts
2
+ function createBunPgListener(databaseUrl, channelsOrOptions = [], onNotify, maybeOptions = {}) {
3
+ let handle = null;
4
+ let loadError = null;
5
+ let closed = false;
6
+ const queue = [];
7
+ void import("@postgresx/bun-listen").then((mod) => {
8
+ if (closed) return;
9
+ const activeHandle = Array.isArray(channelsOrOptions) ? mod.createPgListener(databaseUrl, channelsOrOptions, onNotify, maybeOptions) : mod.createPgListener(databaseUrl, channelsOrOptions);
10
+ handle = activeHandle;
11
+ for (const item of queue.splice(0)) {
12
+ try {
13
+ item.resolve(item.action(activeHandle));
14
+ } catch (error) {
15
+ item.reject(error instanceof Error ? error : new Error(String(error)));
16
+ }
17
+ }
18
+ }).catch((error) => {
19
+ const message = error instanceof Error ? error.message : String(error);
20
+ loadError = new Error(`@postgresx/bun-listen is required for Bun LISTEN/NOTIFY. Install it with \`bun add @postgresx/bun-listen\`. ${message}`);
21
+ for (const item of queue.splice(0)) item.reject(loadError);
22
+ });
23
+ const run = (action) => {
24
+ if (handle) return Promise.resolve(action(handle));
25
+ if (loadError) return Promise.reject(loadError);
26
+ return new Promise((resolve, reject) => {
27
+ queue.push({
28
+ action,
29
+ resolve,
30
+ reject
31
+ });
32
+ });
33
+ };
34
+ return {
35
+ close() {
36
+ closed = true;
37
+ if (handle) handle.close();
38
+ queue.length = 0;
39
+ },
40
+ notify(channel, payload) {
41
+ return run((listener) => listener.notify(channel, payload)).then(() => void 0);
42
+ },
43
+ getHealth() {
44
+ return handle?.getHealth() ?? {
45
+ status: closed ? "closed" : "connecting",
46
+ connected: false,
47
+ listeningChannels: Array.isArray(channelsOrOptions) ? channelsOrOptions : channelsOrOptions.channels ?? [],
48
+ queuedQueries: queue.length,
49
+ activeQuery: false,
50
+ reconnectAttempts: 0,
51
+ lastConnectedAt: null,
52
+ lastMessageAt: null,
53
+ lastNotificationAt: null,
54
+ lastError: null
55
+ };
56
+ },
57
+ on(event, handler) {
58
+ if (handle) return handle.on(event, handler);
59
+ let unsubscribe = null;
60
+ const item = {
61
+ action(listener) {
62
+ unsubscribe = listener.on(event, handler);
63
+ },
64
+ resolve() {
65
+ },
66
+ reject() {
67
+ }
68
+ };
69
+ queue.push(item);
70
+ return () => {
71
+ const index = queue.indexOf(item);
72
+ if (index >= 0) queue.splice(index, 1);
73
+ unsubscribe?.();
74
+ };
75
+ },
76
+ off(event, handler) {
77
+ if (handle) handle.off(event, handler);
78
+ }
79
+ };
80
+ }
81
+ var createPgListener = createBunPgListener;
82
+ function serializePayload(payload) {
83
+ return typeof payload === "string" ? payload : JSON.stringify(payload);
84
+ }
85
+ async function publishPgNotify(sql, channel, payload) {
86
+ await sql.unsafe("SELECT pg_notify($1, $2)", [channel, serializePayload(payload)]);
87
+ }
88
+ function createPgPublisher(sql) {
89
+ return {
90
+ publish(channel, payload) {
91
+ return publishPgNotify(sql, channel, payload);
92
+ }
93
+ };
94
+ }
95
+
96
+ export {
97
+ createBunPgListener,
98
+ createPgListener,
99
+ publishPgNotify,
100
+ createPgPublisher
101
+ };
@@ -0,0 +1,30 @@
1
+ // src/sql.ts
2
+ function quoteIdentifier(identifier) {
3
+ const trimmed = identifier.trim();
4
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(trimmed)) {
5
+ throw new Error(`Invalid SQL identifier: ${identifier}`);
6
+ }
7
+ return `"${trimmed.replaceAll('"', '""')}"`;
8
+ }
9
+ function quoteQualifiedName(name) {
10
+ const parts = name.split(".").map((part) => part.trim()).filter(Boolean);
11
+ if (parts.length === 0 || parts.length > 2) {
12
+ throw new Error(`Invalid SQL table name: ${name}`);
13
+ }
14
+ return parts.map(quoteIdentifier).join(".");
15
+ }
16
+ function indexName(tableName, suffix) {
17
+ const normalized = tableName.replace(/[^A-Za-z0-9_]/g, "_").replace(/^_+/, "").slice(0, 42) || "pg_redis_kit";
18
+ return quoteIdentifier(`idx_${normalized}_${suffix}`.slice(0, 63));
19
+ }
20
+ function normalizePositiveInteger(value, name) {
21
+ if (!Number.isFinite(value) || value <= 0) throw new Error(`${name} must be a positive number`);
22
+ return Math.floor(value);
23
+ }
24
+
25
+ export {
26
+ quoteIdentifier,
27
+ quoteQualifiedName,
28
+ indexName,
29
+ normalizePositiveInteger
30
+ };