forked from hailey.at/cocoon
An atproto PDS written in Go
at main 2.0 kB view raw
1package db 2 3import ( 4 "context" 5 "sync" 6 7 "gorm.io/gorm" 8 "gorm.io/gorm/clause" 9) 10 11type DB struct { 12 cli *gorm.DB 13 mu sync.Mutex 14} 15 16func NewDB(cli *gorm.DB) *DB { 17 return &DB{ 18 cli: cli, 19 mu: sync.Mutex{}, 20 } 21} 22 23func (db *DB) Create(ctx context.Context, value any, clauses []clause.Expression) *gorm.DB { 24 db.mu.Lock() 25 defer db.mu.Unlock() 26 return db.cli.WithContext(ctx).Clauses(clauses...).Create(value) 27} 28 29func (db *DB) Save(ctx context.Context, value any, clauses []clause.Expression) *gorm.DB { 30 db.mu.Lock() 31 defer db.mu.Unlock() 32 return db.cli.WithContext(ctx).Clauses(clauses...).Save(value) 33} 34 35func (db *DB) Exec(ctx context.Context, sql string, clauses []clause.Expression, values ...any) *gorm.DB { 36 db.mu.Lock() 37 defer db.mu.Unlock() 38 return db.cli.WithContext(ctx).Clauses(clauses...).Exec(sql, values...) 39} 40 41func (db *DB) Raw(ctx context.Context, sql string, clauses []clause.Expression, values ...any) *gorm.DB { 42 return db.cli.WithContext(ctx).Clauses(clauses...).Raw(sql, values...) 43} 44 45func (db *DB) AutoMigrate(models ...any) error { 46 return db.cli.AutoMigrate(models...) 47} 48 49func (db *DB) Delete(ctx context.Context, value any, clauses []clause.Expression) *gorm.DB { 50 db.mu.Lock() 51 defer db.mu.Unlock() 52 return db.cli.WithContext(ctx).Clauses(clauses...).Delete(value) 53} 54 55func (db *DB) First(ctx context.Context, dest any, conds ...any) *gorm.DB { 56 return db.cli.WithContext(ctx).First(dest, conds...) 57} 58 59// TODO: this isn't actually good. we can commit even if the db is locked here. this is probably okay for the time being, but need to figure 60// out a better solution. right now we only do this whenever we're importing a repo though so i'm mostly not worried, but it's still bad. 61// e.g. when we do apply writes we should also be using a transcation but we don't right now 62func (db *DB) BeginDangerously(ctx context.Context) *gorm.DB { 63 return db.cli.WithContext(ctx).Begin() 64} 65 66func (db *DB) Lock() { 67 db.mu.Lock() 68} 69 70func (db *DB) Unlock() { 71 db.mu.Unlock() 72}