1- import { relations } from "drizzle-orm" ;
1+ import { relations , sql } from "drizzle-orm" ;
22import {
33 integer ,
44 pgTable ,
55 uuid ,
66 timestamp ,
77 text ,
88 boolean ,
9+ uniqueIndex ,
910} from "drizzle-orm/pg-core" ;
1011import { USER_ID_CONFIG } from "../../../config/identifiers" ;
1112
@@ -17,26 +18,34 @@ export const usersRelation = relations(usersTable, ({ many }) => ({
1718 events : many ( eventsTable ) ,
1819} ) ) ;
1920
20- export const apiKeysTable = pgTable ( "api_keys" , {
21- id : uuid ( "id" ) . primaryKey ( ) . defaultRandom ( ) ,
22- name : text ( "name" ) . notNull ( ) . unique ( ) ,
23- key : text ( "key" ) . notNull ( ) . unique ( ) ,
24- createdAt : timestamp ( "created_at" , {
25- withTimezone : true ,
26- mode : "string" ,
27- } )
28- . defaultNow ( )
29- . notNull ( ) ,
30- expiresAt : timestamp ( "expires_at" , {
31- withTimezone : true ,
32- mode : "string" ,
33- } ) . notNull ( ) ,
34- revoked : boolean ( "revoked" ) . default ( false ) . notNull ( ) ,
35- revokedAt : timestamp ( "revoked_at" , {
36- withTimezone : true ,
37- mode : "string" ,
21+ export const apiKeysTable = pgTable (
22+ "api_keys" ,
23+ {
24+ id : uuid ( "id" ) . primaryKey ( ) . defaultRandom ( ) ,
25+ name : text ( "name" ) . notNull ( ) ,
26+ key : text ( "key" ) . notNull ( ) . unique ( ) ,
27+ createdAt : timestamp ( "created_at" , {
28+ withTimezone : true ,
29+ mode : "string" ,
30+ } )
31+ . defaultNow ( )
32+ . notNull ( ) ,
33+ expiresAt : timestamp ( "expires_at" , {
34+ withTimezone : true ,
35+ mode : "string" ,
36+ } ) . notNull ( ) ,
37+ revoked : boolean ( "revoked" ) . default ( false ) . notNull ( ) ,
38+ revokedAt : timestamp ( "revoked_at" , {
39+ withTimezone : true ,
40+ mode : "string" ,
41+ } ) ,
42+ } ,
43+ ( table ) => ( {
44+ uniqueActiveName : uniqueIndex ( "unique_active_name" )
45+ . on ( table . name )
46+ . where ( sql `${ table . revoked } = false` ) ,
3847 } ) ,
39- } ) ;
48+ ) ;
4049
4150export const apiKeysRelation = relations ( apiKeysTable , ( { many } ) => ( {
4251 events : many ( eventsTable ) ,
@@ -137,4 +146,4 @@ export const aiTokenUsageEventsRelation = relations(
137146 references : [ eventsTable . id ] ,
138147 } ) ,
139148 } ) ,
140- ) ;
149+ ) ;
0 commit comments