1
0
mirror of https://github.com/beego/bee.git synced 2024-11-22 20:20:55 +00:00

add Postgresql support generate(migrate,Scaffold..)

This commit is contained in:
Sergey Lanzman 2016-07-07 15:21:47 +03:00
parent 64b97f53b4
commit 5c12764c5f

View File

@ -51,25 +51,46 @@ func generateSQLFromFields(fields string) string {
ColorLog("[ERRO] the fields format is wrong. should key:type,key:type " + v + "\n") ColorLog("[ERRO] the fields format is wrong. should key:type,key:type " + v + "\n")
return "" return ""
} }
typ, tag := getSqlType(kv[1]) typ, tag := "", ""
switch driver {
case "mysql":
typ, tag = getSqlTypeMysql(kv[1])
case "postgres":
typ, tag = getSqlTypePostgresql(kv[1])
default:
typ, tag = getSqlTypeMysql(kv[1])
}
if typ == "" { if typ == "" {
ColorLog("[ERRO] the fields format is wrong. should key:type,key:type " + v + "\n") ColorLog("[ERRO] the fields format is wrong. should key:type,key:type " + v + "\n")
return "" return ""
} }
if i == 0 && strings.ToLower(kv[0]) != "id" { if i == 0 && strings.ToLower(kv[0]) != "id" {
switch driver {
case "mysql":
sql = sql + "`id` int(11) NOT NULL AUTO_INCREMENT,"
tags = tags + "PRIMARY KEY (`id`),"
case "postgres":
sql = sql + "id interger serial primary key,"
default:
sql = sql + "`id` int(11) NOT NULL AUTO_INCREMENT," sql = sql + "`id` int(11) NOT NULL AUTO_INCREMENT,"
tags = tags + "PRIMARY KEY (`id`)," tags = tags + "PRIMARY KEY (`id`),"
} }
}
sql = sql + "`" + snakeString(kv[0]) + "` " + typ + "," sql = sql + "`" + snakeString(kv[0]) + "` " + typ + ","
if tag != "" { if tag != "" {
tags = tags + fmt.Sprintf(tag, "`"+snakeString(kv[0])+"`") + "," tags = tags + fmt.Sprintf(tag, "`"+snakeString(kv[0])+"`") + ","
} }
} }
if driver == "postgres" {
sql = strings.Replace(sql, "`", "", -1)
tags = strings.Replace(tags, "`", "", -1)
}
sql = strings.TrimRight(sql+tags, ",") sql = strings.TrimRight(sql+tags, ",")
return sql return sql
} }
func getSqlType(ktype string) (tp, tag string) { func getSqlTypeMysql(ktype string) (tp, tag string) {
kv := strings.SplitN(ktype, ":", 2) kv := strings.SplitN(ktype, ":", 2)
switch kv[0] { switch kv[0] {
case "string": case "string":
@ -99,3 +120,30 @@ func getSqlType(ktype string) (tp, tag string) {
} }
return "", "" return "", ""
} }
func getSqlTypePostgresql(ktype string) (tp, tag string) {
kv := strings.SplitN(ktype, ":", 2)
switch kv[0] {
case "string":
if len(kv) == 2 {
return "char(" + kv[1] + ") NOT NULL", ""
} else {
return "TEXT NOT NULL", ""
}
case "text":
return "TEXT NOT NULL", ""
case "auto", "pk":
return "serial primary key", ""
case "datetime":
return "TIMESTAMP WITHOUT TIME ZONE NOT NULL", ""
case "int", "int8", "int16", "int32", "int64":
fallthrough
case "uint", "uint8", "uint16", "uint32", "uint64":
return "integer DEFAULT NULL", ""
case "bool":
return "boolean NOT NULL", ""
case "float32", "float64", "float":
return "numeric NOT NULL", ""
}
return "", ""
}