接续上篇文章《ShardingSphere-Proxy分表场景测试案例》
go测试用例:
package main
import (
"fmt"
"math/rand"
"time"
"github.com/bwmarrin/snowflake"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
var globalDB *gorm.DB
type Order struct {
ID int64 `gorm:"primaryKey"`
OrderId string `gorm:"sharding:order_id"` // 指明 OrderId 是分片键
UserID int64 `gorm:"sharding:user_id"`
ProductID int64
OrderDate int64
}
type Product struct {
ID int64 `gorm:"primaryKey"`
Name string `gorm:"name"`
}
// 定义结构体,用于接收查询结果
type OrderGroup struct {
ID int64 `gorm:"primaryKey"`
OrderId string `gorm:"sharding:order_id"` // 指明 OrderId 是分片键
UserID int64 `gorm:"sharding:user_id"`
ProductID int64
OrderDate int64
SumProduct int64
MaxProduct int64
}
type OrderProduct struct {
Order
Product
}
type User struct {
ID int64 `gorm:"primaryKey"`
Name string `gorm:"name"`
}
type OrderUser struct {
Order
User
}
func main() {
InitDb()
// 示例:插入订单数据
InsertRandomOrders()
// 示例:插入product数据
InsertRandomProducts()
// 示例:插入user数据
InsertRandomUsers()
// 场景1:全表查询,不含分表键
FindAllOrders()
// 场景2:根据订单号查询订单,不含分表健
FindOrderByOrderId("20240101ORDER9503")
// 场景3:根据用户ID查询订单,含分表健
FindOrderByUserID(8648)
// 场景4:等值查询,根据订单id和product_id查询订单。不包含分表健
FindOrderByOrderIdAndProductID("20240101ORDER6546", 861)
// 场景5:等值查询,根据用户id和product_id查询订单。包含分表健
FindOrderByUserIDAndProductID(4581, 213)
// 场景6:in查询,根据用户id查询订单。包含分表健
FindOrderByUserIDIn([]int64{2608, 4581, 2142, 3519})
// 场景7:in查询,根据order_id查询订单。不包含分表健
FindOrderByOrderIdIn([]string{"20240101ORDER6546", "20250101ORDER2295", "20250101ORDER4465", "20240101ORDER7826"})
// 场景8:between查询,根据order_id查询订单。不包含分表健
FindOrderByOrderIdBetween("20240101ORDER6546", "20240101ORDER6548")
// 场景9:beteeen查询,根据user_id查询订单。包含分表健
FindOrderByUserIDBetween(4581, 4583)
// 场景10:or查询,根据order_id查询订单。不包含分表健
FindOrderByOrderIdOr("20240101ORDER6546", "20250101ORDER2295")
// 场景11:or查询,根据user_id查询订单。包含分表健
FindOrderByUserIDOr(4581, 3519)
// 场景12:>查询,根据order_id查询订单。不包含分表健
FindOrderByOrderIdGt("20240101ORDER6546")
// 场景13:>查询,根据user_id查询订单。包含分表健
FindOrderByUserIDGt(4581)
// 场景14:累加聚合查询,根据order_id查询订单。不包含分表健
FindOrderByOrderIdSum("20240101ORDER6546")
// 场景15:累加聚合查询,根据user_id查询订单。包含分表健
FindOrderByUserIDSum(4581)
// 场景16:count查询,根据order_id查询订单。不包含分表健
FindOrderByOrderIdCount("20240101ORDER6546")
// 场景17:count查询,根据user_id查询订单。包含分表健
FindOrderByUserIDCount(4581)
// 场景18:count查询,全表查询。不包含分表健
FindAllOrdersCount()
// 场景19:sum查询,全表查询。不包含分表健
FindAllOrdersSum()
// 场景20:比较聚合查询,max查询,全表查询。不包含分表健
FindAllOrdersMax()
// 场景21:比较聚合查询,min查询,全表查询。不包含分表健
FindAllOrdersMin()
// 场景22:平均聚合查询,全表查询。不包含分表健
FindAllOrdersAvg()
// 场景23:分组聚合查询,根据order_id分组查询。不包含分表健
FindOrderByOrderIdGroupBy()
// 场景24:分组聚合查询,根据user_id分组查询。包含分表健
FindOrderByUserIDGroupBy()
// 场景25:排序、分页查询,根据order_id排序,查询第2页数据。不包含分表健
FindOrderByOrderIdOrderPage(1, 5)
// 场景26:排序、分页查询,根据user_id排序,查询第2页数据。包含分表健
FindOrderByUserIDOrderPage(1, 5)
// 场景27:去重查询,根据order_id去重,查询订单。不包含分表健
FindOrderByOrderIdDistinct()
// 场景28:去重查询,根据user_id去重,查询订单。包含分表健
FindOrderByUserIDDistinct()
// 场景29:join查询,order表和product表关联查询。join条件不包含分表健
FindOrderJoinProduct()
// 场景30:join查询,order表和user表关联查询。join条件包含分表健
FindOrderJoinUser()
// 场景31:子查询,order表和product表关联查询作为子查询,查询订单。join条件不包含分表健
FindOrderSubQueryProduct()
// 场景32:子查询,order表和user表关联查询作为子查询,查询订单。join条件包含分表健
FindOrderSubQueryUser()
// 场景33:where in 子查询表
FindOrderInSubQuery()
// 场景34:union查询。包含分表健
FindOrderUnion()
// 场景35:union all查询。包含分表健
FindOrderUnionAll()
// 场景36:union 查询。不包含分表健
FindOrderUnionByOrderId()
// 场景37:union all查询。不包含分表健
FindOrderUnionAllByOrderId()
// 场景38:根据主键更新
UpdateOrderByID(1866023311733952512, 1)
// 场景39:场景39:根据分表键更新
UpdateOrderByUserID(9148, 1)
// 场景40:根据主键删除
DeleteOrderByID(1866023311071252480)
// 场景41:根据分表键删除
DeleteOrderByUserID(4389)
}
// 生成product数据插入
func InsertRandomProducts() {
// 查询所有订单
var orders []Order
err := globalDB.Table("orders").Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return
}
// 生成product数据
for _, order := range orders {
product := Product{
ID: order.ProductID,
Name: fmt.Sprintf("product_%04d", order.ProductID),
}
InsertProduct(product)
}
}
// 插入product数据
func InsertProduct(product Product) error {
err := globalDB.Table("product").Create(&product).Error
if err != nil {
fmt.Println("Error creating product:", err)
}
return nil
}
// 生成user数据插入
func InsertRandomUsers() {
// 查询所有订单
var orders []Order
err := globalDB.Table("orders").Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return
}
// 生成user数据
for _, order := range orders {
user := User{
ID: order.UserID,
Name: fmt.Sprintf("user_%04d", order.UserID),
}
InsertUser(user)
}
}
// 插入user数据
func InsertUser(user User) error {
err := globalDB.Table("user").Create(&user).Error
if err != nil {
fmt.Println("Error creating user:", err)
}
return nil
}
// 随机生成一些订单数据插入
func InsertRandomOrders() {
node, err := snowflake.NewNode(1)
if err != nil {
fmt.Println("Error creating snowflake node:", err)
return
}
now := time.Now()
for i := 0; i < 10; i++ {
// 雪花id生成
// 生成一个ID
id := node.Generate()
order := Order{
ID: id.Int64(),
OrderId: fmt.Sprintf("20240101ORDER%04d", rand.Int31n(10000)),
UserID: int64(rand.Int31n(10000)),
ProductID: int64(rand.Int31n(1000)),
OrderDate: now.Unix(),
}
InsertOrder(order)
}
// orderDate 用2025年,拼接当前月,日,时,分秒
orderDate := time.Date(2025, now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second(), 0, time.UTC)
for i := 0; i < 10; i++ {
id := node.Generate()
order := Order{
ID: id.Int64(),
OrderId: fmt.Sprintf("20250101ORDER%04d", rand.Int31n(10000)),
UserID: int64(rand.Int31n(10000)),
ProductID: int64(rand.Int31n(1000)),
OrderDate: orderDate.Unix(),
}
InsertOrder(order)
}
}
// 插入订单数据
func InsertOrder(order Order) error {
err := globalDB.Create(&order).Error
if err != nil {
fmt.Println("Error creating order:", err)
}
return nil
}
// 场景1:全表查询,不含分表键
func FindAllOrders() ([]Order, error) {
var orders []Order
err := globalDB.Table("orders").Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景1:全表查询,不含分表键 orders:", orders)
return orders, err
}
// 场景2:根据订单号查询订单,不含分表健
func FindOrderByOrderId(orderId string) ([]Order, error) {
var orders []Order
err := globalDB.Table("orders").Where("order_id=?", orderId).Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景2:根据订单号查询订单,不含分表健 orders:", orders)
return orders, err
}
// 场景3:根据用户ID查询订单,含分表健
func FindOrderByUserID(userID int64) ([]Order, error) {
var orders []Order
err := globalDB.Table("orders").Where("user_id=?", userID).Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景3:根据用户ID查询订单,含分表健 orders:", orders)
return orders, err
}
// 场景4:等值查询,根据订单id和product_id查询订单。不包含分表健
func FindOrderByOrderIdAndProductID(orderId string, productID int64) ([]Order, error) {
var orders []Order
err := globalDB.Table("orders").Where("order_id=? AND product_id=?", orderId, productID).Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景4:等值查询,根据订单id和product_id查询订单 orders:", orders)
return orders, err
}
// 场景5:等值查询,根据用户id和product_id查询订单。包含分表健
func FindOrderByUserIDAndProductID(userID int64, productID int64) ([]Order, error) {
var orders []Order
err := globalDB.Table("orders").Where("user_id=? AND product_id=?", userID, productID).Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景5:等值查询,根据用户id和product_id查询订单 orders:", orders)
return orders, err
}
// 场景6:in查询,根据用户id查询订单。包含分表健
func FindOrderByUserIDIn(userIDs []int64) ([]Order, error) {
var orders []Order
err := globalDB.Table("orders").Where("user_id IN ?", userIDs).Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景6:in查询,根据用户id查询订单 orders:", orders)
return orders, err
}
// 场景7:in查询,根据order_id查询订单。不包含分表健
func FindOrderByOrderIdIn(orderIDs []string) ([]Order, error) {
var orders []Order
err := globalDB.Table("orders").Where("order_id IN ?", orderIDs).Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景7:in查询,根据order_id查询订单 orders:", orders)
return orders, err
}
// 场景8:between查询,根据order_id查询订单。不包含分表健
func FindOrderByOrderIdBetween(orderID1, orderID2 string) ([]Order, error) {
var orders []Order
err := globalDB.Table("orders").Where("order_id BETWEEN ? AND ?", orderID1, orderID2).Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景8:between查询,根据order_id查询订单 orders:", orders)
return orders, err
}
// 场景9:beteeen查询,根据user_id查询订单。包含分表健
// 包含分表健的between查询,似乎不支持。allow-range-query-with-inline-sharding设置为true,可以支持,这个场景待重新测试。
func FindOrderByUserIDBetween(userID1, userID2 int64) ([]Order, error) {
var orders []Order
err := globalDB.Table("orders").Where("user_id BETWEEN ? AND ?", userID1, userID2).Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景9:beteeen查询,根据user_id查询订单 orders:", orders)
return orders, err
}
// 场景10:or查询,根据order_id查询订单。不包含分表健
func FindOrderByOrderIdOr(orderID1, orderID2 string) ([]Order, error) {
var orders []Order
err := globalDB.Table("orders").Where("order_id = ? OR order_id = ?", orderID1, orderID2).Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景10:or查询,根据order_id查询订单 orders:", orders)
return orders, err
}
// 场景11:or查询,根据user_id查询订单。包含分表健
func FindOrderByUserIDOr(userID1, userID2 int64) ([]Order, error) {
var orders []Order
err := globalDB.Table("orders").Where("user_id = ? OR user_id = ?", userID1, userID2).Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景11:or查询,根据user_id查询订单 orders:", orders)
return orders, err
}
// 场景12:>查询,根据order_id查询订单。不包含分表健
func FindOrderByOrderIdGt(orderID string) ([]Order, error) {
var orders []Order
err := globalDB.Table("orders").Where("order_id > ?", orderID).Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景12:>查询,根据order_id查询订单 orders:", orders)
return orders, err
}
// 场景13:>查询,根据user_id查询订单。包含分表健
// 包含分表键的>查询,似乎不支持。allow-range-query-with-inline-sharding设置为true,可以支持,这个场景待重新测试。
func FindOrderByUserIDGt(userID int64) ([]Order, error) {
var orders []Order
err := globalDB.Table("orders").Where("user_id > ?", userID).Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景13:>查询,根据user_id查询订单 orders:", orders)
return orders, err
}
// 场景14:累加聚合查询,根据order_id查询订单。不包含分表健
func FindOrderByOrderIdSum(orderID string) (int64, error) {
var sum int64
err := globalDB.Table("orders").Where("order_id=?", orderID).Select("SUM(product_id)").Scan(&sum).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return 0, err
}
fmt.Println("场景14:累加聚合查询,根据order_id查询订单 orders:", sum)
return sum, err
}
// 场景15:累加聚合查询,根据user_id查询订单。包含分表健
func FindOrderByUserIDSum(userID int64) (int64, error) {
var sum int64
err := globalDB.Table("orders").Where("user_id=?", userID).Select("SUM(product_id)").Scan(&sum).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return 0, err
}
fmt.Println("场景15:累加聚合查询,根据user_id查询订单 orders:", sum)
return sum, err
}
// 场景16:count查询,根据order_id查询订单。不包含分表健
func FindOrderByOrderIdCount(orderID string) (int64, error) {
var count int64
err := globalDB.Table("orders").Where("order_id=?", orderID).Count(&count).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return 0, err
}
fmt.Println("场景16:count查询,根据order_id查询订单 orders:", count)
return count, err
}
// 场景17:count查询,根据user_id查询订单。包含分表健
func FindOrderByUserIDCount(userID int64) (int64, error) {
var count int64
err := globalDB.Table("orders").Where("user_id=?", userID).Count(&count).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return 0, err
}
fmt.Println("场景17:count查询,根据user_id查询订单 orders:", count)
return count, err
}
// 场景18:count查询,全表查询。不包含分表健
func FindAllOrdersCount() (int64, error) {
var count int64
err := globalDB.Table("orders").Count(&count).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return 0, err
}
fmt.Println("场景18:count查询,全表查询 orders:", count)
return count, err
}
// 场景19:sum查询,全表查询。不包含分表健
func FindAllOrdersSum() (int64, error) {
var sum int64
err := globalDB.Table("orders").Select("SUM(product_id)").Scan(&sum).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return 0, err
}
fmt.Println("场景19:sum查询,全表查询 orders:", sum)
return sum, err
}
// 场景20:比较聚合查询,max查询,全表查询。不包含分表健
func FindAllOrdersMax() (int64, error) {
var max int64
err := globalDB.Table("orders").Select("MAX(user_id)").Scan(&max).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return 0, err
}
fmt.Println("场景20:max查询,全表查询 orders:", max)
return max, err
}
// 场景21:比较聚合查询,min查询,全表查询。不包含分表健
func FindAllOrdersMin() (int64, error) {
var min int64
err := globalDB.Table("orders").Select("MIN(user_id)").Scan(&min).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return 0, err
}
fmt.Println("场景21:min查询,全表查询 orders:", min)
return min, err
}
// 场景22:平均聚合查询,全表查询。不包含分表健
func FindAllOrdersAvg() (float64, error) {
var avg float64
err := globalDB.Table("orders").Select("AVG(user_id)").Scan(&avg).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return 0, err
}
fmt.Println("场景22:avg查询,全表查询 orders:", avg)
return avg, err
}
// 场景23:分组聚合查询,根据order_id分组查询。不包含分表健
func FindOrderByOrderIdGroupBy() error {
var orders []OrderGroup
err := globalDB.Table("orders").Group("order_id").Select("*,SUM(product_id) AS sum_product,MAX(product_id) as max_product").Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return err
}
fmt.Printf("场景23:分组聚合查询,根据order_id分组查询 orders:%+v\n", orders)
return err
}
// 场景24:分组聚合查询,根据user_id分组查询。包含分表健
func FindOrderByUserIDGroupBy() error {
var orders []OrderGroup
err := globalDB.Table("orders").Group("user_id").Select("*,SUM(product_id) AS sum_product,MAX(product_id) as max_product").Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return err
}
fmt.Printf("场景24:分组聚合查询,根据user_id分组查询 orders:%+v\n", orders)
return err
}
// 场景25:排序、分页查询,根据order_id排序,查询第2页数据。不包含分表健
func FindOrderByOrderIdOrderPage(page, pageSize int) ([]Order, error) {
var orders []Order
err := globalDB.Table("orders").Order("order_id desc").Offset((page - 1) * pageSize).Limit(pageSize).Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景25:排序、分页查询,根据order_id排序,查询第2页数据 orders:", orders)
return orders, err
}
// 场景26:排序、分页查询,根据user_id排序,查询第2页数据。包含分表健
func FindOrderByUserIDOrderPage(page, pageSize int) ([]Order, error) {
var orders []Order
err := globalDB.Table("orders").Order("user_id desc").Offset((page - 1) * pageSize).Limit(pageSize).Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景26:排序、分页查询,根据user_id排序,查询第2页数据 orders:", orders)
return orders, err
}
// 场景27:去重查询,根据order_id去重,查询订单。不包含分表健
func FindOrderByOrderIdDistinct() ([]Order, error) {
var orders []Order
err := globalDB.Table("orders").Distinct("order_id").Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景27:去重查询,根据order_id去重,查询订单 orders:", orders)
return orders, err
}
// 场景28:去重查询,根据user_id去重,查询订单。包含分表健
func FindOrderByUserIDDistinct() ([]Order, error) {
var orders []Order
err := globalDB.Table("orders").Distinct("user_id").Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景28:去重查询,根据user_id去重,查询订单 orders:", orders)
return orders, err
}
// 场景29:join查询,order表和product表关联查询。join条件不包含分表健
func FindOrderJoinProduct() ([]OrderProduct, error) {
var orders []OrderProduct
err := globalDB.Table("orders").Joins("JOIN product ON orders.product_id = product.id").Select("orders.*,product.*").Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景29:join查询,order表和product表关联查询 orders:", orders)
return orders, err
}
// 场景30:join查询,order表和user表关联查询。join条件包含分表健
func FindOrderJoinUser() ([]OrderUser, error) {
var orders []OrderUser
err := globalDB.Table("orders").Joins("JOIN user ON orders.user_id = user.id").Select("orders.*,user.*").Find(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景30:join查询,order表和user表关联查询 orders:", orders)
return orders, err
}
// 场景31:子查询,order表和product表关联查询作为子查询,查询订单。join条件不包含分表健
func FindOrderSubQueryProduct() ([]OrderProduct, error) {
var orders []OrderProduct
sql := `SELECT subquery.* FROM (SELECT orders.* FROM orders JOIN product ON orders.product_id = product.id) AS subquery`
err := globalDB.Raw(sql).Scan(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景31:子查询,order表和product表关联查询作为子查询,查询订单 orders:", orders)
return orders, err
}
// 场景32:子查询,order表和user表关联查询作为子查询,查询订单。join条件包含分表健
func FindOrderSubQueryUser() ([]OrderUser, error) {
var orders []OrderUser
sql := `SELECT subquery.* FROM (SELECT orders.* FROM orders JOIN user ON orders.user_id = user.id) AS subquery`
err := globalDB.Raw(sql).Scan(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景32:子查询,order表和user表关联查询作为子查询,查询订单 orders:", orders)
return orders, err
}
// 场景33:where in 子查询表
func FindOrderInSubQuery() ([]Order, error) {
var orders []Order
sql := `SELECT * FROM orders WHERE user_id IN (SELECT id FROM user)`
err := globalDB.Raw(sql).Scan(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景33:where in 子查询表 orders:", orders)
return orders, err
}
// 场景34:union查询。包含分表健
func FindOrderUnion() ([]Order, error) {
var orders []Order
sql := `SELECT * FROM orders WHERE user_id = 8648 UNION SELECT * FROM orders WHERE user_id = 3401`
err := globalDB.Raw(sql).Scan(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景34:union查询 orders:", orders)
return orders, err
}
// 场景35:union all查询。包含分表健
func FindOrderUnionAll() ([]Order, error) {
var orders []Order
sql := `SELECT * FROM orders WHERE user_id = 8648 UNION ALL SELECT * FROM orders WHERE user_id = 3401`
err := globalDB.Raw(sql).Scan(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景35:union all查询 orders:", orders)
return orders, err
}
// 场景36:union 查询。不包含分表健
func FindOrderUnionByOrderId() ([]Order, error) {
var orders []Order
sql := `SELECT * FROM orders WHERE order_id = '20240101ORDER6546' UNION SELECT * FROM orders WHERE order_id = '20240101ORDER9728'`
err := globalDB.Raw(sql).Scan(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景36:union查询 orders:", orders)
return orders, err
}
// 场景37:union all查询。不包含分表健
func FindOrderUnionAllByOrderId() ([]Order, error) {
var orders []Order
sql := `SELECT * FROM orders WHERE order_id = '20240101ORDER6546' UNION ALL SELECT * FROM orders WHERE order_id = '20240101ORDER9728'`
err := globalDB.Raw(sql).Scan(&orders).Error
if err != nil {
fmt.Println("Error finding orders:", err)
return nil, err
}
fmt.Println("场景37:union all查询 orders:", orders)
return orders, err
}
// 场景38:根据主键更新
func UpdateOrderByID(ID int64, productID int) error {
err := globalDB.Table("orders").Where("id = ?", ID).Update("product_id", productID).Error
if err != nil {
fmt.Println("Error updating orders:", err)
}
return err
}
// 场景39:根据分表键更新
func UpdateOrderByUserID(userID int64, productID int) error {
err := globalDB.Table("orders").Where("user_id = ?", userID).Update("product_id", productID).Error
if err != nil {
fmt.Println("Error updating orders:", err)
}
return err
}
// 场景40:根据主键删除
func DeleteOrderByID(ID int64) error {
err := globalDB.Table("orders").Where("id = ?", ID).Delete(&Order{}).Error
if err != nil {
fmt.Println("Error deleting orders:", err)
}
return err
}
// 场景41:根据分表键删除
func DeleteOrderByUserID(userID int64) error {
err := globalDB.Table("orders").Where("user_id = ?", userID).Delete(&Order{}).Error
if err != nil {
fmt.Println("Error deleting orders:", err)
}
return err
}
// InitDb 初始化数据库连接
func InitDb() *gorm.DB {
log := logger.Default.LogMode(logger.Info)
// 连接到 MySQL 数据库
dsn := "sharding:sharding@tcp(localhost:13308)/sharding"
db, err := gorm.Open(mysql.New(mysql.Config{
DSN: dsn,
}), &gorm.Config{
Logger: log,
})
if err != nil {
panic("failed to connect database")
}
globalDB = db
return db
}