@postgresx/noredis 0.1.0 → 0.5.2

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,328 @@
1
+ import {
2
+ indexName,
3
+ quoteQualifiedName
4
+ } from "./chunk-RWRM5RVO.js";
5
+
6
+ // src/sorted-set.ts
7
+ var DEFAULT_TABLE_NAME = "pgredis_sorted_set";
8
+ var DEFAULT_NAMESPACE = "default";
9
+ var PgSortedSet = class {
10
+ namespace;
11
+ tableName;
12
+ quotedTableName;
13
+ sql;
14
+ constructor(options) {
15
+ this.sql = options.sql;
16
+ this.namespace = options.namespace || DEFAULT_NAMESPACE;
17
+ this.tableName = options.tableName || DEFAULT_TABLE_NAME;
18
+ this.quotedTableName = quoteQualifiedName(this.tableName);
19
+ }
20
+ async ensureSchema(options = {}) {
21
+ const persistence = options.unlogged === false ? "" : "UNLOGGED ";
22
+ await this.sql.unsafe(`
23
+ CREATE ${persistence}TABLE IF NOT EXISTS ${this.quotedTableName} (
24
+ namespace TEXT NOT NULL,
25
+ key TEXT NOT NULL,
26
+ member TEXT NOT NULL,
27
+ score DOUBLE PRECISION NOT NULL,
28
+ expires_at TIMESTAMPTZ,
29
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
30
+ PRIMARY KEY (namespace, key, member)
31
+ )
32
+ `);
33
+ await this.sql.unsafe(`
34
+ ALTER TABLE ${this.quotedTableName}
35
+ ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ
36
+ `);
37
+ await this.sql.unsafe(`
38
+ CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "score")}
39
+ ON ${this.quotedTableName} (namespace, key, score ASC, member ASC)
40
+ `);
41
+ await this.sql.unsafe(`
42
+ CREATE INDEX IF NOT EXISTS ${indexName(this.tableName, "expires_at")}
43
+ ON ${this.quotedTableName} (expires_at)
44
+ WHERE expires_at IS NOT NULL
45
+ `);
46
+ }
47
+ async zadd(key, score, member) {
48
+ if (!Number.isFinite(score)) throw new Error(`Invalid sorted-set score: ${score}`);
49
+ const rows = await this.sql.unsafe(
50
+ `INSERT INTO ${this.quotedTableName} (namespace, key, member, score, expires_at, updated_at)
51
+ VALUES (
52
+ $1,
53
+ $2,
54
+ $3,
55
+ $4,
56
+ (SELECT MAX(expires_at) FROM ${this.quotedTableName} WHERE namespace = $1 AND key = $2),
57
+ NOW()
58
+ )
59
+ ON CONFLICT (namespace, key, member) DO UPDATE
60
+ SET score = EXCLUDED.score,
61
+ updated_at = NOW()
62
+ RETURNING (xmax = 0)::int AS inserted`,
63
+ [this.namespace, key, member, score]
64
+ );
65
+ return Number(rows[0]?.inserted ?? 0) === 1;
66
+ }
67
+ async zscore(key, member) {
68
+ const rows = await this.sql.unsafe(
69
+ `SELECT score
70
+ FROM ${this.quotedTableName}
71
+ WHERE namespace = $1 AND key = $2 AND member = $3
72
+ AND (expires_at IS NULL OR expires_at > NOW())
73
+ LIMIT 1`,
74
+ [this.namespace, key, member]
75
+ );
76
+ return rows[0] ? Number(rows[0].score) : null;
77
+ }
78
+ async zrange(key, start = 0, stop = -1, options = {}) {
79
+ const limit = stop < 0 ? null : Math.max(0, stop - start + 1);
80
+ const order = options.desc ? "DESC" : "ASC";
81
+ const rows = await this.sql.unsafe(
82
+ `SELECT member, score
83
+ FROM ${this.quotedTableName}
84
+ WHERE namespace = $1 AND key = $2
85
+ AND (expires_at IS NULL OR expires_at > NOW())
86
+ ORDER BY score ${order}, member ${order}
87
+ OFFSET $3
88
+ LIMIT COALESCE($4::bigint, 9223372036854775807)`,
89
+ [this.namespace, key, Math.max(0, start), limit]
90
+ );
91
+ if (options.withScores) {
92
+ return rows.map((row) => ({ member: row.member, score: Number(row.score) }));
93
+ }
94
+ return rows.map((row) => row.member);
95
+ }
96
+ async zrangeByScore(key, min = Number.NEGATIVE_INFINITY, max = Number.POSITIVE_INFINITY, options = {}) {
97
+ const order = options.desc ? "DESC" : "ASC";
98
+ const rows = await this.sql.unsafe(
99
+ `SELECT member, score
100
+ FROM ${this.quotedTableName}
101
+ WHERE namespace = $1
102
+ AND key = $2
103
+ AND score >= $3
104
+ AND score <= $4
105
+ AND (expires_at IS NULL OR expires_at > NOW())
106
+ ORDER BY score ${order}, member ${order}
107
+ OFFSET $5
108
+ LIMIT COALESCE($6::bigint, 9223372036854775807)`,
109
+ [
110
+ this.namespace,
111
+ key,
112
+ min,
113
+ max,
114
+ Math.max(0, options.offset || 0),
115
+ options.limit === void 0 ? null : Math.max(0, Math.floor(options.limit))
116
+ ]
117
+ );
118
+ if (options.withScores) {
119
+ return rows.map((row) => ({ member: row.member, score: Number(row.score) }));
120
+ }
121
+ return rows.map((row) => row.member);
122
+ }
123
+ async zrank(key, member, options = {}) {
124
+ const comparator = options.desc ? "(candidate.score > target.score OR (candidate.score = target.score AND candidate.member > target.member))" : "(candidate.score < target.score OR (candidate.score = target.score AND candidate.member < target.member))";
125
+ const rows = await this.sql.unsafe(
126
+ `WITH target AS (
127
+ SELECT score, member
128
+ FROM ${this.quotedTableName}
129
+ WHERE namespace = $1 AND key = $2 AND member = $3
130
+ AND (expires_at IS NULL OR expires_at > NOW())
131
+ )
132
+ SELECT CASE
133
+ WHEN EXISTS (SELECT 1 FROM target) THEN COUNT(candidate.member)::bigint
134
+ ELSE NULL
135
+ END AS count
136
+ FROM target
137
+ JOIN ${this.quotedTableName} candidate
138
+ ON candidate.namespace = $1
139
+ AND candidate.key = $2
140
+ AND (candidate.expires_at IS NULL OR candidate.expires_at > NOW())
141
+ AND ${comparator}`,
142
+ [this.namespace, key, member]
143
+ );
144
+ if (rows.length === 0 || rows[0]?.count === null || rows[0]?.count === void 0) return null;
145
+ return Number(rows[0].count);
146
+ }
147
+ async zcount(key, min = Number.NEGATIVE_INFINITY, max = Number.POSITIVE_INFINITY) {
148
+ const rows = await this.sql.unsafe(
149
+ `SELECT COUNT(*)::bigint AS count
150
+ FROM ${this.quotedTableName}
151
+ WHERE namespace = $1
152
+ AND key = $2
153
+ AND score >= $3
154
+ AND score <= $4
155
+ AND (expires_at IS NULL OR expires_at > NOW())`,
156
+ [this.namespace, key, min, max]
157
+ );
158
+ return Number(rows[0]?.count ?? 0);
159
+ }
160
+ async zrem(key, ...members) {
161
+ const values = [...new Set(members)];
162
+ if (values.length === 0) return 0;
163
+ const placeholders = values.map((_, index) => `$${index + 3}`).join(", ");
164
+ const rows = await this.sql.unsafe(
165
+ `DELETE FROM ${this.quotedTableName}
166
+ WHERE namespace = $1 AND key = $2 AND member IN (${placeholders})
167
+ RETURNING member`,
168
+ [this.namespace, key, ...values]
169
+ );
170
+ return rows.length;
171
+ }
172
+ async zpopmin(key, count = 1) {
173
+ const rows = await this.sql.unsafe(
174
+ `WITH picked AS (
175
+ SELECT namespace, key, member, score, row_number() OVER (ORDER BY score ASC, member ASC) AS rank
176
+ FROM ${this.quotedTableName}
177
+ WHERE namespace = $1 AND key = $2
178
+ AND (expires_at IS NULL OR expires_at > NOW())
179
+ ORDER BY score ASC, member ASC
180
+ LIMIT $3
181
+ ), deleted AS (
182
+ DELETE FROM ${this.quotedTableName} target
183
+ USING picked
184
+ WHERE target.namespace = picked.namespace
185
+ AND target.key = picked.key
186
+ AND target.member = picked.member
187
+ RETURNING target.member, target.score
188
+ )
189
+ SELECT deleted.member, deleted.score
190
+ FROM deleted
191
+ JOIN picked ON picked.member = deleted.member
192
+ ORDER BY picked.rank ASC`,
193
+ [this.namespace, key, Math.max(1, Math.floor(count))]
194
+ );
195
+ return rows.map((row) => ({ member: row.member, score: Number(row.score) }));
196
+ }
197
+ async zscan(key, cursor = null, count = 100) {
198
+ const limit = Math.max(1, Math.floor(count));
199
+ const rows = await this.sql.unsafe(
200
+ `SELECT member, score
201
+ FROM ${this.quotedTableName}
202
+ WHERE namespace = $1
203
+ AND key = $2
204
+ AND member > COALESCE($3::text, '')
205
+ AND (expires_at IS NULL OR expires_at > NOW())
206
+ ORDER BY member ASC
207
+ LIMIT $4`,
208
+ [this.namespace, key, cursor, limit]
209
+ );
210
+ return {
211
+ cursor: rows.length === limit ? rows[rows.length - 1].member : null,
212
+ entries: rows.map((row) => ({ member: row.member, score: Number(row.score) }))
213
+ };
214
+ }
215
+ async expire(key, ttlMs) {
216
+ const rows = await this.sql.unsafe(
217
+ `UPDATE ${this.quotedTableName}
218
+ SET expires_at = NOW() + ($3::bigint * INTERVAL '1 millisecond'),
219
+ updated_at = NOW()
220
+ WHERE namespace = $1 AND key = $2
221
+ RETURNING member`,
222
+ [this.namespace, key, Math.max(0, Math.floor(ttlMs))]
223
+ );
224
+ return rows.length;
225
+ }
226
+ async persist(key) {
227
+ const rows = await this.sql.unsafe(
228
+ `UPDATE ${this.quotedTableName}
229
+ SET expires_at = NULL,
230
+ updated_at = NOW()
231
+ WHERE namespace = $1 AND key = $2
232
+ RETURNING member`,
233
+ [this.namespace, key]
234
+ );
235
+ return rows.length;
236
+ }
237
+ async ttl(key) {
238
+ const rows = await this.sql.unsafe(
239
+ `SELECT CASE
240
+ WHEN MAX(expires_at) IS NULL THEN NULL
241
+ ELSE GREATEST(0, FLOOR(EXTRACT(EPOCH FROM (MAX(expires_at) - NOW())) * 1000))::bigint
242
+ END AS ttl_ms
243
+ FROM ${this.quotedTableName}
244
+ WHERE namespace = $1 AND key = $2`,
245
+ [this.namespace, key]
246
+ );
247
+ return rows[0]?.ttl_ms === null || rows[0]?.ttl_ms === void 0 ? null : Number(rows[0].ttl_ms);
248
+ }
249
+ async zcard(key) {
250
+ const rows = await this.sql.unsafe(
251
+ `SELECT COUNT(*)::bigint AS count FROM ${this.quotedTableName}
252
+ WHERE namespace = $1 AND key = $2
253
+ AND (expires_at IS NULL OR expires_at > NOW())`,
254
+ [this.namespace, key]
255
+ );
256
+ return Number(rows[0]?.count ?? 0);
257
+ }
258
+ async zrevrange(key, start = 0, stop = -1, options = {}) {
259
+ return this.zrange(key, start, stop, { ...options, desc: true });
260
+ }
261
+ async zincrby(key, amount, member) {
262
+ if (!Number.isFinite(amount)) throw new Error(`Invalid zincrby amount: ${amount}`);
263
+ const rows = await this.sql.unsafe(
264
+ `INSERT INTO ${this.quotedTableName} (namespace, key, member, score, expires_at, updated_at)
265
+ VALUES (
266
+ $1,
267
+ $2,
268
+ $3,
269
+ $4,
270
+ (SELECT MAX(expires_at) FROM ${this.quotedTableName} WHERE namespace = $1 AND key = $2),
271
+ NOW()
272
+ )
273
+ ON CONFLICT (namespace, key, member) DO UPDATE
274
+ SET score = ${this.quotedTableName}.score + EXCLUDED.score,
275
+ updated_at = NOW()
276
+ RETURNING score`,
277
+ [this.namespace, key, member, amount]
278
+ );
279
+ return Number(rows[0]?.score ?? amount);
280
+ }
281
+ async zpopmax(key, count = 1) {
282
+ const rows = await this.sql.unsafe(
283
+ `WITH picked AS (
284
+ SELECT namespace, key, member, score, row_number() OVER (ORDER BY score DESC, member DESC) AS rank
285
+ FROM ${this.quotedTableName}
286
+ WHERE namespace = $1 AND key = $2
287
+ AND (expires_at IS NULL OR expires_at > NOW())
288
+ ORDER BY score DESC, member DESC
289
+ LIMIT $3
290
+ ), deleted AS (
291
+ DELETE FROM ${this.quotedTableName} target
292
+ USING picked
293
+ WHERE target.namespace = picked.namespace
294
+ AND target.key = picked.key
295
+ AND target.member = picked.member
296
+ RETURNING target.member, target.score
297
+ )
298
+ SELECT deleted.member, deleted.score
299
+ FROM deleted
300
+ JOIN picked ON picked.member = deleted.member
301
+ ORDER BY picked.rank ASC`,
302
+ [this.namespace, key, Math.max(1, Math.floor(count))]
303
+ );
304
+ return rows.map((r) => ({ member: r.member, score: Number(r.score) }));
305
+ }
306
+ async cleanupExpired(limit = 1e3) {
307
+ const rows = await this.sql.unsafe(
308
+ `DELETE FROM ${this.quotedTableName}
309
+ WHERE ctid IN (
310
+ SELECT ctid
311
+ FROM ${this.quotedTableName}
312
+ WHERE expires_at IS NOT NULL AND expires_at <= NOW()
313
+ LIMIT $1
314
+ )
315
+ RETURNING member`,
316
+ [Math.max(1, Math.floor(limit))]
317
+ );
318
+ return rows.length;
319
+ }
320
+ };
321
+ function createPgSortedSet(options) {
322
+ return new PgSortedSet(options);
323
+ }
324
+
325
+ export {
326
+ PgSortedSet,
327
+ createPgSortedSet
328
+ };