Signed-off-by: 商讯在线 <swhbox@foxmail.com>
This commit is contained in:
商讯在线 2014-04-17 22:34:19 +08:00
parent b21b2f598c
commit 99a0987009
5 changed files with 404 additions and 404 deletions

View File

@ -1,65 +1,65 @@
package main
import (
//"fmt"
"github.com/lunny/xorm"
"strings"
"text/template"
//"fmt"
"github.com/go-xorm/xorm"
"strings"
"text/template"
)
var (
CPlusTmpl LangTmpl = LangTmpl{
template.FuncMap{"Mapper": mapper.Table2Obj,
"Type": cPlusTypeStr,
"UnTitle": unTitle,
},
nil,
genCPlusImports,
}
CPlusTmpl LangTmpl = LangTmpl{
template.FuncMap{"Mapper": mapper.Table2Obj,
"Type": cPlusTypeStr,
"UnTitle": unTitle,
},
nil,
genCPlusImports,
}
)
func cPlusTypeStr(col *xorm.Column) string {
tp := col.SQLType
name := strings.ToUpper(tp.Name)
switch name {
case xorm.Bit, xorm.TinyInt, xorm.SmallInt, xorm.MediumInt, xorm.Int, xorm.Integer, xorm.Serial:
return "int"
case xorm.BigInt, xorm.BigSerial:
return "__int64"
case xorm.Char, xorm.Varchar, xorm.TinyText, xorm.Text, xorm.MediumText, xorm.LongText:
return "tstring"
case xorm.Date, xorm.DateTime, xorm.Time, xorm.TimeStamp:
return "time_t"
case xorm.Decimal, xorm.Numeric:
return "tstring"
case xorm.Real, xorm.Float:
return "float"
case xorm.Double:
return "double"
case xorm.TinyBlob, xorm.Blob, xorm.MediumBlob, xorm.LongBlob, xorm.Bytea:
return "tstring"
case xorm.Bool:
return "bool"
default:
return "tstring"
}
return ""
tp := col.SQLType
name := strings.ToUpper(tp.Name)
switch name {
case xorm.Bit, xorm.TinyInt, xorm.SmallInt, xorm.MediumInt, xorm.Int, xorm.Integer, xorm.Serial:
return "int"
case xorm.BigInt, xorm.BigSerial:
return "__int64"
case xorm.Char, xorm.Varchar, xorm.TinyText, xorm.Text, xorm.MediumText, xorm.LongText:
return "tstring"
case xorm.Date, xorm.DateTime, xorm.Time, xorm.TimeStamp:
return "time_t"
case xorm.Decimal, xorm.Numeric:
return "tstring"
case xorm.Real, xorm.Float:
return "float"
case xorm.Double:
return "double"
case xorm.TinyBlob, xorm.Blob, xorm.MediumBlob, xorm.LongBlob, xorm.Bytea:
return "tstring"
case xorm.Bool:
return "bool"
default:
return "tstring"
}
return ""
}
func genCPlusImports(tables []*xorm.Table) map[string]string {
imports := make(map[string]string)
imports := make(map[string]string)
for _, table := range tables {
for _, col := range table.Columns {
switch cPlusTypeStr(col) {
case "time_t":
imports[`<time.h>`] = `<time.h>`
case "tstring":
imports["<string>"] = "<string>"
//case "__int64":
// imports[""] = ""
}
}
}
return imports
for _, table := range tables {
for _, col := range table.Columns {
switch cPlusTypeStr(col) {
case "time_t":
imports[`<time.h>`] = `<time.h>`
case "tstring":
imports["<string>"] = "<string>"
//case "__int64":
// imports[""] = ""
}
}
}
return imports
}

View File

@ -1,263 +1,263 @@
package main
import (
"errors"
"fmt"
"github.com/lunny/xorm"
"go/format"
"reflect"
"strings"
"text/template"
"errors"
"fmt"
"github.com/go-xorm/xorm"
"go/format"
"reflect"
"strings"
"text/template"
)
var (
GoLangTmpl LangTmpl = LangTmpl{
template.FuncMap{"Mapper": mapper.Table2Obj,
"Type": typestring,
"Tag": tag,
"UnTitle": unTitle,
"gt": gt,
"getCol": getCol,
},
formatGo,
genGoImports,
}
GoLangTmpl LangTmpl = LangTmpl{
template.FuncMap{"Mapper": mapper.Table2Obj,
"Type": typestring,
"Tag": tag,
"UnTitle": unTitle,
"gt": gt,
"getCol": getCol,
},
formatGo,
genGoImports,
}
)
var (
errBadComparisonType = errors.New("invalid type for comparison")
errBadComparison = errors.New("incompatible types for comparison")
errNoComparison = errors.New("missing argument for comparison")
errBadComparisonType = errors.New("invalid type for comparison")
errBadComparison = errors.New("incompatible types for comparison")
errNoComparison = errors.New("missing argument for comparison")
)
type kind int
const (
invalidKind kind = iota
boolKind
complexKind
intKind
floatKind
integerKind
stringKind
uintKind
invalidKind kind = iota
boolKind
complexKind
intKind
floatKind
integerKind
stringKind
uintKind
)
func basicKind(v reflect.Value) (kind, error) {
switch v.Kind() {
case reflect.Bool:
return boolKind, nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return intKind, nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return uintKind, nil
case reflect.Float32, reflect.Float64:
return floatKind, nil
case reflect.Complex64, reflect.Complex128:
return complexKind, nil
case reflect.String:
return stringKind, nil
}
return invalidKind, errBadComparisonType
switch v.Kind() {
case reflect.Bool:
return boolKind, nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return intKind, nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return uintKind, nil
case reflect.Float32, reflect.Float64:
return floatKind, nil
case reflect.Complex64, reflect.Complex128:
return complexKind, nil
case reflect.String:
return stringKind, nil
}
return invalidKind, errBadComparisonType
}
// eq evaluates the comparison a == b || a == c || ...
func eq(arg1 interface{}, arg2 ...interface{}) (bool, error) {
v1 := reflect.ValueOf(arg1)
k1, err := basicKind(v1)
if err != nil {
return false, err
}
if len(arg2) == 0 {
return false, errNoComparison
}
for _, arg := range arg2 {
v2 := reflect.ValueOf(arg)
k2, err := basicKind(v2)
if err != nil {
return false, err
}
if k1 != k2 {
return false, errBadComparison
}
truth := false
switch k1 {
case boolKind:
truth = v1.Bool() == v2.Bool()
case complexKind:
truth = v1.Complex() == v2.Complex()
case floatKind:
truth = v1.Float() == v2.Float()
case intKind:
truth = v1.Int() == v2.Int()
case stringKind:
truth = v1.String() == v2.String()
case uintKind:
truth = v1.Uint() == v2.Uint()
default:
panic("invalid kind")
}
if truth {
return true, nil
}
}
return false, nil
v1 := reflect.ValueOf(arg1)
k1, err := basicKind(v1)
if err != nil {
return false, err
}
if len(arg2) == 0 {
return false, errNoComparison
}
for _, arg := range arg2 {
v2 := reflect.ValueOf(arg)
k2, err := basicKind(v2)
if err != nil {
return false, err
}
if k1 != k2 {
return false, errBadComparison
}
truth := false
switch k1 {
case boolKind:
truth = v1.Bool() == v2.Bool()
case complexKind:
truth = v1.Complex() == v2.Complex()
case floatKind:
truth = v1.Float() == v2.Float()
case intKind:
truth = v1.Int() == v2.Int()
case stringKind:
truth = v1.String() == v2.String()
case uintKind:
truth = v1.Uint() == v2.Uint()
default:
panic("invalid kind")
}
if truth {
return true, nil
}
}
return false, nil
}
// lt evaluates the comparison a < b.
func lt(arg1, arg2 interface{}) (bool, error) {
v1 := reflect.ValueOf(arg1)
k1, err := basicKind(v1)
if err != nil {
return false, err
}
v2 := reflect.ValueOf(arg2)
k2, err := basicKind(v2)
if err != nil {
return false, err
}
if k1 != k2 {
return false, errBadComparison
}
truth := false
switch k1 {
case boolKind, complexKind:
return false, errBadComparisonType
case floatKind:
truth = v1.Float() < v2.Float()
case intKind:
truth = v1.Int() < v2.Int()
case stringKind:
truth = v1.String() < v2.String()
case uintKind:
truth = v1.Uint() < v2.Uint()
default:
panic("invalid kind")
}
return truth, nil
v1 := reflect.ValueOf(arg1)
k1, err := basicKind(v1)
if err != nil {
return false, err
}
v2 := reflect.ValueOf(arg2)
k2, err := basicKind(v2)
if err != nil {
return false, err
}
if k1 != k2 {
return false, errBadComparison
}
truth := false
switch k1 {
case boolKind, complexKind:
return false, errBadComparisonType
case floatKind:
truth = v1.Float() < v2.Float()
case intKind:
truth = v1.Int() < v2.Int()
case stringKind:
truth = v1.String() < v2.String()
case uintKind:
truth = v1.Uint() < v2.Uint()
default:
panic("invalid kind")
}
return truth, nil
}
// le evaluates the comparison <= b.
func le(arg1, arg2 interface{}) (bool, error) {
// <= is < or ==.
lessThan, err := lt(arg1, arg2)
if lessThan || err != nil {
return lessThan, err
}
return eq(arg1, arg2)
// <= is < or ==.
lessThan, err := lt(arg1, arg2)
if lessThan || err != nil {
return lessThan, err
}
return eq(arg1, arg2)
}
// gt evaluates the comparison a > b.
func gt(arg1, arg2 interface{}) (bool, error) {
// > is the inverse of <=.
lessOrEqual, err := le(arg1, arg2)
if err != nil {
return false, err
}
return !lessOrEqual, nil
// > is the inverse of <=.
lessOrEqual, err := le(arg1, arg2)
if err != nil {
return false, err
}
return !lessOrEqual, nil
}
func getCol(cols map[string]*xorm.Column, name string) *xorm.Column {
return cols[name]
return cols[name]
}
func formatGo(src string) (string, error) {
source, err := format.Source([]byte(src))
if err != nil {
return "", err
}
return string(source), nil
source, err := format.Source([]byte(src))
if err != nil {
return "", err
}
return string(source), nil
}
func genGoImports(tables []*xorm.Table) map[string]string {
imports := make(map[string]string)
imports := make(map[string]string)
for _, table := range tables {
for _, col := range table.Columns {
if typestring(col) == "time.Time" {
imports["time"] = "time"
}
}
}
return imports
for _, table := range tables {
for _, col := range table.Columns {
if typestring(col) == "time.Time" {
imports["time"] = "time"
}
}
}
return imports
}
func typestring(col *xorm.Column) string {
st := col.SQLType
/*if col.IsPrimaryKey {
return "int64"
}*/
t := xorm.SQLType2Type(st)
s := t.String()
if s == "[]uint8" {
return "[]byte"
}
return s
st := col.SQLType
/*if col.IsPrimaryKey {
return "int64"
}*/
t := xorm.SQLType2Type(st)
s := t.String()
if s == "[]uint8" {
return "[]byte"
}
return s
}
func tag(table *xorm.Table, col *xorm.Column) string {
isNameId := (mapper.Table2Obj(col.Name) == "Id")
isIdPk := isNameId && typestring(col) == "int64"
isNameId := (mapper.Table2Obj(col.Name) == "Id")
isIdPk := isNameId && typestring(col) == "int64"
res := make([]string, 0)
if !col.Nullable {
if !isIdPk {
res = append(res, "not null")
}
}
if col.IsPrimaryKey {
if !isIdPk {
res = append(res, "pk")
}
}
if col.Default != "" {
res = append(res, "default "+col.Default)
}
if col.IsAutoIncrement {
if !isIdPk {
res = append(res, "autoincr")
}
}
if col.IsCreated {
res = append(res, "created")
}
if col.IsUpdated {
res = append(res, "updated")
}
for name, _ := range col.Indexes {
index := table.Indexes[name]
var uistr string
if index.Type == xorm.UniqueType {
uistr = "unique"
} else if index.Type == xorm.IndexType {
uistr = "index"
}
if len(index.Cols) > 1 {
uistr += "(" + index.Name + ")"
}
res = append(res, uistr)
}
res := make([]string, 0)
if !col.Nullable {
if !isIdPk {
res = append(res, "not null")
}
}
if col.IsPrimaryKey {
if !isIdPk {
res = append(res, "pk")
}
}
if col.Default != "" {
res = append(res, "default "+col.Default)
}
if col.IsAutoIncrement {
if !isIdPk {
res = append(res, "autoincr")
}
}
if col.IsCreated {
res = append(res, "created")
}
if col.IsUpdated {
res = append(res, "updated")
}
for name, _ := range col.Indexes {
index := table.Indexes[name]
var uistr string
if index.Type == xorm.UniqueType {
uistr = "unique"
} else if index.Type == xorm.IndexType {
uistr = "index"
}
if len(index.Cols) > 1 {
uistr += "(" + index.Name + ")"
}
res = append(res, uistr)
}
nstr := col.SQLType.Name
if col.Length != 0 {
if col.Length2 != 0 {
nstr += fmt.Sprintf("(%v,%v)", col.Length, col.Length2)
} else {
nstr += fmt.Sprintf("(%v)", col.Length)
}
}
res = append(res, nstr)
nstr := col.SQLType.Name
if col.Length != 0 {
if col.Length2 != 0 {
nstr += fmt.Sprintf("(%v,%v)", col.Length, col.Length2)
} else {
nstr += fmt.Sprintf("(%v)", col.Length)
}
}
res = append(res, nstr)
var tags []string
if genJson {
tags = append(tags, "json:\""+col.Name+"\"")
}
if len(res) > 0 {
tags = append(tags, "xorm:\""+strings.Join(res, " ")+"\"")
}
if len(tags) > 0 {
return "`" + strings.Join(tags, " ") + "`"
} else {
return ""
}
var tags []string
if genJson {
tags = append(tags, "json:\""+col.Name+"\"")
}
if len(res) > 0 {
tags = append(tags, "xorm:\""+strings.Join(res, " ")+"\"")
}
if len(tags) > 0 {
return "`" + strings.Join(tags, " ") + "`"
} else {
return ""
}
}

View File

@ -1,51 +1,51 @@
package main
import (
"github.com/lunny/xorm"
"io/ioutil"
"strings"
"text/template"
"github.com/go-xorm/xorm"
"io/ioutil"
"strings"
"text/template"
)
type LangTmpl struct {
Funcs template.FuncMap
Formater func(string) (string, error)
GenImports func([]*xorm.Table) map[string]string
Funcs template.FuncMap
Formater func(string) (string, error)
GenImports func([]*xorm.Table) map[string]string
}
var (
mapper = &xorm.SnakeMapper{}
langTmpls = map[string]LangTmpl{
"go": GoLangTmpl,
"c++": CPlusTmpl,
}
mapper = &xorm.SnakeMapper{}
langTmpls = map[string]LangTmpl{
"go": GoLangTmpl,
"c++": CPlusTmpl,
}
)
func loadConfig(f string) map[string]string {
bts, err := ioutil.ReadFile(f)
if err != nil {
return nil
}
configs := make(map[string]string)
lines := strings.Split(string(bts), "\n")
for _, line := range lines {
line = strings.TrimRight(line, "\r")
vs := strings.Split(line, "=")
if len(vs) == 2 {
configs[strings.TrimSpace(vs[0])] = strings.TrimSpace(vs[1])
}
}
return configs
bts, err := ioutil.ReadFile(f)
if err != nil {
return nil
}
configs := make(map[string]string)
lines := strings.Split(string(bts), "\n")
for _, line := range lines {
line = strings.TrimRight(line, "\r")
vs := strings.Split(line, "=")
if len(vs) == 2 {
configs[strings.TrimSpace(vs[0])] = strings.TrimSpace(vs[1])
}
}
return configs
}
func unTitle(src string) string {
if src == "" {
return ""
}
if src == "" {
return ""
}
if len(src) == 1 {
return strings.ToLower(string(src[0]))
} else {
return strings.ToLower(string(src[0])) + src[1:]
}
if len(src) == 1 {
return strings.ToLower(string(src[0]))
} else {
return strings.ToLower(string(src[0])) + src[1:]
}
}

View File

@ -13,8 +13,8 @@ import (
"github.com/dvirsky/go-pylog/logging"
_ "github.com/go-sql-driver/mysql"
"github.com/go-xorm/xorm"
_ "github.com/lib/pq"
"github.com/lunny/xorm"
_ "github.com/mattn/go-sqlite3"
_ "github.com/ziutek/mymysql/godrv"
)

View File

@ -1,15 +1,15 @@
package main
import (
"fmt"
"github.com/lunny/xorm"
"strings"
"fmt"
"github.com/go-xorm/xorm"
"strings"
)
var CmdShell = &Command{
UsageLine: "shell driverName datasourceName",
Short: "a general shell to operate all kinds of database",
Long: `
UsageLine: "shell driverName datasourceName",
Short: "a general shell to operate all kinds of database",
Long: `
general database's shell for sqlite3, mysql, postgres.
driverName Database driver name, now supported four: mysql mymysql sqlite3 postgres
@ -18,14 +18,14 @@ general database's shell for sqlite3, mysql, postgres.
}
func init() {
CmdShell.Run = runShell
CmdShell.Flags = map[string]bool{}
CmdShell.Run = runShell
CmdShell.Flags = map[string]bool{}
}
var engine *xorm.Engine
func shellHelp() {
fmt.Println(`
fmt.Println(`
show tables show all tables
columns <table_name> show table's column info
indexes <table_name> show table's index info
@ -38,110 +38,110 @@ func shellHelp() {
}
func runShell(cmd *Command, args []string) {
if len(args) != 2 {
fmt.Println("params error, please see xorm help shell")
return
}
if len(args) != 2 {
fmt.Println("params error, please see xorm help shell")
return
}
var err error
engine, err = xorm.NewEngine(args[0], args[1])
if err != nil {
fmt.Println(err)
return
}
var err error
engine, err = xorm.NewEngine(args[0], args[1])
if err != nil {
fmt.Println(err)
return
}
err = engine.Ping()
if err != nil {
fmt.Println(err)
return
}
err = engine.Ping()
if err != nil {
fmt.Println(err)
return
}
var scmd string
fmt.Print("xorm$ ")
for {
var input string
_, err := fmt.Scan(&input)
if err != nil {
fmt.Println(err)
continue
}
if strings.ToLower(input) == "exit" {
fmt.Println("bye")
return
}
if !strings.HasSuffix(input, ";") {
scmd = scmd + " " + input
continue
}
scmd = scmd + " " + input
lcmd := strings.TrimSpace(strings.ToLower(scmd))
if strings.HasPrefix(lcmd, "select") {
res, err := engine.Query(scmd + "\n")
if err != nil {
fmt.Println(err)
} else {
if len(res) <= 0 {
fmt.Println("no records")
} else {
columns := make(map[string]int)
for k, _ := range res[0] {
columns[k] = len(k)
}
var scmd string
fmt.Print("xorm$ ")
for {
var input string
_, err := fmt.Scan(&input)
if err != nil {
fmt.Println(err)
continue
}
if strings.ToLower(input) == "exit" {
fmt.Println("bye")
return
}
if !strings.HasSuffix(input, ";") {
scmd = scmd + " " + input
continue
}
scmd = scmd + " " + input
lcmd := strings.TrimSpace(strings.ToLower(scmd))
if strings.HasPrefix(lcmd, "select") {
res, err := engine.Query(scmd + "\n")
if err != nil {
fmt.Println(err)
} else {
if len(res) <= 0 {
fmt.Println("no records")
} else {
columns := make(map[string]int)
for k, _ := range res[0] {
columns[k] = len(k)
}
for _, m := range res {
for k, s := range m {
l := len(string(s))
if l > columns[k] {
columns[k] = l
}
}
}
for _, m := range res {
for k, s := range m {
l := len(string(s))
if l > columns[k] {
columns[k] = l
}
}
}
var maxlen = 0
for _, l := range columns {
maxlen = maxlen + l + 3
}
maxlen = maxlen + 1
var maxlen = 0
for _, l := range columns {
maxlen = maxlen + l + 3
}
maxlen = maxlen + 1
fmt.Println(strings.Repeat("-", maxlen))
fmt.Print("|")
slice := make([]string, 0)
for k, l := range columns {
fmt.Print(" " + k + " ")
fmt.Print(strings.Repeat(" ", l-len(k)))
fmt.Print("|")
slice = append(slice, k)
}
fmt.Print("\n")
for _, r := range res {
fmt.Print("|")
for _, k := range slice {
fmt.Print(" " + string(r[k]) + " ")
fmt.Print(strings.Repeat(" ", columns[k]-len(string(r[k]))))
fmt.Print("|")
}
fmt.Print("\n")
}
fmt.Println(strings.Repeat("-", maxlen))
//fmt.Println(res)
}
}
} else if lcmd == "show tables;" {
/*tables, err := engine.DBMetas()
if err != nil {
fmt.Println(err)
} else {
fmt.Println(strings.Repeat("-", maxlen))
fmt.Print("|")
slice := make([]string, 0)
for k, l := range columns {
fmt.Print(" " + k + " ")
fmt.Print(strings.Repeat(" ", l-len(k)))
fmt.Print("|")
slice = append(slice, k)
}
fmt.Print("\n")
for _, r := range res {
fmt.Print("|")
for _, k := range slice {
fmt.Print(" " + string(r[k]) + " ")
fmt.Print(strings.Repeat(" ", columns[k]-len(string(r[k]))))
fmt.Print("|")
}
fmt.Print("\n")
}
fmt.Println(strings.Repeat("-", maxlen))
//fmt.Println(res)
}
}
} else if lcmd == "show tables;" {
/*tables, err := engine.DBMetas()
if err != nil {
fmt.Println(err)
} else {
}*/
} else {
cnt, err := engine.Exec(scmd)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%d records changed.\n", cnt)
}
}
scmd = ""
fmt.Print("xorm$ ")
}
}*/
} else {
cnt, err := engine.Exec(scmd)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%d records changed.\n", cnt)
}
}
scmd = ""
fmt.Print("xorm$ ")
}
}