kea-manage/lib/database/postgres/postgres.go

93 lines
2.0 KiB
Go
Raw Permalink Normal View History

package postgres
import (
"context"
"fmt"
2024-09-22 02:02:02 +00:00
"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
2024-09-22 02:02:02 +00:00
conn *pgx.Conn
}
2024-09-22 02:02:02 +00:00
// 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
}
2024-09-22 02:02:02 +00:00
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
2024-09-22 02:02:02 +00:00
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 {
2024-09-22 02:02:02 +00:00
return err
}
if err = tx.Commit(context.Background()); err != nil {
return err
}
if ct.RowsAffected() == 0 {
return database.Exists
}
2024-09-22 02:02:02 +00:00
return nil
}