mirror of
https://github.com/phishingclub/phishingclub.git
synced 2026-12-06 10:03:46 +01:00
208 lines
6.5 KiB
Go
208 lines
6.5 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"github.com/google/uuid"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
"gorm.io/gorm/schema"
|
|
)
|
|
|
|
// Batched writes find the rows of one batch first and then write them by a
|
|
// key. sqlite uses the rowid. postgres has no rowid: a write whose batch is
|
|
// found and written in one statement uses the primary key of the table, or
|
|
// its unique key when it has no primary key; a batch read in one statement
|
|
// and written in a later one uses the uuid primary key id, which never
|
|
// changes and is never given out again.
|
|
|
|
// inBatch matches the rows of one batch: at most limit rows of model that
|
|
// match where, found and written in the same statement.
|
|
//
|
|
// On postgres the statement also repeats where. Under read committed the
|
|
// subquery reads a snapshot taken when the statement starts, and a row that
|
|
// another writer changes before the write reaches it is checked again only
|
|
// against the outer conditions. Without where there, a row that stopped
|
|
// matching in between, such as an enrollment the scheduler completed, would
|
|
// still be written. where must name columns of the table of model without a
|
|
// table, as the outer statement reads them. sqlite runs the statement with no
|
|
// other writer, so it keeps the old text.
|
|
func inBatch(db *gorm.DB, model any, where clause.Expression, limit int) (clause.Expression, error) {
|
|
if !dialectOf(db).IsPostgres() {
|
|
rowids := db.Session(&gorm.Session{NewDB: true}).
|
|
Model(model).
|
|
Select("rowid").
|
|
Where(where).
|
|
Limit(limit)
|
|
return clause.Expr{SQL: "? IN (?)", Vars: []any{clause.Column{Name: "rowid"}, rowids}}, nil
|
|
}
|
|
keys, err := rowKeyColumns(db, model)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
names := make([]string, len(keys))
|
|
for i, key := range keys {
|
|
names[i] = key.Name
|
|
}
|
|
batch := db.Session(&gorm.Session{NewDB: true}).
|
|
Model(model).
|
|
Select(names).
|
|
Where(where).
|
|
Limit(limit)
|
|
var target any = keys[0]
|
|
if len(keys) > 1 {
|
|
list := make([]any, len(keys))
|
|
for i, key := range keys {
|
|
list[i] = key
|
|
}
|
|
target = list
|
|
}
|
|
return clause.And(clause.Expr{SQL: "? IN (?)", Vars: []any{target, batch}}, where), nil
|
|
}
|
|
|
|
// batchWritesDone tells whether a loop of batched writes of model that match
|
|
// where can stop after a write that changed affected rows of a batch of at
|
|
// most limit. A batch smaller than limit means no row was left on sqlite,
|
|
// where nothing else writes during the statement. On postgres a row of the
|
|
// batch that another writer deleted or changed before the write reached it is
|
|
// left out, so a short batch says nothing about the rows after it: the loop
|
|
// stops only when no row matches where any more. A write that changed no row
|
|
// while rows still match made no progress and would loop for ever, so it is
|
|
// an error (errNoBatchProgress). That also ends a loop in the rare case where
|
|
// another writer changed every row of a batch between its read and its write
|
|
// while other rows still match; the caller can run the whole write again.
|
|
func batchWritesDone(ctx context.Context, db *gorm.DB, model any, where clause.Expression, affected int64, limit int) (bool, error) {
|
|
if affected >= int64(limit) {
|
|
return false, nil
|
|
}
|
|
if !dialectOf(db).IsPostgres() {
|
|
return true, nil
|
|
}
|
|
var found []int
|
|
err := db.WithContext(ctx).
|
|
Session(&gorm.Session{NewDB: true}).
|
|
Model(model).
|
|
Select("1").
|
|
Where(where).
|
|
Limit(1).
|
|
Scan(&found).Error
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
if len(found) == 0 {
|
|
return true, nil
|
|
}
|
|
if affected == 0 {
|
|
return false, errNoBatchProgress
|
|
}
|
|
return false, nil
|
|
}
|
|
|
|
// errNoBatchProgress is a batched write on postgres that changed no row while
|
|
// rows still match, see batchWritesDone
|
|
var errNoBatchProgress = errors.New("batched write changed no row while rows still match")
|
|
|
|
// errNoRowKey is returned for a table with neither a primary key nor a unique
|
|
// key of NOT NULL columns, whose rows a batch can not name on postgres
|
|
var errNoRowKey = errors.New("table has no primary key or unique key of not null columns to batch by")
|
|
|
|
// rowKeyColumns returns the columns that name one row of the table of model:
|
|
// the primary key, or the first unique index of more than one column when
|
|
// the table has no primary key. A unique index with a nullable column is not
|
|
// used: `(a, b) IN (...)` is never true for a row with a NULL in a or b, so
|
|
// such a row could never be written and the batch loop would not end.
|
|
func rowKeyColumns(db *gorm.DB, model any) ([]clause.Column, error) {
|
|
stmt := &gorm.Statement{DB: db}
|
|
if err := stmt.Parse(model); err != nil {
|
|
return nil, err
|
|
}
|
|
if fields := stmt.Schema.PrimaryFields; len(fields) > 0 {
|
|
return fieldColumns(fields), nil
|
|
}
|
|
for _, idx := range stmt.Schema.ParseIndexes() {
|
|
if idx.Class != "UNIQUE" || len(idx.Fields) < 2 {
|
|
continue
|
|
}
|
|
fields := make([]*schema.Field, len(idx.Fields))
|
|
nullable := false
|
|
for i, f := range idx.Fields {
|
|
fields[i] = f.Field
|
|
if !f.Field.NotNull && !f.Field.PrimaryKey {
|
|
nullable = true
|
|
}
|
|
}
|
|
if nullable {
|
|
continue
|
|
}
|
|
return fieldColumns(fields), nil
|
|
}
|
|
return nil, errNoRowKey
|
|
}
|
|
|
|
func fieldColumns(fields []*schema.Field) []clause.Column {
|
|
out := make([]clause.Column, len(fields))
|
|
for i, f := range fields {
|
|
out[i] = clause.Column{Name: f.DBName}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// batchKeys holds the keys of the rows of one batch read in one statement
|
|
// and written in a later one: rowids on sqlite, ids on postgres, see the top
|
|
// of this file
|
|
type batchKeys struct {
|
|
postgres bool
|
|
rowids []int64
|
|
ids []uuid.UUID
|
|
}
|
|
|
|
func newBatchKeys(db *gorm.DB) *batchKeys {
|
|
return &batchKeys{postgres: dialectOf(db).IsPostgres()}
|
|
}
|
|
|
|
// column is the key column
|
|
func (k *batchKeys) column() clause.Column {
|
|
if k.postgres {
|
|
return clause.Column{Name: "id"}
|
|
}
|
|
return clause.Column{Name: "rowid"}
|
|
}
|
|
|
|
// pluck reads the keys of the rows q finds
|
|
func (k *batchKeys) pluck(q *gorm.DB) error {
|
|
if k.postgres {
|
|
k.ids = k.ids[:0]
|
|
return q.Pluck("id", &k.ids).Error
|
|
}
|
|
k.rowids = k.rowids[:0]
|
|
return q.Pluck("rowid", &k.rowids).Error
|
|
}
|
|
|
|
func (k *batchKeys) len() int {
|
|
if k.postgres {
|
|
return len(k.ids)
|
|
}
|
|
return len(k.rowids)
|
|
}
|
|
|
|
// last is the key of the last row read
|
|
func (k *batchKeys) last() any {
|
|
if k.postgres {
|
|
return k.ids[len(k.ids)-1]
|
|
}
|
|
return k.rowids[len(k.rowids)-1]
|
|
}
|
|
|
|
// in matches the rows read
|
|
func (k *batchKeys) in() clause.Expression {
|
|
if k.postgres {
|
|
values := make([]any, len(k.ids))
|
|
for i, id := range k.ids {
|
|
values[i] = id
|
|
}
|
|
return clause.IN{Column: k.column(), Values: values}
|
|
}
|
|
return clause.IN{Column: k.column(), Values: int64Values(k.rowids)}
|
|
}
|