File
Blob: kv/sqlite3/prefix.go
| 1 | package sqlite3 |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | |
| 7 | "go.miragespace.co/specter/spec/chord" |
| 8 | ) |
| 9 | |
| 10 | func (s *SqliteKV) PrefixAppend(ctx context.Context, prefix []byte, child []byte) error { |
| 11 | return withWriteTx(ctx, s.writer, func(tx *sql.Tx) error { |
| 12 | res, err := tx.StmtContext(ctx, s.stmts.prefixAppend).Exec(prefix, child) |
| 13 | if err != nil { |
| 14 | return err |
| 15 | } |
| 16 | n, err := res.RowsAffected() |
| 17 | if err != nil { |
| 18 | return err |
| 19 | } |
| 20 | if n == 0 { |
| 21 | return chord.ErrKVPrefixConflict |
| 22 | } |
| 23 | return s.updateKeyTracker(ctx, tx, prefix, PrefixFlag, 0) |
| 24 | }) |
| 25 | } |
| 26 | |
| 27 | func (s *SqliteKV) PrefixContains(ctx context.Context, prefix []byte, child []byte) (bool, error) { |
| 28 | var one int |
| 29 | err := s.stmts.prefixContains.QueryRowContext(ctx, prefix, child).Scan(&one) |
| 30 | if err != nil { |
| 31 | if err == sql.ErrNoRows { |
| 32 | return false, nil |
| 33 | } |
| 34 | return false, err |
| 35 | } |
| 36 | return true, nil |
| 37 | } |
| 38 | |
| 39 | func (s *SqliteKV) PrefixList(ctx context.Context, prefix []byte) ([][]byte, error) { |
| 40 | rows, err := s.stmts.prefixList.QueryContext(ctx, prefix) |
| 41 | if err != nil { |
| 42 | return nil, err |
| 43 | } |
| 44 | defer rows.Close() |
| 45 | |
| 46 | entries := make([][]byte, 0) |
| 47 | for rows.Next() { |
| 48 | var child []byte |
| 49 | if err := rows.Scan(&child); err != nil { |
| 50 | return nil, err |
| 51 | } |
| 52 | entries = append(entries, child) |
| 53 | } |
| 54 | return entries, rows.Err() |
| 55 | } |
| 56 | |
| 57 | func (s *SqliteKV) PrefixRemove(ctx context.Context, prefix []byte, child []byte) error { |
| 58 | return withWriteTx(ctx, s.writer, func(tx *sql.Tx) error { |
| 59 | _, err := tx.StmtContext(ctx, s.stmts.prefixRemove).Exec(prefix, child) |
| 60 | if err != nil { |
| 61 | return err |
| 62 | } |
| 63 | return s.updateKeyTracker(ctx, tx, prefix, 0, PrefixFlag) |
| 64 | }) |
| 65 | } |