GormX is a useful Gorm utility for Golang, which makes it easy to connect to MySQL and PostgreSQL databases.
- Easily create and manage connections to MySQL and PostgreSQL databases
- Create, check, and drop databases
- Create, check, and drop tables
- Define table structures using
gormx.Model
andgormx.RelatedModel
- Preset scopes for sorting and pagination
go get -u github.com/goliajp/gormx
You can create connections to MySQL and PostgreSQL databases using the gormx.NewMysql() and gormx.NewPg() functions respectively. These functions return a *gorm.DB instance, which you can use for Gorm operations.
m := gormx.NewMysql(nil) // nil is the default config: localhost:3306, root, root, mysql
db := m.DB() // db is *gorm.DB, then you can use Gorm normally
p := gormx.NewPg(nil) // nil is the default config: localhost:5432, postgres, postgres, postgres, Asia/Shanghai
db := p.DB() // db is *gorm.DB, then you can use Gorm normally
You can also provide a custom configuration for both MySQL and PostgreSQL connections.
cfg := gormx.MysqlConfig{
User: "your username",
Password: "your password",
Addr: "host:port",
Dbname: "connect dbname",
}
m := gormx.NewMysql(&cfg)
db := m.Open()
cfg := gormx.PgConfig{
User: "your username",
Password: "your password",
Host: "your host",
Port: 9999, // int, your host port
Dbname: "connect dbname",
Tz: "Asia/Shanghai", // timezone
}
p := gormx.NewPg(&cfg)
db := p.Open()
Using the GormX utility, you can perform various database operations such as creating, checking, and dropping databases.
if err := gormx.CreateDatabase(db, "testdb"); err != nil {
// error handler
}
hasTdb, err := gormx.HasDatabase(db, "testdb")
if err != nil {
// error handler
}
tdb := m.Open("testdb")
if err := gormx.DropDatabase(db, "testdb"); err != nil {
// error handler
}
Using the GormX utility, you can perform various table operations such as creating, checking, and dropping tables.
if err := gormx.DropTables(db, "table1", "table2"); err != nil {
// error handler
}
hasTable, err := gormx.HasTable(db, "table1")
if err != nil {
// error handler
}
GormX provides gormx.Model and gormx.RelatedModel to help you define table structures.
type One struct {
gormx.Model
// attrs...
}
type Two struct {
gormx.Model
// attrs...
}
type OneTwo struct { // define the relationship of "one" and "two"
gormx.RelatedModel
OneId int
TwoId int
One *One
Two *Two
}
GormX provides preset scopes that can be helpful when you need to retrieve list results.
var rs []Foo
db.Scopes(gormx.ScopeOrderByCreatedAtDesc).Find(&rs)
var rs []Foo
db.Scopes(gormx.ScopeOrderByUpdatedAtDesc).Find(&rs)
var rs []Foo
db.Scopes(gormx.ScopePagination(1, 10)).Find(&rs)
We welcome contributions to GormX! Feel free to submit issues, feature requests, or pull requests on GitHub.
This project is licensed under the MIT License - see the LICENSE file for details.