sqlbuilder

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2024 License: MIT Imports: 6 Imported by: 0

README

godoc codecov Go Report Card

go-sqlbuilder - multi-dialect fork of github.com/umisama/go-sqlbuilder

This package is a fork of umisama/go-sqlbuilder which primarily adds the ability to use multiple dialects at the same time with the introduction of a new Builder instance type.

Installation

> go get github.com/go-corelibs/go-sqlbuilder@latest

Examples

Buildable

This example does not include any error checking for brevity.

func main() {

    // connect to a sqlite3 instance
    db, _ := sql.Open("sqlite3", ":memory:")
    defer db.Close()

    // construct a new instance, configured for sqlite usage
    b := sqlbuilder.NewBuildable(dialects.Sqlite)

    // define a new table to work with
    table := sqlbuilder.NewTable(
        "table_name",
        &TableOption{},
        IntColumn("id", &ColumnOption{
            PrimaryKey: true,
        }),
        StringColumn("content", nil),
    )

    // create the newly defined table
    sql, args, _ := b.CreateTable(table).ToSQL()
    // execute the create-table statement
     _, _ = db.Exec(query, args...)

     // insert some rows into the table
     query, args, _ = b.Insert(table).
         Set(table.C("content"), "Hello strange new world")
         ToSQL()
    // execute the insert row statement
     _, _ = db.Exec(query, args...)

    // ... and so on, almost identical to the original
    // package usage, with the exception of using the
    // Buildable instance instead of the package-level
    // functions directly. This allows for multiple
    // Buildable instances, with different dialects,
    // to be used at the same time
}

Go-CoreLibs

Go-CoreLibs is a repository of shared code between the Go-Curses and Go-Enjin projects.

License

Copyright 2024 The Go-CoreLibs Authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use file except in compliance with the License.
You may obtain a copy of the license at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Documentation

Overview

Package sqlbuilder is a SQL-query builder for golang. This supports you using relational database with more readable and flexible code than raw SQL query string.

See https://github.com/go-corelibs/go-sqlbuilder for more infomation.

Example
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
	fmt.Println(err.Error())
	return
}

// Set dialect first
// dialects are in github.com/go-corelibs/go-sqlbuilder/dialects
SetDialect(TestDialect{})

// Define a table
tbl_person := NewTable(
	"PERSON",
	&TableOption{},
	IntColumn("id", &ColumnOption{
		PrimaryKey: true,
	}),
	StringColumn("name", &ColumnOption{
		Unique:  true,
		Size:    255,
		Default: "no_name",
	}),
	DateColumn("birth", nil),
)

// Create Table
query, args, err := CreateTable(tbl_person).ToSql()
if err != nil {
	fmt.Println(err.Error())
	return
}
_, err = db.Exec(query, args...)
if err != nil {
	fmt.Println(err.Error())
	return
}

// Insert data
// (Table).C function returns a column object.
query, args, err = Insert(tbl_person).
	Set(tbl_person.C("name"), "Kurisu Makise").
	Set(tbl_person.C("birth"), time.Date(1992, time.July, 25, 0, 0, 0, 0, time.UTC)).
	ToSql()
_, err = db.Exec(query, args...)
if err != nil {
	fmt.Println(err.Error())
	return
}

// Query
var birth time.Time
query, args, err = Select(tbl_person).Columns(
	tbl_person.C("birth"),
).Where(
	tbl_person.C("name").Eq("Kurisu Makise"),
).ToSql()
err = db.QueryRow(query, args...).Scan(&birth)
if err != nil {
	fmt.Println(err.Error())
	return
}
fmt.Printf("Kurisu's birthday is %s,%d %d", birth.Month().String(), birth.Day(), birth.Year())
Output:

Kurisu's birthday is July,25 1992

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetDialect

func SetDialect(opt Dialect)

SetDialect sets dialect for SQL server. Must set dialect at first.

Types

type AlterTableBuilder

type AlterTableBuilder interface {
	RenameTo(name string) AlterTableBuilder
	AddColumn(col ColumnConfig) AlterTableBuilder
	AddColumnAfter(col ColumnConfig, after Column) AlterTableBuilder
	AddColumnFirst(col ColumnConfig) AlterTableBuilder
	DropColumn(col Column) AlterTableBuilder
	ChangeColumn(old_column Column, new_column ColumnConfig) AlterTableBuilder
	ChangeColumnAfter(old_column Column, new_column ColumnConfig, after Column) AlterTableBuilder
	ChangeColumnFirst(old_column Column, new_column ColumnConfig) AlterTableBuilder
	ToSql() (query string, args []interface{}, err error)
	ApplyToTable() error
	// contains filtered or unexported methods
}

AlterTableBuilder is the Buildable interface wrapping of AlterTable

func AlterTable

func AlterTable(tbl Table) AlterTableBuilder

type AlterTableStatement

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

func (*AlterTableStatement) AddColumn

func (*AlterTableStatement) AddColumnAfter

func (b *AlterTableStatement) AddColumnAfter(col ColumnConfig, after Column) AlterTableBuilder

func (*AlterTableStatement) AddColumnFirst

func (b *AlterTableStatement) AddColumnFirst(col ColumnConfig) AlterTableBuilder

func (*AlterTableStatement) ApplyToTable

func (b *AlterTableStatement) ApplyToTable() error

func (*AlterTableStatement) ChangeColumn

func (b *AlterTableStatement) ChangeColumn(old_column Column, new_column ColumnConfig) AlterTableBuilder

func (*AlterTableStatement) ChangeColumnAfter

func (b *AlterTableStatement) ChangeColumnAfter(old_column Column, new_column ColumnConfig, after Column) AlterTableBuilder

func (*AlterTableStatement) ChangeColumnFirst

func (b *AlterTableStatement) ChangeColumnFirst(old_column Column, new_column ColumnConfig) AlterTableBuilder

func (*AlterTableStatement) DropColumn

func (b *AlterTableStatement) DropColumn(col Column) AlterTableBuilder

func (*AlterTableStatement) RenameTo

func (b *AlterTableStatement) RenameTo(name string) AlterTableBuilder

func (*AlterTableStatement) ToSql

func (b *AlterTableStatement) ToSql() (query string, args []interface{}, err error)

type Buildable

type Buildable interface {
	AlterTable(tbl Table) AlterTableBuilder
	CreateTable(tbl Table) CreateTableBuilder
	CreateIndex(tbl Table) CreateIndexBuilder
	Delete(from Table) DeleteBuilder
	Insert(into Table) InsertBuilder
	Select(from Table) SelectBuilder
}

Buildable is an interface for performing the package-level functions which all require a package-level Dialect to be configured using a call to SetDialect. Buildable allows for using one or more independent Dialects at the same time within the same codebase.

func NewBuildable

func NewBuildable(d Dialect) Buildable

NewBuildable constructs a new Buildable instance, configured with the given Dialect

type Column

type Column interface {

	// As creates Column alias.
	As(alias string) Column

	// Eq creates Condition for "column==right".  Type for right is column's one or other Column.
	Eq(right interface{}) Condition

	// NotEq creates Condition for "column<>right".  Type for right is column's one or other Column.
	NotEq(right interface{}) Condition

	// GtEq creates Condition for "column>right".  Type for right is column's one or other Column.
	Gt(right interface{}) Condition

	// GtEq creates Condition for "column>=right".  Type for right is column's one or other Column.
	GtEq(right interface{}) Condition

	// Lt creates Condition for "column<right".  Type for right is column's one or other Column.
	Lt(right interface{}) Condition

	// LtEq creates Condition for "column<=right".  Type for right is column's one or other Column.
	LtEq(right interface{}) Condition

	// Like creates Condition for "column LIKE right".  Type for right is column's one or other Column.
	Like(right string) Condition

	// Between creates Condition for "column BETWEEN lower AND higher".  Type for lower/higher is int or time.Time.
	Between(lower, higher interface{}) Condition

	// In creates Condition for "column IN (values[0], values[1] ...)".  Type for values is column's one or other Column.
	In(values ...interface{}) Condition
	// contains filtered or unexported methods
}

Column represents a table column.

var Star Column = &columnImpl{nil, nil}

Star reprecents * column.

type ColumnConfig

type ColumnConfig interface {
	Name() string
	Type() ColumnType
	Option() *ColumnOption
	// contains filtered or unexported methods
}

ColumnConfig represents a config for table's column. This has a name, data type and some options.

func AnyColumn

func AnyColumn(name string, opt *ColumnOption) ColumnConfig

AnyColumn creates config for any types.

func BoolColumn

func BoolColumn(name string, opt *ColumnOption) ColumnConfig

BoolColumn creates config for BOOLEAN type column.

func BytesColumn

func BytesColumn(name string, opt *ColumnOption) ColumnConfig

BytesColumn creates config for BLOB type column.

func DateColumn

func DateColumn(name string, opt *ColumnOption) ColumnConfig

DateColumn creates config for DATETIME type column.

func FloatColumn

func FloatColumn(name string, opt *ColumnOption) ColumnConfig

FloatColumn creates config for REAL or FLOAT type column.

func IntColumn

func IntColumn(name string, opt *ColumnOption) ColumnConfig

IntColumn creates config for INTEGER type column.

func StringColumn

func StringColumn(name string, opt *ColumnOption) ColumnConfig

StringColumn creates config for TEXT or VARCHAR type column.

type ColumnList

type ColumnList []Column

ColumnList represents list of Column.

type ColumnOption

type ColumnOption struct {
	PrimaryKey    bool
	NotNull       bool
	Unique        bool
	AutoIncrement bool
	Size          int
	SqlType       string
	Default       interface{}
}

ColumnOption represents option for a column. ex: primary key.

type ColumnType

type ColumnType int

ColumnType reprecents a type of column. Dialects handle this for know column options.

const (
	ColumnTypeAny ColumnType = iota
	ColumnTypeInt
	ColumnTypeString
	ColumnTypeDate
	ColumnTypeFloat
	ColumnTypeBool
	ColumnTypeBytes
)

func (ColumnType) CapableTypes

func (t ColumnType) CapableTypes() []reflect.Type

func (ColumnType) String

func (t ColumnType) String() string

type Condition

type Condition interface {
	// contains filtered or unexported methods
}

Condition represents a condition for WHERE clause and other.

func And

func And(conds ...Condition) Condition

And creates a combined condition with "AND" operator.

func Or

func Or(conds ...Condition) Condition

And creates a combined condition with "OR" operator.

type CreateIndexBuilder

type CreateIndexBuilder interface {
	IfNotExists() CreateIndexBuilder
	Columns(columns ...Column) CreateIndexBuilder
	Name(name string) CreateIndexBuilder
	ToSql() (query string, args []interface{}, err error)
	// contains filtered or unexported methods
}

CreateIndexBuilder is the Buildable interface wrapping of CreateTable

func CreateIndex

func CreateIndex(tbl Table) CreateIndexBuilder

CreateIndex returns new "CREATE INDEX" statement. The table is Table object to create index.

type CreateIndexStatement

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

CreateIndexStatement represents a "CREATE INDEX" statement.

func (*CreateIndexStatement) Columns

func (b *CreateIndexStatement) Columns(columns ...Column) CreateIndexBuilder

IfNotExists sets "IF NOT EXISTS" clause. If not set this, returns error on ToSql().

func (*CreateIndexStatement) IfNotExists

func (b *CreateIndexStatement) IfNotExists() CreateIndexBuilder

IfNotExists sets "IF NOT EXISTS" clause.

func (*CreateIndexStatement) Name

Name sets name for index. If not set this, auto generated name will be used.

func (*CreateIndexStatement) ToSql

func (b *CreateIndexStatement) ToSql() (query string, args []interface{}, err error)

ToSql generates query string, placeholder arguments, and returns err on errors.

type CreateTableBuilder

type CreateTableBuilder interface {
	IfNotExists() CreateTableBuilder
	ToSql() (query string, args []interface{}, err error)
	// contains filtered or unexported methods
}

CreateTableBuilder is the Buildable interface wrapping of CreateIndex

func CreateTable

func CreateTable(tbl Table) CreateTableBuilder

CreateTable returns new "CREATE TABLE" statement. The table is Table object to create.

type CreateTableStatement

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

CreateTableStatement represents a "CREATE TABLE" statement.

func (*CreateTableStatement) IfNotExists

func (b *CreateTableStatement) IfNotExists() CreateTableBuilder

IfNotExists sets "IF NOT EXISTS" clause.

func (*CreateTableStatement) ToSql

func (b *CreateTableStatement) ToSql() (query string, args []interface{}, err error)

ToSql generates query string, placeholder arguments, and error.

type DeleteBuilder

type DeleteBuilder interface {
	Where(cond Condition) DeleteBuilder
	ToSql() (query string, args []interface{}, err error)
	// contains filtered or unexported methods
}

DeleteBuilder is the Buildable interface wrapping of Delete

func Delete

func Delete(from Table) DeleteBuilder

Delete returns new DELETE statement. The table is Table object to delete from.

type DeleteStatement

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

DeleteStatement represents a DELETE statement.

func (*DeleteStatement) ToSql

func (b *DeleteStatement) ToSql() (query string, args []interface{}, err error)

ToSql generates query string, placeholder arguments, and returns err on errors.

func (*DeleteStatement) Where

func (b *DeleteStatement) Where(cond Condition) DeleteBuilder

Where sets WHERE clause. cond is filter condition.

type Dialect

type Dialect interface {
	QuerySuffix() string
	BindVar(i int) string
	QuoteField(field interface{}) string
	ColumnTypeToString(ColumnConfig) (string, error)
	ColumnOptionToString(*ColumnOption) (string, error)
	TableOptionToString(*TableOption) (string, error)
}

Dialect encapsulates behaviors that differ across SQL database.

type DropTableStatement

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

DropTableStatement represents a "DROP TABLE" statement.

func (*DropTableStatement) ToSql

func (b *DropTableStatement) ToSql() (query string, args []interface{}, err error)

ToSql generates query string, placeholder arguments, and returns err on errors.

type IDropTableStatement

type IDropTableStatement interface {
	ToSql() (query string, args []interface{}, err error)
	// contains filtered or unexported methods
}

IDropTableStatement is the Buildable interface wrapping of DeleteTable

func DropTable

func DropTable(tbl Table) IDropTableStatement

DropTable returns new "DROP TABLE" statement. The table is Table object to drop.

type IUpdateStatement

type IUpdateStatement interface {
	Set(col Column, val interface{}) IUpdateStatement
	Where(cond Condition) IUpdateStatement
	Limit(limit int) IUpdateStatement
	Offset(offset int) IUpdateStatement
	OrderBy(desc bool, columns ...Column) IUpdateStatement
	ToSql() (query string, args []interface{}, err error)
	// contains filtered or unexported methods
}

IUpdateStatement is the Buildable interface wrapping of Update

func Update

func Update(tbl Table) IUpdateStatement

Update returns new UPDATE statement. The table is Table object to update.

type InsertBuilder

type InsertBuilder interface {
	Columns(columns ...Column) InsertBuilder
	Values(values ...interface{}) InsertBuilder
	Set(column Column, value interface{}) InsertBuilder
	ToSql() (query string, args []interface{}, err error)
	// contains filtered or unexported methods
}

InsertBuilder is the Buildable interface wrapping of Insert

func Insert

func Insert(into Table) InsertBuilder

Insert returns new INSERT statement. The table is Table object for into.

type InsertStatement

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

InsertStatement represents a INSERT statement.

func (*InsertStatement) Columns

func (b *InsertStatement) Columns(columns ...Column) InsertBuilder

Columns sets columns for insert. This overwrite old results of Columns() or Set(). If not set this, get error on ToSql().

func (*InsertStatement) Set

func (b *InsertStatement) Set(column Column, value interface{}) InsertBuilder

Set sets the column and value togeter. Set cannot be called with Columns() or Values() in a statement.

func (*InsertStatement) ToSql

func (b *InsertStatement) ToSql() (query string, args []interface{}, err error)

ToSql generates query string, placeholder arguments, and returns err on errors.

func (*InsertStatement) Values

func (b *InsertStatement) Values(values ...interface{}) InsertBuilder

Values sets VALUES clause. This overwrite old results of Values() or Set().

type SelectBuilder

type SelectBuilder interface {
	Columns(columns ...Column) SelectBuilder
	Where(cond Condition) SelectBuilder
	Distinct() SelectBuilder
	GroupBy(columns ...Column) SelectBuilder
	Having(cond Condition) SelectBuilder
	OrderBy(desc bool, columns ...Column) SelectBuilder
	Limit(limit int) SelectBuilder
	Offset(offset int) SelectBuilder
	ToSql() (query string, args []interface{}, err error)
	ToSubquery(alias string) Table
	// contains filtered or unexported methods
}

SelectBuilder is the Buildable interface wrapping of Select

func Select

func Select(from Table) SelectBuilder

Select returns new SELECT statement with from as FROM clause.

type SelectStatement

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

SelectStatement represents a SELECT statement.

func (*SelectStatement) Columns

func (b *SelectStatement) Columns(columns ...Column) SelectBuilder

Columns set columns for select. Get all columns (use *) if it is not setted.

func (*SelectStatement) Distinct

func (b *SelectStatement) Distinct() SelectBuilder

Distinct sets DISTINCT clause.

func (*SelectStatement) GroupBy

func (b *SelectStatement) GroupBy(columns ...Column) SelectBuilder

GroupBy sets "GROUP BY" clause by the columns.

func (*SelectStatement) Having

func (b *SelectStatement) Having(cond Condition) SelectBuilder

GroupBy sets "HAVING" clause with the cond.

func (*SelectStatement) Limit

func (b *SelectStatement) Limit(limit int) SelectBuilder

Limit sets LIMIT clause.

func (*SelectStatement) Offset

func (b *SelectStatement) Offset(offset int) SelectBuilder

Offset sets OFFSET clause.

func (*SelectStatement) OrderBy

func (b *SelectStatement) OrderBy(desc bool, columns ...Column) SelectBuilder

OrderBy sets "ORDER BY" clause. Use descending order if the desc is true, by the columns.

func (*SelectStatement) ToSql

func (b *SelectStatement) ToSql() (query string, args []interface{}, err error)

ToSql generates query string, placeholder arguments, and returns err on errors.

func (*SelectStatement) ToSubquery

func (m *SelectStatement) ToSubquery(alias string) Table

func (*SelectStatement) Where

func (b *SelectStatement) Where(cond Condition) SelectBuilder

Where sets WHERE clause. The cond is filter condition.

type SqlFunc

type SqlFunc interface {
	Column
	// contains filtered or unexported methods
}

SqlFunc represents function on SQL(ex:count(*)). This can be use in the same way as Column.

func Func

func Func(name string, args ...Column) SqlFunc

Func returns new SQL function. The name is function name, and the args is arguments of function

type Statement

type Statement interface {
	ToSql() (query string, attrs []interface{}, err error)
}

Statement reprecents a statement(SELECT/INSERT/UPDATE and other)

type Table

type Table interface {

	// C returns table's column by the name.
	C(name string) Column

	// Name returns table' name.
	// returns empty if it is joined table or subquery.
	Name() string

	// Option returns table's option(table constraint).
	// returns nil if it is joined table or subquery.
	Option() *TableOption

	// Columns returns all columns.
	Columns() []Column

	// InnerJoin returns a joined table use with "INNER JOIN" clause.
	// The joined table can be handled in same way as single table.
	InnerJoin(Table, Condition) Table

	// LeftOuterJoin returns a joined table use with "LEFT OUTER JOIN" clause.
	// The joined table can be handled in same way as single table.
	LeftOuterJoin(Table, Condition) Table

	// RightOuterJoin returns a joined table use with "RIGHT OUTER JOIN" clause.
	// The joined table can be handled in same way as single table.
	RightOuterJoin(Table, Condition) Table

	// FullOuterJoin returns a joined table use with "FULL OUTER JOIN" clause.
	// The joined table can be handled in same way as single table.
	FullOuterJoin(Table, Condition) Table
	// contains filtered or unexported methods
}

Table represents a table.

func NewTable

func NewTable(name string, option *TableOption, column_configs ...ColumnConfig) Table

NewTable returns a new table named by the name. Specify table columns by the column_config. Panic if column is empty.

type TableOption

type TableOption struct {
	Unique [][]string
}

TableOption reprecents constraint of a table.

type UpdateStatement

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

UpdateStatement represents a UPDATE statement.

func (*UpdateStatement) Limit

func (b *UpdateStatement) Limit(limit int) IUpdateStatement

Limit sets LIMIT clause.

func (*UpdateStatement) Offset

func (b *UpdateStatement) Offset(offset int) IUpdateStatement

Limit sets OFFSET clause.

func (*UpdateStatement) OrderBy

func (b *UpdateStatement) OrderBy(desc bool, columns ...Column) IUpdateStatement

OrderBy sets "ORDER BY" clause. Use descending order if the desc is true, by the columns.

func (*UpdateStatement) Set

func (b *UpdateStatement) Set(col Column, val interface{}) IUpdateStatement

Set sets SETS clause like col=val. Call many time for update multi columns.

func (*UpdateStatement) ToSql

func (b *UpdateStatement) ToSql() (query string, args []interface{}, err error)

ToSql generates query string, placeholder arguments, and returns err on errors.

func (*UpdateStatement) Where

Where sets WHERE clause. The cond is filter condition.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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