当前位置: 首页>>代码示例>>Golang>>正文


Golang gorm.Open函数代码示例

本文整理汇总了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
}
开发者ID:8legd,项目名称:qor-qor,代码行数:25,代码来源:test_db.go

示例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)
	}
}
开发者ID:qor,项目名称:qor-example,代码行数:26,代码来源:db.go

示例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)
	}
}
开发者ID:robxu9,项目名称:kahinah,代码行数:28,代码来源:default.go

示例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)
}
开发者ID:bozzcq,项目名称:qor-example,代码行数:25,代码来源:db.go

示例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()
}
开发者ID:askagirl,项目名称:requestbin-1,代码行数:33,代码来源:main_test.go

示例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))
	}
}
开发者ID:jakeporter,项目名称:govcode.org,代码行数:26,代码来源:db.go

示例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
}
开发者ID:jseriff,项目名称:gorm,代码行数:31,代码来源:main_test.go

示例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
}
开发者ID:jinjing750629,项目名称:rds-broker,代码行数:36,代码来源:db.go

示例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)
	}
}
开发者ID:trigrass2,项目名称:qor-example,代码行数:25,代码来源:db.go

示例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)
	}
}
开发者ID:jabaraster,项目名称:theta,代码行数:27,代码来源:model.go

示例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
}
开发者ID:Rompei,项目名称:qna,代码行数:9,代码来源:db.go

示例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})

}
开发者ID:Felamande,项目名称:hmserver,代码行数:27,代码来源:servermain.go

示例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"})

}
开发者ID:Felamande,项目名称:hmserver,代码行数:32,代码来源:servermain.go

示例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)
}
开发者ID:Felamande,项目名称:hmserver,代码行数:33,代码来源:servermain.go

示例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})

}
开发者ID:Felamande,项目名称:hmserver,代码行数:33,代码来源:servermain.go


注:本文中的github.com/jinzhu/gorm.Open函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。