mirror of
https://github.com/astaxie/beego.git
synced 2025-06-11 08:40:39 +00:00
Merge branch 'master' into master
This commit is contained in:
@ -150,7 +150,7 @@ func (d *commandSyncDb) Run() error {
|
||||
}
|
||||
|
||||
for _, fi := range mi.fields.fieldsDB {
|
||||
if _, ok := columns[fi.column]; ok == false {
|
||||
if _, ok := columns[fi.column]; !ok {
|
||||
fields = append(fields, fi)
|
||||
}
|
||||
}
|
||||
@ -175,7 +175,7 @@ func (d *commandSyncDb) Run() error {
|
||||
}
|
||||
|
||||
for _, idx := range indexes[mi.table] {
|
||||
if d.al.DbBaser.IndexExists(db, idx.Table, idx.Name) == false {
|
||||
if !d.al.DbBaser.IndexExists(db, idx.Table, idx.Name) {
|
||||
if !d.noInfo {
|
||||
fmt.Printf("create index `%s` for table `%s`\n", idx.Name, idx.Table)
|
||||
}
|
||||
|
@ -89,7 +89,7 @@ checkColumn:
|
||||
col = T["float64"]
|
||||
case TypeDecimalField:
|
||||
s := T["float64-decimal"]
|
||||
if strings.Index(s, "%d") == -1 {
|
||||
if !strings.Contains(s, "%d") {
|
||||
col = s
|
||||
} else {
|
||||
col = fmt.Sprintf(s, fi.digits, fi.decimals)
|
||||
@ -120,7 +120,7 @@ func getColumnAddQuery(al *alias, fi *fieldInfo) string {
|
||||
Q := al.DbBaser.TableQuote()
|
||||
typ := getColumnTyp(al, fi)
|
||||
|
||||
if fi.null == false {
|
||||
if !fi.null {
|
||||
typ += " " + "NOT NULL"
|
||||
}
|
||||
|
||||
@ -172,7 +172,7 @@ func getDbCreateSQL(al *alias) (sqls []string, tableIndexes map[string][]dbIndex
|
||||
} else {
|
||||
column += col
|
||||
|
||||
if fi.null == false {
|
||||
if !fi.null {
|
||||
column += " " + "NOT NULL"
|
||||
}
|
||||
|
||||
@ -192,7 +192,7 @@ func getDbCreateSQL(al *alias) (sqls []string, tableIndexes map[string][]dbIndex
|
||||
}
|
||||
}
|
||||
|
||||
if strings.Index(column, "%COL%") != -1 {
|
||||
if strings.Contains(column, "%COL%") {
|
||||
column = strings.Replace(column, "%COL%", fi.column, -1)
|
||||
}
|
||||
|
||||
|
45
orm/db.go
45
orm/db.go
@ -48,7 +48,7 @@ var (
|
||||
"lte": true,
|
||||
"eq": true,
|
||||
"nq": true,
|
||||
"ne": true,
|
||||
"ne": true,
|
||||
"startswith": true,
|
||||
"endswith": true,
|
||||
"istartswith": true,
|
||||
@ -87,7 +87,7 @@ func (d *dbBase) collectValues(mi *modelInfo, ind reflect.Value, cols []string,
|
||||
} else {
|
||||
panic(fmt.Errorf("wrong db field/column name `%s` for model `%s`", column, mi.fullName))
|
||||
}
|
||||
if fi.dbcol == false || fi.auto && skipAuto {
|
||||
if !fi.dbcol || fi.auto && skipAuto {
|
||||
continue
|
||||
}
|
||||
value, err := d.collectFieldValue(mi, fi, ind, insert, tz)
|
||||
@ -224,7 +224,7 @@ func (d *dbBase) collectFieldValue(mi *modelInfo, fi *fieldInfo, ind reflect.Val
|
||||
value = nil
|
||||
}
|
||||
}
|
||||
if fi.null == false && value == nil {
|
||||
if !fi.null && value == nil {
|
||||
return nil, fmt.Errorf("field `%s` cannot be NULL", fi.fullName)
|
||||
}
|
||||
}
|
||||
@ -271,7 +271,7 @@ func (d *dbBase) PrepareInsert(q dbQuerier, mi *modelInfo) (stmtQuerier, string,
|
||||
dbcols := make([]string, 0, len(mi.fields.dbcols))
|
||||
marks := make([]string, 0, len(mi.fields.dbcols))
|
||||
for _, fi := range mi.fields.fieldsDB {
|
||||
if fi.auto == false {
|
||||
if !fi.auto {
|
||||
dbcols = append(dbcols, fi.column)
|
||||
marks = append(marks, "?")
|
||||
}
|
||||
@ -326,7 +326,7 @@ func (d *dbBase) Read(q dbQuerier, mi *modelInfo, ind reflect.Value, tz *time.Lo
|
||||
} else {
|
||||
// default use pk value as where condtion.
|
||||
pkColumn, pkValue, ok := getExistPk(mi, ind)
|
||||
if ok == false {
|
||||
if !ok {
|
||||
return ErrMissPK
|
||||
}
|
||||
whereCols = []string{pkColumn}
|
||||
@ -507,10 +507,9 @@ func (d *dbBase) InsertOrUpdate(q dbQuerier, mi *modelInfo, ind reflect.Value, a
|
||||
case DRPostgres:
|
||||
if len(args) == 0 {
|
||||
return 0, fmt.Errorf("`%s` use InsertOrUpdate must have a conflict column", a.DriverName)
|
||||
} else {
|
||||
args0 = strings.ToLower(args[0])
|
||||
iouStr = fmt.Sprintf("ON CONFLICT (%s) DO UPDATE SET", args0)
|
||||
}
|
||||
args0 = strings.ToLower(args[0])
|
||||
iouStr = fmt.Sprintf("ON CONFLICT (%s) DO UPDATE SET", args0)
|
||||
default:
|
||||
return 0, fmt.Errorf("`%s` nonsupport InsertOrUpdate in beego", a.DriverName)
|
||||
}
|
||||
@ -592,7 +591,7 @@ func (d *dbBase) InsertOrUpdate(q dbQuerier, mi *modelInfo, ind reflect.Value, a
|
||||
row := q.QueryRow(query, values...)
|
||||
var id int64
|
||||
err = row.Scan(&id)
|
||||
if err.Error() == `pq: syntax error at or near "ON"` {
|
||||
if err != nil && err.Error() == `pq: syntax error at or near "ON"` {
|
||||
err = fmt.Errorf("postgres version must 9.5 or higher")
|
||||
}
|
||||
return id, err
|
||||
@ -601,7 +600,7 @@ func (d *dbBase) InsertOrUpdate(q dbQuerier, mi *modelInfo, ind reflect.Value, a
|
||||
// execute update sql dbQuerier with given struct reflect.Value.
|
||||
func (d *dbBase) Update(q dbQuerier, mi *modelInfo, ind reflect.Value, tz *time.Location, cols []string) (int64, error) {
|
||||
pkName, pkValue, ok := getExistPk(mi, ind)
|
||||
if ok == false {
|
||||
if !ok {
|
||||
return 0, ErrMissPK
|
||||
}
|
||||
|
||||
@ -654,7 +653,7 @@ func (d *dbBase) Delete(q dbQuerier, mi *modelInfo, ind reflect.Value, tz *time.
|
||||
} else {
|
||||
// default use pk value as where condtion.
|
||||
pkColumn, pkValue, ok := getExistPk(mi, ind)
|
||||
if ok == false {
|
||||
if !ok {
|
||||
return 0, ErrMissPK
|
||||
}
|
||||
whereCols = []string{pkColumn}
|
||||
@ -699,7 +698,7 @@ func (d *dbBase) UpdateBatch(q dbQuerier, qs *querySet, mi *modelInfo, cond *Con
|
||||
columns := make([]string, 0, len(params))
|
||||
values := make([]interface{}, 0, len(params))
|
||||
for col, val := range params {
|
||||
if fi, ok := mi.fields.GetByAny(col); ok == false || fi.dbcol == false {
|
||||
if fi, ok := mi.fields.GetByAny(col); !ok || !fi.dbcol {
|
||||
panic(fmt.Errorf("wrong field/column name `%s`", col))
|
||||
} else {
|
||||
columns = append(columns, fi.column)
|
||||
@ -834,7 +833,11 @@ func (d *dbBase) DeleteBatch(q dbQuerier, qs *querySet, mi *modelInfo, cond *Con
|
||||
if err := rs.Scan(&ref); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
args = append(args, reflect.ValueOf(ref).Interface())
|
||||
pkValue, err := d.convertValueFromDB(mi.fields.pk, reflect.ValueOf(ref).Interface(), tz)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
args = append(args, pkValue)
|
||||
cnt++
|
||||
}
|
||||
|
||||
@ -929,7 +932,7 @@ func (d *dbBase) ReadBatch(q dbQuerier, qs *querySet, mi *modelInfo, cond *Condi
|
||||
if hasRel {
|
||||
for _, fi := range mi.fields.fieldsDB {
|
||||
if fi.fieldType&IsRelField > 0 {
|
||||
if maps[fi.column] == false {
|
||||
if !maps[fi.column] {
|
||||
tCols = append(tCols, fi.column)
|
||||
}
|
||||
}
|
||||
@ -987,7 +990,7 @@ func (d *dbBase) ReadBatch(q dbQuerier, qs *querySet, mi *modelInfo, cond *Condi
|
||||
|
||||
var cnt int64
|
||||
for rs.Next() {
|
||||
if one && cnt == 0 || one == false {
|
||||
if one && cnt == 0 || !one {
|
||||
if err := rs.Scan(refs...); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@ -1067,7 +1070,7 @@ func (d *dbBase) ReadBatch(q dbQuerier, qs *querySet, mi *modelInfo, cond *Condi
|
||||
cnt++
|
||||
}
|
||||
|
||||
if one == false {
|
||||
if !one {
|
||||
if cnt > 0 {
|
||||
ind.Set(slice)
|
||||
} else {
|
||||
@ -1110,7 +1113,7 @@ func (d *dbBase) Count(q dbQuerier, qs *querySet, mi *modelInfo, cond *Condition
|
||||
|
||||
// generate sql with replacing operator string placeholders and replaced values.
|
||||
func (d *dbBase) GenerateOperatorSQL(mi *modelInfo, fi *fieldInfo, operator string, args []interface{}, tz *time.Location) (string, []interface{}) {
|
||||
sql := ""
|
||||
var sql string
|
||||
params := getFlatParams(fi, args, tz)
|
||||
|
||||
if len(params) == 0 {
|
||||
@ -1357,7 +1360,7 @@ end:
|
||||
func (d *dbBase) setFieldValue(fi *fieldInfo, value interface{}, field reflect.Value) (interface{}, error) {
|
||||
|
||||
fieldType := fi.fieldType
|
||||
isNative := fi.isFielder == false
|
||||
isNative := !fi.isFielder
|
||||
|
||||
setValue:
|
||||
switch {
|
||||
@ -1533,7 +1536,7 @@ setValue:
|
||||
}
|
||||
}
|
||||
|
||||
if isNative == false {
|
||||
if !isNative {
|
||||
fd := field.Addr().Interface().(Fielder)
|
||||
err := fd.SetRaw(value)
|
||||
if err != nil {
|
||||
@ -1594,7 +1597,7 @@ func (d *dbBase) ReadValues(q dbQuerier, qs *querySet, mi *modelInfo, cond *Cond
|
||||
infos = make([]*fieldInfo, 0, len(exprs))
|
||||
for _, ex := range exprs {
|
||||
index, name, fi, suc := tables.parseExprs(mi, strings.Split(ex, ExprSep))
|
||||
if suc == false {
|
||||
if !suc {
|
||||
panic(fmt.Errorf("unknown field/column name `%s`", ex))
|
||||
}
|
||||
cols = append(cols, fmt.Sprintf("%s.%s%s%s %s%s%s", index, Q, fi.column, Q, Q, name, Q))
|
||||
@ -1733,7 +1736,7 @@ func (d *dbBase) TableQuote() string {
|
||||
return "`"
|
||||
}
|
||||
|
||||
// replace value placeholer in parametered sql string.
|
||||
// replace value placeholder in parametered sql string.
|
||||
func (d *dbBase) ReplaceMarks(query *string) {
|
||||
// default use `?` as mark, do nothing
|
||||
}
|
||||
|
@ -60,6 +60,8 @@ var (
|
||||
"sqlite3": DRSqlite,
|
||||
"tidb": DRTiDB,
|
||||
"oracle": DROracle,
|
||||
"oci8": DROracle, // github.com/mattn/go-oci8
|
||||
"ora": DROracle, //https://github.com/rana/ora
|
||||
}
|
||||
dbBasers = map[DriverType]dbBaser{
|
||||
DRMySQL: newdbBaseMysql(),
|
||||
@ -186,7 +188,7 @@ func addAliasWthDB(aliasName, driverName string, db *sql.DB) (*alias, error) {
|
||||
return nil, fmt.Errorf("register db Ping `%s`, %s", aliasName, err.Error())
|
||||
}
|
||||
|
||||
if dataBaseCache.add(aliasName, al) == false {
|
||||
if !dataBaseCache.add(aliasName, al) {
|
||||
return nil, fmt.Errorf("DataBase alias name `%s` already registered, cannot reuse", aliasName)
|
||||
}
|
||||
|
||||
@ -244,11 +246,11 @@ end:
|
||||
|
||||
// RegisterDriver Register a database driver use specify driver name, this can be definition the driver is which database type.
|
||||
func RegisterDriver(driverName string, typ DriverType) error {
|
||||
if t, ok := drivers[driverName]; ok == false {
|
||||
if t, ok := drivers[driverName]; !ok {
|
||||
drivers[driverName] = typ
|
||||
} else {
|
||||
if t != typ {
|
||||
return fmt.Errorf("driverName `%s` db driver already registered and is other type\n", driverName)
|
||||
return fmt.Errorf("driverName `%s` db driver already registered and is other type", driverName)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@ -259,7 +261,7 @@ func SetDataBaseTZ(aliasName string, tz *time.Location) error {
|
||||
if al, ok := dataBaseCache.get(aliasName); ok {
|
||||
al.TZ = tz
|
||||
} else {
|
||||
return fmt.Errorf("DataBase alias name `%s` not registered\n", aliasName)
|
||||
return fmt.Errorf("DataBase alias name `%s` not registered", aliasName)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@ -294,5 +296,5 @@ func GetDB(aliasNames ...string) (*sql.DB, error) {
|
||||
if ok {
|
||||
return al.DB, nil
|
||||
}
|
||||
return nil, fmt.Errorf("DataBase of alias name `%s` not found\n", name)
|
||||
return nil, fmt.Errorf("DataBase of alias name `%s` not found", name)
|
||||
}
|
||||
|
@ -103,8 +103,7 @@ func (d *dbBaseMysql) IndexExists(db dbQuerier, table string, name string) bool
|
||||
// If no will insert
|
||||
// Add "`" for mysql sql building
|
||||
func (d *dbBaseMysql) InsertOrUpdate(q dbQuerier, mi *modelInfo, ind reflect.Value, a *alias, args ...string) (int64, error) {
|
||||
|
||||
iouStr := ""
|
||||
var iouStr string
|
||||
argsMap := map[string]string{}
|
||||
|
||||
iouStr = "ON DUPLICATE KEY UPDATE"
|
||||
|
@ -94,3 +94,43 @@ func (d *dbBaseOracle) IndexExists(db dbQuerier, table string, name string) bool
|
||||
row.Scan(&cnt)
|
||||
return cnt > 0
|
||||
}
|
||||
|
||||
// execute insert sql with given struct and given values.
|
||||
// insert the given values, not the field values in struct.
|
||||
func (d *dbBaseOracle) InsertValue(q dbQuerier, mi *modelInfo, isMulti bool, names []string, values []interface{}) (int64, error) {
|
||||
Q := d.ins.TableQuote()
|
||||
|
||||
marks := make([]string, len(names))
|
||||
for i := range marks {
|
||||
marks[i] = ":" + names[i]
|
||||
}
|
||||
|
||||
sep := fmt.Sprintf("%s, %s", Q, Q)
|
||||
qmarks := strings.Join(marks, ", ")
|
||||
columns := strings.Join(names, sep)
|
||||
|
||||
multi := len(values) / len(names)
|
||||
|
||||
if isMulti {
|
||||
qmarks = strings.Repeat(qmarks+"), (", multi-1) + qmarks
|
||||
}
|
||||
|
||||
query := fmt.Sprintf("INSERT INTO %s%s%s (%s%s%s) VALUES (%s)", Q, mi.table, Q, Q, columns, Q, qmarks)
|
||||
|
||||
d.ins.ReplaceMarks(&query)
|
||||
|
||||
if isMulti || !d.ins.HasReturningID(mi, &query) {
|
||||
res, err := q.Exec(query, values...)
|
||||
if err == nil {
|
||||
if isMulti {
|
||||
return res.RowsAffected()
|
||||
}
|
||||
return res.LastInsertId()
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
row := q.QueryRow(query, values...)
|
||||
var id int64
|
||||
err := row.Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
@ -134,7 +134,7 @@ func (d *dbBaseSqlite) IndexExists(db dbQuerier, table string, name string) bool
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var tmp, index sql.NullString
|
||||
rows.Scan(&tmp, &index, &tmp)
|
||||
rows.Scan(&tmp, &index, &tmp, &tmp, &tmp)
|
||||
if name == index.String {
|
||||
return true
|
||||
}
|
||||
|
@ -63,7 +63,7 @@ func (t *dbTables) set(names []string, mi *modelInfo, fi *fieldInfo, inner bool)
|
||||
// add table info to collection.
|
||||
func (t *dbTables) add(names []string, mi *modelInfo, fi *fieldInfo, inner bool) (*dbTable, bool) {
|
||||
name := strings.Join(names, ExprSep)
|
||||
if _, ok := t.tablesM[name]; ok == false {
|
||||
if _, ok := t.tablesM[name]; !ok {
|
||||
i := len(t.tables) + 1
|
||||
jt := &dbTable{i, fmt.Sprintf("T%d", i), name, names, false, inner, mi, fi, nil}
|
||||
t.tablesM[name] = jt
|
||||
@ -261,7 +261,7 @@ loopFor:
|
||||
fiN, okN = mmi.fields.GetByAny(exprs[i+1])
|
||||
}
|
||||
|
||||
if isRel && (fi.mi.isThrough == false || num != i) {
|
||||
if isRel && (!fi.mi.isThrough || num != i) {
|
||||
if fi.null || t.skipEnd {
|
||||
inner = false
|
||||
}
|
||||
@ -364,7 +364,7 @@ func (t *dbTables) getCondSQL(cond *Condition, sub bool, tz *time.Location) (whe
|
||||
}
|
||||
|
||||
index, _, fi, suc := t.parseExprs(mi, exprs)
|
||||
if suc == false {
|
||||
if !suc {
|
||||
panic(fmt.Errorf("unknown field/column name `%s`", strings.Join(p.exprs, ExprSep)))
|
||||
}
|
||||
|
||||
@ -383,7 +383,7 @@ func (t *dbTables) getCondSQL(cond *Condition, sub bool, tz *time.Location) (whe
|
||||
}
|
||||
}
|
||||
|
||||
if sub == false && where != "" {
|
||||
if !sub && where != "" {
|
||||
where = "WHERE " + where
|
||||
}
|
||||
|
||||
@ -403,7 +403,7 @@ func (t *dbTables) getGroupSQL(groups []string) (groupSQL string) {
|
||||
exprs := strings.Split(group, ExprSep)
|
||||
|
||||
index, _, fi, suc := t.parseExprs(t.mi, exprs)
|
||||
if suc == false {
|
||||
if !suc {
|
||||
panic(fmt.Errorf("unknown field/column name `%s`", strings.Join(exprs, ExprSep)))
|
||||
}
|
||||
|
||||
@ -432,7 +432,7 @@ func (t *dbTables) getOrderSQL(orders []string) (orderSQL string) {
|
||||
exprs := strings.Split(order, ExprSep)
|
||||
|
||||
index, _, fi, suc := t.parseExprs(t.mi, exprs)
|
||||
if suc == false {
|
||||
if !suc {
|
||||
panic(fmt.Errorf("unknown field/column name `%s`", strings.Join(exprs, ExprSep)))
|
||||
}
|
||||
|
||||
|
@ -41,6 +41,8 @@ func getExistPk(mi *modelInfo, ind reflect.Value) (column string, value interfac
|
||||
vu := v.Int()
|
||||
exist = true
|
||||
value = vu
|
||||
} else if fi.fieldType&IsRelField > 0 {
|
||||
_, value, exist = getExistPk(fi.relModelInfo, reflect.Indirect(v))
|
||||
} else {
|
||||
vu := v.String()
|
||||
exist = vu != ""
|
||||
|
@ -75,7 +75,7 @@ func registerModel(PrefixOrSuffix string, model interface{}, isPrefix bool) {
|
||||
}
|
||||
|
||||
if mi.fields.pk == nil {
|
||||
fmt.Printf("<orm.RegisterModel> `%s` need a primary key field, default use 'id' if not set\n", name)
|
||||
fmt.Printf("<orm.RegisterModel> `%s` needs a primary key field, default is to use 'id' if not set\n", name)
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
@ -117,7 +117,7 @@ func bootStrap() {
|
||||
name := getFullName(elm)
|
||||
mii, ok := modelCache.getByFullName(name)
|
||||
if !ok || mii.pkg != elm.PkgPath() {
|
||||
err = fmt.Errorf("can not found rel in field `%s`, `%s` may be miss register", fi.fullName, elm.String())
|
||||
err = fmt.Errorf("can not find rel in field `%s`, `%s` may be miss register", fi.fullName, elm.String())
|
||||
goto end
|
||||
}
|
||||
fi.relModelInfo = mii
|
||||
@ -128,7 +128,7 @@ func bootStrap() {
|
||||
if i := strings.LastIndex(fi.relThrough, "."); i != -1 && len(fi.relThrough) > (i+1) {
|
||||
pn := fi.relThrough[:i]
|
||||
rmi, ok := modelCache.getByFullName(fi.relThrough)
|
||||
if ok == false || pn != rmi.pkg {
|
||||
if !ok || pn != rmi.pkg {
|
||||
err = fmt.Errorf("field `%s` wrong rel_through value `%s` cannot find table", fi.fullName, fi.relThrough)
|
||||
goto end
|
||||
}
|
||||
@ -171,7 +171,7 @@ func bootStrap() {
|
||||
break
|
||||
}
|
||||
}
|
||||
if inModel == false {
|
||||
if !inModel {
|
||||
rmi := fi.relModelInfo
|
||||
ffi := new(fieldInfo)
|
||||
ffi.name = mi.name
|
||||
@ -185,7 +185,7 @@ func bootStrap() {
|
||||
} else {
|
||||
ffi.fieldType = RelReverseMany
|
||||
}
|
||||
if rmi.fields.Add(ffi) == false {
|
||||
if !rmi.fields.Add(ffi) {
|
||||
added := false
|
||||
for cnt := 0; cnt < 5; cnt++ {
|
||||
ffi.name = fmt.Sprintf("%s%d", mi.name, cnt)
|
||||
@ -195,7 +195,7 @@ func bootStrap() {
|
||||
break
|
||||
}
|
||||
}
|
||||
if added == false {
|
||||
if !added {
|
||||
panic(fmt.Errorf("cannot generate auto reverse field info `%s` to `%s`", fi.fullName, ffi.fullName))
|
||||
}
|
||||
}
|
||||
@ -248,7 +248,7 @@ func bootStrap() {
|
||||
break mForA
|
||||
}
|
||||
}
|
||||
if found == false {
|
||||
if !found {
|
||||
err = fmt.Errorf("reverse field `%s` not found in model `%s`", fi.fullName, fi.relModelInfo.fullName)
|
||||
goto end
|
||||
}
|
||||
@ -267,7 +267,7 @@ func bootStrap() {
|
||||
break mForB
|
||||
}
|
||||
}
|
||||
if found == false {
|
||||
if !found {
|
||||
mForC:
|
||||
for _, ffi := range fi.relModelInfo.fields.fieldsByType[RelManyToMany] {
|
||||
conditions := fi.relThrough != "" && fi.relThrough == ffi.relThrough ||
|
||||
@ -287,7 +287,7 @@ func bootStrap() {
|
||||
}
|
||||
}
|
||||
}
|
||||
if found == false {
|
||||
if !found {
|
||||
err = fmt.Errorf("reverse field for `%s` not found in model `%s`", fi.fullName, fi.relModelInfo.fullName)
|
||||
goto end
|
||||
}
|
||||
|
@ -47,7 +47,7 @@ func (f *fields) Add(fi *fieldInfo) (added bool) {
|
||||
} else {
|
||||
return
|
||||
}
|
||||
if _, ok := f.fieldsByType[fi.fieldType]; ok == false {
|
||||
if _, ok := f.fieldsByType[fi.fieldType]; !ok {
|
||||
f.fieldsByType[fi.fieldType] = make([]*fieldInfo, 0)
|
||||
}
|
||||
f.fieldsByType[fi.fieldType] = append(f.fieldsByType[fi.fieldType], fi)
|
||||
@ -334,12 +334,12 @@ checkType:
|
||||
switch onDelete {
|
||||
case odCascade, odDoNothing:
|
||||
case odSetDefault:
|
||||
if initial.Exist() == false {
|
||||
if !initial.Exist() {
|
||||
err = errors.New("on_delete: set_default need set field a default value")
|
||||
goto end
|
||||
}
|
||||
case odSetNULL:
|
||||
if fi.null == false {
|
||||
if !fi.null {
|
||||
err = errors.New("on_delete: set_null need set field null")
|
||||
goto end
|
||||
}
|
||||
|
@ -78,7 +78,7 @@ func addModelFields(mi *modelInfo, ind reflect.Value, mName string, index []int)
|
||||
fi.fieldIndex = append(index, i)
|
||||
fi.mi = mi
|
||||
fi.inModel = true
|
||||
if mi.fields.Add(fi) == false {
|
||||
if !mi.fields.Add(fi) {
|
||||
err = fmt.Errorf("duplicate column name: %s", fi.column)
|
||||
break
|
||||
}
|
||||
|
@ -406,6 +406,11 @@ type UintPk struct {
|
||||
Name string
|
||||
}
|
||||
|
||||
type PtrPk struct {
|
||||
ID *IntegerPk `orm:"pk;rel(one)"`
|
||||
Positive bool
|
||||
}
|
||||
|
||||
var DBARGS = struct {
|
||||
Driver string
|
||||
Source string
|
||||
|
32
orm/orm.go
32
orm/orm.go
@ -107,7 +107,7 @@ func (o *orm) getMiInd(md interface{}, needPtr bool) (mi *modelInfo, ind reflect
|
||||
if mi, ok := modelCache.getByFullName(name); ok {
|
||||
return mi, ind
|
||||
}
|
||||
panic(fmt.Errorf("<Ormer> table: `%s` not found, maybe not RegisterModel", name))
|
||||
panic(fmt.Errorf("<Ormer> table: `%s` not found, make sure it was registered with `RegisterModel()`", name))
|
||||
}
|
||||
|
||||
// get field info from model info by given field name
|
||||
@ -122,21 +122,13 @@ func (o *orm) getFieldInfo(mi *modelInfo, name string) *fieldInfo {
|
||||
// read data to model
|
||||
func (o *orm) Read(md interface{}, cols ...string) error {
|
||||
mi, ind := o.getMiInd(md, true)
|
||||
err := o.alias.DbBaser.Read(o.db, mi, ind, o.alias.TZ, cols, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
return o.alias.DbBaser.Read(o.db, mi, ind, o.alias.TZ, cols, false)
|
||||
}
|
||||
|
||||
// read data to model, like Read(), but use "SELECT FOR UPDATE" form
|
||||
func (o *orm) ReadForUpdate(md interface{}, cols ...string) error {
|
||||
mi, ind := o.getMiInd(md, true)
|
||||
err := o.alias.DbBaser.Read(o.db, mi, ind, o.alias.TZ, cols, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
return o.alias.DbBaser.Read(o.db, mi, ind, o.alias.TZ, cols, true)
|
||||
}
|
||||
|
||||
// Try to read a row from the database, or insert one if it doesn't exist
|
||||
@ -153,6 +145,8 @@ func (o *orm) ReadOrCreate(md interface{}, col1 string, cols ...string) (bool, i
|
||||
id, vid := int64(0), ind.FieldByIndex(mi.fields.pk.fieldIndex)
|
||||
if mi.fields.pk.fieldType&IsPositiveIntegerField > 0 {
|
||||
id = int64(vid.Uint())
|
||||
} else if mi.fields.pk.rel {
|
||||
return o.ReadOrCreate(vid.Interface(), mi.fields.pk.relModelInfo.fields.pk.name)
|
||||
} else {
|
||||
id = vid.Int()
|
||||
}
|
||||
@ -236,15 +230,11 @@ func (o *orm) InsertOrUpdate(md interface{}, colConflitAndArgs ...string) (int64
|
||||
// cols set the columns those want to update.
|
||||
func (o *orm) Update(md interface{}, cols ...string) (int64, error) {
|
||||
mi, ind := o.getMiInd(md, true)
|
||||
num, err := o.alias.DbBaser.Update(o.db, mi, ind, o.alias.TZ, cols)
|
||||
if err != nil {
|
||||
return num, err
|
||||
}
|
||||
return num, nil
|
||||
return o.alias.DbBaser.Update(o.db, mi, ind, o.alias.TZ, cols)
|
||||
}
|
||||
|
||||
// delete model in database
|
||||
// cols shows the delete conditions values read from. deafult is pk
|
||||
// cols shows the delete conditions values read from. default is pk
|
||||
func (o *orm) Delete(md interface{}, cols ...string) (int64, error) {
|
||||
mi, ind := o.getMiInd(md, true)
|
||||
num, err := o.alias.DbBaser.Delete(o.db, mi, ind, o.alias.TZ, cols)
|
||||
@ -359,7 +349,7 @@ func (o *orm) queryRelated(md interface{}, name string) (*modelInfo, *fieldInfo,
|
||||
fi := o.getFieldInfo(mi, name)
|
||||
|
||||
_, _, exist := getExistPk(mi, ind)
|
||||
if exist == false {
|
||||
if !exist {
|
||||
panic(ErrMissPK)
|
||||
}
|
||||
|
||||
@ -430,7 +420,7 @@ func (o *orm) getRelQs(md interface{}, mi *modelInfo, fi *fieldInfo) *querySet {
|
||||
// table name can be string or struct.
|
||||
// e.g. QueryTable("user"), QueryTable(&user{}) or QueryTable((*User)(nil)),
|
||||
func (o *orm) QueryTable(ptrStructOrTableName interface{}) (qs QuerySeter) {
|
||||
name := ""
|
||||
var name string
|
||||
if table, ok := ptrStructOrTableName.(string); ok {
|
||||
name = snakeString(table)
|
||||
if mi, ok := modelCache.get(name); ok {
|
||||
@ -487,7 +477,7 @@ func (o *orm) Begin() error {
|
||||
|
||||
// commit transaction
|
||||
func (o *orm) Commit() error {
|
||||
if o.isTx == false {
|
||||
if !o.isTx {
|
||||
return ErrTxDone
|
||||
}
|
||||
err := o.db.(txEnder).Commit()
|
||||
@ -502,7 +492,7 @@ func (o *orm) Commit() error {
|
||||
|
||||
// rollback transaction
|
||||
func (o *orm) Rollback() error {
|
||||
if o.isTx == false {
|
||||
if !o.isTx {
|
||||
return ErrTxDone
|
||||
}
|
||||
err := o.db.(txEnder).Rollback()
|
||||
|
@ -72,7 +72,7 @@ func (o *queryM2M) Add(mds ...interface{}) (int64, error) {
|
||||
}
|
||||
|
||||
_, v1, exist := getExistPk(o.mi, o.ind)
|
||||
if exist == false {
|
||||
if !exist {
|
||||
panic(ErrMissPK)
|
||||
}
|
||||
|
||||
@ -87,7 +87,7 @@ func (o *queryM2M) Add(mds ...interface{}) (int64, error) {
|
||||
v2 = ind.Interface()
|
||||
} else {
|
||||
_, v2, exist = getExistPk(fi.relModelInfo, ind)
|
||||
if exist == false {
|
||||
if !exist {
|
||||
panic(ErrMissPK)
|
||||
}
|
||||
}
|
||||
@ -104,11 +104,7 @@ func (o *queryM2M) Remove(mds ...interface{}) (int64, error) {
|
||||
fi := o.fi
|
||||
qs := o.qs.Filter(fi.reverseFieldInfo.name, o.md)
|
||||
|
||||
nums, err := qs.Filter(fi.reverseFieldInfoTwo.name+ExprSep+"in", mds).Delete()
|
||||
if err != nil {
|
||||
return nums, err
|
||||
}
|
||||
return nums, nil
|
||||
return qs.Filter(fi.reverseFieldInfoTwo.name+ExprSep+"in", mds).Delete()
|
||||
}
|
||||
|
||||
// check model is existed in relationship of origin model
|
||||
|
@ -153,6 +153,11 @@ func (o querySet) SetCond(cond *Condition) QuerySeter {
|
||||
return &o
|
||||
}
|
||||
|
||||
// get condition from QuerySeter
|
||||
func (o querySet) GetCond() *Condition {
|
||||
return o.cond
|
||||
}
|
||||
|
||||
// return QuerySeter execution result number
|
||||
func (o *querySet) Count() (int64, error) {
|
||||
return o.orm.alias.DbBaser.Count(o.orm.db, o, o.mi, o.cond, o.orm.alias.TZ)
|
||||
|
@ -493,19 +493,33 @@ func (o *rawSet) QueryRows(containers ...interface{}) (int64, error) {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for i := 0; i < ind.NumField(); i++ {
|
||||
f := ind.Field(i)
|
||||
fe := ind.Type().Field(i)
|
||||
_, tags := parseStructTag(fe.Tag.Get(defaultStructTagName))
|
||||
var col string
|
||||
if col = tags["column"]; col == "" {
|
||||
col = snakeString(fe.Name)
|
||||
}
|
||||
if v, ok := columnsMp[col]; ok {
|
||||
value := reflect.ValueOf(v).Elem().Interface()
|
||||
o.setFieldValue(f, value)
|
||||
// define recursive function
|
||||
var recursiveSetField func(rv reflect.Value)
|
||||
recursiveSetField = func(rv reflect.Value) {
|
||||
for i := 0; i < rv.NumField(); i++ {
|
||||
f := rv.Field(i)
|
||||
fe := rv.Type().Field(i)
|
||||
|
||||
// check if the field is a Struct
|
||||
// recursive the Struct type
|
||||
if fe.Type.Kind() == reflect.Struct {
|
||||
recursiveSetField(f)
|
||||
}
|
||||
|
||||
_, tags := parseStructTag(fe.Tag.Get(defaultStructTagName))
|
||||
var col string
|
||||
if col = tags["column"]; col == "" {
|
||||
col = snakeString(fe.Name)
|
||||
}
|
||||
if v, ok := columnsMp[col]; ok {
|
||||
value := reflect.ValueOf(v).Elem().Interface()
|
||||
o.setFieldValue(f, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// init call the recursive function
|
||||
recursiveSetField(ind)
|
||||
}
|
||||
|
||||
if eTyps[0].Kind() == reflect.Ptr {
|
||||
@ -671,7 +685,7 @@ func (o *rawSet) queryRowsTo(container interface{}, keyCol, valueCol string) (in
|
||||
ind *reflect.Value
|
||||
)
|
||||
|
||||
typ := 0
|
||||
var typ int
|
||||
switch container.(type) {
|
||||
case *Params:
|
||||
typ = 1
|
||||
|
@ -93,14 +93,14 @@ wrongArg:
|
||||
}
|
||||
|
||||
func AssertIs(a interface{}, args ...interface{}) error {
|
||||
if ok, err := ValuesCompare(true, a, args...); ok == false {
|
||||
if ok, err := ValuesCompare(true, a, args...); !ok {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func AssertNot(a interface{}, args ...interface{}) error {
|
||||
if ok, err := ValuesCompare(false, a, args...); ok == false {
|
||||
if ok, err := ValuesCompare(false, a, args...); !ok {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
@ -135,7 +135,7 @@ func getCaller(skip int) string {
|
||||
if i := strings.LastIndex(funName, "."); i > -1 {
|
||||
funName = funName[i+1:]
|
||||
}
|
||||
return fmt.Sprintf("%s:%d: \n%s", fn, line, strings.Join(codes, "\n"))
|
||||
return fmt.Sprintf("%s:%s:%d: \n%s", fn, funName, line, strings.Join(codes, "\n"))
|
||||
}
|
||||
|
||||
func throwFail(t *testing.T, err error, args ...interface{}) {
|
||||
@ -193,6 +193,7 @@ func TestSyncDb(t *testing.T) {
|
||||
RegisterModel(new(InLineOneToOne))
|
||||
RegisterModel(new(IntegerPk))
|
||||
RegisterModel(new(UintPk))
|
||||
RegisterModel(new(PtrPk))
|
||||
|
||||
err := RunSyncdb("default", true, Debug)
|
||||
throwFail(t, err)
|
||||
@ -216,6 +217,7 @@ func TestRegisterModels(t *testing.T) {
|
||||
RegisterModel(new(InLineOneToOne))
|
||||
RegisterModel(new(IntegerPk))
|
||||
RegisterModel(new(UintPk))
|
||||
RegisterModel(new(PtrPk))
|
||||
|
||||
BootStrap()
|
||||
|
||||
@ -1012,6 +1014,8 @@ func TestAll(t *testing.T) {
|
||||
var users3 []*User
|
||||
qs = dORM.QueryTable("user")
|
||||
num, err = qs.Filter("user_name", "nothing").All(&users3)
|
||||
throwFailNow(t, err)
|
||||
throwFailNow(t, AssertIs(num, 0))
|
||||
throwFailNow(t, AssertIs(users3 == nil, false))
|
||||
}
|
||||
|
||||
@ -1136,6 +1140,7 @@ func TestRelatedSel(t *testing.T) {
|
||||
}
|
||||
|
||||
err = qs.Filter("user_name", "nobody").RelatedSel("profile").One(&user)
|
||||
throwFail(t, err)
|
||||
throwFail(t, AssertIs(num, 1))
|
||||
throwFail(t, AssertIs(user.Profile, nil))
|
||||
|
||||
@ -1244,20 +1249,24 @@ func TestLoadRelated(t *testing.T) {
|
||||
|
||||
num, err = dORM.LoadRelated(&user, "Posts", true)
|
||||
throwFailNow(t, err)
|
||||
throwFailNow(t, AssertIs(num, 2))
|
||||
throwFailNow(t, AssertIs(len(user.Posts), 2))
|
||||
throwFailNow(t, AssertIs(user.Posts[0].User.UserName, "astaxie"))
|
||||
|
||||
num, err = dORM.LoadRelated(&user, "Posts", true, 1)
|
||||
throwFailNow(t, err)
|
||||
throwFailNow(t, AssertIs(num, 1))
|
||||
throwFailNow(t, AssertIs(len(user.Posts), 1))
|
||||
|
||||
num, err = dORM.LoadRelated(&user, "Posts", true, 0, 0, "-Id")
|
||||
throwFailNow(t, err)
|
||||
throwFailNow(t, AssertIs(num, 2))
|
||||
throwFailNow(t, AssertIs(len(user.Posts), 2))
|
||||
throwFailNow(t, AssertIs(user.Posts[0].Title, "Formatting"))
|
||||
|
||||
num, err = dORM.LoadRelated(&user, "Posts", true, 1, 1, "Id")
|
||||
throwFailNow(t, err)
|
||||
throwFailNow(t, AssertIs(num, 1))
|
||||
throwFailNow(t, AssertIs(len(user.Posts), 1))
|
||||
throwFailNow(t, AssertIs(user.Posts[0].Title, "Formatting"))
|
||||
|
||||
@ -1652,6 +1661,13 @@ func TestRawQueryRow(t *testing.T) {
|
||||
throwFail(t, AssertIs(pid, nil))
|
||||
}
|
||||
|
||||
// user_profile table
|
||||
type userProfile struct {
|
||||
User
|
||||
Age int
|
||||
Money float64
|
||||
}
|
||||
|
||||
func TestQueryRows(t *testing.T) {
|
||||
Q := dDbBaser.TableQuote()
|
||||
|
||||
@ -1722,6 +1738,19 @@ func TestQueryRows(t *testing.T) {
|
||||
throwFailNow(t, AssertIs(usernames[1], "astaxie"))
|
||||
throwFailNow(t, AssertIs(ids[2], 4))
|
||||
throwFailNow(t, AssertIs(usernames[2], "nobody"))
|
||||
|
||||
//test query rows by nested struct
|
||||
var l []userProfile
|
||||
query = fmt.Sprintf("SELECT * FROM %suser_profile%s LEFT JOIN %suser%s ON %suser_profile%s.%sid%s = %suser%s.%sid%s", Q, Q, Q, Q, Q, Q, Q, Q, Q, Q, Q, Q)
|
||||
num, err = dORM.Raw(query).QueryRows(&l)
|
||||
throwFailNow(t, err)
|
||||
throwFailNow(t, AssertIs(num, 2))
|
||||
throwFailNow(t, AssertIs(len(l), 2))
|
||||
throwFailNow(t, AssertIs(l[0].UserName, "slene"))
|
||||
throwFailNow(t, AssertIs(l[0].Age, 28))
|
||||
throwFailNow(t, AssertIs(l[1].UserName, "astaxie"))
|
||||
throwFailNow(t, AssertIs(l[1].Age, 30))
|
||||
|
||||
}
|
||||
|
||||
func TestRawValues(t *testing.T) {
|
||||
@ -1974,6 +2003,7 @@ func TestReadOrCreate(t *testing.T) {
|
||||
created, pk, err := dORM.ReadOrCreate(u, "UserName")
|
||||
throwFail(t, err)
|
||||
throwFail(t, AssertIs(created, true))
|
||||
throwFail(t, AssertIs(u.ID, pk))
|
||||
throwFail(t, AssertIs(u.UserName, "Kyle"))
|
||||
throwFail(t, AssertIs(u.Email, "kylemcc@gmail.com"))
|
||||
throwFail(t, AssertIs(u.Password, "other_pass"))
|
||||
@ -2128,13 +2158,13 @@ func TestUintPk(t *testing.T) {
|
||||
Name: name,
|
||||
}
|
||||
|
||||
created, pk, err := dORM.ReadOrCreate(u, "ID")
|
||||
created, _, err := dORM.ReadOrCreate(u, "ID")
|
||||
throwFail(t, err)
|
||||
throwFail(t, AssertIs(created, true))
|
||||
throwFail(t, AssertIs(u.Name, name))
|
||||
|
||||
nu := &UintPk{ID: 8}
|
||||
created, pk, err = dORM.ReadOrCreate(nu, "ID")
|
||||
created, pk, err := dORM.ReadOrCreate(nu, "ID")
|
||||
throwFail(t, err)
|
||||
throwFail(t, AssertIs(created, false))
|
||||
throwFail(t, AssertIs(nu.ID, u.ID))
|
||||
@ -2144,6 +2174,48 @@ func TestUintPk(t *testing.T) {
|
||||
dORM.Delete(u)
|
||||
}
|
||||
|
||||
func TestPtrPk(t *testing.T) {
|
||||
parent := &IntegerPk{ID: 10, Value: "10"}
|
||||
|
||||
id, _ := dORM.Insert(parent)
|
||||
if !IsMysql {
|
||||
// MySql does not support last_insert_id in this case: see #2382
|
||||
throwFail(t, AssertIs(id, 10))
|
||||
}
|
||||
|
||||
ptr := PtrPk{ID: parent, Positive: true}
|
||||
num, err := dORM.InsertMulti(2, []PtrPk{ptr})
|
||||
throwFail(t, err)
|
||||
throwFail(t, AssertIs(num, 1))
|
||||
throwFail(t, AssertIs(ptr.ID, parent))
|
||||
|
||||
nptr := &PtrPk{ID: parent}
|
||||
created, pk, err := dORM.ReadOrCreate(nptr, "ID")
|
||||
throwFail(t, err)
|
||||
throwFail(t, AssertIs(created, false))
|
||||
throwFail(t, AssertIs(pk, 10))
|
||||
throwFail(t, AssertIs(nptr.ID, parent))
|
||||
throwFail(t, AssertIs(nptr.Positive, true))
|
||||
|
||||
nptr = &PtrPk{Positive: true}
|
||||
created, pk, err = dORM.ReadOrCreate(nptr, "Positive")
|
||||
throwFail(t, err)
|
||||
throwFail(t, AssertIs(created, false))
|
||||
throwFail(t, AssertIs(pk, 10))
|
||||
throwFail(t, AssertIs(nptr.ID, parent))
|
||||
|
||||
nptr.Positive = false
|
||||
num, err = dORM.Update(nptr)
|
||||
throwFail(t, err)
|
||||
throwFail(t, AssertIs(num, 1))
|
||||
throwFail(t, AssertIs(nptr.ID, parent))
|
||||
throwFail(t, AssertIs(nptr.Positive, false))
|
||||
|
||||
num, err = dORM.Delete(nptr)
|
||||
throwFail(t, err)
|
||||
throwFail(t, AssertIs(num, 1))
|
||||
}
|
||||
|
||||
func TestSnake(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"i": "i",
|
||||
|
10
orm/types.go
10
orm/types.go
@ -145,6 +145,16 @@ type QuerySeter interface {
|
||||
// //sql-> WHERE T0.`profile_id` IS NOT NULL AND NOT T0.`Status` IN (?) OR T1.`age` > 2000
|
||||
// num, err := qs.SetCond(cond1).Count()
|
||||
SetCond(*Condition) QuerySeter
|
||||
// get condition from QuerySeter.
|
||||
// sql's where condition
|
||||
// cond := orm.NewCondition()
|
||||
// cond = cond.And("profile__isnull", false).AndNot("status__in", 1)
|
||||
// qs = qs.SetCond(cond)
|
||||
// cond = qs.GetCond()
|
||||
// cond := cond.Or("profile__age__gt", 2000)
|
||||
// //sql-> WHERE T0.`profile_id` IS NOT NULL AND NOT T0.`Status` IN (?) OR T1.`age` > 2000
|
||||
// num, err := qs.SetCond(cond).Count()
|
||||
GetCond() *Condition
|
||||
// add LIMIT value.
|
||||
// args[0] means offset, e.g. LIMIT num,offset.
|
||||
// if Limit <= 0 then Limit will be set to default limit ,eg 1000
|
||||
|
29
orm/utils.go
29
orm/utils.go
@ -92,11 +92,11 @@ func (f StrTo) Int64() (int64, error) {
|
||||
i := new(big.Int)
|
||||
ni, ok := i.SetString(f.String(), 10) // octal
|
||||
if !ok {
|
||||
return int64(v), err
|
||||
return v, err
|
||||
}
|
||||
return ni.Int64(), nil
|
||||
}
|
||||
return int64(v), err
|
||||
return v, err
|
||||
}
|
||||
|
||||
// Uint string to uint
|
||||
@ -130,11 +130,11 @@ func (f StrTo) Uint64() (uint64, error) {
|
||||
i := new(big.Int)
|
||||
ni, ok := i.SetString(f.String(), 10)
|
||||
if !ok {
|
||||
return uint64(v), err
|
||||
return v, err
|
||||
}
|
||||
return ni.Uint64(), nil
|
||||
}
|
||||
return uint64(v), err
|
||||
return v, err
|
||||
}
|
||||
|
||||
// String string to string
|
||||
@ -219,22 +219,17 @@ func snakeString(s string) string {
|
||||
// camel string, xx_yy to XxYy
|
||||
func camelString(s string) string {
|
||||
data := make([]byte, 0, len(s))
|
||||
j := false
|
||||
k := false
|
||||
num := len(s) - 1
|
||||
flag, num := true, len(s)-1
|
||||
for i := 0; i <= num; i++ {
|
||||
d := s[i]
|
||||
if k == false && d >= 'A' && d <= 'Z' {
|
||||
k = true
|
||||
}
|
||||
if d >= 'a' && d <= 'z' && (j || k == false) {
|
||||
d = d - 32
|
||||
j = false
|
||||
k = true
|
||||
}
|
||||
if k && d == '_' && num > i && s[i+1] >= 'a' && s[i+1] <= 'z' {
|
||||
j = true
|
||||
if d == '_' {
|
||||
flag = true
|
||||
continue
|
||||
} else if flag {
|
||||
if d >= 'a' && d <= 'z' {
|
||||
d = d - 32
|
||||
}
|
||||
flag = false
|
||||
}
|
||||
data = append(data, d)
|
||||
}
|
||||
|
36
orm/utils_test.go
Normal file
36
orm/utils_test.go
Normal file
@ -0,0 +1,36 @@
|
||||
// Copyright 2014 beego Author. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package orm
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCamelString(t *testing.T) {
|
||||
snake := []string{"pic_url", "hello_world_", "hello__World", "_HelLO_Word", "pic_url_1", "pic_url__1"}
|
||||
camel := []string{"PicUrl", "HelloWorld", "HelloWorld", "HelLOWord", "PicUrl1", "PicUrl1"}
|
||||
|
||||
answer := make(map[string]string)
|
||||
for i, v := range snake {
|
||||
answer[v] = camel[i]
|
||||
}
|
||||
|
||||
for _, v := range snake {
|
||||
res := camelString(v)
|
||||
if res != answer[v] {
|
||||
t.Error("Unit Test Fail:", v, res, answer[v])
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user