gaum
A story about Bare Minimum Struct Relational Mapping, by Horacio Duran
This intends to provide a bare minimum ORM-Like-but-not-quite interface to work with postgres.
The original intent behind this project is to allow us to replace gorm in a project at work because it is falling a bit short.
This library is, as it's name indicates, a bare minimum. It is not a "drop in" replacement for gorm because I wanted to change a bit the behavior.
How to use it, there are two components that can be used separately:
- The DB connector: Which allows interaction with the underlying DB, it adds almost nothing to the underlying API but some minor level of magic when fetching the data and a set of helpers to convert from the more practical
? argument placeholders to the numbered positionals required by the DB $1, $2,.... with a few convenient expansions like making (?) into ($1...n) based on the passed arguments (with limitations).
- The Chain: Provides a set of convenience functions and methods that allows chaining and combining to produce a struct that can render itself into a consistent SQL query (the promise is that the same object renders itself into the same SQL object each time).
DB
Note all the examples in this doc are using the postgres driver because it is the itch I am scratching, along with it we provide a standard postgres driver, which can be used if you hit a limitation in the other one (which we did), I do not intend to write other drivers and most of the code will be strongly opinionated towards postgres, this said, if someone else feels like writing different drivers I'll gladly accept PRs
As stated above, the DB component provides a set of convenience functions that allow querying and executing statements in the db and retrieving the results if any with slightlty less friction than the bare bones functions.
To first open a connection we will need an instance of connection.DatabaseHandler and invoke the Open method.
Open creates a db connection pool and returns a connection.DB object containing it. By default it uses a pool, once again, because I have no use for single connection.
// imports used
// "github.com/ShiftLeftSecurity/gaum/db/connection"
// "github.com/ShiftLeftSecurity/gaum/db/postgrespq"
// "github.com/ShiftLeftSecurity/gaum/db/logging"
var connector connection.DatabaseHandler
// This uses Postgres PQ driver, which is the standard sql driver for postgres, you can use
// pgx one for a bit of efficiency increase in some aspects but outcome is not always guaranteed
// as we use PQ for real life testing (automated tests use both)
connector = postgrespq.Connector{
ConnectionString: "a connection string",
}
// Wrappers are provider for go standard logging and testging t.Log but build more is trivial
// and can be pretty much cargo culted from the existing one.
logger := logging.NewGoLogger(standardgologger)
maxConnLifetime := 1 * time.Minute
dbConnection, err := gaumConnector.Open(&connection.Information{
Logger: logger,
// For production `Error` is the recommended logging level as the driver and the underlying
// library are quite chatty.
LogLevel: connection.Error,
// You can omit this if you don't have special db requirements, most uses should be ok
// with default but we provide just in case.
// Side note: this only works with PQ driver.
ConnMaxLifetime: &maxConnLifetime,
// This is possible but rarely necessary, I just added the example in case you hit one of
// the corner cases which require it.
CustomDial: func(network, addr string) (net.Conn, error) {
d := &net.Dialer{
KeepAlive: time.Minute,
}
return d.Dial(network, addr)
},
// Most of these can be provided as the ConnectionString when instantiating the connector
Host: "127.0.0.1",
Port: 5432,
Database: "postgres",
User: "postgres",
Password: "mysecretpassword",
MaxConnPoolConns: 10,
})
if err != nil {
// do something
}
The connection string is enough to open a connection but if Open receives a non nil parameter the overlapping parameters will be taken from the connection.Information in the Open invocation.
The Information struct contains most of the possible data one can use for a connection, strongly biased to postgres.
A note about the logger object passed to Open, its an instance of logging.Logger which is basically an Interface for logging that I consider sane enough and that I in turn addapt to what pgx takes.
For ease of use, as stated in this example a wrapper for the standard go log is provided.
For testing purposes, another wrapper is provided that wraps on the *testing.T object to facilitate testing info.
Some of the items in DB
DB.Clone returns a deep copy of the db.
EscapeArgs is in the wrong place in the code, but will do for now. This is something to be known before any querying function. To avoid the hassle of having to put $<argnumber> in each query argument placeholder, the convenience gorm provides was taken and it's possible to use ? as a placeholder. To allow for our lazy side to take over, we need to invoke EscapeArgs on the query and args to both check for number of arg consistency and properly escape the placeholders before calling any of the queries, now for all of these functions, there is also another with the same name provided with an E prepend that invokes EscapeArgs for you.
A more useful and feature complete of EscapeArgs can be found in chain.MarksToPlaceholders that will not only convert ? signs into positional arguments that the db accepts but also unwrap slice arguments where appropriate and returns the expanded list of arguments.
( See EscapeArgs And QueryIter )
EQueryIter will execute the query and return a closure that holds the cursor. Calling the returned closure produces advancement of the cursor, one can pass the pointer to a struct that one wants populated. The rules for populating a struct are made from the passed list of fields (containing the column names to be fetched in the query, beware no consistency is checked until query time and by then all will go boom or you will be missing data) there will be snake to camel case conversion and matching that to the struct member name (or the contents of gaum:"field_name:something"). If no fields are specified we will make a query to the db to ask for a description of the fields returned, try not to let that happen as it requires extra roundtrips and adds uncertainty.
Ideally this and all other queries will be used through chain that will take care of the ugly parts.
Note: this WILL hold a connection from the pool until you either invoke close() function returned in each iteration or deplete results, a timer option is planned but don't hold your breath.
(See EscapeArgs And Query )
EQuery will return a closure, similar to QueryIter but it will take a slice pointer (sorry, reflection) only since it will fetch all the results in one call and populate the slice. The rest of the behavior is the same.
Note: this WILL hold a connection from the pool until you either invoke close() function returned or run the closure, a timer option is planned but don't hold your breath.
( See EscapeArgs And QueryPrimitive )
QueryPrimitive will return a closure, similar to Query but it will take a pointer to slice of primitives, for this the SELECT statement must return only one column or the query will fail before even executing. The rest of the behavior is the same.
Note: this WILL hold a connection from the pool until you either invoke close() function returned or run the closure, a timer option is planned but don't hold your breath.
( See EscapeArgs And Raw )
Raw will run the passed query with the passed arguments and try to fetch the resulting row into the passed pointer receivers, this will do for one row only and you have to be careful to pass enough (and properly typed, see sql.Scanner ) receivers for the fields you are querying and no more.
( See EscapeArgs And Exec )
Exec is intended for queries that do not return results such as... well anything that is not a SELECT (and sometimes SELECT if you do not expect results, such as when invoking a stored procedure) you just pass the query and the arguments.
Transactions
Transactions are fairly simple. DB offers BeginTransaction that returns a disposable DB object whose life extends only to the boundary of the transaction and will end when you either RollbackTransaction or CommitTransaction. These things are idempotent so if you call Begin on a transaction nothing bad happens and equally if you call Rollback or Commit on a non transaction. To know if your db is a transaction use IsTransaction
DB.BulkInsert
This has not yet been tested, it's intention is to use the COPY statement.
Chain
The Chain (poor decision on my part used the very long ExpressionChain