Пример #1
1
func init() {
	var err error

	if os.Getenv("DB") == "mysql" {
		if DB, err = gorm.Open("mysql", "qor:qor@/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)
}
Пример #2
0
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:gorm@%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
}
Пример #3
0
// 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
}
Пример #4
0
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:gorm@/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()
}
Пример #5
0
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:%s@localhost/%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:%s@/%s?charset=utf8&parseTime=True&loc=Local", dbuser, dbpwd, dbname))
	}

	if err != nil {
		panic(err)
	}

	return &db
}
Пример #6
0
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
0
func init() {
	var err error

	dbConfig := config.Config.DB
	if config.Config.DB.Adapter == "mysql" {
		DB, err = gorm.Open("mysql", fmt.Sprintf("%v:%v@/%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:%v@localhost/%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)
	}
}
Пример #8
0
func init() {
	var err error
	switch DBType {
	case "mysql":
		DB, err = gorm.Open("mysql", fmt.Sprintf("%s:%s@tcp(%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:%s@%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)
	}
}
Пример #9
0
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)
	}
}
Пример #10
0
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:%v@/%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)
	}
}
Пример #11
0
Файл: db.go Проект: Rompei/qna
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
0
//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})

}
Пример #13
0
//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:password@/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)
}
Пример #14
0
func main() {
	db, err := gorm.Open("mysql", dsn)
	checkErr(err, "Failed to connect database")
	defer db.Close()

	//  レコードの追加
	//  memberだけでなく関係テーブルのレコードも同時に追加している
	members := []Member{
		{Name: "ミク", Birthday: "10/19", BloodType: "AB", Hobbies: []Hobby{{Name: "ブログ"}, {Name: "ショッピング"}}},
		{Name: "マホ", Birthday: "1/8", BloodType: "AB", Hobbies: []Hobby{{Name: "漫画"}, {Name: "ゲーム"}}},
		{Name: "コヒメ", Birthday: "11/24", BloodType: "O", Hobbies: []Hobby{{Name: "ゲーム"}, {Name: "茶道"}}},
	}
	for _, member := range members {
		db.Create(&member)
	}

	fmt.Println("\nすべてのメンバーを取得:\n")
	var allMembers []Member
	db.Find(&allMembers)
	fmt.Println(allMembers)

	fmt.Println("\n\nメンバー1人のみ取得(Hobbiesもあわせて取得):\n")
	var miku Member
	db.Where("name = ?", "ミク").First(&miku)
	db.Model(&miku).Related(&miku.Hobbies)
	fmt.Printf("%#v\n", miku)
}
Пример #15
0
func Setup() {
	var err error
	cfg := config.Read()

	connectionString := cfg.DB.ConnectionString
	if cfg.DB.Type == "sqlite3" {
		connectionString = config.ConfigFile(connectionString)
		log.Println("Using SQLite DB at", connectionString)
	}
	for {
		db, err = gorm.Open(cfg.DB.Type, connectionString)

		if err == nil {
			break
		} else {
			log.Println("Cannot connect to DB. Will try again in 2 seconds:", err)
			time.Sleep(time.Duration(2) * time.Second)
		}
	}

	db.AutoMigrate(
		&User{},
		&CredRecord{},
		&Peer{},
		&SentMessage{},
	)

	db.Model(&CredRecord{}).AddUniqueIndex("idx_cred_hash", "cred_hash")
	db.Model(&CredRecord{}).AddIndex("idx_statement_hash", "statement_hash")
	db.Model(&SentMessage{}).AddUniqueIndex("idx_message_hash", "message_hash")
	db.Model(&User{}).AddUniqueIndex("idx_fingerprint", "fingerprint")
}
Пример #16
0
Файл: initDB.go Проект: WnP/zut
func Initdb() *gorm.DB {
	log := logging.MustGetLogger("log")

	log.Debug("db path: %s", viper.GetString("db.path"))
	log.Debug("db filename: %s", viper.GetString("db.filename"))

	db, err := gorm.Open(
		"sqlite3",
		filepath.Join(
			viper.GetString("db.path"),
			viper.GetString("db.filename"),
		),
	)
	if err != nil {
		log.Critical("Unable to open db file: %s", err)
		os.Exit(1)
	}
	if viper.GetString("logtype") == "debug" {
		db.LogMode(viper.GetBool("debug"))
	}
	db.CreateTable(new(Temperature))
	db.DB().Ping()

	return &db
}
Пример #17
0
func Open(dialect string, addr string, filestoragePath string) (*api.Services, error) {
	conn, err := migration.Open(dialect, addr, migrations.Migrations)
	if err != nil {
		return nil, err
	}
	db, err := gorm.Open(dialect, conn)
	if err != nil {
		return nil, err
	}

	r := &resources{
		DB:              &db,
		Ports:           operator.NewScheduler(16000, 2000),
		FilestoragePath: filestoragePath,
	}
	s := &api.Services{
		Rankings: &rankingsDB{r},
		Games:    &gamesDB{r},
		Matches:  &matchesDB{r},
		Players:  &playersDB{r},
		Users:    &usersDB{r},
		DB:       &db,
	}
	r.Services = s
	return s, nil
}
Пример #18
0
func InitDB() {
	var (
		driver string
		spec   string
		found  bool
	)

	// Read configuration
	if driver, found = revel.Config.String("db.driver"); !found {
		revel.ERROR.Fatal("No db.driver found.")
	}
	if spec, found = revel.Config.String("db.spec"); !found {
		revel.ERROR.Fatal("No db.spec found.")
	}

	maxIdleConns := revel.Config.IntDefault("db.max_idle_conns", 10)
	maxOpenConns := revel.Config.IntDefault("db.max_open_conns", 100)
	singularTable := revel.Config.BoolDefault("db.singular_table", false)
	logMode := revel.Config.BoolDefault("db.log_mode", false)

	// Initialize `gorm`
	dbm, err := gorm.Open(driver, spec)
	if err != nil {
		revel.ERROR.Fatal(err)
	}

	DB = &dbm

	dbm.DB().Ping()
	dbm.DB().SetMaxIdleConns(maxIdleConns)
	dbm.DB().SetMaxOpenConns(maxOpenConns)
	dbm.SingularTable(singularTable)
	dbm.LogMode(logMode)
	dbm.SetLogger(gorm.Logger{revel.INFO})
}
Пример #19
0
//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
}
Пример #20
0
func NewDbConnection(dbFlag string) (*DbConnection, error) {
	if _, exist := Config.Databases[dbFlag]; !exist {
		return nil, fmt.Errorf("dbFlag %s, not exist", dbFlag)
	}

	dbConfig := Config.Databases[dbFlag]

	host := dbConfig.Host
	port := dbConfig.Port
	user := dbConfig.User
	password := dbConfig.Password
	dbName := dbConfig.DbName
	logMode := dbConfig.LogMode

	dbSource := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8", user, password, host, port, dbName)
	dbConn, err := gorm.Open("mysql", dbSource)
	if err != nil {
		return nil, err
	}

	if true == logMode {
		dbConn.LogMode(true)
	} else {
		dbConn.LogMode(false)
	}

	return &DbConnection{
		Conn: dbConn,
	}, nil
}
Пример #21
0
// NewDatabase returns a gorm.DB struct, gorm.DB.DB() returns a database handle
// see http://golang.org/pkg/database/sql/#DB
func NewDatabase(cnf *config.Config) (*gorm.DB, error) {
	// Postgres
	if cnf.Database.Type == "postgres" {
		// Connection args
		// see https://godoc.org/github.com/lib/pq#hdr-Connection_String_Parameters
		args := fmt.Sprintf(
			"sslmode=disable host=%s port=%d user=%s password='******' dbname=%s",
			cnf.Database.Host,
			cnf.Database.Port,
			cnf.Database.User,
			cnf.Database.Password,
			cnf.Database.DatabaseName,
		)

		db, err := gorm.Open(cnf.Database.Type, args)
		if err != nil {
			return &db, err
		}

		return &db, nil
	}

	// Database type not supported
	return &gorm.DB{},
		fmt.Errorf("Database type %s not suppported", cnf.Database.Type)
}
Пример #22
0
func init() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	var err error
	//loc=Local转换本地时间,否则写入mysql的时间是utc时间(当前时间-8小时)
	sqlConnection = "writeuser:writeuser@tcp(192.168.1.116:3306)/TestInsert?charset=utf8&parseTime=True&loc=Local"
	db, err = gorm.Open("mysql", sqlConnection)
	if err != nil {
		panic(err.Error())
		return
	}
	//defer db.Close()

	// Get database connection handle [*sql.DB](http://golang.org/pkg/database/sql/#DB)
	db.DB()

	// Then you could invoke `*sql.DB`'s functions with it
	db.DB().Ping()
	db.DB().SetMaxIdleConns(5)
	db.DB().SetMaxOpenConns(20)

	// Disable table name's pluralization, eg: user-->users
	//db.SingularTable(true)

	// Enable Logger
	db.LogMode(true)
}
Пример #23
0
func initDB() *gorm.DB {

	if os.Getenv("DATABASE_URL") != "" {
		os.Setenv("driver", "postgres")
		os.Setenv("dbsource", os.Getenv("DATABASE_URL"))
		log.Println("Using PostgreSQL")
	} else {
		os.Setenv("driver", "sqlite3")
		os.Setenv("dbsource", "./vertigo.db")
		log.Println("Using SQLite3")
	}

	db, err := gorm.Open(os.Getenv("driver"), os.Getenv("dbsource"))

	if err != nil {
		panic(err)
	}

	db.LogMode(false)

	// Here database and tables are created in case they do not exist yet.
	// If database or tables do exist, nothing will happen to the original ones.
	db.CreateTable(&User{})
	db.CreateTable(&Post{})
	db.AutoMigrate(&User{}, &Post{})

	return &db
}
Пример #24
0
//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})

}
Пример #25
0
//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"})

}
Пример #26
0
func GetDatabase() gorm.DB {
	db, err := gorm.Open("mysql", Config.DatabaseURI)
	if err != nil {
		panic(err)
	}
	return db
}
Пример #27
0
func init() {

	var err error
	var dbString string

	dbConfig := openConfig()

	// Определение типа СУБД
	if dbConfig.DbType == "mysql" {
		dbString = dbConfig.DbName + ":" + dbConfig.DbPass + "@tcp(" + dbConfig.DbHost + ":3306)/" + dbConfig.DbName + "?charset=utf8&parseTime=True"
	} else if dbConfig.DbType == "postgres" {
		dbString = dbConfig.DbType + "://" + dbConfig.DbLogin + ":" + dbConfig.DbPass + "@" + dbConfig.DbHost + "/" + dbConfig.DbName + "?sslmode=disable"
	} else {
		panic("Не удается определить SQL драйвер " + dbConfig.DbType)
	}

	DB, err = gorm.Open(dbConfig.DbType, dbString)
	if err != nil {
		panic(err)
	} else {
		fmt.Println("Соединение с базой данных установленно!\n")
	}
	DB.DB()
	if dbConfig.DbType == "mysql" {
		DB.Set("gorm:table_options", "ENGINE=InnoDB COLLATE=utf8_general_ci")

	}

	DB.Set("gorm:table_options", "ENGINE=InnoDB COLLATE=utf8_general_ci").AutoMigrate(&Workplace{}, &Promocode{}, &PromocodeDiscountType{}, &Company{}, &Document{}, &Card{}, &Discount{})

}
Пример #28
0
func main() {
	flag.Parse()
	m := methodMap[*method]

	db, err := gorm.Open("mysql", "root:@tcp(127.0.0.1:3306)/test?charset=utf8&parseTime=True")
	if err != nil {
		logrus.Fatal("Database open error: ", err)
	}
	if err := db.DB().Ping(); err != nil {
		logrus.Fatal("Database ping error: ", err)
	}
	db.SingularTable(true)
	db.DropTable(&TestTable{})
	panicOnError(db.AutoMigrate(&TestTable{}).Error)

	c := int64(*iterNum * *goNum)
	panicOnError(db.Save(&TestTable{Counter: c}).Error)

	logrus.Infof("Initial counter state: %d", c)
	logrus.Infof("Number of decrements per goroutine: %d", *iterNum)
	logrus.Infof("Number of goroutines: %d", *goNum)
	logrus.Infof("Method: %s", *method)
	logrus.Infof("Method description:\n%s", strings.TrimSpace(methodDoc[*method]))
	done := make(chan bool)
	for i := 0; i < *goNum; i++ {
		go m(&db, *iterNum, done)
	}
	for i := 0; i < *goNum; i++ {
		<-done
	}

	var tt TestTable
	panicOnError(db.First(&tt, 1).Error)
	logrus.Infof("Result: %d", tt.Counter)
}
Пример #29
0
// Connect - Will connect and ping connection in hope that all is ok
func (m *Connection) Connect() error {
	m.Logger.Debug("Connecting to MySQL server (uri: %s) ...", m.URI)

	var err error

	m.DB, err = gorm.Open("mysql", m.URI)
	//m.DB.SetLogger(m.Logger)

	if err != nil {
		m.Logger.Error("Got error while attempting to create mysql connection: %s", err)
		return err
	}

	if err := m.DB.DB().Ping(); err != nil {
		m.Logger.Error("Got error while attempting to PING database: %s", err)
		return err
	}

	concurrency := utils.GetConcurrencyCount("PU_GO_MAX_CONCURRENCY")

	// Setting up max idle conns based on concurrency
	m.DB.DB().SetMaxIdleConns(int(concurrency))
	m.DB.DB().SetMaxOpenConns(int(concurrency))

	return nil
}
Пример #30
0
func init() {
	var err error
	DB, err = gorm.Open("postgres", "user=rebel password=Ohlolk70 dbname=survey port=5433 sslmode=disable")
	if err != nil {
		panic(fmt.Sprintf("Database connection error: ", err))
	}
}