@@ -38,35 +38,40 @@ export async function run(
3838 // `TokenBucket` is an unlogged table which are significantly faster to
3939 // write to than regular tables, but are not durable. This is important
4040 // because this script will be called on every request.
41- const rows = await ctx . db . $queryRaw < TokenBucket [ ] > `
42- WITH updated_bucket AS (
43- UPDATE "TokenBuckets" b
41+ const rows = await ctx . db . $queryRawUnsafe < TokenBucket [ ] > (
42+ `
43+ WITH
44+ "UpdateBucket" AS (
45+ UPDATE "${ ctx . dbSchema } "."TokenBuckets" b
4446 SET
4547 "tokens" = CASE
4648 -- Reset the bucket and consume 1 token
47- WHEN now() > b."lastRefill" + make_interval(secs => ${ req . period } ) THEN ${
48- req . requests - 1
49- }
49+ WHEN now() > b."lastRefill" + make_interval(secs => $4) THEN $3 - 1
5050 -- Consume 1 token
5151 ELSE b.tokens - 1
5252 END,
5353 "lastRefill" = CASE
54- WHEN now() > b."lastRefill" + make_interval(secs => ${ req . period } ) THEN now()
54+ WHEN now() > b."lastRefill" + make_interval(secs => $4 ) THEN now()
5555 ELSE b."lastRefill"
5656 END
57- WHERE b."type" = ${ req . type } AND b."key" = ${ req . key }
57+ WHERE b."type" = $1 AND b."key" = $2
5858 RETURNING b."tokens", b."lastRefill"
5959 ),
6060 inserted AS (
61- INSERT INTO "TokenBuckets" ("type", "key", "tokens", "lastRefill")
62- SELECT ${ req . type } , ${ req . key } , ${ req . requests - 1 } , now()
63- WHERE NOT EXISTS (SELECT 1 FROM updated_bucket )
61+ INSERT INTO "${ ctx . dbSchema } "." TokenBuckets" ("type", "key", "tokens", "lastRefill")
62+ SELECT $1 , $2, $3 - 1, now()
63+ WHERE NOT EXISTS (SELECT 1 FROM "UpdateBucket" )
6464 RETURNING "tokens", "lastRefill"
6565 )
66- SELECT * FROM updated_bucket
66+ SELECT * FROM "UpdateBucket"
6767 UNION ALL
6868 SELECT * FROM inserted;
69- ` ;
69+ ` ,
70+ req . type ,
71+ req . key ,
72+ req . requests ,
73+ req . period ,
74+ ) ;
7075 const { tokens, lastRefill } = rows [ 0 ] ;
7176
7277 // If the bucket is empty, throw an error
0 commit comments