本文整理汇总了Golang中github.com/jinzhu/gorm.DB.DB方法的典型用法代码示例。如果您正苦于以下问题:Golang DB.DB方法的具体用法?Golang DB.DB怎么用?Golang DB.DB使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/jinzhu/gorm.DB
的用法示例。
在下文中一共展示了DB.DB方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: createDatabaseConn
// createDatabaseConn creates a new GORM database with the specified database
// configuration.
func (s *Server) createDatabaseConn() (*gorm.DB, error) {
var (
db gorm.DB
err error
dbCfg = s.cfg.Db
connectionString = fmt.Sprintf(
"host=%v port=%v user=%v password=%v dbname=%v sslmode=disable",
dbCfg.Host,
dbCfg.Port,
dbCfg.User,
dbCfg.Password,
dbCfg.Name,
)
)
db, err = gorm.Open("postgres", connectionString)
if err != nil {
return nil, err
}
db.DB().SetMaxIdleConns(10)
db.LogMode(s.cfg.DbLogMode)
return &db, nil
}
示例2: 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
}
示例3: InitGORM
func InitGORM(dialect, args string) (*gorm.DB, error) {
var db gorm.DB
var err error
var i int
retry:
for {
db, err = gorm.Open(dialect, args)
switch {
case err == nil:
break retry
case i >= RETRY:
return nil, err
default:
logs.Error(err)
i++
}
time.Sleep(TIMEOUT)
}
if db.DB().Ping() != nil {
return &db, err
}
return &db, nil
}
示例4: prepareDatabase
func prepareDatabase(driver string, db *gorm.DB) error {
if driver == "mysql" {
db.DB().SetMaxIdleConns(0)
}
validations.RegisterCallbacks(
db,
)
return nil
}
示例5: loadData
func loadData(paths []string, cnf *config.Config, db *gorm.DB) {
for _, path := range paths {
data, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal(err)
}
if err := fixtures.Load(data, db.DB(), cnf.Database.Type); err != nil {
log.Fatal(err)
}
}
}
示例6: pingDatabase
func pingDatabase(driver string, db *gorm.DB) error {
for i := 0; i < 30; i++ {
err := db.DB().Ping()
if err == nil {
return nil
}
logrus.Infof("Database ping failed, retry in 1s")
time.Sleep(time.Second)
}
return fmt.Errorf("Database ping attempts failed")
}
示例7: LoadData
// LoadData loads fixtures
func LoadData(paths []string, cnf *config.Config, db *gorm.DB) error {
for _, path := range paths {
data, err := ioutil.ReadFile(path)
if err != nil {
return err
}
if err := fixtures.Load(data, db.DB(), cnf.Database.Type); err != nil {
return err
}
}
return nil
}
示例8: opendb
// 建立数据库连接
func opendb(dbname, dbuser, dbpass string) (*gorm.DB, error) {
var (
dbtype, dsn string
db gorm.DB
err error
)
if dbuser == "" {
dbuser = config.GetStringDefault("dbuser", "root")
}
if dbpass == "" {
dbpass = config.GetStringDefault("dbpass", "root")
}
dbtype = strings.ToLower(config.GetStringDefault("dbtype", "mysql"))
if dbtype == "mysql" {
dsn = fmt.Sprintf("%s:%[email protected]%s(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
dbuser,
dbpass,
config.GetStringDefault("dbproto", "tcp"),
config.GetStringDefault("dbhost", "localhost"),
config.GetIntDefault("dbport", 3306),
dbname,
)
} else if dbtype == "pg" || dbtype == "postgres" || dbtype == "postgresql" {
dbtype = "postgres"
dsn = fmt.Sprintf("user=%s password=%s host=%s port=%d dbname=%s sslmode=disable",
dbuser,
dbpass,
config.GetStringDefault("dbhost", "127.0.0.1"),
config.GetIntDefault("dbport", 5432),
dbname)
}
db, err = gorm.Open(dbtype, dsn)
if err != nil {
log.Println(err.Error())
return &db, err
}
err = db.DB().Ping()
if err != nil {
log.Println(err.Error())
return &db, err
}
return &db, nil
}
示例9: Connect
//Connect init gorm ORM.
func (orm *AppOrm) Connect(conf interfaces.Config) error {
var db gorm.DB
dbUri, err := conf.Get("DatabaseUri")
if dbUri, ok := dbUri.(string); err == nil && ok {
log.Println(dbUri)
db, err = gorm.Open("mysql", dbUri)
}
if err != nil {
log.Fatal(err.Error())
return err
}
db.DB()
db.DB().Ping()
db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
// Disable table name's pluralization
db.SingularTable(true)
if env, err := conf.Get("env"); err == nil && env == "dev" {
db.LogMode(true)
}
orm.driver = &db
return nil
}
示例10: initDb
func initDb(db gorm.DB) {
defer fmt.Printf("Init DB DONE! \n")
db.DB().Ping()
db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
db.CreateTable(&Erp{})
db.CreateTable(&Entry{})
db.CreateTable(&SyncField{})
db.Model(&Entry{}).Related(&SyncField{}, "EntryId")
db.CreateTable(&Decorator{})
db.Model(&SyncField{}).Related(&Decorator{}, "DecoratorId")
db.CreateTable(&SyncEvent{})
}
示例11: ExtractDBSQL
//ExtractDBSQL ---
func ExtractDBSQL() (gormdb chaospeddler.GormDB) {
var err error
var db *gorm.DB
appEnv, _ := cfenv.Current()
service, _ := appEnv.Services.WithName("sql-info")
host := fmt.Sprintf("%v", service.Credentials["hostname"])
port := fmt.Sprintf("%v", service.Credentials["port"])
dbname := fmt.Sprintf("%v", service.Credentials["name"])
user := fmt.Sprintf("%v", service.Credentials["username"])
pass := fmt.Sprintf("%v", service.Credentials["password"])
connectionString := user + ":" + pass + "@tcp(" + host + ":" + port + ")" + "/" + dbname + "?charset=utf8&parseTime=True&loc=Local"
lo.G.Error("connection string: ", connectionString)
if db, err = gorm.Open("mysql", connectionString); err == nil {
db.DB()
db.DB().Ping()
db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
db.SingularTable(true)
db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(
new(chaospeddler.ServiceInstance),
new(chaospeddler.ServiceBinding),
)
gormdb = db
} else {
lo.G.Error("there was an error connecting to mysql: ", err)
panic(err)
}
return
}
示例12: InitDatabase
// InitDatabase initialize new database connection
// the first argument is a driver to use, the second one - connection parameters
// Examples:
// InitDatabase("sqlite3","/var/lib/gossha/gossha.db")
// InitDatabase("sqlite3",":memory:")
// InitDatabase("mysql", "user:[email protected]/dbname?charset=utf8&parseTime=True&loc=Local")
// InitDatabase("postgres", "user=gorm dbname=gorm sslmode=disable")
// InitDatabase("postgres", "postgres://pqgotest:[email protected]/pqgotest?sslmode=verify-full")
func InitDatabase(driver, dbPath string, verboseLogging bool) error {
var db *gorm.DB
db, err := gorm.Open(driver, dbPath)
db.LogMode(verboseLogging)
err = db.DB().Ping()
if err != nil {
return err
}
db.DB().SetMaxIdleConns(5)
db.DB().SetMaxOpenConns(5)
// Disable table name's pluralization
db.SingularTable(true)
err = db.AutoMigrate(&User{}, &Message{}, &Key{}, &Session{}).Error
if err != nil {
return err
}
err = db.Model(&User{}).AddUniqueIndex("idx_contact_name", "name").Error
if err != nil {
return err
}
err = db.Model(&Message{}).AddIndex("idx_message", "user_id", "created_at").Error
if err != nil {
return err
}
err = db.Model(&Key{}).AddIndex("idx_key", "user_id", "created_at").Error
if err != nil {
return err
}
err = db.Model(&Key{}).AddUniqueIndex("idx_key_content", "content", "user_id", "created_at").Error
if err != nil {
return err
}
err = db.Model(&Session{}).AddIndex("idx_session", "user_id", "created_at").Error
if err != nil {
return err
}
DB = db
return nil
}
示例13: NewDb
func NewDb(Cnf DbConfig) *Db {
var err error
var db *gorm.DB
switch Cnf.DriverName {
case "sqlite3":
db, err = gorm.Open("sqlite3", Cnf.DataSourceName)
logger.CheckFatal(err, "Got error when connect database")
//this.DbMap = &gorp.DbMap{Db: db, Dialect: gorp.SqliteDialect{}}
case "mysql":
//db, err := sql.Open("mysql", "user:[email protected](localhost:5555)/dbname?charset=utf8&parseTime=True&loc=Local")
db, err = gorm.Open("mysql", fmt.Sprintf("%s:%[email protected](%s)/%s?charset=%s&parseTime=True&loc=Local",
Cnf.UserName,
Cnf.Password,
Cnf.Host,
Cnf.DataSourceName,
Cnf.Encoding))
logger.CheckFatal(err, "Got error when connect database")
//this.DbMap = &gorp.DbMap{Db: db, Dialect: gorp.MySQLDialect{"InnoDB", "UTF8"}}
default:
logger.Fatal("The types of database does not support:"+Cnf.DriverName, err)
}
db.DB()
db.DB().Ping()
db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
// Disable table name's pluralization
db.SingularTable(true)
// construct a gorp DbMap
//
return &Db{Cnf: Cnf, db: db}
}
示例14:
&models.PatternPart{},
&models.Workflow{},
).Error; err != nil {
l.Fatal("Could not automigrate.", err)
return
}
path := filepath.Join(os.Getenv("GOPATH"), "/src/github.com/Bnei-Baruch/mms-file-manager/migrations")
/*
dbConf := goose.DBConf{
MigrationsDir: path,
Driver: goose.DBDriver{
Name: "postgres",
DSN: os.Getenv("DATABASE_URL"),
Dialect: goose.PostgresDialect{},
Import: "github.com/lib/pq",
},
}
*/
var target int64
target, err = goose.GetMostRecentDBVersion(path)
if err != nil {
l.Fatal(err)
}
if err = goose.RunMigrations(db.DB(), path, target); err != nil {
l.Fatal(err)
}
},
}
示例15: main
func main() {
// --------------------------------------------------------------------
// Parse flags
// --------------------------------------------------------------------
var configFilePath string
var printConfig bool
var migrateDB bool
var scheduler *remoteworkitem.Scheduler
flag.StringVar(&configFilePath, "config", "", "Path to the config file to read")
flag.BoolVar(&printConfig, "printConfig", false, "Prints the config (including merged environment variables) and exits")
flag.BoolVar(&migrateDB, "migrateDatabase", false, "Migrates the database to the newest version and exits.")
flag.Parse()
// Override default -config switch with environment variable only if -config switch was
// not explicitly given via the command line.
configSwitchIsSet := false
flag.Visit(func(f *flag.Flag) {
if f.Name == "config" {
configSwitchIsSet = true
}
})
if !configSwitchIsSet {
if envConfigPath, ok := os.LookupEnv("ALMIGHTY_CONFIG_FILE_PATH"); ok {
configFilePath = envConfigPath
}
}
var err error
if err = configuration.Setup(configFilePath); err != nil {
logrus.Panic(nil, map[string]interface{}{
"configFilePath": configFilePath,
"err": err,
}, "failed to setup the configuration")
}
if printConfig {
os.Exit(0)
}
// Initialized developer mode flag for the logger
log.InitializeLogger(configuration.IsPostgresDeveloperModeEnabled())
printUserInfo()
var db *gorm.DB
for {
db, err = gorm.Open("postgres", configuration.GetPostgresConfigString())
if err != nil {
db.Close()
log.Logger().Errorf("ERROR: Unable to open connection to database %v\n", err)
log.Logger().Infof("Retrying to connect in %v...\n", configuration.GetPostgresConnectionRetrySleep())
time.Sleep(configuration.GetPostgresConnectionRetrySleep())
} else {
defer db.Close()
break
}
}
if configuration.IsPostgresDeveloperModeEnabled() {
db = db.Debug()
}
// Migrate the schema
err = migration.Migrate(db.DB())
if err != nil {
log.Panic(nil, map[string]interface{}{
"err": fmt.Sprintf("%+v", err),
}, "failed migration")
}
// Nothing to here except exit, since the migration is already performed.
if migrateDB {
os.Exit(0)
}
// Make sure the database is populated with the correct types (e.g. bug etc.)
if configuration.GetPopulateCommonTypes() {
// set a random request ID for the context
ctx, req_id := client.ContextWithRequestID(context.Background())
log.Debug(ctx, nil, "Initializing the population of the database... Request ID: %v", req_id)
if err := models.Transactional(db, func(tx *gorm.DB) error {
return migration.PopulateCommonTypes(ctx, tx, workitem.NewWorkItemTypeRepository(tx))
}); err != nil {
log.Panic(ctx, map[string]interface{}{
"err": fmt.Sprintf("%+v", err),
}, "failed to populate common types")
}
if err := models.Transactional(db, func(tx *gorm.DB) error {
return migration.BootstrapWorkItemLinking(ctx, link.NewWorkItemLinkCategoryRepository(tx), link.NewWorkItemLinkTypeRepository(tx))
}); err != nil {
log.Panic(ctx, map[string]interface{}{
"err": fmt.Sprintf("%+v", err),
}, "failed to bootstap work item linking")
}
}
// Scheduler to fetch and import remote tracker items
scheduler = remoteworkitem.NewScheduler(db)
defer scheduler.Stop()
//.........这里部分代码省略.........