db2go

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2024 License: Apache-2.0 Imports: 4 Imported by: 0

README

db2go

db2go is a utility written in Go that connects to a MySQL database, reads the schema of a specified table, and generates a Go struct representing the table's structure. The tool uses JSON struct tags to facilitate easy marshaling and unmarshaling of data.

Features

  • Connects to a MySQL database using the provided connection details.
  • Reads the schema of a specified table using MySQL's DESCRIBE command.
  • Generates Go structs based on the table's schema, with optional JSON struct tags.

Usage

go get github.com/bitsbuster/db2go
Example

Generate a Go struct for a table named users in a MySQL database:

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/ardanlabs/conf"
	"github.com/bitsbuster/db2go"
)

type Arguments struct {
	Host         string `conf:"flag:host,short:h,required"`
	Port         uint16 `conf:"flag:port,short:p,default:3306"`
	User         string `conf:"flag:user,short:u,required"`
	Password     string `conf:"flag:password,short:s,required"`
	DatabaseName string `conf:"flag:db,short:d,required"`
	Timeout      uint16 `conf:"flag:timeout,short:t,default:10"`
	Table        string `conf:"flag:table,short:b,required"`
}

func main() {

	arguments := &Arguments{}
	//check for execution argument to start app as bridge or redis dispatcher
	if err := conf.Parse(os.Args[1:], "", arguments); err != nil {
		log.Panic(err)
	}

	connection := db2go.GetDbConnection(&db2go.ConnectionString{
		Host:         arguments.Host,
		Port:         arguments.Port,
		User:         arguments.User,
		Password:     arguments.Password,
		DatabaseName: arguments.DatabaseName,
		Timeout:      arguments.Timeout,
	})

	defer connection.Close()

	tableDescriptor := db2go.GetTable(connection, arguments.Table)

	st := db2go.CreateStruct(tableDescriptor, arguments.Table, true)

	fmt.Printf("%s\n", st)
}

Build the binary:

go build -o db2go

Then you can execute it:

./db2go \
  --host 127.0.0.1 \
  --port 3306 \
  --user root \
  --password secret \
  --db my_database \
  --timeout 10 \
  --table users

Sample output:

type Users struct {
    ID       *uint64     `json:"id"`
    Name     string      `json:"name"`
    Email    *string     `json:"email"`
    Created  string      `json:"created"`
    Modified *time.Time  `json:"modified"`
    Data     []byte      `json:"data"`
}

How It Works

  1. Parses command-line arguments using the conf package.
  2. Connects to the MySQL database using the provided connection details.
  3. Uses MySQL's DESCRIBE command to retrieve the schema of the specified table.
  4. Generates a Go struct from the schema, including JSON struct tags if the feature is enabled.

License

This project is licensed under the Apache 2.0 License.


Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Camelize

func Camelize(input string, capitalised bool) string

Camelize converts a string with underscores into camelCase.

func CreateStruct

func CreateStruct(tt []TableDescriptor, tableName string, withJson bool) string

CreateStruct creates a new struct with the camelized name of the table from the table descriptor. If withJson is true, creates the struct tags for json

func GetDbConnection

func GetDbConnection(c *ConnectionString) *sql.DB

GetDbConnection returns the connection to the database using ConnectionString

Types

type ConnectionString

type ConnectionString struct {
	// Host specifies the hostname or IP address of the database server.
	Host string
	// Port is the port number on which the database server is listening.
	Port uint16
	// Timeout is the maximum amount of time (in seconds) to wait for the database connection to be established.
	Timeout uint16
	// User is the username used for authenticating to the database.
	User string
	// Password is the password associated with the User for database authentication.
	Password string
	// DatabaseName is the name of the specific database to connect to on the server.
	DatabaseName string
}

ConnectionString defines the details required to establish a connection to a database.

type TableDescriptor

type TableDescriptor struct {
	// Field is the name of the column in the table.
	Field string
	// Type is the data type of the column, as defined in the database schema (e.g., INT, VARCHAR(255)).
	Type string
	// Null indicates whether the column can contain NULL values ("YES" or "NO").
	Null string
	// Key specifies if the column is part of a key (e.g., "PRI" for primary key, "UNI" for unique key).
	Key string
	// Default is the default value assigned to the column, if any. A nil value indicates no default.
	Default *string
	// Extra contains additional information about the column, such as auto-increment settings.
	Extra string
}

TableDescriptor represents the schema details of a single column in a database table.

func GetTableDescriptor added in v1.0.0

func GetTableDescriptor(conn *sql.DB, tableName string) []TableDescriptor

GetTableDescriptor returns the information from sql "describe <tableName>" query in a TableDescriptor struct

Jump to

Keyboard shortcuts

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