all repos

onasty @ f01c95c

a one-time notes service

onasty/internal/store/psqlutil/psqlutil.go (view raw)

Smirnov Oleksandr Smirnov Oleksandr
ss2316544@gmail.com
fix(noterepo): check if the .Create violates the unique constraint (#146)..., 11 months ago
1
package psqlutil
2
3
import (
4
	"context"
5
	"errors"
6
7
	"github.com/jackc/pgx/v5/pgconn"
8
	"github.com/jackc/pgx/v5/pgxpool"
9
)
10
11
type DB struct{ *pgxpool.Pool }
12
13
func Connect(ctx context.Context, dsn string) (*DB, error) {
14
	db, err := pgxpool.New(ctx, dsn)
15
	if err != nil {
16
		return nil, err
17
	}
18
19
	if err := db.Ping(ctx); err != nil {
20
		return nil, err
21
	}
22
23
	return &DB{
24
		Pool: db,
25
	}, nil
26
}
27
28
func (db *DB) Close() error {
29
	db.Pool.Close()
30
	return nil
31
}
32
33
// IsDuplicateErr function that checks if the error is a duplicate key violation.
34
func IsDuplicateErr(err error, constraintName string) bool {
35
	var pgErr *pgconn.PgError
36
	if errors.As(err, &pgErr) {
37
		return pgErr.Code == "23505" && // unique_violation
38
			pgErr.ConstraintName == constraintName
39
	}
40
	return false
41
}