コード例 #1
0
ファイル: manager.go プロジェクト: yamazaki164/csr
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
}
コード例 #2
0
ファイル: gorm.go プロジェクト: arbrix/go-test
//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
}
コード例 #3
0
ファイル: server.go プロジェクト: gitter-badger/abcd
// 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
}
コード例 #4
0
ファイル: test_db.go プロジェクト: caizengjun/qor
// 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:%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)
	}

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

	return db
}
コード例 #5
0
ファイル: model.go プロジェクト: jabaraster/theta
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)()
}
コード例 #6
0
ファイル: data.go プロジェクト: umschlag/umschlag-api
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
}
コード例 #7
0
ファイル: init.go プロジェクト: vodolaz095/gossha
// 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:password@/dbname?charset=utf8&parseTime=True&loc=Local")
// InitDatabase("postgres", "user=gorm dbname=gorm sslmode=disable")
// InitDatabase("postgres", "postgres://*****:*****@localhost/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
}
コード例 #8
0
ファイル: main.go プロジェクト: quorumsco/indexor
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
}
コード例 #9
0
ファイル: server.go プロジェクト: 8legd/hugocms
func ListenAndServe(addr string, auth Auth, dbType DatabaseType) {
	var db *gorm.DB
	var err error

	if dbType == DB_MySQL {
		dbConn := fmt.Sprintf("%s:%s@tcp(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)
}
コード例 #10
0
ファイル: main.go プロジェクト: quorumsco/ES-indexor
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
}
コード例 #11
0
ファイル: main.go プロジェクト: quorumsco/cli
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 :"******"-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
}