Browse Source

Database migration fixes

Vova Tkach 5 years ago
parent
commit
5741f8ab58
3 changed files with 33 additions and 3 deletions
  1. 1 2
      main.go
  2. 1 1
      modules/module_index_act_mysql_setup.go
  3. 31 0
      support/support.go

+ 1 - 2
main.go

@@ -70,8 +70,7 @@ func main() {
 
 	// Run database migration
 	if err := support.New().Migration(consts.ParamWwwDir); err != nil {
-		fmt.Println(err)
-		return
+		fmt.Printf("[ERROR] MIGRATION FAILED: %s\n", err)
 	}
 
 	// Init logger

+ 1 - 1
modules/module_index_act_mysql_setup.go

@@ -379,7 +379,7 @@ func (this *Modules) RegisterAction_IndexMysqlSetup() *Action {
 			return
 		}
 		if _, err = tx.Exec(
-			`INSERT INTO settings (name, value) VALUES ('database_version', '000000000');`,
+			`INSERT INTO settings (name, value) VALUES ('database_version', '000000002');`,
 		); err != nil {
 			tx.Rollback()
 			wrap.MsgError(err.Error())

+ 31 - 0
support/support.go

@@ -3,6 +3,8 @@ package support
 import (
 	"io/ioutil"
 	"os"
+	"regexp"
+	"strings"
 
 	"golang-fave/engine/sqlw"
 	"golang-fave/support/migrate"
@@ -17,6 +19,18 @@ func New() *Support {
 	return &sup
 }
 
+func (this *Support) isSettingsTableDoesntExist(err error) bool {
+	error_msg := strings.ToLower(err.Error())
+	if match, _ := regexp.MatchString(`^error 1146`, error_msg); match {
+		if match, _ := regexp.MatchString(`'[^\.]+\.settings'`, error_msg); match {
+			if match, _ := regexp.MatchString(`doesn't exist$`, error_msg); match {
+				return true
+			}
+		}
+	}
+	return false
+}
+
 func (this *Support) Migration(dir string) error {
 	files, err := ioutil.ReadDir(dir)
 	if err != nil {
@@ -49,6 +63,23 @@ func (this *Support) Migrate(host string) error {
 		defer db.Close()
 		var version string
 		if err := db.QueryRow(`SELECT value FROM settings WHERE name = 'database_version' LIMIT 1;`).Scan(&version); err != nil {
+			if this.isSettingsTableDoesntExist(err) {
+				if _, err := db.Exec(
+					`CREATE TABLE settings (
+						name varchar(255) NOT NULL COMMENT 'Setting name',
+						value text NOT NULL COMMENT 'Setting value'
+					) ENGINE=InnoDB DEFAULT CHARSET=utf8;`,
+				); err != nil {
+					return err
+				}
+				if _, err := db.Exec(
+					`INSERT INTO settings (name, value) VALUES ('database_version', '000000002');`,
+				); err != nil {
+					return err
+				}
+				version = "000000002"
+				err = nil
+			}
 			return err
 		}
 		return this.Process(db, version, host)