Esempio n. 1
0
File: db.go Progetto: jhbsz/cloud
func SetupDB(t *testing.T) *sqlx.DB {
	// open the db
	db, err := sqlx.Open("postgres", dbURL)
	if err != nil {
		t.Fatal(err)
	}

	// run pending migrations
	// assumes path for migrations is data/migrations
	t.Log("Starting database migrations...")
	pwd, _ := os.Getwd()
	errs, ok := migrate.UpSync(dbURL, filepath.Join(pwd, "/../data/migrations"))
	if !ok {
		for _, err := range errs {
			t.Error(err)
			t.Fatal("SetupDB: migrations failed")
		}
	}
	t.Log("Completed database migrations")

	// truncate tables
	t.Log("Truncating tables...")
	tables := []string{}
	q := "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_name <> 'schema_migrations';"
	if err := db.Select(&tables, q); err != nil {
		t.Fatal(err)
	}
	if _, err := db.Exec(fmt.Sprintf("TRUNCATE %s RESTART IDENTITY;", strings.Join(tables, ", "))); err != nil {
		t.Fatal(err)
	}
	t.Log("Completed truncating tables")

	return db
}
Esempio n. 2
0
func Migrate(dbConfPath string, migrationPath string, test bool) (errors []error) {
	connString, err := loadConnectionString(dbConfPath, test)
	if err != nil {
		return append(errors, err)
	}
	url := fmt.Sprintf("mysql://%s", connString)
	errors, _ = migrate.UpSync(url, migrationPath)
	return
}
Esempio n. 3
0
func applyMigrations() {
	allErrors, ok := migrate.UpSync(viper.GetString("database_url"), "./migrations")
	fmt.Println("Database: ", viper.GetString("database_url"))
	if !ok {
		fmt.Println("Migratinos failed")
		fmt.Println("driver: ", viper.GetString("database_url"))
		fmt.Println("Errors: ", allErrors)
	}
}
Esempio n. 4
0
func tgmigrate(c *cli.Context) {
	allErrors, ok := migrate.UpSync(c.String("pgconn"), "./db")
	if !ok {
		println("tgmigrate errors:")
		for _, err := range allErrors {
			println("\t" + err.Error())
		}
		os.Exit(DBMIGRATION_ERROR)
	}
}
func (s *postgres) migrate() error {
	glog.V(2).Infof("database migration started. dir: %s", s.mirgrationPath)
	dbinfo := s.createDbUrl()
	allErrors, ok := migrate.UpSync(dbinfo, s.mirgrationPath)
	if !ok || len(allErrors) > 0 {
		return fmt.Errorf("migrate failed: %v", allErrors)
	}
	glog.V(2).Infof("migrated database completed")
	return nil
}
Esempio n. 6
0
func Patch() {
	errors, ok := migrate.UpSync("sqlite3://"+option.String("dbpath"), "migrations")

	if !ok {
		for _, err := range errors {
			logrus.WithFields(logrus.Fields{
				"Path": option.String("dbpath"),
			}).Error(err.Error())
		}
	}
}
Esempio n. 7
0
func migrateUp() {
	absPath := getAbsPath()
	allErrors, ok := migrate.UpSync("mysql://"+config.MysqlDSL(), absPath)
	if !ok {
		for _, error := range allErrors {
			s := error.Error()
			fmt.Printf("Error! type: %T; value: %q\n", s, s)
		}
		// do sth with allErrors slice
	}

}
Esempio n. 8
0
func RunMigrations() {
	migrationsDir := os.Getenv("ET_MIGRATIONS")
	if migrationsDir == "" {
		migrationsDir = "./migrations"
	}

	allErrors, ok := migrate.UpSync(migrateUrl, migrationsDir)
	if !ok {
		for _, err := range allErrors {
			fmt.Println(err)
		}
	}
}
Esempio n. 9
0
func migrateDB() {
	fmt.Println("TBBR-API - Running Migrations located in: " + os.Getenv("TBBR_MIGRATIONS_DIR"))

	allErrors, ok := migrate.UpSync(getDBUrl(), os.Getenv("TBBR_MIGRATIONS_DIR"))
	if !ok {
		fmt.Println("TBBR-API Migrations failed!")
		fmt.Println(allErrors)
		fmt.Println("TBBR-API exiting...")
		os.Exit(1)
	}

	fmt.Println("TBBR-API - Migrations Finished!")
}
Esempio n. 10
0
// Make sure the database at the URL is up to date with respect to
// migrations, or return an error. The migration scripts are taken
// from `basedir/{scheme}`, with the scheme coming from the URL.
func Migrate(dburl, basedir string) (uint64, error) {
	u, err := url.Parse(dburl)
	if err != nil {
		return 0, errors.Wrap(err, "parsing database URL")
	}
	migrationsPath := filepath.Join(basedir, DriverForScheme(u.Scheme))
	if _, err := os.Stat(migrationsPath); err != nil {
		if os.IsNotExist(err) {
			return 0, errors.Wrapf(err, "migrations dir %s does not exist; driver %s not supported", migrationsPath, u.Scheme)
		}
		return 0, errors.Wrapf(err, "verifying migrations directory %s exists", migrationsPath)
	}

	errs, _ := migrate.UpSync(dburl, migrationsPath)
	if len(errs) > 0 {
		return 0, errors.Wrap(compositeError{errs}, "migrating database")
	}
	version, err := migrate.Version(dburl, migrationsPath)
	if err != nil {
		return 0, err
	}
	return version, nil
}
Esempio n. 11
0
// Migrate runs the migrations.
func Migrate(db, path string) ([]error, bool) {
	return migrate.UpSync(db, path)
}
Esempio n. 12
0
// MigrateUp migrates the database to the latest version of the schema.
func (db *DB) MigrateUp(path string) ([]error, bool) {
	return migrate.UpSync(db.uri, path)
}
Esempio n. 13
0
func (ds *DB) UpSync(migrationsPath string) ([]error, bool) {
	return migrate.UpSync(ds.driver+"://"+ds.dsn, filepath.Join(migrationsPath, ds.driver))
}
Esempio n. 14
0
func main() {
	logrus.Println("running migrations")
	allErrors, ok := migrate.UpSync(dbAddr, "./migrations")
	if !ok {
		logrus.Println("Oh no ...")
		logrus.Fatal(allErrors)
		// do sth with allErrors slice
	}

	// Echo instance
	e := echo.New()
	e.Use(mw.LoggerWithConfig(mw.LoggerConfig{
		Format: "method=${method}, uri=${uri}, status=${status}\n",
	}))
	e.Use(mw.Recover())
	e.Use(mw.CORS())

	s := store.Connect(dbAddr)
	s.EnsureAdmin()
	e.Use(h.SetDB(s))

	// catch sql no rows errors and return as a 404
	// e.Use(func(h echo.HandlerFunc) echo.HandlerFunc {
	// 	return func(c echo.Context) error {
	// 		err := h(c)
	// 		if err == store.ErrNoRows {
	// 			return echo.NewHTTPError(http.StatusNotFound)
	// 		}
	// 		return err
	// 	}
	// })

	// e.Post("/session", h.CreateSession(signingkey, signingmethod))
	e.Post("/activate/:token", h.ActivateAccount)
	e.Get("/setup", h.CanSetup)
	e.Post("/setup", h.SetupApp)

	decoded, err := base64.URLEncoding.DecodeString(signingkey)
	if err != nil {
		panic(err)
	}

	auth := e.Group("")
	auth.Use(mw.JWT(decoded))
	auth.Get("/me", h.GetSession)
	// Accounts
	auth.Get("/account", h.GetAllAccounts)
	auth.Post("/account", h.CreateAccount)
	auth.Delete("/account/:id", h.DeleteAccount)

	// People
	g := auth.Group("/person")
	g.GET("", h.GetAllPeople)
	g.POST("", h.CreatePerson)
	g.GET("/:id", h.GetPerson)
	g.PUT("/:id", h.UpdatePerson)
	g.DELETE("/:id", h.DeletePerson)

	// Courses
	g = auth.Group("/course")
	g.GET("", h.GetAllCourses)
	g.POST("", h.CreateCourse)
	g.GET("/:id", h.GetCourse)
	g.PUT("/:id", h.UpdateCourse)
	g.PUT("/:courseID/term/:termID", h.CreateCourseTerm)
	g.DELETE("/:id", h.DeleteCourse)
	g.GET("/:courseID/term/:termID/assignments", h.GetCourseAssignments)
	g.GET("/:courseID/term/:termID/gradebook", h.GetGradebook)

	// Attempt
	g = auth.Group("/attempt")
	g.GET("", h.GetAllAttempts)
	g.POST("", h.CreateAttempt)
	g.GET("/:id", h.GetAttempt)
	g.PUT("/:id", h.UpdateAttempt)
	g.DELETE("/:id", h.DeleteAttempt)

	// Announcement
	g = auth.Group("/announcement")
	g.GET("", h.GetAllAnnouncements)
	g.POST("", h.CreateAnnouncement)
	g.GET("/:id", h.GetAnnouncement)
	g.PUT("/:id", h.UpdateAnnouncement)
	g.DELETE("/:id", h.DeleteAnnouncement)

	// Enrollments
	g = auth.Group("/enrollment")
	g.GET("", h.GetAllEnrollments)
	g.POST("", h.CreateEnrollment)
	g.GET("/:id", h.GetEnrollment)
	g.PUT("/:id", h.UpdateEnrollment)
	g.DELETE("/:id", h.DeleteEnrollment)

	// Terms
	g = auth.Group("/term")
	g.GET("", h.GetAllTerms)
	g.POST("", h.CreateTerm)
	g.GET("/:id", h.GetTerm)
	g.PUT("/:id", h.UpdateTerm)
	g.DELETE("/:id", h.DeleteTerm)

	// Levels
	g = auth.Group("/level")
	g.GET("", h.GetAllLevels)
	g.POST("", h.CreateLevel)
	g.GET("/:id", h.GetLevel)
	g.PUT("/:id", h.UpdateLevel)
	g.DELETE("/:id", h.DeleteLevel)

	// Assignments
	g = auth.Group("/assignment")
	g.GET("", h.GetAllAssignments)
	g.POST("", h.CreateAssignment)
	g.GET("/:id", h.GetAssignment)
	g.PUT("/:id", h.UpdateAssignment)
	g.DELETE("/:id", h.DeleteAssignment)

	// AssignmentGroups
	g = auth.Group("/group")
	g.GET("", h.GetAllAssignmentGroups)
	g.POST("", h.CreateAssignmentGroup)
	g.GET("/:id", h.GetAssignmentGroup)
	g.PUT("/:id", h.UpdateAssignmentGroup)
	g.DELETE("/:id", h.DeleteAssignmentGroup)

	// AssignmentGrades
	g = auth.Group("/grade")

	// Start server
	logrus.Println("Listening On:", port)

	e.Run(standard.New(":" + port))
}
Esempio n. 15
0
func (app *Application) MigrateUp() (err []error, ok bool) {
	return migrate.UpSync(app.dsn, "./migrations")
}