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


Golang DB.LogMode方法代码示例

本文整理汇总了Golang中github.com/jinzhu/gorm.DB.LogMode方法的典型用法代码示例。如果您正苦于以下问题:Golang DB.LogMode方法的具体用法?Golang DB.LogMode怎么用?Golang DB.LogMode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在github.com/jinzhu/gorm.DB的用法示例。


在下文中一共展示了DB.LogMode方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: NewManager

func NewManager() *Manager {
	var found bool
	var driver string
	if driver, found = revel.Config.String("db.driver"); !found {
		revel.ERROR.Fatal("db driver not found")
	}

	var spec string
	if spec, found = revel.Config.String("db.spec"); !found {
		revel.ERROR.Fatal("db spec not found.")
	}

	if driver == "sqlite3" {
		spec = path.Join(revel.AppPath, spec)
	}

	var err error
	var db *gorm.DB
	db, err = gorm.Open(driver, spec)
	if err != nil {
		revel.ERROR.Fatal(err)
	}

	db.LogMode(revel.Config.BoolDefault("db.debug", false))

	m := &Manager{
		DB: db,
	}

	return m
}
开发者ID:yamazaki164,项目名称:csr,代码行数:31,代码来源:manager.go

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

示例3: 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
}
开发者ID:gitter-badger,项目名称:abcd,代码行数:27,代码来源:server.go

示例4: TestDB

// TestDB initialize a db for testing
func TestDB() *gorm.DB {
	var db *gorm.DB
	var err error
	var dbuser, dbpwd, dbname = "qor", "qor", "qor_test"

	if os.Getenv("DB_USER") != "" {
		dbuser = os.Getenv("DB_USER")
	}

	if os.Getenv("DB_PWD") != "" {
		dbpwd = os.Getenv("DB_PWD")
	}

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

	if os.Getenv("DEBUG") != "" {
		db.LogMode(true)
	}

	return db
}
开发者ID:caizengjun,项目名称:qor,代码行数:33,代码来源:test_db.go

示例5: initializeDatabase

func initializeDatabase(db *gorm.DB) {
	db.SingularTable(true) // 自動生成されるテーブル名を単数形にする.

	db.CreateTable(&Property{})
	db.CreateTable(&Room{})
	//    db.AutoMigrate(&Family{}, &FamilyCredential{}) // 使いこなせないので当面自動マイグレーションはoff.

	db.LogMode(true)
	defer beginTx(db)()
}
开发者ID:jabaraster,项目名称:theta,代码行数:10,代码来源:model.go

示例6: setupDatabase

func setupDatabase(driver string, db *gorm.DB) *gorm.DB {
	if config.Debug {
		db.LogMode(true)
		db.SetLogger(gormrus.New())
	}

	if err := prepareDatabase(driver, db); err != nil {
		logrus.Fatalln(err)
	}

	if err := pingDatabase(driver, db); err != nil {
		logrus.Fatalln(err)
	}

	if err := migrateDatabase(driver, db); err != nil {
		logrus.Fatalln(err)
	}

	return db
}
开发者ID:umschlag,项目名称:umschlag-api,代码行数:20,代码来源:data.go

示例7: 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
}
开发者ID:vodolaz095,项目名称:gossha,代码行数:47,代码来源:init.go

示例8: script

func script(ctx *cli.Context) error {
	var err error
	var config settings.Config
	if ctx.String("config") != "" {
		config, err = settings.Parse(ctx.String("config"))
		if err != nil {
			logs.Error(err)
		}
	}

	logs.Level(logs.DebugLevel)

	dialect, args, err := config.SqlDB()
	if err != nil {
		logs.Critical(err)
		os.Exit(1)
	}
	logs.Debug("database type: %s", dialect)

	var db *gorm.DB
	if db, err = databases.InitGORM(dialect, args); err != nil {
		logs.Critical(err)
		os.Exit(1)
	}
	logs.Debug("connected to %s", args)

	if config.Migrate() {
		db.AutoMigrate(models.Models()...)
		logs.Debug("database migrated successfully")
	}

	db.LogMode(true)

	ElasticSettings, err := config.Elasticsearch()
	var client *elastic.Client
	client, err = dialElasticRetry(ElasticSettings.String())
	if err != nil {
		logs.Critical(err)
		os.Exit(1)
	}

	// Use the IndexExists service to check if a specified index exists.
	exists, err := client.IndexExists("contacts").Do()
	if err != nil {
		logs.Critical(err)
		os.Exit(1)
	}
	if !exists {
		logs.Critical("No contacts index")
		os.Exit(1)
	}

	ID := config.Int("id")
	if ID == -1 {
		logs.Debug("Looking for ID")
		ID, err = findID(client)
		if err != nil {
			logs.Debug(err)
			os.Exit(1)
		}
	}
	logs.Debug("Last ID is : %d", ID)

	contacts, err := findContacts(ID, db)

	doContacts := config.Bool("contacts")
	doFacts := config.Bool("facts")
	if doContacts == false && doFacts == false {
		logs.Debug("Nothing to be done, please activate some options")
		os.Exit(1)
	}

	for _, contact := range contacts {
		id := contact.ID
		if id != 0 {
			contact, err := addAddresses(contact, db)
			if err == nil {
				if contact != nil {
					if doContacts {
						logs.Debug("Indexing contact %d : %s %s", id, contact.Surname, contact.Firstname)
						err = index(contact, client)
						if err != nil {
							logs.Critical(err)
						}
					}
					if doFacts {
						logs.Debug("Creating and indexing fact for contact %d : %s %s", id, contact.Surname, contact.Firstname)
						err = createFact(contact, client, db)
						if err != nil {
							logs.Critical(err)
						}
					}
				} else {
					logs.Debug("Could not index contact %d", id)
				}
			}
		}
	}

	return nil
//.........这里部分代码省略.........
开发者ID:quorumsco,项目名称:indexor,代码行数:101,代码来源:main.go

示例9: ListenAndServe

func ListenAndServe(addr string, auth Auth, dbType DatabaseType) {
	var db *gorm.DB
	var err error

	if dbType == DB_MySQL {
		dbConn := fmt.Sprintf("%s:%[email protected](127.0.0.1:3306)", auth.UserName, auth.Password)
		db, err = gorm.Open("mysql", dbConn+"/hugocms_"+auth.UserName+"?charset=utf8&parseTime=True&loc=Local")
	} else {
		db, err = gorm.Open("sqlite3", "hugocms_"+auth.UserName+".db")
	}

	if err != nil {
		handleError(err)
	}
	db.LogMode(true)

	// to reset to an empty database drop the settings table
	if !db.HasTable(&models.Settings{}) {
		for _, table := range hugocms_qor.Tables {
			if err := db.DropTableIfExists(table).Error; err != nil {
				handleError(err)
			}
		}
	}

	for _, table := range hugocms_qor.Tables {
		if err := db.AutoMigrate(table).Error; err != nil {
			handleError(err)
		}
	}

	// Because this is a singleton a single record must already exist in the database (there is no create through QOR admin just update)
	db.FirstOrCreate(&models.Settings{})

	siteName := fmt.Sprintf("%s - Hugo CMS", auth.UserName)
	if err := setupConfig(addr, siteName, db, auth); err != nil {
		handleError(err)
	}

	// Add session support - used by Auth
	sessionLifetime := 3600 // session lifetime in seconds
	SessionManager, err = session.NewManager("memory", fmt.Sprintf(`{"cookieName":"gosessionid","gclifetime":%d}`, sessionLifetime))
	if err != nil {
		handleError(err)
	}
	go SessionManager.GC()

	// Create Hugo's content directory if it doesnt exist
	// TODO read content dir from config
	if _, err := os.Stat("./content"); os.IsNotExist(err) {
		err = os.MkdirAll("./content", os.ModePerm)
	}

	mux := http.NewServeMux()

	mux.Handle("/", http.FileServer(http.Dir("public")))

	adm := hugocms_qor.SetupAdmin()

	adm.MountTo("/admin", mux)
	adm.GetRouter().Post("/auth", func(ctx *admin.Context) {
		// we will only hit this on succesful login - redirect to admin dashboard
		w := ctx.Writer
		r := ctx.Request
		http.Redirect(w, r, "/admin", http.StatusFound)
	})
	adm.GetRouter().Get("/logout", func(ctx *admin.Context) {
		w := ctx.Writer
		r := ctx.Request
		sess, err := SessionManager.SessionStart(w, r)
		if err != nil {
			handleError(err)
		}
		defer sess.SessionRelease(w)
		sess.Delete("User")
		http.Redirect(w, r, "/login", http.StatusFound)
	})

	// NOTE: `system` is where QOR admin will upload files e.g. images - we map this to Hugo's static dir along with our other static assets
	// TODO read static dir from config
	// TODO read static assets list from config
	for _, path := range []string{"system", "css", "fonts", "images", "js", "login"} {
		mux.Handle(fmt.Sprintf("/%s/", path), http.FileServer(http.Dir("static")))
	}

	if err := http.ListenAndServe(config.QOR.Addr, mux); err != nil {
		handleError(err)
	}

	// to re-generate site delete `config.json`
	if _, err := os.Stat("config.json"); os.IsNotExist(err) {
		hugocms_qor.CallSave(adm)
	}

	fmt.Printf("Listening on: %s\n", config.QOR.Addr)
}
开发者ID:8legd,项目名称:hugocms,代码行数:96,代码来源:server.go

示例10: script

func script(ctx *cli.Context) error {
	var err error
	var config settings.Config
	if ctx.String("config") != "" {
		config, err = settings.Parse(ctx.String("config"))
		if err != nil {
			logs.Error(err)
		}
	}

	logs.Level(logs.DebugLevel)

	dialect, args, err := config.SqlDB()
	if err != nil {
		logs.Critical(err)
		os.Exit(1)
	}
	logs.Debug("database type: %s", dialect)

	var db *gorm.DB
	if db, err = databases.InitGORM(dialect, args); err != nil {
		logs.Critical(err)
		os.Exit(1)
	}
	logs.Debug("connected to %s", args)

	if config.Migrate() {
		db.AutoMigrate(models.Models()...)
		logs.Debug("database migrated successfully")
	}

	db.LogMode(true)

	ElasticSettings, err := config.Elasticsearch()
	var client *elastic.Client
	client, err = dialElasticRetry(ElasticSettings.String())
	if err != nil {
		logs.Critical(err)
		os.Exit(1)
	}

	// Use the IndexExists service to check if a specified index exists.
	exists, err := client.IndexExists("contacts").Do()
	if err != nil {
		logs.Critical(err)
		os.Exit(1)
	}
	if !exists {
		logs.Critical("No contacts index")
		os.Exit(1)
	}

	ID, err := findID(client)
	if err != nil {
		logs.Debug(err)
		os.Exit(1)
	}
	logs.Debug("Last ID is : %d", ID)

	contacts, err := findContacts(ID, db)

	for _, contact := range contacts {
		contact, err := addAddresses(contact, db)
		if err != nil {
			logs.Critical(err)
			os.Exit(1)
		}
		logs.Debug("Indexing contact %d : %s %s", contact.ID, contact.Surname, contact.Firstname)
		err = index(contact, client)
		if err != nil {
			logs.Critical(err)
			os.Exit(1)
		}
	}

	return nil
}
开发者ID:quorumsco,项目名称:ES-indexor,代码行数:77,代码来源:main.go

示例11: add

func add(ctx *cli.Context) error {
	var err error
	var config settings.Config
	if ctx.String("config") != "" {
		config, err = settings.Parse(ctx.String("config"))
		if err != nil {
			logs.Error(err)
		}
	}

	var mail = ctx.String("mail")
	var password = ctx.String("password")
	var firstname = ctx.String("firstname")
	var surname = ctx.String("surname")
	var groupID = ctx.String("group")

	if mail == "" || password == "" || firstname == "" || surname == "" {
		logs.Error("All arguments are required")
		return errors.New("all arguments are required")
	}

	passwordHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		panic(err)
	}

	var convGroupID = 0
	if groupID != "" {
		convGroupID, err = strconv.Atoi(groupID)
		if err != nil {
			logs.Error(err)
			return err
		}
	}

	u := &models.User{
		Mail:      sPtr(mail),
		Password:  sPtr(string(passwordHash)),
		Firstname: sPtr(firstname),
		Surname:   sPtr(surname),
		GroupID:   uint(convGroupID),
	}
	errs := u.Validate()

	logs.Level(logs.DebugLevel)

	if len(errs) > 0 {
		logs.Error(errs)
		return errors.New("Informations are not valid")
	}

	dialect, args, err := config.SqlDB()
	if err != nil {
		logs.Critical(err)
		os.Exit(1)
	}
	logs.Debug("database type: %s", dialect)

	var db *gorm.DB
	if db, err = databases.InitGORM(dialect, args); err != nil {
		logs.Critical(err)
		os.Exit(1)
	}
	logs.Debug("connected to %s", args)

	if config.Migrate() {
		db.AutoMigrate(models.Models()...)
		logs.Debug("database migrated successfully")
	}

	db.LogMode(true)

	var store = models.UserStore(db)
	err = store.Save(u)
	if err != nil {
		logs.Error(err)
		return err
	}

	logs.Debug("New user :")
	logs.Debug("-Mail : %s", mail)
	logs.Debug("-Password : %s", password)
	logs.Debug("-Firstname : %s", firstname)
	logs.Debug("-Surname : %s", surname)
	logs.Debug("-GroupID : %d", convGroupID)
	return nil
}
开发者ID:quorumsco,项目名称:cli,代码行数:87,代码来源:main.go


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