dbtypegen

package module
v0.0.0-...-f99e6db Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 27, 2022 License: MIT Imports: 9 Imported by: 0

README

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

Documentation

Overview

Example
package main

import (
	"context"
	"database/sql"
	"fmt"
	"io/ioutil"
	"strings"
	"time"

	_ "github.com/go-sql-driver/mysql"
	dbtype "github.com/johejo/dbtypegen/testdata"
)

func main() {
	ctx := context.Background()
	db, err := sql.Open("mysql", "root:pass@tcp(localhost:3306)/dbtypegen?charset=utf8mb4&parseTime=true&loc=UTC&multiStatements=true")
	if err != nil {
		panic(err)
	}
	defer func() {
		if _, err := db.ExecContext(ctx, "DROP TABLE `user`"); err != nil {
			panic(err)
		}
		if _, err := db.ExecContext(ctx, "DROP TABLE `group`"); err != nil {
			panic(err)
		}
		if err := db.Close(); err != nil {
			panic(err)
		}
	}()

	schema, err := ioutil.ReadFile("testdata/schema.sql")
	if err != nil {
		panic(err)
	}

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

	var u dbtype.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)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Generate

func Generate(ctx context.Context, r io.Reader, opts ...Option) ([]byte, error)

Generate generates go source code and returns the data.

Types

type Option

type Option func(*config)

Option is option for generator.

func WithJSONType

func WithJSONType(jsonType string) Option

WithJSONType returns an option that sets json type.

func WithPackage

func WithPackage(pkg string) Option

WithPackage returns an option that sets package name.

func WithTag

func WithTag(tag string) Option

WithTag returns an option that sets struct tag.

func WithTypePrefix

func WithTypePrefix(typePrefix string) Option

WithTypePrefix returns an option that sets type prefix.

func WithTypeSuffix

func WithTypeSuffix(typeSuffix string) Option

WithTypeSuffix returns an option that sets type suffix.

func WithUUIDType

func WithUUIDType(uuidType string) Option

WithUUIDType returns an option that sets uuid type.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL