本文整理汇总了Golang中github.com/jinzhu/gorm.Open函数的典型用法代码示例。如果您正苦于以下问题:Golang Open函数的具体用法?Golang Open怎么用?Golang Open使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Open函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestDB
func TestDB() *gorm.DB {
dbuser, dbpwd, dbname := "qor", "qor", "qor_test"
if os.Getenv("TEST_ENV") == "CI" {
dbuser, dbpwd = os.Getenv("DB_USER"), os.Getenv("DB_PWD")
}
var db gorm.DB
var err error
if os.Getenv("TEST_DB") == "postgres" {
db, err = gorm.Open("postgres", fmt.Sprintf("postgres://%s:%[email protected]/%s?sslmode=disable", dbuser, dbpwd, dbname))
} else {
// CREATE USER 'qor'@'localhost' IDENTIFIED BY 'qor';
// CREATE DATABASE qor_test;
// GRANT ALL ON qor_test.* TO 'qor'@'localhost';
db, err = gorm.Open("mysql", fmt.Sprintf("%s:%[email protected]/%s?charset=utf8&parseTime=True&loc=Local", dbuser, dbpwd, dbname))
}
if err != nil {
panic(err)
}
return &db
}
示例2: init
func init() {
var err error
dbConfig := config.Config.DB
if config.Config.DB.Adapter == "mysql" {
DB, err = gorm.Open("mysql", fmt.Sprintf("%v:%[email protected]/%v?parseTime=True&loc=Local", dbConfig.User, dbConfig.Password, dbConfig.Name))
} else if config.Config.DB.Adapter == "postgres" {
DB, err = gorm.Open("postgres", fmt.Sprintf("postgres://%v:%[email protected]/%v?sslmode=disable", dbConfig.User, dbConfig.Password, dbConfig.Name))
} else {
panic(errors.New("not supported database adapter"))
}
if err == nil {
if os.Getenv("DEBUG") != "" {
DB.LogMode(true)
}
Publish = publish.New(DB.Set("l10n:mode", "unscoped"))
l10n.RegisterCallbacks(DB)
sorting.RegisterCallbacks(DB)
validations.RegisterCallbacks(DB)
media_library.RegisterCallbacks(DB)
} else {
panic(err)
}
}
示例3: init
func init() {
var err error
switch DBType {
case "mysql":
DB, err = gorm.Open("mysql", fmt.Sprintf("%s:%[email protected](%s)/%s", DBUser, DBPass, DBHost, DBName))
case "sqlite3":
DB, err = gorm.Open("sqlite3", "file:"+DBName)
case "postgres":
DB, err = gorm.Open("postgres", fmt.Sprintf("postgres://%s:%[email protected]%s/%s", DBUser, DBPass, DBHost, DBName))
default:
klog.Fatalf("db: I don't know how to handle %v", DBType)
}
DB.LogMode(DBDebug)
DB.SetLogger(gorm.Logger{LogWriter: klog.Logger})
if err = DB.DB().Ping(); err != nil {
klog.Fatalf("db: couldn't ping the database: %v", err)
}
DB.DB().SetMaxIdleConns(10)
DB.DB().SetMaxOpenConns(100)
if err = DB.AutoMigrate(&Advisory{}, &List{}, &ListActivity{},
&ListArtifact{}, &ListLink{}, &ListStage{}, &ListStageProcess{},
&User{}, &UserPermission{}).Error; err != nil {
klog.Fatalf("db: failed to automigrate: %v", err)
}
}
示例4: init
func init() {
var err error
if os.Getenv("DB") == "mysql" {
if DB, err = gorm.Open("mysql", "qor:[email protected]/qor_bookstore?parseTime=True&loc=Local"); err != nil {
panic(err)
}
} else {
if DB, err = gorm.Open("postgres", "user=qor password=qor dbname=qor_bookstore sslmode=disable"); err != nil {
panic(err)
}
}
DB.AutoMigrate(&models.Author{}, &models.Book{}, &models.User{})
DB.LogMode(true)
Pub = publish.New(&DB)
Pub.AutoMigrate(&models.Author{}, &models.Book{})
StagingDB = Pub.DraftDB() // Draft resources are saved here
ProductionDB = Pub.ProductionDB() // Published resources are saved here
l10n.Global = "en-US"
l10n.RegisterCallbacks(&DB)
}
示例5: init
func init() {
var err error
switch os.Getenv("GORM_DIALECT") {
case "mysql":
// CREATE USER 'gorm'@'localhost' IDENTIFIED BY 'gorm';
// CREATE DATABASE gorm;
// GRANT ALL ON gorm.* TO 'gorm'@'localhost';
fmt.Println("testing mysql...")
DB, err = gorm.Open("mysql", "gorm:[email protected]/gorm?charset=utf8&parseTime=True")
case "postgres":
fmt.Println("testing postgres...")
DB, err = gorm.Open("postgres", "user=gorm DB.ame=gorm sslmode=disable")
case "mssql":
fmt.Println("testing mssql...")
DB, err = gorm.Open("mssql", "server=SERVER_HERE;database=rogue;user id=USER_HERE;password=PW_HERE;port=1433")
default:
fmt.Println("testing sqlite3...")
DB, err = gorm.Open("sqlite3", "/tmp/gorm.db")
}
// DB.SetLogger(Logger{log.New(os.Stdout, "\r\n", 0)})
// DB.SetLogger(log.New(os.Stdout, "\r\n", 0))
DB.LogMode(true)
DB.LogMode(false)
if err != nil {
panic(fmt.Sprintf("No error should happen when connect database, but got %+v", err))
}
DB.DB().SetMaxIdleConns(10)
runMigration()
}
示例6: init
func init() {
var err error
cmd := os.Args[0]
if strings.Contains(cmd, "test") {
// We are doing testing!
DB, err = gorm.Open("sqlite3", ":memory:")
fmt.Println("TEST")
DB.AutoMigrate(Organization{})
DB.AutoMigrate(Repository{})
DB.AutoMigrate(Commit{})
DB.AutoMigrate(User{})
DB.AutoMigrate(Pull{})
DB.AutoMigrate(Issue{})
DB.AutoMigrate(CommitOrgStats{})
DB.AutoMigrate(RepoStat{})
} else {
DB, err = gorm.Open("postgres", os.Getenv("PG_CONN_STR"))
// DB.LogMode(true)
DB.DB().SetMaxOpenConns(10)
}
if err != nil {
panic(fmt.Sprintf("Got error when connect database, the error is '%v'", err))
}
}
示例7: OpenTestConnection
func OpenTestConnection() (db *gorm.DB, err error) {
switch os.Getenv("GORM_DIALECT") {
case "mysql":
// CREATE USER 'gorm'@'localhost' IDENTIFIED BY 'gorm';
// CREATE DATABASE gorm;
// GRANT ALL ON gorm.* TO 'gorm'@'localhost';
fmt.Println("testing mysql...")
dbhost := os.Getenv("GORM_DBADDRESS")
if dbhost != "" {
dbhost = fmt.Sprintf("tcp(%v)", dbhost)
}
db, err = gorm.Open("mysql", fmt.Sprintf("gorm:[email protected]%v/gorm?charset=utf8&parseTime=True", dbhost))
case "postgres":
fmt.Println("testing postgres...")
dbhost := os.Getenv("GORM_DBHOST")
if dbhost != "" {
dbhost = fmt.Sprintf("host=%v ", dbhost)
}
db, err = gorm.Open("postgres", fmt.Sprintf("%vuser=gorm password=gorm DB.name=gorm sslmode=disable", dbhost))
case "foundation":
fmt.Println("testing foundation...")
db, err = gorm.Open("foundation", "dbname=gorm port=15432 sslmode=disable")
case "mssql":
fmt.Println("testing mssql...")
db, err = gorm.Open("mssql", "server=SERVER_HERE;database=rogue;user id=USER_HERE;password=PW_HERE;port=1433")
default:
fmt.Println("testing sqlite3...")
db, err = gorm.Open("sqlite3", filepath.Join(os.TempDir(), "gorm.db"))
}
return
}
示例8: DBInit
// DBinit is a generic helper function that will try to connect to a database with the config in the input.
// Supported DB types:
// * postgres
// * sqlite3
func DBInit(dbConfig *DBConfig) (*gorm.DB, error) {
var DB gorm.DB
var err error
switch dbConfig.DbType {
case "postgres":
conn := "dbname=%s user=%s password=%s host=%s sslmode=%s port=%d"
conn = fmt.Sprintf(conn,
dbConfig.DbName,
dbConfig.Username,
dbConfig.Password,
dbConfig.Url,
dbConfig.Sslmode,
dbConfig.Port)
DB, err = gorm.Open("postgres", conn)
case "sqlite3":
DB, err = gorm.Open("sqlite3", dbConfig.DbName)
default:
errorString := "Cannot connect. Unsupported DB type: (" + dbConfig.DbType + ")"
log.Println(errorString)
return nil, errors.New(errorString)
}
if err != nil {
log.Println("Error!")
return nil, err
}
if err = DB.DB().Ping(); err != nil {
log.Println("Unable to verify connection to database")
return nil, err
}
return &DB, nil
}
示例9: init
func init() {
var err error
var db gorm.DB
dbConfig := config.Config.DB
if config.Config.DB.Adapter == "mysql" {
db, err = gorm.Open("mysql", fmt.Sprintf("%v:%[email protected]/%v?parseTime=True&loc=Local", dbConfig.User, dbConfig.Password, dbConfig.Name))
} else if config.Config.DB.Adapter == "postgres" {
db, err = gorm.Open("postgres", fmt.Sprintf("user=%v password=%v dbname=%v sslmode=disable", dbConfig.User, dbConfig.Password, dbConfig.Name))
} else {
panic(errors.New("not supported database adapter"))
}
if err == nil {
DB = &db
Publish = publish.New(DB)
config.Config.I18n = i18n.New(database.New(DB))
l10n.RegisterCallbacks(DB)
sorting.RegisterCallbacks(DB)
validations.RegisterCallbacks(DB)
} else {
panic(err)
}
}
示例10: init
func init() {
config := configuration.Get().Database
switch config.Kind {
case configuration.DbKind_SQLite:
db, err := gorm.Open("sqlite3", config.SQLite.DatabaseFilePath)
if err != nil {
panic(err)
}
_db = &db
initializeDatabase(_db)
case configuration.DbKind_PostgreSQL:
cs := fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s sslmode=disable",
env.ResolveEnv(config.PostgreSQL.Host),
env.ResolveEnv(config.PostgreSQL.Port),
env.ResolveEnv(config.PostgreSQL.User),
env.ResolveEnv(config.PostgreSQL.Database),
env.ResolveEnv(config.PostgreSQL.Password),
)
fmt.Println("★", cs)
db, err := gorm.Open("postgres", cs)
if err != nil {
panic(err)
}
_db = &db
initializeDatabase(_db)
}
}
示例11: newDB
func newDB() *gorm.DB {
hostname, _ := os.Hostname()
if strings.Contains(hostname, "local") {
db, _ := gorm.Open("postgres", "user=rompei dbname=qna sslmode=disable")
return &db
}
db, _ := gorm.Open("postgres", os.Getenv("DATABASE_URL"))
return &db
}
示例12: GetBkimg
//GetBkimg url: /user/bkimg/get
func GetBkimg(cookie UserCookie, config Config, logger *log.Logger, r render.Render) {
if !cookie.Validate() {
r.JSON(http.StatusOK, J{"data": nil})
logger.Info("Fail to auth whith cookie:", cookie)
return
}
db, err := gorm.Open(config.DB.Type, config.DB.Uri)
if err != nil {
r.JSON(http.StatusInternalServerError, J{"data": nil, "err": J{"code": 201, "msg": "database open error."}})
return
}
var BkimgName string
row := db.Table("users").Where(&cookie).Select("bkimg").Row()
if row == nil {
r.JSON(http.StatusInternalServerError, J{"data": nil})
logger.Error(err)
return
}
row.Scan(&BkimgName)
r.JSON(http.StatusOK, J{"data": BkimgName, "err": nil})
}
示例13: handleAddSched
//handleAddSched URL: /sched/add
func handleAddSched(cookie UserCookie, schedForm Sched, r render.Render, logger *log.Logger, config Config) {
if !cookie.Validate() {
r.JSON(http.StatusOK, J{"data": nil})
return
}
if !schedForm.Validate() {
r.JSON(http.StatusOK, J{"data": nil, "err": J{"code": 101, "msg": "invalid form"}})
return
}
db, err := gorm.Open(config.DB.Type, config.DB.Uri)
if err != nil {
r.JSON(http.StatusInternalServerError, J{"data": nil})
logger.Error(err)
return
}
defer db.Close()
var count int
db.Table("users").Where(&cookie).Count(&count)
if count == 0 {
r.JSON(http.StatusOK, J{"data": nil})
return
}
err = db.Table("scheds").Create(&schedForm).Error
if err != nil {
r.JSON(http.StatusOK, J{"data": nil, "err": J{"code": 300, "msg": err.Error()}})
return
}
r.JSON(http.StatusOK, J{"data": "insert OK"})
}
示例14: handleGetSched
//handleGetSched URL:/sched/all 获取日程表数据
func handleGetSched(r render.Render, logger *log.Logger, config Config, cookie UserCookie) {
if !cookie.Validate() {
logger.Info("Fail to auth whith cookie:", cookie)
r.JSON(http.StatusOK, J{"data": nil})
return
}
//type表示数据库的类型,如mysql,sqlite3等
//uri为需要打开的数据库连接,格式为user:[email protected]/dbname?charset=utf8
//两者都定义在config.ini中
db, err := gorm.Open(config.DB.Type, config.DB.Uri)
if err != nil {
r.JSON(http.StatusInternalServerError, J{"data": nil})
logger.Error(err)
return
}
defer db.Close()
var count int
db.Table("users").Where(&cookie).Count(&count)
if count == 0 {
r.JSON(http.StatusOK, J{"data": nil})
return
}
var sched []Sched
db.Table("scheds").Select("*").Where("user=?", cookie.Name).Find(&sched)
r.JSON(http.StatusOK, J{"data": sched})
logger.Info("Schedule items total", len(sched), "in JSON,", "with cookie:", cookie)
}
示例15: RegisterHandler
//RegisterHandler url: /user/register
func RegisterHandler(w http.ResponseWriter, config Config, form UserRegisterForm, r render.Render, logger *log.Logger) {
if !form.Validate() {
r.JSON(http.StatusOK, J{"data": nil, "err": J{"code": 100, "msg": "invalid name"}})
return
}
priv := util.GetRandomString(10)
p1 := util.Md5(form.Pwd, priv)
SecKey := util.Md5(p1, config.AuthConfig.ConstSalt)
db, err := gorm.Open(config.DB.Type, config.DB.Uri)
if err != nil {
r.JSON(http.StatusInternalServerError, J{"data": nil, "err": J{"code": 201, "msg": "database open error."}})
return
}
defer db.Close()
NewUser := User{
Name: form.Name,
SecKey: SecKey,
Priv: priv,
}
//把新用户插入users表中
err = db.Table("users").Create(&NewUser).Error
if err != nil {
r.JSON(http.StatusInternalServerError, J{"data": nil, "err": J{"code": 202, "msg": "database insert error."}})
logger.Error(err)
return
}
r.JSON(http.StatusOK, J{"data": NewUser.Name, "err": nil})
}