ploto

package module
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2021 License: MIT Imports: 10 Imported by: 1

README

ploto

A go Library for scan database/sql rows to struct、slice、other types. And it support multiple databases connection management

It's not an ORM. works with database/sql

功能

  • Scan rows, 支持struct,slice,map,其他基本类型
  • 多数据库配置连接管理

说明

仅对database/sql的DB.Query,DB.QueryContext,DB.QueryRow,DB.QueryRowContext进行封装,其他使用保持不变.

  • Query/QueryContext 结果Scan支持*Slice、*Struct、*Map、*int等基本类型.
  • QueryRow/QueryRowContext 结果Scan支持*Struct、*Map、*int等基本类型. 结果为空返回sql.ErrNoRows

数据库配置

配置支持多数据库连接,格式如下:

mysql
{"mysql": {
		"clients": {
			"test":{
				"host": "127.0.0.1",
				"port": 3307,
				"user": "test",
				"password": "asfasdf@#sddfsdf",
				"database": "test"
			}
		},
		"default": {
			"port": 3306,
			"dialect": "mysql",
			"pool": {
				"maxIdleConns": 2,
				"maxLeftTime": 60000, 
				"maxOpenConns": 5
			},
			"dialectOptions": {
				"parseTime":true,
				"multiStatements": true,
				"writeTimeout": "3000ms",
				"readTimeout": "3000ms",
				"timeout":"3000ms",
				"parseTime": true,
				"loc":"Local",

			}	
		}
	}}

更多dialectOptions参数见: https://github.com/go-sql-driver/mysql#parameters

mssql
{"mssql": {
		"clients": {
	 
			"test":{
				"host": "127.0.0.1",
				"user": "sa",
				"password": "test123",
				"database": "test",
				"pool": {
					"maxIdleConns": 20,
					"maxLeftTime": 60000,
					"maxOpenConns": 50
				},
				"dialectOptions": {
					"dial timeout": "10"

				}
			}
		},
		"default": {
			"port": 1433,
			"dialect": "sqlserver", //or mssql
			"pool": {
				"maxIdleConns": 2,
				"maxLeftTime": 60000,
				"maxOpenConns": 5
			},
			"dialectOptions": {
				"dial timeout": "3"
			}
		}
	}}

更多dialectOptions 参数见:https://github.com/denisenkom/go-mssqldb#connection-parameters-and-dsn

Using

配合多数据库管理一起使用
package main

import (
    "encoding/json"
    "fmt"
    "github.com/feiin/ploto"
     _ "github.com/go-sql-driver/mysql"
)

func getConfig() (config Configs) {
    testConfig := `{"mysql": {
        "clients": {
            "test":{
                "host": "127.0.0.1",
                "port": 3306,
                "user": "root",
                "password": "root",
                "database": "test"
            }
        },
        "default": {
            "port": 3306,
            "dialect": "mysql",
            "pool": {
                "maxIdleConns": 2,
                "maxLeftTime": 60000, 
                "maxOpenConns": 5
            },
            "dialectOptions": {
                "parseTime":true,
                "multiStatements": true,
                "writeTimeout": "3000ms",
                "readTimeout": "3000ms",
                "timeout":"3000ms",
				"parseTime": true,
				"loc":"Local",
            }   
        }
    }}`

    var conf Configs

    json.Unmarshal([]byte(testConfig), &conf)

    // fmt.Printf("conf %+v", conf)
    return conf

}

type User struct {
    Id          int64  `db:"id"`
    Name        string `db:"name"`
    CreatedTime string `db:"created_time"`
    UpdatedTime string `db:"updated_time"`
}

type Configs struct {
    Mysql ploto.DialectConfig `json:"mysql"`
   // Mssql ploto.DialectConfig `json:"mssql"`
}

func main() {

    configs := getConfig()
    db, err := ploto.Open(configs.Mysql, nil)
    if err != nil {
        panic(err)
    }
    defer db.Close()

    
    var users []User
    err = db.Use("test").Query("select * from users where id<100").Scan(&users)
    if err != nil {
        panic(err)
    }
    fmt.Printf("users %+v", users)

	//Exec....
	result, err := db.Use("test").Exec("update users set name=? where  id=?","xxx",1)
    if err != nil {
		//...
        panic(err)
    }
	
	
	//Exec....
	result, err := db.Use("test").Exec("insert uesrs(name,created_time) values(?,now())","xxx")
    if err != nil {
		//...
        panic(err)
    }

}

只用Scan功能

支持对rows结果转化到struct,slice,int等

struct定义字段tag为db

type User struct {
    Id          int64  `db:"id"`
    Name        string `db:"name"`
    CreatedTime string `db:"created_time"`
    UpdatedTime string `db:"updated_time"`
}

package main

import (
	"database/sql"
	"fmt"
	"github.com/feiin/ploto"
	_ "github.com/go-sql-driver/mysql"
)

func main() {
	db, err := sql.Open("mysql", "user:password@/database")
	if err != nil {
		panic(err.Error()) // Just for example purpose. You should use proper error handling instead of panic
	}
	defer db.Close()

	//scan rows to slices
	var users []User
	rows, err = db.Query("select * from users where id<100")
	if err != nil {
		panic(err)
	}
	defer rows.Close()

	for rows.Next() {
		var user User
		err := ploto.Scan(rows, &user)
		users = append(users, user)
	}


	//ScanResult等同上代码
	var users []User
	rows, err = db.Query("select * from users where id<100")
	if err != nil {
		panic(err)
	}

	//No need to Close
	err := ploto.ScanResult(rows, &users)

	//.....
	// select count(1) as cnt from users

	if rows.Next() {
		var a int64
		ploto.Scan(rows,&a)
	}
	//.....

	// select * from users where id=1

	if rows.Next() {
		var user User 
		ploto.Scan(rows,&user)
	}
	//.....
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Scan

func Scan(rows *sql.Rows, dest interface{}) error

Scan

func ScanResult

func ScanResult(rows *sql.Rows, dest interface{}) error

func ScanSlice

func ScanSlice(rows *sql.Rows, dest interface{}) error

Types

type DB

type DB struct {
	*sql.DB
}

func (*DB) Query

func (db *DB) Query(query string, args ...interface{}) *RowsResult

Query executes a query that returns RowsResult, typically a SELECT. The args are for any placeholder parameters in the query.

func (*DB) QueryContext

func (db *DB) QueryContext(ctx context.Context, query string, args ...interface{}) *RowsResult

QueryContext executes a query that returns RowsResult, typically a SELECT. The args are for any placeholder parameters in the query.

func (*DB) QueryRow added in v0.2.3

func (db *DB) QueryRow(query string, args ...interface{}) *RowResult

QueryRow executes a query that is expected to return at most one row. QueryRow always returns a non-nil value. Errors are deferred until Row's Scan method is called. If the query selects no rows, the *Row's Scan will return ErrNoRows. Otherwise, the *Row's Scan scans the first selected row and discards the rest.

func (*DB) QueryRowContext added in v0.2.3

func (db *DB) QueryRowContext(ctx context.Context, query string, args ...interface{}) *RowResult

QueryRowContext executes a query that is expected to return at most one row. QueryRowContext always returns a non-nil value. Errors are deferred until Row's Scan method is called. If the query selects no rows, the *Row's Scan will return ErrNoRows. Otherwise, the *Row's Scan scans the first selected row and discards the rest.

func (*DB) RawDB

func (db *DB) RawDB() *sql.DB

RawDB return the *sql.DB

type DefaultLogger

type DefaultLogger struct {
}

func (DefaultLogger) Debug

func (l DefaultLogger) Debug(format string, v ...interface{})

func (DefaultLogger) Error

func (l DefaultLogger) Error(format string, v ...interface{})

func (DefaultLogger) Info

func (l DefaultLogger) Info(format string, v ...interface{})

func (DefaultLogger) Warn

func (l DefaultLogger) Warn(format string, v ...interface{})

type Dialect

type Dialect struct {
	Clients map[string]*DB
	Configs DialectConfig
	// contains filtered or unexported fields
}

func Open

func Open(configs DialectConfig, log LoggerInterface) (*Dialect, error)

Init init all the database clients

func (*Dialect) Close

func (dialect *Dialect) Close() error

Close Close the database

func (*Dialect) CreateClient

func (dialect *Dialect) CreateClient(database string) (db *DB, err error)

CreateClient create the db pool for the database

func (*Dialect) Use

func (dialect *Dialect) Use(database string) (db *DB)

Use get the db's conn

type DialectConfig

type DialectConfig struct {
	Clients map[string]interface{} `json:"clients"`
	Default map[string]interface{} `json:"default"`
}

type DialectDSN

type DialectDSN interface {
	GetDialectDSN(database string, config map[string]interface{}) string
}

type LoggerInterface

type LoggerInterface interface {
	Debug(string, ...interface{})
	Info(string, ...interface{})
	Warn(string, ...interface{})
	Error(string, ...interface{})
}

type Mssql

type Mssql struct {
}

Mssql mssql dialector

func (Mssql) GetDialectDSN

func (m Mssql) GetDialectDSN(database string, config map[string]interface{}) string

GetDialectDSN

**config:{
	 	"clients": {
			"share":{
				"host": "127.0.0.1",
				"user": "sa",
				"password": "test123",
				"database": "test"
			},
			"test":{
				"host": "127.0.0.1",
				"port": 1433,
				"user": "sa",
				"password": "test123",
				"database": "test",
				"pool": {
					"maxIdleConns": 20,
					"maxLeftTime": 60000,
					"maxOpenConns": 50
				},
				"dialectOptions": {
					"dial timeout": "10"

				}
			}
		},
		"default": {
			"port": 1433,
			"dialect": "sqlserver",
			"pool": {
				"maxIdleConns": 2,
				"maxLeftTime": 60000,
				"maxOpenConns": 5
			},
			"dialectOptions": {
				"dial timeout": "3"
			}
		}
	}

*

type Mysql

type Mysql struct {
}

Mysql mysql dialector

func (Mysql) GetDialectDSN

func (m Mysql) GetDialectDSN(database string, config map[string]interface{}) string

GetDialectDSN

**config:{
	 	"clients": {
			"share":{
				"host": "127.0.0.1",
				"user": "test",
				"password": "test123",
				"database": "test"
			},
			"test":{
				"host": "127.0.0.1",
				"port": 3307,
				"user": "test",
				"password": "test123",
				"database": "test",
				"pool": {
					"maxIdleConns": 20,
					"maxLeftTime": 60000,
					"maxOpenConns": 50
				},
				"dialectOptions": {
					"writeTimeout": "2000ms",
					"readTimeout": "2000ms",
					"timeout":"2000ms"
				}
			}
		},
		"default": {
			"port": 3306,
			"dialect": "mysql",
			"pool": {
				"maxIdleConns": 2,
				"maxLeftTime": 60000,
				"maxOpenConns": 5
			},
			"dialectOptions": {
				"writeTimeout": "3000ms",
				"readTimeout": "3000ms",
				"timeout":"3000ms"
			}
		}
	}

*

type RowResult

type RowResult struct {
	LastError error
	// contains filtered or unexported fields
}

func (*RowResult) Err added in v0.2.3

func (r *RowResult) Err() error

RowResult return the error of RowResult

func (*RowResult) Scan added in v0.2.3

func (r *RowResult) Scan(dest interface{}) error

Scan RowResult's scan

type RowsResult

type RowsResult struct {
	*sql.Rows
	LastError error
}

func (RowsResult) Close

func (r RowsResult) Close() error

Close returns the connection to the connection pool

func (*RowsResult) Raw

func (r *RowsResult) Raw() (*sql.Rows, error)

Raw

func (*RowsResult) Scan

func (r *RowsResult) Scan(dest interface{}) error

Scan

Jump to

Keyboard shortcuts

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