/
common.go
79 lines (68 loc) · 1.79 KB
/
common.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package migrations
import (
"fmt"
"os"
"github.com/beslow/goblog/initialize"
"github.com/beslow/goblog/models"
)
func Migrate() {
createMigrations()
createConsts()
createHistoryWorks()
createHistoryEducations()
createGoAdminTables()
createPosts()
createComments()
createCategories()
addCategoryIDToPosts()
addSummaryToPosts()
}
func createMigrations() {
if !existTable("migrations") {
initialize.DB.Exec(`CREATE TABLE migrations (
timestamp varchar(100) NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;`)
}
}
func existTable(table string) bool {
var existTable int
raw := `SELECT EXISTS (
SELECT
TABLE_NAME
FROM
information_schema.TABLES
WHERE
TABLE_SCHEMA LIKE '` + initialize.DefaultConfig.Name + `' AND
TABLE_TYPE LIKE 'BASE TABLE' AND
TABLE_NAME = '` + table + `'
)`
if err := initialize.DB.Raw(raw).Scan(&existTable).Error; err != nil {
fmt.Printf("check table's existence fail: %#v\n", err)
os.Exit(1)
}
return existTable == 1
}
// create table and mark the migration's timestamp
func createTableWithTimestamp(table, createSql, timestamp string) {
var migration models.Migration
if err := initialize.DB.Where("timestamp = ?", timestamp).Find(&migration).Error; err != nil {
fmt.Printf("query migration fail: %#v\n", err)
os.Exit(1)
}
if migration.Timestamp == "" {
createTable(table, createSql)
if err := initialize.DB.Create(&models.Migration{Timestamp: timestamp}).Error; err != nil {
fmt.Printf("add migration timestamp fail: %#v\n", err)
os.Exit(1)
}
}
}
func createTable(table, createSql string) {
if !existTable(table) {
if err := initialize.DB.Exec(createSql).Error; err != nil {
fmt.Printf("create %s fail: %#v\n", table, err)
os.Exit(1)
}
fmt.Printf("create table %s successfully\n", table)
}
}