Skip to content

dbtypegen is a tool that generates Go structures from a database schema.

License

Notifications You must be signed in to change notification settings

johejo/dbtypegen

Repository files navigation

dbtypegen

ci Go Reference codecov Go Report Card

dbtypegen is a tool that generates Go structures from a database schema.

Install

go install github.com/johejo/dbtypegen/cmd/dbtypegen

Usage

mkdir example
cd example/
go mod init example

Create schema DDL

schema.sql

CREATE TABLE `user` (
  id   BIGINT PRIMARY KEY,
  created_at DATETIME(3) NOT NULL,
  active BOOLEAN DEFAULT NULL,
  name VARCHAR(36) NOT NULL
);
dbtypegen -schema schema.sql -out ./db_types_gen.go -package example

Generated file

// Code generated by dbtypegen, DO NOT EDIT.

package example

import (
	"time"
)

// User is the type that represents table `user`.
type User struct {
	Id        int64     `db:"id"`
	CreatedAt time.Time `db:"created_at"`
	Active    bool      `db:"active"`
	Name      string    `db:"name"`
}

// Columns returns all columns as joined string
func (t *User) Columns() string {
	return "id,created_at,active,name"
}

// ColumnList returns all columns as slice of string.
func (t *User) ColumnList() []string {
	return []string{"id", "created_at", "active", "name"}
}

// TableName returns the name of table.
func (t *User) TableName() string {
	return "user"
}

// SelectAll returns a part of query like `SELECT id,name FROM people`.
func (t *User) SelectAll() string {
	return "SELECT id,created_at,active,name FROM user"
}

// ScanAll returns field's pointers for row.Scan.
func (t *User) ScanAll() []interface{} {
	return []interface{}{&t.Id, &t.CreatedAt, &t.Active, &t.Name}
}

INSERT and SELECT

var u User

var b strings.Builder
b.WriteString("INSERT INTO ")
b.WriteString(u.TableName())
b.WriteString(" (")
b.WriteString(u.Columns())
b.WriteString(") ")
b.WriteString("VALUES (?,?,?,?)")
q := b.String()
now := time.Now()
args := []interface{}{1, now, true, "Gopher"}

if _, err := db.ExecContext(ctx, q, args...); err != nil {
	panic(err)
}

if err := db.QueryRowContext(ctx, u.SelectAll()+" WHERE id=?", 1).Scan(u.ScanAll()...); err != nil {
	panic(err)
}

fmt.Println(u)
// {1 20xx-xx-xx xx:xx:xx.xxx +0000 UTC true Gopher}

License

MIT

Author

Mitsuo Heijo

About

dbtypegen is a tool that generates Go structures from a database schema.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Languages