Documentation
¶
Overview ¶
Package go-sql is an SQL library that adds Higher Level capabilities to the standard `database/sql` library.
Usage ¶
Example:
package main
import (
"github.com/gildas/g-logger"
"github.com/gildas/g-sql"
)
type Person struct {
ID string `json:"id" sql:"key"`
Lastname string `json:"lastName" sql:"index,varchar(80)"`
Firstname string `json:"firstName" sql:"index,varchar(80)"`
Age int `json:"age"`
NotNeeded int ` sql:"-"`
}
func main() {
db, err := sql.Open("postgres", "connectionstring", logger.Create("MYAPP"))
if err != nil {
panic(err)
}
defer db.Close()
// Create the SQL table "person" after the type Person
err = db.CreateTable(Person{})
// Insert some data
err = db.Insert(Person{"1234", "Doe", "John", 34, 314})
err = db.Insert(Person{"4567", "Doe", "Jane", 15, 314})
// Find data!
results, err := db.FindAll(Person{}, sql.Queries{}.Add("lastname", "Doe"))
for _, result := range results {
if person, ok := result.(*Person); ok {
fmt.Printf("%s %s, age=%d\n", person.Lastname, person.Firstname, person.Age)
}
}
// Find Single data
result, err := db.Find(Person{}, sql.Queries{}.Add("lastname", "Doe").Add("age", sql.QueryGreater, 18))
fmt.Printf("%s %s, age=%d\n", person.Lastname, person.Firstname, person.Age)
// Update data
err := suite.DB.UpdateAll(Person{}, sql.Queries{}.Add("age", 18).Add("age", sql.QuerySet, 25))
// Delete data
err := suite.DB.DeleteAll(Person{}, sql.Queries{}.Add("age", sql.QueryGreater, 50))
// Drop the table
err := suite.DB.DeleteTable(Person{})
}
For the sake of readability, I removed the error management. DON'T!
As you can see, using actual GO struct types is rather easy now. We do not support the entire set of SQL types or GO types, but we have the basics.
We also support time.Time, `uuid.UUID` from https://pkg.go.dev/github.com/google/uuid, pointers for simple types, and foreign keys, this is how you would use these:
import "github.com/google/uuid"
type Manager struct {
ID uuid.UUID `sql:"key"`
Name string
}
type TeamMember struct {
ID uuid.UUID `sql:"key"`
Manager *Manager `sql:foreign=ID"`
Joined time.Time
Shift time.Duration
WeekStart *time.Weekday
}
Note that for the foreign keys to work, - The target field must be a pointer to a struct, - the target `struct` must implement the database/sql Scanner (https://pkg.go.dev/database/sql?tab=doc#Scanner) interface, - the target `struct` key must be a uuid.UUID, string, or int (any type of int)
You can also use the Statement object level of using the Database:
package main
import (
"github.com/gildas/g-logger"
"github.com/gildas/g-sql"
)
func main() {
db, err := sql.Open("postgres", "connectionstring", logger.Create("MYAPP"))
if err != nil {
panic(err)
}
defer db.Close()
// Insert some data
statement, parms = sql.InsertStatement{}.With(db).Build("person", nil, sql.Queries{}.Add("lastname", "Doe").Add("age", 34))
_, err := db.Exec(statement, parms...)
// Find data!
statement, parms = sql.SelectStatement{}.With(db).Build("person", []string("id", "age"), sql.Queries{}.Add("lastname", "Doe"))
rows, err := db.Query(statement, parms...)
// Then, scan the rows as usual from "database/sql"
// Update data
statement, parms = sql.UpdateStatement{}.With(db).Build("person", nil, sql.Queries{}.Add("lastname", "Doe").Add("age", sql.QuerySet, 25))
_, err := db.Exec(statement, parms...)
// Delete data
statement, parms = sqlDeleteStatement{}.With(db).Build("person", nil, sql.Queries{}.Add("age", sql.Greater, 50))
_, err := db.Exec(statement, parms...)
}
Index ¶
- Variables
- type DB
- func (db *DB) Close() error
- func (db *DB) CreateTable(schema interface{}) error
- func (db *DB) DeleteAll(schema interface{}, queries Queries) error
- func (db *DB) DeleteTable(schema interface{}) error
- func (db *DB) Exec(query string, args ...interface{}) (gosql.Result, error)
- func (db *DB) ExecContext(ctx context.Context, query string, args ...interface{}) (gosql.Result, error)
- func (db *DB) Find(schema interface{}, queries Queries) (interface{}, error)
- func (db *DB) FindAll(schema interface{}, queries Queries) ([]interface{}, error)
- func (db *DB) HttpHandler() func(http.Handler) http.Handler
- func (db *DB) Insert(blob interface{}) error
- func (db DB) Ping() error
- func (db *DB) Query(query string, args ...interface{}) (*gosql.Rows, error)
- func (db *DB) QueryContext(ctx context.Context, query string, args ...interface{}) (*gosql.Rows, error)
- func (db *DB) QueryRow(query string, args ...interface{}) *gosql.Row
- func (db *DB) QueryRowContext(ctx context.Context, query string, args ...interface{}) *gosql.Row
- func (db *DB) ToContext(parent context.Context) context.Context
- func (db *DB) UpdateAll(schema interface{}, queries Queries) error
- type DBTime
- type DeleteStatement
- type InsertStatement
- type Queries
- type Query
- type QueryOperator
- type SelectStatement
- type Statement
- type UpdateStatement
Constants ¶
This section is empty.
Variables ¶
var ( QueryBetween = QueryOperator{"BETWEEN", 3} QueryDifferent = QueryOperator{"<>", 2} QueryEqual = QueryOperator{"=", 2} QueryGreater = QueryOperator{">", 2} QueryGreaterOrEqual = QueryOperator{">=", 2} QueryIn = QueryOperator{"IN", math.MaxInt32} QueryLesser = QueryOperator{"<", 2} QueryLesserOrEqual = QueryOperator{"<=", 2} QueryLike = QueryOperator{"LIKE", 2} QuerySet = QueryOperator{"SET", 2} )
var VERSION = "0.0.3" + commit
VERSION is the version of this application
Functions ¶
This section is empty.
Types ¶
type DB ¶
func FromContext ¶
FromContext retrieves a DB stored in the given context
func Open ¶
Open opens a database specified by its database driver name and a driver-specific data source name, usually consisting of at least a database name and connection information.
Most users will open a database via a driver-specific connection helper function that returns a *DB. No database drivers are included in the Go standard library. See https://golang.org/s/sqldrivers for a list of third-party drivers.
Open may just validate its arguments without creating a connection to the database. To verify that the data source name is valid, call Ping.
The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once. It is rarely necessary to close a DB.
func (*DB) Close ¶
Close closes the database and prevents new queries from starting. Close then waits for all queries that have started processing on the server to finish.
It is rare to Close a DB, as the DB handle is meant to be long-lived and shared between many goroutines.
func (*DB) CreateTable ¶
CreateTable creates an SQL Table from a schema
func (*DB) DeleteTable ¶
DeleteTable deletes (drops) the SQL table that represents the schema
func (*DB) Exec ¶
Exec executes a query without returning any rows. The args are for any placeholder parameters in the query
func (*DB) ExecContext ¶
func (db *DB) ExecContext(ctx context.Context, query string, args ...interface{}) (gosql.Result, error)
Exec executes a query without returning any rows. The args are for any placeholder parameters in the query
func (*DB) HttpHandler ¶
HttpHandler wraps a DB in an http middleware Handler
func (DB) Ping ¶
Ping verifies a connection to the database is still alive, establishing a connection if necessary
func (*DB) Query ¶
Query executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query
func (*DB) QueryContext ¶
func (db *DB) QueryContext(ctx context.Context, query string, args ...interface{}) (*gosql.Rows, error)
Query executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query
func (*DB) QueryRow ¶
QueryRow executes a query that is expected to return at most one row. QueryRow always returns a non-nil value. Errors are deferred until Row's Scan method is called. If the query selects no rows, the *Row's Scan will return ErrNoRows. Otherwise, the *Row's Scan scans the first selected row and discards the rest
func (*DB) QueryRowContext ¶
QueryRowContext executes a query that is expected to return at most one row. QueryRowContext always returns a non-nil value. Errors are deferred until Row's Scan method is called. If the query selects no rows, the *Row's Scan will return ErrNoRows. Otherwise, the *Row's Scan scans the first selected row and discards the rest
type DeleteStatement ¶
func (DeleteStatement) Build ¶
func (statement DeleteStatement) Build(table string, columns []string, queries Queries) (string, []interface{})
Build builds the statement to be executed by the DB
func (DeleteStatement) With ¶
func (statement DeleteStatement) With(db *DB) Statement
type InsertStatement ¶
func (InsertStatement) Build ¶
func (statement InsertStatement) Build(table string, columns []string, queries Queries) (string, []interface{})
Build builds the statement to be executed by the DB
func (InsertStatement) With ¶
func (statement InsertStatement) With(db *DB) Statement
type Queries ¶
Queries describes a map of Query objects
func QueriesFromRequest ¶
QueriesFromRequest creates a Queries from an HTTP Request
func QueriesFromURL ¶
QueriesFromURL creates Queries from a URL (from its query part)
func (Queries) Add ¶
Add adds a new Query
If the key is already present, values are added If no values are given, the Queries is unchanged
func (Queries) WhereClause ¶
WhereClause builds the SQL Where Clause for a Statement
type QueryOperator ¶
QueryOperator describes the operator used to build
func (QueryOperator) String ¶
func (operator QueryOperator) String() string
String returns a string representation of the operator
type SelectStatement ¶
func (SelectStatement) Build ¶
func (statement SelectStatement) Build(table string, columns []string, queries Queries) (string, []interface{})
Build builds the statement to be executed by the DB
func (SelectStatement) With ¶
func (statement SelectStatement) With(db *DB) Statement
type Statement ¶
type Statement interface {
With(db *DB) Statement
Build(table string, columns []string, queries Queries) (string, []interface{})
}
Statement describes stuff that can be Built into a statement string with its parameters
type UpdateStatement ¶
func (UpdateStatement) Build ¶
func (statement UpdateStatement) Build(table string, columns []string, queries Queries) (string, []interface{})
Build builds the statement to be executed by the DB
func (UpdateStatement) With ¶
func (statement UpdateStatement) With(db *DB) Statement