-
Notifications
You must be signed in to change notification settings - Fork 1
/
orm_test.go
115 lines (100 loc) · 2.87 KB
/
orm_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package orm
import (
"context"
"fmt"
"testing"
"time"
db2 "github.com/assembly-hub/db"
"github.com/assembly-hub/orm/dbtype"
)
type Table1 struct {
ID int `json:"id"`
Name string `json:"name"`
// type: 指定字段接收数据类型,目前为固定值:json
JSON []int `json:"json" type:"json"`
// tb:查询tag,跨表查询可以用
// ref:关联配置,left是关联逻辑;tb_id=id为关联条件,多个逗号隔开
// 如:left;tb_id=id,name=name,其中tb_id为当前表字段,id为被关联表字段,以此类推
Tb *Table2 `json:"tb2" ref:"left;ref=id"`
}
type Table2 struct {
ID int `json:"id"`
Name string `json:"name"`
Tb *Table3 `json:"tb3" ref:"left;ref=id"`
}
type Table3 struct {
ID int `json:"id"`
Name string `json:"name"`
Tb *Table1 `json:"tb1" ref:"left;ref=id"`
}
var ref *Reference
func init() {
// 使用之前需要完成表定义
// 定义表关联
// mysql mariadb sqlserver postgres opengauss sqllite oracle
// mysql mariadb sqlserver postgres opengauss sqllite oracle
ref = NewReference(dbtype.MySQL)
// 添加表定义
ref.AddTableDef("table1", Table1{})
ref.AddTableDef("table2", Table2{})
ref.AddTableDef("table3", Table3{})
// 编译表关系
ref.BuildRefs()
}
func TestORM_Query(t *testing.T) {
var db db2.Executor
orm := NewORM(context.Background(), "table1", db, ref)
orm.Select("tb2.count(id) as c", "id")
orm.Wheres(map[string]interface{}{
"id__gt": 0,
"tb2.count(id)__gt": 0,
})
orm.GroupBy("tb2.name").Having("#c__gt", 1)
fmt.Println(orm.ToSQL(false))
}
func TestORM(t *testing.T) {
var db db2.Executor
orm := NewORM(context.Background(), "table1", db, ref)
_, err := orm.ReplaceManySameClos([]interface{}{map[string]interface{}{
"id": 1,
"name": "test ORM",
}, map[string]interface{}{
"id": 2,
"name": "test ORM2",
}}, []string{"id", "name"}, 10, true)
if err != nil {
fmt.Println(err.Error())
}
}
func TestORM2(t *testing.T) {
var db db2.Executor
orm := NewORM(context.Background(), "table1", db, ref)
_, err := orm.ReplaceOne(map[string]interface{}{
"id": 1,
"name": "test ORM",
})
if err != nil {
fmt.Println(err.Error())
}
}
func TestORM3(t *testing.T) {
var db db2.Executor
orm := NewORM(context.Background(), "table1", db, ref)
orm.Wheres(Where{
"id__gt": 0, // table1的id > 1
"name__startswith": "test", // table1的name like 'test%'
// tb2:table1的tag字段(可以理解为table2的别名),tb3:table2的tag字段(可以理解为table3的别名)
// 含义:select * from table1 left join table2 left join table3 where table3.id > 1
"tb2.tb3.id__gt": 1,
"dt__date": "2023-01-01",
})
orm.Page(1, 10)
t1 := time.Now()
c := 1000000
for i := 0; i < c; i++ {
orm.ToSQL(false)
}
t2 := time.Now()
fmt.Println(float64(t2.UnixMicro()-t1.UnixMicro()) / float64(c))
fmt.Println(orm.ToSQL(false))
}