[auth] optimize ban query

This commit is contained in:
Devin Zuczek
2026-10-27 23:06:06 -04:00
parent 6f5fd27fa8
commit 1d55ae8b80
3 changed files with 33 additions and 11 deletions
@@ -0,0 +1,15 @@
-- Expose the account's `signupIp` and `deviceId` (both in the JSON blob) as indexed
-- generated columns, so the signup caps (`countAccountsBySignupIp`,
-- `countAccountsByDeviceId` in @repo/domain's accounts-db.ts) are an index lookup
-- instead of running json_extract over every account. The IP count alone was a third
-- of D1's query time, and both run on every account creation.
--
-- Same construction as `has_plus` (0009) and `is_influencer` (0012), but a full index
-- rather than a partial one: the lookup is by value, not by a fixed flag. Kept in sync
-- with SCHEMA_DDL in @repo/domain's accounts-db.ts (and its mirror in
-- apps/econ/src/avatar-db.ts).
ALTER TABLE account ADD COLUMN signup_ip TEXT GENERATED ALWAYS AS (json_extract(data, '$.signupIp')) VIRTUAL;
ALTER TABLE account ADD COLUMN device_id TEXT GENERATED ALWAYS AS (json_extract(data, '$.deviceId')) VIRTUAL;
CREATE INDEX IF NOT EXISTS idx_account_signup_ip ON account (signup_ip);
CREATE INDEX IF NOT EXISTS idx_account_device_id ON account (device_id);
+5 -1
View File
@@ -17,11 +17,15 @@ export const SCHEMA_DDL: string[] = [
account_id INTEGER GENERATED ALWAYS AS (json_extract(data, '$.accountId')) VIRTUAL,
username_lower TEXT GENERATED ALWAYS AS (lower(json_extract(data, '$.username'))) VIRTUAL,
has_plus INTEGER GENERATED ALWAYS AS (json_extract(data, '$.hasPlus')) VIRTUAL,
is_influencer INTEGER GENERATED ALWAYS AS (json_extract(data, '$.isInfluencer')) VIRTUAL
is_influencer INTEGER GENERATED ALWAYS AS (json_extract(data, '$.isInfluencer')) VIRTUAL,
signup_ip TEXT GENERATED ALWAYS AS (json_extract(data, '$.signupIp')) VIRTUAL,
device_id TEXT GENERATED ALWAYS AS (json_extract(data, '$.deviceId')) VIRTUAL
)`,
`CREATE UNIQUE INDEX IF NOT EXISTS idx_accounts_account_id ON account (account_id)`,
`CREATE INDEX IF NOT EXISTS idx_account_has_plus ON account (has_plus) WHERE has_plus = 1`,
`CREATE INDEX IF NOT EXISTS idx_account_is_influencer ON account (is_influencer) WHERE is_influencer = 1`,
`CREATE INDEX IF NOT EXISTS idx_account_signup_ip ON account (signup_ip)`,
`CREATE INDEX IF NOT EXISTS idx_account_device_id ON account (device_id)`,
]
/** The stored avatar payload — opaque JSON the client sets and reads back. */