db2go

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2024 License: Apache-2.0 Imports: 5 Imported by: 0

README

Go Reference

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)

	// Creates the struct based on the table
	st := db2go.CreateStruct(tableDescriptor, arguments.Table, true)

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

	// To create a go file (including package) with the structs for all the tables you can execute the following lines
	descriptors := db2go.GetDescriptorsForAllTables(connection)

	db2go.CreateAllTablesStructFile("./allTablesDTO.go", "dto", descriptors, true)
}

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 snake_case string into a camelCase or PascalCase string.

This function transforms an input string from snake_case to camelCase or PascalCase, depending on the `capitalised` flag. Each underscore-separated word in the input string is capitalized, and underscores are removed.

Parameters:

  • input: string - The snake_case string to convert.
  • capitalised: bool - A flag indicating whether the first letter of the resulting string should be capitalized (PascalCase) or lowercase (camelCase).

Returns:

  • string: The camelCase or PascalCase representation of the input string.

Example Usage:

  • Camelize("example_input", false) -> "exampleInput"
  • Camelize("example_input", true) -> "ExampleInput"

Notes:

  • If the input string is empty or contains no underscores, it is returned unchanged.
  • The function assumes the input string is in valid snake_case format.

func CreateAllTablesStructFile added in v1.0.1

func CreateAllTablesStructFile(filename string, packageName string, descriptors map[string][]TableDescriptor, withJson bool)

CreateAllTablesStructFile generates Go struct definitions for multiple database tables and writes them to a specified file.

This function takes a map of table names to their descriptors, generates Go struct definitions for each table using the `CreateStruct` function, and writes all the generated code to a file. The resulting file includes the specified package name.

Parameters:

  • filename: string - The name of the file where the generated structs will be written.
  • packageName: string - The name of the Go package to include at the top of the file.
  • descriptors: map[string][]TableDescriptor - A map where the keys are table names, and the values are slices of `TableDescriptor` objects containing metadata about the table columns.
  • withJson: bool - A flag indicating whether to include JSON tags for the struct fields.

Notes:

  • The function uses the `CreateStruct` function to generate each struct definition.
  • The `writeToFile` helper function is used to write the generated code to the specified file.
  • Ensure the provided `filename` is writable, and the `packageName` is a valid Go package name.
  • The file will contain all the structs, separated by newlines, under the specified package.

func CreateStruct

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

CreateStruct generates a Go struct definition based on the table descriptors.

This function takes a slice of `TableDescriptor` objects, a table name, and an optional flag for including JSON tags. It generates a Go struct definition where each column in the table corresponds to a struct field. The field names are camel-cased, and their types are determined based on the column descriptors.

Parameters:

  • tt: []TableDescriptor - A slice of `TableDescriptor` objects containing metadata about the columns of the table.
  • tableName: string - The name of the table, used as the base name for the generated struct.
  • withJson: bool - A flag indicating whether to include JSON tags for the struct fields.

Returns:

  • string: A string representation of the generated Go struct.

Panics:

  • The function panics if the provided table descriptor slice is empty.

Notes:

  • The struct fields are formatted for alignment, ensuring consistent spacing.
  • JSON tags are included in the struct definition if `withJson` is set to `true`.
  • Helper functions like `Camelize` and `getType` are expected to handle field name conversion and type determination, respectively.

func GetDbConnection

func GetDbConnection(c *ConnectionString) *sql.DB

GetDbConnection establishes and returns a connection to a MySQL database.

This function creates a database connection using the provided `ConnectionString` object, formats the connection URI, and verifies the connection by pinging the database.

Parameters:

  • c: *ConnectionString - A pointer to a `ConnectionString` struct containing the database connection details, including user, password, host, port, database name, and timeout.

Returns:

  • *sql.DB: A pointer to an established SQL database connection.

Behavior:

  • The function formats the connection string to include parsing of time values and a timeout.
  • If the connection cannot be created or the database cannot be reached, the function logs the error message and panics.

Notes:

  • The caller is responsible for closing the returned connection to avoid resource leaks.
  • This function assumes a MySQL database and uses the Go `sql` package along with the MySQL driver.
  • Ensure the `ConnectionString` struct contains valid and properly formatted connection parameters.

Example Usage:

connString := &ConnectionString{
    User:         "root",
    Password:     "password",
    Host:         "localhost",
    Port:         3306,
    DatabaseName: "my_database",
    Timeout:      5,
}
db := GetDbConnection(connString)

func GetDbTableNames added in v1.0.1

func GetDbTableNames(conn *sql.DB) []string

GetDbTableNames retrieves the names of all tables in the connected database.

This function executes a "SHOW TABLES" query on the provided database connection `conn` to list all tables in the current database. It processes the query results, scans each table name, and appends it to a slice of strings.

Parameters:

  • conn: *sql.DB - A pointer to an open SQL database connection.

Returns:

  • []string: A slice containing the names of all tables in the database.

Notes:

  • This function will panic if there is an error executing the query or scanning the rows. Ensure error handling and proper database connection setup before calling this function.

func GetDescriptorsForAllTables added in v1.0.1

func GetDescriptorsForAllTables(conn *sql.DB) map[string][]TableDescriptor

GetDescriptorsForAllTables retrieves table descriptors for all tables in a database.

This function queries the database connection `conn` to get the names of all tables using the `GetDbTableNames` function. It then iterates over each table name and retrieves its descriptors using the `GetTableDescriptor` function. The results are stored in a map where the keys are table names and the values are slices of `TableDescriptor` objects.

Parameters:

  • conn: *sql.DB - A pointer to an open SQL database connection.

Returns:

  • map[string][]TableDescriptor: A map where the key is the table name (string) and the value is a slice of `TableDescriptor` containing metadata for the respective table.

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 retrieves the column descriptors for a specified table.

This function executes a "DESCRIBE" query on the provided table name using the database connection `conn`. It retrieves the column details and stores them as a slice of `TableDescriptor` objects, where each object contains metadata about a single column.

Parameters:

  • conn: *sql.DB - A pointer to an open SQL database connection.
  • tableName: string - The name of the table to describe.

Returns:

  • []TableDescriptor: A slice of `TableDescriptor` objects containing metadata about the columns of the specified table.

Notes:

  • This function will panic if there is an error executing the query or scanning the rows. Ensure proper error handling and valid table names are used before calling this function.

Jump to

Keyboard shortcuts

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