A simple database connection and migration handler for go applications. It has 2 primary applications:
- serving as a go-between (pun not intended) between
database/sql
and your program by providing an abstraction layer, thus somewhat decoupling from a single database handling library, - making connection handling easier by providing migration functionality and hiding connection management with easy access methods.
At the start of your program, run
err := gotabase.InitialiseConnection(connectionString, driverName)
to prepare the database connection.
After that, you can access the connection pool by using the gotabase.GetConnection()
method.
You can execute migrations by calling the Migrate
method in the migrations
package.
There are a couple of important things to remember:
- You should store your migrations in a file with
.sql
extension. These files should be contained in a folder calledsql
. The files should have names consisting of a single number, starting at 0 and going SEQUENTIALLY up (as in0.sql
,1.sql
,2.sql
...). If you need to remove a migration after a next number has been used, leave the file empty instead of removing it. - Your database model must, from the very beginning, include a migrations table (it MUST be created in your
0.sql
migration file). By default, it should contain a single integer column calledid
as a primary key. Note that this behaviour can be modified or adjusted to a different DBMS by overwriting theMigrationCreator
,IsInitialMigrationError
andLatestMigrationSelectorSql
variables of themigrations
package. - The interface for providing database migrations files must be implemented, as there's no default implementation. You can, however, use the
embed.FS
struct, as it fulfills the conditions of this interface. See below for more details.
The easiest way to provide migration files is to use the embed.FS
struct.
First, create sql
folder somewhere within your project directory structure.
Then, in the same directory as the sql
folder, declare variable in the following way:
var (
//go:embed sql
migrations embed.FS
)
This will embed the contents of the sql
directory in your output binary file, making it easy to distribute those files.
You can also use the migrations
variable in place of the provider interface.
This library logs certain errors and information into a logger.
By default, Logrus is used as a logger.
This can be overwritten by assigning custom values to variables in logger
package.
Note that calling LogPanic
expects the system to panic afterward, as not doing so might lead to unexpected results.
The operations
package offers a set of functions typically used in repositories, when using databases.
When using those functions, errors returned can be controlled by setting relevant fields in the Errors
object.