kea-manage/lib/database/postgres/postgres.go
Matthew Stobbs a78f001a41 working configuration for reservations
- Make ipv4 reservations in kea by directly writing to the database
- uses same configuration file as database configuration under the
heading reservationV4
2024-09-24 14:43:54 -06:00

64 lines
1.4 KiB
Go

package postgres
import (
"context"
"fmt"
"git.staur.ca/stobbsm/kea-manage/ipv4/reservation"
"git.staur.ca/stobbsm/kea-manage/lib/database"
"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.MacAddr, r.Type, 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
}