dbwrap

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: May 11, 2024 License: MIT Imports: 8 Imported by: 0

README

Обёртка для SQLX

Добавлены методы:

Exec(query string, args ...interface{}) (int64, error)
NamedExec(query string, arg interface{}) (int64, error)
Select(dest interface{}, query string, args ...interface{}) error
NamedSelect(dest interface{}, query string, arg interface{}) error
SelectMaps(query string, args ...interface{}) (ret []map[string]interface{}, err error)
NamedSelectMaps(query string, arg interface{}) (ret []map[string]interface{}, err error)
Get(dest interface{}, query string, args ...interface{}) error
NamedGet(dest interface{}, query string, arg interface{}) error
GetMap(query string, args ...interface{}) (ret map[string]interface{}, err error)
NamedGetMap(query string, arg interface{}) (ret map[string]interface{}, err error)

Протестировано для MSSQL, PostgreSQL, MySQL, SQLite

Установка go get github.com/mpuzanov/dbwrap

Примеры


    config := dbwrap.NewConfig("sqlserver").WithPassword(password).WithDB("master").WithPort(port)
    db, err := dbwrap.NewConnect(config)
    if err != nil {
        panic(err)
    }
    log.Println("cfg.DB", config.String())


    query := fmt.Sprintf(`select last_name, email, created_at from %s where last_name=:Name`, tableName)
    person := Person{}
    err = db.NamedGet(&person, query, map[string]interface{}{"Name": "Иванов"})

Драйвера БД

Для PostgreSQL:

go get github.com/lib/pq

Для MSSQL Server:

go get github.com/denisenkom/go-mssqldb

Для MySQL:

github.com/go-sql-driver/mysql

Для SQLite:

go get github.com/mattn/go-sqlite3

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrBadConfigDB = errors.New("не заполнены параметры подключения к БД")

ErrBadConfigDB ошибка

Functions

This section is empty.

Types

type Config

type Config struct {
	Host         string `yaml:"host" env:"DB_HOST" env-required:"true"`
	Port         int    `yaml:"port" env:"DB_PORT" env-default:"1433" env-description:"sql server port"`
	User         string `yaml:"user" env:"DB_USER" env-required:"true"`
	Password     string `yaml:"password" env:"DB_PASSWORD" env-required:"true"`
	Database     string `yaml:"database" env:"DB_DATABASE" env-required:"true"`
	TimeoutQuery int    `yaml:"timeout_query" env:"TIMEOUT_QUERY" env-default:"300"` // Second
	APPName      string `yaml:"app_name" env:"APP_NAME"`
	DriverName   string `yaml:"driver_name" env:"DRIVER_NAME"  env-default:"sqlserver"`
}

Config структура для параметров соединения с БД

func NewConfig

func NewConfig(driverName string) *Config

NewConfig создание конфига по умолчанию

func (*Config) GetDatabaseURL

func (c *Config) GetDatabaseURL() string

GetDatabaseURL "sqlserver://user:password@host:port?database=database_name" "postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable" "mysql://username:password@protocol(address)/dbname?param=value" "user:password@tcp(127.0.0.1:3306)/sql_test?charset=utf8mb4&parseTime=True" sqlite3 или имя БД или :memory: driver sqlserver || postgres

func (*Config) String

func (c *Config) String() string

String вывод полей в строку

func (*Config) WithDB

func (c *Config) WithDB(dbname string) *Config

WithDB установка БД

func (*Config) WithDriverName

func (c *Config) WithDriverName(driverName string) *Config

WithDriverName задания наименования драйвера БД

func (*Config) WithPassword

func (c *Config) WithPassword(pwd string) *Config

WithPassword установка пароля

func (*Config) WithPort

func (c *Config) WithPort(port int) *Config

WithPort установка порта БД

type DBSQL

type DBSQL struct {
	DBX *sqlx.DB
	Cfg *Config
}

DBSQL ...

func NewConnect

func NewConnect(cfg *Config) (*DBSQL, error)

NewConnect Создание подключения к БД

func (*DBSQL) Close

func (d *DBSQL) Close() error

Close закрытие соединений

func (*DBSQL) Exec

func (d *DBSQL) Exec(query string, args ...interface{}) (int64, error)

Exec Выполнение запроса DML

func (*DBSQL) Get

func (d *DBSQL) Get(dest interface{}, query string, args ...interface{}) error

Get ...

func (*DBSQL) GetMap

func (d *DBSQL) GetMap(query string, args ...interface{}) (ret map[string]interface{}, err error)

GetMap ...

func (*DBSQL) NamedExec

func (d *DBSQL) NamedExec(query string, arg interface{}) (int64, error)

NamedExec Выполнение запроса DML

func (*DBSQL) NamedGet

func (d *DBSQL) NamedGet(dest interface{}, query string, arg interface{}) error

NamedGet ...

func (*DBSQL) NamedGetMap

func (d *DBSQL) NamedGetMap(query string, arg interface{}) (ret map[string]interface{}, err error)

NamedGetMap ...

func (*DBSQL) NamedSelect

func (d *DBSQL) NamedSelect(dest interface{}, query string, arg interface{}) error

NamedSelect получаем данные из запроса в слайс структур

var users []User

err := ts.db.NamedSelect(&users, "select * from users where name=:Name", map[string]interface{}{"Name": "admin"})

func (*DBSQL) NamedSelectMaps

func (d *DBSQL) NamedSelectMaps(query string, arg interface{}) (ret []map[string]interface{}, err error)

NamedSelectMaps ...

func (*DBSQL) Select

func (d *DBSQL) Select(dest interface{}, query string, args ...interface{}) error

Select получаем данные из запроса в слайс структур

var users []User

err := ts.db.Select(&users, "select * from users")

func (*DBSQL) SelectMaps

func (d *DBSQL) SelectMaps(query string, args ...interface{}) (ret []map[string]interface{}, err error)

SelectMaps ...

func (*DBSQL) SetTimeout

func (d *DBSQL) SetTimeout(timeout uint)

SetTimeout установка таймаута для выполнения запроса в секундах

Jump to

Keyboard shortcuts

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