simpledb

package module
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2022 License: GPL-2.0 Imports: 15 Imported by: 0

README

SimpleDB

A simple ORM for MySQL.

Installation

Easily install simpledb with the following command:

go get github.com/Nigel2392/simpledb

Usage

Documentation

Index

Constants

View Source
const (
	IN   = "IN"
	EQ   = "="
	NE   = "!="
	GT   = ">"
	GTE  = ">="
	LT   = "<"
	LTE  = "<="
	LIKE = "LIKE"
)

Equality operators for use in filters

View Source
const TAG = "simpledb"

Tag to get from model structs.

Variables

This section is empty.

Functions

func AllColumns added in v1.2.0

func AllColumns(model any, exclude ...string) []string

Get all of the model columns, including related fields. Optionally, you can specify a list of columns to exclude.

func CheckSQLError added in v1.0.8

func CheckSQLError(err error, number int) bool

Check for SQL errors

func Columns

func Columns(model any, exclude ...string) []string

Get the model columns, excluding related fields. Optionally, you can specify a list of columns to exclude.

func ColumnsWithTypes

func ColumnsWithTypes(model any) ([]string, []string)

Get the columns with golang types

func Exclude

func Exclude[T comparable](a []T, b []T) []T

Exclude an item from a slice.

func GetColType

func GetColType(typ string, dialect string) string

Get the column types for a specified golang type

func GetColTypes

func GetColTypes(types []string, dialect string) []string

Get the column types for the model

func GetValue

func GetValue(model Model, column string) any

Get a value from a model struct

func MapToSlice

func MapToSlice[T string | int | bool | int8 | int16 | int32 | int64](m map[T]any) ([]T, []any)

Convert a map to a slice of keys and a slice of values

func Scan

func Scan(model Model, row *sql.Rows, exclude []string) error

Scan a row into a model

func SetValue

func SetValue(model Model, column string, value any)

Set a value on a model struct

func TagValid

func TagValid(field reflect.StructField) bool

Verify if a field/tag is valid to be used.

func TagValues

func TagValues(field reflect.StructField) []string

Split tags into lists of [Key:Value, Key:Value, ...] pairs.

Types

type Column

type Column struct {
	Table    string
	Name     string
	Default  string
	Type     DBType
	Raw      string
	Length   int
	Nullable bool
	Unique   bool
	Primary  bool
	Index    bool
	Auto     bool
	Tags     ModelTags
}

Representation of a column, used to create tables when migrating

func MigrationColumns

func MigrationColumns(model Model) []Column

Get the columns needed for a migration

func (Column) String

func (c Column) String() string

Generate a query for the column

type DBType

type DBType string
const (
	VARCHAR     DBType = "VARCHAR"
	TEXT        DBType = "TEXT"
	INT         DBType = "INT"
	BOOLEAN     DBType = "BOOLEAN"
	TINYINT     DBType = "TINYINT"
	SMALLINT    DBType = "SMALLINT"
	BIGINT      DBType = "BIGINT"
	FLOAT       DBType = "FLOAT"
	DOUBLE      DBType = "DOUBLE"
	DATETIME    DBType = "DATETIME"
	BLOB        DBType = "BLOB"
	FOREIGN_KEY DBType = "FOREIGN KEY"
)

Database types

type Database

type Database struct {
	Host     string
	Port     any
	Username string
	Password string `json:"-"`
	Database string
	SSL_MODE string
	LIMIT    int

	LatestMigration *Migration       `json:"-"`
	Logger          simplelog.Logger `json:"-"`
	// contains filtered or unexported fields
}

Database is the main struct for the database

func NewDatabase

func NewDatabase(loglevel ...string) *Database

Connect to the database

func (*Database) Addr

func (db *Database) Addr() string

Get the address of the database

func (*Database) AllModel

func (d *Database) AllModel(model Model, include []string) ModelSet

All models from a table

func (*Database) AllModels added in v1.1.6

func (db *Database) AllModels() []Model

Return all the models registered with the database

func (*Database) AllQ

func (d *Database) AllQ(model Model, exclude []string) string

AllQ returns a query that will return all rows in the table.

func (*Database) AlterDropOneToOne

func (db *Database) AlterDropOneToOne(from, to string) error

func (*Database) AlterOneToOne

func (db *Database) AlterOneToOne(from, to string) error

func (*Database) Begin

func (db *Database) Begin() (*sql.Tx, error)

Begin a transaction

func (*Database) CheckError added in v1.0.8

func (db *Database) CheckError(err error, number int) bool

Check for SQL errors

func (*Database) Close

func (db *Database) Close() error

Close the database connection

func (*Database) Connect

func (db *Database) Connect() error

Connect to the database

func (*Database) Count

func (db *Database) Count(table_name string, filter ...Filter) (int, error)

Count the number of rows in a table. Allows filters.

func (*Database) CreateFKTable

func (db *Database) CreateFKTable(from, to string) error

func (*Database) CreateTableQuery

func (d *Database) CreateTableQuery(table string, columns []string) string

Create a table from columns.

func (*Database) DB_Columns

func (db *Database) DB_Columns(table_name string) ([]string, error)

Get column information for a model.

func (*Database) DB_Columns_With_Type

func (db *Database) DB_Columns_With_Type(table_name string) (map[string]string, error)

Get column information for a model. Also retrieves the column type.

func (*Database) DB_Tables

func (d *Database) DB_Tables() ([]string, error)

Get the tables from the database

func (*Database) DSN

func (db *Database) DSN() string

Get the DSN for the database

func (*Database) DeleteFK

func (db *Database) DeleteFK(from, to Model) error

func (*Database) DeleteModel added in v1.1.0

func (d *Database) DeleteModel(model Model) error

Delete a model from the database

func (*Database) DeleteOneToOne added in v1.1.9

func (db *Database) DeleteOneToOne(from, to Model) error

func (*Database) DeleteQuery

func (d *Database) DeleteQuery(table string, where string) string

Delete a row from a table.

func (*Database) DropFKTable

func (db *Database) DropFKTable(from, to string) error

func (*Database) DropTable

func (db *Database) DropTable(table_name string) error

Drop a table.

func (*Database) Exec

func (db *Database) Exec(query string, args ...interface{}) (sql.Result, error)

Exec a query

func (*Database) ExecContext

func (db *Database) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

Exec a query with context

func (*Database) ExecCreateTable

func (d *Database) ExecCreateTable(table string, columns []string) error

Execute creating a table.

func (*Database) ExecDelete

func (d *Database) ExecDelete(table string, where string) error

Execute deleting a row.

func (*Database) ExecInsert

func (d *Database) ExecInsert(table string, columns []string, values []interface{}) (int64, error)

Execute inserting a row.

func (*Database) ExecSelect

func (d *Database) ExecSelect(table string, where string) (*sql.Rows, error)

Execute selecting from a table.

func (*Database) ExecUpdate

func (d *Database) ExecUpdate(table string, columns []string, values []interface{}, where string, conditional any) (int64, error)

Execute updating a row.

func (*Database) Filter

func (d *Database) Filter(model Model, filter Filters, include []string) ModelSet

Filter returns a QuerySet with the given filters applied.

func (*Database) FilterWithLimit

func (d *Database) FilterWithLimit(model Model, filters Filters, limit int, include []string) ModelSet

See Filter. Also allows you to specify a limit on the number of results returned.

func (*Database) GetColumnValue

func (db *Database) GetColumnValue(model Model, col string, id any) interface{}

Get the column for a model.

func (*Database) GetFromEnv

func (db *Database) GetFromEnv() *Database

Get the credentials from the environment variables

func (*Database) GetOneToOneReverse added in v1.1.9

func (db *Database) GetOneToOneReverse(from, to Model) (Model, error)

func (*Database) InsertFK

func (db *Database) InsertFK(from, to Model) error

func (*Database) InsertModel

func (d *Database) InsertModel(model Model) error

Insert a model into the database. Takes a pointer to a model and a sql.Row and scans the ID of result into the model

func (*Database) InsertOneToOne added in v1.1.9

func (db *Database) InsertOneToOne(from, to Model) error

func (*Database) InsertQuery

func (d *Database) InsertQuery(table string, columns []string) string

Insert a row into a table.

func (*Database) LoadCredentials

func (db *Database) LoadCredentials() *Database

Load the credentials from the .env file

func (*Database) Migrate

func (db *Database) Migrate() error

Migrate the database to the latest version

func (*Database) NewQS

func (db *Database) NewQS(mdl Model) *QuerySet

Shorthand for a queryset

func (*Database) Ping

func (db *Database) Ping() error

Ping the database

func (*Database) Prepare

func (db *Database) Prepare(query string) (*sql.Stmt, error)

Prepare a query

func (*Database) PrepareContext

func (db *Database) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)

Prepare a query with context

func (*Database) Query

func (db *Database) Query(query string, args ...interface{}) (*sql.Rows, error)

Query the database

func (*Database) QueryContext

func (db *Database) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

Query the database with context

func (*Database) QueryRow

func (db *Database) QueryRow(query string, args ...interface{}) *sql.Row

Query a database row

func (*Database) QueryRowContext

func (db *Database) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row

Query the database row with context

func (*Database) QuerySelect

func (d *Database) QuerySelect(table string, columns []string, where string) (*sql.Rows, error)

Execute selecting a row from a table.

func (*Database) QuerySelectOne

func (d *Database) QuerySelectOne(table string, column string, where string) *sql.Row

Execute selecting one row from a table.

func (*Database) QuerySelectRow

func (d *Database) QuerySelectRow(table string, columns []string, where string) *sql.Row

Execute selecting one row from a table.

func (*Database) Register

func (db *Database) Register(model Model)

Register a model with the database This will be used to create the table if it doesn't exist, and to create the migration if it doesn't exist

func (*Database) SelectFK

func (db *Database) SelectFK(from, to Model) (ModelSet, error)

func (*Database) SelectFKReverse

func (db *Database) SelectFKReverse(from, to Model) (ModelSet, error)

func (*Database) SelectOneQuery

func (d *Database) SelectOneQuery(table string, column string, where string) string

Select one row from a table.

func (*Database) SelectOneToOne added in v1.1.9

func (db *Database) SelectOneToOne(from, to Model) (Model, error)

func (*Database) SelectQuery

func (d *Database) SelectQuery(table string, columns []string, where string) string

Select from a table.

func (*Database) SelectRowQuery

func (d *Database) SelectRowQuery(table string, columns []string, where string) string

Select a row from a table.

func (*Database) String

func (db *Database) String() string

Database string method

func (*Database) UpdateModel added in v1.0.5

func (d *Database) UpdateModel(model Model) (Model, error)

Update a model in the database.

func (*Database) UpdateQuery

func (d *Database) UpdateQuery(table string, columns []string, where string) string

Update a row in a table.

type Filter

type Filter struct {
	Column   string
	Value    any
	Operator string
}

Generic filter for a queryset.

type Filters

type Filters []*Filter

List of filters, handy for creating a query.

func (Filters) Add

func (f Filters) Add(column string, op string, value any) Filters

Add a filter to the list of filters.

func (Filters) Get

func (f Filters) Get(column string) any

Get a filter from the list of filters.

func (Filters) Has

func (f Filters) Has(column string) bool

Check if a filter exists in the list of filters.

func (Filters) Len

func (f Filters) Len() int

func (Filters) Query

func (f Filters) Query(and bool) (string, []interface{})

Returns a string with the query and a list of values to be used in the query.

func (Filters) Remove

func (f Filters) Remove(column string) Filters

Remove a filter from the list of filters.

type Migration

type Migration struct {
	Database  *Database
	Tables    []Table
	Models    []Model
	Directory string
}

Migration represents a set of changes to the database

func NewMigration

func NewMigration(db *Database) *Migration

Initialize a new migration

func (*Migration) CreateFromModels

func (m *Migration) CreateFromModels(models []Model)

Create a migration from models.

func (Migration) GetLatestMigration

func (m Migration) GetLatestMigration() (Migration, error)

Read the latest migration from the file system

func (Migration) Run

func (m Migration) Run() error

Execute a migration

func (Migration) Validate

func (m Migration) Validate(other Migration) ([]Table, []Column, []Relation, []Column, []Table, []Column, []Relation)

Validate a migration This is used to make sure all fields are the same, if not, we can ALTER the fields on the database side.

func (Migration) Write

func (m Migration) Write() error

Write a migration to the file system

type Model

type Model interface {
	TableName() string
}

Model interface

func NewModel

func NewModel(model Model) Model

Get a new model struct from an existing model struct

func ScanRow

func ScanRow(row *sql.Row, model Model, include []string) (Model, error)

Scan a row into a model

type ModelSet

type ModelSet []Model

ModelSet is a client-side representation of a queryset. Allows limited filtering.

func ScanRows

func ScanRows(rows *sql.Rows, model Model, include []string) ModelSet

Scan rows into models, put those into a ModelSet

func (ModelSet) Filter

func (ms ModelSet) Filter(args []string) ModelSet

Filter a modelset, returns a new modelset. Example:

qs.Filter("name=John,Paul")
qs.Filter("age=18,19,20")

Better to use on smaller sets, less than 1000. Otherwise use the Database.Filter() method.

func (ModelSet) Len

func (ms ModelSet) Len() int

Len returns the number of models in the ModelSet.

func (ModelSet) String

func (ms ModelSet) String() string

String returns a string representation of the ModelSet.

func (ModelSet) Values

func (ms ModelSet) Values(exclude ...string) []map[string]any

Return a slice of slices of values.

type ModelTags

type ModelTags map[string]string

ModelTags is a map of tags for a model.

func TagMap

func TagMap(field reflect.StructField) ModelTags

Generate a map from the list of [Key:Value, Key:Value, ...] pairs.

func (ModelTags) Auto

func (t ModelTags) Auto() bool

Auto is a special tag that indicates that the column is auto-incrementing.

func (ModelTags) Default

func (t ModelTags) Default() string

Default is a special tag that indicates that the column has a default value. This default value is however very limited, and can only be set in the model tags.

func (ModelTags) Get

func (t ModelTags) Get(key string) string

Get a tag value.

func (ModelTags) Has

func (t ModelTags) Has(key string) bool

Check if tag exists.

func (ModelTags) Index

func (t ModelTags) Index() bool

Verify if column needs an index.

func (ModelTags) Length

func (t ModelTags) Length() int

Get the length of a column.

func (ModelTags) Nullable

func (t ModelTags) Nullable() bool

Verify if column is nullable.

func (ModelTags) Primary

func (t ModelTags) Primary() bool

Verify if column is a primary key.

func (ModelTags) Raw

func (t ModelTags) Raw() string

Used for annotating your type tags with raw sql. Example:

type User struct {
    ID int `simpledb:"RAW: NOT NULL AUTO_INCREMENT PRIMARY"`
}

func (ModelTags) RelType

func (t ModelTags) RelType() string

Get the relation type from the tag.

func (ModelTags) Set

func (t ModelTags) Set(key string, value string)

Set a tag value.

func (ModelTags) ToColumn

func (t ModelTags) ToColumn(tname, name, typ string) Column

Convert tag map to a column used for migrations.

func (ModelTags) Type

func (t ModelTags) Type() string

Get the column type from the tag.

func (ModelTags) Unique

func (t ModelTags) Unique() bool

Verify if column is unique.

type QuerySet

type QuerySet struct {
	Statements []string

	Filters Filters
	Q       string

	Model    Model
	OFFSET   int
	LIMIT    int
	PAGESIZE int
	// contains filtered or unexported fields
}

Queryset is a struct that handles generating SQL queries

func NewQuerySet

func NewQuerySet(db *Database, model ...Model) *QuerySet

Initialize the QuerySet

func (*QuerySet) Add

func (q *QuerySet) Add(statement string) *QuerySet

Add SQL statement to the QuerySet

func (*QuerySet) AddFiters

func (q *QuerySet) AddFiters(filters Filters) *QuerySet

Add filters to apply in the where clause at the end of a query

func (*QuerySet) All

func (q *QuerySet) All() *QuerySet

Get all models from the table

func (*QuerySet) Clear

func (q *QuerySet) Clear() *QuerySet

Clear the QuerySet

func (*QuerySet) Count

func (q *QuerySet) Count() *QuerySet

Count all models in the table

func (*QuerySet) Exec

func (q *QuerySet) Exec() (*sql.Rows, error)

Execute the query and return the results

func (*QuerySet) ExecOne

func (q *QuerySet) ExecOne() (*sql.Row, error)

Execute the query and return the results

func (*QuerySet) ExecRow

func (q *QuerySet) ExecRow() (*sql.Row, error)

Execute the query and return the results

func (*QuerySet) From

func (q *QuerySet) From(table ...string) *QuerySet

From sets the table to query from

func (*QuerySet) Get

func (q *QuerySet) Get(values ...int) *QuerySet

Get a single model from the database

func (*QuerySet) GroupBy

func (q *QuerySet) GroupBy(columns ...string) *QuerySet

Group by a column

func (*QuerySet) Join

func (q *QuerySet) Join(table string, column string, value any, op string) *QuerySet

Join a table to the query

func (*QuerySet) Limit

func (q *QuerySet) Limit(limit int) *QuerySet

Limit the number of results returned

func (*QuerySet) MultiModel

func (q *QuerySet) MultiModel(model ...Model) ModelSet

Execute the query and return the results as a ModelSet

func (*QuerySet) Offset

func (q *QuerySet) Offset(offset int) *QuerySet

Offset the results returned

func (*QuerySet) OrderBy

func (q *QuerySet) OrderBy(column string, order string) *QuerySet

OrderBy sets the order of the query

func (*QuerySet) Page

func (q *QuerySet) Page(page int) ModelSet

Paginate the results

func (*QuerySet) Query

func (q *QuerySet) Query() (string, []interface{})

Generate the SQL query and values to be passed to the database

func (*QuerySet) Raw

func (q *QuerySet) Raw(sql string) (string, []any)

Enter raw SQL into the end of the query Returns the sql query, and the values to be passed to the database

func (*QuerySet) Select

func (q *QuerySet) Select(columns ...string) *QuerySet

Select specific columns from the table

func (*QuerySet) SingleModel

func (q *QuerySet) SingleModel(model ...Model) (Model, error)

Execute the query and return the results as a Model

func (*QuerySet) Where

func (q *QuerySet) Where(column string, op string, value any) *QuerySet

Where adds a where clause to end of the query

type Relation

type Relation struct {
	From string
	To   string
	Type DBType
}

Represents a relation between two tables.

func MigrationRelations

func MigrationRelations(model Model) []Relation

Get the related fields for migrating a model.

type Table

type Table struct {
	Name      string
	Columns   []Column
	Relations []Relation
}

Table representation, used to create tables when migrating

func ModelToTable

func ModelToTable(model Model) Table

Convert a model to a table. Used for migrations

func (Table) String

func (t Table) String() string

Generate a query for the table

Jump to

Keyboard shortcuts

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