这主要集中在为我计划编写的涉及创建数据库的测试套件提供setup()和teardown()方法。
我已经弄清楚了如何使用GORM创建数据库。但是,我不确定这是否是最佳方法。
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"log"
)
func main() {
db, err := gorm.Open("postgres", "host=127.0.0.1 port=5432 user=superuser dbname=postgres password='' sslmode=disable")
capture(err)
db = db.Exec("CREATE DATABASE test_db;")
if db.Error != nil {
fmt.Println("Unable to create DB test_db, attempting to connect assuming it exists...")
db, err = gorm.Open("postgres", "host=127.0.0.1 port=5432 user=superuser dbname=test_db password='' sslmode=disable")
if err != nil {
fmt.Println("Unable to connect to test_db")
capture(err)
}
}
defer db.Close()
}
func capture(err error) {
if err != nil {
log.Fatalf("%s", err)
}
}
Run Code Online (Sandbox Code Playgroud)
我先连接到默认postgres数据库,然后创建第二个计划使用的测试数据库。
这是最好的方法吗?或者是否可以在没有预先存在的数据库的情况下连接到Postgres。
注意:我已经在人们使用SQL驱动程序仅使用连接字符串连接到数据库的地方查找了答案user:password@/。这并没有在我的情况下工作。(喜欢这里)
我还尝试了没有数据库名称的连接字符串,这导致驱动程序尝试连接到具有与用户相同名称的数据库。失败,因为这样的数据库不存在。
这是我如何使用Gorm实现创建postgreSQL数据库,关键是仅连接到postgreSQL,创建数据库不需要连接到“数据库”,只需连接到数据库引擎就足够了。只是不要在连接字符串中传递数据库基数。
在main.go中
package main
import (
"gorm.io/driver/postgres"
"gorm.io/gorm"
"fmt"
"github.com/joho/godotenv"
)
func createDatabase() {
dsn := fmt.Sprintf("host=%s port=%s user=%s password=%s sslmode=disable TimeZone=%s", Config("DB_HOST"), Config("DB_PORT"), Config("DB_USER"), Config("DB_PASSWORD"), Config("DB_TIMEZONE"))
DB, _ := gorm.Open(postgres.Open(dsn), &gorm.Config{})
createDatabaseCommand := fmt.Sprintf("CREATE DATABASE %s", Config("DB_NAME"))
DB.Exec(createDatabaseCommand)
}
func main() {
createDatabase()
}
Run Code Online (Sandbox Code Playgroud)
现在只需运行go get -d ./... && go run main.go
你的方法似乎足够有效。您还可以在连接到数据库之前使用 postgrescreatedb实用程序创建数据库。例如:
import (
"log"
"os/exec"
"bytes"
)
func createPgDb() {
cmd := exec.Command("createdb", "-p", "5432", "-h", "127.0.0.1", "-U", "superuser", "-e", "test_db")
var out bytes.Buffer
cmd.Stdout = &out
if err := cmd.Run(); err != nil {
log.Printf("Error: %v", err)
}
log.Printf("Output: %q\n", out.String())
}
Run Code Online (Sandbox Code Playgroud)
此示例摘自 Go 手册中的 Command / Run 示例https://golang.org/pkg/os/exec/#Command
| 归档时间: |
|
| 查看次数: |
1295 次 |
| 最近记录: |