Compare commits

..

7 Commits

Author SHA1 Message Date
198f3ebb5d bug fix 2023-05-17 14:48:33 +08:00
2185a61564 add support for BLOB 2023-05-16 16:49:14 +08:00
fb9808a139
go mod support 2022-03-14 12:32:48 +08:00
db0843647c
variable name change 2021-11-12 16:18:31 +08:00
e74077e7d5 orm update add 2021-07-21 17:25:57 +08:00
Starainrt
5db5af26e0 bug fix 2021-06-17 14:58:29 +08:00
Starainrt
918fed8166 simple orm add 2021-06-16 15:26:58 +08:00
9 changed files with 1328 additions and 56 deletions

8
.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,8 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 数据源本地存储已忽略文件
/dataSources/
/dataSources.local.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/

8
.idea/modules.xml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/stardb.iml" filepath="$PROJECT_DIR$/.idea/stardb.iml" />
</modules>
</component>
</project>

9
.idea/stardb.iml generated Normal file
View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="Go" enabled="true" />
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

6
.idea/vcs.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module b612.me/stardb
go 1.16

511
orm_v1.go Normal file
View File

@ -0,0 +1,511 @@
package stardb
import (
"context"
"database/sql"
"errors"
"fmt"
"reflect"
"strings"
)
func (star *StarRows) Orm(ins interface{}) error {
//check if is slice
if !star.parsed {
if err := star.parserows(); err != nil {
return err
}
}
t := reflect.TypeOf(ins)
v := reflect.ValueOf(ins)
if t.Kind() != reflect.Ptr {
return errors.New("interface not writable")
}
//now convert to slice
t = t.Elem()
v = v.Elem()
if v.Kind() == reflect.Slice || v.Kind() == reflect.Array {
//get type of slice
sigType := t.Elem()
var result reflect.Value
result = reflect.New(t).Elem()
if star.Length == 0 {
v.Set(result)
return nil
}
for i := 0; i < star.Length; i++ {
val := reflect.New(sigType)
star.setAllRefValue(val.Interface(), "db", i)
result = reflect.Append(result, val.Elem())
}
v.Set(result)
return nil
}
if star.Length == 0 {
return nil
}
return star.setAllRefValue(ins, "db", 0)
}
func (star *StarDB) queryX(ctx context.Context, ins interface{}, args ...interface{}) (*StarRows, error) {
kvMap, err := getAllRefValue(ins, "db")
if err != nil {
return nil, err
}
for k, v := range args {
if k == 0 {
continue
}
switch v.(type) {
case string:
str := v.(string)
if strings.Index(str, ":") == 0 {
if _, ok := kvMap[str[1:]]; ok {
args[k] = kvMap[str[1:]]
} else {
args[k] = ""
}
continue
}
if strings.Index(str, `\:`) == 0 {
args[k] = kvMap[str[1:]]
}
}
}
return star.query(ctx, args...)
}
func (star *StarDB) QueryX(ins interface{}, args ...interface{}) (*StarRows, error) {
return star.queryX(nil, ins, args)
}
func (star *StarDB) QueryXS(ins interface{}, args ...interface{}) ([]*StarRows, error) {
var starRes []*StarRows
t := reflect.TypeOf(ins)
v := reflect.ValueOf(ins)
if t.Kind() == reflect.Ptr {
t = t.Elem()
v = v.Elem()
}
//now convert to slice
if v.Kind() == reflect.Slice || v.Kind() == reflect.Array {
for i := 0; i < v.Len(); i++ {
result, err := star.queryX(nil, v.Index(i).Interface(), args...)
if err != nil {
return starRes, err
}
starRes = append(starRes, result)
}
} else {
result, err := star.queryX(nil, ins, args...)
if err != nil {
return starRes, err
}
starRes = append(starRes, result)
}
return starRes, nil
}
func (star *StarDB) ExecXS(ins interface{}, args ...interface{}) ([]sql.Result, error) {
var starRes []sql.Result
t := reflect.TypeOf(ins)
v := reflect.ValueOf(ins)
if t.Kind() == reflect.Ptr {
t = t.Elem()
v = v.Elem()
}
//now convert to slice
if v.Kind() == reflect.Slice || v.Kind() == reflect.Array {
for i := 0; i < v.Len(); i++ {
result, err := star.execX(nil, v.Index(i).Interface(), args...)
if err != nil {
return starRes, err
}
starRes = append(starRes, result)
}
} else {
result, err := star.execX(nil, ins, args...)
if err != nil {
return starRes, err
}
starRes = append(starRes, result)
}
return starRes, nil
}
func (star *StarDB) ExecX(ins interface{}, args ...interface{}) (sql.Result, error) {
return star.execX(nil, ins, args...)
}
func getUpdateSentence(ins interface{}, sheetName string, primaryKey ...string) (string, []string, error) {
Keys, err := getAllRefKey(ins, "db")
if err != nil {
return "", []string{}, err
}
var mystr string
for k, v := range Keys {
mystr += fmt.Sprintf("%s=? ", v)
Keys[k] = ":" + v
}
mystr = fmt.Sprintf("update %s set %s where ", sheetName, mystr)
var whereSlice []string
for _, v := range primaryKey {
whereSlice = append(whereSlice, v+"=?")
Keys = append(Keys, ":"+v)
}
mystr += strings.Join(whereSlice, " and ")
return mystr, Keys, nil
}
func getInsertSentence(ins interface{}, sheetName string, autoIncrease ...string) (string, []string, error) {
Keys, err := getAllRefKey(ins, "db")
if err != nil {
return "", []string{}, err
}
var mystr, rps string
var rtnKeys []string
cns:
for _, v := range Keys {
for _, vs := range autoIncrease {
if v == vs {
rps += "null,"
continue cns
}
}
rtnKeys = append(rtnKeys, ":"+v)
rps += "?,"
}
mystr = fmt.Sprintf("insert into %s (%s) values (%s) ", sheetName, strings.Join(Keys, ","), rps[:len(rps)-1])
return mystr, rtnKeys, nil
}
func (star *StarDB) execX(ctx context.Context, ins interface{}, args ...interface{}) (sql.Result, error) {
kvMap, err := getAllRefValue(ins, "db")
if err != nil {
return nil, err
}
for k, v := range args {
if k == 0 {
continue
}
switch v.(type) {
case string:
str := v.(string)
if strings.Index(str, ":") == 0 {
if _, ok := kvMap[str[1:]]; ok {
args[k] = kvMap[str[1:]]
} else {
args[k] = ""
}
continue
}
if strings.Index(str, `\:`) == 0 {
args[k] = kvMap[str[1:]]
}
}
}
return star.exec(ctx, args...)
}
func (star *StarDB) Update(ins interface{}, sheetName string, primaryKey ...string) (sql.Result, error) {
return star.updateinsert(nil, true, ins, sheetName, primaryKey...)
}
func (star *StarDB) UpdateContext(ctx context.Context, ins interface{}, sheetName string, primaryKey ...string) (sql.Result, error) {
return star.updateinsert(ctx, true, ins, sheetName, primaryKey...)
}
func (star *StarDB) Insert(ins interface{}, sheetName string, autoCreaseKey ...string) (sql.Result, error) {
return star.updateinsert(nil, false, ins, sheetName, autoCreaseKey...)
}
func (star *StarDB) InsertContext(ctx context.Context, ins interface{}, sheetName string, autoCreaseKey ...string) (sql.Result, error) {
return star.updateinsert(ctx, false, ins, sheetName, autoCreaseKey...)
}
func (star *StarDB) updateinsert(ctx context.Context, isUpdate bool, ins interface{}, sheetName string, primaryKey ...string) (sql.Result, error) {
var sqlStr string
var para []string
var err error
if isUpdate {
sqlStr, para, err = getUpdateSentence(ins, sheetName, primaryKey...)
} else {
sqlStr, para, err = getInsertSentence(ins, sheetName, primaryKey...)
}
if err != nil {
return nil, err
}
tmpStr := append([]interface{}{}, sqlStr)
for _, v := range para {
tmpStr = append(tmpStr, v)
}
return star.execX(ctx, ins, tmpStr...)
}
func (star *StarDB) QueryXContext(ctx context.Context, ins interface{}, args ...interface{}) (*StarRows, error) {
return star.queryX(ctx, ins, args)
}
func (star *StarDB) QueryXSContext(ctx context.Context, ins interface{}, args ...interface{}) ([]*StarRows, error) {
var starRes []*StarRows
t := reflect.TypeOf(ins)
v := reflect.ValueOf(ins)
if t.Kind() == reflect.Ptr {
t = t.Elem()
v = v.Elem()
}
//now convert to slice
if v.Kind() == reflect.Slice || v.Kind() == reflect.Array {
for i := 0; i < v.Len(); i++ {
result, err := star.queryX(ctx, v.Index(i).Interface(), args...)
if err != nil {
return starRes, err
}
starRes = append(starRes, result)
}
} else {
result, err := star.queryX(ctx, ins, args...)
if err != nil {
return starRes, err
}
starRes = append(starRes, result)
}
return starRes, nil
}
func (star *StarDB) ExecXSContext(ctx context.Context, ins interface{}, args ...interface{}) ([]sql.Result, error) {
var starRes []sql.Result
t := reflect.TypeOf(ins)
v := reflect.ValueOf(ins)
if t.Kind() == reflect.Ptr {
t = t.Elem()
v = v.Elem()
}
//now convert to slice
if v.Kind() == reflect.Slice || v.Kind() == reflect.Array {
for i := 0; i < v.Len(); i++ {
result, err := star.execX(ctx, v.Index(i).Interface(), args...)
if err != nil {
return starRes, err
}
starRes = append(starRes, result)
}
} else {
result, err := star.execX(ctx, ins, args...)
if err != nil {
return starRes, err
}
starRes = append(starRes, result)
}
return starRes, nil
}
func (star *StarDB) ExecXContext(ctx context.Context, ins interface{}, args ...interface{}) (sql.Result, error) {
return star.execX(ctx, ins, args...)
}
func (star *StarTx) queryX(ctx context.Context, ins interface{}, args ...interface{}) (*StarRows, error) {
kvMap, err := getAllRefValue(ins, "db")
if err != nil {
return nil, err
}
for k, v := range args {
if k == 0 {
continue
}
switch v.(type) {
case string:
str := v.(string)
if strings.Index(str, ":") == 0 {
if _, ok := kvMap[str[1:]]; ok {
args[k] = kvMap[str[1:]]
} else {
args[k] = ""
}
continue
}
if strings.Index(str, `\:`) == 0 {
args[k] = kvMap[str[1:]]
}
}
}
return star.query(ctx, args...)
}
func (star *StarTx) QueryX(ins interface{}, args ...interface{}) (*StarRows, error) {
return star.queryX(nil, ins, args)
}
func (star *StarTx) QueryXS(ins interface{}, args ...interface{}) ([]*StarRows, error) {
var starRes []*StarRows
t := reflect.TypeOf(ins)
v := reflect.ValueOf(ins)
if t.Kind() == reflect.Ptr {
t = t.Elem()
v = v.Elem()
}
//now convert to slice
if v.Kind() == reflect.Slice || v.Kind() == reflect.Array {
for i := 0; i < v.Len(); i++ {
result, err := star.queryX(nil, v.Index(i).Interface(), args...)
if err != nil {
return starRes, err
}
starRes = append(starRes, result)
}
} else {
result, err := star.queryX(nil, ins, args...)
if err != nil {
return starRes, err
}
starRes = append(starRes, result)
}
return starRes, nil
}
func (star *StarTx) Update(ins interface{}, sheetName string, primaryKey ...string) (sql.Result, error) {
return star.updateinsert(nil, true, ins, sheetName, primaryKey...)
}
func (star *StarTx) UpdateContext(ctx context.Context, ins interface{}, sheetName string, primaryKey ...string) (sql.Result, error) {
return star.updateinsert(ctx, true, ins, sheetName, primaryKey...)
}
func (star *StarTx) Insert(ins interface{}, sheetName string, autoCreaseKey ...string) (sql.Result, error) {
return star.updateinsert(nil, false, ins, sheetName, autoCreaseKey...)
}
func (star *StarTx) InsertContext(ctx context.Context, ins interface{}, sheetName string, autoCreaseKey ...string) (sql.Result, error) {
return star.updateinsert(ctx, false, ins, sheetName, autoCreaseKey...)
}
func (star *StarTx) updateinsert(ctx context.Context, isUpdate bool, ins interface{}, sheetName string, primaryKey ...string) (sql.Result, error) {
var sqlStr string
var para []string
var err error
if isUpdate {
sqlStr, para, err = getUpdateSentence(ins, sheetName, primaryKey...)
} else {
sqlStr, para, err = getInsertSentence(ins, sheetName, primaryKey...)
}
if err != nil {
return nil, err
}
tmpStr := append([]interface{}{}, sqlStr)
for _, v := range para {
tmpStr = append(tmpStr, v)
}
return star.execX(ctx, ins, tmpStr...)
}
func (star *StarTx) ExecXS(ins interface{}, args ...interface{}) ([]sql.Result, error) {
var starRes []sql.Result
t := reflect.TypeOf(ins)
v := reflect.ValueOf(ins)
if t.Kind() == reflect.Ptr {
t = t.Elem()
v = v.Elem()
}
//now convert to slice
if v.Kind() == reflect.Slice || v.Kind() == reflect.Array {
for i := 0; i < v.Len(); i++ {
result, err := star.execX(nil, v.Index(i).Interface(), args...)
if err != nil {
return starRes, err
}
starRes = append(starRes, result)
}
} else {
result, err := star.execX(nil, ins, args...)
if err != nil {
return starRes, err
}
starRes = append(starRes, result)
}
return starRes, nil
}
func (star *StarTx) ExecX(ins interface{}, args ...interface{}) (sql.Result, error) {
return star.execX(nil, ins, args...)
}
func (star *StarTx) execX(ctx context.Context, ins interface{}, args ...interface{}) (sql.Result, error) {
kvMap, err := getAllRefValue(ins, "db")
if err != nil {
return nil, err
}
for k, v := range args {
if k == 0 {
continue
}
switch v.(type) {
case string:
str := v.(string)
if strings.Index(str, ":") == 0 {
if _, ok := kvMap[str[1:]]; ok {
args[k] = kvMap[str[1:]]
} else {
args[k] = ""
}
continue
}
if strings.Index(str, `\:`) == 0 {
args[k] = kvMap[str[1:]]
}
}
}
return star.exec(ctx, args...)
}
func (star *StarTx) QueryXContext(ctx context.Context, ins interface{}, args ...interface{}) (*StarRows, error) {
return star.queryX(ctx, ins, args)
}
func (star *StarTx) QueryXSContext(ctx context.Context, ins interface{}, args ...interface{}) ([]*StarRows, error) {
var starRes []*StarRows
t := reflect.TypeOf(ins)
v := reflect.ValueOf(ins)
if t.Kind() == reflect.Ptr {
t = t.Elem()
v = v.Elem()
}
//now convert to slice
if v.Kind() == reflect.Slice || v.Kind() == reflect.Array {
for i := 0; i < v.Len(); i++ {
result, err := star.queryX(ctx, v.Index(i).Interface(), args...)
if err != nil {
return starRes, err
}
starRes = append(starRes, result)
}
} else {
result, err := star.queryX(ctx, ins, args...)
if err != nil {
return starRes, err
}
starRes = append(starRes, result)
}
return starRes, nil
}
func (star *StarTx) ExecXSContext(ctx context.Context, ins interface{}, args ...interface{}) ([]sql.Result, error) {
var starRes []sql.Result
t := reflect.TypeOf(ins)
v := reflect.ValueOf(ins)
if t.Kind() == reflect.Ptr {
t = t.Elem()
v = v.Elem()
}
//now convert to slice
if v.Kind() == reflect.Slice || v.Kind() == reflect.Array {
for i := 0; i < v.Len(); i++ {
result, err := star.execX(ctx, v.Index(i).Interface(), args...)
if err != nil {
return starRes, err
}
starRes = append(starRes, result)
}
} else {
result, err := star.execX(ctx, ins, args...)
if err != nil {
return starRes, err
}
starRes = append(starRes, result)
}
return starRes, nil
}
func (star *StarTx) ExecXContext(ctx context.Context, ins interface{}, args ...interface{}) (sql.Result, error) {
return star.execX(ctx, ins, args...)
}

245
reflect.go Normal file
View File

@ -0,0 +1,245 @@
package stardb
import (
"errors"
"reflect"
"time"
)
func (star *StarRows) setAllRefValue(stc interface{}, skey string, rows int) error {
t := reflect.TypeOf(stc)
v := reflect.ValueOf(stc)
if t.Kind() == reflect.Ptr {
v = v.Elem()
}
if t.Kind() != reflect.Ptr && !v.CanSet() {
return errors.New("interface{} is not writable")
}
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if v.Kind() != reflect.Struct {
return errors.New("interface{} is not a struct")
}
for i := 0; i < t.NumField(); i++ {
tp := t.Field(i)
srFrd := v.Field(i)
seg := tp.Tag.Get(skey)
if seg == "" && !tp.IsExported() {
continue
}
if srFrd.Kind() == reflect.Ptr && reflect.TypeOf(srFrd.Interface()).Elem().Kind() == reflect.Struct {
if seg == "" {
continue
}
if seg == "---" {
sp := reflect.New(reflect.TypeOf(srFrd.Interface()).Elem()).Interface()
star.setAllRefValue(sp, skey, rows)
v.Field(i).Set(reflect.ValueOf(sp))
continue
}
}
if srFrd.Kind() == reflect.Struct {
if seg == "" {
continue
}
if seg == "---" {
sp := reflect.New(reflect.TypeOf(v.Field(i).Interface())).Interface()
star.setAllRefValue(sp, skey, rows)
v.Field(i).Set(reflect.ValueOf(sp).Elem())
continue
}
}
if _, ok := star.Row(rows).columnref[seg]; !ok {
continue
}
myInt64 := star.Row(rows).MustInt64(seg)
myUint64 := star.Row(rows).MustUint64(seg)
switch v.Field(i).Kind() {
case reflect.String:
v.Field(i).SetString(star.Row(rows).MustString(seg))
case reflect.Int64:
v.Field(i).SetInt(myInt64)
case reflect.Int32:
v.Field(i).SetInt(int64(star.Row(rows).MustInt32(seg)))
case reflect.Int16:
v.Field(i).SetInt(int64(int16(myInt64)))
case reflect.Int8:
v.Field(i).SetInt(int64(int8(myInt64)))
case reflect.Uint64:
v.Field(i).SetUint(myUint64)
case reflect.Uint32:
v.Field(i).SetUint(uint64(uint32(myUint64)))
case reflect.Uint16:
v.Field(i).SetUint(uint64(uint16(myUint64)))
case reflect.Uint8:
v.Field(i).SetUint(uint64(uint8(myUint64)))
case reflect.Bool:
v.Field(i).SetBool(star.Row(rows).MustBool(seg))
case reflect.Float64:
v.Field(i).SetFloat(star.Row(rows).MustFloat64(seg))
case reflect.Float32:
v.Field(i).SetFloat(float64(star.Row(rows).MustFloat32(seg)))
case reflect.Slice, reflect.Array:
if t.Field(i).Type.Elem().Kind() == reflect.Uint8 {
v.Field(i).SetBytes(star.Row(rows).MustBytes(seg))
}
case reflect.Interface, reflect.Struct, reflect.Ptr:
inf := star.Row(rows).Result[star.columnref[seg]]
switch vtype := inf.(type) {
case time.Time:
v.Field(i).Set(reflect.ValueOf(vtype))
}
default:
}
}
return nil
}
func setRefValue(stc interface{}, skey, key string, value interface{}) error {
t := reflect.TypeOf(stc)
v := reflect.ValueOf(stc).Elem()
if t.Kind() != reflect.Ptr || !v.CanSet() {
return errors.New("interface{} is not writable")
}
if v.Kind() != reflect.Struct {
return errors.New("interface{} is not a struct")
}
t = t.Elem()
for i := 0; i < t.NumField(); i++ {
tp := t.Field(i)
seg := tp.Tag.Get(skey)
if seg == "" || key != seg {
continue
}
v.Field(i).Set(reflect.ValueOf(value))
}
return nil
}
func getAllRefValue(stc interface{}, skey string) (map[string]interface{}, error) {
result := make(map[string]interface{})
t := reflect.TypeOf(stc)
v := reflect.ValueOf(stc)
if t.Kind() == reflect.Ptr {
if v.IsNil() {
return nil, errors.New("ptr interface{} is nil")
}
t = t.Elem()
v = v.Elem()
}
if v.Kind() != reflect.Struct {
return nil, errors.New("interface{} is not a struct")
}
for i := 0; i < t.NumField(); i++ {
tp := t.Field(i)
srFrd := v.Field(i)
seg := tp.Tag.Get(skey)
if seg == "" && !tp.IsExported() {
continue
}
if srFrd.Kind() == reflect.Ptr && reflect.TypeOf(srFrd.Interface()).Elem().Kind() == reflect.Struct {
if srFrd.IsNil() {
continue
}
if seg == "---" {
res, err := getAllRefValue(reflect.ValueOf(srFrd.Elem().Interface()).Interface(), skey)
if err != nil {
return result, err
}
for k, v := range res {
result[k] = v
}
continue
}
}
if v.Field(i).Kind() == reflect.Struct {
res, err := getAllRefValue(v.Field(i).Interface(), skey)
if seg == "---" {
if err != nil {
return result, err
}
for k, v := range res {
result[k] = v
}
continue
}
}
if seg == "" {
continue
}
value := v.Field(i)
if !value.CanInterface() {
continue
}
result[seg] = value.Interface()
}
return result, nil
}
func getAllRefKey(stc interface{}, skey string) ([]string, error) {
var result []string
_, isStruct := isWritableStruct(stc)
if !isStruct {
return []string{}, errors.New("interface{} is not a struct")
}
t := reflect.TypeOf(stc)
v := reflect.ValueOf(stc)
if t.Kind() == reflect.Ptr {
if v.IsNil() {
return []string{}, errors.New("ptr interface{} is nil")
}
t = t.Elem()
v = v.Elem()
}
for i := 0; i < t.NumField(); i++ {
srFrd := v.Field(i)
profile := t.Field(i)
seg := profile.Tag.Get(skey)
if seg == "" && !profile.IsExported() {
continue
}
if srFrd.Kind() == reflect.Ptr && reflect.TypeOf(srFrd.Interface()).Elem().Kind() == reflect.Struct {
if srFrd.IsNil() {
continue
}
if seg == "---" {
res, err := getAllRefKey(reflect.ValueOf(srFrd.Elem().Interface()).Interface(), skey)
if err != nil {
return result, err
}
for _, v := range res {
result = append(result, v)
}
continue
}
}
if v.Field(i).Kind() == reflect.Struct && seg == "---" {
res, err := getAllRefKey(v.Field(i).Interface(), skey)
if err != nil {
return result, err
}
for _, v := range res {
result = append(result, v)
}
}
if seg != "" {
result = append(result, seg)
}
}
return result, nil
}
func isWritableStruct(stc interface{}) (isWritable bool, isStruct bool) {
t := reflect.TypeOf(stc)
v := reflect.ValueOf(stc)
if t.Kind() == reflect.Ptr || v.CanSet() {
isWritable = true
}
if v.Kind() == reflect.Struct {
isStruct = true
}
return
}

55
reflect_test.go Normal file
View File

@ -0,0 +1,55 @@
package stardb
import (
"fmt"
"testing"
)
type Useless struct {
Leader string `db:"leader"`
Usable bool `db:"use"`
O *Whoami `db:"---"`
Data []byte `db:"data"`
}
type Whoami struct {
Hehe string `db:"hehe"`
}
func TestUpInOrm(t *testing.T) {
var hehe = Useless{
Leader: "no",
Usable: false,
}
sqlstr, param, err := getUpdateSentence(hehe, "ryz", "leader")
fmt.Println(sqlstr, param, err)
sqlstr, param, err = getInsertSentence(hehe, "ryz", "use")
fmt.Println(sqlstr, param, err)
}
func Test_SetRefVal(t *testing.T) {
var hehe = Useless{
Leader: "no",
Data: []byte{1, 2, 3},
}
fmt.Printf("%+v\n", hehe)
fmt.Println(setRefValue(&hehe, "db", "leader", "sb"))
fmt.Printf("%+v\n", hehe)
fmt.Println(getAllRefKey(hehe, "db"))
fmt.Println(getAllRefValue(hehe, "db"))
fmt.Println(setRefValue(&hehe, "db", "data", []byte{4, 5, 6, 7, 8}))
fmt.Printf("%+v\n", hehe)
fmt.Println(getAllRefKey(hehe, "db"))
fmt.Println(getAllRefValue(hehe, "db"))
}
func Test_Ref(t *testing.T) {
oooooo := Useless{
Leader: "Heheeee",
}
oooooo.O = &Whoami{"fuck"}
fmt.Println(getAllRefKey(oooooo, "db"))
fmt.Println(getAllRefValue(oooooo, "db"))
fmt.Println(getAllRefValue(&oooooo, "db"))
}

View File

@ -1,6 +1,7 @@
package stardb
import (
"context"
"database/sql"
"errors"
"reflect"
@ -10,8 +11,13 @@ import (
// StarDB 一个简单封装的DB库
type StarDB struct {
DB *sql.DB
Rows *sql.Rows
Db *sql.DB
ManualScan bool
}
type StarTx struct {
Db *StarDB
Tx *sql.Tx
}
// StarRows 为查询结果集(按行)
@ -23,6 +29,12 @@ type StarRows struct {
ColumnsType []reflect.Type
columnref map[string]int
result [][]interface{}
parsed bool
}
type StarDBStmt struct {
Stmt *sql.Stmt
Db *StarDB
}
// StarResult 为查询结果集(总)
@ -87,6 +99,12 @@ func (star *StarResultCol) MustBool() []bool {
} else {
tmp = false
}
case uint64:
if vtype > 0 {
tmp = true
} else {
tmp = false
}
case string:
tmp, _ = strconv.ParseBool(vtype)
default:
@ -118,6 +136,8 @@ func (star *StarResultCol) MustFloat32() []float32 {
tmp = float32(vtype)
case int64:
tmp = float32(vtype)
case uint64:
tmp = float32(vtype)
case time.Time:
tmp = float32(vtype.Unix())
default:
@ -150,6 +170,8 @@ func (star *StarResultCol) MustFloat64() []float64 {
tmp = float64(vtype)
case int64:
tmp = float64(vtype)
case uint64:
tmp = float64(vtype)
case time.Time:
tmp = float64(vtype.Unix())
default:
@ -184,6 +206,8 @@ func (star *StarResultCol) MustString() []string {
tmp = strconv.FormatFloat(float64(vtype), 'f', 10, 32)
case int:
tmp = strconv.Itoa(vtype)
case uint64:
tmp = strconv.FormatUint(vtype, 10)
case time.Time:
tmp = vtype.String()
default:
@ -213,6 +237,8 @@ func (star *StarResultCol) MustInt32() []int32 {
tmp = int32(vtype)
case int64:
tmp = int32(vtype)
case uint64:
tmp = int32(vtype)
case int32:
tmp = vtype
case time.Time:
@ -246,6 +272,8 @@ func (star *StarResultCol) MustInt64() []int64 {
tmp = int64(vtype)
case int32:
tmp = int64(vtype)
case uint64:
tmp = int64(vtype)
case int64:
tmp = vtype
case time.Time:
@ -259,6 +287,39 @@ func (star *StarResultCol) MustInt64() []int64 {
return res
}
// MustUint64 列查询结果转Int64
func (star *StarResultCol) MustUint64() []uint64 {
var res []uint64
var tmp uint64
for _, v := range star.Result {
switch vtype := v.(type) {
case nil:
tmp = 0
case float64:
tmp = uint64(vtype)
case float32:
tmp = uint64(vtype)
case string:
tmp, _ = strconv.ParseUint(vtype, 10, 64)
case int:
tmp = uint64(vtype)
case int32:
tmp = uint64(vtype)
case int64:
tmp = uint64(vtype)
case uint64:
tmp = vtype
case time.Time:
tmp = uint64(vtype.Unix())
default:
tmpt := string(vtype.([]byte))
tmp, _ = strconv.ParseUint(tmpt, 10, 64)
}
res = append(res, tmp)
}
return res
}
// MustInt 列查询结果转Int
func (star *StarResultCol) MustInt() []int {
var res []int
@ -280,6 +341,8 @@ func (star *StarResultCol) MustInt() []int {
tmp = int(vtype)
case int64:
tmp = int(vtype)
case uint64:
tmp = int(vtype)
case time.Time:
tmp = int(vtype.Unix())
default:
@ -312,6 +375,8 @@ func (star *StarResultCol) MustDate(layout string) []time.Time {
tmp = time.Unix(int64(vtype), 0)
case int64:
tmp = time.Unix(vtype, 0)
case uint64:
tmp = time.Unix(int64(vtype), 0)
case time.Time:
tmp = vtype
default:
@ -377,6 +442,8 @@ func (star *StarResult) MustDate(name, layout string) time.Time {
res = time.Unix(int64(vtype), 0)
case int64:
res = time.Unix(vtype, 0)
case uint64:
res = time.Unix(int64(vtype), 0)
case time.Time:
res = vtype
default:
@ -406,6 +473,8 @@ func (star *StarResult) MustInt64(name string) int64 {
res = int64(vtype)
case int32:
res = int64(vtype)
case uint64:
res = int64(vtype)
case int64:
res = vtype
case time.Time:
@ -440,6 +509,8 @@ func (star *StarResult) MustInt32(name string) int32 {
res = vtype
case int64:
res = int32(vtype)
case uint64:
res = int32(vtype)
case time.Time:
res = int32(vtype.Unix())
default:
@ -449,6 +520,37 @@ func (star *StarResult) MustInt32(name string) int32 {
return res
}
// MustUint 列查询结果转uint
func (star *StarResult) MustUint64(name string) uint64 {
var res uint64
num, ok := star.columnref[name]
if !ok {
return 0
}
tmp := star.Result[num]
switch vtype := tmp.(type) {
case nil:
res = 0
case float64:
res = uint64(vtype)
case float32:
res = uint64(vtype)
case string:
res, _ = strconv.ParseUint(vtype, 10, 64)
case uint64:
res = vtype
case int32:
res = uint64(vtype)
case int64:
res = uint64(vtype)
case time.Time:
res = uint64(vtype.Unix())
default:
res, _ = strconv.ParseUint(string(tmp.([]byte)), 10, 64)
}
return res
}
// MustString 列查询结果转string
func (star *StarResult) MustString(name string) string {
var res string
@ -473,6 +575,8 @@ func (star *StarResult) MustString(name string) string {
res = strconv.FormatFloat(float64(vtype), 'f', 10, 32)
case int:
res = strconv.Itoa(vtype)
case uint64:
res = strconv.FormatUint(vtype, 10)
case time.Time:
res = vtype.String()
default:
@ -503,6 +607,8 @@ func (star *StarResult) MustFloat64(name string) float64 {
res = float64(vtype)
case float32:
res = float64(vtype)
case uint64:
res = float64(vtype)
case time.Time:
res = float64(vtype.Unix())
default:
@ -534,6 +640,8 @@ func (star *StarResult) MustFloat32(name string) float32 {
res = float32(vtype)
case int32:
res = float32(vtype)
case uint64:
res = float32(vtype)
case time.Time:
res = float32(vtype.Unix())
default:
@ -567,6 +675,8 @@ func (star *StarResult) MustInt(name string) int {
res = int(vtype)
case int64:
res = int(vtype)
case uint64:
res = int(vtype)
case time.Time:
res = int(vtype.Unix())
default:
@ -619,6 +729,12 @@ func (star *StarResult) MustBool(name string) bool {
} else {
res = false
}
case uint64:
if vtype > 0 {
res = true
} else {
res = false
}
case string:
res, _ = strconv.ParseBool(vtype)
default:
@ -674,7 +790,10 @@ func (star *StarRows) Close() error {
return star.Rows.Close()
}
func (star *StarRows) parserows() {
func (star *StarRows) parserows() error {
defer func() {
star.parsed = true
}()
star.result = [][]interface{}{}
star.columnref = make(map[string]int)
star.StringResult = []map[string]string{}
@ -691,7 +810,7 @@ func (star *StarRows) parserows() {
}
for star.Rows.Next() {
if err := star.Rows.Scan(scanArgs...); err != nil {
return
return err
}
record := make(map[string]string)
var rescopy []interface{}
@ -724,33 +843,96 @@ func (star *StarRows) parserows() {
star.StringResult = append(star.StringResult, record)
}
star.Length = len(star.StringResult)
return nil
}
// Query 进行Query操作
func (star *StarDB) Query(args ...interface{}) (*StarRows, error) {
func (star *StarDB) Begin() (*StarTx, error) {
tx, err := star.Db.Begin()
if err != nil {
return nil, err
}
stx := new(StarTx)
stx.Db = star
stx.Tx = tx
return stx, err
}
func (star *StarDB) BeginTx(ctx context.Context, opts *sql.TxOptions) (*StarTx, error) {
tx, err := star.Db.BeginTx(ctx, opts)
if err != nil {
return nil, err
}
stx := new(StarTx)
stx.Db = star
stx.Tx = tx
return stx, err
}
func (star *StarTx) Query(args ...interface{}) (*StarRows, error) {
return star.query(nil, args...)
}
func (star *StarTx) QueryContext(ctx context.Context, args ...interface{}) (*StarRows, error) {
return star.query(ctx, args...)
}
func (star *StarTx) ExecStmt(args ...interface{}) (sql.Result, error) {
if len(args) <= 1 {
return nil, errors.New("parameter not enough")
}
stmt, err := star.Prepare(args[0].(string))
if err != nil {
return nil, err
}
defer stmt.Close()
return stmt.Exec(args[1:]...)
}
func (star *StarTx) ExecStmtContext(ctx context.Context, args ...interface{}) (sql.Result, error) {
if len(args) <= 1 {
return nil, errors.New("parameter not enough")
}
stmt, err := star.PrepareContext(ctx, args[0].(string))
if err != nil {
return nil, err
}
defer stmt.Close()
return stmt.ExecContext(ctx, args[1:]...)
}
func (star *StarTx) QueryStmt(args ...interface{}) (*StarRows, error) {
if len(args) <= 1 {
return nil, errors.New("parameter not enough")
}
stmt, err := star.Prepare(args[0].(string))
if err != nil {
return nil, err
}
defer stmt.Close()
return stmt.Query(args[1:]...)
}
func (star *StarTx) QueryStmtContext(ctx context.Context, args ...interface{}) (*StarRows, error) {
if len(args) <= 1 {
return nil, errors.New("parameter not enough")
}
stmt, err := star.PrepareContext(ctx, args[0].(string))
if err != nil {
return nil, err
}
defer stmt.Close()
return stmt.QueryContext(ctx, args[1:]...)
}
func (star *StarTx) query(ctx context.Context, args ...interface{}) (*StarRows, error) {
var err error
var rows *sql.Rows
effect := new(StarRows)
if err = star.DB.Ping(); err != nil {
if err = star.Db.Ping(); err != nil {
return effect, err
}
if len(args) == 0 {
return effect, errors.New("no args")
}
if len(args) == 1 {
sql := args[0]
if star.Rows, err = star.DB.Query(sql.(string)); err != nil {
return effect, err
}
effect.Rows = star.Rows
effect.parserows()
return effect, nil
}
sql := args[0]
stmt, err := star.DB.Prepare(sql.(string))
if err != nil {
return effect, err
}
defer stmt.Close()
var para []interface{}
for k, v := range args {
if k != 0 {
@ -760,56 +942,263 @@ func (star *StarDB) Query(args ...interface{}) (*StarRows, error) {
}
}
}
if star.Rows, err = stmt.Query(para...); err != nil {
if ctx == nil {
if rows, err = star.Tx.Query(args[0].(string), para...); err != nil {
return effect, err
}
effect.Rows = star.Rows
effect.parserows()
return effect, nil
} else {
if rows, err = star.Tx.QueryContext(ctx, args[0].(string), para...); err != nil {
return effect, err
}
}
effect.Rows = rows
if !star.Db.ManualScan {
err = effect.parserows()
}
return effect, err
}
func (star *StarDB) Query(args ...interface{}) (*StarRows, error) {
return star.query(nil, args...)
}
func (star *StarDB) QueryContext(ctx context.Context, args ...interface{}) (*StarRows, error) {
return star.query(ctx, args...)
}
func (star *StarDB) QueryStmt(args ...interface{}) (*StarRows, error) {
if len(args) <= 1 {
return nil, errors.New("parameter not enough")
}
stmt, err := star.Prepare(args[0].(string))
if err != nil {
return nil, err
}
defer stmt.Close()
return stmt.Query(args[1:]...)
}
func (star *StarDB) QueryStmtContext(ctx context.Context, args ...interface{}) (*StarRows, error) {
if len(args) <= 1 {
return nil, errors.New("parameter not enough")
}
stmt, err := star.PrepareContext(ctx, args[0].(string))
if err != nil {
return nil, err
}
defer stmt.Close()
return stmt.QueryContext(ctx, args[1:]...)
}
func (star *StarDB) ExecStmt(args ...interface{}) (sql.Result, error) {
if len(args) <= 1 {
return nil, errors.New("parameter not enough")
}
stmt, err := star.Prepare(args[0].(string))
if err != nil {
return nil, err
}
defer stmt.Close()
return stmt.Exec(args[1:]...)
}
func (star *StarDB) ExecStmtContext(ctx context.Context, args ...interface{}) (sql.Result, error) {
if len(args) <= 1 {
return nil, errors.New("parameter not enough")
}
stmt, err := star.PrepareContext(ctx, args[0].(string))
if err != nil {
return nil, err
}
defer stmt.Close()
return stmt.ExecContext(ctx, args[1:]...)
}
func (star *StarDBStmt) Query(args ...interface{}) (*StarRows, error) {
return star.query(nil, args...)
}
func (star *StarDBStmt) QueryContext(ctx context.Context, args ...interface{}) (*StarRows, error) {
return star.query(ctx, args...)
}
func (star *StarDBStmt) Exec(args ...interface{}) (sql.Result, error) {
return star.exec(nil, args...)
}
func (star *StarDBStmt) ExecContext(ctx context.Context, args ...interface{}) (sql.Result, error) {
return star.exec(ctx, args...)
}
func (star *StarDBStmt) Close() error {
return star.Stmt.Close()
}
func (star *StarDBStmt) query(ctx context.Context, args ...interface{}) (*StarRows, error) {
var err error
var rows *sql.Rows
effect := new(StarRows)
if len(args) == 0 {
return effect, errors.New("no args")
}
if ctx == nil {
if rows, err = star.Stmt.Query(args...); err != nil {
return effect, err
}
} else {
if rows, err = star.Stmt.QueryContext(ctx, args...); err != nil {
return effect, err
}
}
effect.Rows = rows
if !star.Db.ManualScan {
err = effect.parserows()
}
return effect, err
}
func (star *StarDBStmt) exec(ctx context.Context, args ...interface{}) (sql.Result, error) {
if len(args) == 0 {
return nil, errors.New("no args")
}
if ctx == nil {
return star.Stmt.Exec(args...)
}
return star.Stmt.ExecContext(ctx, args...)
}
func (star *StarDB) Prepare(sqlStr string) (*StarDBStmt, error) {
stmt := new(StarDBStmt)
stmtS, err := star.Db.Prepare(sqlStr)
if err != nil {
return nil, err
}
stmt.Stmt = stmtS
stmt.Db = star
return stmt, err
}
func (star *StarDB) PrepareContext(ctx context.Context, sqlStr string) (*StarDBStmt, error) {
stmt := new(StarDBStmt)
stmtS, err := star.Db.PrepareContext(ctx, sqlStr)
if err != nil {
return nil, err
}
stmt.Stmt = stmtS
stmt.Db = star
return stmt, err
}
func (star *StarTx) Prepare(sqlStr string) (*StarDBStmt, error) {
stmt := new(StarDBStmt)
stmtS, err := star.Tx.Prepare(sqlStr)
if err != nil {
return nil, err
}
stmt.Stmt = stmtS
stmt.Db = star.Db
return stmt, err
}
func (star *StarTx) PrepareContext(ctx context.Context, sqlStr string) (*StarDBStmt, error) {
stmt := new(StarDBStmt)
stmtS, err := star.Tx.PrepareContext(ctx, sqlStr)
if err != nil {
return nil, err
}
stmt.Db = star.Db
stmt.Stmt = stmtS
return stmt, err
}
// Query 进行Query操作
func (star *StarDB) query(ctx context.Context, args ...interface{}) (*StarRows, error) {
var err error
var rows *sql.Rows
effect := new(StarRows)
if err = star.Db.Ping(); err != nil {
return effect, err
}
if len(args) == 0 {
return effect, errors.New("no args")
}
var para []interface{}
for k, v := range args {
if k != 0 {
switch vtype := v.(type) {
default:
para = append(para, vtype)
}
}
}
if ctx == nil {
if rows, err = star.Db.Query(args[0].(string), para...); err != nil {
return effect, err
}
} else {
if rows, err = star.Db.QueryContext(ctx, args[0].(string), para...); err != nil {
return effect, err
}
}
effect.Rows = rows
if !star.ManualScan {
err = effect.parserows()
}
return effect, err
}
// Open 打开一个新的数据库
func (star *StarDB) Open(Method, ConnStr string) error {
var err error
star.DB, err = sql.Open(Method, ConnStr)
if err != nil {
return err
}
err = star.DB.Ping()
star.Db, err = sql.Open(Method, ConnStr)
return err
}
// Close 关闭打开的数据库
func (star *StarDB) Close() error {
if err := star.DB.Close(); err != nil {
return err
return star.Db.Close()
}
return star.DB.Close()
func (star *StarDB) Ping() error {
return star.Db.Ping()
}
func (star *StarDB) Stats() sql.DBStats {
return star.Db.Stats()
}
func (star *StarDB) SetMaxOpenConns(n int) {
star.Db.SetMaxOpenConns(n)
}
func (star *StarDB) SetMaxIdleConns(n int) {
star.Db.SetMaxIdleConns(n)
}
func (star *StarDB) PingContext(ctx context.Context) error {
return star.Db.PingContext(ctx)
}
func (star *StarDB) Conn(ctx context.Context) (*sql.Conn, error) {
return star.Db.Conn(ctx)
}
func (star *StarDB) Exec(args ...interface{}) (sql.Result, error) {
return star.exec(nil, args...)
}
func (star *StarDB) ExecContext(ctx context.Context, args ...interface{}) (sql.Result, error) {
return star.exec(ctx, args...)
}
// Exec 执行Exec操作
func (star *StarDB) Exec(args ...interface{}) (sql.Result, error) {
func (star *StarDB) exec(ctx context.Context, args ...interface{}) (sql.Result, error) {
var err error
var effect sql.Result
if err = star.DB.Ping(); err != nil {
return effect, err
if err = star.Db.Ping(); err != nil {
return nil, err
}
if len(args) == 0 {
return effect, errors.New("no args")
return nil, errors.New("no args")
}
if len(args) == 1 {
sql := args[0]
if _, err = star.DB.Exec(sql.(string)); err != nil {
return effect, err
}
return effect, nil
}
sql := args[0]
stmt, err := star.DB.Prepare(sql.(string))
if err != nil {
return effect, err
}
defer stmt.Close()
var para []interface{}
for k, v := range args {
if k != 0 {
@ -819,10 +1208,48 @@ func (star *StarDB) Exec(args ...interface{}) (sql.Result, error) {
}
}
}
if effect, err = stmt.Exec(para...); err != nil {
return effect, err
if ctx == nil {
return star.Db.Exec(args[0].(string), para...)
}
return effect, nil
return star.Db.ExecContext(ctx, args[0].(string), para...)
}
func (star *StarTx) Exec(args ...interface{}) (sql.Result, error) {
return star.exec(nil, args...)
}
func (star *StarTx) ExecContext(ctx context.Context, args ...interface{}) (sql.Result, error) {
return star.exec(ctx, args...)
}
func (star *StarTx) exec(ctx context.Context, args ...interface{}) (sql.Result, error) {
var err error
if err = star.Db.Ping(); err != nil {
return nil, err
}
if len(args) == 0 {
return nil, errors.New("no args")
}
var para []interface{}
for k, v := range args {
if k != 0 {
switch vtype := v.(type) {
default:
para = append(para, vtype)
}
}
}
if ctx == nil {
return star.Tx.Exec(args[0].(string), para...)
}
return star.Tx.ExecContext(ctx, args[0].(string), para...)
}
func (star *StarTx) Commit() error {
return star.Tx.Commit()
}
func (star *StarTx) Rollback() error {
return star.Tx.Rollback()
}
// FetchAll 把结果集全部转为key-value型<string>数据