/kin

A declarative database manager in Go

Primary LanguageGoMIT LicenseMIT

Kin

CircleCI Go Report Card Documentation Coverage Status

Kin is very experimental - don't use it for anything real!

Kin is an opinionated, PostgreSQL-specific database driver that places an emphasis on writing SQL and explicit mappings to database tables. It gives users the control to write their own SQL queries, uses simple patterns that focus on control.

This means that kin isn't for everyone! It's certainly not a full-featured ORM in the mold of Gorm or Ruby's ActiveRecord. Instead, Kin smoothes out the rough edges and gives better error handling to SQL packages already built into Go.

Finally, support for running migrations is built in.

Getting Started

Installing kin is as simple as running:

go get github.com/jmataya/kin

Next, define your models, connect to the database, and you're off to the races!

package main

import (
        "database/sql"
        "fmt"
        "time"

        "github.com/jmataya/kin"
)

// User is a representation of a table called "users" with columns
// id (int), name (text), attributes (jsonb), is_active (bool), and
// created_at (timestamp).
type User struct {
	ID         int                    `db:"id"`
	Name       string                 `db:"name"`
	Attributes map[string]interface{} `db:"attributes"`
	IsActive   bool                   `db:"is_active"`
	CreatedAt  time.Time              `db:"created_at"`
}

func (u User) TableName() string {
	return "users"
}

func main() {
        // Connect with a raw Postgres URL.
        dbStr := "postgresql://localhost:5432/kin_test?user=kin"
        db, _ := sql.Open("postgres", dbStr)
        defer db.Close()
        
        // For most operations, Kin leverages SQL.
        queryStr := "SELECT * FROM users WHERE id = $1"
        id := 1
        
        // Output a single result into the user struct defined above.
		user, err := kin.NewQuery[User](db).Raw(queryStr, id).One()
        if err != nil {
                panic(err)
        }
        
        // Print the result.
        fmt.Printf("User: %+v\n", user)
}

Developing

You will need a database in order to run tests. Create a Postgres instance and put the database URL into a .env file in the root of the project. It should look something like this:

DATABASE_URL=postgresql://localhost:5432/kin_test?user=kin

Next, you can run tests with:

go test

Author

Jeff Mataya (jeff@jeffmataya.com)

License

MIT