database

package
v0.13.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 7, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HealthMiddleware

func HealthMiddleware(hc *HealthChecker) func(next func()) func()

HealthMiddleware creates HTTP middleware for database health checks

func RunSeeder

func RunSeeder(db *sql.DB, seeder Seeder) error

RunSeeder runs a single seeder

func Vector added in v0.12.0

func Vector(embedding []float32) string

Vector formats an embedding for a query parameter.

Both pgvector and sqlite-vec accept the same text form -- "[0.1,0.2,0.3]" -- so one function covers both. Formatted with 'g' rather than a fixed precision: an embedding is float32 and printing more digits than it has stores noise, printing fewer changes the distance.

Types

type BaseSeeder

type BaseSeeder struct {
	TableName string
}

BaseSeeder provides common functionality for seeders

func (*BaseSeeder) BulkInsert

func (bs *BaseSeeder) BulkInsert(db *sql.DB, data []map[string]interface{}) error

BulkInsert performs bulk insertion of data

func (*BaseSeeder) DropAndRecreateTable

func (bs *BaseSeeder) DropAndRecreateTable(db *sql.DB, createSQL string) error

DropAndRecreateTable drops and recreates a table (requires table schema)

func (*BaseSeeder) TruncateTable

func (bs *BaseSeeder) TruncateTable(db *sql.DB) error

TruncateTable clears all data from a table

type ConnectionMonitor

type ConnectionMonitor struct {
	// contains filtered or unexported fields
}

ConnectionMonitor provides advanced connection monitoring

func NewConnectionMonitor

func NewConnectionMonitor(db *sql.DB, maxConnections int, warningThreshold float64) *ConnectionMonitor

NewConnectionMonitor creates a new connection monitor

func (*ConnectionMonitor) GetConnectionStats

func (cm *ConnectionMonitor) GetConnectionStats() *ConnectionStats

GetConnectionStats returns detailed connection statistics

func (*ConnectionMonitor) OptimizeConnections

func (cm *ConnectionMonitor) OptimizeConnections() []string

OptimizeConnections suggests connection pool optimizations

type ConnectionStats

type ConnectionStats struct {
	OpenConnections    int     `json:"open_connections"`
	InUse              int     `json:"in_use"`
	Idle               int     `json:"idle"`
	MaxOpenConnections int     `json:"max_open_connections"`
	MaxIdleConnections int     `json:"max_idle_connections"`
	MaxLifetime        string  `json:"max_lifetime"`
	MaxIdleTime        string  `json:"max_idle_time"`
	UtilizationPercent float64 `json:"utilization_percent"`
	Warning            string  `json:"warning,omitempty"`
}

ConnectionStats provides detailed connection statistics

type DB

type DB interface {
	Query(query string, args ...interface{}) (*sql.Rows, error)
	QueryRow(query string, args ...interface{}) *sql.Row
	Exec(query string, args ...interface{}) (sql.Result, error)
	Prepare(query string) (*sql.Stmt, error)
}

DB is an interface that both *sql.DB and *sql.Tx implement This allows QueryBuilder to work with both regular queries and transactions

type Dialect added in v0.7.0

type Dialect int

Dialect selects the placeholder syntax the builder emits.

const (
	// DialectQuestion uses ? placeholders: MySQL, MariaDB, SQLite.
	DialectQuestion Dialect = iota
	// DialectDollar uses $1, $2, ... placeholders: PostgreSQL.
	DialectDollar
)

func DialectFor added in v0.7.0

func DialectFor(databaseType string) Dialect

DialectFor maps a DATABASE_TYPE value to the placeholder syntax its driver expects. Unknown values get ? -- the majority of drivers -- rather than an error, so an unrecognised name degrades to the previous behaviour.

type Distance added in v0.12.0

type Distance int

Distance is how similarity between two vectors is measured.

The choice is not free: it must match the operator class the index was built with, or the index is not used and the query silently becomes a sequential scan over every row. That is the single most common way vector search "works" in development and falls over in production.

const (
	// Cosine ignores magnitude and compares direction. The right default for
	// text embeddings, and what OpenAI and most others document.
	Cosine Distance = iota

	// L2 is Euclidean distance. For embeddings where magnitude is meaningful.
	L2

	// InnerProduct is the negative dot product. Fastest, and correct only for
	// normalised vectors -- on unnormalised ones it ranks by magnitude as much
	// as by similarity.
	InnerProduct
)

type Factory

type Factory struct {
	// contains filtered or unexported fields
}

Factory provides a fluent interface for creating seed data

func NewFactory

func NewFactory() *Factory

NewFactory creates a new factory instance

func (*Factory) Create

func (f *Factory) Create(count int, template map[string]interface{}) *Factory

Create adds records to the factory

func (*Factory) CreateOne

func (f *Factory) CreateOne(record map[string]interface{}) *Factory

CreateOne adds a single record to the factory

func (*Factory) GetData

func (f *Factory) GetData() []map[string]interface{}

GetData returns all created data

func (*Factory) Insert

func (f *Factory) Insert(db *sql.DB, tableName string) error

Insert inserts the factory data into database using BaseSeeder

type Faker

type Faker struct{}

Common faker functions for generating test data

func NewFaker

func NewFaker() *Faker

NewFaker creates a new faker instance

func (*Faker) Boolean

func (fake *Faker) Boolean() func(int) interface{}

Boolean returns a function that generates alternating boolean values

func (*Faker) Email

func (fake *Faker) Email() func(int) interface{}

Email returns a function that generates emails

func (*Faker) Name

func (fake *Faker) Name() func(int) interface{}

Name returns a function that generates names

func (*Faker) Now

func (fake *Faker) Now() interface{}

Now returns current timestamp

func (*Faker) RandomInt

func (fake *Faker) RandomInt(min, max int) func(int) interface{}

RandomInt returns a function that generates random integers in range

func (*Faker) Sequence

func (fake *Faker) Sequence(format string) func(int) interface{}

Sequence returns a function that generates sequential values

type HealthChecker

type HealthChecker struct {
	// contains filtered or unexported fields
}

HealthChecker provides database health monitoring functionality

func NewHealthChecker

func NewHealthChecker(db *sql.DB, timeout time.Duration) *HealthChecker

NewHealthChecker creates a new database health checker

func (*HealthChecker) Check

func (hc *HealthChecker) Check(ctx context.Context) *HealthStatus

Check performs comprehensive health checks on the database

func (*HealthChecker) IsHealthy

func (hc *HealthChecker) IsHealthy(ctx context.Context) bool

IsHealthy returns true if the database is healthy

func (*HealthChecker) MonitorHealth

func (hc *HealthChecker) MonitorHealth(ctx context.Context, interval time.Duration, callback func(*HealthStatus))

MonitorHealth continuously monitors database health

func (*HealthChecker) QuickCheck

func (hc *HealthChecker) QuickCheck(ctx context.Context) error

QuickCheck performs a basic ping test

func (*HealthChecker) WaitForHealthy

func (hc *HealthChecker) WaitForHealthy(ctx context.Context, maxWait time.Duration) error

WaitForHealthy waits for the database to become healthy

type HealthStatus

type HealthStatus struct {
	Status           string            `json:"status"`
	ResponseTime     time.Duration     `json:"response_time"`
	ConnectionsOpen  int               `json:"connections_open"`
	ConnectionsInUse int               `json:"connections_in_use"`
	ConnectionsIdle  int               `json:"connections_idle"`
	MaxConnections   int               `json:"max_connections"`
	Errors           []string          `json:"errors,omitempty"`
	Checks           map[string]string `json:"checks"`
	Timestamp        time.Time         `json:"timestamp"`
	DatabaseType     string            `json:"database_type"`
	Version          string            `json:"version"`
}

HealthStatus represents the health status of the database

type Model

type Model struct {
	// contains filtered or unexported fields
}

Model represents a database table with configuration options. It provides a type-safe way to define and query database tables without runtime reflection.

func NewModel

func NewModel(table string) *Model

NewModel creates a new Model for the given table name. The table name is validated to prevent SQL injection.

func (*Model) All

func (m *Model) All(db *sql.DB) (*sql.Rows, error)

All retrieves all records from the table.

func (*Model) Create

func (m *Model) Create(db *sql.DB, data map[string]interface{}) (sql.Result, error)

Create inserts a new record and returns the result.

func (*Model) Delete

func (m *Model) Delete(db *sql.DB, id interface{}) (sql.Result, error)

Delete performs a hard delete for the given ID. For soft delete, use SoftDelete instead.

func (*Model) Find

func (m *Model) Find(db *sql.DB, id interface{}) *sql.Row

Find retrieves a single record by its primary key.

func (*Model) HasSoftDelete

func (m *Model) HasSoftDelete() bool

HasSoftDelete returns whether soft delete is enabled.

func (*Model) PrimaryKey

func (m *Model) PrimaryKey() string

PrimaryKey returns the primary key column name.

func (*Model) Query

func (m *Model) Query(db *sql.DB) *QueryBuilder

Query creates a new QueryBuilder for this model. If soft delete is enabled, it automatically adds WHERE deleted_at IS NULL.

func (*Model) Table

func (m *Model) Table() string

Table returns the table name.

func (*Model) Update

func (m *Model) Update(db *sql.DB, id interface{}, data map[string]interface{}) (sql.Result, error)

Update updates records matching the given ID.

func (*Model) WithDialect added in v0.7.0

func (m *Model) WithDialect(dialect Dialect) *Model

WithDialect selects the placeholder syntax for queries this model builds. Required for PostgreSQL, whose wire protocol rejects ? placeholders.

model := NewModel("users").WithDialect(DialectFor(cfg.Database.Type))

func (*Model) WithPrimaryKey

func (m *Model) WithPrimaryKey(pk string) *Model

WithPrimaryKey sets a custom primary key column name.

func (*Model) WithSoftDelete

func (m *Model) WithSoftDelete() *Model

WithSoftDelete enables soft delete support for this model. When enabled, Query() will automatically exclude soft-deleted records by adding a WHERE deleted_at IS NULL condition.

type QueryBuilder

type QueryBuilder struct {
	// contains filtered or unexported fields
}

QueryBuilder provides a fluent interface for building SQL queries

func Active

func Active(qb *QueryBuilder) *QueryBuilder

Active is a predefined scope that filters for active records.

func Draft

func Draft(qb *QueryBuilder) *QueryBuilder

Draft is a predefined scope for draft/unpublished content.

func NewQueryBuilder

func NewQueryBuilder(db *sql.DB) *QueryBuilder

NewQueryBuilder creates a new query builder emitting ? placeholders.

Use WithDialect for PostgreSQL: its wire protocol only accepts $1, $2, ... and rejects ? outright.

func Oldest

func Oldest(qb *QueryBuilder) *QueryBuilder

Oldest is a predefined scope that orders by created_at ASC.

func Published

func Published(qb *QueryBuilder) *QueryBuilder

Published is a predefined scope for published content.

func Recent

func Recent(qb *QueryBuilder) *QueryBuilder

Recent is a predefined scope that orders by created_at DESC.

func (*QueryBuilder) BelongsTo

func (qb *QueryBuilder) BelongsTo(relatedTable, foreignKey string, fkValue interface{}) *QueryBuilder

BelongsTo returns a query builder for the parent in a one-to-many relationship. Example: post.BelongsTo("users", "user_id", post.UserID) returns the user for a post.

func (*QueryBuilder) Chunk

func (qb *QueryBuilder) Chunk(size int, fn func(rows *sql.Rows) bool) error

Chunk processes query results in chunks of the specified size. The callback function receives each chunk of rows. Return false from the callback to stop processing.

Example:

db.Table("users").Chunk(100, func(rows *sql.Rows) bool {
    for rows.Next() {
        // process row
    }
    return true // continue processing
})

func (*QueryBuilder) ChunkByID

func (qb *QueryBuilder) ChunkByID(size int, column string, fn func(rows *sql.Rows) bool) error

ChunkByID processes query results by ID in batches. This is more efficient for large tables as it uses indexed ID lookups.

func (*QueryBuilder) Count

func (qb *QueryBuilder) Count() (int64, error)

Count returns the count of rows

func (*QueryBuilder) Delete

func (qb *QueryBuilder) Delete() (sql.Result, error)

Delete builds and executes a DELETE query

func (*QueryBuilder) Exists

func (qb *QueryBuilder) Exists() (bool, error)

Exists checks if any rows exist

func (*QueryBuilder) First

func (qb *QueryBuilder) First() *sql.Row

First executes the query and returns the first row

func (*QueryBuilder) ForceDelete

func (qb *QueryBuilder) ForceDelete() (sql.Result, error)

ForceDelete permanently deletes rows, ignoring soft delete. This is an alias for Delete() but makes the intent explicit.

func (*QueryBuilder) Get

func (qb *QueryBuilder) Get() (*sql.Rows, error)

Get executes the query and returns all rows

func (*QueryBuilder) GroupBy

func (qb *QueryBuilder) GroupBy(columns ...string) *QueryBuilder

GroupBy adds a GROUP BY clause

func (*QueryBuilder) HasMany

func (qb *QueryBuilder) HasMany(relatedTable, foreignKey string, id interface{}) *QueryBuilder

HasMany returns a query builder for a one-to-many relationship. Example: user.HasMany("posts", "user_id", userID) returns all posts for a user.

func (*QueryBuilder) Having

func (qb *QueryBuilder) Having(column, operator string, value interface{}) *QueryBuilder

Having adds a HAVING condition

func (*QueryBuilder) Insert

func (qb *QueryBuilder) Insert(data map[string]interface{}) (sql.Result, error)

Insert builds and executes an INSERT query

func (*QueryBuilder) Join

func (qb *QueryBuilder) Join(table, on string) *QueryBuilder

Join adds an INNER JOIN

func (*QueryBuilder) LeftJoin

func (qb *QueryBuilder) LeftJoin(table, on string) *QueryBuilder

LeftJoin adds a LEFT JOIN

func (*QueryBuilder) Limit

func (qb *QueryBuilder) Limit(count int) *QueryBuilder

Limit sets the LIMIT clause

func (*QueryBuilder) Nearest added in v0.12.0

func (qb *QueryBuilder) Nearest(column string, embedding []float32, distance Distance) *QueryBuilder

Nearest orders results by distance from an embedding, closest first.

It is the whole of vector search in a query builder:

rows, err := database.NewQueryBuilder(db).WithDialect(database.DialectDollar).
    Table("documents").
    Where("organization_id", "=", orgID).
    Nearest("embedding", queryVector, database.Cosine).
    Limit(10).
    Get()

The filter and the ordering compose, which is the reason to keep the vector in the primary database at all: a separate vector store cannot answer "the ten nearest documents *belonging to this organization*" without either duplicating the tenancy model or over-fetching and filtering afterwards.

The embedding is a bound parameter, not interpolated. It arrives from a model and is therefore data.

func (*QueryBuilder) NearestWithin added in v0.12.0

func (qb *QueryBuilder) NearestWithin(column string, embedding []float32, distance Distance, threshold float64) *QueryBuilder

NearestWithin filters to rows within a distance, rather than ordering by it.

Useful when "similar enough" is a threshold rather than a ranking -- a deduplication check, or a "did anybody already ask this" lookup. The threshold is in the units of the chosen distance, so it is not portable between them: cosine distance runs 0 to 2, L2 is unbounded.

func (*QueryBuilder) Offset

func (qb *QueryBuilder) Offset(count int) *QueryBuilder

Offset sets the OFFSET clause

func (*QueryBuilder) OnlyTrashed

func (qb *QueryBuilder) OnlyTrashed() *QueryBuilder

OnlyTrashed returns only soft-deleted records.

func (*QueryBuilder) OrWhere

func (qb *QueryBuilder) OrWhere(column, operator string, value interface{}) *QueryBuilder

OrWhere adds an OR WHERE condition

func (*QueryBuilder) OrderBy

func (qb *QueryBuilder) OrderBy(column, direction string) *QueryBuilder

OrderBy adds an ORDER BY clause

func (*QueryBuilder) Paginate

func (qb *QueryBuilder) Paginate(page, perPage int) *QueryBuilder

Paginate adds pagination to the query

func (*QueryBuilder) Raw

func (qb *QueryBuilder) Raw(query string, params ...interface{}) (*sql.Rows, error)

Raw executes a raw SQL query

func (*QueryBuilder) RawExec

func (qb *QueryBuilder) RawExec(query string, params ...interface{}) (sql.Result, error)

RawExec executes a raw SQL statement

func (*QueryBuilder) Restore

func (qb *QueryBuilder) Restore() (sql.Result, error)

Restore clears the deleted_at timestamp, effectively "undeleting" the row.

func (*QueryBuilder) RightJoin

func (qb *QueryBuilder) RightJoin(table, on string) *QueryBuilder

RightJoin adds a RIGHT JOIN

func (*QueryBuilder) Scope

func (qb *QueryBuilder) Scope(scopes ...Scope) *QueryBuilder

Scope applies one or more scopes to the query builder. Scopes are reusable query modifications.

Example:

Active := func(qb *QueryBuilder) *QueryBuilder {
    return qb.Where("active", "=", true)
}
users, _ := db.Table("users").Scope(Active).Get()

func (*QueryBuilder) Select

func (qb *QueryBuilder) Select(columns ...string) *QueryBuilder

Select specifies the columns to select

func (*QueryBuilder) SoftDelete

func (qb *QueryBuilder) SoftDelete() (sql.Result, error)

SoftDelete sets deleted_at to current timestamp instead of deleting the row. This is useful for preserving data while marking it as deleted.

func (*QueryBuilder) Table

func (qb *QueryBuilder) Table(table string) *QueryBuilder

Table sets the table name for the query

func (*QueryBuilder) ToSQL

func (qb *QueryBuilder) ToSQL() (string, []interface{}, error)

ToSQL builds the SQL query string and returns it with parameters

func (*QueryBuilder) Transaction

func (qb *QueryBuilder) Transaction(fn func(tx *QueryBuilder) error) error

Transaction executes a function within a database transaction. If the function returns an error, the transaction is rolled back. If the function returns nil, the transaction is committed.

func (*QueryBuilder) Union

func (qb *QueryBuilder) Union(query *QueryBuilder) *QueryBuilder

Union adds a UNION clause

func (*QueryBuilder) UnionAll

func (qb *QueryBuilder) UnionAll(query *QueryBuilder) *QueryBuilder

UnionAll adds a UNION ALL clause

func (*QueryBuilder) Update

func (qb *QueryBuilder) Update(data map[string]interface{}) (sql.Result, error)

Update builds and executes an UPDATE query

func (*QueryBuilder) Where

func (qb *QueryBuilder) Where(column, operator string, value interface{}) *QueryBuilder

Where adds a WHERE condition

func (*QueryBuilder) WhereBetween

func (qb *QueryBuilder) WhereBetween(column string, start, end interface{}) *QueryBuilder

WhereBetween adds a BETWEEN condition

func (*QueryBuilder) WhereIn

func (qb *QueryBuilder) WhereIn(column string, values []interface{}) *QueryBuilder

WhereIn adds a WHERE IN condition

func (*QueryBuilder) WhereNotNull

func (qb *QueryBuilder) WhereNotNull(column string) *QueryBuilder

WhereNotNull adds a WHERE column IS NOT NULL condition

func (*QueryBuilder) WhereNull

func (qb *QueryBuilder) WhereNull(column string) *QueryBuilder

WhereNull adds a WHERE column IS NULL condition

func (*QueryBuilder) WithDialect added in v0.7.0

func (qb *QueryBuilder) WithDialect(dialect Dialect) *QueryBuilder

WithDialect sets the placeholder syntax for this builder and returns it.

func (*QueryBuilder) WithTrashed

func (qb *QueryBuilder) WithTrashed() *QueryBuilder

WithTrashed includes soft-deleted records in the query results. Use this when you need to access deleted records.

type Scope

type Scope func(*QueryBuilder) *QueryBuilder

Scope is a function that modifies a QueryBuilder. Use scopes to create reusable query constraints.

type Seeder

type Seeder interface {
	Run(db *sql.DB) error
}

Seeder interface defines the structure for database seeders

type SeederRegistry

type SeederRegistry struct {
	// contains filtered or unexported fields
}

SeederRegistry manages all registered seeders

func CreateSeederRegistry

func CreateSeederRegistry() *SeederRegistry

CreateSeederRegistry creates and registers common seeders

func NewSeederRegistry

func NewSeederRegistry() *SeederRegistry

NewSeederRegistry creates a new seeder registry

func (*SeederRegistry) ListSeeders

func (sr *SeederRegistry) ListSeeders() []string

ListSeeders returns all registered seeder names

func (*SeederRegistry) Register

func (sr *SeederRegistry) Register(name string, seeder Seeder)

Register adds a seeder to the registry

func (*SeederRegistry) Run

func (sr *SeederRegistry) Run(db *sql.DB, name string) error

Run executes a specific seeder by name

func (*SeederRegistry) RunAll

func (sr *SeederRegistry) RunAll(db *sql.DB) error

RunAll executes all registered seeders

type TxBeginner

type TxBeginner interface {
	Begin() (*sql.Tx, error)
}

TxBeginner is an interface for types that can begin a transaction

type UserSeeder

type UserSeeder struct {
	BaseSeeder
}

Example seeder implementation

func NewUserSeeder

func NewUserSeeder() *UserSeeder

NewUserSeeder creates a new user seeder

func (*UserSeeder) Run

func (us *UserSeeder) Run(db *sql.DB) error

Run executes the user seeder

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL