collection.go

299 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
package database

import (
	"errors"
	"fmt"
	"reflect"
	"strings"
	"time"
)

var (
	// ErrNotFound is returned when a record doesn't exist
	ErrNotFound = errors.New("record not found")

	// ErrDuplicate is returned when a unique constraint is violated
	ErrDuplicate = errors.New("duplicate record")
)

// Collection is a generic repository for type-safe CRUD operations.
type Collection[E any] struct {
	db     *Database
	table  string
	mirror *mirror
}

// ManageOption configures a Collection during creation.
type ManageOption[E any] func(*Collection[E])

// WithIndex creates a non-unique index on the specified columns.
// Panics on failure — this is a declarative startup-time operation.
func WithIndex[E any](columns ...string) ManageOption[E] {
	return func(c *Collection[E]) {
		indexName := fmt.Sprintf("idx_%s_%s", strings.ToLower(c.table), strings.ToLower(strings.Join(columns, "_")))
		query := fmt.Sprintf(`CREATE INDEX IF NOT EXISTS "%s" ON "%s"(%s)`, indexName, c.table, strings.Join(columns, ", "))
		if _, err := c.db.Exec(query); err != nil {
			panic(fmt.Sprintf("database: create index %s: %v", indexName, err))
		}
	}
}

// WithUniqueIndex creates a unique index on the specified column(s).
// Pass multiple columns for a composite unique constraint (e.g., WithUniqueIndex("UserID", "TileID")).
// Panics on failure — this is a declarative startup-time operation.
func WithUniqueIndex[E any](columns ...string) ManageOption[E] {
	return func(c *Collection[E]) {
		indexName := fmt.Sprintf("idx_%s_%s_unique", strings.ToLower(c.table), strings.ToLower(strings.Join(columns, "_")))
		query := fmt.Sprintf(`CREATE UNIQUE INDEX IF NOT EXISTS "%s" ON "%s"(%s)`, indexName, c.table, strings.Join(columns, ", "))
		if _, err := c.db.Exec(query); err != nil {
			panic(fmt.Sprintf("database: create unique index %s: %v", indexName, err))
		}
	}
}

// Manage creates a new Collection for the given entity type.
// The table name is derived from the struct name.
// Tables are automatically created if they don't exist, and missing columns are added.
func Manage[E any](db *Database, model *E, opts ...ManageOption[E]) *Collection[E] {
	m := reflectType[E]()

	c := &Collection[E]{
		db:     db,
		table:  m.Name(),
		mirror: m,
	}

	// Auto-create table and migrate schema.
	// Panics on failure — schema is declarative and runs at startup.
	if !c.db.TableExists(c.table) {
		if err := c.db.CreateTable(c.table, c.mirror.Columns()); err != nil {
			panic(fmt.Sprintf("database: create table %s: %v", c.table, err))
		}
	} else {
		// Table exists, check for missing columns
		existing := make(map[string]bool)
		for _, name := range c.db.GetColumns(c.table) {
			existing[name] = true
		}

		for _, col := range c.mirror.Columns() {
			if !existing[col.Name] {
				if err := c.db.AddColumn(c.table, col); err != nil {
					panic(fmt.Sprintf("database: add column %s.%s: %v", c.table, col.Name, err))
				}
			}
		}
	}

	// Apply options (including index creation)
	for _, opt := range opts {
		opt(c)
	}

	return c
}

// Get retrieves an entity by ID
func (c *Collection[E]) Get(id string) (*E, error) {
	return c.First("WHERE ID = ?", id)
}

// First returns the first entity matching the query
func (c *Collection[E]) First(where string, args ...any) (*E, error) {
	results, err := c.Search(where+" LIMIT 1", args...)
	if err != nil {
		return nil, err
	}
	if len(results) == 0 {
		return nil, ErrNotFound
	}
	return results[0], nil
}

// Search returns all entities matching the query
func (c *Collection[E]) Search(where string, args ...any) ([]*E, error) {
	cols := c.mirror.Columns()
	names := make([]string, len(cols))
	for i, col := range cols {
		names[i] = col.Name
	}

	query := fmt.Sprintf(`SELECT %s FROM "%s" %s`, strings.Join(names, ", "), c.table, where)

	rows, err := c.db.Query(query, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	results := make([]*E, 0)
	for rows.Next() {
		entity := new(E)
		if err := c.mirror.Scan(rows, entity); err != nil {
			return nil, err
		}
		results = append(results, entity)
	}

	return results, rows.Err()
}

// All returns all entities in the collection
func (c *Collection[E]) All() ([]*E, error) {
	return c.Search("")
}

// Insert creates a new record and returns the generated ID
func (c *Collection[E]) Insert(entity *E) (string, error) {
	v := reflect.ValueOf(entity).Elem()

	// Set ID if empty
	idField := c.mirror.Field(v, "ID")
	if idField.IsValid() && idField.String() == "" {
		idField.SetString(c.db.GenerateID())
	}

	// Set timestamps
	now := time.Now()
	if createdAt := c.mirror.Field(v, "CreatedAt"); createdAt.IsValid() && createdAt.Type() == reflect.TypeOf(time.Time{}) && createdAt.Interface().(time.Time).IsZero() {
		createdAt.Set(reflect.ValueOf(now))
	}
	if updatedAt := c.mirror.Field(v, "UpdatedAt"); updatedAt.IsValid() {
		updatedAt.Set(reflect.ValueOf(now))
	}

	// Build INSERT query
	cols := c.mirror.Columns()
	names := make([]string, len(cols))
	placeholders := make([]string, len(cols))
	for i, col := range cols {
		names[i] = col.Name
		placeholders[i] = "?"
	}
	values := c.mirror.Values(v)

	query := fmt.Sprintf(
		`INSERT INTO "%s" (%s) VALUES (%s)`,
		c.table,
		strings.Join(names, ", "),
		strings.Join(placeholders, ", "),
	)

	_, err := c.db.Exec(query, values...)
	if err != nil {
		if strings.Contains(err.Error(), "UNIQUE constraint") {
			return "", ErrDuplicate
		}
		return "", err
	}

	if idField.IsValid() {
		return idField.String(), nil
	}
	return "", nil
}

// Update saves changes to an existing record
func (c *Collection[E]) Update(entity *E) error {
	v := reflect.ValueOf(entity).Elem()

	// Update timestamp
	if updatedAt := c.mirror.Field(v, "UpdatedAt"); updatedAt.IsValid() {
		updatedAt.Set(reflect.ValueOf(time.Now()))
	}

	// Build UPDATE query (skip ID and CreatedAt)
	var sets []string
	var values []any
	for _, col := range c.mirror.Columns() {
		if col.Name == "ID" || col.Name == "CreatedAt" {
			continue
		}
		f := c.mirror.Field(v, col.Name)
		if !f.IsValid() {
			continue
		}
		sets = append(sets, col.Name+" = ?")
		values = append(values, f.Interface())
	}

	// Add ID for WHERE clause
	idField := c.mirror.Field(v, "ID")
	if !idField.IsValid() {
		return fmt.Errorf("entity %T has no ID field", entity)
	}
	values = append(values, idField.Interface())

	query := fmt.Sprintf(`UPDATE "%s" SET %s WHERE ID = ?`, c.table, strings.Join(sets, ", "))

	result, err := c.db.Exec(query, values...)
	if err != nil {
		return err
	}

	rows, _ := result.RowsAffected()
	if rows == 0 {
		return ErrNotFound
	}

	return nil
}

// Delete removes a record
func (c *Collection[E]) Delete(entity *E) error {
	v := reflect.ValueOf(entity).Elem()
	idField := c.mirror.Field(v, "ID")
	if !idField.IsValid() {
		return fmt.Errorf("entity %T has no ID field", entity)
	}
	id := idField.Interface()

	result, err := c.db.Exec(fmt.Sprintf(`DELETE FROM "%s" WHERE ID = ?`, c.table), id)
	if err != nil {
		return err
	}

	rows, _ := result.RowsAffected()
	if rows == 0 {
		return ErrNotFound
	}

	return nil
}

// DeleteByID removes a record by ID without requiring a full entity.
// Returns ErrNotFound if no record with the given ID exists.
func (c *Collection[E]) DeleteByID(id string) error {
	result, err := c.db.Exec(fmt.Sprintf(`DELETE FROM "%s" WHERE ID = ?`, c.table), id)
	if err != nil {
		return err
	}

	rows, _ := result.RowsAffected()
	if rows == 0 {
		return ErrNotFound
	}

	return nil
}

// Count returns the number of records matching the query.
func (c *Collection[E]) Count(where string, args ...any) (int, error) {
	query := fmt.Sprintf(`SELECT COUNT(*) FROM "%s" %s`, c.table, where)

	var count int
	if err := c.db.QueryRow(query, args...).Scan(&count); err != nil {
		return 0, err
	}
	return count, nil
}

// DB returns the underlying database connection
func (c *Collection[E]) DB() *Database {
	return c.db
}

// Table returns the table name
func (c *Collection[E]) Table() string {
	return c.table
}