mud

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2025 License: MIT Imports: 18 Imported by: 0

README

mud - Database ORM for Go

Note: This is a work in progress and is not yet ready for production use.

mud is a versatile and lightweight ORM (Object-Relational Mapping) package for Go that supports multiple database backends including PostgreSQL, MySQL, SQLite, and Microsoft SQL Server.

Features

  • Support for multiple database backends
  • Fluent query builder interface
  • Advanced WHERE clause construction
  • Automatic model mapping
  • Transaction support
  • Field validation and type safety
  • UUID support for primary keys

Installation

go get github.com/markoxley/mud

Quick Start

package main

import (
    "github.com/markoxley/mud"
    "github.com/markoxley/mud/where"
)

// Define your model
type User struct {
    mud.Model
    Username  string `mud:"size:64,key:true"`
    Email     string `mud:"size:256"`
}

func main() {
    // Initialize database connection
    config := mud.Config{
        Driver:   "mysql",
        Host:     "localhost",
        Port:     3306,
        Database: "mydb",
        Username: "user",
        Password: "password",
    }

    db, err := mud.Connect(config)
    if err != nil {
        panic(err)
    }
    defer db.Close()

    // Create a new user
    user := &User{
        Username: "johndoe",
        Email:    "john@example.com",
    }

    err = db.Save(user)
    if err != nil {
        panic(err)
    }

    // Query users with WHERE clause
    var users []User
    where := where.Equal("username", "johndoe")
    err = db.Find(&users, where)
    if err != nil {
        panic(err)
    }

    // Update user, we reuse the Save method
    user.Email = "john.doe@example.com"
    err = db.Save(user)
    if err != nil {
        panic(err)
    }

    // Delete user
    err = db.Remove(user)
    if err != nil {
        panic(err)
    }

    // Convenience functions with generics
    user, err = mud.First[User](db, where.Equal("username", "johndoe"))
    if err != nil {
        panic(err)
    }

    user, err = mud.FromID[User](db, *user.ID)
    if err != nil {
        panic(err)
    }
}

WHERE Clause Builder

mud provides a powerful WHERE clause builder with support for various conditions:

// Basic conditions
where.Equal("field", value)
where.NotEqual("field", value)
where.Greater("field", value)
where.Less("field", value)

// String operations
where.Contains("field", "substring")
where.StartsWith("field", "prefix")
where.EndsWith("field", "suffix")

// Null checks
where.IsNull("field")
where.NotIsNull("field")

// Range operations
where.Between("field", value1, value2)
where.In("field", []interface{}{value1, value2})

// Combining conditions
where.Equal("field1", value1).AndEqual("field2", value2)
where.Equal("field1", value1).OrEqual("field2", value2)

Order clause builder

mud provides a powerful ORDER BY clause builder with support for various conditions:

// Basic conditions
order.Asc("field")
order.Desc("field")

// Combining conditions
order.Asc("field1").Desc("field2")

Model Tags

mud uses struct tags to define model properties:

  • mud:"" - Specify the field is to be included in the database
  • mud:"key:true" - Create an index on field
  • mud:"size:255" - Set field size
  • mud:"allowNull" - Allow NULL values

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Documentation

Overview

Package mud provides a database ORM (Object-Relational Mapping) implementation with support for SQLite, MySQL, and SQL Server databases.

Copyright (c) 2025 DaggerTech. All rights reserved. Use of this source code is governed by an MIT license that can be found in the LICENSE file. Package mud provides a database ORM (Object-Relational Mapping) implementation with support for SQLite, MySQL, and SQL Server databases.

Copyright (c) 2025 DaggerTech. All rights reserved. Use of this source code is governed by an MIT license that can be found in the LICENSE file. Package mud provides a database ORM (Object-Relational Mapping) implementation with support for SQLite, MySQL, and SQL Server databases.

Copyright (c) 2025 DaggerTech. All rights reserved. Use of this source code is governed by an MIT license that can be found in the LICENSE file.

Copyright (c) 2025 DaggerTech. All rights reserved. Use of this source code is governed by an MIT license that can be found in the LICENSE file. Package mud provides a database ORM (Object-Relational Mapping) implementation with support for SQLite, MySQL, and SQL Server databases.

Copyright (c) 2025 DaggerTech. All rights reserved. Use of this source code is governed by an MIT license that can be found in the LICENSE file. Package mud provides a database ORM (Object-Relational Mapping) implementation with support for SQLite, MySQL, and SQL Server databases.

Copyright (c) 2025 DaggerTech. All rights reserved. Use of this source code is governed by an MIT license that can be found in the LICENSE file. Package mud provides a database ORM (Object-Relational Mapping) implementation with support for SQLite, MySQL, and SQL Server databases.

Copyright (c) 2025 DaggerTech. All rights reserved. Use of this source code is governed by an MIT license that can be found in the LICENSE file. Package mud provides interfaces for database operations in the ORM.

Copyright (c) 2025 DaggerTech. All rights reserved. Use of this source code is governed by an MIT license that can be found in the LICENSE file. Package mud provides database management interfaces and implementations.

Copyright (c) 2025 DaggerTech. All rights reserved. Use of this source code is governed by an MIT license that can be found in the LICENSE file. Package mud provides base model functionality for database entities.

Copyright (c) 2025 DaggerTech. All rights reserved. Use of this source code is governed by an MIT license that can be found in the LICENSE file. Package mud provides interfaces and utilities for database model management.

Copyright (c) 2025 DaggerTech. All rights reserved. Use of this source code is governed by an MIT license that can be found in the LICENSE file. Package mud provides a simple ORM implementation for MS SQL Server databases.

Copyright (c) 2025 DaggerTech. All rights reserved. Use of this source code is governed by an MIT license that can be found in the LICENSE file. Package mud provides a simple ORM implementation for MySQL databases.

Copyright (c) 2025 DaggerTech. All rights reserved. Use of this source code is governed by an MIT license that can be found in the LICENSE file. Package mud provides a simple ORM implementation for SQLite databases.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Fetch

func Fetch[T Modeller](db *DB, criteria ...interface{}) ([]*T, error)

func First

func First[T Modeller](db *DB, criteria ...interface{}) (*T, error)

func FromID added in v0.0.2

func FromID[T Modeller](db *DB, id string) (*T, error)

func GetTableName

func GetTableName(m Modeller) string

GetTableName determines the database table name for a model. If the model is a pointer, it dereferences it to get the actual type name. The table name is derived from the struct type name.

func GetTypeName

func GetTypeName(m Manager) string

GetTypeName returns the type name of the manager implementation

func Range

func Range[T Modeller](db *DB, criteria ...interface{}) iter.Seq[*T]

func Version

func Version() string

Version returns the current version of the mud package as a string. The version follows semantic versioning format (MAJOR.MINOR.PATCH). Returns:

A string representing the current version

Types

type Config

type Config struct {
	// Type specifies the type of database (sqlite, mysql, sqlserver)
	Type string `json:"type"`
	// Host specifies the hostname or IP address of the database server
	// This is optional for SQLite databases
	Host string `json:"host,omitzero"`
	// Database specifies the name of the database to connect to
	Database string `json:"database"`
	// User specifies the username for database authentication
	// This is optional for SQLite databases
	User string `json:"user,omitzero"`
	// Password specifies the password for database authentication
	// This is optional for SQLite databases
	Password string `json:"password,omitzero"`
	// Deletable indicates whether records can be permanently deleted
	// When false, records are soft-deleted (marked with delete date)
	Deletable bool `json:"deletable,omitzero"`
	// DisabledTransactions indicates whether database transactions should be disabled
	// When true, each operation will be executed independently
	DisabledTransactions bool `json:"disabledTransactions,omitzero"`
}

Config represents the configuration for a database connection. It contains all the necessary information to establish and configure a database connection.

type Criteria

type Criteria struct {
	// Where defines the WHERE condition for the query
	Where interface{}
	// Order defines the ORDER BY condition for the query
	Order interface{}
	// Limit specifies the maximum number of rows to return
	Limit int
	// Offset specifies the number of rows to skip
	Offset int
	// IncDeleted indicates whether to include soft-deleted records
	IncDeleted bool
}

Criteria is used to safely build search criteria for database queries. It provides a structured way to define WHERE, ORDER BY, LIMIT, and OFFSET conditions.

func (Criteria) LimitString

func (c Criteria) LimitString(mgr Manager) string

LimitString returns the limiter in SQL format @receiver c @return string

func (Criteria) OffsetString

func (c Criteria) OffsetString(mgr Manager) string

OffsetString returns the offset in SQL format @receiver c @return string

func (Criteria) OrderString

func (c Criteria) OrderString(mgr Manager) string

OrderString returns the ORDER BY condition in SQL format. It converts the criteria's Order condition into a properly formatted SQL ORDER BY clause. Parameters:

mgr: The database manager used to format the ORDER BY condition

Returns:

A string containing the SQL ORDER BY clause

func (Criteria) String

func (c Criteria) String(mgr Manager) string

String returns the full criteria in SQL format @receiver c @return string

func (Criteria) WhereString

func (c Criteria) WhereString(mgr Manager) string

WhereString returns the WHERE condition in SQL format. It converts the criteria's Where condition into a properly formatted SQL WHERE clause. Parameters:

mgr: The database manager used to format the WHERE condition

Returns:

A string containing the SQL WHERE clause

type DB

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

func New

func New(config *Config) (*DB, error)

func (*DB) BeginTransaction

func (db *DB) BeginTransaction() (*sql.Tx, error)

func (*DB) Close

func (db *DB) Close()

func (*DB) CommitTransaction

func (db *DB) CommitTransaction(tx *sql.Tx) error

commitTransaction commites the transaction to the database @param tx

func (*DB) Count

func (db *DB) Count(m Modeller, criteria ...interface{}) int

Count returns the number of rows in the database that match the criteria @param criteria @return int

func (*DB) Fetch

func (db *DB) Fetch(mdl Modeller, criteria ...interface{}) ([]Modeller, error)

Fetch populates the slice with models from the database that match the criteria. Returns an error if this fails @param criteria @return []*T @return error

func (*DB) First

func (db *DB) First(m Modeller, criteria ...interface{}) (Modeller, error)

First returns the first model that matches the criteria @param criteria @return *T @return error

func (*DB) Range

func (db *DB) Range(mdl Modeller, criteria ...interface{}) iter.Seq[Modeller]

func (*DB) RawExecute

func (db *DB) RawExecute(sql string, tx ...*sql.Tx) error

RawExecute executes a sql statement on the database, without returning a value Not recommended for general use - can break shadowing @param sql @return bool

func (*DB) RawScalar

func (db *DB) RawScalar(sql string, tx ...*sql.Tx) (interface{}, bool)

RawScalar exeutes a raw sql statement that returns a single value Not recommended for general use @param sql @return interface{} @return bool

func (*DB) RawSelect

func (db *DB) RawSelect(qry string, tx ...*sql.Tx) ([]map[string]interface{}, error)

RawSelect executes a raw sql statement on the database Not recommended for general use @param sql @return []map

func (*DB) Refresh

func (db *DB) Refresh(m Modeller) error

func (*DB) Remove

func (db *DB) Remove(m Modeller, tx ...*sql.Tx) error

Remove removes the passed model from the database @param m @return bool

func (*DB) RemoveMany

func (db *DB) RemoveMany(m Modeller, c *Criteria, tx ...*sql.Tx) (int, error)

RemoveMany removes all models of the specified type that match the criteria @param c @return int @return bool

func (*DB) RollbackTransaction

func (db *DB) RollbackTransaction(tx *sql.Tx) error

func (*DB) Save

func (db *DB) Save(m Modeller, tx ...*sql.Tx) error

Save stores the model in the database. Depending on the status of the model, this is either an update or an insert command @param m @return bool

type ErrNoResults

type ErrNoResults struct {
	// Err contains the underlying error that caused the no results condition
	Err error
}

ErrNoResults represents an error that occurs when a database query returns no results. This error is typically returned when a query expects at least one result but finds none.

func NoResults

func NoResults(msg string) ErrNoResults

NoResults creates a new ErrNoResults error with the specified message. This function is used to wrap errors when a database query returns no results. Parameters:

msg: The error message to include in the error

Returns:

A new ErrNoResults error

func (ErrNoResults) Error

func (e ErrNoResults) Error() string

Error returns the error message for ErrNoResults. This method implements the error interface for ErrNoResults. Returns:

The error message as a string

type FieldSize

type FieldSize struct {
	// Size represents the maximum length of the field
	Size int
	// Decimal represents the number of decimal places for numeric types
	Decimal int
}

FieldSize represents the size and precision of a database field. It is used to store the maximum length and decimal places for numeric types.

func NewSize

func NewSize(sz, dec int) FieldSize

NewSize creates a new FieldSize with the specified size and decimal places. This function is used to define the size constraints for database fields. Parameters:

sz: The maximum length of the field
dec: The number of decimal places (for numeric types)

Returns:

A new FieldSize instance

func (FieldSize) String

func (s FieldSize) String() string

String returns a string representation of the field size. For numeric types with decimal places, it returns "size,decimal". For other types, it returns just the size. This method is used for generating SQL schema definitions. Returns:

A string representation of the field size

type MSSQLManager

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

MSSQLManager implements the database management interface for Microsoft SQL Server. It handles SQL Server specific query generation and database operations.

func (*MSSQLManager) BuildQuery

func (m *MSSQLManager) BuildQuery(where string, order string, limit string, offset string) string

BuildQuery combines WHERE, ORDER BY, LIMIT, and OFFSET clauses into a complete query string.

func (*MSSQLManager) ConnectionString

func (m *MSSQLManager) ConnectionString(cfg *Config) (string, error)

ConnectionString generates a SQL Server connection string from the provided configuration. Returns an error if the configuration is nil or missing required fields.

func (*MSSQLManager) GetDB

func (m *MSSQLManager) GetDB() *DB

GetDB returns the current database connection.

func (*MSSQLManager) IdentityString

func (m *MSSQLManager) IdentityString(f string) string

IdentityString wraps a field name in square brackets for SQL Server identifier escaping.

func (*MSSQLManager) IndexCreate

func (m *MSSQLManager) IndexCreate() string

IndexCreate returns the SQL Server index creation query template.

func (*MSSQLManager) LimitString

func (m *MSSQLManager) LimitString(c *Criteria) string

LimitString generates the SQL Server specific FETCH NEXT clause for result limiting. Returns an empty string if criteria is nil or limit is less than 1.

func (*MSSQLManager) OffsetString

func (m *MSSQLManager) OffsetString(c *Criteria) string

OffsetString generates the SQL Server specific OFFSET clause. Returns an empty string if criteria is nil or offset is less than 1.

func (*MSSQLManager) Operators

func (m *MSSQLManager) Operators() []string

Operators returns a list of SQL Server compatible operator formats for query building. These formats include comparison, LIKE, IN, BETWEEN, and NULL check operators.

func (*MSSQLManager) SetDB

func (m *MSSQLManager) SetDB(db *DB)

SetDB assigns a database connection to the manager.

func (*MSSQLManager) TableCreate

func (m *MSSQLManager) TableCreate() string

TableCreate returns the SQL Server table creation query template. The template includes a check to prevent creating duplicate tables.

func (*MSSQLManager) TableExistsQuery

func (m *MSSQLManager) TableExistsQuery(name string) string

TableExistsQuery generates a query to check if a table exists in the database.

type Manager

type Manager interface {
	// SetDB assigns a database connection to the manager
	SetDB(db *DB)

	// GetDB returns the current database connection
	GetDB() *DB

	// ConnectionString generates a database-specific connection string from the configuration
	ConnectionString(cfg *Config) (string, error)

	// LimitString generates the database-specific LIMIT clause
	LimitString(c *Criteria) string

	// OffsetString generates the database-specific OFFSET clause
	OffsetString(c *Criteria) string

	// IdentityString wraps field names with database-specific identifier quotes
	IdentityString(f string) string

	// BuildQuery combines WHERE, ORDER BY, LIMIT, and OFFSET clauses into a query
	BuildQuery(where string, order string, limit string, offset string) string

	// TableExistsQuery generates a query to check if a table exists
	TableExistsQuery(name string) string

	// Operators returns a list of database-specific operator formats
	Operators() []string

	// TableCreate returns the database-specific table creation template
	TableCreate() string

	// IndexCreate returns the database-specific index creation template
	IndexCreate() string
}

Manager defines the interface for database-specific operations. Each supported database type (SQLite, MySQL, SQL Server) implements this interface to provide its specific SQL syntax and behavior.

func GetManager

func GetManager(config *Config) (Manager, error)

GetManager creates and returns a database-specific Manager implementation based on the configuration. Supported database types are: "sqlite", "mysql", and "sqlserver". Returns an error if an unsupported database type is specified or if config is nil.

type Model

type Model struct {
	// Unique identifier for the record
	ID *string
	// Timestamp when the record was created
	CreateDate time.Time
	// Timestamp of the last update
	LastUpdate time.Time
	// Timestamp when the record was soft deleted (nil if active)
	DeleteDate *time.Time
	// contains filtered or unexported fields
}

Model represents the base structure for all database entities. It provides common fields and functionality for tracking creation, updates, and soft deletion of records.

func CreateModel

func CreateModel() Model

CreateModel initializes a new Model instance with current timestamps. This should be called when creating new database entities.

func (*Model) Disable

func (m *Model) Disable()

Disable marks the model as soft deleted by setting its DeleteDate to current time.

func (Model) GetID

func (m Model) GetID() *string

GetID returns the unique identifier of the model.

func (Model) IsDeleted

func (m Model) IsDeleted() bool

IsDeleted checks if the model has been soft deleted. Returns true if DeleteDate is not nil, indicating the record is deleted.

func (Model) IsNew

func (m Model) IsNew() bool

IsNew checks if the model is a new record (has not been saved to database). Returns true if the ID is nil, indicating the record hasn't been assigned an ID.

func (Model) StandingData

func (m Model) StandingData() []Modeller

StandingData returns a list of default records for the model. This can be overridden by implementing models to provide seed data.

type Modeller

type Modeller interface {
	// StandingData returns the standing data for the model.
	// This is used to provide seed or default data for the model.
	StandingData() []Modeller

	// GetID returns the ID of the model.
	// Returns nil if the model hasn't been saved to the database.
	GetID() *string

	// IsNew returns true if the model has yet to be saved to the database.
	IsNew() bool

	// IsDeleted returns true if the model has been marked as deleted.
	// This is used for soft deletion support.
	IsDeleted() bool
}

Modeller defines the interface for database model objects. Any struct that implements this interface can be used as a database model.

type MySQLManager

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

MySQLManager implements the database management interface for MySQL. It handles MySQL specific query generation and database operations.

func (*MySQLManager) BuildQuery

func (m *MySQLManager) BuildQuery(where string, order string, limit string, offset string) string

BuildQuery combines WHERE, ORDER BY, LIMIT, and OFFSET clauses into a complete query string.

func (*MySQLManager) ConnectionString

func (m *MySQLManager) ConnectionString(cfg *Config) (string, error)

ConnectionString generates a MySQL connection string from the provided configuration. Returns an error if the configuration is nil or missing required fields.

func (*MySQLManager) GetDB

func (m *MySQLManager) GetDB() *DB

GetDB returns the current database connection.

func (*MySQLManager) IdentityString

func (m *MySQLManager) IdentityString(f string) string

IdentityString wraps a field name in backticks for MySQL identifier escaping.

func (*MySQLManager) IndexCreate

func (m *MySQLManager) IndexCreate() string

IndexCreate returns the MySQL index creation query template.

func (*MySQLManager) LimitString

func (m *MySQLManager) LimitString(c *Criteria) string

LimitString generates the MySQL specific LIMIT clause for result limiting. Returns an empty string if criteria is nil or limit is less than 1.

func (*MySQLManager) OffsetString

func (m *MySQLManager) OffsetString(c *Criteria) string

OffsetString generates the MySQL specific OFFSET clause. Returns an empty string if criteria is nil or offset is less than 1.

func (*MySQLManager) Operators

func (m *MySQLManager) Operators() []string

Operators returns a list of MySQL compatible operator formats for query building. These formats include comparison, LIKE, IN, BETWEEN, and NULL check operators.

func (*MySQLManager) SetDB

func (m *MySQLManager) SetDB(db *DB)

SetDB assigns a database connection to the manager.

func (*MySQLManager) TableCreate

func (m *MySQLManager) TableCreate() string

TableCreate returns the MySQL table creation query template. The template includes IF NOT EXISTS to prevent duplicate table creation errors.

func (*MySQLManager) TableExistsQuery

func (m *MySQLManager) TableExistsQuery(name string) string

TableExistsQuery generates a query to check if a table exists in the database.

type Remover

type Remover interface{}

Remover defines the interface for objects that can be removed from the database.

type Restorer

type Restorer interface {
	// Restore generates a restore query for the object using the provided manager.
	// Returns the generated query string and any error encountered.
	Restore(mgr Manager) error
}

Restorer defines the interface for objects that can be restored from the database.

type SqliteManager

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

SqliteManager implements the database management interface for SQLite. It handles SQLite specific query generation and database operations.

func (*SqliteManager) BuildQuery

func (m *SqliteManager) BuildQuery(where string, order string, limit string, offset string) string

BuildQuery combines WHERE, ORDER BY, LIMIT, and OFFSET clauses into a complete query string.

func (*SqliteManager) ConnectionString

func (m *SqliteManager) ConnectionString(cfg *Config) (string, error)

ConnectionString generates a SQLite connection string from the provided configuration. Returns an error if the configuration is nil or missing required fields. Note that SQLite only requires the database path, unlike other SQL databases.

func (*SqliteManager) GetDB

func (m *SqliteManager) GetDB() *DB

GetDB returns the current database connection.

func (*SqliteManager) IdentityString

func (m *SqliteManager) IdentityString(f string) string

IdentityString wraps a field name in double quotes for SQLite identifier escaping.

func (*SqliteManager) IndexCreate

func (m *SqliteManager) IndexCreate() string

IndexCreate returns the SQLite index creation query template.

func (*SqliteManager) LimitString

func (m *SqliteManager) LimitString(c *Criteria) string

LimitString generates the SQLite specific LIMIT clause for result limiting. Returns an empty string if criteria is nil or limit is less than 1.

func (*SqliteManager) OffsetString

func (m *SqliteManager) OffsetString(c *Criteria) string

OffsetString generates the SQLite specific OFFSET clause. Returns an empty string if criteria is nil or offset is less than 1.

func (*SqliteManager) Operators

func (m *SqliteManager) Operators() []string

Operators returns a list of SQLite compatible operator formats for query building. These formats include comparison, LIKE, IN, BETWEEN, and NULL check operators.

func (*SqliteManager) SetDB

func (m *SqliteManager) SetDB(db *DB)

SetDB assigns a database connection to the manager.

func (*SqliteManager) TableCreate

func (m *SqliteManager) TableCreate() string

TableCreate returns the SQLite table creation query template. The template includes IF NOT EXISTS to prevent duplicate table creation errors.

func (*SqliteManager) TableExistsQuery

func (m *SqliteManager) TableExistsQuery(name string) string

TableExistsQuery generates a query to check if a table exists in the database. Uses the sqlite_master system table to check for table existence.

type Updater

type Updater interface {
	// Update generates an update query for the object using the provided manager.
	// Returns the generated query string and any error encountered.
	Update(mgr Manager) error
}

Updater defines the interface for objects that can be updated in the database.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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