edb

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2021 License: MIT Imports: 7 Imported by: 0

README

edb

Package edb simple and convenient operation of database data table, structure mapping

  • now only supports MySQL
  • todo ...

usage

package main

import (
    "github.com/RLOFLS/edb"
    "fmt"
    "log"
    "time"

    _ "github.com/go-sql-driver/mysql"
)

func main() {

    edb.AddConfig("default", &edb.Config{
        Driver: "mysql", 
        Host: "127.0.0.1", 
        Port: "3306", 
        Username: "root", 
        Password: "12345678", 
        Database: "test", 
        Charset: "utf8"
    })
    //start
    edb.Boot("default")

    //define structure corresponds to the data table
    //naming rules:
    //database : user_config   => struct : UserConfig
    type User struct {
        Id        int `type:"autoPk"`
        Name      string
        Age       int
        CreatedAt time.Time `type:"dateTime"`
        UpdatedAt time.Time `type:"dateTime"`
    }

    lf := func(err error) {
        if err != nil {
            log.Fatal(err)
        }
    }

    //Insert
    fmt.Println("---Insert----")
    t, _ := time.ParseInLocation(edb.FTimeDateTime, "2021-01-01 01:01:01", time.Local)
    m, err := edb.New(&User{
        Name:      "Test",
        Age:       222,
        CreatedAt: t,
        UpdatedAt: t,
    })
    lf(err)
    id, err := m.Insert()
    lf(err)
    fmt.Println("last insert id:", id)

    //Select support Eq, Lt, Lte, Gt, Gte, Like, OrderBy, OrderByDesc chain opreation
    // eg: m.Eq("name", "a").Gt("age", 22)
    fmt.Println("---Select----")
    m2, err := edb.New(&User{})
    lf(err)
    i2, err := m2.Eq("name", "test").First()
    lf(err)
    user2 := i2.(*User)
    fmt.Printf("Select user: userName: %s, age: %d, createTime: %s\n", user2.Name, user2.Age, user2.CreatedAt.Format(edb.FTimeDateTime))

    //Get all
    fmt.Println("---Get----")
    m3, err := edb.New(&User{})
    lf(err)
    collect3, err := m3.Eq("name", "test").Get()
    lf(err)
    for collect3.Next() {
        u := collect3.Item()
        user3 := u.(*User)
        fmt.Printf("Get User: userName: %s, age: %d, createTime: %s\n", user3.Name, user3.Age, user3.CreatedAt.Format(edb.FTimeDateTime))
    }

    //Paginate
    fmt.Println("---Paginate----")
    m4, err := edb.New(&User{})
    lf(err)
    collect4, err := m4.Like("name", "%t%").OrderByDesc("created_at").Paginate(1, 10)
    lf(err)
    fmt.Printf("Paginate User: total count: %d\n", collect4.Total())
    for collect4.Next() {
        u := collect4.Item()
        user4 := u.(*User)
        fmt.Printf("Paginate User: userName: %s, age: %d, createTime: %s\n", user4.Name, user4.Age, user4.CreatedAt.Format(edb.FTimeDateTime))
    }

    //Update
    fmt.Println("---Update----")
    m5, err := edb.New(&User{
        Id:        1,
        Name:      "ttttt",
        Age:       111,
        UpdatedAt: time.Now(),
    })
    lf(err)
    //default pk as where condition => where id=1
    rowAffected, err := m5.Update([]string{"name", "age", "created_at"})
    lf(err)
    fmt.Printf("Update User: rowAffected : %d\n", rowAffected)

    //Delete
    fmt.Println("---Delete----")
    m6, err := edb.New(&User{})
    lf(err)
    rowAffected2, err := m6.Eq("name", "ttttt").Delete()
    lf(err)
    fmt.Printf("Delete User: rowAffected : %d\n", rowAffected2)

    //customize structure mapping, just query
    fmt.Println("---customize structure mapping----")
    type UserCount struct {
        UserName string
        Total    int
    }
    m7, err := edb.New(&UserCount{})
    lf(err)
    prepareSQL := "SELECT `name` AS user_name, count(*) AS total FROM `user` GROUP BY `name`"
    collect7, err := m7.QueryCollect(prepareSQL)
    lf(err)
    for collect7.Next() {
        i := collect7.Item()
        userCount := i.(*UserCount)
        fmt.Printf("userName: %s, count: %d\n", userCount.UserName, userCount.Total)
    }

    //and more usage see package test file

}

Documentation

Overview

Package edb simple and convenient operation of database data table, structure mapping

Example:

package main

import (
	"github.com/RLOFLS/edb"
	"fmt"
	"log"
	"time"

	_ "github.com/go-sql-driver/mysql"
)

func main() {

  //start
  edb.AddConfig("default", &edb.Config{Driver: "mysql", Host: "127.0.0.1", Port: "3306", Username: "root", Password: "12345678", Database: "test", Charset: "utf8"})
  edb.Boot("default")

  //define structure corresponds to the data table
  //naming rules:
  //database : user_config   => struct : UserConfig
  type User struct {
  	Id        int `type:"autoPk"`
  	Name      string
  	Age       int
  	CreatedAt time.Time `type:"dateTime"`
  	UpdatedAt time.Time `type:"dateTime"`
  }

  lf := func(err error) {
  	if err != nil {
  		log.Fatal(err)
  	}
  }

  //Insert
  fmt.Println("---Insert----")
  t, _ := time.ParseInLocation(edb.FTimeDateTime, "2021-01-01 01:01:01", time.Local)
  m, err := edb.New(&User{
  	Name:      "Test",
  	Age:       222,
  	CreatedAt: t,
  	UpdatedAt: t,
  })
  lf(err)
  id, err := m.Insert()
  lf(err)
  fmt.Println("last insert id:", id)

  //Select support Eq, Lt, Lte, Gt, Gte, Like, OrderBy, OrderByDesc chain opreation
  // eg: m.Eq("name", "a").Gt("age", 22)
  fmt.Println("---Select----")
  m2, err := edb.New(&User{})
  lf(err)
  i2, err := m2.Eq("name", "test").First()
  lf(err)
  user2 := i2.(*User)
  fmt.Printf("Select user: userName: %s, age: %d, createTime: %s\n", user2.Name, user2.Age, user2.CreatedAt.Format(edb.FTimeDateTime))

  //Get all
  fmt.Println("---Get----")
  m3, err := edb.New(&User{})
  lf(err)
  collect3, err := m3.Eq("name", "test").Get()
  lf(err)
  for collect3.Next() {
  	u := collect3.Item()
  	user3 := u.(*User)
  	fmt.Printf("Get User: userName: %s, age: %d, createTime: %s\n", user3.Name, user3.Age, user3.CreatedAt.Format(edb.FTimeDateTime))
  }

  //Paginate
  fmt.Println("---Paginate----")
  m4, err := edb.New(&User{})
  lf(err)
  collect4, err := m4.Like("name", "%t%").OrderByDesc("created_at").Paginate(1, 10)
  lf(err)
  fmt.Printf("Paginate User: total count: %d\n", collect4.Total())
  for collect4.Next() {
  	u := collect4.Item()
  	user4 := u.(*User)
  	fmt.Printf("Paginate User: userName: %s, age: %d, createTime: %s\n", user4.Name, user4.Age, user4.CreatedAt.Format(edb.FTimeDateTime))
  }

  //Update
  fmt.Println("---Update----")
  m5, err := edb.New(&User{
  	Id:        1,
  	Name:      "ttttt",
  	Age:       111,
  	UpdatedAt: time.Now(),
  })
  lf(err)
  //default pk as where condition => where id=1
  rowAffected, err := m5.Update([]string{"name", "age", "created_at"})
  lf(err)
  fmt.Printf("Update User: rowAffected : %d\n", rowAffected)

  //Delete
  fmt.Println("---Delete----")
  m6, err := edb.New(&User{})
  lf(err)
  rowAffected2, err := m6.Eq("name", "ttttt").Delete()
  lf(err)
  fmt.Printf("Delete User: rowAffected : %d\n", rowAffected2)

  //customize structure mapping, just query
  fmt.Println("---customize structure mapping----")
  type UserCount struct {
  	UserName string
  	Total    int
  }
  m7, err := edb.New(&UserCount{})
  lf(err)
  prepareSQL := "SELECT `name` AS user_name, count(*) AS total FROM `user` GROUP BY `name`"
  collect7, err := m7.QueryCollect(prepareSQL)
  lf(err)
  for collect7.Next() {
  	i := collect7.Item()
  	userCount := i.(*UserCount)
  	fmt.Printf("userName: %s, count: %d\n", userCount.UserName, userCount.Total)
  }

  //and more usage see package test file

}

Index

Constants

View Source
const (
	// OPSelect select
	OPSelect = iota
	// OPDelete delete
	OPDelete
	// OPUpdate update
	OPUpdate
	// OPInsert insert
	OPInsert
)
View Source
const (
	TagAutoPK   = "autoPk"
	TagPK       = "pk"
	TagDate     = "date"
	TagDateTime = "dateTime"
	TagTime     = "time"

	FTimeTime     = "15:04:05"
	FTimeDate     = "2006-01-02"
	FTimeDateTime = "2006-01-02 15:04:05"
)

structrue tag time formatting

View Source
const DriverMysql = "mysql"

DriverMysql driver support

Variables

This section is empty.

Functions

func AddConfig

func AddConfig(connectName string, config *Config) bool

AddConfig add database connection configuration

func Boot

func Boot(connectName string)

Boot start up

Types

type Builder

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

Builder builder

func NewBuilder

func NewBuilder() *Builder

NewBuilder new builder

func (*Builder) OrderBy

func (b *Builder) OrderBy(field string)

OrderBy ASC sort

func (*Builder) OrderByDesc

func (b *Builder) OrderByDesc(field string)

OrderByDesc DESC sort

func (*Builder) Select

func (b *Builder) Select(fields []string) error

Select select field

func (*Builder) Update

func (b *Builder) Update(updateFields []string)

Update update opreate, pass the fields that need to be updated

func (*Builder) WhereCondition

func (b *Builder) WhereCondition(field string, condition string, value interface{}) error

WhereCondition where condition

type Collect

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

Collect collect

func (*Collect) Err

func (c *Collect) Err() error

Err get err

func (*Collect) Item

func (c *Collect) Item() interface{}

Item get the value of the current iteration mapping

func (*Collect) Next

func (c *Collect) Next() bool

Next iterative data, if return true , call Item() get value calling again will iterate the next item of data

func (*Collect) Total

func (c *Collect) Total() int64

Total get the total number of queries, just Model.Paginate

type Config

type Config struct {
	Driver    string
	Host      string
	Port      string
	Database  string
	Username  string
	Password  string
	Charset   string
	Collation string
}

Config database connect config

func (*Config) DNS

func (c *Config) DNS() string

DNS return dns string

type Field

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

Field field

type Manager

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

Manager magage database connections

func (*Manager) Exec

func (m *Manager) Exec(query string, bindings ...interface{}) (sql.Result, error)

Exec exec

func (*Manager) Query

func (m *Manager) Query(query string, bindings ...interface{}) (*sql.Rows, error)

Query query

func (*Manager) QueryCollect

func (m *Manager) QueryCollect(query string, bindings ...interface{}) (*Collect, error)

QueryCollect query and return *Collect

type Model

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

Model model

func New

func New(entity interface{}) (m *Model, err error)

New new model, and init someting

func (*Model) Delete

func (m *Model) Delete() (rowAffected int64, err error)

Delete delete, if there is no where condition, the pk will be used as the query condition

Example usage: (

m, err := New(&User{
	Id: 1,
})
//default  pk    => where `id` = 1
rowAffected, err := m.Delete()

)

func (*Model) Eq

func (m *Model) Eq(field string, value interface{}) *Model

Eq Eq("name", "tom") => name='tom'

func (*Model) Exec

func (m *Model) Exec(query string, args ...interface{}) (sql.Result, error)

Exec exec and return sql.Resqult

func (*Model) First

func (m *Model) First() (interface{}, error)

First get the first, if there is no where condition, the pk will be used as the query condition

func (*Model) Get

func (m *Model) Get() (collect *Collect, err error)

Get get all, return *Collect if there is no where condition, the pk will be used as the query condition, take out througth for loop

Example usage:

(

	c, err := m.Get()
	if err != nil {
  //...
 }
 for c.Next() {
	 i := c.Item()
	 //...
 }

)

func (*Model) Gt

func (m *Model) Gt(field string, value interface{}) *Model

Gt Gt("age", 1) => `age` > 1

func (*Model) Gte

func (m *Model) Gte(field string, value interface{}) *Model

Gte Gte("age", 1) => `age` >= 1

func (*Model) Insert

func (m *Model) Insert() (id int64, err error)

Insert insert entity

func (*Model) Like

func (m *Model) Like(field string, value interface{}) *Model

Like Like("name", "%sss") => `name` LIKE '%sss'

func (*Model) Lt

func (m *Model) Lt(field string, value interface{}) *Model

Lt Lt("age", 1) => `age` < 1

func (*Model) Lte

func (m *Model) Lte(field string, value interface{}) *Model

Lte Lte("age", 1) => `age` <= 1

func (*Model) Neq

func (m *Model) Neq(field string, value interface{}) *Model

Neq Neq("name", "tom") => name !='tom'

func (*Model) OrderBy

func (m *Model) OrderBy(field string) *Model

OrderBy ASC sort

func (*Model) OrderByDesc

func (m *Model) OrderByDesc(field string) *Model

OrderByDesc DESC sort

func (*Model) Paginate

func (m *Model) Paginate(page int64, pageSize int64) (collect *Collect, err error)

Paginate paginate query, return *Collect, usage as Get()

func (*Model) Query

func (m *Model) Query(query string, args ...interface{}) (*sql.Rows, error)

Query query and return *sql.Rows

func (*Model) QueryCollect

func (m *Model) QueryCollect(query string, args ...interface{}) (collect *Collect, err error)

QueryCollect query and return *Collect

func (*Model) Select

func (m *Model) Select(s []string) *Model

Select select fields

func (*Model) Update

func (m *Model) Update(updateFields []string) (rowAffected int64, err error)

Update update according to rhe passed field, if there is no where condition, the pk will be used as the query condition

Example usage:

(

m, err := New(&User{
	Id:   1,
	Name: "ttt",
	Age:  333,
})
rowAffected, err := m.Update([]string{"name", "age"})

)

type Query

type Query interface {
	// Select
	Select([]string) *Model
	// Eq("name", "tom") => name='tom'
	Eq(field string, value interface{}) *Model
	// Neq("name", "tom") => name !='tom'
	Neq(field string, value interface{}) *Model
	// Lt("age", 1) => `age` < 1
	Lt(field string, value interface{}) *Model
	// Lte("age", 1) => `age` <= 1
	Lte(field string, value interface{}) *Model
	// Gt("age", 1) => `age` > 1
	Gt(field string, value interface{}) *Model
	// Gte("age", 1) => `age` >= 1
	Gte(field string, value interface{}) *Model
	// Like("name", "%sss") => `name` LIKE '%sss'
	Like(field string, value interface{}) *Model
	// Order ASC sort
	OrderBy(string) *Model
	// OrderByDesc DESC sort
	OrderByDesc(string) *Model
	Get() (*Collect, error)
	First() (interface{}, error)
	Paginate(page int64, pageSize int64) (*Collect, error)
	Delete() (rowAffected int64, err error)
	Insert() (id int64, err error)
	Update([]string) (rowAffected int64, err error)
	// todo
	// Transaction(conn string, closure func()) error
	Query(string, ...interface{}) (*sql.Rows, error)
	Exec(string, ...interface{}) (sql.Result, error)
}

Query query

type Stmt

type Stmt interface {
	// Build build sql, and bind parameters
	Build() error
	// PrepareSQL get prepare sql
	PrepareSQL() string
	// Bindings get prepare bind parameters
	Bindings() []interface{}
	// SetBuilder set Builder
	SetBuilder(*Builder)
	// SetOp
	SetOp(operateType)
	// contains filtered or unexported methods
}

Stmt stmt

type StmtMysql

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

StmtMysql nysql stmt

func (*StmtMysql) Bindings

func (sm *StmtMysql) Bindings() []interface{}

Bindings get prepare bind parameters

func (*StmtMysql) Build

func (sm *StmtMysql) Build() error

Build build dql, and bind parameters

func (*StmtMysql) PrepareSQL

func (sm *StmtMysql) PrepareSQL() string

PrepareSQL get prepare sql

func (*StmtMysql) SetBuilder

func (sm *StmtMysql) SetBuilder(b *Builder)

SetBuilder SetBuilder

func (*StmtMysql) SetOp

func (sm *StmtMysql) SetOp(op operateType)

SetOp SetOp

type SupportTypes

type SupportTypes map[string]bool

SupportTypes support driver syntax, unsupported types will not be processed

Jump to

Keyboard shortcuts

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