gomysql

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2024 License: MIT Imports: 12 Imported by: 0

README

gomysql

go语言实现的mysql帮助库

实例化db
package main

import (
	"log"
	
	"github.com/grpc-boot/gomysql"
)

func main() {
	db, err := gomysql.NewDb(gomysql.Options{
		Host:     "127.0.0.1",
		Port:     3306,
		DbName:   "users",
		UserName: "root",
		Password: "12345678",
	})

	if err != nil {
		log.Fatalf("init db failed with error: %v\n", err)
	}
}

Create-Table
package main

import (
	"testing"

    "github.com/grpc-boot/gomysql"
	"github.com/grpc-boot/gomysql/condition"
	"github.com/grpc-boot/gomysql/helper"
)

func TestDb_Exec(t *testing.T) {
	res, err := gomysql.Exec(db.Executor(), "CREATE TABLE IF NOT EXISTS `users` " +
		"(`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '主键id'," +
		"`user_name` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT '' COMMENT '登录名'," +
		"`nickname` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '昵称'," +
		"`passwd` char(32) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL DEFAULT '' COMMENT '密码'," +
		"`email` varchar(64) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT '' COMMENT '邮箱'," +
		"`mobile` varchar(16) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL DEFAULT '' COMMENT '手机号'," +
		"`is_on` tinyint unsigned NOT NULL DEFAULT '0' COMMENT '账号状态(1已启用,0已禁用)'," +
		"`created_at` bigint unsigned NOT NULL DEFAULT '0' COMMENT '创建时间'," +
		"`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'," +
		"`last_login_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上次登录时间'," +
		"`remark` tinytext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci COMMENT '备注'," +
		"PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;")
	if err != nil {
		t.Fatalf("create table failed with error: %v\n", err)
	}

	count, err := res.RowsAffected()
	t.Logf("rows affected: %d error: %v\n", count, err)
}
Model
package main

import (
  "context"
  "fmt"
  "log"
  "strings"
  "time"

  "github.com/grpc-boot/gomysql"
  "github.com/grpc-boot/gomysql/helper"
)

var (
  DefaultUserModel = &UserModel{}
  db               *gomysql.Db
)

func init() {
  var err error
  db, err = gomysql.NewDb(gomysql.Options{
    Host:     "127.0.0.1",
    Port:     3306,
    DbName:   "users",
    UserName: "root",
    Password: "12345678",
  })

  if err != nil {
    log.Fatalf("init db failed with error: %v\n", err)
  }

  gomysql.SetLogger(func(query string, args ...any) {
    fmt.Printf("%s exec sql: %s args: %+v\n", time.Now().Format(time.DateTime), query, args)
  })

  gomysql.SetErrorLog(func(err error, query string, args ...any) {
    fmt.Printf("error: %v exec sql: %s args: %+v\n", err, query, args)
  })
}

func main() {
  current := time.Now()
  id, err := db.InsertWithInsertedIdContext(
    context.Background(),
    `users`,
    helper.Columns{"user_name", "nickname", "passwd", "is_on", "created_at", "updated_at"},
    helper.Row{"user1", "nickname1", strings.Repeat("1", 32), 1, time.Now().Unix(), time.Now().Format(time.DateTime)},
  )
  if err != nil {
    t.Fatalf("insert data failed with error: %v\n", err)
  }

  t.Logf("insert data with id: %d\n", id)

  user, err := gomysql.FindById(db.Executor(), id, DefaultUserModel)
  if err != nil {
    panic(err)
  }

  fmt.Printf("UserInfo: %+v\n", user)
}

type UserModel struct {
  Id          int64
  UserName    string
  NickName    string
  Passwd      string
  Email       string
  Mobile      string
  IsOn        uint8
  CreatedAt   int64
  UpdatedAt   time.Time
  LastLoginAt time.Time
  Remark      string
}

func (um *UserModel) PrimaryKey() string {
  return `id`
}

func (um *UserModel) TableName(args ...any) string {
  return `users`
}

func (um *UserModel) NewModel() gomysql.Model {
  return &UserModel{}
}

func (um *UserModel) Assemble(br gomysql.BytesRecord) {
  fmt.Printf("updated_at:%s\n", br.String("updated_at"))
  um.Id = br.ToInt64("id")
  um.UserName = br.String("user_name")
  um.NickName = br.String("nickname")
  um.Passwd = br.String("passwd")
  um.Email = br.String("email")
  um.Mobile = br.String("mobile")
  um.IsOn = br.ToUint8("is_on")
  um.CreatedAt = br.ToInt64("created_at")
  um.UpdatedAt, _ = time.Parse(time.DateTime, br.String("updated_at"))
  um.LastLoginAt, _ = time.Parse(time.DateTime, br.String("last_login_at"))
  um.Remark = br.String("remark")
}

Select
package main

import (
	"testing"
	"time"

	"github.com/grpc-boot/gomysql/condition"
	"github.com/grpc-boot/gomysql/helper"
)

func TestDb_Find(t *testing.T) {
	// SELECT * FROM users WHERE id=1
	query := helper.AcquireQuery().
		From(`users`).
		Where(condition.Equal{"id", 1})

	defer query.Close()

	record, err := db.FindOne(query)
	if err != nil {
		t.Fatalf("want nil, got %v", err)
	}
	t.Logf("record: %+v\n", record)

	// SELECT * FROM users WHERE id IN(1, 2)
	query1 := helper.AcquireQuery().
		From(`users`).
		Where(condition.In[int]{"id", []int{1, 2}})
	defer query1.Close()

	records, err := db.FindTimeout(time.Second*2, query1)
	if err != nil {
		t.Fatalf("want nil, got %v", err)
	}
	t.Logf("records: %+v\n", records)

	// SELECT * FROM users WHERE user_name LIKE 'user%' AND created_at>= timestamp
	query2 := helper.AcquireQuery().
		From(`users`).
		Where(condition.And{
			condition.BeginWith{"user_name", "user"},
			condition.Gte{"created_at", time.Now().Add(-7 * 24 * time.Hour).Unix()},
		})
	defer query2.Close()

	records, err = db.FindTimeout(time.Second*2, query2)
	if err != nil {
		t.Fatalf("want nil, got %v", err)
	}
	t.Logf("records: %+v\n", records)

	// SELECT * FROM users WHERE (user_name LIKE 'animal' AND created_at BETWEEN timestamp1 AND timestamp2) OR user_name LIKE 'user%'
	query3 := helper.AcquireQuery().
		From(`users`).
		Where(condition.Or{
			condition.And{
				condition.BeginWith{"user_name", "animal"},
				condition.Between{"created_at", time.Now().Add(-30 * 7 * 24 * time.Hour).Unix(), time.Now().Unix()},
			},
			condition.BeginWith{"user_name", "user"},
		})
	defer query3.Close()

	records, err = db.FindTimeout(time.Second*2, query3)
	if err != nil {
		t.Fatalf("want nil, got %v", err)
	}
	t.Logf("records: %+v\n", records)
}
Insert
package main

import (
	"context"
	"strings"
	"testing"
	"time"

	"github.com/grpc-boot/gomysql/condition"
	"github.com/grpc-boot/gomysql/helper"
)

func TestDb_Insert(t *testing.T) {
  id, err := db.InsertWithInsertedIdContext(
    context.Background(),
    `users`,
    helper.Columns{"user_name", "nickname", "passwd", "is_on", "created_at", "updated_at"},
    helper.Row{"user1", "nickname1", strings.Repeat("1", 32), 1, time.Now().Unix(), time.Now().Format(time.DateTime)},
  )
  if err != nil {
    t.Fatalf("insert data failed with error: %v\n", err)
  }

  t.Logf("insert data with id: %d\n", id)
}
Update
package main

import (
	"context"
	"testing"
	"time"

	"github.com/grpc-boot/gomysql/condition"
	"github.com/grpc-boot/gomysql/helper"
)

func TestDb_Update(t *testing.T) {
  rows, err := db.UpdateWithRowsAffectedContext(
    context.Background(),
    `users`,
    `last_login_at=?`,
    condition.Equal{Field: "id", Value: 1},
    time.Now().Format(time.DateTime),
  )

  if err != nil {
    t.Fatalf("update data failed with error: %v\n", err)
  }

  t.Logf("update data rows affected: %d", rows)
}
Delete
package main

import (
	"context"
	"testing"
	"time"

	"github.com/grpc-boot/gomysql/condition"
	"github.com/grpc-boot/gomysql/helper"
)

func TestDb_Delete(t *testing.T) {
  ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  defer cancel()
  rows, err := db.DeleteWithRowsAffectedContext(
    ctx,
    `users`,
    condition.Equal{Field: "id", Value: 1},
  )

  if err != nil {
    t.Fatalf("delete data failed with error: %v\n", err)
  }
  t.Logf("delete data rows affected: %d", rows)
}
Transaction
package main

import (
	"context"
	"testing"
	"time"
	
	"github.com/grpc-boot/gomysql"
	"github.com/grpc-boot/gomysql/condition"
	"github.com/grpc-boot/gomysql/helper"
)

func TestDb_BeginTx(t *testing.T) {
  ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
  defer cancel()
  tx, err := db.BeginTx(ctx, nil)
  if err != nil {
    t.Fatalf("begin failed with error: %v", err)
  }

  query := helper.AcquireQuery().
    From(`users`).
    Where(condition.Equal{"id", 1})
  defer query.Close()
  records, err := gomysql.Find(tx, query)
  if err != nil {
    tx.Rollback()
    t.Fatalf("query failed with error: %v", err)
  }

  if len(records) != 1 {
    tx.Rollback()
    t.Fatal("row not exists")
  }

  res, err := gomysql.Update(tx, `users`, "updated_at=?", condition.Equal{"updated_at", records[0].String("updated_at")}, time.Now().Format(time.DateTime))
  if err != nil {
    tx.Rollback()
    t.Fatalf("update failed with error: %v", err)
  }

  tx.Commit()
  count, _ := res.RowsAffected()
  t.Logf("updated count: %d", count)
}
Read-Write-Splitting

支持failover和failback

package main

import (
  "testing"

  "github.com/grpc-boot/gomysql"
  "github.com/grpc-boot/gomysql/condition"
)

func TestPool_Random(t *testing.T) {
	opt := gomysql.PoolOptions{
		Masters: []gomysql.Options{
			{
				Host:     "127.0.0.1",
				Port:     3306,
				DbName:   "users",
				UserName: "root",
				Password: "12345678",
			},
			{
				Host:     "127.0.0.1",
				Port:     3306,
				DbName:   "users",
				UserName: "root",
				Password: "12345678",
			},
		},
		Slaves: []gomysql.Options{
			{
				Host:     "127.0.0.1",
				Port:     3306,
				DbName:   "users",
				UserName: "root",
				Password: "12345678",
			},
			{
				Host:     "127.0.0.1",
				Port:     3306,
				DbName:   "users",
				UserName: "root",
				Password: "12345678",
			},
			{
				Host:     "127.0.0.1",
				Port:     3306,
				DbName:   "users",
				UserName: "root",
				Password: "12345678",
			},
		},
	}

	pool, err := gomysql.NewPool(opt)
	if err != nil {
		t.Fatalf("want nil, got %v", err)
	}

	query := helper.AcquireQuery().
		From(`users`).
		Where(condition.Equal{"id", 1})
	defer query.Close()

    record, err := pool.FindOne(gomysql.TypeMaster, query)
    if err != nil {
      t.Fatalf("find one error: %v", err)
    }
    t.Logf("query records: %+v", record)
  
    record, err = pool.FindOne(gomysql.TypeSlave, query)
    if err != nil {
      t.Fatalf("find one error: %v", err)
    }
    t.Logf("query records: %+v", record)
}
Sql-Log
package main

import (
	"fmt"
	"time"

	"github.com/grpc-boot/gomysql"
)

func init() {
  // 输出sql和参数到标准输入,修改func定制自己的日志,方便分析sql
  gomysql.SetLogger(func(query string, args ...any) {
    fmt.Printf("%s exec sql: %s args: %+v\n", time.Now().Format(time.DateTime), query, args)
  })

  // 记录错误日志
  gomysql.SetErrorLog(func(err error, query string, args ...any) {
    fmt.Printf("error: %v exec sql: %s args: %+v\n", err, query, args)
  })
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BytesRecords2Models added in v1.0.3

func BytesRecords2Models[T Model](brs []BytesRecord, model T) []T

func DealNotRowsError added in v1.1.0

func DealNotRowsError(err error) error

func Delete

func Delete(db Executor, table string, condition condition.Condition) (sql.Result, error)

func DeleteContext

func DeleteContext(ctx context.Context, db Executor, table string, condition condition.Condition) (sql.Result, error)

func DeleteWithRowsAffectedContext added in v1.1.0

func DeleteWithRowsAffectedContext(ctx context.Context, db Executor, table string, condition condition.Condition) (rows int64, err error)

func Exec

func Exec(db Executor, query string, args ...any) (sql.Result, error)

func ExecContext

func ExecContext(ctx context.Context, db Executor, query string, args ...any) (res sql.Result, err error)

func ExecWithInsertedIdContext added in v1.1.0

func ExecWithInsertedIdContext(ctx context.Context, db Executor, query string, args ...any) (insertedId int64, err error)

func ExecWithRowsAffectedContext added in v1.1.0

func ExecWithRowsAffectedContext(ctx context.Context, db Executor, query string, args ...any) (rows int64, err error)

func FindAll added in v1.0.6

func FindAll[T DbModel](db Executor, con condition.Condition, model T, args ...any) ([]T, error)

func FindAllTimeoutWithPool added in v1.0.8

func FindAllTimeoutWithPool[T DbModel](timeout time.Duration, pool *Pool, dbType DbType, con condition.Condition, model T, args ...any) ([]T, error)

func FindAllWithPoolContext added in v1.0.8

func FindAllWithPoolContext[T DbModel](ctx context.Context, pool *Pool, dbType DbType, con condition.Condition, model T, args ...any) ([]T, error)

func FindById added in v1.0.6

func FindById[T DbModel](db Executor, id int64, model T, args ...any) (T, error)

func FindByIdTimeoutWithPool added in v1.0.8

func FindByIdTimeoutWithPool[T DbModel](timeout time.Duration, pool *Pool, dbType DbType, id int64, model T, args ...any) (T, error)

func FindByIdWithPoolContext added in v1.0.8

func FindByIdWithPoolContext[T DbModel](ctx context.Context, pool *Pool, dbType DbType, id int64, model T, args ...any) (T, error)

func FindModel added in v1.0.4

func FindModel[T Model](model T, db Executor, q *helper.Query) (T, error)

func FindModelByPoolContext added in v1.0.8

func FindModelByPoolContext[T Model](ctx context.Context, dbType DbType, model T, pool *Pool, q *helper.Query) (m T, err error)

func FindModelByPoolTimeout added in v1.0.8

func FindModelByPoolTimeout[T Model](timeout time.Duration, dbType DbType, model T, pool *Pool, q *helper.Query) (m T, err error)

func FindModelContext added in v1.0.4

func FindModelContext[T Model](ctx context.Context, model T, db Executor, q *helper.Query) (m T, err error)

func FindModelTimeout added in v1.0.4

func FindModelTimeout[T Model](timeout time.Duration, model T, db Executor, q *helper.Query) (T, error)

func FindModels added in v1.0.4

func FindModels[T Model](model T, db Executor, q *helper.Query) ([]T, error)

func FindModelsByPoolContext added in v1.0.8

func FindModelsByPoolContext[T Model](ctx context.Context, dbType DbType, model T, pool *Pool, q *helper.Query) ([]T, error)

func FindModelsByPoolTimeout added in v1.0.8

func FindModelsByPoolTimeout[T Model](timeout time.Duration, dbType DbType, model T, pool *Pool, q *helper.Query) ([]T, error)

func FindModelsContext added in v1.0.4

func FindModelsContext[T Model](ctx context.Context, model T, db Executor, q *helper.Query) ([]T, error)

func FindModelsTimeout added in v1.0.4

func FindModelsTimeout[T Model](timeout time.Duration, model T, db Executor, q *helper.Query) ([]T, error)

func Insert

func Insert(db Executor, table string, columns helper.Columns, rows ...helper.Row) (sql.Result, error)

func InsertContext

func InsertContext(ctx context.Context, db Executor, table string, columns helper.Columns, rows ...helper.Row) (sql.Result, error)

func InsertWithInsertedIdContext added in v1.1.0

func InsertWithInsertedIdContext(ctx context.Context, db Executor, table string, columns helper.Columns, row helper.Row) (id int64, err error)

func InsertWithRowsAffectedContext added in v1.1.0

func InsertWithRowsAffectedContext(ctx context.Context, db Executor, table string, columns helper.Columns, rows ...helper.Row) (rowsAffected int64, err error)

func Query

func Query(db Executor, query string, args ...any) (*sql.Rows, error)

func QueryContext

func QueryContext(ctx context.Context, db Executor, query string, args ...any) (rows *sql.Rows, err error)

func QueryRow added in v1.0.6

func QueryRow(db Executor, query string, args ...any) *sql.Row

func QueryRowContext added in v1.0.6

func QueryRowContext(ctx context.Context, db Executor, query string, args ...any) (row *sql.Row)

func ScanModel added in v1.0.3

func ScanModel[T Model](model T, rows *sql.Rows, err error) ([]T, error)

func Select

func Select(db Executor, q *helper.Query) (*sql.Rows, error)

func SelectContext

func SelectContext(ctx context.Context, db Executor, q *helper.Query) (*sql.Rows, error)

func SetErrorLog added in v1.1.0

func SetErrorLog(l ErrLog)

func SetLogger added in v1.0.2

func SetLogger(l LogSql)

func Update

func Update(db Executor, table, setters string, condition condition.Condition, setterArgs ...any) (sql.Result, error)

func UpdateContext

func UpdateContext(ctx context.Context, db Executor, table, setters string, condition condition.Condition, setterArgs ...any) (sql.Result, error)

func UpdateWithRowsAffectedContext added in v1.1.0

func UpdateWithRowsAffectedContext(ctx context.Context, db Executor, table, setters string, condition condition.Condition, setterArgs ...any) (rows int64, err error)

Types

type BytesRecord added in v1.0.3

type BytesRecord map[string][]byte

func ScanBytesRecords added in v1.0.3

func ScanBytesRecords(rows *sql.Rows, err error) ([]BytesRecord, error)

func (BytesRecord) Bytes added in v1.0.3

func (br BytesRecord) Bytes(key string) []byte

func (BytesRecord) Clone added in v1.0.6

func (br BytesRecord) Clone() BytesRecord

func (BytesRecord) Exists added in v1.0.3

func (br BytesRecord) Exists(key string) bool

func (BytesRecord) String added in v1.0.3

func (br BytesRecord) String(key string) string

func (BytesRecord) ToBool added in v1.0.3

func (br BytesRecord) ToBool(key string) bool

func (BytesRecord) ToFloat64 added in v1.0.3

func (br BytesRecord) ToFloat64(key string) float64

func (BytesRecord) ToInt added in v1.0.3

func (br BytesRecord) ToInt(key string) int

func (BytesRecord) ToInt32 added in v1.0.3

func (br BytesRecord) ToInt32(key string) int32

func (BytesRecord) ToInt64 added in v1.0.3

func (br BytesRecord) ToInt64(key string) int64

func (BytesRecord) ToInt8 added in v1.0.3

func (br BytesRecord) ToInt8(key string) int8

func (BytesRecord) ToRecord added in v1.0.5

func (br BytesRecord) ToRecord() Record

func (BytesRecord) ToUint32 added in v1.0.3

func (br BytesRecord) ToUint32(key string) uint32

func (BytesRecord) ToUint64 added in v1.0.3

func (br BytesRecord) ToUint64(key string) uint64

func (BytesRecord) ToUint8 added in v1.0.3

func (br BytesRecord) ToUint8(key string) uint8

type Db

type Db struct {
	// contains filtered or unexported fields
}

func NewDb

func NewDb(opt Options) (*Db, error)

func (*Db) AcquireQuery

func (db *Db) AcquireQuery() *helper.Query

func (*Db) Begin

func (db *Db) Begin() (tx *sql.Tx, err error)

func (*Db) BeginTx

func (db *Db) BeginTx(ctx context.Context, opts *sql.TxOptions) (tx *sql.Tx, err error)

func (*Db) Delete

func (db *Db) Delete(table string, where condition.Condition) (sql.Result, error)

func (*Db) DeleteContext

func (db *Db) DeleteContext(ctx context.Context, table string, where condition.Condition) (sql.Result, error)

func (*Db) DeleteWithRowsAffectedContext added in v1.1.0

func (db *Db) DeleteWithRowsAffectedContext(ctx context.Context, table string, where condition.Condition) (rows int64, err error)

func (*Db) Executor added in v1.1.0

func (db *Db) Executor() Executor

func (*Db) Find

func (db *Db) Find(q *helper.Query) (records []Record, err error)

func (*Db) FindContext

func (db *Db) FindContext(ctx context.Context, q *helper.Query) (records []Record, err error)

func (*Db) FindOne

func (db *Db) FindOne(q *helper.Query) (Record, error)

func (*Db) FindOneContext

func (db *Db) FindOneContext(ctx context.Context, q *helper.Query) (Record, error)

func (*Db) FindOneTimeout

func (db *Db) FindOneTimeout(timeout time.Duration, q *helper.Query) (Record, error)

func (*Db) FindTimeout

func (db *Db) FindTimeout(timeout time.Duration, q *helper.Query) (records []Record, err error)

func (*Db) Insert

func (db *Db) Insert(table string, columns helper.Columns, rows ...helper.Row) (sql.Result, error)

func (*Db) InsertContext

func (db *Db) InsertContext(ctx context.Context, table string, columns helper.Columns, rows ...helper.Row) (sql.Result, error)

func (*Db) InsertWithInsertedIdContext added in v1.1.0

func (db *Db) InsertWithInsertedIdContext(ctx context.Context, table string, columns helper.Columns, row helper.Row) (id int64, err error)

func (*Db) InsertWithInsertedIdTimeout added in v1.1.0

func (db *Db) InsertWithInsertedIdTimeout(timeout time.Duration, table string, columns helper.Columns, row helper.Row) (id int64, err error)

func (*Db) Options

func (db *Db) Options() Options

func (*Db) Pool

func (db *Db) Pool() *sql.DB

func (*Db) Update

func (db *Db) Update(table string, setter string, where condition.Condition, setterArgs ...any) (sql.Result, error)

func (*Db) UpdateContext

func (db *Db) UpdateContext(ctx context.Context, table string, setter string, where condition.Condition, setterArgs ...any) (sql.Result, error)

func (*Db) UpdateWithRowsAffectedContext added in v1.1.0

func (db *Db) UpdateWithRowsAffectedContext(ctx context.Context, table string, setter string, where condition.Condition, setterArgs ...any) (rows int64, err error)

type DbModel added in v1.0.6

type DbModel interface {
	Model
	PrimaryKey() string
	TableName(args ...any) string
}

type DbType

type DbType uint8
const (
	TypeMaster DbType = 0
	TypeSlave  DbType = 1
)

type ErrLog added in v1.1.0

type ErrLog func(err error, query string, args ...any)

type Executor

type Executor interface {
	Query(query string, args ...any) (*sql.Rows, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRow(query string, args ...any) *sql.Row
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
	Exec(query string, args ...any) (sql.Result, error)
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}

type LogSql added in v1.0.2

type LogSql func(query string, args ...any)

type Model added in v1.0.3

type Model interface {
	NewModel() Model
	Assemble(br BytesRecord)
}

type Options

type Options struct {
	DbName                string `json:"dbName" yaml:"dbName"`
	Host                  string `json:"host" yaml:"host"`
	Port                  uint32 `json:"port" yaml:"port"`
	UserName              string `json:"userName" yaml:"userName"`
	Password              string `json:"password" yaml:"password"`
	CharSet               string `json:"charSet" yaml:"charSet"`
	MaxIdleConns          int    `json:"maxIdleConns" yaml:"maxIdleConns"`
	MaxOpenConns          int    `json:"maxOpenConns" yaml:"maxOpenConns"`
	ConnMaxIdleTimeSecond int64  `json:"connMaxIdleTimeSecond" yaml:"connMaxIdleTimeSecond"`
	ConnMaxLifetimeSecond int64  `json:"connMaxLifetimeSecond" yaml:"connMaxLifetimeSecond"`
}

func DefaultMysqlOption

func DefaultMysqlOption() Options

func (*Options) ConnMaxIdleTime

func (o *Options) ConnMaxIdleTime() time.Duration

func (*Options) ConnMaxLifetime

func (o *Options) ConnMaxLifetime() time.Duration

func (*Options) Dsn

func (o *Options) Dsn() string

type Pool

type Pool struct {
	// contains filtered or unexported fields
}

func NewPool

func NewPool(opt PoolOptions, checkInterval time.Duration) (*Pool, error)

func (*Pool) AcquireQuery added in v1.0.6

func (p *Pool) AcquireQuery() *helper.Query

func (*Pool) Begin added in v1.0.6

func (p *Pool) Begin() (tx *sql.Tx, err error)

func (*Pool) BeginTx added in v1.0.6

func (p *Pool) BeginTx(ctx context.Context, opts *sql.TxOptions) (tx *sql.Tx, err error)

func (*Pool) Close added in v1.0.6

func (p *Pool) Close() error

func (*Pool) Delete added in v1.0.6

func (p *Pool) Delete(table string, where condition.Condition) (sql.Result, error)

func (*Pool) DeleteContext added in v1.0.6

func (p *Pool) DeleteContext(ctx context.Context, table string, where condition.Condition) (result sql.Result, err error)

func (*Pool) DeleteWithRowsAffectedContext added in v1.1.0

func (p *Pool) DeleteWithRowsAffectedContext(ctx context.Context, table string, where condition.Condition) (rows int64, err error)

func (*Pool) Find added in v1.0.6

func (p *Pool) Find(dbType DbType, q *helper.Query) (records []Record, err error)

func (*Pool) FindContext added in v1.0.6

func (p *Pool) FindContext(ctx context.Context, dbType DbType, q *helper.Query) (records []Record, err error)

func (*Pool) FindOne added in v1.0.6

func (p *Pool) FindOne(dbType DbType, q *helper.Query) (Record, error)

func (*Pool) FindOneContext added in v1.0.6

func (p *Pool) FindOneContext(ctx context.Context, dbType DbType, q *helper.Query) (r Record, err error)

func (*Pool) FindOneTimeout added in v1.0.6

func (p *Pool) FindOneTimeout(timeout time.Duration, dbType DbType, q *helper.Query) (Record, error)

func (*Pool) FindTimeout added in v1.0.6

func (p *Pool) FindTimeout(timeout time.Duration, dbType DbType, q *helper.Query) (records []Record, err error)

func (*Pool) Insert added in v1.0.6

func (p *Pool) Insert(table string, columns helper.Columns, rows ...helper.Row) (sql.Result, error)

func (*Pool) InsertContext added in v1.0.6

func (p *Pool) InsertContext(ctx context.Context, table string, columns helper.Columns, rows ...helper.Row) (result sql.Result, err error)

func (*Pool) InsertWithInsertedIdContext added in v1.1.0

func (p *Pool) InsertWithInsertedIdContext(ctx context.Context, table string, columns helper.Columns, row helper.Row) (id int64, err error)

func (*Pool) Rand added in v1.0.9

func (p *Pool) Rand(dbType DbType) *Db

func (*Pool) RandExecutor added in v1.1.0

func (p *Pool) RandExecutor(dbType DbType) Executor

func (*Pool) Update added in v1.0.6

func (p *Pool) Update(table string, setter string, where condition.Condition, setterArgs ...any) (sql.Result, error)

func (*Pool) UpdateContext added in v1.0.6

func (p *Pool) UpdateContext(ctx context.Context, table string, setter string, where condition.Condition, setterArgs ...any) (result sql.Result, err error)

func (*Pool) UpdateWithRowsAffectedContext added in v1.1.0

func (p *Pool) UpdateWithRowsAffectedContext(ctx context.Context, table string, setter string, where condition.Condition, setterArgs ...any) (rows int64, err error)

type PoolOptions

type PoolOptions struct {
	Masters []Options `json:"masters" yaml:"masters"`
	Slaves  []Options `json:"slaves" yaml:"slaves"`
}

type Record

type Record map[string]string

func Find

func Find(db Executor, q *helper.Query) (records []Record, err error)

func FindContext

func FindContext(ctx context.Context, db Executor, q *helper.Query) (records []Record, err error)

func FindOne

func FindOne(db Executor, q *helper.Query) (Record, error)

func FindOneContext

func FindOneContext(ctx context.Context, db Executor, q *helper.Query) (Record, error)

func FindOneTimeout

func FindOneTimeout(timeout time.Duration, db Executor, q *helper.Query) (Record, error)

func FindTimeout

func FindTimeout(timeout time.Duration, db Executor, q *helper.Query) (records []Record, err error)

func Scan

func Scan(rows *sql.Rows, err error) ([]Record, error)

func (Record) Clone added in v1.0.6

func (r Record) Clone() Record

func (Record) Exists

func (r Record) Exists(key string) bool

func (Record) String

func (r Record) String(key string) string

func (Record) ToBool

func (r Record) ToBool(key string) bool

func (Record) ToBytes

func (r Record) ToBytes(key string) []byte

func (Record) ToBytesRecord added in v1.0.5

func (r Record) ToBytesRecord() BytesRecord

func (Record) ToFloat64

func (r Record) ToFloat64(key string) float64

func (Record) ToInt

func (r Record) ToInt(key string) int

func (Record) ToInt32

func (r Record) ToInt32(key string) int32

func (Record) ToInt64

func (r Record) ToInt64(key string) int64

func (Record) ToInt8

func (r Record) ToInt8(key string) int8

func (Record) ToUint32

func (r Record) ToUint32(key string) uint32

func (Record) ToUint64

func (r Record) ToUint64(key string) uint64

func (Record) ToUint8

func (r Record) ToUint8(key string) uint8

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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