package postgres import ( "context" "fmt" "git.staur.ca/stobbsm/kea-manage/ipv4/reservation" "git.staur.ca/stobbsm/kea-manage/lib/database" "git.staur.ca/stobbsm/kea-manage/lib/types" "github.com/jackc/pgx/v5" ) type Postgres struct { connString string conn *pgx.Conn } // Open receives the host, port, username, password and database name of a postgresql // database, and manages connections to it. func Open(host, port, user, password, name string) *Postgres { var p = &Postgres{ connString: fmt.Sprintf("postgres://%s:%s@%s:%s/%s", user, password, host, port, name), } return p } func (p *Postgres) connect(ctx context.Context) error { var err error p.conn, err = pgx.Connect(ctx, p.connString) return err } func (p *Postgres) close() { p.conn.Close(context.Background()) } // InsertResV4 adds IPv4 reservations to the kea database func (p *Postgres) InsertResV4(r *reservation.ReservationV4) error { if err := p.connect(context.Background()); err != nil { return err } defer p.close() tx, err := p.conn.Begin(context.Background()) if err != nil { return err } defer tx.Rollback(context.Background()) ct, err := tx.Exec(context.Background(), insertIfNotExists, r.Identifier, types.HwAddress.Int(), r.SubnetID, r.Ipv4, r.Hostname) if err != nil { return err } if err = tx.Commit(context.Background()); err != nil { return err } if ct.RowsAffected() == 0 { return database.Exists } return nil } func (p *Postgres) UpdateResV4(r *reservation.ReservationV4) error { if err := p.connect(context.Background()); err != nil { return err } defer p.close() tx, err := p.conn.Begin(context.Background()) if err != nil { return err } defer tx.Rollback(context.Background()) ct, err := tx.Exec(context.Background(), update, r.Identifier, types.HwAddress.Int(), r.SubnetID, r.Ipv4, r.Hostname) if err != nil { return err } if err = tx.Commit(context.Background()); err != nil { return err } if ct.RowsAffected() == 0 { return database.Exists } return nil }