azer/crud
azer/crud has 321 GitHub stars and 17 forks. GitHot measured 0 stars in 24 hours. Last checked 2026-11-12 06:53 UTC. Last push 2025-11-02.
Relational database library for SQL databases & Go.
측정된 스타 증가
- in 24h
- 0
- in 7 days
- 업데이트 지연
- in 15 days
- 업데이트 지연
- in 1 month
- 업데이트 지연
서로 겹치는 기간의 순증가량이며 일별 합계가 아닙니다. 측정값이 없으면 비워 둡니다. 스타는 관심도를 나타내며 품질을 보장하지 않습니다.
README.md
OriginalCRUD
Lightweight, simple relational database library for Go. Supports PostgreSQL and MySQL.
Table of Contents
- Install
- Initialize
- Define
- Create
- CreateAndRead
- Read
- Update
- Delete
- Contexts
- Transactions
- Logs
- Custom Queries
- What's Missing?
- LICENSE
Install
$ go get github.com/azer/crud/v4
Initialize
import (
"github.com/azer/crud/v4"
_ "github.com/go-sql-driver/mysql"
)
var DB *crud.DB
func init () {
var err error
DB, err = crud.Connect("mysql", os.Getenv("DATABASE_URL"))
err = DB.Ping()
}
Define
type User struct {
Id int `sql:"auto-increment primary-key"`
FirstName string
LastName string
ProfileId int
}
type Profile struct {
Id int `sql:"auto-increment primary-key"`
Bio string `sql:"text"`
}
CRUD will automatically convert column names from "FirstName" (CamelCase) to "first_name" (snake_case) for you. You can still choose custom names though;
type Post struct {
Slug string `sql:"name=slug_id varchar(255) primary-key required"`
}
If no primary key is specified, CRUD will look for a field named "Id" with int type, and set it as auto-incrementing primary-key field.
Create & Drop Tables
CreateTables takes list of structs and makes sure they exist in the database.
err := DB.CreateTables(User{}, Profile{})
err := DB.DropTables(User{}, Profile{})
Reset Tables
Shortcut for dropping and creating tables.
err := DB.ResetTables(User{}, Profile{})
SQL Options
CRUD tries to be smart about figuring out the best SQL options for your structs, and lets you choose manually, too. For example;
type Tweet struct {
Text string `sql:"varchar(140) required name=tweet"`
}
Above example sets the type of the Text column as varchar(140), makes it required (NOT NULL) and changes the column name as tweet.
Here is the list of the options that you can pass;
- Types:
int,bigint,varchar,text,date,time,timestamp auto-increment/autoincrement/auto_incrementprimary-key/primarykey/primary_keyrequireddefault='?'name=?table-name=?
If you'd like a struct field to be ignored by CRUD, choose - as options:
type Foo struct {
IgnoreMe string `sql:"-"`
}
Create
Simply pass a struct. It can be pointer or not.
user := &User{1, "Foo", "Bar", 1}
err := DB.Create(user)
CreateAndRead
Create a row, and read it back from the DB. The values of the struct you passed get resetted to whatever the corresponding DB row has. In the other words, CreateAndRead creates, and reads. So you got fields generated by the DB scanned to your struct, like ID.
Make sure passing a pointer.
user := User{
FirstName:"Foo"
}
err := DB.CreateAndRead(&user)
user.Id
// => 123
Read
You can read single/multiple rows, or custom values, with the Read method.
Reading a single row:
Pass your struct's pointer, and a query;
user := &User{}
err := DB.Read(user, "SELECT * FROM users WHERE id = ?", 1)
// => SELECT * FROM users WHERE id = 1
fmt.Println(user.Name)
// => Foo
Reading multiple rows:
users := []*User{}
err := DB.Read(&users, "SELECT * FROM users")
// => SELECT * FROM users
fmt.Println(len(users))
// => 10
Scanning to custom values:
names := []string{}
err := DB.Read(&names, "SELECT name FROM users")
name := ""
err := DB.Read(&name, "SELECT name FROM users WHERE id=1")
totalUsers := 0
err := DB.Read(&totalUsers, "SELECT COUNT(id) FROM users"
Update
Updates matching row in database, returns sql.ErrNoRows nothing matched.
user := &User{}
err := DB.Read(user, "SELECT * FROM users WHERE id = ?", 1)
user.Name = "Yolo"
err := DB.Update(user)
Delete
Deletes matching row in database, returns sql.ErrNoRows nothing matched.
err := DB.Delete(&User{
Id: 1
})
Contexts
Use WithContext method to get a DB client with context. Here is an example;
db := DB.WithContext(context.Background())
Transactions
Use Begin method of a crud.DB instance to create a new transaction. Each transaction will provide you following methods;
- Commit
- Rollback
- Exec
- Query
- Create
- CreateAndRead
- Read
- Update
- Delete
tx, err := DB.Begin(context.Background())
err := tx.Create(&User{
Name: "yolo"
})
err := tx.Delete(&User{
Id: 123
})
err := tx.Commit()
CRUD generates an ID for each transaction, and uses that for logging queries and the state of the transactions. You can override transaction IDs in some use cases such as having same IDs and ID field keys with your Rest framework generating request IDs;
tx.Id = requestId
tx.IdKey = "requestId"
Logs
If you want to see crud's internal logs, specify crud in the LOG environment variable when you run your app. For example;
$ LOG=crud go run myapp.go
Custom Queries
result, err := DB.Query("DROP DATABASE yolo") // or .Exec
Running Tests
DATABASE_URL="?" go test ./...
What's Missing?
- Foreign Keys: Won't implement
- Make UTF-8 Default: Looks like the default charset is not UTF8.
LICENSE
관련 프로젝트 살펴보기
Asabeneh/30-Days-Of-Python
30 Days of Python 프로그래밍 챌린지는 Python 프로그래밍 언어를 30일 동안 배우기 위한 단계별 가이드입니다. 이 챌린지는 100일 이상 걸릴 수 있습니다. 자신의 속도에 맞춰 진행하세요. 다음 동영상도 도움이 될 수 있습니다: https://www.youtube.com/channel/UC7PNRuno1rzYPb1xLa4yktw
78,618 스타grafana/grafana
개방적이고 조합 가능한 옵저버빌리티 및 데이터 시각화 플랫폼입니다. Prometheus, Loki, Elasticsearch, InfluxDB, Postgres 등 여러 소스의 메트릭, 로그, 트레이스를 시각화합니다.
77,859 스타redis/redis
실시간 데이터 기반 애플리케이션을 구축하는 개발자에게 Redis는 가장 선호되고, 가장 빠르며, 기능이 가장 풍부한 캐시, 데이터 구조 서버이자 문서 및 벡터 쿼리 엔진입니다.
77,472 스타apache/superset
Apache Superset는 데이터 시각화 및 데이터 탐색 플랫폼입니다.
75,495 스타