Files
bryanpedini d34894c9cd
Test / test (push) Canceled after 6m35s
Build and publish image / image (push) Successful in 13m42s
fix: support utf8mb4 across MySQL and MariaDB
2026-11-20 15:14:28 +01:00

193 lines
6.6 KiB
Go

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
package main
import (
"context"
"database/sql"
"errors"
"fmt"
)
type zoneSummary struct {
Zone string
RecordCount int64
SOAContent sql.NullString
}
type recordStore struct {
q dbtx
t tableNames
}
func newRecordStore(q dbtx, t tableNames) recordStore {
return recordStore{q: q, t: t}
}
const recordColumns = "`id`, `zone`, `name`, `ttl`, `content`, `record_type`"
func recordZoneKey(column string) string {
// Use the same ASCII case mapping as normalizeZone, including on
// servers where the records column uses a language-specific collation.
lower := "LOWER(CONVERT(" + column + " USING utf8mb4) COLLATE utf8mb4_bin)"
return "CAST(CASE WHEN RIGHT(" + column + ", 1) = CAST('.' AS BINARY) THEN " + lower + " ELSE CONCAT(" + lower + ", '.') END AS BINARY)"
}
var zoneRowsWhere = " WHERE " + recordZoneKey("`zone`") + " = ?"
func zoneSummarySelect(filter string) string {
return "SELECT k.`zone_key`, k.`record_count`, (SELECT s.`content` FROM {records} s WHERE " + recordZoneKey("s.`zone`") +
" = k.`zone_key` AND CAST(s.`record_type` AS BINARY) = 'SOA' ORDER BY OCTET_LENGTH(s.`name`) <> 0, s.`id` LIMIT 1) FROM (SELECT " +
recordZoneKey("r.`zone`") + " AS `zone_key`, COUNT(*) AS `record_count` FROM {records} r" + filter +
" GROUP BY `zone_key`) k ORDER BY k.`zone_key`"
}
func (s recordStore) ListZones(ctx context.Context) ([]zoneSummary, error) {
defer traceStore(ctx, "recordStore.ListZones")()
return s.queryZones(ctx, s.t.sql(zoneSummarySelect("")))
}
func (s recordStore) ListZonesOfUser(ctx context.Context, userID int64) ([]zoneSummary, error) {
defer traceStore(ctx, "recordStore.ListZonesOfUser")()
return s.queryZones(ctx, s.t.sql(zoneSummarySelect(" WHERE "+recordZoneKey("r.`zone`")+
" IN (SELECT CAST(d.`zone` AS BINARY) FROM {delegations} d WHERE d.`user_id` = ?)")), userID)
}
func (s recordStore) queryZones(ctx context.Context, query string, args ...any) ([]zoneSummary, error) {
rows, err := s.q.QueryContext(ctx, query, args...)
if err != nil {
return nil, fmt.Errorf("list zones: %w", err)
}
defer rows.Close()
var zones []zoneSummary
for rows.Next() {
var z zoneSummary
if err := rows.Scan(&z.Zone, &z.RecordCount, &z.SOAContent); err != nil {
return nil, fmt.Errorf("list zones: %w", err)
}
zones = append(zones, z)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("list zones: %w", err)
}
return zones, nil
}
func (s recordStore) ZoneExists(ctx context.Context, zone string) (bool, error) {
defer traceStore(ctx, "recordStore.ZoneExists")()
var one int
err := s.q.QueryRowContext(ctx, s.t.sql("SELECT 1 FROM {records}"+zoneRowsWhere+" LIMIT 1"), zone).Scan(&one)
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("zone exists: %w", err)
}
return true, nil
}
func (s recordStore) ZoneRows(ctx context.Context, zone string) ([]recordRow, error) {
defer traceStore(ctx, "recordStore.ZoneRows")()
return s.queryRecords(ctx, s.t.sql("SELECT "+recordColumns+" FROM {records}"+zoneRowsWhere+" ORDER BY `id`"), zone)
}
func (s recordStore) ZoneRowsForUpdate(ctx context.Context, zone string) ([]recordRow, error) {
defer traceStore(ctx, "recordStore.ZoneRowsForUpdate")()
return s.queryRecords(ctx, s.t.sql("SELECT "+recordColumns+" FROM {records}"+zoneRowsWhere+" ORDER BY `id` FOR UPDATE"), zone)
}
func (s recordStore) queryRecords(ctx context.Context, query string, args ...any) ([]recordRow, error) {
rows, err := s.q.QueryContext(ctx, query, args...)
if err != nil {
return nil, fmt.Errorf("read records: %w", err)
}
defer rows.Close()
var records []recordRow
for rows.Next() {
var r recordRow
if err := rows.Scan(&r.ID, &r.Zone, &r.Name, &r.TTL, &r.Content, &r.RecordType); err != nil {
return nil, fmt.Errorf("read records: %w", err)
}
records = append(records, r)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("read records: %w", err)
}
return records, nil
}
func (s recordStore) RecordByID(ctx context.Context, id int64) (recordRow, error) {
defer traceStore(ctx, "recordStore.RecordByID")()
return s.queryRecord(ctx, s.t.sql("SELECT "+recordColumns+" FROM {records} WHERE `id` = ?"), id)
}
func (s recordStore) RecordByIDForUpdate(ctx context.Context, id int64) (recordRow, error) {
defer traceStore(ctx, "recordStore.RecordByIDForUpdate")()
return s.queryRecord(ctx, s.t.sql("SELECT "+recordColumns+" FROM {records} WHERE `id` = ? FOR UPDATE"), id)
}
func (s recordStore) queryRecord(ctx context.Context, query string, id int64) (recordRow, error) {
var r recordRow
err := s.q.QueryRowContext(ctx, query, id).Scan(&r.ID, &r.Zone, &r.Name, &r.TTL, &r.Content, &r.RecordType)
if errors.Is(err, sql.ErrNoRows) {
return recordRow{}, errRowNotFound
}
if err != nil {
return recordRow{}, fmt.Errorf("read record: %w", err)
}
return r, nil
}
func (s recordStore) InsertRecord(ctx context.Context, r recordRow) (int64, error) {
defer traceStore(ctx, "recordStore.InsertRecord")()
res, err := s.q.ExecContext(privateSQLArgs(ctx, 4),
s.t.sql("INSERT INTO {records} (`zone`, `name`, `ttl`, `content`, `record_type`) VALUES (?, ?, ?, ?, ?)"),
r.Zone, r.Name, r.TTL, r.Content, r.RecordType)
if err != nil {
return 0, fmt.Errorf("insert record: %w", err)
}
id, err := res.LastInsertId()
if err != nil {
return 0, fmt.Errorf("insert record: %w", err)
}
return id, nil
}
func (s recordStore) UpdateRecord(ctx context.Context, r recordRow) error {
defer traceStore(ctx, "recordStore.UpdateRecord")()
_, err := s.q.ExecContext(privateSQLArgs(ctx, 4),
s.t.sql("UPDATE {records} SET `zone` = ?, `name` = ?, `ttl` = ?, `content` = ?, `record_type` = ? WHERE `id` = ?"),
r.Zone, r.Name, r.TTL, r.Content, r.RecordType, r.ID)
if err != nil {
return fmt.Errorf("update record: %w", err)
}
return nil
}
func (s recordStore) DeleteRecord(ctx context.Context, id int64) (bool, error) {
defer traceStore(ctx, "recordStore.DeleteRecord")()
res, err := s.q.ExecContext(ctx, s.t.sql("DELETE FROM {records} WHERE `id` = ?"), id)
if err != nil {
return false, fmt.Errorf("delete record: %w", err)
}
n, err := res.RowsAffected()
if err != nil {
return false, fmt.Errorf("delete record: %w", err)
}
return n > 0, nil
}
func (s recordStore) DeleteZoneRecords(ctx context.Context, zone string) (int64, error) {
defer traceStore(ctx, "recordStore.DeleteZoneRecords")()
res, err := s.q.ExecContext(ctx, s.t.sql("DELETE FROM {records}"+zoneRowsWhere), zone)
if err != nil {
return 0, fmt.Errorf("delete zone records: %w", err)
}
n, err := res.RowsAffected()
if err != nil {
return 0, fmt.Errorf("delete zone records: %w", err)
}
return n, nil
}