Finish upgrade the gorm framework.

This commit is contained in:
lishuang 2022-03-15 02:17:26 +08:00
parent 69412300b6
commit 161096fbb2
19 changed files with 167 additions and 187 deletions

View File

@ -1,5 +1,7 @@
package core package core
import "gorm.io/gorm/schema"
const ( const (
//authentication key of cookie //authentication key of cookie
COOKIE_AUTH_KEY = "_ak" COOKIE_AUTH_KEY = "_ak"
@ -22,6 +24,8 @@ type Config interface {
MysqlUrl() string MysqlUrl() string
//files storage location. //files storage location.
MatterPath() string MatterPath() string
//table name strategy
NamingStrategy() schema.NamingStrategy
//when installed by user. Write configs to tank.json //when installed by user. Write configs to tank.json
FinishInstall(mysqlPort int, mysqlHost string, mysqlSchema string, mysqlUsername string, mysqlPassword string, mysqlCharset string) FinishInstall(mysqlPort int, mysqlHost string, mysqlSchema string, mysqlUsername string, mysqlPassword string, mysqlCharset string)
} }

View File

@ -1,9 +1,7 @@
package rest package rest
import ( import (
"fmt"
"math" "math"
"time"
) )
const ( const (
@ -17,25 +15,6 @@ const (
EMPTY_JSON_ARRAY = "[]" EMPTY_JSON_ARRAY = "[]"
) )
type IBase interface {
//name of db table
TableName() string
}
// Mysql 5.5 only support one CURRENT_TIMESTAMP
// so we use 2018-01-01 00:00:00 as default, which is the first release date of EyeblueTank
type Base struct {
Uuid string `json:"uuid" gorm:"type:char(36);primary_key;unique"`
Sort int64 `json:"sort" gorm:"type:bigint(20) not null"`
UpdateTime time.Time `json:"updateTime" gorm:"type:timestamp not null;default:CURRENT_TIMESTAMP"`
CreateTime time.Time `json:"createTime" gorm:"type:timestamp not null;default:'2018-01-01 00:00:00'"`
}
func (this *Base) TableName() string {
panic(fmt.Sprintf("you should overwrite TableName() in %v", this))
return ""
}
//pager //pager
type Pager struct { type Pager struct {
Page int `json:"page"` Page int `json:"page"`

View File

@ -1,18 +1,15 @@
package rest package rest
import ( import "time"
"github.com/eyebluecn/tank/code/core"
)
/** /**
* the link table for Share and Matter. * the link table for Share and Matter.
*/ */
type Bridge struct { type Bridge struct {
Base Uuid string `json:"uuid" gorm:"type:char(36);primary_key;unique"`
ShareUuid string `json:"shareUuid" gorm:"type:char(36)"` Sort int64 `json:"sort" gorm:"type:bigint(20) not null"`
MatterUuid string `json:"matterUuid" gorm:"type:char(36)"` UpdateTime time.Time `json:"updateTime" gorm:"type:timestamp not null;default:CURRENT_TIMESTAMP"`
} CreateTime time.Time `json:"createTime" gorm:"type:timestamp not null;default:'2018-01-01 00:00:00'"`
ShareUuid string `json:"shareUuid" gorm:"type:char(36)"`
func (this *Bridge) TableName() string { MatterUuid string `json:"matterUuid" gorm:"type:char(36)"`
return core.TABLE_PREFIX + "bridge"
} }

View File

@ -1,27 +1,25 @@
package rest package rest
import "github.com/eyebluecn/tank/code/core" import "time"
/** /**
* application's dashboard. * application's dashboard.
*/ */
type Dashboard struct { type Dashboard struct {
Base Uuid string `json:"uuid" gorm:"type:char(36);primary_key;unique"`
InvokeNum int64 `json:"invokeNum" gorm:"type:bigint(20) not null"` //api invoke num. Sort int64 `json:"sort" gorm:"type:bigint(20) not null"`
TotalInvokeNum int64 `json:"totalInvokeNum" gorm:"type:bigint(20) not null;default:0"` //total invoke num up to now. UpdateTime time.Time `json:"updateTime" gorm:"type:timestamp not null;default:CURRENT_TIMESTAMP"`
Uv int64 `json:"uv" gorm:"type:bigint(20) not null;default:0"` //today's uv CreateTime time.Time `json:"createTime" gorm:"type:timestamp not null;default:'2018-01-01 00:00:00'"`
TotalUv int64 `json:"totalUv" gorm:"type:bigint(20) not null;default:0"` //total uv InvokeNum int64 `json:"invokeNum" gorm:"type:bigint(20) not null"` //api invoke num.
MatterNum int64 `json:"matterNum" gorm:"type:bigint(20) not null;default:0"` //file's num TotalInvokeNum int64 `json:"totalInvokeNum" gorm:"type:bigint(20) not null;default:0"` //total invoke num up to now.
TotalMatterNum int64 `json:"totalMatterNum" gorm:"type:bigint(20) not null;default:0"` //file's total number Uv int64 `json:"uv" gorm:"type:bigint(20) not null;default:0"` //today's uv
FileSize int64 `json:"fileSize" gorm:"type:bigint(20) not null;default:0"` //today's file size TotalUv int64 `json:"totalUv" gorm:"type:bigint(20) not null;default:0"` //total uv
TotalFileSize int64 `json:"totalFileSize" gorm:"type:bigint(20) not null;default:0"` //total file's size MatterNum int64 `json:"matterNum" gorm:"type:bigint(20) not null;default:0"` //file's num
AvgCost int64 `json:"avgCost" gorm:"type:bigint(20) not null;default:0"` //api time cost in ms TotalMatterNum int64 `json:"totalMatterNum" gorm:"type:bigint(20) not null;default:0"` //file's total number
Dt string `json:"dt" gorm:"type:varchar(45) not null;index:idx_dt"` //date FileSize int64 `json:"fileSize" gorm:"type:bigint(20) not null;default:0"` //today's file size
} TotalFileSize int64 `json:"totalFileSize" gorm:"type:bigint(20) not null;default:0"` //total file's size
AvgCost int64 `json:"avgCost" gorm:"type:bigint(20) not null;default:0"` //api time cost in ms
// set File's table name to be `profiles` Dt string `json:"dt" gorm:"type:varchar(45) not null;index:idx_dt"` //date
func (this *Dashboard) TableName() string {
return core.TABLE_PREFIX + "dashboard"
} }
/** /**

View File

@ -1,18 +1,16 @@
package rest package rest
import ( import (
"github.com/eyebluecn/tank/code/core"
"time" "time"
) )
type DownloadToken struct { type DownloadToken struct {
Base Uuid string `json:"uuid" gorm:"type:char(36);primary_key;unique"`
Sort int64 `json:"sort" gorm:"type:bigint(20) not null"`
UpdateTime time.Time `json:"updateTime" gorm:"type:timestamp not null;default:CURRENT_TIMESTAMP"`
CreateTime time.Time `json:"createTime" gorm:"type:timestamp not null;default:'2018-01-01 00:00:00'"`
UserUuid string `json:"userUuid" gorm:"type:char(36) not null"` UserUuid string `json:"userUuid" gorm:"type:char(36) not null"`
MatterUuid string `json:"matterUuid" gorm:"type:char(36) not null;index:idx_mu"` MatterUuid string `json:"matterUuid" gorm:"type:char(36) not null;index:idx_mu"`
ExpireTime time.Time `json:"expireTime" gorm:"type:timestamp not null;default:'2018-01-01 00:00:00'"` ExpireTime time.Time `json:"expireTime" gorm:"type:timestamp not null;default:'2018-01-01 00:00:00'"`
Ip string `json:"ip" gorm:"type:varchar(128) not null"` Ip string `json:"ip" gorm:"type:varchar(128) not null"`
} }
func (this *DownloadToken) TableName() string {
return core.TABLE_PREFIX + "download_token"
}

View File

@ -1,22 +1,20 @@
package rest package rest
import "github.com/eyebluecn/tank/code/core" import "time"
/** /**
* visit record. * visit record.
*/ */
type Footprint struct { type Footprint struct {
Base Uuid string `json:"uuid" gorm:"type:char(36);primary_key;unique"`
UserUuid string `json:"userUuid" gorm:"type:char(36)"` Sort int64 `json:"sort" gorm:"type:bigint(20) not null"`
Ip string `json:"ip" gorm:"type:varchar(128) not null"` UpdateTime time.Time `json:"updateTime" gorm:"type:timestamp not null;default:CURRENT_TIMESTAMP"`
Host string `json:"host" gorm:"type:varchar(45) not null"` CreateTime time.Time `json:"createTime" gorm:"type:timestamp not null;default:'2018-01-01 00:00:00'"`
Uri string `json:"uri" gorm:"type:varchar(255) not null"` UserUuid string `json:"userUuid" gorm:"type:char(36)"`
Params string `json:"params" gorm:"type:text"` Ip string `json:"ip" gorm:"type:varchar(128) not null"`
Cost int64 `json:"cost" gorm:"type:bigint(20) not null;default:0"` Host string `json:"host" gorm:"type:varchar(45) not null"`
Success bool `json:"success" gorm:"type:tinyint(1) not null;default:0"` Uri string `json:"uri" gorm:"type:varchar(255) not null"`
} Params string `json:"params" gorm:"type:text"`
Cost int64 `json:"cost" gorm:"type:bigint(20) not null;default:0"`
// set File's table name to be `profiles` Success bool `json:"success" gorm:"type:tinyint(1) not null;default:0"`
func (this *Footprint) TableName() string {
return core.TABLE_PREFIX + "footprint"
} }

View File

@ -67,7 +67,7 @@ func (this *ImageCacheDao) CheckByUuidAndUserUuid(uuid string, userUuid string)
// Read // Read
var imageCache = &ImageCache{} var imageCache = &ImageCache{}
db := core.CONTEXT.GetDB().Where(&ImageCache{Base: Base{Uuid: uuid}, UserUuid: userUuid}).First(imageCache) db := core.CONTEXT.GetDB().Where(&ImageCache{Uuid: uuid, UserUuid: userUuid}).First(imageCache)
this.PanicError(db.Error) this.PanicError(db.Error)
return imageCache return imageCache

View File

@ -1,29 +1,25 @@
package rest package rest
import ( import "time"
"github.com/eyebluecn/tank/code/core"
)
/** /**
* image cache. * image cache.
*/ */
type ImageCache struct { type ImageCache struct {
Base Uuid string `json:"uuid" gorm:"type:char(36);primary_key;unique"`
Name string `json:"name" gorm:"type:varchar(255) not null"` Sort int64 `json:"sort" gorm:"type:bigint(20) not null"`
UserUuid string `json:"userUuid" gorm:"type:char(36)"` UpdateTime time.Time `json:"updateTime" gorm:"type:timestamp not null;default:CURRENT_TIMESTAMP"`
Username string `json:"username" gorm:"type:varchar(45) not null"` CreateTime time.Time `json:"createTime" gorm:"type:timestamp not null;default:'2018-01-01 00:00:00'"`
MatterUuid string `json:"matterUuid" gorm:"type:char(36);index:idx_mu"` Name string `json:"name" gorm:"type:varchar(255) not null"`
MatterName string `json:"matterName" gorm:"type:varchar(255) not null"` UserUuid string `json:"userUuid" gorm:"type:char(36)"`
Mode string `json:"mode" gorm:"type:varchar(512)"` Username string `json:"username" gorm:"type:varchar(45) not null"`
Md5 string `json:"md5" gorm:"type:varchar(45)"` MatterUuid string `json:"matterUuid" gorm:"type:char(36);index:idx_mu"`
Size int64 `json:"size" gorm:"type:bigint(20) not null;default:0"` MatterName string `json:"matterName" gorm:"type:varchar(255) not null"`
Path string `json:"path" gorm:"type:varchar(512)"` Mode string `json:"mode" gorm:"type:varchar(512)"`
Matter *Matter `json:"matter" gorm:"-"` Md5 string `json:"md5" gorm:"type:varchar(45)"`
} Size int64 `json:"size" gorm:"type:bigint(20) not null;default:0"`
Path string `json:"path" gorm:"type:varchar(512)"`
// set File's table name to be `profiles` Matter *Matter `json:"matter" gorm:"-"`
func (this *ImageCache) TableName() string {
return core.TABLE_PREFIX + "image_cache"
} }
// get the absolute path. path in db means relative path. // get the absolute path. path in db means relative path.

View File

@ -31,7 +31,7 @@ type InstallController struct {
matterService *MatterService matterService *MatterService
imageCacheDao *ImageCacheDao imageCacheDao *ImageCacheDao
imageCacheService *ImageCacheService imageCacheService *ImageCacheService
tableNames []IBase tableNames []interface{}
} }
func (this *InstallController) Init() { func (this *InstallController) Init() {
@ -67,18 +67,18 @@ func (this *InstallController) Init() {
this.imageCacheService = c this.imageCacheService = c
} }
this.tableNames = []IBase{ this.tableNames = []interface{}{
&Dashboard{}, &Dashboard{},
//&Bridge{}, &Bridge{},
//&DownloadToken{}, &DownloadToken{},
//&Footprint{}, &Footprint{},
//&ImageCache{}, &ImageCache{},
//&Matter{}, &Matter{},
//&Preference{}, &Preference{},
//&Session{}, &Session{},
//&Share{}, &Share{},
//&UploadToken{}, &UploadToken{},
//&User{}, &User{},
} }
} }
@ -117,6 +117,7 @@ func (this *InstallController) openDbConnection(writer http.ResponseWriter, requ
this.logger.Info("Connect MySQL %s", mysqlUrl) this.logger.Info("Connect MySQL %s", mysqlUrl)
//log config
dbLogger := logger.New( dbLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{ logger.Config{
@ -126,9 +127,11 @@ func (this *InstallController) openDbConnection(writer http.ResponseWriter, requ
Colorful: false, // colorful print Colorful: false, // colorful print
}, },
) )
//table name strategy
namingStrategy := core.CONFIG.NamingStrategy()
var err error = nil var err error = nil
db, err := gorm.Open(mysql.Open(mysqlUrl), &gorm.Config{Logger: dbLogger}) db, err := gorm.Open(mysql.Open(mysqlUrl), &gorm.Config{Logger: dbLogger, NamingStrategy: namingStrategy})
this.PanicError(err) this.PanicError(err)
return db return db
@ -149,47 +152,56 @@ func (this *InstallController) closeDbConnection(db *gorm.DB) {
} }
} }
// (exists, allFields, missingFields) // (tableName, exists, allFields, missingFields)
func (this *InstallController) getTableMeta(gormDb *gorm.DB, schemaName string, entity IBase) (bool, []*schema.Field, []*schema.Field) { func (this *InstallController) getTableMeta(gormDb *gorm.DB, entity interface{}) (string, bool, []*InstallFieldInfo, []*InstallFieldInfo) {
//get all useful fields from model. //get all useful fields from model.
entitySchema, err := schema.Parse(entity, &sync.Map{}, schema.NamingStrategy{}) entitySchema, err := schema.Parse(entity, &sync.Map{}, core.CONFIG.NamingStrategy())
this.PanicError(err) this.PanicError(err)
tableName := entitySchema.Table tableName := entitySchema.Table
allFields := entitySchema.Fields
var missingFields = make([]*schema.Field, 0) var allFields = make([]*InstallFieldInfo, 0)
for _, field := range entitySchema.Fields {
allFields = append(allFields, &InstallFieldInfo{
Name: field.DBName,
DataType: string(field.DataType),
})
}
var missingFields = make([]*InstallFieldInfo, 0)
if !gormDb.Migrator().HasTable(tableName) { if !gormDb.Migrator().HasTable(tableName) {
missingFields = append(missingFields, allFields...) missingFields = append(missingFields, allFields...)
return false, allFields, missingFields return tableName, false, allFields, missingFields
} else { } else {
for _, field := range allFields { for _, field := range allFields {
//tag with `gorm:"-"` will be "" //tag with `gorm:"-"` will be ""
if field.DBName != "" { if field.Name != "" {
database := gormDb.Migrator().CurrentDatabase() database := gormDb.Migrator().CurrentDatabase()
if !third.MysqlMigratorHasColumn(gormDb, database, tableName, field.DBName) { if !third.MysqlMigratorHasColumn(gormDb, database, tableName, field.Name) {
missingFields = append(missingFields, field) missingFields = append(missingFields, field)
} }
} }
} }
return true, allFields, missingFields return tableName, true, allFields, missingFields
} }
} }
func (this *InstallController) getTableMetaList(db *gorm.DB, mysqlSchema string) []*InstallTableInfo { func (this *InstallController) getTableMetaList(db *gorm.DB) []*InstallTableInfo {
var installTableInfos []*InstallTableInfo var installTableInfos []*InstallTableInfo
for _, iBase := range this.tableNames { for _, iBase := range this.tableNames {
exist, allFields, missingFields := this.getTableMeta(db, mysqlSchema, iBase) tableName, exist, allFields, missingFields := this.getTableMeta(db, iBase)
installTableInfos = append(installTableInfos, &InstallTableInfo{ installTableInfos = append(installTableInfos, &InstallTableInfo{
Name: iBase.TableName(), Name: tableName,
TableExist: exist, TableExist: exist,
AllFields: allFields, AllFields: allFields,
MissingFields: missingFields, MissingFields: missingFields,
@ -208,7 +220,7 @@ func (this *InstallController) validateTableMetaList(tableInfoList []*InstallTab
var strs []string var strs []string
for _, v := range tableInfo.MissingFields { for _, v := range tableInfo.MissingFields {
strs = append(strs, v.DBName) strs = append(strs, v.Name)
} }
panic(result.BadRequest(fmt.Sprintf("table %s miss the following fields %v", tableInfo.Name, strs))) panic(result.BadRequest(fmt.Sprintf("table %s miss the following fields %v", tableInfo.Name, strs)))
@ -236,32 +248,29 @@ func (this *InstallController) Verify(writer http.ResponseWriter, request *http.
} }
func (this *InstallController) TableInfoList(writer http.ResponseWriter, request *http.Request) *result.WebResult { func (this *InstallController) TableInfoList(writer http.ResponseWriter, request *http.Request) *result.WebResult {
mysqlSchema := request.FormValue("mysqlSchema")
db := this.openDbConnection(writer, request) db := this.openDbConnection(writer, request)
defer this.closeDbConnection(db) defer this.closeDbConnection(db)
return this.Success(this.getTableMetaList(db, mysqlSchema)) return this.Success(this.getTableMetaList(db))
} }
func (this *InstallController) CreateTable(writer http.ResponseWriter, request *http.Request) *result.WebResult { func (this *InstallController) CreateTable(writer http.ResponseWriter, request *http.Request) *result.WebResult {
var installTableInfos []*InstallTableInfo var installTableInfos []*InstallTableInfo
mysqlSchema := request.FormValue("mysqlSchema") mysqlCharset := request.FormValue("mysqlCharset")
db := this.openDbConnection(writer, request) db := this.openDbConnection(writer, request)
defer this.closeDbConnection(db) defer this.closeDbConnection(db)
for _, iBase := range this.tableNames { for _, iBase := range this.tableNames {
//complete the missing fields or create table. use utf8 charset //complete the missing fields or create table. use utf8 charset
db1 := db.Set("gorm:table_options", "CHARSET=utf8mb4").AutoMigrate(iBase) err := db.Set("gorm:table_options", fmt.Sprintf("CHARSET=%s", mysqlCharset)).AutoMigrate(iBase)
if db1.Error() != "" { this.PanicError(err)
panic(result.BadRequest(`migrate table error`))
}
exist, allFields, missingFields := this.getTableMeta(db, mysqlSchema, iBase) tableName, exist, allFields, missingFields := this.getTableMeta(db, iBase)
installTableInfos = append(installTableInfos, &InstallTableInfo{ installTableInfos = append(installTableInfos, &InstallTableInfo{
Name: iBase.TableName(), Name: tableName,
TableExist: exist, TableExist: exist,
AllFields: allFields, AllFields: allFields,
MissingFields: missingFields, MissingFields: missingFields,
@ -393,7 +402,7 @@ func (this *InstallController) Finish(writer http.ResponseWriter, request *http.
defer this.closeDbConnection(db) defer this.closeDbConnection(db)
//Recheck the integrity of tables. //Recheck the integrity of tables.
tableMetaList := this.getTableMetaList(db, mysqlSchema) tableMetaList := this.getTableMetaList(db)
this.validateTableMetaList(tableMetaList) this.validateTableMetaList(tableMetaList)
//At least one admin //At least one admin

View File

@ -1,15 +1,19 @@
package rest package rest
import (
"gorm.io/gorm/schema"
)
/** /**
* table meta info. * table meta info.
*/ */
type InstallTableInfo struct { type InstallTableInfo struct {
Name string `json:"name"` Name string `json:"name"`
TableExist bool `json:"tableExist"` TableExist bool `json:"tableExist"`
AllFields []*schema.Field `json:"allFields"` AllFields []*InstallFieldInfo `json:"allFields"`
MissingFields []*schema.Field `json:"missingFields"` MissingFields []*InstallFieldInfo `json:"missingFields"`
}
/**
* table meta info.
*/
type InstallFieldInfo struct {
Name string `json:"name"`
DataType string `json:"dataType"`
} }

View File

@ -138,7 +138,7 @@ func (this *MatterDao) FindByUserUuidAndPuuidAndDirTrue(userUuid string, puuid s
func (this *MatterDao) CheckByUuidAndUserUuid(uuid string, userUuid string) *Matter { func (this *MatterDao) CheckByUuidAndUserUuid(uuid string, userUuid string) *Matter {
var matter = &Matter{} var matter = &Matter{}
db := core.CONTEXT.GetDB().Where(&Matter{Base: Base{Uuid: uuid}, UserUuid: userUuid}).First(matter) db := core.CONTEXT.GetDB().Where(&Matter{Uuid: uuid, UserUuid: userUuid}).First(matter)
this.PanicError(db.Error) this.PanicError(db.Error)
return matter return matter

View File

@ -30,7 +30,10 @@ const (
* file is too common. so we use matter as file. * file is too common. so we use matter as file.
*/ */
type Matter struct { type Matter struct {
Base Uuid string `json:"uuid" gorm:"type:char(36);primary_key;unique"`
Sort int64 `json:"sort" gorm:"type:bigint(20) not null"`
UpdateTime time.Time `json:"updateTime" gorm:"type:timestamp not null;default:CURRENT_TIMESTAMP"`
CreateTime time.Time `json:"createTime" gorm:"type:timestamp not null;default:'2018-01-01 00:00:00'"`
Puuid string `json:"puuid" gorm:"type:char(36);index:idx_puuid"` Puuid string `json:"puuid" gorm:"type:char(36);index:idx_puuid"`
UserUuid string `json:"userUuid" gorm:"type:char(36);index:idx_uu"` UserUuid string `json:"userUuid" gorm:"type:char(36);index:idx_uu"`
Username string `json:"username" gorm:"type:varchar(45) not null"` Username string `json:"username" gorm:"type:varchar(45) not null"`
@ -49,11 +52,6 @@ type Matter struct {
DeleteTime time.Time `json:"deleteTime" gorm:"type:timestamp not null;index:idx_delt;default:'2018-01-01 00:00:00'"` DeleteTime time.Time `json:"deleteTime" gorm:"type:timestamp not null;index:idx_delt;default:'2018-01-01 00:00:00'"`
} }
// set File's table name to be `profiles`
func (Matter) TableName() string {
return core.TABLE_PREFIX + "matter"
}
// get matter's absolute path. the Path property is relative path in db. // get matter's absolute path. the Path property is relative path in db.
func (this *Matter) AbsolutePath() string { func (this *Matter) AbsolutePath() string {
return GetUserMatterRootDir(this.Username) + this.Path return GetUserMatterRootDir(this.Username) + this.Path

View File

@ -1,30 +1,28 @@
package rest package rest
import ( import (
"github.com/eyebluecn/tank/code/core"
jsoniter "github.com/json-iterator/go" jsoniter "github.com/json-iterator/go"
"time"
) )
type Preference struct { type Preference struct {
Base Uuid string `json:"uuid" gorm:"type:char(36);primary_key;unique"`
Name string `json:"name" gorm:"type:varchar(45)"` Sort int64 `json:"sort" gorm:"type:bigint(20) not null"`
LogoUrl string `json:"logoUrl" gorm:"type:varchar(255)"` UpdateTime time.Time `json:"updateTime" gorm:"type:timestamp not null;default:CURRENT_TIMESTAMP"`
FaviconUrl string `json:"faviconUrl" gorm:"type:varchar(255)"` CreateTime time.Time `json:"createTime" gorm:"type:timestamp not null;default:'2018-01-01 00:00:00'"`
Copyright string `json:"copyright" gorm:"type:varchar(1024)"` Name string `json:"name" gorm:"type:varchar(45)"`
Record string `json:"record" gorm:"type:varchar(1024)"` LogoUrl string `json:"logoUrl" gorm:"type:varchar(255)"`
DownloadDirMaxSize int64 `json:"downloadDirMaxSize" gorm:"type:bigint(20) not null;default:-1"` FaviconUrl string `json:"faviconUrl" gorm:"type:varchar(255)"`
DownloadDirMaxNum int64 `json:"downloadDirMaxNum" gorm:"type:bigint(20) not null;default:-1"` Copyright string `json:"copyright" gorm:"type:varchar(1024)"`
DefaultTotalSizeLimit int64 `json:"defaultTotalSizeLimit" gorm:"type:bigint(20) not null;default:-1"` Record string `json:"record" gorm:"type:varchar(1024)"`
AllowRegister bool `json:"allowRegister" gorm:"type:tinyint(1) not null;default:0"` DownloadDirMaxSize int64 `json:"downloadDirMaxSize" gorm:"type:bigint(20) not null;default:-1"`
PreviewConfig string `json:"previewConfig" gorm:"type:text"` DownloadDirMaxNum int64 `json:"downloadDirMaxNum" gorm:"type:bigint(20) not null;default:-1"`
ScanConfig string `json:"scanConfig" gorm:"type:text"` DefaultTotalSizeLimit int64 `json:"defaultTotalSizeLimit" gorm:"type:bigint(20) not null;default:-1"`
DeletedKeepDays int64 `json:"deletedKeepDays" gorm:"type:bigint(20) not null;default:7"` AllowRegister bool `json:"allowRegister" gorm:"type:tinyint(1) not null;default:0"`
Version string `json:"version" gorm:"-"` PreviewConfig string `json:"previewConfig" gorm:"type:text"`
} ScanConfig string `json:"scanConfig" gorm:"type:text"`
DeletedKeepDays int64 `json:"deletedKeepDays" gorm:"type:bigint(20) not null;default:7"`
// set File's table name to be `profiles` Version string `json:"version" gorm:"-"`
func (this *Preference) TableName() string {
return core.TABLE_PREFIX + "preference"
} }
const ( const (

View File

@ -1,18 +1,15 @@
package rest package rest
import ( import (
"github.com/eyebluecn/tank/code/core"
"time" "time"
) )
type Session struct { type Session struct {
Base Uuid string `json:"uuid" gorm:"type:char(36);primary_key;unique"`
Sort int64 `json:"sort" gorm:"type:bigint(20) not null"`
UpdateTime time.Time `json:"updateTime" gorm:"type:timestamp not null;default:CURRENT_TIMESTAMP"`
CreateTime time.Time `json:"createTime" gorm:"type:timestamp not null;default:'2018-01-01 00:00:00'"`
UserUuid string `json:"userUuid" gorm:"type:char(36)"` UserUuid string `json:"userUuid" gorm:"type:char(36)"`
Ip string `json:"ip" gorm:"type:varchar(128) not null"` Ip string `json:"ip" gorm:"type:varchar(128) not null"`
ExpireTime time.Time `json:"expireTime" gorm:"type:timestamp not null;default:'2018-01-01 00:00:00'"` ExpireTime time.Time `json:"expireTime" gorm:"type:timestamp not null;default:'2018-01-01 00:00:00'"`
} }
// set User's table name to be `profiles`
func (this *Session) TableName() string {
return core.TABLE_PREFIX + "session"
}

View File

@ -1,7 +1,6 @@
package rest package rest
import ( import (
"github.com/eyebluecn/tank/code/core"
"time" "time"
) )
@ -22,7 +21,10 @@ const (
* share record * share record
*/ */
type Share struct { type Share struct {
Base Uuid string `json:"uuid" gorm:"type:char(36);primary_key;unique"`
Sort int64 `json:"sort" gorm:"type:bigint(20) not null"`
UpdateTime time.Time `json:"updateTime" gorm:"type:timestamp not null;default:CURRENT_TIMESTAMP"`
CreateTime time.Time `json:"createTime" gorm:"type:timestamp not null;default:'2018-01-01 00:00:00'"`
Name string `json:"name" gorm:"type:varchar(255)"` Name string `json:"name" gorm:"type:varchar(255)"`
ShareType string `json:"shareType" gorm:"type:varchar(45)"` ShareType string `json:"shareType" gorm:"type:varchar(45)"`
Username string `json:"username" gorm:"type:varchar(45)"` Username string `json:"username" gorm:"type:varchar(45)"`
@ -34,8 +36,3 @@ type Share struct {
DirMatter *Matter `json:"dirMatter" gorm:"-"` DirMatter *Matter `json:"dirMatter" gorm:"-"`
Matters []*Matter `json:"matters" gorm:"-"` Matters []*Matter `json:"matters" gorm:"-"`
} }
// set File's table name to be `profiles`
func (this *Share) TableName() string {
return core.TABLE_PREFIX + "share"
}

View File

@ -1,12 +1,14 @@
package rest package rest
import ( import (
"github.com/eyebluecn/tank/code/core"
"time" "time"
) )
type UploadToken struct { type UploadToken struct {
Base Uuid string `json:"uuid" gorm:"type:char(36);primary_key;unique"`
Sort int64 `json:"sort" gorm:"type:bigint(20) not null"`
UpdateTime time.Time `json:"updateTime" gorm:"type:timestamp not null;default:CURRENT_TIMESTAMP"`
CreateTime time.Time `json:"createTime" gorm:"type:timestamp not null;default:'2018-01-01 00:00:00'"`
UserUuid string `json:"userUuid" gorm:"type:char(36) not null"` UserUuid string `json:"userUuid" gorm:"type:char(36) not null"`
FolderUuid string `json:"folderUuid" gorm:"type:char(36) not null"` FolderUuid string `json:"folderUuid" gorm:"type:char(36) not null"`
MatterUuid string `json:"matterUuid" gorm:"type:char(36) not null"` MatterUuid string `json:"matterUuid" gorm:"type:char(36) not null"`
@ -16,7 +18,3 @@ type UploadToken struct {
Size int64 `json:"size" gorm:"type:bigint(20) not null;default:0"` Size int64 `json:"size" gorm:"type:bigint(20) not null;default:0"`
Ip string `json:"ip" gorm:"type:varchar(128) not null"` Ip string `json:"ip" gorm:"type:varchar(128) not null"`
} }
func (this *UploadToken) TableName() string {
return core.TABLE_PREFIX + "upload_token"
}

View File

@ -1,7 +1,6 @@
package rest package rest
import ( import (
"github.com/eyebluecn/tank/code/core"
"time" "time"
) )
@ -28,7 +27,10 @@ const (
) )
type User struct { type User struct {
Base Uuid string `json:"uuid" gorm:"type:char(36);primary_key;unique"`
Sort int64 `json:"sort" gorm:"type:bigint(20) not null"`
UpdateTime time.Time `json:"updateTime" gorm:"type:timestamp not null;default:CURRENT_TIMESTAMP"`
CreateTime time.Time `json:"createTime" gorm:"type:timestamp not null;default:'2018-01-01 00:00:00'"`
Role string `json:"role" gorm:"type:varchar(45)"` Role string `json:"role" gorm:"type:varchar(45)"`
Username string `json:"username" gorm:"type:varchar(45) not null;unique"` Username string `json:"username" gorm:"type:varchar(45) not null;unique"`
Password string `json:"-" gorm:"type:varchar(255)"` Password string `json:"-" gorm:"type:varchar(255)"`
@ -40,8 +42,3 @@ type User struct {
TotalSize int64 `json:"totalSize" gorm:"type:bigint(20) not null;default:0"` TotalSize int64 `json:"totalSize" gorm:"type:bigint(20) not null;default:0"`
Status string `json:"status" gorm:"type:varchar(45)"` Status string `json:"status" gorm:"type:varchar(45)"`
} }
// set User's table name to be `profiles`
func (this *User) TableName() string {
return core.TABLE_PREFIX + "user"
}

View File

@ -4,6 +4,7 @@ import (
"github.com/eyebluecn/tank/code/core" "github.com/eyebluecn/tank/code/core"
"github.com/eyebluecn/tank/code/tool/util" "github.com/eyebluecn/tank/code/tool/util"
"github.com/json-iterator/go" "github.com/json-iterator/go"
"gorm.io/gorm/schema"
"io/ioutil" "io/ioutil"
"os" "os"
"time" "time"
@ -178,6 +179,14 @@ func (this *TankConfig) MatterPath() string {
return this.matterPath return this.matterPath
} }
//matter path
func (this *TankConfig) NamingStrategy() schema.NamingStrategy {
return schema.NamingStrategy{
TablePrefix: core.TABLE_PREFIX,
SingularTable: true,
}
}
//Finish the installation. Write config to tank.json //Finish the installation. Write config to tank.json
func (this *TankConfig) FinishInstall(mysqlPort int, mysqlHost string, mysqlSchema string, mysqlUsername string, mysqlPassword string, mysqlCharset string) { func (this *TankConfig) FinishInstall(mysqlPort int, mysqlHost string, mysqlSchema string, mysqlUsername string, mysqlPassword string, mysqlCharset string) {

View File

@ -75,6 +75,7 @@ func (this *TankContext) ServeHTTP(writer http.ResponseWriter, request *http.Req
func (this *TankContext) OpenDb() { func (this *TankContext) OpenDb() {
//log strategy.
dbLogger := logger.New( dbLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{ logger.Config{
@ -84,9 +85,11 @@ func (this *TankContext) OpenDb() {
Colorful: false, // colorful print Colorful: false, // colorful print
}, },
) )
//table name strategy.
namingStrategy := core.CONFIG.NamingStrategy()
var err error = nil var err error = nil
this.db, err = gorm.Open(mysql.Open(core.CONFIG.MysqlUrl()), &gorm.Config{Logger: dbLogger}) this.db, err = gorm.Open(mysql.Open(core.CONFIG.MysqlUrl()), &gorm.Config{Logger: dbLogger, NamingStrategy: namingStrategy})
if err != nil { if err != nil {
core.LOGGER.Panic("failed to connect mysql database") core.LOGGER.Panic("failed to connect mysql database")