database

package
v0.0.0-...-213805d Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2023 License: MIT Imports: 8 Imported by: 0

README

Sample usage

dbConn, err := database.NewGorm(database.Config{
    DatabaseType: database.DBTypePostgresql,
    Host:         "localhost",
    Username:     "postgres",
    Password:     "postgres",
    DatabaseName: "zero_setting",
})
if err != nil {
    log.Println("err:", err)
    return
}
// dbConn, err := database.NewSqlxDB(database.Config{
// 	DatabaseType: database.DBTypePostgresql,
// 	Host:         "localhost",
// 	Username:     "postgres",
// 	Password:     "postgres",
// 	DatabaseName: "zero_setting",
// })
// if err != nil {
// 	log.Println("err:", err)
// 	return
// }

type TestTable struct {
    ID          int    `json:"id" db:"id"`
    TestName    string `json:"name" db:"test_name"`
    Description string `json:"desc" db:"description"`
}

err = dbConn.Exec("INSERT INTO test_table (test_name, description) VALUES ($1, $2) RETURNING id",
    "input name", "sample data")
log.Println("err:", err)

retID, err := dbConn.ExecReturn("INSERT INTO test_table (test_name, description) VALUES ($1, $2) RETURNING id",
    "sample name", "sample data with last inserted id")
log.Println("err:", err)
log.Println("retID:", retID)

var output TestTable
err = dbConn.QueryRow("select * from test_table where id = $1", &output, 1)
log.Println("err:", err)
log.Println("output:", output)

var result []TestTable
err = dbConn.Query("select * from test_table where description ilike '%'||$1||'%'", &result, `data`)
log.Println("err:", err)
log.Println("result:", result)
for _, val := range result {
    log.Printf("val:%+v\n", val)
}

Documentation

Index

Constants

View Source
const (
	DBTypeUnknown = iota
	DBTypePostgresql
	DBTypeMySql
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	DatabaseType DBType
	Host         string
	Username     string
	Password     string
	DatabaseName string
	SSLMode      string // default: disable, only for postgres
	Port         int    // default: 5432 for postgres, 3306 for mysql
	TimeZone     string // default: Local
}

type DBType

type DBType int

type Database

type Database interface {
	QueryRow(query string, result any, params ...any) error
	Query(query string, result any, params ...any) error
	Exec(query string, params ...any) error
	ExecReturn(query string, params ...any) (int, error)
}

func NewGorm

func NewGorm(cfg Config) (Database, error)

func NewSqlxDB

func NewSqlxDB(cfg Config) (Database, error)

Jump to

Keyboard shortcuts

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