- Docs Home
- About TiDB
- Quick Start
- Develop
- Overview
- Quick Start
- Build a TiDB Cluster in TiDB Cloud (Developer Tier)
- CRUD SQL in TiDB
- Build a Simple CRUD App with TiDB
- Example Applications
- Connect to TiDB
- Design Database Schema
- Write Data
- Read Data
- Transaction
- Optimize
- Troubleshoot
- Reference
- Cloud Native Development Environment
- Third-party Support
- Deploy
- Software and Hardware Requirements
- Environment Configuration Checklist
- Plan Cluster Topology
- Install and Start
- Verify Cluster Status
- Test Cluster Performance
- Migrate
- Overview
- Migration Tools
- Migration Scenarios
- Migrate from Aurora
- Migrate MySQL of Small Datasets
- Migrate MySQL of Large Datasets
- Migrate and Merge MySQL Shards of Small Datasets
- Migrate and Merge MySQL Shards of Large Datasets
- Migrate from CSV Files
- Migrate from SQL Files
- Migrate from One TiDB Cluster to Another TiDB Cluster
- Migrate from TiDB to MySQL-compatible Databases
- Advanced Migration
- Integrate
- Overview
- Integration Scenarios
- Maintain
- Monitor and Alert
- Troubleshoot
- TiDB Troubleshooting Map
- Identify Slow Queries
- Analyze Slow Queries
- SQL Diagnostics
- Identify Expensive Queries Using Top SQL
- Identify Expensive Queries Using Logs
- Statement Summary Tables
- Troubleshoot Hotspot Issues
- Troubleshoot Increased Read and Write Latency
- Save and Restore the On-Site Information of a Cluster
- Troubleshoot Cluster Setup
- Troubleshoot High Disk I/O Usage
- Troubleshoot Lock Conflicts
- Troubleshoot TiFlash
- Troubleshoot Write Conflicts in Optimistic Transactions
- Troubleshoot Inconsistency Between Data and Indexes
- Performance Tuning
- Tuning Guide
- Configuration Tuning
- System Tuning
- Software Tuning
- SQL Tuning
- Overview
- Understanding the Query Execution Plan
- SQL Optimization Process
- Overview
- Logic Optimization
- Physical Optimization
- Prepare Execution Plan Cache
- Control Execution Plans
- Tutorials
- TiDB Tools
- Overview
- Use Cases
- Download
- TiUP
- Documentation Map
- Overview
- Terminology and Concepts
- Manage TiUP Components
- FAQ
- Troubleshooting Guide
- Command Reference
- Overview
- TiUP Commands
- TiUP Cluster Commands
- Overview
- tiup cluster audit
- tiup cluster check
- tiup cluster clean
- tiup cluster deploy
- tiup cluster destroy
- tiup cluster disable
- tiup cluster display
- tiup cluster edit-config
- tiup cluster enable
- tiup cluster help
- tiup cluster import
- tiup cluster list
- tiup cluster patch
- tiup cluster prune
- tiup cluster reload
- tiup cluster rename
- tiup cluster replay
- tiup cluster restart
- tiup cluster scale-in
- tiup cluster scale-out
- tiup cluster start
- tiup cluster stop
- tiup cluster template
- tiup cluster upgrade
- TiUP DM Commands
- Overview
- tiup dm audit
- tiup dm deploy
- tiup dm destroy
- tiup dm disable
- tiup dm display
- tiup dm edit-config
- tiup dm enable
- tiup dm help
- tiup dm import
- tiup dm list
- tiup dm patch
- tiup dm prune
- tiup dm reload
- tiup dm replay
- tiup dm restart
- tiup dm scale-in
- tiup dm scale-out
- tiup dm start
- tiup dm stop
- tiup dm template
- tiup dm upgrade
- TiDB Cluster Topology Reference
- DM Cluster Topology Reference
- Mirror Reference Guide
- TiUP Components
- PingCAP Clinic Diagnostic Service
- TiDB Operator
- Dumpling
- TiDB Lightning
- TiDB Data Migration
- About TiDB Data Migration
- Architecture
- Quick Start
- Deploy a DM cluster
- Tutorials
- Advanced Tutorials
- Maintain
- Cluster Upgrade
- Tools
- Performance Tuning
- Manage Data Sources
- Manage Tasks
- Export and Import Data Sources and Task Configurations of Clusters
- Handle Alerts
- Daily Check
- Reference
- Architecture
- Command Line
- Configuration Files
- OpenAPI
- Compatibility Catalog
- Secure
- Monitoring and Alerts
- Error Codes
- Glossary
- Example
- Troubleshoot
- Release Notes
- Backup & Restore (BR)
- Point-in-Time Recovery
- TiDB Binlog
- TiCDC
- Dumpling
- sync-diff-inspector
- TiSpark
- Reference
- Cluster Architecture
- Key Monitoring Metrics
- Secure
- Privileges
- SQL
- SQL Language Structure and Syntax
- SQL Statements
ADD COLUMN
ADD INDEX
ADMIN
ADMIN CANCEL DDL
ADMIN CHECKSUM TABLE
ADMIN CHECK [TABLE|INDEX]
ADMIN SHOW DDL [JOBS|QUERIES]
ADMIN SHOW TELEMETRY
ALTER DATABASE
ALTER INDEX
ALTER INSTANCE
ALTER PLACEMENT POLICY
ALTER TABLE
ALTER TABLE COMPACT
ALTER TABLE SET TIFLASH MODE
ALTER USER
ANALYZE TABLE
BACKUP
BATCH
BEGIN
CHANGE COLUMN
COMMIT
CHANGE DRAINER
CHANGE PUMP
CREATE [GLOBAL|SESSION] BINDING
CREATE DATABASE
CREATE INDEX
CREATE PLACEMENT POLICY
CREATE ROLE
CREATE SEQUENCE
CREATE TABLE LIKE
CREATE TABLE
CREATE USER
CREATE VIEW
DEALLOCATE
DELETE
DESC
DESCRIBE
DO
DROP [GLOBAL|SESSION] BINDING
DROP COLUMN
DROP DATABASE
DROP INDEX
DROP PLACEMENT POLICY
DROP ROLE
DROP SEQUENCE
DROP STATS
DROP TABLE
DROP USER
DROP VIEW
EXECUTE
EXPLAIN ANALYZE
EXPLAIN
FLASHBACK TABLE
FLUSH PRIVILEGES
FLUSH STATUS
FLUSH TABLES
GRANT <privileges>
GRANT <role>
INSERT
KILL [TIDB]
LOAD DATA
LOAD STATS
MODIFY COLUMN
PREPARE
RECOVER TABLE
RENAME INDEX
RENAME TABLE
REPLACE
RESTORE
REVOKE <privileges>
REVOKE <role>
ROLLBACK
SAVEPOINT
SELECT
SET DEFAULT ROLE
SET [NAMES|CHARACTER SET]
SET PASSWORD
SET ROLE
SET TRANSACTION
SET [GLOBAL|SESSION] <variable>
SHOW ANALYZE STATUS
SHOW [BACKUPS|RESTORES]
SHOW [GLOBAL|SESSION] BINDINGS
SHOW BUILTINS
SHOW CHARACTER SET
SHOW COLLATION
SHOW [FULL] COLUMNS FROM
SHOW CONFIG
SHOW CREATE PLACEMENT POLICY
SHOW CREATE SEQUENCE
SHOW CREATE TABLE
SHOW CREATE USER
SHOW DATABASES
SHOW DRAINER STATUS
SHOW ENGINES
SHOW ERRORS
SHOW [FULL] FIELDS FROM
SHOW GRANTS
SHOW INDEX [FROM|IN]
SHOW INDEXES [FROM|IN]
SHOW KEYS [FROM|IN]
SHOW MASTER STATUS
SHOW PLACEMENT
SHOW PLACEMENT FOR
SHOW PLACEMENT LABELS
SHOW PLUGINS
SHOW PRIVILEGES
SHOW [FULL] PROCESSSLIST
SHOW PROFILES
SHOW PUMP STATUS
SHOW SCHEMAS
SHOW STATS_HEALTHY
SHOW STATS_HISTOGRAMS
SHOW STATS_META
SHOW STATUS
SHOW TABLE NEXT_ROW_ID
SHOW TABLE REGIONS
SHOW TABLE STATUS
SHOW [FULL] TABLES
SHOW [GLOBAL|SESSION] VARIABLES
SHOW WARNINGS
SHUTDOWN
SPLIT REGION
START TRANSACTION
TABLE
TRACE
TRUNCATE
UPDATE
USE
WITH
- Data Types
- Functions and Operators
- Overview
- Type Conversion in Expression Evaluation
- Operators
- Control Flow Functions
- String Functions
- Numeric Functions and Operators
- Date and Time Functions
- Bit Functions and Operators
- Cast Functions and Operators
- Encryption and Compression Functions
- Locking Functions
- Information Functions
- JSON Functions
- Aggregate (GROUP BY) Functions
- Window Functions
- Miscellaneous Functions
- Precision Math
- Set Operations
- List of Expressions for Pushdown
- TiDB Specific Functions
- Clustered Indexes
- Constraints
- Generated Columns
- SQL Mode
- Table Attributes
- Transactions
- Garbage Collection (GC)
- Views
- Partitioning
- Temporary Tables
- Cached Tables
- Character Set and Collation
- Placement Rules in SQL
- System Tables
mysql
- INFORMATION_SCHEMA
- Overview
ANALYZE_STATUS
CLIENT_ERRORS_SUMMARY_BY_HOST
CLIENT_ERRORS_SUMMARY_BY_USER
CLIENT_ERRORS_SUMMARY_GLOBAL
CHARACTER_SETS
CLUSTER_CONFIG
CLUSTER_HARDWARE
CLUSTER_INFO
CLUSTER_LOAD
CLUSTER_LOG
CLUSTER_SYSTEMINFO
COLLATIONS
COLLATION_CHARACTER_SET_APPLICABILITY
COLUMNS
DATA_LOCK_WAITS
DDL_JOBS
DEADLOCKS
ENGINES
INSPECTION_RESULT
INSPECTION_RULES
INSPECTION_SUMMARY
KEY_COLUMN_USAGE
METRICS_SUMMARY
METRICS_TABLES
PARTITIONS
PLACEMENT_POLICIES
PROCESSLIST
REFERENTIAL_CONSTRAINTS
SCHEMATA
SEQUENCES
SESSION_VARIABLES
SLOW_QUERY
STATISTICS
TABLES
TABLE_CONSTRAINTS
TABLE_STORAGE_STATS
TIDB_HOT_REGIONS
TIDB_HOT_REGIONS_HISTORY
TIDB_INDEXES
TIDB_SERVERS_INFO
TIDB_TRX
TIFLASH_REPLICA
TIKV_REGION_PEERS
TIKV_REGION_STATUS
TIKV_STORE_STATUS
USER_PRIVILEGES
VARIABLES_INFO
VIEWS
METRICS_SCHEMA
- UI
- TiDB Dashboard
- Overview
- Maintain
- Access
- Overview Page
- Cluster Info Page
- Top SQL Page
- Key Visualizer Page
- Metrics Relation Graph
- SQL Statements Analysis
- Slow Queries Page
- Cluster Diagnostics
- Monitoring Page
- Search Logs Page
- Instance Profiling
- Session Management and Configuration
- FAQ
- CLI
- Command Line Flags
- Configuration File Parameters
- System Variables
- Storage Engines
- Telemetry
- Errors Codes
- Table Filter
- Schedule Replicas by Topology Labels
- FAQs
- Release Notes
- All Releases
- Release Timeline
- TiDB Versioning
- TiDB Installation Packages
- v6.2
- v6.1
- v6.0
- v5.4
- v5.3
- v5.2
- v5.1
- v5.0
- v4.0
- v3.1
- v3.0
- v2.1
- v2.0
- v1.0
- Glossary
Build a Simple CRUD App with TiDB and Golang
This document describes how to use TiDB and Golang to build a simple CRUD application.
It is recommended to use Golang 1.16 or a later version.
Step 1. Launch your TiDB cluster
The following introduces how to start a TiDB cluster.
Use a TiDB Cloud free cluster
For detailed steps, see Create a free cluster.
Use a local cluster
For detailed steps, see Deploy a local test cluster or Deploy a TiDB Cluster Using TiUP.
Step 2. Get the code
git clone https://github.com/pingcap-inc/tidb-example-golang.git
- Using go-sql-driver/mysql
- Using GORM (Recommended)
Change to the sqldriver
directory:
cd sqldriver
The structure of this directory is as follows:
.
├── Makefile
├── dao.go
├── go.mod
├── go.sum
├── sql
│ └── dbinit.sql
├── sql.go
└── sqldriver.go
You can find initialization statements for the table creation in dbinit.sql
:
USE test;
DROP TABLE IF EXISTS player;
CREATE TABLE player (
`id` VARCHAR(36),
`coins` INTEGER,
`goods` INTEGER,
PRIMARY KEY (`id`)
);
sqldriver.go
is the main body of the sqldriver
. TiDB is highly compatible with the MySQL protocol, so you need to initialize a MySQL source instance db, err := sql.Open("mysql", dsn)
to connect to TiDB. Then, you can use dao.go
to read, edit, add, and delete data.
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
// 1. Configure the example database connection.
dsn := "root:@tcp(127.0.0.1:4000)/test?charset=utf8mb4"
openDB("mysql", dsn, func(db *sql.DB) {
// 2. Run some simple examples.
simpleExample(db)
// 3. Explore more.
tradeExample(db)
})
}
func simpleExample(db *sql.DB) {
// Create a player, who has a coin and a goods.
err := createPlayer(db, Player{ID: "test", Coins: 1, Goods: 1})
if err != nil {
panic(err)
}
// Get a player.
testPlayer, err := getPlayer(db, "test")
if err != nil {
panic(err)
}
fmt.Printf("getPlayer: %+v\n", testPlayer)
// Create players with bulk inserts. Insert 1919 players totally, with 114 players per batch.
err = bulkInsertPlayers(db, randomPlayers(1919), 114)
if err != nil {
panic(err)
}
// Count players amount.
playersCount, err := getCount(db)
if err != nil {
panic(err)
}
fmt.Printf("countPlayers: %d\n", playersCount)
// Print 3 players.
threePlayers, err := getPlayerByLimit(db, 3)
if err != nil {
panic(err)
}
for index, player := range threePlayers {
fmt.Printf("print %d player: %+v\n", index+1, player)
}
}
func tradeExample(db *sql.DB) {
// Player 1: id is "1", has only 100 coins.
// Player 2: id is "2", has 114514 coins, and 20 goods.
player1 := Player{ID: "1", Coins: 100}
player2 := Player{ID: "2", Coins: 114514, Goods: 20}
// Create two players "by hand", using the INSERT statement on the backend.
if err := createPlayer(db, player1); err != nil {
panic(err)
}
if err := createPlayer(db, player2); err != nil {
panic(err)
}
// Player 1 wants to buy 10 goods from player 2.
// It will cost 500 coins, but player 1 cannot afford it.
fmt.Println("\nbuyGoods:\n => this trade will fail")
if err := buyGoods(db, player2.ID, player1.ID, 10, 500); err == nil {
panic("there shouldn't be success")
}
// So player 1 has to reduce the incoming quantity to two.
fmt.Println("\nbuyGoods:\n => this trade will success")
if err := buyGoods(db, player2.ID, player1.ID, 2, 100); err != nil {
panic(err)
}
}
func openDB(driverName, dataSourceName string, runnable func(db *sql.DB)) {
db, err := sql.Open(driverName, dataSourceName)
if err != nil {
panic(err)
}
defer db.Close()
runnable(db)
}
To adapt TiDB transactions, write a toolkit util according to the following code:
package util
import (
"context"
"database/sql"
)
type TiDBSqlTx struct {
*sql.Tx
conn *sql.Conn
pessimistic bool
}
func TiDBSqlBegin(db *sql.DB, pessimistic bool) (*TiDBSqlTx, error) {
ctx := context.Background()
conn, err := db.Conn(ctx)
if err != nil {
return nil, err
}
if pessimistic {
_, err = conn.ExecContext(ctx, "set @@tidb_txn_mode=?", "pessimistic")
} else {
_, err = conn.ExecContext(ctx, "set @@tidb_txn_mode=?", "optimistic")
}
if err != nil {
return nil, err
}
tx, err := conn.BeginTx(ctx, nil)
if err != nil {
return nil, err
}
return &TiDBSqlTx{
conn: conn,
Tx: tx,
pessimistic: pessimistic,
}, nil
}
func (tx *TiDBSqlTx) Commit() error {
defer tx.conn.Close()
return tx.Tx.Commit()
}
func (tx *TiDBSqlTx) Rollback() error {
defer tx.conn.Close()
return tx.Tx.Rollback()
}
dao.go
defines a set of data manipulation methods to provide the ability to write data. This is also the core part of this example.
package main
import (
"database/sql"
"fmt"
"math/rand"
"strings"
"github.com/google/uuid"
"github.com/pingcap-inc/tidb-example-golang/util"
)
type Player struct {
ID string
Coins int
Goods int
}
// createPlayer create a player
func createPlayer(db *sql.DB, player Player) error {
_, err := db.Exec(CreatePlayerSQL, player.ID, player.Coins, player.Goods)
return err
}
// getPlayer get a player
func getPlayer(db *sql.DB, id string) (Player, error) {
var player Player
rows, err := db.Query(GetPlayerSQL, id)
if err != nil {
return player, err
}
defer rows.Close()
if rows.Next() {
err = rows.Scan(&player.ID, &player.Coins, &player.Goods)
if err == nil {
return player, nil
} else {
return player, err
}
}
return player, fmt.Errorf("can not found player")
}
// getPlayerByLimit get players by limit
func getPlayerByLimit(db *sql.DB, limit int) ([]Player, error) {
var players []Player
rows, err := db.Query(GetPlayerByLimitSQL, limit)
if err != nil {
return players, err
}
defer rows.Close()
for rows.Next() {
player := Player{}
err = rows.Scan(&player.ID, &player.Coins, &player.Goods)
if err == nil {
players = append(players, player)
} else {
return players, err
}
}
return players, nil
}
// bulk-insert players
func bulkInsertPlayers(db *sql.DB, players []Player, batchSize int) error {
tx, err := util.TiDBSqlBegin(db, true)
if err != nil {
return err
}
stmt, err := tx.Prepare(buildBulkInsertSQL(batchSize))
if err != nil {
return err
}
defer stmt.Close()
for len(players) > batchSize {
if _, err := stmt.Exec(playerToArgs(players[:batchSize])...); err != nil {
tx.Rollback()
return err
}
players = players[batchSize:]
}
if len(players) != 0 {
if _, err := tx.Exec(buildBulkInsertSQL(len(players)), playerToArgs(players)...); err != nil {
tx.Rollback()
return err
}
}
if err := tx.Commit(); err != nil {
tx.Rollback()
return err
}
return nil
}
func getCount(db *sql.DB) (int, error) {
count := 0
rows, err := db.Query(GetCountSQL)
if err != nil {
return count, err
}
defer rows.Close()
if rows.Next() {
if err := rows.Scan(&count); err != nil {
return count, err
}
}
return count, nil
}
func buyGoods(db *sql.DB, sellID, buyID string, amount, price int) error {
var sellPlayer, buyPlayer Player
tx, err := util.TiDBSqlBegin(db, true)
if err != nil {
return err
}
buyExec := func() error {
stmt, err := tx.Prepare(GetPlayerWithLockSQL)
if err != nil {
return err
}
defer stmt.Close()
sellRows, err := stmt.Query(sellID)
if err != nil {
return err
}
defer sellRows.Close()
if sellRows.Next() {
if err := sellRows.Scan(&sellPlayer.ID, &sellPlayer.Coins, &sellPlayer.Goods); err != nil {
return err
}
}
sellRows.Close()
if sellPlayer.ID != sellID || sellPlayer.Goods < amount {
return fmt.Errorf("sell player %s goods not enough", sellID)
}
buyRows, err := stmt.Query(buyID)
if err != nil {
return err
}
defer buyRows.Close()
if buyRows.Next() {
if err := buyRows.Scan(&buyPlayer.ID, &buyPlayer.Coins, &buyPlayer.Goods); err != nil {
return err
}
}
buyRows.Close()
if buyPlayer.ID != buyID || buyPlayer.Coins < price {
return fmt.Errorf("buy player %s coins not enough", buyID)
}
updateStmt, err := tx.Prepare(UpdatePlayerSQL)
if err != nil {
return err
}
defer updateStmt.Close()
if _, err := updateStmt.Exec(-amount, price, sellID); err != nil {
return err
}
if _, err := updateStmt.Exec(amount, -price, buyID); err != nil {
return err
}
return nil
}
err = buyExec()
if err == nil {
fmt.Println("\n[buyGoods]:\n 'trade success'")
tx.Commit()
} else {
tx.Rollback()
}
return err
}
func playerToArgs(players []Player) []interface{} {
var args []interface{}
for _, player := range players {
args = append(args, player.ID, player.Coins, player.Goods)
}
return args
}
func buildBulkInsertSQL(amount int) string {
return CreatePlayerSQL + strings.Repeat(",(?,?,?)", amount-1)
}
func randomPlayers(amount int) []Player {
players := make([]Player, amount, amount)
for i := 0; i < amount; i++ {
players[i] = Player{
ID: uuid.New().String(),
Coins: rand.Intn(10000),
Goods: rand.Intn(10000),
}
}
return players
}
sql.go
defines SQL statements as constants:
package main
const (
CreatePlayerSQL = "INSERT INTO player (id, coins, goods) VALUES (?, ?, ?)"
GetPlayerSQL = "SELECT id, coins, goods FROM player WHERE id = ?"
GetCountSQL = "SELECT count(*) FROM player"
GetPlayerWithLockSQL = GetPlayerSQL + " FOR UPDATE"
UpdatePlayerSQL = "UPDATE player set goods = goods + ?, coins = coins + ? WHERE id = ?"
GetPlayerByLimitSQL = "SELECT id, coins, goods FROM player LIMIT ?"
)
Compared with GORM, the go-sql-driver/mysql implementation might be not a best practice, because you need to write error handling logic, close *sql.Rows
manually and cannot reuse code easily, which makes your code slightly redundant.
GORM is a popular open-source ORM library for Golang. The following instructions take v1.23.5
as an example.
To adapt TiDB transactions, write a toolkit util according to the following code:
package util
import (
"context"
"database/sql"
)
type TiDBSqlTx struct {
*sql.Tx
conn *sql.Conn
pessimistic bool
}
func TiDBSqlBegin(db *sql.DB, pessimistic bool) (*TiDBSqlTx, error) {
ctx := context.Background()
conn, err := db.Conn(ctx)
if err != nil {
return nil, err
}
if pessimistic {
_, err = conn.ExecContext(ctx, "set @@tidb_txn_mode=?", "pessimistic")
} else {
_, err = conn.ExecContext(ctx, "set @@tidb_txn_mode=?", "optimistic")
}
if err != nil {
return nil, err
}
tx, err := conn.BeginTx(ctx, nil)
if err != nil {
return nil, err
}
return &TiDBSqlTx{
conn: conn,
Tx: tx,
pessimistic: pessimistic,
}, nil
}
func (tx *TiDBSqlTx) Commit() error {
defer tx.conn.Close()
return tx.Tx.Commit()
}
func (tx *TiDBSqlTx) Rollback() error {
defer tx.conn.Close()
return tx.Tx.Rollback()
}
Change to the gorm
directory:
cd gorm
The structure of this directory is as follows:
.
├── Makefile
├── go.mod
├── go.sum
└── gorm.go
gorm.go
is the main body of the gorm
. Compared with go-sql-driver/mysql, GORM avoids differences in database creation between different databases. It also implements a lot of operations, such as AutoMigrate and CRUD of objects, which greatly simplifies the code.
Player
is a data entity struct that is a mapping for tables. Each property of a Player
corresponds to a field in the player
table. Compared with go-sql-driver/mysql, Player
in GORM adds struct tags to indicate mapping relationships for more information, such as gorm:"primaryKey;type:VARCHAR(36);column:id"
.
package main
import (
"fmt"
"math/rand"
"github.com/google/uuid"
"github.com/pingcap-inc/tidb-example-golang/util"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/logger"
)
type Player struct {
ID string `gorm:"primaryKey;type:VARCHAR(36);column:id"`
Coins int `gorm:"column:coins"`
Goods int `gorm:"column:goods"`
}
func (*Player) TableName() string {
return "player"
}
func main() {
// 1. Configure the example database connection.
db := createDB()
// AutoMigrate for player table
db.AutoMigrate(&Player{})
// 2. Run some simple examples.
simpleExample(db)
// 3. Explore more.
tradeExample(db)
}
func tradeExample(db *gorm.DB) {
// Player 1: id is "1", has only 100 coins.
// Player 2: id is "2", has 114514 coins, and 20 goods.
player1 := &Player{ID: "1", Coins: 100}
player2 := &Player{ID: "2", Coins: 114514, Goods: 20}
// Create two players "by hand", using the INSERT statement on the backend.
db.Clauses(clause.OnConflict{UpdateAll: true}).Create(player1)
db.Clauses(clause.OnConflict{UpdateAll: true}).Create(player2)
// Player 1 wants to buy 10 goods from player 2.
// It will cost 500 coins, but player 1 cannot afford it.
fmt.Println("\nbuyGoods:\n => this trade will fail")
if err := buyGoods(db, player2.ID, player1.ID, 10, 500); err == nil {
panic("there shouldn't be success")
}
// So player 1 has to reduce the incoming quantity to two.
fmt.Println("\nbuyGoods:\n => this trade will success")
if err := buyGoods(db, player2.ID, player1.ID, 2, 100); err != nil {
panic(err)
}
}
func simpleExample(db *gorm.DB) {
// Create a player, who has a coin and a goods.
if err := db.Clauses(clause.OnConflict{UpdateAll: true}).
Create(&Player{ID: "test", Coins: 1, Goods: 1}).Error; err != nil {
panic(err)
}
// Get a player.
var testPlayer Player
db.Find(&testPlayer, "id = ?", "test")
fmt.Printf("getPlayer: %+v\n", testPlayer)
// Create players with bulk inserts. Insert 1919 players totally, with 114 players per batch.
bulkInsertPlayers := make([]Player, 1919, 1919)
total, batch := 1919, 114
for i := 0; i < total; i++ {
bulkInsertPlayers[i] = Player{
ID: uuid.New().String(),
Coins: rand.Intn(10000),
Goods: rand.Intn(10000),
}
}
if err := db.Session(&gorm.Session{Logger: db.Logger.LogMode(logger.Error)}).
CreateInBatches(bulkInsertPlayers, batch).Error; err != nil {
panic(err)
}
// Count players amount.
playersCount := int64(0)
db.Model(&Player{}).Count(&playersCount)
fmt.Printf("countPlayers: %d\n", playersCount)
// Print 3 players.
threePlayers := make([]Player, 3, 3)
db.Limit(3).Find(&threePlayers)
for index, player := range threePlayers {
fmt.Printf("print %d player: %+v\n", index+1, player)
}
}
func createDB() *gorm.DB {
dsn := "root:@tcp(127.0.0.1:4000)/test?charset=utf8mb4"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
})
if err != nil {
panic(err)
}
return db
}
func buyGoods(db *gorm.DB, sellID, buyID string, amount, price int) error {
return util.TiDBGormBegin(db, true, func(tx *gorm.DB) error {
var sellPlayer, buyPlayer Player
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
Find(&sellPlayer, "id = ?", sellID).Error; err != nil {
return err
}
if sellPlayer.ID != sellID || sellPlayer.Goods < amount {
return fmt.Errorf("sell player %s goods not enough", sellID)
}
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
Find(&buyPlayer, "id = ?", buyID).Error; err != nil {
return err
}
if buyPlayer.ID != buyID || buyPlayer.Coins < price {
return fmt.Errorf("buy player %s coins not enough", buyID)
}
updateSQL := "UPDATE player set goods = goods + ?, coins = coins + ? WHERE id = ?"
if err := tx.Exec(updateSQL, -amount, price, sellID).Error; err != nil {
return err
}
if err := tx.Exec(updateSQL, amount, -price, buyID).Error; err != nil {
return err
}
fmt.Println("\n[buyGoods]:\n 'trade success'")
return nil
})
}
Step 3. Run the code
The following content introduces how to run the code step by step.
Step 3.1 Table initialization
- Using go-sql-driver/mysql
- Using GORM (Recommended)
When using go-sql-driver/mysql, you need to initialize the database tables manually. If you are using a local cluster, and MySQL client has been installed locally, you can run it directly in the sqldriver
directory:
make mysql
Or you can execute the following command:
mysql --host 127.0.0.1 --port 4000 -u root<sql/dbinit.sql
If you are using a non-local cluster or MySQL client has not been installed, connect to your cluster and run the statement in the sql/dbinit.sql
file.
When using go-sql-driver/mysql, you need to connect to your cluster and run the statement in the sql/dbinit.sql
file to initialize the database tables manually.
No need to initialize tables manually.
Step 3.2 Modify parameters for TiDB Cloud
- Using go-sql-driver/mysql
- Using GORM (Recommended)
If you are using a non-local default cluster, such as TiDB Cloud or other remote clusters, modify the value of the dsn
in sqldriver.go
:
dsn := "root:@tcp(127.0.0.1:4000)/test?charset=utf8mb4"
Suppose that the password you set is 123456
and the connection string you get from TiDB Cloud is the following:
mysql --connect-timeout 15 -u root -h xxx.tidbcloud.com -P 4000 -p
In this case, you can modify the parameters as follows:
dsn := "root:123456@tcp(xxx.tidbcloud.com:4000)/test?charset=utf8mb4"
If you are using a non-local default cluster, such as TiDB Cloud or other remote clusters, modify the value of the dsn
in gorm.go
:
dsn := "root:@tcp(127.0.0.1:4000)/test?charset=utf8mb4"
Suppose that the password you set is 123456
and the connection string you get from TiDB Cloud is the following:
mysql --connect-timeout 15 -u root -h xxx.tidbcloud.com -P 4000 -p
In this case, you can modify the parameters as follows:
dsn := "root:123456@tcp(xxx.tidbcloud.com:4000)/test?charset=utf8mb4"
Step 3.3 Run
- Using go-sql-driver/mysql
- Using GORM (Recommended)
To run the code, you can run make mysql
, make build
and make run
respectively:
make mysql # this command executes `mysql --host 127.0.0.1 --port 4000 -u root<sql/dbinit.sql`
make build # this command executes `go build -o bin/sql-driver-example`
make run # this command executes `./bin/sql-driver-example`
Or you can use the native commands:
mysql --host 127.0.0.1 --port 4000 -u root<sql/dbinit.sql
go build -o bin/sql-driver-example
./bin/sql-driver-example
Or run the make all
command directly, which is a combination of make mysql
, make build
and make run
.
To run the code, you can run make build
and make run
respectively:
make build # this command executes `go build -o bin/gorm-example`
make run # this command executes `./bin/gorm-example`
Or you can use the native commands:
go build -o bin/gorm-example
./bin/gorm-example
Or run the make
command directly, which is a combination of make build
and make run
.
Step 4. Expected output
- Using go-sql-driver/mysql
- Using GORM (Recommended)