gorm-shardinglisted
Install: claude install-skill liurida/gorm-development-skill
# Sharding
The Sharding plugin partitions large tables into smaller ones using SQL parsing, redirecting queries to the appropriate shard.
**Reference:** https://gorm.io/docs/sharding.html
**Repository:** https://github.com/go-gorm/sharding
## Features
- Non-intrusive design (plugin-based)
- No network middleware overhead
- PostgreSQL and MySQL support
- Built-in primary key generators (Snowflake, PostgreSQL Sequence, custom)
## Quick Reference
| Config | Purpose |
|--------|---------|
| `ShardingKey` | Column used to determine shard |
| `NumberOfShards` | Total number of shards (e.g., 64) |
| `PrimaryKeyGenerator` | ID generation strategy |
| `ShardingAlgorithm` | Custom shard routing function |
## Basic Setup
```go
import (
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/sharding"
)
db, err := gorm.Open(postgres.New(postgres.Config{
DSN: "postgres://localhost:5432/sharding-db?sslmode=disable",
}))
// Register sharding for specific tables
db.Use(sharding.Register(sharding.Config{
ShardingKey: "user_id",
NumberOfShards: 64,
PrimaryKeyGenerator: sharding.PKSnowflake,
}, "orders", "order_items", "notifications"))
```
## Primary Key Generators
```go
// Snowflake IDs (recommended for distributed systems)
sharding.PKSnowflake
// PostgreSQL Sequence
sharding.PKPGSequence
// Custom generator
sharding.PKCustom
```
## CRUD Operations
**Critical:** All operations on sharded tables MUST include the sharding key.
```go
// CREATE - sharding key