sql

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Mar 31, 2020 License: MIT Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-sql

GoDoc go-sql is an SQL library that adds Higher Level capabilities to the standard database/sql library.

master Build Status Tests coverage
dev Build Status Tests coverage

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, 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 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...)
}

TODO

There is still a lot to do....

  • Support for 'NULL'able columns, until now all columns have to be non null,
  • It would be nice to not force the target struct of a foreign key to impletement the Scanner interface,

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

Constants

This section is empty.

Variables

View Source
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}
)
View Source
var VERSION = "0.0.3" + commit

VERSION is the version of this application

Functions

This section is empty.

Types

type DB

type DB struct {
	Logger *logger.Logger
	// contains filtered or unexported fields
}

func FromContext

func FromContext(context context.Context) (*DB, error)

FromContext retrieves a DB stored in the given context

func Must

func Must(db *DB, err error) *DB

Must returns the given DB or panics upon error

func Open

func Open(drivername string, datasourceName string, l *logger.Logger) (db *DB, err error)

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

func (db *DB) Close() error

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

func (db *DB) CreateTable(schema interface{}) error

CreateTable creates an SQL Table from a schema

func (*DB) DeleteAll

func (db *DB) DeleteAll(schema interface{}, queries Queries) error

DeleteAll deletes all objects of a schema that satisfy the queries

func (*DB) DeleteTable

func (db *DB) DeleteTable(schema interface{}) error

DeleteTable deletes (drops) the SQL table that represents the schema

func (*DB) Exec

func (db *DB) Exec(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) 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) Find

func (db *DB) Find(schema interface{}, queries Queries) (interface{}, error)

Find retrieves the first object of a schema that satisfies the queries

func (*DB) FindAll

func (db *DB) FindAll(schema interface{}, queries Queries) ([]interface{}, error)

FindAll retrieves all objects of a schema that satisfy the queries

func (*DB) HttpHandler

func (db *DB) HttpHandler() func(http.Handler) http.Handler

HttpHandler wraps a DB in an http middleware Handler

func (*DB) Insert

func (db *DB) Insert(blob interface{}) error

Insert insert a blob in its SQL table

func (DB) Ping

func (db DB) Ping() error

Ping verifies a connection to the database is still alive, establishing a connection if necessary

func (*DB) Query

func (db *DB) Query(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) 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

func (db *DB) QueryRow(query string, args ...interface{}) *gosql.Row

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

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

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

func (*DB) ToContext

func (db *DB) ToContext(parent context.Context) context.Context

ToContext stores db to the given context

func (*DB) UpdateAll

func (db *DB) UpdateAll(schema interface{}, queries Queries) error

UpdateAll updates all objects of a schema that satisfy the queries

type DBTime added in v0.0.2

type DBTime time.Time

func (*DBTime) Scan added in v0.0.2

func (t *DBTime) Scan(blob interface{}) (err error)

type DeleteStatement

type DeleteStatement struct {
	DB     *DB
	Logger *logger.Logger
}

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

type InsertStatement struct {
	DB     *DB
	Logger *logger.Logger
}

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

type Queries map[string]Query

Queries describes a map of Query objects

func QueriesFromRequest

func QueriesFromRequest(r *http.Request) Queries

QueriesFromRequest creates a Queries from an HTTP Request

func QueriesFromURL

func QueriesFromURL(u *url.URL) Queries

QueriesFromURL creates Queries from a URL (from its query part)

func (Queries) Add

func (queries Queries) Add(key string, values ...interface{}) Queries

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

func (queries Queries) WhereClause() (string, []interface{})

WhereClause builds the SQL Where Clause for a Statement

type Query

type Query []interface{}

Query describes a query in a Statement Where Clause

type QueryOperator

type QueryOperator struct {
	Operator string
	Arity    int
}

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

type SelectStatement struct {
	DB     *DB
	Logger *logger.Logger
}

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

type UpdateStatement struct {
	DB     *DB
	Logger *logger.Logger
}

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

Jump to

Keyboard shortcuts

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