@postgresx/noredis 0.11.0 → 0.12.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.
Files changed (40) hide show
  1. package/dist/adapters/bun.d.ts +5 -8
  2. package/dist/adapters/ioredis.d.ts +12 -15
  3. package/dist/adapters/ioredis.js +8 -1
  4. package/dist/adapters/node.d.ts +11 -13
  5. package/dist/adapters/redis.d.ts +12 -15
  6. package/dist/adapters/redis.js +8 -1
  7. package/dist/adapters/web.d.ts +11 -16
  8. package/dist/advisory-lock.d.ts +24 -0
  9. package/dist/{chunk-WRMEEA6T.js → chunk-6PU53SX7.js} +16 -2
  10. package/dist/{chunk-HW3WONAC.js → chunk-JRMUZTI4.js} +128 -15
  11. package/dist/{chunk-YSWHEFPX.js → chunk-LN56Y4FI.js} +68 -0
  12. package/dist/client.d.ts +70 -0
  13. package/dist/counter.d.ts +27 -0
  14. package/dist/errors.d.ts +5 -0
  15. package/dist/hash-index.d.ts +1 -43
  16. package/dist/hash.d.ts +40 -0
  17. package/dist/index.d.ts +17 -16
  18. package/dist/index.js +3 -3
  19. package/dist/kv-cache.d.ts +16 -20
  20. package/dist/kv.d.ts +1 -3
  21. package/dist/list-index.d.ts +1 -53
  22. package/dist/list-index.js +1 -1
  23. package/dist/list.d.ts +74 -0
  24. package/dist/metrics.d.ts +48 -0
  25. package/dist/pipeline.d.ts +14 -0
  26. package/dist/pubsub-index.d.ts +1 -60
  27. package/dist/pubsub.d.ts +57 -0
  28. package/dist/queue.d.ts +50 -0
  29. package/dist/rate-limit.d.ts +108 -0
  30. package/dist/redis-aliases.d.ts +129 -0
  31. package/dist/set-index.d.ts +1 -42
  32. package/dist/set.d.ts +39 -0
  33. package/dist/sorted-set-index.d.ts +1 -58
  34. package/dist/sorted-set-index.js +1 -1
  35. package/dist/sorted-set.d.ts +73 -0
  36. package/dist/sql.d.ts +8 -0
  37. package/dist/stream.d.ts +59 -0
  38. package/package.json +4 -4
  39. package/dist/client-ChVkyyno.d.ts +0 -513
  40. package/dist/sql-DKf2TDlu.d.ts +0 -10
@@ -1,13 +1,10 @@
1
- import { P as PgSqlLike } from '../sql-DKf2TDlu.js';
2
-
3
- interface BunSqlAdapterInput {
1
+ import type { PgSqlLike } from "../sql.js";
2
+ export interface BunSqlAdapterInput {
4
3
  unsafe<T = Record<string, unknown>>(query: string, params?: readonly unknown[]): Promise<T[]>;
5
4
  begin?<T>(callback: (tx: PgSqlLike) => Promise<T>): Promise<T>;
6
5
  }
7
- interface BunSqlAdapter extends PgSqlLike {
6
+ export interface BunSqlAdapter extends PgSqlLike {
8
7
  readonly raw: BunSqlAdapterInput;
9
8
  }
10
- declare function createBunSqlAdapter(sql: BunSqlAdapterInput): BunSqlAdapter;
11
- declare const createBunPostgresAdapter: typeof createBunSqlAdapter;
12
-
13
- export { type BunSqlAdapter, type BunSqlAdapterInput, createBunPostgresAdapter, createBunSqlAdapter };
9
+ export declare function createBunSqlAdapter(sql: BunSqlAdapterInput): BunSqlAdapter;
10
+ export declare const createBunPostgresAdapter: typeof createBunSqlAdapter;
@@ -1,12 +1,3 @@
1
- import { Q as PgredisClient, $ as PipelineFacade, U as PgredisMigrationAliases } from '../client-ChVkyyno.js';
2
- import '../kv-cache.js';
3
- import '../pubsub-index.js';
4
- import '../sql-DKf2TDlu.js';
5
- import '../hash-index.js';
6
- import '../list-index.js';
7
- import '../set-index.js';
8
- import '../sorted-set-index.js';
9
-
10
1
  /**
11
2
  * ioredis 兼容外观适配器
12
3
  *
@@ -16,13 +7,14 @@ import '../sorted-set-index.js';
16
7
  * 不安装 ioredis 运行时依赖。用于 NestJS microservices、
17
8
  * cache-manager 等期望 ioredis 接口的场景。
18
9
  */
19
-
20
- interface IoredisAdapterOptions {
10
+ import type { PgredisClient } from "../client.js";
11
+ import { type PgredisMigrationAliases, type PipelineFacade } from "../redis-aliases.js";
12
+ export interface IoredisAdapterOptions {
21
13
  client: PgredisClient;
22
14
  /** 是否将不支持命令静默返回 null 而非抛错,默认 false */
23
15
  silentUnsupported?: boolean;
24
16
  }
25
- interface IoredisLikeAdapter {
17
+ export interface IoredisLikeAdapter {
26
18
  get(key: string): Promise<string | null>;
27
19
  set(key: string, value: string, ...args: unknown[]): Promise<"OK" | null>;
28
20
  del(...keys: string[]): Promise<number>;
@@ -75,6 +67,9 @@ interface IoredisLikeAdapter {
75
67
  llen(key: string): Promise<number>;
76
68
  lrange(key: string, start?: number, stop?: number): Promise<string[]>;
77
69
  lrem(key: string, count: number, value: string): Promise<number>;
70
+ ltrim(key: string, start?: number, stop?: number): Promise<"OK">;
71
+ lindex(key: string, index: number): Promise<string | null>;
72
+ lset(key: string, index: number, value: string): Promise<"OK">;
78
73
  sadd(key: string, ...members: string[]): Promise<number>;
79
74
  srem(key: string, ...members: string[]): Promise<number>;
80
75
  smembers(key: string): Promise<string[]>;
@@ -97,6 +92,10 @@ interface IoredisLikeAdapter {
97
92
  zrank(key: string, member: string): Promise<number | null>;
98
93
  zcount(key: string, min: number, max: number): Promise<number>;
99
94
  zrem(key: string, ...members: string[]): Promise<number>;
95
+ zremrangebyscore(key: string, min: number | string, max: number | string): Promise<number>;
96
+ zremrangebyrank(key: string, start: number, stop: number): Promise<number>;
97
+ zmscore(key: string, ...members: string[]): Promise<Array<number | null>>;
98
+ zrevrank(key: string, member: string): Promise<number | null>;
100
99
  zcard(key: string): Promise<number>;
101
100
  zincrby(key: string, amount: number, member: string): Promise<number>;
102
101
  zpopmin(key: string, count?: number): Promise<Array<{
@@ -125,6 +124,4 @@ interface IoredisLikeAdapter {
125
124
  /** 底层 noredis 客户端 */
126
125
  readonly noredis: PgredisMigrationAliases;
127
126
  }
128
- declare function createIoredisAdapter(options: IoredisAdapterOptions): IoredisLikeAdapter;
129
-
130
- export { type IoredisAdapterOptions, type IoredisLikeAdapter, createIoredisAdapter };
127
+ export declare function createIoredisAdapter(options: IoredisAdapterOptions): IoredisLikeAdapter;
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createPgredisMigrationAliases
3
- } from "../chunk-WRMEEA6T.js";
3
+ } from "../chunk-6PU53SX7.js";
4
4
 
5
5
  // src/adapters/ioredis.ts
6
6
  function str(v) {
@@ -85,6 +85,9 @@ function createIoredisAdapter(options) {
85
85
  llen: (key) => aliases.llen(key),
86
86
  lrange: (key, start, stop) => aliases.lrange(key, start, stop).then(strArr),
87
87
  lrem: (key, count, value) => aliases.lrem(key, count, value),
88
+ ltrim: (key, start, stop) => aliases.ltrim(key, start, stop),
89
+ lindex: (key, index) => aliases.lindex(key, index).then(str),
90
+ lset: (key, index, value) => aliases.lset(key, index, value),
88
91
  // Set
89
92
  sadd: (key, ...members) => aliases.sadd(key, ...members),
90
93
  srem: (key, ...members) => aliases.srem(key, ...members),
@@ -113,6 +116,10 @@ function createIoredisAdapter(options) {
113
116
  zrank: (key, member) => aliases.zrank(key, member),
114
117
  zcount: (key, min, max) => aliases.zcount(key, min, max),
115
118
  zrem: (key, ...members) => aliases.zrem(key, ...members),
119
+ zremrangebyscore: (key, min, max) => aliases.zremrangebyscore(key, Number(min), Number(max)),
120
+ zremrangebyrank: (key, start, stop) => aliases.zremrangebyrank(key, start, stop),
121
+ zmscore: (key, ...members) => aliases.zmscore(key, ...members),
122
+ zrevrank: (key, member) => aliases.zrevrank(key, member),
116
123
  zcard: (key) => aliases.zcard(key),
117
124
  zincrby: (key, amount, member) => aliases.zincrby(key, amount, member),
118
125
  zpopmin: (key, count) => aliases.zpopmin(key, count),
@@ -1,22 +1,20 @@
1
- import { Pool, ClientConfig, PoolConfig } from 'pg';
2
- import { NotifyHandler, PgListenerHandle } from '../pubsub-index.js';
3
- import { P as PgSqlLike } from '../sql-DKf2TDlu.js';
4
-
5
- type PgConnectionInput = string | PoolConfig | Pool;
6
- interface NodePgAdapter extends PgSqlLike {
7
- getPool(): Promise<Pool>;
1
+ import type { ClientConfig, Pool as PgPool, PoolConfig } from "pg";
2
+ import type { NotifyHandler, PgListenerHandle } from "../pubsub.js";
3
+ import type { PgSqlLike } from "../sql.js";
4
+ export type PgConnectionInput = string | PoolConfig | PgPool;
5
+ export interface NodePgAdapter extends PgSqlLike {
6
+ getPool(): Promise<PgPool>;
8
7
  close(): Promise<void>;
9
8
  }
10
- declare function createPgAdapter(input: PgConnectionInput): NodePgAdapter;
11
- declare const createNodePostgresAdapter: typeof createPgAdapter;
9
+ export declare function createPgAdapter(input: PgConnectionInput): NodePgAdapter;
10
+ export declare const createNodePostgresAdapter: typeof createPgAdapter;
12
11
  type ListenerLogger = Partial<Pick<typeof console, "debug" | "info" | "warn" | "error">>;
13
- interface NodePgListenerOptions extends ClientConfig {
12
+ export interface NodePgListenerOptions extends ClientConfig {
14
13
  channels?: string[];
15
14
  onNotify?: NotifyHandler;
16
15
  reconnectDelayMs?: number | ((attempt: number) => number);
17
16
  healthCheckIntervalMs?: number;
18
17
  logger?: ListenerLogger | false;
19
18
  }
20
- declare function createPgNodeListener(input: string | ClientConfig, options?: NodePgListenerOptions): PgListenerHandle;
21
-
22
- export { type NodePgAdapter, type NodePgListenerOptions, type PgConnectionInput, createNodePostgresAdapter, createPgAdapter, createPgNodeListener };
19
+ export declare function createPgNodeListener(input: string | ClientConfig, options?: NodePgListenerOptions): PgListenerHandle;
20
+ export {};
@@ -1,12 +1,3 @@
1
- import { Q as PgredisClient, $ as PipelineFacade, U as PgredisMigrationAliases } from '../client-ChVkyyno.js';
2
- import '../kv-cache.js';
3
- import '../pubsub-index.js';
4
- import '../sql-DKf2TDlu.js';
5
- import '../hash-index.js';
6
- import '../list-index.js';
7
- import '../set-index.js';
8
- import '../sorted-set-index.js';
9
-
10
1
  /**
11
2
  * redis.js (node-redis) 兼容外观适配器
12
3
  *
@@ -15,11 +6,12 @@ import '../sorted-set-index.js';
15
6
  *
16
7
  * 不安装 redis 运行时依赖。
17
8
  */
18
-
19
- interface RedisJsAdapterOptions {
9
+ import type { PgredisClient } from "../client.js";
10
+ import { type PgredisMigrationAliases, type PipelineFacade } from "../redis-aliases.js";
11
+ export interface RedisJsAdapterOptions {
20
12
  client: PgredisClient;
21
13
  }
22
- interface RedisJsLikeAdapter {
14
+ export interface RedisJsLikeAdapter {
23
15
  get(key: string): Promise<string | null>;
24
16
  set(key: string, value: string, options?: {
25
17
  EX?: number;
@@ -83,6 +75,9 @@ interface RedisJsLikeAdapter {
83
75
  lLen(key: string): Promise<number>;
84
76
  lRange(key: string, start?: number, stop?: number): Promise<string[]>;
85
77
  lRem(key: string, count: number, value: string): Promise<number>;
78
+ lTrim(key: string, start?: number, stop?: number): Promise<"OK">;
79
+ lIndex(key: string, index: number): Promise<string | null>;
80
+ lSet(key: string, index: number, value: string): Promise<"OK">;
86
81
  sAdd(key: string, ...members: string[]): Promise<number>;
87
82
  sRem(key: string, ...members: string[]): Promise<number>;
88
83
  sMembers(key: string): Promise<string[]>;
@@ -108,6 +103,10 @@ interface RedisJsLikeAdapter {
108
103
  zRank(key: string, member: string): Promise<number | null>;
109
104
  zCount(key: string, min: number, max: number): Promise<number>;
110
105
  zRem(key: string, ...members: string[]): Promise<number>;
106
+ zRemRangeByScore(key: string, min: number | string, max: number | string): Promise<number>;
107
+ zRemRangeByRank(key: string, start: number, stop: number): Promise<number>;
108
+ zMScore(key: string, ...members: string[]): Promise<Array<number | null>>;
109
+ zRevRank(key: string, member: string): Promise<number | null>;
111
110
  zCard(key: string): Promise<number>;
112
111
  zIncrBy(key: string, amount: number, member: string): Promise<number>;
113
112
  zPopMin(key: string, count?: number): Promise<Array<{
@@ -138,6 +137,4 @@ interface RedisJsLikeAdapter {
138
137
  /** 底层 noredis 客户端 */
139
138
  readonly noredis: PgredisMigrationAliases;
140
139
  }
141
- declare function createRedisJsAdapter(options: RedisJsAdapterOptions): RedisJsLikeAdapter;
142
-
143
- export { type RedisJsAdapterOptions, type RedisJsLikeAdapter, createRedisJsAdapter };
140
+ export declare function createRedisJsAdapter(options: RedisJsAdapterOptions): RedisJsLikeAdapter;
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createPgredisMigrationAliases
3
- } from "../chunk-WRMEEA6T.js";
3
+ } from "../chunk-6PU53SX7.js";
4
4
 
5
5
  // src/adapters/redis.ts
6
6
  function str(v) {
@@ -69,6 +69,9 @@ function createRedisJsAdapter(options) {
69
69
  lLen: (key) => aliases.llen(key),
70
70
  lRange: (key, start, stop) => aliases.lrange(key, start, stop).then(strArr),
71
71
  lRem: (key, count, value) => aliases.lrem(key, count, value),
72
+ lTrim: (key, start, stop) => aliases.ltrim(key, start, stop),
73
+ lIndex: (key, index) => aliases.lindex(key, index).then(str),
74
+ lSet: (key, index, value) => aliases.lset(key, index, value),
72
75
  // Set
73
76
  sAdd: (key, ...members) => aliases.sadd(key, ...members),
74
77
  sRem: (key, ...members) => aliases.srem(key, ...members),
@@ -91,6 +94,10 @@ function createRedisJsAdapter(options) {
91
94
  zRank: (key, member) => aliases.zrank(key, member),
92
95
  zCount: (key, min, max) => aliases.zcount(key, min, max),
93
96
  zRem: (key, ...members) => aliases.zrem(key, ...members),
97
+ zRemRangeByScore: (key, min, max) => aliases.zremrangebyscore(key, Number(min), Number(max)),
98
+ zRemRangeByRank: (key, start, stop) => aliases.zremrangebyrank(key, start, stop),
99
+ zMScore: (key, ...members) => aliases.zmscore(key, ...members),
100
+ zRevRank: (key, member) => aliases.zrevrank(key, member),
94
101
  zCard: (key) => aliases.zcard(key),
95
102
  zIncrBy: (key, amount, member) => aliases.zincrby(key, amount, member),
96
103
  zPopMin: (key, count) => aliases.zpopmin(key, count),
@@ -1,32 +1,27 @@
1
- import { PgKvSetOptions, PgKvCache } from '../kv-cache.js';
2
- import '../pubsub-index.js';
3
- import '../sql-DKf2TDlu.js';
4
-
5
- type SessionCallback<T = unknown> = (error?: unknown, value?: T | null) => void;
6
- interface PgredisSessionStoreOptions {
1
+ import type { PgKvCache, PgKvSetOptions } from "../kv-cache.js";
2
+ export type SessionCallback<T = unknown> = (error?: unknown, value?: T | null) => void;
3
+ export interface PgredisSessionStoreOptions {
7
4
  prefix?: string;
8
5
  ttlMs?: number;
9
6
  }
10
- interface PgredisCacheHelperOptions {
7
+ export interface PgredisCacheHelperOptions {
11
8
  prefix?: string;
12
9
  ttlMs?: number;
13
10
  }
14
- interface PgredisSessionStore {
11
+ export interface PgredisSessionStore {
15
12
  get(sessionId: string, callback?: SessionCallback): Promise<unknown | null> | void;
16
13
  set(sessionId: string, session: unknown, callback?: SessionCallback<void>): Promise<void> | void;
17
14
  destroy(sessionId: string, callback?: SessionCallback<void>): Promise<void> | void;
18
15
  touch(sessionId: string, session: unknown, callback?: SessionCallback<void>): Promise<void> | void;
19
16
  }
20
- interface PgredisCacheHelpers {
17
+ export interface PgredisCacheHelpers {
21
18
  get<T = unknown>(key: string): Promise<T | null>;
22
19
  set<T = unknown>(key: string, value: T, options?: PgKvSetOptions): Promise<boolean>;
23
20
  delete(key: string): Promise<boolean>;
24
21
  wrap<T>(key: string, loader: () => Promise<T> | T, options?: PgKvSetOptions): Promise<T>;
25
22
  }
26
- declare function createPgredisSessionStore(cache: PgKvCache, options?: PgredisSessionStoreOptions): PgredisSessionStore;
27
- declare const createExpressSessionStore: typeof createPgredisSessionStore;
28
- declare const createFastifySessionStore: typeof createPgredisSessionStore;
29
- declare const createElysiaSessionStore: typeof createPgredisSessionStore;
30
- declare function createPgredisCacheHelpers(cache: PgKvCache, options?: PgredisCacheHelperOptions): PgredisCacheHelpers;
31
-
32
- export { type PgredisCacheHelperOptions, type PgredisCacheHelpers, type PgredisSessionStore, type PgredisSessionStoreOptions, type SessionCallback, createElysiaSessionStore, createExpressSessionStore, createFastifySessionStore, createPgredisCacheHelpers, createPgredisSessionStore };
23
+ export declare function createPgredisSessionStore(cache: PgKvCache, options?: PgredisSessionStoreOptions): PgredisSessionStore;
24
+ export declare const createExpressSessionStore: typeof createPgredisSessionStore;
25
+ export declare const createFastifySessionStore: typeof createPgredisSessionStore;
26
+ export declare const createElysiaSessionStore: typeof createPgredisSessionStore;
27
+ export declare function createPgredisCacheHelpers(cache: PgKvCache, options?: PgredisCacheHelperOptions): PgredisCacheHelpers;
@@ -0,0 +1,24 @@
1
+ import type { PgSqlLike } from "./sql.js";
2
+ export type PgAdvisoryLockKey = string | number | bigint | readonly [number, number];
3
+ export interface PgAdvisoryLockOptions {
4
+ wait?: boolean;
5
+ lockTimeoutMs?: number;
6
+ transaction?: <T>(callback: (tx: PgSqlLike) => Promise<T>) => Promise<T>;
7
+ }
8
+ export declare class PgAdvisoryLockBusyError extends Error {
9
+ readonly key: PgAdvisoryLockKey;
10
+ constructor(key: PgAdvisoryLockKey);
11
+ }
12
+ interface LockSqlArgs {
13
+ expression: string;
14
+ params: readonly unknown[];
15
+ }
16
+ export declare function advisoryLockKeyToSqlArgs(key: PgAdvisoryLockKey): LockSqlArgs;
17
+ export declare function withPgAdvisoryLock<T>(sql: PgSqlLike, key: PgAdvisoryLockKey, callback: (tx: PgSqlLike) => Promise<T>, options?: PgAdvisoryLockOptions): Promise<T>;
18
+ export declare class PgAdvisoryLocker {
19
+ private readonly sql;
20
+ constructor(sql: PgSqlLike);
21
+ withLock<T>(key: PgAdvisoryLockKey, callback: (tx: PgSqlLike) => Promise<T>, options?: PgAdvisoryLockOptions): Promise<T>;
22
+ }
23
+ export declare function createPgAdvisoryLocker(sql: PgSqlLike): PgAdvisoryLocker;
24
+ export {};
@@ -158,8 +158,18 @@ function createPgredisMigrationAliases(client) {
158
158
  },
159
159
  llen: (key) => client.list.llen(key),
160
160
  lrange: (key, start, stop) => client.list.lrange(key, start, stop),
161
- async lrem() {
162
- throw new UnsupportedCommandError("lrem");
161
+ async lrem(key, count, value) {
162
+ return client.list.lrem(key, count, value);
163
+ },
164
+ async ltrim(key, start = 0, stop = -1) {
165
+ await client.list.ltrim(key, start, stop);
166
+ return "OK";
167
+ },
168
+ lindex: (key, index) => client.list.lindex(key, index),
169
+ async lset(key, index, value) {
170
+ const replaced = await client.list.lset(key, index, value);
171
+ if (!replaced) throw new Error("lset: index out of range");
172
+ return "OK";
163
173
  },
164
174
  // Set
165
175
  sadd: (key, ...members) => client.set.sadd(key, ...members),
@@ -202,6 +212,10 @@ function createPgredisMigrationAliases(client) {
202
212
  zrank: (key, member) => client.sortedSet.zrank(key, member),
203
213
  zcount: (key, min, max) => client.sortedSet.zcount(key, min, max),
204
214
  zrem: (key, ...members) => client.sortedSet.zrem(key, ...members),
215
+ zremrangebyscore: (key, min, max) => client.sortedSet.zremrangebyscore(key, min, max),
216
+ zremrangebyrank: (key, start, stop) => client.sortedSet.zremrangebyrank(key, start, stop),
217
+ zmscore: (key, ...members) => client.sortedSet.zmscore(key, ...members),
218
+ zrevrank: (key, member) => client.sortedSet.zrevrank(key, member),
205
219
  zcard: (key) => client.sortedSet.zcard(key),
206
220
  zincrby: (key, amount, member) => client.sortedSet.zincrby(key, amount, member),
207
221
  zpopmin: (key, count) => client.sortedSet.zpopmin(key, count),
@@ -76,18 +76,129 @@ var PgList = class {
76
76
  return this.blockingPop(keys, "right", options);
77
77
  }
78
78
  async lrange(key, start = 0, stop = -1) {
79
- const limit = stop < 0 ? null : Math.max(0, stop - start + 1);
79
+ const rows = await this.selectSlice(key, start, stop);
80
+ return rows.map((row) => row.value);
81
+ }
82
+ /**
83
+ * LINDEX: the element at a zero-based index, negative counting from the
84
+ * tail. Returns null when the index is out of range.
85
+ */
86
+ async lindex(key, index = 0) {
87
+ const rows = await this.selectSlice(key, index, index);
88
+ return rows.length === 0 ? null : rows[0].value;
89
+ }
90
+ /**
91
+ * LSET: overwrite the element at a zero-based index, negative counting from
92
+ * the tail. Returns false when the index is out of range, which is the error
93
+ * Redis reports for the same input.
94
+ */
95
+ async lset(key, index, value) {
80
96
  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]
97
+ `WITH ordered AS (
98
+ SELECT id,
99
+ (row_number() OVER (ORDER BY position ASC, id ASC) - 1)::bigint AS idx,
100
+ count(*) OVER () AS total
101
+ FROM ${this.quotedTableName}
102
+ WHERE namespace = $1 AND key = $2
103
+ AND (expires_at IS NULL OR expires_at > NOW())
104
+ ), target AS (
105
+ SELECT id
106
+ FROM ordered
107
+ WHERE ordered.idx = CASE WHEN $3::bigint < 0 THEN ordered.total + $3::bigint ELSE $3::bigint END
108
+ )
109
+ UPDATE ${this.quotedTableName} target_row
110
+ SET value = $4::jsonb
111
+ FROM target
112
+ WHERE target_row.id = target.id
113
+ RETURNING target_row.id`,
114
+ [this.namespace, key, Math.trunc(index), jsonValue(value)]
89
115
  );
90
- return rows.map((row) => parseValue(row.value));
116
+ return rows.length > 0;
117
+ }
118
+ /**
119
+ * LTRIM: keep the inclusive [start, stop] range, negative counting from the
120
+ * tail, and delete everything outside it. Returns the number of removed
121
+ * elements. Redis itself answers OK.
122
+ */
123
+ async ltrim(key, start = 0, stop = -1) {
124
+ const rows = await this.sql.unsafe(
125
+ `WITH ordered AS (
126
+ SELECT id,
127
+ (row_number() OVER (ORDER BY position ASC, id ASC) - 1)::bigint AS idx,
128
+ count(*) OVER () AS total
129
+ FROM ${this.quotedTableName}
130
+ WHERE namespace = $1 AND key = $2
131
+ AND (expires_at IS NULL OR expires_at > NOW())
132
+ ), bounds AS (
133
+ SELECT CASE WHEN $3::bigint < 0 THEN total + $3::bigint ELSE $3::bigint END AS keep_from,
134
+ CASE WHEN $4::bigint < 0 THEN total + $4::bigint ELSE $4::bigint END AS keep_to
135
+ FROM ordered
136
+ LIMIT 1
137
+ ), discarded AS (
138
+ SELECT ordered.id
139
+ FROM ordered, bounds
140
+ WHERE ordered.idx < bounds.keep_from OR ordered.idx > bounds.keep_to
141
+ )
142
+ DELETE FROM ${this.quotedTableName} target_row
143
+ USING discarded
144
+ WHERE target_row.id = discarded.id
145
+ RETURNING target_row.id`,
146
+ [this.namespace, key, Math.trunc(start), Math.trunc(stop)]
147
+ );
148
+ return rows.length;
149
+ }
150
+ /**
151
+ * LREM: remove occurrences of value. count > 0 removes from the head, count
152
+ * < 0 from the tail, count = 0 removes every occurrence. Returns the number
153
+ * of removed elements.
154
+ */
155
+ async lrem(key, count = 0, value) {
156
+ const order = count < 0 ? "DESC" : "ASC";
157
+ const limit = count === 0 ? null : Math.abs(Math.trunc(count));
158
+ const rows = await this.sql.unsafe(
159
+ `WITH matched AS (
160
+ SELECT id
161
+ FROM ${this.quotedTableName}
162
+ WHERE namespace = $1 AND key = $2
163
+ AND (expires_at IS NULL OR expires_at > NOW())
164
+ AND value = $3::jsonb
165
+ ORDER BY position ${order}, id ${order}
166
+ LIMIT COALESCE($4::bigint, 9223372036854775807)
167
+ )
168
+ DELETE FROM ${this.quotedTableName} target_row
169
+ USING matched
170
+ WHERE target_row.id = matched.id
171
+ RETURNING target_row.id`,
172
+ [this.namespace, key, jsonValue(value), limit]
173
+ );
174
+ return rows.length;
175
+ }
176
+ // selectSlice resolves Redis-style inclusive indices over the live rows.
177
+ // Both ends accept negative offsets counting from the tail, which the former
178
+ // OFFSET/LIMIT form could not express: lrange(key, 0, -2) returned everything.
179
+ async selectSlice(key, start, stop) {
180
+ const rows = await this.sql.unsafe(
181
+ `WITH ordered AS (
182
+ SELECT value,
183
+ (row_number() OVER (ORDER BY position ASC, id ASC) - 1)::bigint AS idx,
184
+ count(*) OVER () AS total
185
+ FROM ${this.quotedTableName}
186
+ WHERE namespace = $1 AND key = $2
187
+ AND (expires_at IS NULL OR expires_at > NOW())
188
+ ), bounds AS (
189
+ SELECT CASE WHEN $3::bigint < 0 THEN total + $3::bigint ELSE $3::bigint END AS slice_from,
190
+ CASE WHEN $4::bigint < 0 THEN total + $4::bigint ELSE $4::bigint END AS slice_to
191
+ FROM ordered
192
+ LIMIT 1
193
+ )
194
+ SELECT ordered.idx, ordered.value
195
+ FROM ordered, bounds
196
+ WHERE ordered.idx >= GREATEST(bounds.slice_from, 0)
197
+ AND ordered.idx <= bounds.slice_to
198
+ ORDER BY ordered.idx ASC`,
199
+ [this.namespace, key, Math.trunc(start), Math.trunc(stop)]
200
+ );
201
+ return rows.map((row) => ({ idx: Number(row.idx), value: parseValue(row.value) }));
91
202
  }
92
203
  async llen(key) {
93
204
  const rows = await this.sql.unsafe(
@@ -110,14 +221,16 @@ var PgList = class {
110
221
  }
111
222
  async push(key, values, side) {
112
223
  if (values.length === 0) return this.llen(key);
113
- const base = this.now();
224
+ const nowParam = `$${values.length * 3 + 1}`;
225
+ const anchor = side === "left" ? `(SELECT LEAST(COALESCE(MIN(position) - 1, ${nowParam}::double precision), ${nowParam}::double precision) FROM ${this.quotedTableName} WHERE namespace = $1 AND key = $2)` : `(SELECT GREATEST(COALESCE(MAX(position) + 1, ${nowParam}::double precision), ${nowParam}::double precision) FROM ${this.quotedTableName} WHERE namespace = $1 AND key = $2)`;
114
226
  const params = [];
115
227
  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())`;
228
+ const position = side === "left" ? `${anchor} - ${values.length - 1 - index}` : `${anchor} + ${index}`;
229
+ const paramIndex = index * 3;
230
+ params.push(this.namespace, key, jsonValue(value));
231
+ return `($${paramIndex + 1}, $${paramIndex + 2}, ${position}, $${paramIndex + 3}::jsonb, (SELECT MAX(expires_at) FROM ${this.quotedTableName} WHERE namespace = $${paramIndex + 1} AND key = $${paramIndex + 2}), NOW())`;
120
232
  }).join(", ");
233
+ params.push(this.now());
121
234
  await this.sql.unsafe(
122
235
  `INSERT INTO ${this.quotedTableName} (namespace, key, position, value, expires_at, created_at)
123
236
  VALUES ${groups}`,
@@ -169,6 +169,70 @@ var PgSortedSet = class {
169
169
  );
170
170
  return rows.length;
171
171
  }
172
+ /**
173
+ * ZREMRANGEBYSCORE: delete every member whose score falls in the inclusive
174
+ * [min, max] range. Returns the number of removed members.
175
+ */
176
+ async zremrangebyscore(key, min = Number.NEGATIVE_INFINITY, max = Number.POSITIVE_INFINITY) {
177
+ const rows = await this.sql.unsafe(
178
+ `DELETE FROM ${this.quotedTableName}
179
+ WHERE namespace = $1 AND key = $2 AND score >= $3 AND score <= $4
180
+ RETURNING member`,
181
+ [this.namespace, key, min, max]
182
+ );
183
+ return rows.length;
184
+ }
185
+ /**
186
+ * ZREMRANGEBYRANK: delete every member whose rank falls in the inclusive
187
+ * [start, stop] range, negative offsets counting from the tail. Returns the
188
+ * number of removed members.
189
+ */
190
+ async zremrangebyrank(key, start = 0, stop = -1) {
191
+ const rows = await this.sql.unsafe(
192
+ `WITH ordered AS (
193
+ SELECT member,
194
+ (row_number() OVER (ORDER BY score ASC, member ASC) - 1)::bigint AS idx,
195
+ count(*) OVER () AS total
196
+ FROM ${this.quotedTableName}
197
+ WHERE namespace = $1 AND key = $2
198
+ AND (expires_at IS NULL OR expires_at > NOW())
199
+ ), bounds AS (
200
+ SELECT CASE WHEN $3::bigint < 0 THEN total + $3::bigint ELSE $3::bigint END AS range_from,
201
+ CASE WHEN $4::bigint < 0 THEN total + $4::bigint ELSE $4::bigint END AS range_to
202
+ FROM ordered
203
+ LIMIT 1
204
+ ), victims AS (
205
+ SELECT ordered.member
206
+ FROM ordered, bounds
207
+ WHERE ordered.idx >= GREATEST(bounds.range_from, 0)
208
+ AND ordered.idx <= bounds.range_to
209
+ )
210
+ DELETE FROM ${this.quotedTableName} target_row
211
+ USING victims
212
+ WHERE target_row.namespace = $1
213
+ AND target_row.key = $2
214
+ AND target_row.member = victims.member
215
+ RETURNING target_row.member`,
216
+ [this.namespace, key, Math.trunc(start), Math.trunc(stop)]
217
+ );
218
+ return rows.length;
219
+ }
220
+ /**
221
+ * ZMSCORE: the score of every requested member, in argument order, with null
222
+ * for the members that are absent or expired.
223
+ */
224
+ async zmscore(key, ...members) {
225
+ if (members.length === 0) return [];
226
+ const rows = await this.sql.unsafe(
227
+ `SELECT member, score
228
+ FROM ${this.quotedTableName}
229
+ WHERE namespace = $1 AND key = $2 AND member = ANY($3::text[])
230
+ AND (expires_at IS NULL OR expires_at > NOW())`,
231
+ [this.namespace, key, members]
232
+ );
233
+ const scores = new Map(rows.map((row) => [row.member, Number(row.score)]));
234
+ return members.map((member) => scores.get(member) ?? null);
235
+ }
172
236
  async zpopmin(key, count = 1) {
173
237
  const rows = await this.sql.unsafe(
174
238
  `WITH picked AS (
@@ -258,6 +322,10 @@ var PgSortedSet = class {
258
322
  async zrevrange(key, start = 0, stop = -1, options = {}) {
259
323
  return this.zrange(key, start, stop, { ...options, desc: true });
260
324
  }
325
+ /** ZREVRANK: the rank counting from the highest score. */
326
+ async zrevrank(key, member) {
327
+ return this.zrank(key, member, { desc: true });
328
+ }
261
329
  async zincrby(key, amount, member) {
262
330
  if (!Number.isFinite(amount)) throw new Error(`Invalid zincrby amount: ${amount}`);
263
331
  const rows = await this.sql.unsafe(
@@ -0,0 +1,70 @@
1
+ import { type PgKvCache, type PgKvCacheOptions } from "./kv-cache.js";
2
+ import { type PgAdvisoryLocker } from "./advisory-lock.js";
3
+ import { type PgCounter } from "./counter.js";
4
+ import { type PgHash } from "./hash.js";
5
+ import { type PgList } from "./list.js";
6
+ import { type PgredisCleanupMetrics, type PgredisMetrics } from "./metrics.js";
7
+ import { PgredisPipeline, type PgredisBatchOperation } from "./pipeline.js";
8
+ import { type PgPublisher } from "./pubsub.js";
9
+ import { type PgBossJobQueue, type PgBossQueueOptions, type QueueResult } from "./queue.js";
10
+ import { type PgFixedWindowRateLimiter } from "./rate-limit.js";
11
+ import { type PgredisMigrationAliases } from "./redis-aliases.js";
12
+ import { type PgSet } from "./set.js";
13
+ import { type PgSortedSet } from "./sorted-set.js";
14
+ import type { PgSqlLike } from "./sql.js";
15
+ import { type PgOutboxStream } from "./stream.js";
16
+ export interface PgredisOptions {
17
+ sql: PgSqlLike;
18
+ namespace?: string;
19
+ tablePrefix?: string;
20
+ cache?: Omit<PgKvCacheOptions, "sql" | "namespace" | "tableName"> & {
21
+ tableName?: string;
22
+ };
23
+ rateLimit?: {
24
+ limit: number;
25
+ windowMs: number;
26
+ tableName?: string;
27
+ };
28
+ queue?: PgBossQueueOptions | string;
29
+ outbox?: {
30
+ tableName?: string;
31
+ };
32
+ }
33
+ export interface PgredisSchemaOptions {
34
+ /** Controls cache-style primitives; the durable outbox always remains logged. */
35
+ unlogged?: boolean;
36
+ }
37
+ export interface PgredisClient {
38
+ cache: PgKvCache;
39
+ counter: PgCounter;
40
+ hash: PgHash;
41
+ set: PgSet;
42
+ list: PgList;
43
+ sortedSet: PgSortedSet;
44
+ locks: PgAdvisoryLocker;
45
+ pubsub: PgPublisher;
46
+ rateLimit?: PgFixedWindowRateLimiter;
47
+ queue?: PgBossJobQueue;
48
+ outbox: PgOutboxStream;
49
+ stream: PgOutboxStream;
50
+ redis: PgredisMigrationAliases;
51
+ batch<T>(operation: PgredisBatchOperation<T>): Promise<T>;
52
+ pipeline(): PgredisPipeline;
53
+ health(): Promise<{
54
+ ok: true;
55
+ }>;
56
+ stats(): Promise<{
57
+ cache: ReturnType<PgKvCache["stats"]>;
58
+ queue?: QueueResult[];
59
+ cleanup: PgredisCleanupMetrics;
60
+ }>;
61
+ metrics(): Promise<PgredisMetrics>;
62
+ cleanupExpired(limit?: number): Promise<Record<string, number>>;
63
+ startCleanupWorker(options?: {
64
+ intervalMs?: number;
65
+ limit?: number;
66
+ onError?: (error: unknown) => void;
67
+ }): () => void;
68
+ ensureSchema(options?: PgredisSchemaOptions): Promise<void>;
69
+ }
70
+ export declare function createPgredis(options: PgredisOptions): PgredisClient;