dal

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2016 License: Apache-2.0 Imports: 3 Imported by: 0

README

GO-DAL

提供基于Golang的数据访问层

获取

$ go get github.com/antlinker/go-dal

针对MySQL数据库的CRUD范例

package main

import (
	"fmt"
	"time"

	"github.com/antlinker/go-dal"
	_ "github.com/antlinker/go-dal/mysql"
)

type Student struct {
	ID       int64
	StuCode  string
	StuName  string
	Sex      int
	Age      int
	Birthday time.Time
	Memo     string
}

func main() {
	dal.RegisterProvider(dal.MYSQL, `{"datasource":"root:123456@tcp(127.0.0.1:3306)/testdb?charset=utf8","maxopen":100,"maxidle":50,"print":true}`)
	insert()
	update()
	delete()
	list()
}

func insert() {
	stud := Student{
		StuCode:  "S001",
		StuName:  "Lyric",
		Sex:      1,
		Age:      25,
		Birthday: time.Now(),
		Memo:     "Message...",
	}
	entity := dal.NewTranAEntity("student", stud).Entity
	result := dal.Exec(entity)
	if err := result.Error; err != nil {
		panic(err)
	}
	fmt.Println("===> Student Insert:", result.Result)
}

func update() {
	stud := map[string]interface{}{
		"StuName": "Lyric01",
		"Sex":     1,
		"Age":     26,
	}
	cond := dal.NewFieldsKvCondition(map[string]interface{}{"StuCode": "S001"}).Condition
	entity := dal.NewTranUEntity("student", stud, cond).Entity
	result := dal.Exec(entity)
	if err := result.Error; err != nil {
		panic(err)
	}
	fmt.Println("===> Student Update:", result.Result)
}

func delete() {
	cond := dal.NewFieldsKvCondition(Student{StuCode: "S001"}).Condition
	entity := dal.NewTranDEntity("student", cond).Entity
	result := dal.Exec(entity)
	if err := result.Error; err != nil {
		panic(err)
	}
	fmt.Println("===> Student Delete:", result.Result)
}

func list() {
	entity := dal.NewQueryEntity("student", dal.QueryCondition{}, "*")().Entity
	var stuData []Student
	err := dal.AssignList(entity, &stuData)
	if err != nil {
		panic(err)
	}
	fmt.Println("===> Student List:", stuData)
}

针对MySQL数据库的事务操作范例

func insertManyData() {
	var entities []dal.TranEntity
	for i := 0; i < 1000; i++ {
		var stu Student
		stu.StuCode = fmt.Sprintf("S-%d", i)
		stu.StuName = fmt.Sprintf("SName-%d", i)
		stu.Birthday = time.Now()
		entities = append(entities, dal.NewTranAEntity("student", stu).Entity)
	}
	result := dal.ExecTrans(entities)
	if err := result.Error; err != nil {
		panic(err)
	}
	fmt.Println("===> Insert data numbers:", result.Result)
}

针对MySQL数据库的分页查询范例

func pager() {
	entity := dal.NewQueryPagerEntity("student",
		dal.NewCondition("where StuCode like ? order by ID", "S-%").Condition,
		dal.NewPagerParam(1, 20),
		"StuCode", "StuName", "Birthday").Entity
	result, err := dal.Pager(entity)
	if err != nil {
		panic(err)
	}
	fmt.Println("===> Query total:")
	fmt.Println(result.Total)
	fmt.Println("===> Query rows:")
	fmt.Println(result.Rows)
}

MySql配置信息

type Config struct {
	// DataSource 数据库连接
	DataSource string `json:"datasource"`
	// MaxOpenConns 打开最大连接数
	MaxOpenConns int `json:"maxopen"`
	// MaxIdleConns 连接池保持连接数量
	MaxIdleConns int `json:"maxidle"`
	// ConnMaxLifetime 连接池的生命周期
	ConnMaxLifetime time.Duration `json:"maxlifetime"`
	// IsPrint 是否打印SQL
	IsPrint bool `json:"print"`
}

License

Copyright 2015.All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidValue = errors.New("Invalid values!")
)

Functions

func AssignList

func AssignList(entity QueryEntity, output interface{}) error

AssignList 将查询结果解析到对应的指针地址 (数据类型包括:[]map[string]string,[]map[string]interface{},[]struct)

func AssignSingle

func AssignSingle(entity QueryEntity, output interface{}) error

AssignSingle 将查询结果解析到对应的指针地址 (数据类型包括:map[string]string,map[string]interface{},struct)

func List

func List(entity QueryEntity) ([]map[string]string, error)

List 查询列表数据

func NewQueryEntity

func NewQueryEntity(table string, cond QueryCondition, fields ...string) func(resultType ...QueryResultType) QueryEntityResult

NewQueryEntity 创建新的查询实体

func Query

func Query(entity QueryEntity) (interface{}, error)

Query 查询数据 (根据QueryResultType返回数据结果类型)

func RegisterDBProvider

func RegisterDBProvider(provideName ProvideEngine, provider DBProvider)

RegisterDBProvider 注册DBProvider

func RegisterProvider

func RegisterProvider(provideName ProvideEngine, config string) error

RegisterProvider 提供全局的provider

func Single

func Single(entity QueryEntity) (map[string]string, error)

Single 查询单条数据

Types

type CondType

type CondType byte

CondType 查询条件类型标识

const (
	COND_KV CondType = iota + 1
	COND_CV
)

type DBProvider

type DBProvider interface {
	Provider
	// InitDB 数据库初始化
	// config 为配置信息(以json字符串的方式提供)
	InitDB(config string) error
}

DBProvider 提供DB初始化

type PagerParam

type PagerParam struct {
	PageIndex int
	PageSize  int
}

PagerParam 分页参数

func NewPagerParam

func NewPagerParam(pageIndex, pageSize int) PagerParam

NewPagerParam 创建新的分页参数

type ProvideEngine

type ProvideEngine string

ProvideEngine 数据库操作引擎

const (
	// MYSQL mysql数据库
	MYSQL ProvideEngine = "mysql"
)

type Provider

type Provider interface {
	QueryProvider
	TranProvider
}

Provider 提供统一的数据库操作

var (
	// GDAL 提供全局的Provider
	GDAL Provider
)

type QueryCondition

type QueryCondition struct {
	CType     CondType
	FieldsKv  map[string]interface{}
	Condition string
	Values    []interface{}
}

QueryCondition 查询条件

type QueryConditionResult

type QueryConditionResult struct {
	ResultError
	Condition QueryCondition
}

ConditionResult 提供查询条件处理

func NewCondition

func NewCondition(condition string, values ...interface{}) QueryConditionResult

NewCondition 获取查询条件 condition 查询条件 values 格式化参数

func NewFieldsKvCondition

func NewFieldsKvCondition(fieldsKv interface{}) QueryConditionResult

NewFieldsKvCondition 获取键值查询条件实例 fieldsKv 数据类型(map[string]interface{} or map[string]string or struct) 如果fieldsKv为struct类型,只保留非零值字段

type QueryEntity

type QueryEntity struct {
	Table        string
	FieldsSelect string
	Condition    QueryCondition
	ResultType   QueryResultType
	PagerParam   PagerParam
}

QueryEntity 提供数据查询结构体

type QueryEntityResult

type QueryEntityResult struct {
	ResultError
	Entity QueryEntity
}

QueryEntityResult 提供查询实体

func NewQueryPagerEntity

func NewQueryPagerEntity(table string, cond QueryCondition, pagerParam PagerParam, fields ...string) QueryEntityResult

NewQueryPagerEntity 创建新的分页查询实体

type QueryPagerResult

type QueryPagerResult struct {
	Rows  []map[string]interface{} `json:"rows"`
	Total int64                    `json:"total"`
}

QueryPagerResult 分页查询结果类型

func Pager

func Pager(entity QueryEntity) (QueryPagerResult, error)

Pager 查询分页数据

type QueryProvider

type QueryProvider interface {
	// Single 查询单条数据
	Single(QueryEntity) (map[string]string, error)
	// AssignSingle 将查询结果解析到对应的指针地址
	// (数据类型包括:map[string]string,map[string]interface{},struct)
	AssignSingle(QueryEntity, interface{}) error
	// List 查询列表数据
	List(QueryEntity) ([]map[string]string, error)
	// AssignList 将查询结果解析到对应的指针地址
	// (数据类型包括:[]map[string]string,[]map[string]interface{},[]struct)
	AssignList(QueryEntity, interface{}) error
	// Pager 查询分页数据
	Pager(QueryEntity) (QueryPagerResult, error)
	// Query 查询数据(根据QueryResultType返回数据结果类型)
	Query(QueryEntity) (interface{}, error)
}

QueryProvider 提供数据库查询接口

type QueryResultType

type QueryResultType byte

QueryResultType 查询结果类型

const (
	// QSingle 单条数据
	QSingle QueryResultType = 1 << iota
	// QList 列表数据
	QList
	// QPager 分页数据
	QPager
)

type ResultError

type ResultError struct {
	Error error
}

ResultError 提供统一的错误处理

type TranEntity

type TranEntity struct {
	Table       string
	Operate     TranOperate
	FieldsValue map[string]interface{}
	Condition   QueryCondition
}

TranEntity 提供事务性操作结构体

type TranEntityResult

type TranEntityResult struct {
	ResultError
	Entity TranEntity
}

TranEntityResult 提供事务实体

func NewTranAEntity

func NewTranAEntity(table string, fieldsValue interface{}) TranEntityResult

NewTranAEntity 创建新增实体 fieldsValue 数据类型(map[string]interface{} or map[string]string or struct) 如果fieldsValue为struct类型,只保留非零值字段

func NewTranDEntity

func NewTranDEntity(table string, cond QueryCondition) TranEntityResult

NewTranUEntity 创建删除实体

func NewTranUEntity

func NewTranUEntity(table string, fieldsValue interface{}, cond QueryCondition) TranEntityResult

NewTranUEntity 创建更新实体 fieldsValue 数据类型(map[string]interface{} or map[string]string or struct) 如果fieldsValue为struct类型,只保留非零值字段

type TranOperate

type TranOperate byte

TranOperate 操作

const (
	// TA 新增
	TA TranOperate = 1 << iota
	// TU 更新
	TU
	// TD 删除
	TD
)

type TranProvider

type TranProvider interface {
	// Exec 执行单条事务性操作
	Exec(TranEntity) TranResult
	// ExecTrans 执行多条事务性操作
	ExecTrans([]TranEntity) TranResult
}

TranProvider 提供数据库事务操作

type TranResult

type TranResult struct {
	ResultError
	Result int64
}

TranResult 提供事务结果处理

func Exec

func Exec(entity TranEntity) TranResult

Exec 执行单条事务性操作

func ExecTrans

func ExecTrans(entities []TranEntity) TranResult

ExecTrans 执行多条事务性操作

Directories

Path Synopsis
sample

Jump to

Keyboard shortcuts

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