Documentation
¶
Index ¶
- Variables
- type ChunkParser
- type Config
- type DB
- func (c DB) Delete(ctx context.Context, table Table, idOrRecord interface{}) error
- func (c DB) Exec(ctx context.Context, query string, params ...interface{}) (rowsAffected int64, _ error)
- func (c DB) Insert(ctx context.Context, table Table, record interface{}) error
- func (c DB) Query(ctx context.Context, records interface{}, query string, params ...interface{}) error
- func (c DB) QueryChunks(ctx context.Context, parser ChunkParser) error
- func (c DB) QueryOne(ctx context.Context, record interface{}, query string, params ...interface{}) error
- func (c DB) Transaction(ctx context.Context, fn func(Provider) error) error
- func (c DB) Update(ctx context.Context, table Table, record interface{}) error
- type DBAdapter
- type Dialect
- type Mock
- func (m Mock) Delete(ctx context.Context, table Table, idOrRecord interface{}) error
- func (m Mock) Exec(ctx context.Context, query string, params ...interface{}) (rowsAffected int64, _ error)
- func (m Mock) Insert(ctx context.Context, table Table, record interface{}) error
- func (m Mock) Query(ctx context.Context, records interface{}, query string, params ...interface{}) error
- func (m Mock) QueryChunks(ctx context.Context, parser ChunkParser) error
- func (m Mock) QueryOne(ctx context.Context, record interface{}, query string, params ...interface{}) error
- func (m Mock) SetFallbackDatabase(db Provider) Mock
- func (m Mock) Transaction(ctx context.Context, fn func(db Provider) error) error
- func (m Mock) Update(ctx context.Context, table Table, record interface{}) error
- type PGXAdapter
- type PGXResult
- type PGXRows
- type PGXTx
- type Provider
- type Result
- type Rows
- type SQLAdapter
- type SQLTx
- type Table
- type Tx
- type TxBeginner
Constants ¶
This section is empty.
Variables ¶
var ErrAbortIteration error = fmt.Errorf("ksql: abort iteration, should only be used inside QueryChunks function")
ErrAbortIteration ...
var ErrRecordNotFound error = errors.Wrap(sql.ErrNoRows, "ksql: the query returned no results")
ErrRecordNotFound ...
Functions ¶
This section is empty.
Types ¶
type ChunkParser ¶
type ChunkParser struct {
// The Query and Params are used together to build a query with
// protection from injection, just like when using the Find function.
Query string
Params []interface{}
ChunkSize int
// This attribute must be a function with the following signature:
//
// `func(chunk []<Record>) error`.
//
// Where the actual Record type should be of a struct
// representing the rows you are expecting to receive.
ForEachChunk interface{}
}
ChunkParser stores the arguments of the QueryChunks function
type Config ¶
type Config struct {
// MaxOpenCons defaults to 1 if not set
MaxOpenConns int
}
Config describes the optional arguments accepted by the ksql.New() function.
func (*Config) SetDefaultValues ¶ added in v1.2.0
func (c *Config) SetDefaultValues()
SetDefaultValues should be called by all adapters to set the default config values if unset.
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB represents the ksql client responsible for interfacing with the "database/sql" package implementing the KissSQL interface `ksql.Provider`.
func NewWithAdapter ¶
NewWithAdapter allows the user to insert a custom implementation of the DBAdapter interface
func (DB) Delete ¶
Delete deletes one record from the database using the ID or IDs defined on the ksql.Table passed as second argument.
For tables with a single ID column you can pass the record to be deleted as a struct, as a map or just pass the ID itself.
For tables with composite keys you must pass the record as a struct or a map so that ksql can read all the composite keys from it.
The examples below should work for both types of tables:
err := c.Delete(ctx, UsersTable, user)
err := c.Delete(ctx, UserPostsTable, map[string]interface{}{
"user_id": user.ID,
"post_id": post.ID,
})
The example below is shorter but will only work for tables with a single primary key:
err := c.Delete(ctx, UsersTable, user.ID)
func (DB) Exec ¶
func (c DB) Exec(ctx context.Context, query string, params ...interface{}) (rowsAffected int64, _ error)
Exec just runs an SQL command on the database returning no rows.
func (DB) Insert ¶
Insert one or more instances on the database
If the original instances have been passed by reference the ID is automatically updated after insertion is completed.
func (DB) Query ¶
func (c DB) Query( ctx context.Context, records interface{}, query string, params ...interface{}, ) error
Query queries several rows from the database, the input should be a slice of structs (or *struct) passed by reference and it will be filled with all the results.
Note: it is very important to make sure the query will return a small known number of results, otherwise you risk of overloading the available memory.
func (DB) QueryChunks ¶
func (c DB) QueryChunks( ctx context.Context, parser ChunkParser, ) error
QueryChunks is meant to perform queries that returns more results than would normally fit on memory, for others cases the Query and QueryOne functions are indicated.
The ChunkParser argument has 4 attributes: (1) The Query; (2) The query args; (3) The chunk size; (4) A callback function called ForEachChunk, that will be called to process each chunk loaded from the database.
Note that the signature of the ForEachChunk callback can be any function that receives a slice of structs or a slice of pointers to struct as its only argument and that reflection will be used to instantiate this argument and to fill it with the database rows.
func (DB) QueryOne ¶
func (c DB) QueryOne( ctx context.Context, record interface{}, query string, params ...interface{}, ) error
QueryOne queries one instance from the database, the input struct must be passed by reference and the query should return only one result.
QueryOne returns a ErrRecordNotFound if the query returns no results.
func (DB) Transaction ¶
Transaction just runs an SQL command on the database returning no rows.
type DBAdapter ¶
type DBAdapter interface {
ExecContext(ctx context.Context, query string, args ...interface{}) (Result, error)
QueryContext(ctx context.Context, query string, args ...interface{}) (Rows, error)
}
DBAdapter is minimalistic interface to decouple our implementation from database/sql, i.e. if any struct implements the functions below with the exact same semantic as the sql package it will work with ksql.
To create a new client using this adapter use ksql.NewWithAdapter()
type Dialect ¶
type Dialect interface {
InsertMethod() insertMethod
Escape(str string) string
Placeholder(idx int) string
DriverName() string
}
Dialect is used to represent the different ways of writing SQL queries used by each SQL driver.
func GetDriverDialect ¶
GetDriverDialect instantiantes the dialect for the provided driver string, if the drive is not supported it returns an error
type Mock ¶
type Mock struct {
InsertFn func(ctx context.Context, table Table, record interface{}) error
UpdateFn func(ctx context.Context, table Table, record interface{}) error
DeleteFn func(ctx context.Context, table Table, idOrRecord interface{}) error
QueryFn func(ctx context.Context, records interface{}, query string, params ...interface{}) error
QueryOneFn func(ctx context.Context, record interface{}, query string, params ...interface{}) error
QueryChunksFn func(ctx context.Context, parser ChunkParser) error
ExecFn func(ctx context.Context, query string, params ...interface{}) (rowsAffected int64, _ error)
TransactionFn func(ctx context.Context, fn func(db Provider) error) error
}
Mock implements the Provider interface in order to allow users to easily mock the behavior of a ksql.Provider.
To mock a particular method, e.g. Insert, you just need to overwrite the corresponding function attribute whose name is InsertFn().
NOTE: This mock should be instantiated inside each unit test not globally.
For capturing input values use a closure as in the example:
var insertRecord interface{}
dbMock := Mock{
InsertFn: func(ctx context.Context, table Table, record interface{}) error {
insertRecord = record
},
}
NOTE: It is recommended not to make assertions inside the mocked methods, you should only check the captured values afterwards as all tests should have 3 stages: (1) setup, (2) run and finally (3) assert.
For cases where the function will be called several times you might want to capture the number of calls as well as the values passed each time for that use closures and a slice of values, e.g.:
var insertRecords []interface{}
dbMock := Mock{
InsertFn: func(ctx context.Context, table Table, record interface{}) error {
insertRecords = append(insertRecords, record)
},
}
expectedNumberOfCalls := 2
assert.Equal(t, expectedNumberOfCalls, len(insertRecords))
expectedInsertedRecords := []interface{}{
user1,
user2,
}
assert.Equal(t, expectedInsertedRecords, insertRecords)
func (Mock) Delete ¶
Delete mocks the behavior of the Delete method. If DeleteFn is set it will just call it returning the same return values. If DeleteFn is unset it will panic with an appropriate error message.
func (Mock) Exec ¶
func (m Mock) Exec(ctx context.Context, query string, params ...interface{}) (rowsAffected int64, _ error)
Exec mocks the behavior of the Exec method. If ExecFn is set it will just call it returning the same return values. If ExecFn is unset it will panic with an appropriate error message.
func (Mock) Insert ¶
Insert mocks the behavior of the Insert method. If InsertFn is set it will just call it returning the same return values. If InsertFn is unset it will panic with an appropriate error message.
func (Mock) Query ¶
func (m Mock) Query(ctx context.Context, records interface{}, query string, params ...interface{}) error
Query mocks the behavior of the Query method. If QueryFn is set it will just call it returning the same return values. If QueryFn is unset it will panic with an appropriate error message.
func (Mock) QueryChunks ¶
func (m Mock) QueryChunks(ctx context.Context, parser ChunkParser) error
QueryChunks mocks the behavior of the QueryChunks method. If QueryChunksFn is set it will just call it returning the same return values. If QueryChunksFn is unset it will panic with an appropriate error message.
func (Mock) QueryOne ¶
func (m Mock) QueryOne(ctx context.Context, record interface{}, query string, params ...interface{}) error
QueryOne mocks the behavior of the QueryOne method. If QueryOneFn is set it will just call it returning the same return values. If QueryOneFn is unset it will panic with an appropriate error message.
func (Mock) SetFallbackDatabase ¶
SetFallbackDatabase will set all the Fn attributes to use the function from the input database.
SetFallbackDatabase is useful when you only want to overwrite some of the operations, e.g. for testing errors or if you want to use the same setup for making unit tests and integration tests, this way instead of creating a new server with a real database and another with a mocked one you can start the server once and run both types of tests.
Example Usage:
db, err := ksql.New(...)
if err != nil {
t.Fatal(err.Error())
}
mockdb := ksql.Mock{
UpdateFn: func(_ context.Context, _ ksql.Table, record interface{}) error {
return ksql.ErrRecordNotFound
},
}.SetFallbackDatabase(db)
// Passing the address to the service so
// you can change it for each test
myService := myservice.New(..., &mockdb, ...)
func (Mock) Transaction ¶
Transaction mocks the behavior of the Transaction method. If TransactionFn is set it will just call it returning the same return values. If TransactionFn is unset it will just call the input function passing the Mock itself as the database.
type PGXAdapter ¶
type PGXAdapter struct {
// contains filtered or unexported fields
}
PGXAdapter adapts the sql.DB type to be compatible with the `DBAdapter` interface
func NewPGXAdapter ¶ added in v1.2.0
func NewPGXAdapter(db *pgxpool.Pool) PGXAdapter
NewPGXAdapter instantiates a new pgx adapter
func (PGXAdapter) BeginTx ¶
func (p PGXAdapter) BeginTx(ctx context.Context) (Tx, error)
BeginTx implements the Tx interface
func (PGXAdapter) ExecContext ¶
func (p PGXAdapter) ExecContext(ctx context.Context, query string, args ...interface{}) (Result, error)
ExecContext implements the DBAdapter interface
func (PGXAdapter) QueryContext ¶
func (p PGXAdapter) QueryContext(ctx context.Context, query string, args ...interface{}) (Rows, error)
QueryContext implements the DBAdapter interface
type PGXResult ¶
type PGXResult struct {
// contains filtered or unexported fields
}
PGXResult is used to implement the DBAdapter interface and implements the Result interface
func (PGXResult) LastInsertId ¶
LastInsertId implements the Result interface
func (PGXResult) RowsAffected ¶
RowsAffected implements the Result interface
type PGXRows ¶
PGXRows implements the Rows interface and is used to help the PGXAdapter to implement the DBAdapter interface.
type PGXTx ¶
type PGXTx struct {
// contains filtered or unexported fields
}
PGXTx is used to implement the DBAdapter interface and implements the Tx interface
func (PGXTx) ExecContext ¶
ExecContext implements the Tx interface
func (PGXTx) QueryContext ¶
QueryContext implements the Tx interface
type Provider ¶
type Provider interface {
Insert(ctx context.Context, table Table, record interface{}) error
Update(ctx context.Context, table Table, record interface{}) error
Delete(ctx context.Context, table Table, idOrRecord interface{}) error
Query(ctx context.Context, records interface{}, query string, params ...interface{}) error
QueryOne(ctx context.Context, record interface{}, query string, params ...interface{}) error
QueryChunks(ctx context.Context, parser ChunkParser) error
Exec(ctx context.Context, query string, params ...interface{}) (rowsAffected int64, _ error)
Transaction(ctx context.Context, fn func(Provider) error) error
}
Provider describes the ksql public behavior.
The Insert, Update, Delete and QueryOne functions return ksql.ErrRecordNotFound if no record was found or no rows were changed during the operation.
type Rows ¶
type Rows interface {
Scan(...interface{}) error
Close() error
Next() bool
Err() error
Columns() ([]string, error)
}
Rows represents the results from a call to Query()
type SQLAdapter ¶
SQLAdapter adapts the sql.DB type to be compatible with the `DBAdapter` interface
func NewSQLAdapter ¶ added in v1.3.0
func NewSQLAdapter(db *sql.DB) SQLAdapter
NewSQLAdapter returns a new instance of SQLAdapter with the provided database instance.
func (SQLAdapter) BeginTx ¶
func (s SQLAdapter) BeginTx(ctx context.Context) (Tx, error)
BeginTx implements the Tx interface
func (SQLAdapter) ExecContext ¶
func (s SQLAdapter) ExecContext(ctx context.Context, query string, args ...interface{}) (Result, error)
ExecContext implements the DBAdapter interface
func (SQLAdapter) QueryContext ¶
func (s SQLAdapter) QueryContext(ctx context.Context, query string, args ...interface{}) (Rows, error)
QueryContext implements the DBAdapter interface
type SQLTx ¶
SQLTx is used to implement the DBAdapter interface and implements the Tx interface
func (SQLTx) ExecContext ¶
ExecContext implements the Tx interface
func (SQLTx) QueryContext ¶
QueryContext implements the Tx interface
type Table ¶
type Table struct {
// contains filtered or unexported fields
}
Table describes the required information for inserting, updating and deleting entities from the database by ID using the 3 helper functions created for that purpose.
func NewTable ¶
NewTable returns a Table instance that stores the tablename and the names of columns used as ID, if no column name is passed it defaults to using the `"id"` column.
This Table is required only for using the helper methods:
- Insert - Update - Delete
Passing multiple ID columns will be interpreted as a single composite key, if you want to use the helper functions with different keys you'll need to create multiple Table instances for the same database table, each with a different set of ID columns, but this is usually not necessary.
type Tx ¶
type Tx interface {
ExecContext(ctx context.Context, query string, args ...interface{}) (Result, error)
QueryContext(ctx context.Context, query string, args ...interface{}) (Rows, error)
Rollback(ctx context.Context) error
Commit(ctx context.Context) error
}
Tx represents a transaction and is expected to be returned by the DBAdapter.BeginTx function
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
adapters
|
|
|
kpgx5
module
|
|
|
kpostgres
module
|
|
|
modernc-ksqlite
module
|
|
|
benchmarks
module
|
|
|
examples
|
|
|
all_adapters
command
|
|
|
crud
command
|
|
|
example_service
Package exampleservice is a generated GoMock package.
|
Package exampleservice is a generated GoMock package. |
|
internal
|
|