Skip to content

Commit

Permalink
feat: support tidb (#638)
Browse files Browse the repository at this point in the history
  • Loading branch information
Cheese authored Feb 9, 2023
1 parent 29d9dd5 commit a00b07c
Showing 1 changed file with 46 additions and 1 deletion.
47 changes: 46 additions & 1 deletion pages/docs/connecting_to_the_database.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ title: Connecting to a Database
layout: page
---

GORM officially supports the databases MySQL, PostgreSQL, SQLite, SQL Server
GORM officially supports the databases MySQL, PostgreSQL, SQLite, SQL Server, and TiDB

## MySQL

Expand Down Expand Up @@ -158,6 +158,51 @@ dsn := "sqlserver://gorm:LoremIpsum86@localhost:9930?database=gorm"
db, err := gorm.Open(sqlserver.Open(dsn), &gorm.Config{})
```

## TiDB

TiDB is compatible with MySQL protocol. You can follow the [MySQL](#mysql) part to create a connection to TiDB.

There are some points noteworthy for TiDB:

- You can use `gorm:"primaryKey;default:auto_random()"` tag to use [`AUTO_RANDOM`](https://docs.pingcap.com/tidb/stable/auto-random) feature for TiDB.
- TiDB doesn't support the foreign key feature yet so far. You can see the TiDB document [MySQL Compatibility](https://docs.pingcap.com/tidb/stable/mysql-compatibility) for more information.
- TiDB supported [`SAVEPOINT`](https://docs.pingcap.com/tidb/stable/sql-statement-savepoint) from `v6.2.0`, please notice the version of TiDB when you use this feature.

```go
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)

type Product struct {
ID uint `gorm:"primaryKey;default:auto_random()"`
Code string
Price uint
}

func main() {
db, err := gorm.Open(mysql.Open("root:@tcp(127.0.0.1:4000)/test"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}

db.AutoMigrate(&Product{})

insertProduct := &Product{Code: "D42", Price: 100}

db.Create(insertProduct)
fmt.Printf("insert ID: %d, Code: %s, Prict: %d\n",
insertProduct.ID, insertProduct.Code, insertProduct.Price)

readProduct := &Product{}
db.First(&readProduct, "code = ?", "D42") // find product with code D42

fmt.Printf("read ID: %d, Code: %s, Prict: %d\n",
readProduct.ID, readProduct.Code, readProduct.Price)
}
```

## Clickhouse

https://github.com/go-gorm/clickhouse
Expand Down

0 comments on commit a00b07c

Please sign in to comment.