onasty/internal/store/psqlutil/psqlutil.go (view raw)
Olexandr Smirnov
Olexandr Smirnov
ss2316544@gmail.com refactor: make the `read_at` field nullable (#187)..., 9 months ago
ss2316544@gmail.com refactor: make the `read_at` field nullable (#187)..., 9 months ago
| 1 | package psqlutil |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | "time" |
| 8 | |
| 9 | "github.com/jackc/pgx/v5/pgconn" |
| 10 | "github.com/jackc/pgx/v5/pgxpool" |
| 11 | ) |
| 12 | |
| 13 | type DB struct{ *pgxpool.Pool } |
| 14 | |
| 15 | func Connect(ctx context.Context, dsn string) (*DB, error) { |
| 16 | db, err := pgxpool.New(ctx, dsn) |
| 17 | if err != nil { |
| 18 | return nil, err |
| 19 | } |
| 20 | |
| 21 | if err := db.Ping(ctx); err != nil { |
| 22 | return nil, err |
| 23 | } |
| 24 | |
| 25 | return &DB{ |
| 26 | Pool: db, |
| 27 | }, nil |
| 28 | } |
| 29 | |
| 30 | func (db *DB) Close() error { |
| 31 | db.Pool.Close() |
| 32 | return nil |
| 33 | } |
| 34 | |
| 35 | // IsDuplicateErr function that checks if the error is a duplicate key violation. |
| 36 | func IsDuplicateErr(err error, constraintName string) bool { |
| 37 | var pgErr *pgconn.PgError |
| 38 | if errors.As(err, &pgErr) { |
| 39 | return pgErr.Code == "23505" && // unique_violation |
| 40 | pgErr.ConstraintName == constraintName |
| 41 | } |
| 42 | return false |
| 43 | } |
| 44 | |
| 45 | // NullTimeToTime converts sql.NullTime to time.Time. |
| 46 | // Returns zero [time.Time] if NullTime is not valid. |
| 47 | func NullTimeToTime(t sql.NullTime) time.Time { |
| 48 | if t.Valid { |
| 49 | return t.Time |
| 50 | } |
| 51 | return time.Time{} |
| 52 | } |