Merge branch 'master' of https://github.com/gogf/gf into gogf-master

This commit is contained in:
hailaz 2021-11-18 09:52:27 +08:00
commit 747ed6c64d
1063 changed files with 10717 additions and 18202 deletions

View File

@ -1,46 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/container/garray"
)
func main() {
// Create a int array, which is concurrent-unsafe in default.
a := garray.NewIntArray()
// Appending items.
for i := 0; i < 10; i++ {
a.Append(i)
}
// Get the length of the array.
fmt.Println(a.Len())
// Get the slice of the array.
fmt.Println(a.Slice())
// Get the item of specified index.
fmt.Println(a.Get(6))
// Insert after/before specified index.
a.InsertAfter(9, 11)
a.InsertBefore(10, 10)
fmt.Println(a.Slice())
a.Set(0, 100)
fmt.Println(a.Slice())
// Searching the item and returning the index.
fmt.Println(a.Search(5))
// Remove item of specified index.
a.Remove(0)
fmt.Println(a.Slice())
// Clearing the array.
fmt.Println(a.Slice())
a.Clear()
fmt.Println(a.Slice())
}

View File

@ -1,22 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"github.com/gogf/gf/v2/container/garray"
)
func main() {
type Student struct {
Id int
Name string
Scores *garray.IntArray
}
s := Student{
Id: 1,
Name: "john",
Scores: garray.NewIntArrayFrom([]int{100, 99, 98}),
}
b, _ := json.Marshal(s)
fmt.Println(string(b))
}

View File

@ -1,19 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"github.com/gogf/gf/v2/container/garray"
)
func main() {
b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`)
type Student struct {
Id int
Name string
Scores *garray.IntArray
}
s := Student{}
json.Unmarshal(b, &s)
fmt.Println(s)
}

View File

@ -1,40 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/container/garray"
)
func main() {
// 自定义排序数组,降序排序(SortedIntArray管理的数据是升序)
a := garray.NewSortedArray(func(v1, v2 interface{}) int {
if v1.(int) < v2.(int) {
return 1
}
if v1.(int) > v2.(int) {
return -1
}
return 0
})
// 添加数据
a.Add(2)
a.Add(3)
a.Add(1)
fmt.Println(a.Slice())
// 添加重复数据
a.Add(3)
fmt.Println(a.Slice())
// 检索数据,返回最后对比的索引位置,检索结果
// 检索结果0: 匹配; <0:参数小于对比值; >0:参数大于对比值
fmt.Println(a.Search(1))
// 设置不可重复
a.SetUnique(true)
fmt.Println(a.Slice())
a.Add(1)
fmt.Println(a.Slice())
}

View File

@ -1,23 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/container/garray"
)
func main() {
array := garray.NewSortedStrArray()
array.Add("9")
array.Add("8")
array.Add("7")
array.Add("6")
array.Add("5")
array.Add("4")
array.Add("3")
array.Add("2")
array.Add("1")
fmt.Println(array.Slice())
// output:
// [1 2 3 4 5 6 7 8 9]
}

View File

@ -1,22 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/container/glist"
)
func main() {
l := glist.New()
// Push
l.PushBack(1)
l.PushBack(2)
e := l.PushFront(0)
// Insert
l.InsertBefore(e, -1)
l.InsertAfter(e, "a")
fmt.Println(l)
// Pop
fmt.Println(l.PopFront())
fmt.Println(l.PopBack())
fmt.Println(l)
}

View File

@ -1,23 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"github.com/gogf/gf/v2/container/glist"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
type Student struct {
Id int
Name string
Scores *glist.List
}
s := Student{
Id: 1,
Name: "john",
Scores: glist.NewFrom(g.Slice{100, 99, 98}),
}
b, _ := json.Marshal(s)
fmt.Println(string(b))
}

View File

@ -1,19 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"github.com/gogf/gf/v2/container/glist"
)
func main() {
b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`)
type Student struct {
Id int
Name string
Scores *glist.List
}
s := Student{}
json.Unmarshal(b, &s)
fmt.Println(s)
}

View File

@ -1,74 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/container/gmap"
)
func main() {
// 创建一个默认的gmap对象
// 默认情况下该gmap对象不支持并发安全特性
// 初始化时可以给定true参数开启并发安全特性用以并发安全场景。
m := gmap.New()
// 设置键值对
for i := 0; i < 10; i++ {
m.Set(i, i)
}
// 查询大小
fmt.Println(m.Size())
// 批量设置键值对(不同的数据类型对象参数不同)
m.Sets(map[interface{}]interface{}{
10: 10,
11: 11,
})
fmt.Println(m.Size())
// 查询是否存在
fmt.Println(m.Contains(1))
// 查询键值
fmt.Println(m.Get(1))
// 删除数据项
m.Remove(9)
fmt.Println(m.Size())
// 批量删除
m.Removes([]interface{}{10, 11})
fmt.Println(m.Size())
// 当前键名列表(随机排序)
fmt.Println(m.Keys())
// 当前键值列表(随机排序)
fmt.Println(m.Values())
// 查询键名,当键值不存在时,写入给定的默认值
fmt.Println(m.GetOrSet(100, 100))
// 删除键值对,并返回对应的键值
fmt.Println(m.Remove(100))
// 遍历map
m.Iterator(func(k interface{}, v interface{}) bool {
fmt.Printf("%v:%v ", k, v)
return true
})
// 自定义写锁操作
m.LockFunc(func(m map[interface{}]interface{}) {
m[99] = 99
})
// 自定义读锁操作
m.RLockFunc(func(m map[interface{}]interface{}) {
fmt.Println(m[99])
})
// 清空map
m.Clear()
// 判断map是否为空
fmt.Println(m.IsEmpty())
}

View File

@ -1,19 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/container/gmap"
)
func main() {
m := gmap.New()
m.Sets(g.MapAnyAny{
"name": "john",
"score": 100,
})
b, _ := json.Marshal(m)
fmt.Println(string(b))
}

View File

@ -1,14 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"github.com/gogf/gf/v2/container/gmap"
)
func main() {
m := gmap.Map{}
s := []byte(`{"name":"john","score":100}`)
json.Unmarshal(s, &m)
fmt.Println(m.Map())
}

View File

@ -1,26 +0,0 @@
package main
import (
"github.com/gogf/gf/v2/container/gmap"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
m1 := gmap.New(true)
m1.Set("1", "1")
m2 := m1.Map()
m2["2"] = "2"
g.Dump(m1.Clone())
g.Dump(m2)
//output:
//{
// "1": "1"
//}
//
//{
// "1": "1",
// "2": "2"
//}
}

View File

@ -1,31 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/container/gmap"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gutil"
)
func main() {
array := g.Slice{2, 3, 1, 5, 4, 6, 8, 7, 9}
hashMap := gmap.New()
linkMap := gmap.NewListMap()
treeMap := gmap.NewTreeMap(gutil.ComparatorInt)
for _, v := range array {
hashMap.Set(v, v)
}
for _, v := range array {
linkMap.Set(v, v)
}
for _, v := range array {
treeMap.Set(v, v)
}
fmt.Println("HashMap Keys:", hashMap.Keys())
fmt.Println("HashMap Values:", hashMap.Values())
fmt.Println("LinkMap Keys:", linkMap.Keys())
fmt.Println("LinkMap Values:", linkMap.Values())
fmt.Println("TreeMap Keys:", treeMap.Keys())
fmt.Println("TreeMap Values:", treeMap.Values())
}

View File

@ -1,63 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/container/gmap"
"github.com/gogf/gf/v2/util/gutil"
)
func main() {
m := gmap.NewTreeMap(gutil.ComparatorInt)
// 设置键值对
for i := 0; i < 10; i++ {
m.Set(i, i)
}
// 查询大小
fmt.Println(m.Size())
// 批量设置键值对(不同的数据类型对象参数不同)
m.Sets(map[interface{}]interface{}{
10: 10,
11: 11,
})
fmt.Println(m.Size())
// 查询是否存在
fmt.Println(m.Contains(1))
// 查询键值
fmt.Println(m.Get(1))
// 删除数据项
m.Remove(9)
fmt.Println(m.Size())
// 批量删除
m.Removes([]interface{}{10, 11})
fmt.Println(m.Size())
// 当前键名列表(随机排序)
fmt.Println(m.Keys())
// 当前键值列表(随机排序)
fmt.Println(m.Values())
// 查询键名,当键值不存在时,写入给定的默认值
fmt.Println(m.GetOrSet(100, 100))
// 删除键值对,并返回对应的键值
fmt.Println(m.Remove(100))
// 遍历map
m.IteratorAsc(func(k interface{}, v interface{}) bool {
fmt.Printf("%v:%v ", k, v)
return true
})
fmt.Println()
// 清空map
m.Clear()
// 判断map是否为空
fmt.Println(m.IsEmpty())
}

View File

@ -1,26 +0,0 @@
package main
import (
"fmt"
"time"
"github.com/gogf/gf/v2/container/gpool"
)
func main() {
// 创建一个对象池过期时间为1000毫秒
p := gpool.New(1000*time.Millisecond, nil)
// 从池中取一个对象返回nil及错误信息
fmt.Println(p.Get())
// 丢一个对象到池中
p.Put(1)
// 重新从池中取一个对象返回1
fmt.Println(p.Get())
// 等待1秒后重试发现对象已过期返回nil及错误信息
time.Sleep(time.Second)
fmt.Println(p.Get())
}

View File

@ -1,33 +0,0 @@
package main
import (
"fmt"
"time"
"github.com/gogf/gf/v2/container/gpool"
"github.com/gogf/gf/v2/net/gtcp"
"github.com/gogf/gf/v2/os/glog"
)
func main() {
// 创建对象复用池对象过期时间为3000毫秒并给定创建及销毁方法
p := gpool.New(3000*time.Millisecond, func() (interface{}, error) {
return gtcp.NewConn("www.baidu.com:80")
}, func(i interface{}) {
glog.Print("expired")
i.(*gtcp.Conn).Close()
})
conn, err := p.Get()
if err != nil {
panic(err)
}
result, err := conn.(*gtcp.Conn).SendRecv([]byte("HEAD / HTTP/1.1\n\n"), -1)
if err != nil {
panic(err)
}
fmt.Println(string(result))
// 丢回池中以便重复使用
p.Put(conn)
// 等待一定时间观察过期方法调用
time.Sleep(4 * time.Second)
}

View File

@ -1,34 +0,0 @@
package main
import (
"fmt"
"time"
"github.com/gogf/gf/v2/container/gqueue"
"github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/os/gtimer"
)
func main() {
q := gqueue.New()
// 数据生产者每隔1秒往队列写数据
gtimer.SetInterval(time.Second, func() {
v := gtime.Now().String()
q.Push(v)
fmt.Println("Push:", v)
})
// 3秒后关闭队列
gtimer.SetTimeout(3*time.Second, func() {
q.Close()
})
// 消费者,不停读取队列数据并输出到终端
for {
if v := q.Pop(); v != nil {
fmt.Println(" Pop:", v)
} else {
break
}
}
}

View File

@ -1,28 +0,0 @@
package main
import (
"fmt"
"time"
"github.com/gogf/gf/v2/container/gqueue"
"github.com/gogf/gf/v2/os/gtimer"
)
func main() {
q := gqueue.New()
// 数据生产者每隔1秒往队列写数据
gtimer.SetInterval(time.Second, func() {
for i := 0; i < 10; i++ {
q.Push(i)
}
})
// 消费者,不停读取队列数据并输出到终端
for {
if v := q.Pop(); v != nil {
fmt.Println(" Pop:", v)
} else {
break
}
}
}

View File

@ -1,30 +0,0 @@
package main
import (
"fmt"
"time"
"github.com/gogf/gf/v2/container/gqueue"
"github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/os/gtimer"
)
func main() {
queue := gqueue.New()
// 数据生产者每隔1秒往队列写数据
gtimer.SetInterval(time.Second, func() {
queue.Push(gtime.Now().String())
})
// 消费者,不停读取队列数据并输出到终端
for {
select {
case v := <-queue.C:
if v != nil {
fmt.Println(v)
} else {
return
}
}
}
}

View File

@ -1,28 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/container/gring"
)
func main() {
r1 := gring.New(10)
for i := 0; i < 5; i++ {
r1.Set(i).Next()
}
fmt.Println("Len:", r1.Len())
fmt.Println("Cap:", r1.Cap())
fmt.Println(r1.SlicePrev())
fmt.Println(r1.SliceNext())
r2 := gring.New(10)
for i := 0; i < 10; i++ {
r2.Set(i).Next()
}
fmt.Println("Len:", r2.Len())
fmt.Println("Cap:", r2.Cap())
fmt.Println(r2.SlicePrev())
fmt.Println(r2.SliceNext())
}

View File

@ -1,58 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/container/gring"
)
type Player struct {
position int // 位置
alive bool // 是否存活
}
const (
playerCount = 41 // 玩家人数
startPos = 1 // 开始报数位置
)
var (
deadline = 3
)
func main() {
// 关闭并发安全,当前场景没有必要
r := gring.New(playerCount, false)
// 设置所有玩家初始值
for i := 1; i <= playerCount; i++ {
r.Put(&Player{i, true})
}
// 如果开始报数的位置不为1则设置开始位置
if startPos > 1 {
r.Move(startPos - 1)
}
counter := 1 // 报数从1开始因为下面的循环从第二个开始计算
deadCount := 0 // 死亡人数初始值为0
// 直到所有人都死亡,否则循环一直执行
for deadCount < playerCount {
// 跳到下一个人
r.Next()
// 如果是活着的人,则报数
if r.Val().(*Player).alive {
counter++
}
// 如果报数为deadline则此人淘汰出局
if counter == deadline {
r.Val().(*Player).alive = false
fmt.Printf("Player %d died!\n", r.Val().(*Player).position)
deadCount++
counter = 0
}
}
}

View File

@ -1,53 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/container/gset"
)
func main() {
// 创建一个非并发安全的集合对象
s := gset.New(true)
// 添加数据项
s.Add(1)
// 批量添加数据项
s.Add([]interface{}{1, 2, 3}...)
// 集合数据项大小
fmt.Println(s.Size())
// 集合中是否存在指定数据项
fmt.Println(s.Contains(2))
// 返回数据项slice
fmt.Println(s.Slice())
// 删除数据项
s.Remove(3)
// 遍历数据项
s.Iterator(func(v interface{}) bool {
fmt.Println("Iterator:", v)
return true
})
// 将集合转换为字符串
fmt.Println(s.String())
// 并发安全写锁操作
s.LockFunc(func(m map[interface{}]struct{}) {
m[4] = struct{}{}
})
// 并发安全读锁操作
s.RLockFunc(func(m map[interface{}]struct{}) {
fmt.Println(m)
})
// 清空集合
s.Clear()
fmt.Println(s.Size())
}

View File

@ -1,23 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/container/gset"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
s1 := gset.NewFrom(g.Slice{1, 2, 3})
s2 := gset.NewFrom(g.Slice{4, 5, 6})
s3 := gset.NewFrom(g.Slice{1, 2, 3, 4, 5, 6, 7})
// 交集
fmt.Println(s3.Intersect(s1).Slice())
// 差集
fmt.Println(s3.Diff(s1).Slice())
// 并集
fmt.Println(s1.Union(s2).Slice())
// 补集
fmt.Println(s1.Complement(s3).Slice())
}

View File

@ -1,22 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"github.com/gogf/gf/v2/container/gset"
)
func main() {
type Student struct {
Id int
Name string
Scores *gset.IntSet
}
s := Student{
Id: 1,
Name: "john",
Scores: gset.NewIntSetFrom([]int{100, 99, 98}),
}
b, _ := json.Marshal(s)
fmt.Println(string(b))
}

View File

@ -1,19 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"github.com/gogf/gf/v2/container/gset"
)
func main() {
b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`)
type Student struct {
Id int
Name string
Scores *gset.IntSet
}
s := Student{}
json.Unmarshal(b, &s)
fmt.Println(s)
}

View File

@ -1,29 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/container/gtree"
"github.com/gogf/gf/v2/util/gutil"
)
func main() {
tree := gtree.NewAVLTree(gutil.ComparatorInt)
for i := 0; i < 10; i++ {
tree.Set(i, i*10)
}
// 打印树形
tree.Print()
// 前序遍历
fmt.Println("ASC:")
tree.IteratorAsc(func(key, value interface{}) bool {
fmt.Println(key, value)
return true
})
// 后续遍历
fmt.Println("DESC:")
tree.IteratorDesc(func(key, value interface{}) bool {
fmt.Println(key, value)
return true
})
}

View File

@ -1,22 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/container/gtree"
)
func main() {
tree := gtree.NewBTree(10, func(v1, v2 interface{}) int {
return v1.(int) - v2.(int)
})
for i := 0; i < 20; i++ {
tree.Set(i, i*10)
}
fmt.Println(tree.String())
tree.IteratorDesc(func(key, value interface{}) bool {
fmt.Println(key, value)
return true
})
}

View File

@ -1,63 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/container/gtree"
"github.com/gogf/gf/v2/util/gutil"
)
func main() {
m := gtree.NewRedBlackTree(gutil.ComparatorInt)
// 设置键值对
for i := 0; i < 10; i++ {
m.Set(i, i*10)
}
// 查询大小
fmt.Println(m.Size())
// 批量设置键值对(不同的数据类型对象参数不同)
m.Sets(map[interface{}]interface{}{
10: 10,
11: 11,
})
fmt.Println(m.Size())
// 查询是否存在
fmt.Println(m.Contains(1))
// 查询键值
fmt.Println(m.Get(1))
// 删除数据项
m.Remove(9)
fmt.Println(m.Size())
// 批量删除
m.Removes([]interface{}{10, 11})
fmt.Println(m.Size())
// 当前键名列表(随机排序)
fmt.Println(m.Keys())
// 当前键值列表(随机排序)
fmt.Println(m.Values())
// 查询键名,当键值不存在时,写入给定的默认值
fmt.Println(m.GetOrSet(100, 100))
// 删除键值对,并返回对应的键值
fmt.Println(m.Remove(100))
// 遍历map
m.IteratorAsc(func(k interface{}, v interface{}) bool {
fmt.Printf("%v:%v ", k, v)
return true
})
fmt.Println()
// 清空map
m.Clear()
// 判断map是否为空
fmt.Println(m.IsEmpty())
}

View File

@ -1,17 +0,0 @@
package main
import (
"github.com/gogf/gf/v2/container/gtree"
)
func main() {
tree := gtree.NewRedBlackTree(func(v1, v2 interface{}) int {
return v1.(int) - v2.(int)
})
for i := 0; i < 10; i++ {
tree.Set(i, i)
}
tree.Print()
tree.Flip()
tree.Print()
}

View File

@ -1,21 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/container/gtype"
)
func main() {
// 创建一个Int型的并发安全基本类型对象
i := gtype.NewInt()
// 设置值
i.Set(10)
// 获取值
fmt.Println(i.Val())
// (整型/浮点型有效)数值 增加/删除 delta
fmt.Println(i.Add(-1))
}

View File

@ -1,22 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"github.com/gogf/gf/v2/container/gtype"
)
func main() {
type Student struct {
Id *gtype.Int
Name *gtype.String
Scores *gtype.Interface
}
s := Student{
Id: gtype.NewInt(1),
Name: gtype.NewString("john"),
Scores: gtype.NewInterface([]int{100, 99, 98}),
}
b, _ := json.Marshal(s)
fmt.Println(string(b))
}

View File

@ -1,19 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"github.com/gogf/gf/v2/container/gtype"
)
func main() {
b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`)
type Student struct {
Id *gtype.Int
Name *gtype.String
Scores *gtype.Interface
}
s := Student{}
json.Unmarshal(b, &s)
fmt.Println(s)
}

View File

@ -1,22 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
type Student struct {
Id *g.Var
Name *g.Var
Scores *g.Var
}
s := Student{
Id: g.NewVar(1),
Name: g.NewVar("john"),
Scores: g.NewVar([]int{100, 99, 98}),
}
b, _ := json.Marshal(s)
fmt.Println(string(b))
}

View File

@ -1,19 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
b := []byte(`{"Id":1,"Name":"john","Scores":[100,99,98]}`)
type Student struct {
Id *g.Var
Name *g.Var
Scores *g.Var
}
s := Student{}
json.Unmarshal(b, &s)
fmt.Println(s)
}

View File

@ -1,33 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
var v g.Var
v.Set("123")
fmt.Println(v.Val())
// 基本类型转换
fmt.Println(v.Int())
fmt.Println(v.Uint())
fmt.Println(v.Float64())
// slice转换
fmt.Println(v.Ints())
fmt.Println(v.Floats())
fmt.Println(v.Strings())
// struct转换
type Score struct {
Value int
}
s := new(Score)
v.Struct(s)
fmt.Println(s)
}

View File

@ -1,71 +0,0 @@
package driver
import (
"context"
"database/sql"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/os/gtime"
)
// MyDriver is a custom database driver, which is used for testing only.
// For simplifying the unit testing case purpose, MyDriver struct inherits the mysql driver
// gdb.DriverMysql and overwrites its functions DoQuery and DoExec.
// So if there's any sql execution, it goes through MyDriver.DoQuery/MyDriver.DoExec firstly
// and then gdb.DriverMysql.DoQuery/gdb.DriverMysql.DoExec.
// You can call it sql "HOOK" or "HiJack" as your will.
type MyDriver struct {
*gdb.DriverMysql
}
var (
// customDriverName is my driver name, which is used for registering.
customDriverName = "MyDriver"
)
func init() {
// It here registers my custom driver in package initialization function "init".
// You can later use this type in the database configuration.
if err := gdb.Register(customDriverName, &MyDriver{}); err != nil {
panic(err)
}
}
// New creates and returns a database object for mysql.
// It implements the interface of gdb.Driver for extra database driver installation.
func (d *MyDriver) New(core *gdb.Core, node *gdb.ConfigNode) (gdb.DB, error) {
return &MyDriver{
&gdb.DriverMysql{
Core: core,
},
}, nil
}
// DoQuery commits the sql string and its arguments to underlying driver
// through given link object and returns the execution result.
func (d *MyDriver) DoQuery(ctx context.Context, link gdb.Link, sql string, args ...interface{}) (rows *sql.Rows, err error) {
tsMilli := gtime.TimestampMilli()
rows, err = d.DriverMysql.DoQuery(ctx, link, sql, args...)
link.Exec(
"INSERT INTO `monitor`(`sql`,`cost`,`time`,`error`) VALUES(?,?,?,?)",
gdb.FormatSqlWithArgs(sql, args),
gtime.TimestampMilli()-tsMilli,
gtime.Now(),
err,
)
return
}
// DoExec commits the query string and its arguments to underlying driver
// through given link object and returns the execution result.
func (d *MyDriver) DoExec(ctx context.Context, link gdb.Link, sql string, args ...interface{}) (result sql.Result, err error) {
tsMilli := gtime.TimestampMilli()
result, err = d.DriverMysql.DoExec(ctx, link, sql, args...)
link.Exec(
"INSERT INTO `monitor`(`sql`,`cost`,`time`,`error`) VALUES(?,?,?,?)",
gdb.FormatSqlWithArgs(sql, args),
gtime.TimestampMilli()-tsMilli,
gtime.Now(),
err,
)
return
}

View File

@ -1 +0,0 @@
package main

View File

@ -1,3 +0,0 @@
[database]
linkinfo = "mssql:user id=test;password=test1;server=122.152.202.91;port=1433;database=test;encrypt=disable"

View File

@ -1,23 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/os/gtime"
//_ "github.com/denisenkom/go-mssqldb"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
type Table2 struct {
Id string `orm:"id;pr" json:"id"` //ID
CreateTime gtime.Time `orm:"createtime" json:"createtime"` //创建时间
UpdateTime gtime.Time `orm:"updatetime" json:"updatetime"` //更新时间
}
var table2 Table2
err := g.DB().Model("table2").Where("id", 1).Scan(&table2)
if err != nil {
panic(err)
}
fmt.Println(table2.CreateTime)
}

View File

@ -1,565 +0,0 @@
package main
import (
"fmt"
"time"
//_ "github.com/denisenkom/go-mssqldb"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// 本文件用于gf框架的mssql数据库操作示例不作为单元测试使用
var db gdb.DB
// 初始化配置及创建数据库
func init() {
gdb.AddDefaultConfigNode(gdb.ConfigNode{
Host: "127.0.0.1",
Port: "1433",
User: "sa",
Pass: "123456",
Name: "test",
Type: "mssql",
Role: "master",
Charset: "utf8",
})
db, _ = gdb.New()
//gins.Config().SetPath("/home/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/.example/frame")
//db = g.Database()
//gdb.SetConfig(gdb.ConfigNode {
// Host : "127.0.0.1",
// Port : 3306,
// User : "root",
// Pass : "123456",
// Name : "test",
// Type : "mysql",
//})
//db, _ = gdb.Instance()
//gdb.SetConfig(gdb.Config {
// "default" : gdb.ConfigGroup {
// gdb.ConfigNode {
// Host : "127.0.0.1",
// Port : "3306",
// User : "root",
// Pass : "123456",
// Name : "test",
// Type : "mysql",
// Role : "master",
// Weight : 100,
// },
// gdb.ConfigNode {
// Host : "127.0.0.2",
// Port : "3306",
// User : "root",
// Pass : "123456",
// Name : "test",
// Type : "mysql",
// Role : "master",
// Weight : 100,
// },
// gdb.ConfigNode {
// Host : "127.0.0.3",
// Port : "3306",
// User : "root",
// Pass : "123456",
// Name : "test",
// Type : "mysql",
// Role : "master",
// Weight : 100,
// },
// gdb.ConfigNode {
// Host : "127.0.0.4",
// Port : "3306",
// User : "root",
// Pass : "123456",
// Name : "test",
// Type : "mysql",
// Role : "master",
// Weight : 100,
// },
// },
//})
//db, _ = gdb.Instance()
}
// 创建测试数据库
func create() error {
fmt.Println("drop table aa_user:")
_, err := db.Exec("drop table aa_user")
if err != nil {
fmt.Println("drop table aa_user error.", err)
}
s := `
CREATE TABLE aa_user (
id int not null,
name VARCHAR(60),
age int,
addr varchar(60),
PRIMARY KEY (id)
)
`
fmt.Println("create table aa_user:")
_, err = db.Exec(s)
if err != nil {
fmt.Println("create table error.", err)
return err
}
/*_, err = db.Exec("drop sequence id_seq")
if err != nil {
fmt.Println("drop sequence id_seq", err)
}
fmt.Println("create sequence id_seq")
_, err = db.Exec("create sequence id_seq increment by 1 start with 1 maxvalue 9999999999 cycle cache 10")
if err != nil {
fmt.Println("create sequence id_seq error.", err)
return err
}
s = `
CREATE TRIGGER id_trigger before insert on aa_user for each row
begin
select id_seq.nextval into :new.id from dual;
end;
`
_, err = db.Exec(s)
if err != nil {
fmt.Println("create trigger error.", err)
return err
}*/
_, err = db.Exec("drop table user_detail")
if err != nil {
fmt.Println("drop table user_detail", err)
}
s = `
CREATE TABLE user_detail (
id int not null,
site VARCHAR(255),
PRIMARY KEY (id)
)
`
fmt.Println("create table user_detail:")
_, err = db.Exec(s)
if err != nil {
fmt.Println("create table user_detail error.", err)
return err
}
fmt.Println("create table success.")
return nil
}
// 数据写入
func insert(id int) {
fmt.Println("insert:")
r, err := db.Insert("aa_user", gdb.Map{
"id": id,
"name": "john",
"age": id,
})
fmt.Println(r.LastInsertId())
fmt.Println(r.RowsAffected())
if err == nil {
r, err = db.Insert("user_detail", gdb.Map{
"id": id,
"site": "http://johng.cn",
})
if err == nil {
fmt.Printf("id: %d\n", id)
} else {
fmt.Println(err)
}
} else {
fmt.Println(err)
}
fmt.Println()
}
// 基本sql查询
func query() {
fmt.Println("query:")
list, err := db.GetAll("select * from aa_user where 1=1")
if err == nil {
fmt.Println(list)
} else {
fmt.Println(err)
}
list, err = db.Table("aa_user").OrderBy("id").Limit(0, 5).Select()
if err == nil {
fmt.Println(list)
} else {
fmt.Println(err)
}
fmt.Println()
}
// replace into
func replace() {
fmt.Println("replace:")
r, err := db.Save("aa_user", gdb.Map{
"id": 1,
"name": "john",
})
if err == nil {
fmt.Println(r.LastInsertId())
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 数据保存
func save() {
fmt.Println("save:")
r, err := db.Save("aa_user", gdb.Map{
"id": 1,
"name": "john",
})
if err == nil {
fmt.Println(r.LastInsertId())
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 批量写入
func batchInsert() {
fmt.Println("batchInsert:")
_, err := db.BatchInsert("aa_user", gdb.List{
{"id": 11, "name": "batchInsert_john_1", "age": 11},
{"id": 12, "name": "batchInsert_john_2", "age": 12},
{"id": 13, "name": "batchInsert_john_3", "age": 13},
{"id": 14, "name": "batchInsert_john_4", "age": 14},
}, 10)
if err != nil {
fmt.Println(err)
}
fmt.Println()
}
// 数据更新
func update1() {
fmt.Println("update1:")
r, err := db.Update("aa_user", gdb.Map{"name": "john1", "age": 1}, "id=?", 1)
if err == nil {
fmt.Println(r.LastInsertId())
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 数据更新
func update2() {
fmt.Println("update2:")
r, err := db.Update("aa_user", gdb.Map{"name": "john6", "age": 6}, "id=?", 2)
if err == nil {
fmt.Println(r.LastInsertId())
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 数据更新
func update3() {
fmt.Println("update3:")
r, err := db.Update("aa_user", "name=?", "id=?", "john2", 3)
if err == nil {
fmt.Println(r.LastInsertId())
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 链式查询操作1
func linkopSelect1() {
fmt.Println("linkopSelect1:")
r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("u.*, ud.site").Where("u.id > ?", 1).Limit(3, 5).Select()
if err == nil {
fmt.Println(r)
} else {
fmt.Println(err)
}
fmt.Println()
}
// 链式查询操作2
func linkopSelect2() {
fmt.Println("linkopSelect2:")
r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("u.*,ud.site").Where("u.id=?", 1).One()
if err == nil {
fmt.Println(r)
} else {
fmt.Println(err)
}
fmt.Println()
}
// 链式查询操作3
func linkopSelect3() {
fmt.Println("linkopSelect3:")
r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("ud.site").Where("u.id=?", 1).Value()
if err == nil {
fmt.Println(r.String())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 链式查询数量1
func linkopCount1() {
fmt.Println("linkopCount1:")
r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Where("name like ?", "john").Count()
if err == nil {
fmt.Println(r)
} else {
fmt.Println(err)
}
fmt.Println()
}
// 错误操作
func linkopUpdate1() {
fmt.Println("linkopUpdate1:")
r, err := db.Table("henghe_setting").Update()
if err == nil {
fmt.Println(r.RowsAffected())
} else {
fmt.Println("error", err)
}
fmt.Println()
}
// 通过Map指针方式传参方式
func linkopUpdate2() {
fmt.Println("linkopUpdate2:")
r, err := db.Table("aa_user").Data(gdb.Map{"name": "john2"}).Where("name=?", "john").Update()
if err == nil {
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 通过字符串方式传参
func linkopUpdate3() {
fmt.Println("linkopUpdate3:")
r, err := db.Table("aa_user").Data("name='john3'").Where("name=?", "john2").Update()
if err == nil {
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// Where条件使用Map
func linkopUpdate4() {
fmt.Println("linkopUpdate4:")
r, err := db.Table("aa_user").Data(gdb.Map{"name": "john11111"}).Where(g.Map{"id": 1}).Update()
if err == nil {
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 链式批量写入
func linkopBatchInsert1() {
fmt.Println("linkopBatchInsert1:")
r, err := db.Table("aa_user").Filter().Data(gdb.List{
{"id": 21, "name": "linkopBatchInsert1_john_1", "amt": 21.21, "tt": "haha"},
{"id": 22, "name": "linkopBatchInsert1_john_2", "amt": 22.22, "cc": "hahacc"},
{"id": 23, "name": "linkopBatchInsert1_john_3", "amt": 23.23, "bb": "hahabb"},
{"id": 24, "name": "linkopBatchInsert1_john_4", "amt": 24.24, "aa": "hahaaa"},
}).Insert()
if err == nil {
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 链式批量写入,指定每批次写入的条数
func linkopBatchInsert2() {
fmt.Println("linkopBatchInsert2:")
r, err := db.Table("aa_user").Data(gdb.List{
{"id": 25, "name": "linkopBatchInsert2john_1"},
{"id": 26, "name": "linkopBatchInsert2john_2"},
{"id": 27, "name": "linkopBatchInsert2john_3"},
{"id": 28, "name": "linkopBatchInsert2john_4"},
}).Batch(2).Insert()
if err == nil {
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 链式批量保存
func linkopBatchSave() {
fmt.Println("linkopBatchSave:")
r, err := db.Table("aa_user").Data(gdb.List{
{"id": 1, "name": "john_1"},
{"id": 2, "name": "john_2"},
{"id": 3, "name": "john_3"},
{"id": 4, "name": "john_4"},
}).Save()
if err == nil {
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 事务操作示例1
func transaction1() {
fmt.Println("transaction1:")
if tx, err := db.Begin(); err == nil {
r, err := tx.Insert("aa_user", gdb.Map{
"id": 30,
"name": "transaction1",
})
tx.Rollback()
fmt.Println(r, err)
}
fmt.Println()
}
// 事务操作示例2
func transaction2() {
fmt.Println("transaction2:")
if tx, err := db.Begin(); err == nil {
r, err := tx.Table("user_detail").Data(gdb.Map{"id": 6, "site": "www.baidu.com哈哈哈*?''\"~!@#$%^&*()"}).Insert()
tx.Commit()
fmt.Println(r, err)
}
fmt.Println()
}
// 主从io复用测试在mysql中使用 show full processlist 查看链接信息
func keepPing() {
fmt.Println("keepPing:")
for i := 0; i < 30; i++ {
fmt.Println("ping...", i)
err := db.PingMaster()
if err != nil {
fmt.Println(err)
return
}
err = db.PingSlave()
if err != nil {
fmt.Println(err)
return
}
time.Sleep(1 * time.Second)
}
}
// like语句查询
func likeQuery() {
fmt.Println("likeQuery:")
if r, err := db.Table("aa_user").Where("name like ?", "%john%").Select(); err == nil {
fmt.Println(r)
} else {
fmt.Println(err)
}
}
// mapToStruct
func mapToStruct() {
type User struct {
Id int
Name string
Age int
Addr string
}
fmt.Println("mapToStruct:")
if r, err := db.Table("aa_user").Where("id=?", 1).One(); err == nil {
u := User{}
if err := r.ToStruct(&u); err == nil {
fmt.Println(r)
fmt.Println(u)
} else {
fmt.Println(err)
}
} else {
fmt.Println(err)
}
}
func main() {
db.PingMaster()
db.SetDebug(true)
/*err := create()
if err != nil {
return
}*/
//test1
/*for i := 1; i < 5; i++ {
insert(i)
}*/
//insert(2)
//query()
//batchInsert()
//query()
//replace()
//save()
/*update1()
update2()
update3()
*/
/*linkopSelect1()
linkopSelect2()
linkopSelect3()
linkopCount1()
*/
/*linkopUpdate1()
linkopUpdate2()
linkopUpdate3()
linkopUpdate4()
*/
linkopBatchInsert1()
query()
//linkopBatchInsert2()
//transaction1()
//transaction2()
//
//keepPing()
//likeQuery()
//mapToStruct()
//getQueriedSqls()
}

View File

@ -1,26 +0,0 @@
# MySQL.
[database]
[database.logger]
Level = "all"
Stdout = true
CtxKeys = ["RequestId"]
[database.default]
link = "mysql:root:12345678@tcp(127.0.0.1:3306)/test"
debug = true
# Redis.
[redis]
default = "127.0.0.1:6379,0"
cache = "127.0.0.1:6379,1"
#[database]
# [[database.default]]
# type = "mysql"
# link = "root:12345678@tcp(127.0.0.1:3306)/test?parseTime=true&loc=Local"
#

View File

@ -1,41 +0,0 @@
package main
import (
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/os/gctx"
"sync"
"time"
)
var db gdb.DB
func init() {
gdb.AddDefaultConfigNode(gdb.ConfigNode{
Host: "127.0.0.1",
Port: "3306",
User: "root",
Pass: "12345678",
Name: "test",
Type: "mysql",
Role: "master",
Charset: "utf8",
MaxOpenConnCount: 100,
})
db, _ = gdb.New()
}
func main() {
var (
wg = sync.WaitGroup{}
ctx = gctx.New()
)
for i := 0; i < 100000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(10 * time.Second)
db.Ctx(ctx).Model("user").Where("id=1").All()
}()
}
wg.Wait()
}

View File

@ -1,4 +0,0 @@
# MySQL数据库配置
[database]
link = "mysql:root:8692651@tcp(192.168.1.11:3306)/test"

View File

@ -1,7 +0,0 @@
# MySQL数据库配置
[database]
[database.default]
link = "mysql:root:8692651@tcp(192.168.1.11:3306)/test"
[database.user]
link = "mysql:root:8692651@tcp(192.168.1.11:3306)/test"

View File

@ -1,24 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
func main() {
var (
db = g.DB()
ctx = gctx.New()
)
// 开启调试模式以便于记录所有执行的SQL
db.SetDebug(true)
r, e := db.Ctx(ctx).GetAll("SELECT * from `user` where id in(?)", g.Slice{})
if e != nil {
fmt.Println(e)
}
if r != nil {
fmt.Println(r)
}
}

View File

@ -1,29 +0,0 @@
package main
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
func main() {
var (
db = g.DB()
ctx = gctx.New()
)
db.Ctx(ctx).Model("user").
Where("nickname like ? and passport like ?", g.Slice{"T3", "t3"}).
OrderAsc("id").All()
conditions := g.Map{
"nickname like ?": "%T%",
"id between ? and ?": g.Slice{1, 3},
"id >= ?": 1,
"create_time > ?": 0,
"id in(?)": g.Slice{1, 2, 3},
}
db.Ctx(ctx).Model("user").Where(conditions).OrderAsc("id").All()
var params []interface{}
db.Ctx(ctx).Model("user").Where("1=1", params).OrderAsc("id").All()
}

View File

@ -1,28 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
func main() {
var (
db = g.DB()
ctx = gctx.New()
)
db.SetDebug(true)
list := make(g.List, 0)
for i := 0; i < 100; i++ {
list = append(list, g.Map{
"name": fmt.Sprintf(`name_%d`, i),
})
}
r, e := db.Ctx(ctx).Model("user").Data(list).Batch(2).Insert()
if e != nil {
panic(e)
}
if r != nil {
fmt.Println(r.LastInsertId())
}
}

View File

@ -1,55 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/crypto/gaes"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
gdb.AddDefaultConfigNode(gdb.ConfigNode{
Host: "127.0.0.1",
Port: "3306",
User: "root",
Pass: "123456",
Name: "test",
Type: "mysql",
Role: "master",
Charset: "utf8",
})
var (
ctx = gctx.New()
)
db, err := gdb.New()
if err != nil {
panic(err)
}
key := "0123456789123456"
name := "john"
encryptedName, err := gaes.Encrypt([]byte(name), []byte(key))
if err != nil {
fmt.Println(err)
}
// 写入
r, err := db.Ctx(ctx).Model("user").Data(g.Map{
"uid": 1,
"name": encryptedName,
}).Save()
if err != nil {
fmt.Println(err)
}
fmt.Println(r.RowsAffected())
// 查询
one, err := db.Ctx(ctx).Model("user").Where("name=?", encryptedName).One()
if err != nil {
fmt.Println(err)
}
fmt.Println(one.Map())
}

View File

@ -1,24 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
var (
db = g.DB()
ctx = gctx.New()
)
db.SetDebug(true)
r, e := db.Ctx(ctx).Model("test").All()
if e != nil {
panic(e)
}
if r != nil {
fmt.Println(r.List())
}
}

View File

@ -1,44 +0,0 @@
package main
import (
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/util/gutil"
"time"
)
func main() {
gdb.AddDefaultConfigNode(gdb.ConfigNode{
Host: "127.0.0.1",
Port: "3306",
User: "root",
Pass: "12345678",
Name: "test",
Type: "mysql",
Role: "master",
Charset: "utf8",
})
var (
ctx = gctx.New()
)
db, err := gdb.New()
if err != nil {
panic(err)
}
//db.GetCache().SetAdapter(adapter.NewRedis(g.Redis()))
// 开启调试模式以便于记录所有执行的SQL
db.SetDebug(true)
// 执行2次查询并将查询结果缓存3秒并可执行缓存名称(可选)
for i := 0; i < 3; i++ {
r, _ := db.Ctx(ctx).Model("user").Cache(3000*time.Second).Where("id=?", 1).One()
gutil.Dump(r.Map())
}
// 执行更新操作,并清理指定名称的查询缓存
//db.Table("user").Cache(-1, "vip-user").Data(gdb.Map{"name": "smith"}).Where("id=?", 1).Update()
// 再次执行查询,启用查询缓存特性
//r, _ := db.Table("user").Cache(300000*time.Second, "vip-user").Where("id=?", 1).One()
//gutil.Dump(r.Map())
}

View File

@ -1,24 +0,0 @@
package main
import (
"github.com/gogf/gf/v2/frame/g"
)
func main() {
// error!
r, err := g.DB().Model("user").Where(g.Map{
"or": g.Map{
"nickname": "jim",
"create_time > ": "2019-10-01",
},
"and": g.Map{
"nickname": "tom",
"create_time > ": "2019-10-01",
},
}).All()
if err != nil {
panic(err)
}
g.Dump(r)
}

View File

@ -1,16 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
if r, err := g.DB().Model("user").Where("uid=?", 1).One(); err == nil {
fmt.Println(r["uid"].Int())
fmt.Println(r["name"].String())
} else {
fmt.Println(err)
}
}

View File

@ -1,17 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
g.Config().SetFileName("config2.toml")
if r, err := g.DB().Model("user").Where("uid=?", 1).One(); err == nil {
fmt.Println(r["uid"].Int())
fmt.Println(r["name"].String())
} else {
fmt.Println(err)
}
}

View File

@ -1,24 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
g.Config().SetFileName("config3.toml")
if r, err := g.DB().Model("user").Where("uid=?", 1).One(); err == nil {
fmt.Println(r["uid"].Int())
fmt.Println(r["name"].String())
} else {
fmt.Println(err)
}
if r, err := g.DB("user").Model("user").Where("uid=?", 1).One(); err == nil {
fmt.Println(r["uid"].Int())
fmt.Println(r["name"].String())
} else {
fmt.Println(err)
}
}

View File

@ -1,14 +0,0 @@
package main
import (
"context"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
ctx := context.WithValue(context.Background(), "RequestId", "123456789")
_, err := g.DB().Ctx(ctx).Query("SELECT 1")
if err != nil {
panic(err)
}
}

View File

@ -1,14 +0,0 @@
package main
import (
"context"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
ctx := context.WithValue(context.Background(), "RequestId", "123456789")
_, err := g.DB().Model("user").Ctx(ctx).All()
if err != nil {
panic(err)
}
}

View File

@ -1,27 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gtime"
)
func main() {
var (
db = g.DB()
ctx = gctx.New()
)
db.SetDebug(true)
r, err := db.Ctx(ctx).Model("user").Data(g.Map{
"name": "john",
"create_time": gtime.Now().String(),
}).Insert()
if err == nil {
fmt.Println(r.LastInsertId())
} else {
panic(err)
}
}

View File

@ -1,41 +0,0 @@
package main
import (
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/os/glog"
)
func main() {
gdb.AddDefaultConfigNode(gdb.ConfigNode{
Host: "127.0.0.1",
Port: "3306",
User: "root",
Pass: "12345678",
Name: "test",
Type: "mysql",
Role: "master",
Charset: "utf8",
})
var (
ctx = gctx.New()
)
db, err := gdb.New()
if err != nil {
panic(err)
}
//db.SetDebug(false)
glog.SetPath("/tmp")
// 执行3条SQL查询
for i := 1; i <= 3; i++ {
db.Ctx(ctx).Model("user").Where("uid=?", i).One()
}
// 构造一条错误查询
db.Model("user").Where("no_such_field=?", "just_test").One()
db.Ctx(ctx).Model("user").Data(g.Map{"name": "smith"}).Where("uid=?", 1).Save()
}

View File

@ -1,22 +0,0 @@
package main
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
func main() {
var (
db = g.DB()
ctx = gctx.New()
)
// 执行3条SQL查询
for i := 1; i <= 3; i++ {
db.Ctx(ctx).Model("user").Where("id=?", i).One()
}
// 构造一条错误查询
db.Ctx(ctx).Model("user").Where("no_such_field=?", "just_test").One()
db.Ctx(ctx).Model("user").Data(g.Map{"name": "smith"}).Where("uid=?", 1).Save()
}

View File

@ -1,9 +0,0 @@
package main
import (
"github.com/gogf/gf/v2/frame/g"
)
func main() {
g.DB().Model("user").Distinct().CountColumn("uid,name")
}

View File

@ -1,30 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
//db := g.DB()
gdb.AddDefaultConfigNode(gdb.ConfigNode{
Link: "root:12345678@tcp(127.0.0.1:3306)/test?parseTime=true&loc=Local",
Type: "mysql",
Charset: "utf8",
})
db, _ := gdb.New()
db.SetDebug(true)
r, e := db.Model("user").Data(g.Map{
"create_at": "now()",
}).Unscoped().Insert()
if e != nil {
panic(e)
}
if r != nil {
fmt.Println(r.LastInsertId())
}
}

View File

@ -1,50 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
)
var (
tableName = "orders"
dao = g.DB().Model(tableName).Safe()
)
type OrderServiceEntity struct {
GoodsPrice float64 `json:"goods_price" gvalid:"required"`
PayTo int8 `json:"payTo" gvalid:"required"`
PayStatus int8 `json:"payStatus" `
CreateTime string `json:"createTime" `
AppId string `json:"appId" gvalid:"required"`
PayUser string `json:"pay_user" gvalid:"required"`
QrUrl string `json:"qr_url" `
}
type Create struct {
Id int64 `json:"id" gconv:"id"`
GoodsPrice float64 `json:"goodsPrice" gconv:"goods_price"`
PayTo int8 `json:"payTo" gconv:"pay_to"`
PayStatus int8 `json:"payStatus" gconv:"pay_status"`
CreateTime string `json:"createTime" gconv:"create_time"`
UserId int `json:"user_id" `
PayUser string `json:"pay_user" `
QrUrl string `json:"qr_url" `
}
func main() {
g.DB().SetDebug(true)
userInfo := Create{
Id: 3,
}
orderService := OrderServiceEntity{
GoodsPrice: 0.1,
PayTo: 1,
}
size, err := dao.Where("user_id", userInfo.Id).
And("goods_price", float64(100.10)).
And("pay_status", 0).
And("pay_to", orderService.PayTo).Count()
fmt.Println(err)
fmt.Println(size)
}

View File

@ -1,41 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/encoding/gjson"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
gdb.AddDefaultConfigNode(gdb.ConfigNode{
Host: "127.0.0.1",
Port: "3306",
User: "root",
Pass: "12345678",
Name: "test",
Type: "mysql",
Role: "master",
Charset: "utf8",
})
var (
db = g.DB()
ctx = gctx.New()
)
one, err := db.Ctx(ctx).Model("user").Where("id=?", 1).One()
if err != nil {
panic(err)
}
// 使用内置方法转换为json/xml
fmt.Println(one.Json())
fmt.Println(one.Xml())
// 自定义方法方法转换为json/xml
jsonContent, _ := gjson.New(one.Map()).ToJson()
fmt.Println(string(jsonContent))
xmlContent, _ := gjson.New(one.Map()).ToJson()
fmt.Println(string(xmlContent))
}

View File

@ -1,26 +0,0 @@
package main
import (
"github.com/gogf/gf/v2/os/gctx"
"time"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
var (
db = g.DB()
ctx = gctx.New()
)
// 开启调试模式以便于记录所有执行的SQL
db.SetDebug(true)
for {
for i := 0; i < 10; i++ {
go db.Ctx(ctx).Model("user").All()
}
time.Sleep(time.Millisecond * 100)
}
}

View File

@ -1,22 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
"time"
)
func main() {
var (
db = g.DB()
ctx = gctx.New()
)
db.SetDebug(true)
for {
r, err := db.Ctx(ctx).Model("user").All()
fmt.Println(err)
fmt.Println(r)
time.Sleep(time.Second * 10)
}
}

View File

@ -1,23 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
db := g.DB()
// 开启调试模式以便于记录所有执行的SQL
db.SetDebug(true)
type User struct {
Uid int
Name string
}
user := (*User)(nil)
fmt.Println(user)
err := db.Model("test").Where("id=1").Scan(&user)
fmt.Println(err)
fmt.Println(user)
}

View File

@ -1,22 +0,0 @@
package main
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
func main() {
var (
db = g.DB()
ctx = gctx.New()
)
db.SetDebug(true)
tables, err := db.Tables(ctx)
if err != nil {
panic(err)
}
if tables != nil {
g.Dump(tables)
}
}

View File

@ -1,29 +0,0 @@
package main
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
func main() {
var (
db = g.DB()
ctx = gctx.New()
)
db.SetDebug(true)
tables, e := db.Tables(ctx)
if e != nil {
panic(e)
}
if tables != nil {
g.Dump(tables)
for _, table := range tables {
fields, err := db.TableFields(ctx, table)
if err != nil {
panic(err)
}
g.Dump(fields)
}
}
}

View File

@ -1,27 +0,0 @@
package main
import (
"github.com/gogf/gf/v2/frame/g"
)
func main() {
var (
db = g.DB()
table = "user"
)
tx, err := db.Begin()
if err != nil {
panic(err)
}
if err = tx.Begin(); err != nil {
panic(err)
}
_, err = tx.Model(table).Data(g.Map{"id": 1, "name": "john"}).Insert()
if err = tx.Rollback(); err != nil {
panic(err)
}
_, err = tx.Model(table).Data(g.Map{"id": 2, "name": "smith"}).Insert()
if err = tx.Commit(); err != nil {
panic(err)
}
}

View File

@ -1,37 +0,0 @@
package main
import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
func main() {
var (
err error
db = g.DB()
ctx = gctx.New()
table = "user"
)
if err = db.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
// Nested transaction 1.
if err = tx.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
_, err = tx.Model(table).Data(g.Map{"id": 1, "name": "john"}).Insert()
return err
}); err != nil {
return err
}
// Nested transaction 2, panic.
if err = tx.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
_, err = tx.Model(table).Data(g.Map{"id": 2, "name": "smith"}).Insert()
// Create a panic that can make this transaction rollback automatically.
panic("error")
}); err != nil {
return err
}
return nil
}); err != nil {
panic(err)
}
}

View File

@ -1,40 +0,0 @@
package main
import (
"github.com/gogf/gf/v2/frame/g"
)
func main() {
var (
err error
db = g.DB()
table = "user"
)
tx, err := db.Begin()
if err != nil {
panic(err)
}
defer func() {
if err := recover(); err != nil {
_ = tx.Rollback()
}
}()
if _, err = tx.Model(table).Data(g.Map{"id": 1, "name": "john"}).Insert(); err != nil {
panic(err)
}
if err = tx.SavePoint("MyPoint"); err != nil {
panic(err)
}
if _, err = tx.Model(table).Data(g.Map{"id": 2, "name": "smith"}).Insert(); err != nil {
panic(err)
}
if _, err = tx.Model(table).Data(g.Map{"id": 3, "name": "green"}).Insert(); err != nil {
panic(err)
}
if err = tx.RollbackTo("MyPoint"); err != nil {
panic(err)
}
if err = tx.Commit(); err != nil {
panic(err)
}
}

View File

@ -1,34 +0,0 @@
package main
import (
"database/sql"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/encoding/gjson"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
db := g.DB()
table := "medicine_clinics_upload_yinchuan"
list, err := db.Model(table).All()
if err != nil && err != sql.ErrNoRows {
panic(err)
}
content := ""
for _, item := range list {
if j, err := gjson.DecodeToJson(item["upload_data"].String()); err != nil {
panic(err)
} else {
s, _ := j.ToJsonIndentString()
content += item["id"].String() + "\t" + item["medicine_clinic_id"].String() + "\t"
content += s
content += "\n\n"
//if _, err := db.Table(table).Data("data_decode", s).Where("id", item["id"].Int()).Update(); err != nil {
// panic(err)
//}
}
}
gfile.PutContents("/Users/john/Temp/medicine_clinics_upload_yinchuan.txt", content)
}

View File

@ -1,17 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
db := g.DB()
db.SetDebug(true)
result, err := db.Model("pw_passageway m,pw_template t").Data("t.status", 99).Where("m.templateId=t.id AND m.status = 0").Update()
if err != nil {
panic(err)
}
fmt.Println(result.RowsAffected())
}

View File

@ -1,15 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
one, err := g.Model("carlist c").
LeftJoin("cardetail d", "c.postid=d.carid").
Where("c.postid", "142039140032006").
Fields("c.*,d.*").One()
fmt.Println(err)
g.Dump(one)
}

View File

@ -1,69 +0,0 @@
package main
import (
"context"
"fmt"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/util/gmeta"
)
func main() {
type UserDetail struct {
gmeta.Meta `orm:"table:user_detail"`
Uid int `json:"uid"`
Address string `json:"address"`
}
type UserScore struct {
gmeta.Meta `orm:"table:user_score"`
Id int `json:"id"`
Uid int `json:"uid"`
Score int `json:"score"`
}
type User struct {
gmeta.Meta `orm:"table:user"`
Id int `json:"id"`
Name string `json:"name"`
UserDetail *UserDetail `orm:"with:uid=id"`
UserScores []*UserScore `orm:"with:uid=id"`
}
db := g.DB()
err := db.Transaction(gctx.New(), func(ctx context.Context, tx *gdb.TX) error {
for i := 1; i <= 5; i++ {
// User.
user := User{
Name: fmt.Sprintf(`name_%d`, i),
}
lastInsertId, err := db.Ctx(ctx).Model(user).Data(user).OmitEmpty().InsertAndGetId()
if err != nil {
return err
}
// Detail.
userDetail := UserDetail{
Uid: int(lastInsertId),
Address: fmt.Sprintf(`address_%d`, lastInsertId),
}
_, err = db.Ctx(ctx).Model(userDetail).Data(userDetail).OmitEmpty().Insert()
if err != nil {
return err
}
// Scores.
for j := 1; j <= 5; j++ {
userScore := UserScore{
Uid: int(lastInsertId),
Score: j,
}
_, err = db.Ctx(ctx).Model(userScore).Data(userScore).OmitEmpty().Insert()
if err != nil {
return err
}
}
}
return nil
})
fmt.Println(err)
}

View File

@ -1,37 +0,0 @@
package main
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gmeta"
)
func main() {
type UserDetail struct {
gmeta.Meta `orm:"table:user_detail"`
Uid int `json:"uid"`
Address string `json:"address"`
}
type UserScore struct {
gmeta.Meta `orm:"table:user_score"`
Id int `json:"id"`
Uid int `json:"uid"`
Score int `json:"score"`
}
type User struct {
gmeta.Meta `orm:"table:user"`
Id int `json:"id"`
Name string `json:"name"`
UserDetail *UserDetail `orm:"with:uid=id"`
UserScores []*UserScore `orm:"with:uid=id"`
}
db := g.DB()
var user *User
err := db.Model(user).WithAll().Where("id", 3).Scan(&user)
if err != nil {
panic(err)
}
g.Dump(user)
}

View File

@ -1,34 +0,0 @@
package main
import (
"github.com/gogf/gf/v2/frame/g"
"time"
)
func test1() {
db := g.DB()
db.SetDebug(true)
time.Sleep(1 * time.Minute)
r, e := db.Model("test").Where("id", 10000).Count()
if e != nil {
panic(e)
}
g.Dump(r)
}
func test2() {
db := g.DB()
db.SetDebug(true)
dao := db.Model("test").Safe()
time.Sleep(1 * time.Minute)
r, e := dao.Where("id", 10000).Count()
if e != nil {
panic(e)
}
g.Dump(r)
}
func main() {
test1()
test2()
}

View File

@ -1,565 +0,0 @@
package main
import (
"fmt"
"time"
//_ "github.com/mattn/go-oci8"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
)
// 本文件用于gf框架的mysql数据库操作示例不作为单元测试使用
var db gdb.DB
// 初始化配置及创建数据库
func init() {
gdb.AddDefaultConfigNode(gdb.ConfigNode{
Host: "192.168.146.0",
Port: "1521",
User: "test",
Pass: "test",
Name: "orcl",
Type: "oracle",
Role: "master",
})
db, _ = gdb.New()
//gins.Config().SetPath("/home/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/.example/frame")
//db = g.Database()
//gdb.SetConfig(gdb.ConfigNode {
// Host : "127.0.0.1",
// Port : 3306,
// User : "root",
// Pass : "123456",
// Name : "test",
// Type : "mysql",
//})
//db, _ = gdb.Instance()
//gdb.SetConfig(gdb.Config {
// "default" : gdb.ConfigGroup {
// gdb.ConfigNode {
// Host : "127.0.0.1",
// Port : "3306",
// User : "root",
// Pass : "123456",
// Name : "test",
// Type : "mysql",
// Role : "master",
// Weight : 100,
// },
// gdb.ConfigNode {
// Host : "127.0.0.2",
// Port : "3306",
// User : "root",
// Pass : "123456",
// Name : "test",
// Type : "mysql",
// Role : "master",
// Weight : 100,
// },
// gdb.ConfigNode {
// Host : "127.0.0.3",
// Port : "3306",
// User : "root",
// Pass : "123456",
// Name : "test",
// Type : "mysql",
// Role : "master",
// Weight : 100,
// },
// gdb.ConfigNode {
// Host : "127.0.0.4",
// Port : "3306",
// User : "root",
// Pass : "123456",
// Name : "test",
// Type : "mysql",
// Role : "master",
// Weight : 100,
// },
// },
//})
//db, _ = gdb.Instance()
}
// 创建测试数据库
func create() error {
fmt.Println("drop table aa_user:")
_, err := db.Exec("drop table aa_user")
if err != nil {
fmt.Println("drop table aa_user error.", err)
}
s := `
CREATE TABLE aa_user (
id number(10) not null,
name VARCHAR2(45),
age number(8),
addr varchar2(60),
amt number(12,2),
PRIMARY KEY (id)
)
`
fmt.Println("create table aa_user:")
_, err = db.Exec(s)
if err != nil {
fmt.Println("create table error.", err)
return err
}
_, err = db.Exec("drop sequence id_seq")
if err != nil {
fmt.Println("drop sequence id_seq", err)
}
/*fmt.Println("create sequence id_seq")
_, err = db.Exec("create sequence id_seq increment by 1 start with 1 maxvalue 9999999999 cycle cache 10")
if err != nil {
fmt.Println("create sequence id_seq error.", err)
return err
}
s = `
CREATE TRIGGER id_trigger before insert on aa_user for each row
begin
select id_seq.nextval into :new.id from dual;
end;
`
_, err = db.Exec(s)
if err != nil {
fmt.Println("create trigger error.", err)
return err
}*/
_, err = db.Exec("drop table user_detail")
if err != nil {
fmt.Println("drop table user_detail", err)
}
s = `
CREATE TABLE user_detail (
id number(10) not null,
site VARCHAR2(255),
PRIMARY KEY (id)
)
`
fmt.Println("create table user_detail:")
_, err = db.Exec(s)
if err != nil {
fmt.Println("create table user_detail error.", err)
return err
}
fmt.Println("create table success.")
return nil
}
// 数据写入
func insert(id int) {
fmt.Println("insert:")
r, err := db.Insert("aa_user", gdb.Map{
"id": id,
"name": "john",
"age": id,
})
fmt.Println(r.LastInsertId())
fmt.Println(r.RowsAffected())
if err == nil {
r, err = db.Insert("user_detail", gdb.Map{
"id": id,
"site": "http://johng.cn",
})
if err == nil {
fmt.Printf("id: %d\n", id)
} else {
fmt.Println(err)
}
} else {
fmt.Println(err)
}
fmt.Println()
}
// 基本sql查询
func query() {
fmt.Println("query:")
list, err := db.GetAll("select * from aa_user")
if err == nil {
fmt.Println(list)
} else {
fmt.Println(err)
}
list, err = db.Table("aa_user").OrderBy("id").Limit(0, 2).Select()
if err == nil {
fmt.Println(list)
} else {
fmt.Println(err)
}
fmt.Println()
}
// replace into
func replace() {
fmt.Println("replace:")
r, err := db.Save("aa_user", gdb.Map{
"id": 1,
"name": "john",
})
if err == nil {
fmt.Println(r.LastInsertId())
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 数据保存
func save() {
fmt.Println("save:")
r, err := db.Save("aa_user", gdb.Map{
"id": 1,
"name": "john",
})
if err == nil {
fmt.Println(r.LastInsertId())
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 批量写入
func batchInsert() {
fmt.Println("batchInsert:")
_, err := db.BatchInsert("aa_user", gdb.List{
{"id": 11, "name": "batchInsert_john_1", "age": 11, "amt": 11.11},
{"id": 12, "name": "batchInsert_john_2", "age": 12, "amt": 12.12},
{"id": 13, "name": "batchInsert_john_3", "age": 13, "amt": 13.13},
{"id": 14, "name": "batchInsert_john_4", "age": 14, "amt": 14.14},
}, 10)
if err != nil {
fmt.Println(err)
}
fmt.Println()
}
// 数据更新
func update1() {
fmt.Println("update1:")
r, err := db.Update("aa_user", gdb.Map{"name": "john1", "age": 1}, "id=?", 1)
if err == nil {
fmt.Println(r.LastInsertId())
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 数据更新
func update2() {
fmt.Println("update2:")
r, err := db.Update("aa_user", gdb.Map{"name": "john6", "age": 6}, "id=?", 2)
if err == nil {
fmt.Println(r.LastInsertId())
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 数据更新
func update3() {
fmt.Println("update3:")
r, err := db.Update("aa_user", "name=?", "id=?", "john2", 3)
if err == nil {
fmt.Println(r.LastInsertId())
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 链式查询操作1
func linkopSelect1() {
fmt.Println("linkopSelect1:")
r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("u.*, ud.site").Where("u.id > ?", 1).Limit(0, 2).Select()
if err == nil {
fmt.Println(r)
} else {
fmt.Println(err)
}
fmt.Println()
}
// 链式查询操作2
func linkopSelect2() {
fmt.Println("linkopSelect2:")
r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("u.*,ud.site").Where("u.id=?", 1).One()
if err == nil {
fmt.Println(r)
} else {
fmt.Println(err)
}
fmt.Println()
}
// 链式查询操作3
func linkopSelect3() {
fmt.Println("linkopSelect3:")
r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Fields("ud.site").Where("u.id=?", 1).Value()
if err == nil {
fmt.Println(r.String())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 链式查询数量1
func linkopCount1() {
fmt.Println("linkopCount1:")
r, err := db.Table("aa_user u").LeftJoin("user_detail ud", "u.id=ud.id").Where("name like ?", "john").Count()
if err == nil {
fmt.Println(r)
} else {
fmt.Println(err)
}
fmt.Println()
}
// 错误操作
func linkopUpdate1() {
fmt.Println("linkopUpdate1:")
r, err := db.Table("henghe_setting").Update()
if err == nil {
fmt.Println(r.RowsAffected())
} else {
fmt.Println("error", err)
}
fmt.Println()
}
// 通过Map指针方式传参方式
func linkopUpdate2() {
fmt.Println("linkopUpdate2:")
r, err := db.Table("aa_user").Data(gdb.Map{"name": "john2"}).Where("name=?", "john").Update()
if err == nil {
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 通过字符串方式传参
func linkopUpdate3() {
fmt.Println("linkopUpdate3:")
r, err := db.Table("aa_user").Data("name='john3'").Where("name=?", "john2").Update()
if err == nil {
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// Where条件使用Map
func linkopUpdate4() {
fmt.Println("linkopUpdate4:")
r, err := db.Table("aa_user").Data(gdb.Map{"name": "john11111"}).Where(g.Map{"id": 1}).Update()
if err == nil {
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 链式批量写入
func linkopBatchInsert1() {
fmt.Println("linkopBatchInsert1:")
r, err := db.Table("aa_user").Filter().Data(gdb.List{
{"id": 21, "name": "linkopBatchInsert1_john_1", "amt": 21.21, "tt": "haha"},
{"id": 22, "name": "linkopBatchInsert1_john_2", "amt": 22.22, "cc": "hahacc"},
{"id": 23, "name": "linkopBatchInsert1_john_3", "amt": 23.23, "bb": "hahabb"},
{"id": 24, "name": "linkopBatchInsert1_john_4", "amt": 24.24, "aa": "hahaaa"},
}).Insert()
if err == nil {
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 链式批量写入,指定每批次写入的条数
func linkopBatchInsert2() {
fmt.Println("linkopBatchInsert2:")
r, err := db.Table("aa_user").Data(gdb.List{
{"id": 25, "name": "linkopBatchInsert2john_1"},
{"id": 26, "name": "linkopBatchInsert2john_2"},
{"id": 27, "name": "linkopBatchInsert2john_3"},
{"id": 28, "name": "linkopBatchInsert2john_4"},
}).Batch(2).Insert()
if err == nil {
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 链式批量保存
func linkopBatchSave() {
fmt.Println("linkopBatchSave:")
r, err := db.Table("aa_user").Data(gdb.List{
{"id": 1, "name": "john_1"},
{"id": 2, "name": "john_2"},
{"id": 3, "name": "john_3"},
{"id": 4, "name": "john_4"},
}).Save()
if err == nil {
fmt.Println(r.RowsAffected())
} else {
fmt.Println(err)
}
fmt.Println()
}
// 事务操作示例1
func transaction1() {
fmt.Println("transaction1:")
if tx, err := db.Begin(); err == nil {
r, err := tx.Insert("aa_user", gdb.Map{
"id": 30,
"name": "transaction1",
})
tx.Rollback()
fmt.Println(r, err)
}
fmt.Println()
}
// 事务操作示例2
func transaction2() {
fmt.Println("transaction2:")
if tx, err := db.Begin(); err == nil {
r, err := tx.Table("user_detail").Data(gdb.Map{"id": 5, "site": "www.baidu.com哈哈哈*?~!@#$%^&*()"}).Insert()
tx.Commit()
fmt.Println(r, err)
}
fmt.Println()
}
// 主从io复用测试在mysql中使用 show full processlist 查看链接信息
func keepPing() {
fmt.Println("keepPing:")
for i := 0; i < 30; i++ {
fmt.Println("ping...", i)
err := db.PingMaster()
if err != nil {
fmt.Println(err)
return
}
err = db.PingSlave()
if err != nil {
fmt.Println(err)
return
}
time.Sleep(1 * time.Second)
}
}
// like语句查询
func likeQuery() {
fmt.Println("likeQuery:")
if r, err := db.Table("aa_user").Where("name like ?", "%john%").Select(); err == nil {
fmt.Println(r)
} else {
fmt.Println(err)
}
}
// mapToStruct
func mapToStruct() {
type User struct {
Id int
Name string
Age int
Addr string
}
fmt.Println("mapToStruct:")
if r, err := db.Table("aa_user").Where("id=?", 1).One(); err == nil {
u := User{}
if err := r.ToStruct(&u); err == nil {
fmt.Println(r)
fmt.Println(u)
} else {
fmt.Println(err)
}
} else {
fmt.Println(err)
}
}
func main() {
db.PingMaster()
db.SetDebug(true)
/*err := create()
if err != nil {
return
}*/
//test1
/*for i := 1; i < 5; i++ {
insert(i)
}
query()
*/
//batchInsert()
//query()
//replace()
//save()
//update1()
//update2()
//update3()
/*linkopSelect1()
linkopSelect2()
linkopSelect3()
linkopCount1()
*/
/*linkopUpdate1()
linkopUpdate2()
linkopUpdate3()
linkopUpdate4()
*/
linkopBatchInsert1()
query()
//linkopBatchInsert2()
//transaction1()
//transaction2()
//
//keepPing()
//likeQuery()
//mapToStruct()
//getQueriedSqls()
}

View File

@ -1,47 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
_ "github.com/mattn/go-sqlite3"
)
func main() {
gdb.SetConfig(gdb.Config{
"default": gdb.ConfigGroup{
gdb.ConfigNode{
Name: "/tmp/my.db",
Type: "sqlite",
},
},
})
db := g.DB()
if db == nil {
panic("db create failed")
}
// 创建表
sql := `CREATE TABLE user (
uid INT PRIMARY KEY NOT NULL,
name VARCHAR(30) NOT NULL
);`
if _, err := db.Exec(sql); err != nil {
fmt.Println(err)
}
// 写入数据
result, err := db.Table("user").Data(g.Map{"uid": 1, "name": "john"}).Save()
if err == nil {
fmt.Println(result.RowsAffected())
} else {
fmt.Println(err)
}
// 删除表
sql = `DROP TABLE user;`
if _, err := db.Exec(sql); err != nil {
fmt.Println(err)
}
}

View File

@ -1,4 +0,0 @@
# Redis数据库配置
[redis]
default = "127.0.0.1:6379,0"
cache = "127.0.0.1:6379,1"

View File

@ -1,21 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/database/gredis"
"github.com/gogf/gf/v2/util/gconv"
)
// 使用原生gredis.New操作redis但是注意需要自己调用Close方法关闭redis链接池
func main() {
config := &gredis.Config{
Host: "127.0.0.1",
Port: 6379,
}
redis := gredis.New(config)
defer redis.Close()
redis.Do("SET", "k", "v")
v, _ := redis.Do("GET", "k")
fmt.Println(gconv.String(v))
}

View File

@ -1,15 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gconv"
)
// 使用框架封装的g.Redis()方法获得redis操作对象单例不需要开发者显示调用Close方法
func main() {
g.Redis().Do("SET", "k", "v")
v, _ := g.Redis().Do("GET", "k")
fmt.Println(gconv.String(v))
}

View File

@ -1,16 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gconv"
)
func main() {
conn := g.Redis().Conn()
defer conn.Close()
conn.Do("SET", "k", "v")
v, _ := conn.Do("GET", "k")
fmt.Println(gconv.String(v))
}

View File

@ -1,17 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
conn := g.Redis().Conn()
defer conn.Close()
if _, err := conn.Do("SET", "k", "v"); err != nil {
panic(err)
}
v, _ := conn.DoVar("GET", "k")
fmt.Println(v.String())
}

View File

@ -1,21 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gconv"
)
func main() {
conn := g.Redis().Conn()
defer conn.Close()
conn.Send("SET", "foo", "bar")
conn.Send("GET", "foo")
conn.Flush()
// reply from SET
conn.Receive()
// reply from GET
v, _ := conn.Receive()
fmt.Println(gconv.String(v))
}

View File

@ -1,20 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
conn := g.Redis().Conn()
defer conn.Close()
conn.Send("SET", "foo", "bar")
conn.Send("GET", "foo")
conn.Flush()
// reply from SET
conn.Receive()
// reply from GET
v, _ := conn.ReceiveVar()
fmt.Println(v.String())
}

View File

@ -1,24 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gconv"
)
func main() {
conn := g.Redis().Conn()
defer conn.Close()
_, err := conn.Do("SUBSCRIBE", "channel")
if err != nil {
panic(err)
}
for {
reply, err := conn.Receive()
if err != nil {
panic(err)
}
fmt.Println(gconv.Strings(reply))
}
}

View File

@ -1,23 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
conn := g.Redis().Conn()
defer conn.Close()
_, err := conn.Do("SUBSCRIBE", "channel")
if err != nil {
panic(err)
}
for {
reply, err := conn.ReceiveVar()
if err != nil {
panic(err)
}
fmt.Println(reply.Strings())
}
}

View File

@ -1,12 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/debug/gdebug"
)
func main() {
gdebug.PrintStack()
fmt.Println(gdebug.CallerPackage())
fmt.Println(gdebug.CallerFunction())
}

View File

@ -1,10 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/debug/gdebug"
)
func main() {
fmt.Println(gdebug.BuildInfo())
}

View File

@ -1,16 +0,0 @@
package gbase64
import (
"fmt"
"github.com/gogf/gf/v2/encoding/gbase64"
)
func main() {
s := "john"
b := gbase64.Encode(s)
c, e := gbase64.Decode(b)
fmt.Println(b)
fmt.Println(c)
fmt.Println(e)
}

View File

@ -1,55 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/encoding/gbinary"
"github.com/gogf/gf/v2/os/glog"
)
func main() {
// 使用gbinary.Encoded对基本数据类型进行二进制打包
fmt.Println(gbinary.Encode(18, 300, 1.01))
// 使用gbinary.Decode对整形二进制解包注意第二个及其后参数为字长确定的整形变量的指针地址字长确定的类型
// 例如int8/16/32/64、uint8/16/32/64、float32/64
// 这里的1.01默认为float64类型(64位系统下)
buffer := gbinary.Encode(18, 300, 1.01)
var i1 int8
var i2 int16
var f3 float64
if err := gbinary.Decode(buffer, &i1, &i2, &f3); err != nil {
glog.Error(err)
} else {
fmt.Println(i1, i2, f3)
}
// 编码/解析 int自动识别变量长度
fmt.Println(gbinary.DecodeToInt(gbinary.EncodeInt(1)))
fmt.Println(gbinary.DecodeToInt(gbinary.EncodeInt(300)))
fmt.Println(gbinary.DecodeToInt(gbinary.EncodeInt(70000)))
fmt.Println(gbinary.DecodeToInt(gbinary.EncodeInt(2000000000)))
fmt.Println(gbinary.DecodeToInt(gbinary.EncodeInt(500000000000)))
// 编码/解析 uint自动识别变量长度
fmt.Println(gbinary.DecodeToUint(gbinary.EncodeUint(1)))
fmt.Println(gbinary.DecodeToUint(gbinary.EncodeUint(300)))
fmt.Println(gbinary.DecodeToUint(gbinary.EncodeUint(70000)))
fmt.Println(gbinary.DecodeToUint(gbinary.EncodeUint(2000000000)))
fmt.Println(gbinary.DecodeToUint(gbinary.EncodeUint(500000000000)))
// 编码/解析 int8/16/32/64
fmt.Println(gbinary.DecodeToInt8(gbinary.EncodeInt8(int8(100))))
fmt.Println(gbinary.DecodeToInt16(gbinary.EncodeInt16(int16(100))))
fmt.Println(gbinary.DecodeToInt32(gbinary.EncodeInt32(int32(100))))
fmt.Println(gbinary.DecodeToInt64(gbinary.EncodeInt64(int64(100))))
// 编码/解析 uint8/16/32/64
fmt.Println(gbinary.DecodeToUint8(gbinary.EncodeUint8(uint8(100))))
fmt.Println(gbinary.DecodeToUint16(gbinary.EncodeUint16(uint16(100))))
fmt.Println(gbinary.DecodeToUint32(gbinary.EncodeUint32(uint32(100))))
fmt.Println(gbinary.DecodeToUint64(gbinary.EncodeUint64(uint64(100))))
// 编码/解析 string
fmt.Println(gbinary.DecodeToString(gbinary.EncodeString("I'm string!")))
}

View File

@ -1,33 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/encoding/gbinary"
)
func main() {
// 传感器状态0:已下线, 1:开启, 2:关闭, 3:待机
count := 100
status := 1
// 网关编码
bits := make([]gbinary.Bit, 0)
for i := 0; i < count; i++ {
bits = gbinary.EncodeBits(bits, status, 2)
}
buffer := gbinary.EncodeBitsToBytes(bits)
fmt.Println("buffer length:", len(buffer))
/* 上报过程忽略,这里只展示编码/解码示例 */
// 平台解码
alivecount := 0
sensorbits := gbinary.DecodeBytesToBits(buffer)
for i := 0; i < len(sensorbits); i += 2 {
if gbinary.DecodeBits(sensorbits[i:i+2]) == 1 {
alivecount++
}
}
fmt.Println("alived sensor:", alivecount)
}

View File

@ -1,33 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/encoding/gbinary"
)
func main() {
// Meta元数据文件数据结构[键名哈希64(64bit,8byte) 键名长度(8bit,1byte) 键值长度(24bit,3byte) 数据文件偏移量(40bit,5byte)](变长)
hash := 521369841259754125
klen := 12
vlen := 35535
offset := 80000000
// 编码
bits := make([]gbinary.Bit, 0)
bits = gbinary.EncodeBits(bits, hash, 64)
bits = gbinary.EncodeBits(bits, klen, 8)
bits = gbinary.EncodeBits(bits, vlen, 24)
bits = gbinary.EncodeBits(bits, offset, 40)
buffer := gbinary.EncodeBitsToBytes(bits)
fmt.Println("meta length:", len(buffer))
/* 文件存储及数据查询过程忽略,这里只展示元数据编码/解码示例 */
// 解码
metabits := gbinary.DecodeBytesToBits(buffer)
fmt.Println("hash :", gbinary.DecodeBits(metabits[0:64]))
fmt.Println("klen :", gbinary.DecodeBits(metabits[64:72]))
fmt.Println("vlen :", gbinary.DecodeBits(metabits[72:96]))
fmt.Println("offset:", gbinary.DecodeBits(metabits[96:136]))
}

View File

@ -1,28 +0,0 @@
# 模板引擎目录
viewpath = "/home/www/templates/"
# MySQL数据库配置
[database]
[[database.default]]
host = "127.0.0.1"
port = "3306"
user = "root"
pass = "123456"
name = "test"
type = "mysql"
role = "master"
charset = "utf8"
priority = "1"
[[database.default]]
host = "127.0.0.1"
port = "3306"
user = "root"
pass = "123456"
name = "test"
type = "mysql"
role = "master"
charset = "utf8"
priority = "1"
# Redis数据库配置
[redis]
disk = "127.0.0.1:6379,0"
cache = "127.0.0.1:6379,1"

View File

@ -1,20 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
fmt.Println(g.Config().Get("redis"))
type RedisConfig struct {
Disk string
Cache string
}
redisCfg := new(RedisConfig)
fmt.Println(g.Config().GetStruct("redis", redisCfg))
fmt.Println(redisCfg)
}

View File

@ -1,20 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/encoding/gcharset"
)
func main() {
src := "~{;(<dR;:x>F#,6@WCN^O`GW!#"
srcCharset := "GB2312"
dstCharset := "UTF-8"
str, err := gcharset.Convert(dstCharset, srcCharset, src)
if err != nil {
panic(err)
}
fmt.Println(str)
// output:
// 花间一壶酒,独酌无相亲。
}

View File

@ -1,15 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/encoding/gcompress"
)
func main() {
err := gcompress.UnZipFile(
`D:\Workspace\Go\GOPATH\src\github.com\gogf\gf\geg\encoding\gcompress\data.zip`,
`D:\Workspace\Go\GOPATH\src\github.com\gogf\gf\geg`,
)
fmt.Println(err)
}

View File

@ -1,16 +0,0 @@
package main
import (
"fmt"
"github.com/gogf/gf/v2/encoding/gcompress"
"github.com/gogf/gf/v2/os/gfile"
)
func main() {
err := gcompress.UnZipContent(
gfile.GetBytes(`D:\Workspace\Go\GOPATH\src\github.com\gogf\gf\geg\encoding\gcompress\data.zip`),
`D:\Workspace\Go\GOPATH\src\github.com\gogf\gf\geg`,
)
fmt.Println(err)
}

View File

@ -1,68 +0,0 @@
package main
import (
"archive/zip"
"fmt"
"github.com/gogf/gf/v2/encoding/gcompress"
"io"
"os"
"path/filepath"
"strings"
)
// srcFile could be a single file or a directory
func Zip(srcFile string, destZip string) error {
zipfile, err := os.Create(destZip)
if err != nil {
return err
}
defer zipfile.Close()
archive := zip.NewWriter(zipfile)
defer archive.Close()
filepath.Walk(srcFile, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
header.Name = strings.TrimPrefix(path, filepath.Dir(srcFile)+"/")
// header.Name = path
if info.IsDir() {
header.Name += "/"
} else {
header.Method = zip.Deflate
}
writer, err := archive.CreateHeader(header)
if err != nil {
return err
}
if !info.IsDir() {
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(writer, file)
}
return err
})
return err
}
func main() {
src := `/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/test`
dst := `/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/test.zip`
//src := `/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/README.MD`
//dst := `/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/README.MD.zip`
fmt.Println(gcompress.ZipPath(src, dst))
//fmt.Println(Zip(src, dst))
}

Some files were not shown because too many files have changed in this diff Show More