41dd6e58 by slene

orm 1. complete QueryRow/QueryRows api 2. QuerySeter.All support *[]Type and *[]*Type

1 parent 22d2de9f
...@@ -479,15 +479,19 @@ func (d *dbBase) ReadBatch(q dbQuerier, qs *querySet, mi *modelInfo, cond *Condi ...@@ -479,15 +479,19 @@ func (d *dbBase) ReadBatch(q dbQuerier, qs *querySet, mi *modelInfo, cond *Condi
479 ind := reflect.Indirect(val) 479 ind := reflect.Indirect(val)
480 480
481 errTyp := true 481 errTyp := true
482
483 one := true 482 one := true
483 isPtr := true
484 484
485 if val.Kind() == reflect.Ptr { 485 if val.Kind() == reflect.Ptr {
486 fn := "" 486 fn := ""
487 if ind.Kind() == reflect.Slice { 487 if ind.Kind() == reflect.Slice {
488 one = false 488 one = false
489 if ind.Type().Elem().Kind() == reflect.Ptr { 489 typ := ind.Type().Elem()
490 typ := ind.Type().Elem().Elem() 490 switch typ.Kind() {
491 case reflect.Ptr:
492 fn = getFullName(typ.Elem())
493 case reflect.Struct:
494 isPtr = false
491 fn = getFullName(typ) 495 fn = getFullName(typ)
492 } 496 }
493 } else { 497 } else {
...@@ -601,13 +605,21 @@ func (d *dbBase) ReadBatch(q dbQuerier, qs *querySet, mi *modelInfo, cond *Condi ...@@ -601,13 +605,21 @@ func (d *dbBase) ReadBatch(q dbQuerier, qs *querySet, mi *modelInfo, cond *Condi
601 if one { 605 if one {
602 ind.Set(mind) 606 ind.Set(mind)
603 } else { 607 } else {
608 if cnt == 0 {
609 slice = reflect.New(ind.Type()).Elem()
610 }
611
612 if isPtr {
604 slice = reflect.Append(slice, mind.Addr()) 613 slice = reflect.Append(slice, mind.Addr())
614 } else {
615 slice = reflect.Append(slice, mind)
616 }
605 } 617 }
606 } 618 }
607 cnt++ 619 cnt++
608 } 620 }
609 621
610 if one == false { 622 if one == false && cnt > 0 {
611 ind.Set(slice) 623 ind.Set(slice)
612 } 624 }
613 625
......
...@@ -10,6 +10,7 @@ const ( ...@@ -10,6 +10,7 @@ const (
10 od_SET_DEFAULT = "set_default" 10 od_SET_DEFAULT = "set_default"
11 od_DO_NOTHING = "do_nothing" 11 od_DO_NOTHING = "do_nothing"
12 defaultStructTagName = "orm" 12 defaultStructTagName = "orm"
13 defaultStructTagDelim = ";"
13 ) 14 )
14 15
15 var ( 16 var (
......
...@@ -16,7 +16,7 @@ type Data struct { ...@@ -16,7 +16,7 @@ type Data struct {
16 Char string `orm:"size(50)"` 16 Char string `orm:"size(50)"`
17 Text string `orm:"type(text)"` 17 Text string `orm:"type(text)"`
18 Date time.Time `orm:"type(date)"` 18 Date time.Time `orm:"type(date)"`
19 DateTime time.Time 19 DateTime time.Time `orm:"column(datetime)"`
20 Byte byte 20 Byte byte
21 Rune rune 21 Rune rune
22 Int int 22 Int int
...@@ -37,10 +37,10 @@ type Data struct { ...@@ -37,10 +37,10 @@ type Data struct {
37 type DataNull struct { 37 type DataNull struct {
38 Id int 38 Id int
39 Boolean bool `orm:"null"` 39 Boolean bool `orm:"null"`
40 Char string `orm:"size(50);null"` 40 Char string `orm:"null;size(50)"`
41 Text string `orm:"type(text);null"` 41 Text string `orm:"null;type(text)"`
42 Date time.Time `orm:"type(date);null"` 42 Date time.Time `orm:"null;type(date)"`
43 DateTime time.Time `orm:"null"` 43 DateTime time.Time `orm:"null;column(datetime)""`
44 Byte byte `orm:"null"` 44 Byte byte `orm:"null"`
45 Rune rune `orm:"null"` 45 Rune rune `orm:"null"`
46 Int int `orm:"null"` 46 Int int `orm:"null"`
...@@ -174,7 +174,10 @@ var ( ...@@ -174,7 +174,10 @@ var (
174 IsPostgres = DBARGS.Driver == "postgres" 174 IsPostgres = DBARGS.Driver == "postgres"
175 ) 175 )
176 176
177 var dORM Ormer 177 var (
178 dORM Ormer
179 dDbBaser dbBaser
180 )
178 181
179 func init() { 182 func init() {
180 Debug, _ = StrTo(DBARGS.Debug).Bool() 183 Debug, _ = StrTo(DBARGS.Debug).Bool()
......
...@@ -114,7 +114,7 @@ func getFieldType(val reflect.Value) (ft int, err error) { ...@@ -114,7 +114,7 @@ func getFieldType(val reflect.Value) (ft int, err error) {
114 func parseStructTag(data string, attrs *map[string]bool, tags *map[string]string) { 114 func parseStructTag(data string, attrs *map[string]bool, tags *map[string]string) {
115 attr := make(map[string]bool) 115 attr := make(map[string]bool)
116 tag := make(map[string]string) 116 tag := make(map[string]string)
117 for _, v := range strings.Split(data, ";") { 117 for _, v := range strings.Split(data, defaultStructTagDelim) {
118 v = strings.TrimSpace(v) 118 v = strings.TrimSpace(v)
119 if supportTag[v] == 1 { 119 if supportTag[v] == 1 {
120 attr[v] = true 120 attr[v] = true
......
...@@ -4,6 +4,8 @@ import ( ...@@ -4,6 +4,8 @@ import (
4 "database/sql" 4 "database/sql"
5 "fmt" 5 "fmt"
6 "reflect" 6 "reflect"
7 "strings"
8 "time"
7 ) 9 )
8 10
9 type rawPrepare struct { 11 type rawPrepare struct {
...@@ -64,14 +66,362 @@ func (o *rawSet) Exec() (sql.Result, error) { ...@@ -64,14 +66,362 @@ func (o *rawSet) Exec() (sql.Result, error) {
64 return o.orm.db.Exec(query, args...) 66 return o.orm.db.Exec(query, args...)
65 } 67 }
66 68
67 func (o *rawSet) QueryRow(...interface{}) error { 69 func (o *rawSet) setFieldValue(ind reflect.Value, value interface{}) {
68 //TODO 70 switch ind.Kind() {
71 case reflect.Bool:
72 if value == nil {
73 ind.SetBool(false)
74 } else if v, ok := value.(bool); ok {
75 ind.SetBool(v)
76 } else {
77 v, _ := StrTo(ToStr(value)).Bool()
78 ind.SetBool(v)
79 }
80
81 case reflect.String:
82 if value == nil {
83 ind.SetString("")
84 } else {
85 ind.SetString(ToStr(value))
86 }
87
88 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
89 if value == nil {
90 ind.SetInt(0)
91 } else {
92 val := reflect.ValueOf(value)
93 switch val.Kind() {
94 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
95 ind.SetInt(val.Int())
96 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
97 ind.SetInt(int64(val.Uint()))
98 default:
99 v, _ := StrTo(ToStr(value)).Int64()
100 ind.SetInt(v)
101 }
102 }
103 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
104 if value == nil {
105 ind.SetUint(0)
106 } else {
107 val := reflect.ValueOf(value)
108 switch val.Kind() {
109 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
110 ind.SetUint(uint64(val.Int()))
111 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
112 ind.SetUint(val.Uint())
113 default:
114 v, _ := StrTo(ToStr(value)).Uint64()
115 ind.SetUint(v)
116 }
117 }
118 case reflect.Float64, reflect.Float32:
119 if value == nil {
120 ind.SetFloat(0)
121 } else {
122 val := reflect.ValueOf(value)
123 switch val.Kind() {
124 case reflect.Float64:
125 ind.SetFloat(val.Float())
126 default:
127 v, _ := StrTo(ToStr(value)).Float64()
128 ind.SetFloat(v)
129 }
130 }
131
132 case reflect.Struct:
133 if value == nil {
134 ind.Set(reflect.Zero(ind.Type()))
135
136 } else if _, ok := ind.Interface().(time.Time); ok {
137 var str string
138 switch d := value.(type) {
139 case time.Time:
140 o.orm.alias.DbBaser.TimeFromDB(&d, o.orm.alias.TZ)
141 ind.Set(reflect.ValueOf(d))
142 case []byte:
143 str = string(d)
144 case string:
145 str = d
146 }
147 if str != "" {
148 if len(str) >= 19 {
149 str = str[:19]
150 t, err := time.ParseInLocation(format_DateTime, str, o.orm.alias.TZ)
151 if err == nil {
152 t = t.In(DefaultTimeLoc)
153 ind.Set(reflect.ValueOf(t))
154 }
155 } else if len(str) >= 10 {
156 str = str[:10]
157 t, err := time.ParseInLocation(format_Date, str, DefaultTimeLoc)
158 if err == nil {
159 ind.Set(reflect.ValueOf(t))
160 }
161 }
162 }
163 }
164 }
165 }
166
167 func (o *rawSet) loopInitRefs(typ reflect.Type, refsPtr *[]interface{}, sIdxesPtr *[][]int) {
168 sIdxes := *sIdxesPtr
169 refs := *refsPtr
170
171 if typ.Kind() == reflect.Struct {
172 if typ.String() == "time.Time" {
173 var ref interface{}
174 refs = append(refs, &ref)
175 sIdxes = append(sIdxes, []int{0})
176 } else {
177 idxs := []int{}
178 outFor:
179 for idx := 0; idx < typ.NumField(); idx++ {
180 ctyp := typ.Field(idx)
181
182 tag := ctyp.Tag.Get(defaultStructTagName)
183 for _, v := range strings.Split(tag, defaultStructTagDelim) {
184 if v == "-" {
185 continue outFor
186 }
187 }
188
189 tp := ctyp.Type
190 if tp.Kind() == reflect.Ptr {
191 tp = tp.Elem()
192 }
193
194 if tp.String() == "time.Time" {
195 var ref interface{}
196 refs = append(refs, &ref)
197
198 } else if tp.Kind() != reflect.Struct {
199 var ref interface{}
200 refs = append(refs, &ref)
201
202 } else {
203 // skip other type
204 continue
205 }
206
207 idxs = append(idxs, idx)
208 }
209 sIdxes = append(sIdxes, idxs)
210 }
211 } else {
212 var ref interface{}
213 refs = append(refs, &ref)
214 sIdxes = append(sIdxes, []int{0})
215 }
216
217 *sIdxesPtr = sIdxes
218 *refsPtr = refs
219 }
220
221 func (o *rawSet) loopSetRefs(refs []interface{}, sIdxes [][]int, sInds []reflect.Value, nIndsPtr *[]reflect.Value, eTyps []reflect.Type, init bool) {
222 nInds := *nIndsPtr
223
224 cur := 0
225 for i, idxs := range sIdxes {
226 sInd := sInds[i]
227 eTyp := eTyps[i]
228
229 typ := eTyp
230 isPtr := false
231 if typ.Kind() == reflect.Ptr {
232 isPtr = true
233 typ = typ.Elem()
234 }
235 if typ.Kind() == reflect.Ptr {
236 isPtr = true
237 typ = typ.Elem()
238 }
239
240 var nInd reflect.Value
241 if init {
242 nInd = reflect.New(sInd.Type()).Elem()
243 } else {
244 nInd = nInds[i]
245 }
246
247 val := reflect.New(typ)
248 ind := val.Elem()
249
250 tpName := ind.Type().String()
251
252 if ind.Kind() == reflect.Struct {
253 if tpName == "time.Time" {
254 value := reflect.ValueOf(refs[cur]).Elem().Interface()
255 if isPtr && value == nil {
256 val = reflect.New(val.Type()).Elem()
257 } else {
258 o.setFieldValue(ind, value)
259 }
260 cur++
261 } else {
262 hasValue := false
263 for _, idx := range idxs {
264 tind := ind.Field(idx)
265 value := reflect.ValueOf(refs[cur]).Elem().Interface()
266 if value != nil {
267 hasValue = true
268 }
269 if tind.Kind() == reflect.Ptr {
270 if value == nil {
271 tindV := reflect.New(tind.Type()).Elem()
272 tind.Set(tindV)
273 } else {
274 tindV := reflect.New(tind.Type().Elem())
275 o.setFieldValue(tindV.Elem(), value)
276 tind.Set(tindV)
277 }
278 } else {
279 o.setFieldValue(tind, value)
280 }
281 cur++
282 }
283 if hasValue == false && isPtr {
284 val = reflect.New(val.Type()).Elem()
285 }
286 }
287 } else {
288 value := reflect.ValueOf(refs[cur]).Elem().Interface()
289 if isPtr && value == nil {
290 val = reflect.New(val.Type()).Elem()
291 } else {
292 o.setFieldValue(ind, value)
293 }
294 cur++
295 }
296
297 if nInd.Kind() == reflect.Slice {
298 if isPtr {
299 nInd = reflect.Append(nInd, val)
300 } else {
301 nInd = reflect.Append(nInd, ind)
302 }
303 } else {
304 if isPtr {
305 nInd.Set(val)
306 } else {
307 nInd.Set(ind)
308 }
309 }
310
311 nInds[i] = nInd
312 }
313 }
314
315 func (o *rawSet) QueryRow(containers ...interface{}) error {
316 if len(containers) == 0 {
317 panic("<RawSeter.QueryRow> need at least one arg")
318 }
319
320 refs := make([]interface{}, 0, len(containers))
321 sIdxes := make([][]int, 0)
322 sInds := make([]reflect.Value, 0)
323 eTyps := make([]reflect.Type, 0)
324
325 for _, container := range containers {
326 val := reflect.ValueOf(container)
327 ind := reflect.Indirect(val)
328
329 if val.Kind() != reflect.Ptr {
330 panic("<RawSeter.QueryRow> all args must be use ptr")
331 }
332
333 etyp := ind.Type()
334 typ := etyp
335 if typ.Kind() == reflect.Ptr {
336 typ = typ.Elem()
337 }
338 if typ.Kind() == reflect.Ptr {
339 typ = typ.Elem()
340 }
341
342 sInds = append(sInds, ind)
343 eTyps = append(eTyps, etyp)
344
345 o.loopInitRefs(typ, &refs, &sIdxes)
346 }
347
348 query := o.query
349 o.orm.alias.DbBaser.ReplaceMarks(&query)
350
351 args := getFlatParams(nil, o.args, o.orm.alias.TZ)
352 row := o.orm.db.QueryRow(query, args...)
353
354 if err := row.Scan(refs...); err == sql.ErrNoRows {
355 return ErrNoRows
356 } else if err != nil {
357 return err
358 }
359
360 nInds := make([]reflect.Value, len(sInds))
361 o.loopSetRefs(refs, sIdxes, sInds, &nInds, eTyps, true)
362 for i, sInd := range sInds {
363 nInd := nInds[i]
364 sInd.Set(nInd)
365 }
366
69 return nil 367 return nil
70 } 368 }
71 369
72 func (o *rawSet) QueryRows(...interface{}) (int64, error) { 370 func (o *rawSet) QueryRows(containers ...interface{}) (int64, error) {
73 //TODO 371 refs := make([]interface{}, 0)
74 return 0, nil 372 sIdxes := make([][]int, 0)
373 sInds := make([]reflect.Value, 0)
374 eTyps := make([]reflect.Type, 0)
375
376 for _, container := range containers {
377 val := reflect.ValueOf(container)
378 sInd := reflect.Indirect(val)
379 if val.Kind() != reflect.Ptr || sInd.Kind() != reflect.Slice {
380 panic("<RawSeter.QueryRows> all args must be use ptr slice")
381 }
382
383 etyp := sInd.Type().Elem()
384 typ := etyp
385 if typ.Kind() == reflect.Ptr {
386 typ = typ.Elem()
387 }
388
389 sInds = append(sInds, sInd)
390 eTyps = append(eTyps, etyp)
391
392 o.loopInitRefs(typ, &refs, &sIdxes)
393 }
394
395 query := o.query
396 o.orm.alias.DbBaser.ReplaceMarks(&query)
397
398 args := getFlatParams(nil, o.args, o.orm.alias.TZ)
399 rows, err := o.orm.db.Query(query, args...)
400 if err != nil {
401 return 0, err
402 }
403
404 nInds := make([]reflect.Value, len(sInds))
405
406 var cnt int64
407 for rows.Next() {
408 if err := rows.Scan(refs...); err != nil {
409 return 0, err
410 }
411
412 o.loopSetRefs(refs, sIdxes, sInds, &nInds, eTyps, cnt == 0)
413
414 cnt++
415 }
416
417 if cnt > 0 {
418 for i, sInd := range sInds {
419 nInd := nInds[i]
420 sInd.Set(nInd)
421 }
422 }
423
424 return cnt, nil
75 } 425 }
76 426
77 func (o *rawSet) readValues(container interface{}) (int64, error) { 427 func (o *rawSet) readValues(container interface{}) (int64, error) {
......
...@@ -216,6 +216,7 @@ func TestRegisterModels(t *testing.T) { ...@@ -216,6 +216,7 @@ func TestRegisterModels(t *testing.T) {
216 BootStrap() 216 BootStrap()
217 217
218 dORM = NewOrm() 218 dORM = NewOrm()
219 dDbBaser = getDbAlias("default").DbBaser
219 } 220 }
220 221
221 func TestModelSyntax(t *testing.T) { 222 func TestModelSyntax(t *testing.T) {
...@@ -629,9 +630,23 @@ func TestOperators(t *testing.T) { ...@@ -629,9 +630,23 @@ func TestOperators(t *testing.T) {
629 func TestAll(t *testing.T) { 630 func TestAll(t *testing.T) {
630 var users []*User 631 var users []*User
631 qs := dORM.QueryTable("user") 632 qs := dORM.QueryTable("user")
632 num, err := qs.All(&users) 633 num, err := qs.OrderBy("Id").All(&users)
633 throwFail(t, err) 634 throwFail(t, err)
634 throwFail(t, AssertIs(num, T_Equal, 3)) 635 throwFailNow(t, AssertIs(num, T_Equal, 3))
636
637 throwFail(t, AssertIs(users[0].UserName, T_Equal, "slene"))
638 throwFail(t, AssertIs(users[1].UserName, T_Equal, "astaxie"))
639 throwFail(t, AssertIs(users[2].UserName, T_Equal, "nobody"))
640
641 var users2 []User
642 qs = dORM.QueryTable("user")
643 num, err = qs.OrderBy("Id").All(&users2)
644 throwFail(t, err)
645 throwFailNow(t, AssertIs(num, T_Equal, 3))
646
647 throwFailNow(t, AssertIs(users2[0].UserName, T_Equal, "slene"))
648 throwFailNow(t, AssertIs(users2[1].UserName, T_Equal, "astaxie"))
649 throwFailNow(t, AssertIs(users2[2].UserName, T_Equal, "nobody"))
635 650
636 qs = dORM.QueryTable("user") 651 qs = dORM.QueryTable("user")
637 num, err = qs.Filter("user_name", "nothing").All(&users) 652 num, err = qs.Filter("user_name", "nothing").All(&users)
...@@ -645,8 +660,14 @@ func TestOne(t *testing.T) { ...@@ -645,8 +660,14 @@ func TestOne(t *testing.T) {
645 err := qs.One(&user) 660 err := qs.One(&user)
646 throwFail(t, AssertIs(err, T_Equal, ErrMultiRows)) 661 throwFail(t, AssertIs(err, T_Equal, ErrMultiRows))
647 662
663 user = User{}
664 err = qs.OrderBy("Id").Limit(1).One(&user)
665 throwFailNow(t, err)
666 throwFail(t, AssertIs(user.UserName, T_Equal, "slene"))
667
648 err = qs.Filter("user_name", "nothing").One(&user) 668 err = qs.Filter("user_name", "nothing").One(&user)
649 throwFail(t, AssertIs(err, T_Equal, ErrNoRows)) 669 throwFail(t, AssertIs(err, T_Equal, ErrNoRows))
670
650 } 671 }
651 672
652 func TestValues(t *testing.T) { 673 func TestValues(t *testing.T) {
...@@ -836,68 +857,282 @@ func TestPrepareInsert(t *testing.T) { ...@@ -836,68 +857,282 @@ func TestPrepareInsert(t *testing.T) {
836 throwFail(t, AssertIs(err, T_Equal, ErrStmtClosed)) 857 throwFail(t, AssertIs(err, T_Equal, ErrStmtClosed))
837 } 858 }
838 859
839 func TestRawQueryRow(t *testing.T) { 860 func TestRawExec(t *testing.T) {
861 Q := dDbBaser.TableQuote()
840 862
841 } 863 query := fmt.Sprintf("UPDATE %suser%s SET %suser_name%s = ? WHERE %suser_name%s = ?", Q, Q, Q, Q, Q, Q)
842 864 res, err := dORM.Raw(query, "testing", "slene").Exec()
843 func TestRawQueryRows(t *testing.T) {
844
845 }
846
847 func TestRawValues(t *testing.T) {
848 switch {
849 case IsMysql || IsSqlite:
850
851 res, err := dORM.Raw("UPDATE user SET user_name = ? WHERE user_name = ?", "testing", "slene").Exec()
852 throwFail(t, err) 865 throwFail(t, err)
853 num, err := res.RowsAffected() 866 num, err := res.RowsAffected()
854 throwFail(t, AssertIs(num, T_Equal, 1), err) 867 throwFail(t, AssertIs(num, T_Equal, 1), err)
855 868
856 res, err = dORM.Raw("UPDATE user SET user_name = ? WHERE user_name = ?", "slene", "testing").Exec() 869 res, err = dORM.Raw(query, "slene", "testing").Exec()
857 throwFail(t, err) 870 throwFail(t, err)
858 num, err = res.RowsAffected() 871 num, err = res.RowsAffected()
859 throwFail(t, AssertIs(num, T_Equal, 1), err) 872 throwFail(t, AssertIs(num, T_Equal, 1), err)
873 }
860 874
861 var maps []Params 875 func TestRawQueryRow(t *testing.T) {
862 num, err = dORM.Raw("SELECT user_name FROM user WHERE status = ?", 1).Values(&maps) 876 var (
863 throwFail(t, err) 877 Boolean bool
864 throwFail(t, AssertIs(num, T_Equal, 1)) 878 Char string
865 if num == 1 { 879 Text string
866 throwFail(t, AssertIs(maps[0]["user_name"], T_Equal, "slene")) 880 Date time.Time
881 DateTime time.Time
882 Byte byte
883 Rune rune
884 Int int
885 Int8 int
886 Int16 int16
887 Int32 int32
888 Int64 int64
889 Uint uint
890 Uint8 uint8
891 Uint16 uint16
892 Uint32 uint32
893 Uint64 uint64
894 Float32 float32
895 Float64 float64
896 Decimal float64
897 )
898
899 data_values := make(map[string]interface{}, len(Data_Values))
900
901 for k, v := range Data_Values {
902 data_values[strings.ToLower(k)] = v
867 } 903 }
868 904
869 var lists []ParamsList 905 Q := dDbBaser.TableQuote()
870 num, err = dORM.Raw("SELECT user_name FROM user WHERE status = ?", 1).ValuesList(&lists) 906
871 throwFail(t, err) 907 cols := []string{
872 throwFail(t, AssertIs(num, T_Equal, 1)) 908 "id", "boolean", "char", "text", "date", "datetime", "byte", "rune", "int", "int8", "int16", "int32",
873 if num == 1 { 909 "int64", "uint", "uint8", "uint16", "uint32", "uint64", "float32", "float64", "decimal",
874 throwFail(t, AssertIs(lists[0][0], T_Equal, "slene")) 910 }
911 sep := fmt.Sprintf("%s, %s", Q, Q)
912 query := fmt.Sprintf("SELECT %s%s%s FROM data WHERE id = ?", Q, strings.Join(cols, sep), Q)
913 var id int
914 values := []interface{}{
915 &id, &Boolean, &Char, &Text, &Date, &DateTime, &Byte, &Rune, &Int, &Int8, &Int16, &Int32,
916 &Int64, &Uint, &Uint8, &Uint16, &Uint32, &Uint64, &Float32, &Float64, &Decimal,
917 }
918 err := dORM.Raw(query, 1).QueryRow(values...)
919 throwFailNow(t, err)
920 for i, col := range cols {
921 vu := values[i]
922 v := reflect.ValueOf(vu).Elem().Interface()
923 switch col {
924 case "id":
925 throwFail(t, AssertIs(id, T_Equal, 1))
926 case "date":
927 v = v.(time.Time).In(DefaultTimeLoc)
928 value := data_values[col].(time.Time).In(DefaultTimeLoc)
929 throwFail(t, AssertIs(v, T_Equal, value, test_Date))
930 case "datetime":
931 v = v.(time.Time).In(DefaultTimeLoc)
932 value := data_values[col].(time.Time).In(DefaultTimeLoc)
933 throwFail(t, AssertIs(v, T_Equal, value, test_DateTime))
934 default:
935 throwFail(t, AssertIs(v, T_Equal, data_values[col]))
936 }
875 } 937 }
876 938
877 var list ParamsList 939 type Tmp struct {
878 num, err = dORM.Raw("SELECT profile_id FROM user ORDER BY id ASC").ValuesFlat(&list) 940 Skip0 string
879 throwFail(t, err) 941 Id int
880 throwFail(t, AssertIs(num, T_Equal, 3)) 942 Char *string
881 if num == 3 { 943 Skip1 int `orm:"-"`
882 throwFail(t, AssertIs(list[0], T_Equal, "2")) 944 Date time.Time
883 throwFail(t, AssertIs(list[1], T_Equal, "3")) 945 DateTime time.Time
884 throwFail(t, AssertIs(list[2], T_Equal, nil))
885 } 946 }
886 947
887 case IsPostgres: 948 Boolean = false
949 Text = ""
950 Int64 = 0
951 Uint = 0
952
953 tmp := new(Tmp)
954
955 cols = []string{
956 "int", "char", "date", "datetime", "boolean", "text", "int64", "uint",
957 }
958 query = fmt.Sprintf("SELECT NULL, %s%s%s FROM data WHERE id = ?", Q, strings.Join(cols, sep), Q)
959 values = []interface{}{
960 tmp, &Boolean, &Text, &Int64, &Uint,
961 }
962 err = dORM.Raw(query, 1).QueryRow(values...)
963 throwFailNow(t, err)
964
965 for _, col := range cols {
966 switch col {
967 case "id":
968 throwFail(t, AssertIs(tmp.Id, T_Equal, data_values[col]))
969 case "char":
970 c := tmp.Char
971 throwFail(t, AssertIs(*c, T_Equal, data_values[col]))
972 case "date":
973 v := tmp.Date.In(DefaultTimeLoc)
974 value := data_values[col].(time.Time).In(DefaultTimeLoc)
975 throwFail(t, AssertIs(v, T_Equal, value, test_Date))
976 case "datetime":
977 v := tmp.DateTime.In(DefaultTimeLoc)
978 value := data_values[col].(time.Time).In(DefaultTimeLoc)
979 throwFail(t, AssertIs(v, T_Equal, value, test_DateTime))
980 case "boolean":
981 throwFail(t, AssertIs(Boolean, T_Equal, data_values[col]))
982 case "text":
983 throwFail(t, AssertIs(Text, T_Equal, data_values[col]))
984 case "int64":
985 throwFail(t, AssertIs(Int64, T_Equal, data_values[col]))
986 case "uint":
987 throwFail(t, AssertIs(Uint, T_Equal, data_values[col]))
988 }
989 }
990
991 var (
992 uid int
993 status *int
994 pid *int
995 )
888 996
889 res, err := dORM.Raw(`UPDATE "user" SET "user_name" = ? WHERE "user_name" = ?`, "testing", "slene").Exec() 997 cols = []string{
998 "id", "status", "profile_id",
999 }
1000 query = fmt.Sprintf("SELECT %s%s%s FROM %suser%s WHERE id = ?", Q, strings.Join(cols, sep), Q, Q, Q)
1001 err = dORM.Raw(query, 4).QueryRow(&uid, &status, &pid)
890 throwFail(t, err) 1002 throwFail(t, err)
891 num, err := res.RowsAffected() 1003 throwFail(t, AssertIs(uid, T_Equal, 4))
892 throwFail(t, AssertIs(num, T_Equal, 1), err) 1004 throwFail(t, AssertIs(*status, T_Equal, 3))
1005 throwFail(t, AssertIs(pid, T_Equal, nil))
1006 }
1007
1008 func TestQueryRows(t *testing.T) {
1009 Q := dDbBaser.TableQuote()
1010
1011 cols := []string{
1012 "id", "boolean", "char", "text", "date", "datetime", "byte", "rune", "int", "int8", "int16", "int32",
1013 "int64", "uint", "uint8", "uint16", "uint32", "uint64", "float32", "float64", "decimal",
1014 }
1015
1016 var datas []*Data
1017 var dids []int
1018
1019 sep := fmt.Sprintf("%s, %s", Q, Q)
1020 query := fmt.Sprintf("SELECT %s%s%s, id FROM %sdata%s", Q, strings.Join(cols, sep), Q, Q, Q)
1021 num, err := dORM.Raw(query).QueryRows(&datas, &dids)
1022 throwFailNow(t, err)
1023 throwFailNow(t, AssertIs(num, T_Equal, 1))
1024 throwFailNow(t, AssertIs(len(datas), T_Equal, 1))
1025 throwFailNow(t, AssertIs(len(dids), T_Equal, 1))
1026 throwFailNow(t, AssertIs(dids[0], T_Equal, 1))
1027
1028 ind := reflect.Indirect(reflect.ValueOf(datas[0]))
1029
1030 for name, value := range Data_Values {
1031 e := ind.FieldByName(name)
1032 vu := e.Interface()
1033 switch name {
1034 case "Date":
1035 vu = vu.(time.Time).In(DefaultTimeLoc).Format(test_Date)
1036 value = value.(time.Time).In(DefaultTimeLoc).Format(test_Date)
1037 case "DateTime":
1038 vu = vu.(time.Time).In(DefaultTimeLoc).Format(test_DateTime)
1039 value = value.(time.Time).In(DefaultTimeLoc).Format(test_DateTime)
1040 }
1041 throwFail(t, AssertIs(vu == value, T_Equal, true), value, vu)
1042 }
893 1043
894 res, err = dORM.Raw(`UPDATE "user" SET "user_name" = ? WHERE "user_name" = ?`, "slene", "testing").Exec() 1044 type Tmp struct {
1045 Id int
1046 Name string
1047 Skiped0 string `orm:"-"`
1048 Pid *int
1049 Skiped1 Data
1050 Skiped2 *Data
1051 }
1052
1053 var (
1054 ids []int
1055 userNames []string
1056 profileIds1 []int
1057 profileIds2 []*int
1058 createds []time.Time
1059 updateds []time.Time
1060 tmps1 []*Tmp
1061 tmps2 []Tmp
1062 )
1063 cols = []string{
1064 "id", "user_name", "profile_id", "profile_id", "id", "user_name", "profile_id", "id", "user_name", "profile_id", "created", "updated",
1065 }
1066 query = fmt.Sprintf("SELECT %s%s%s FROM %suser%s ORDER BY id", Q, strings.Join(cols, sep), Q, Q, Q)
1067 num, err = dORM.Raw(query).QueryRows(&ids, &userNames, &profileIds1, &profileIds2, &tmps1, &tmps2, &createds, &updateds)
1068 throwFailNow(t, err)
1069 throwFailNow(t, AssertIs(num, T_Equal, 3))
1070
1071 var users []User
1072 dORM.QueryTable("user").OrderBy("Id").All(&users)
1073
1074 for i := 0; i < 3; i++ {
1075 id := ids[i]
1076 name := userNames[i]
1077 pid1 := profileIds1[i]
1078 pid2 := profileIds2[i]
1079 created := createds[i]
1080 updated := updateds[i]
1081
1082 user := users[i]
1083 throwFailNow(t, AssertIs(id, T_Equal, user.Id))
1084 throwFailNow(t, AssertIs(name, T_Equal, user.UserName))
1085 if user.Profile != nil {
1086 throwFailNow(t, AssertIs(pid1, T_Equal, user.Profile.Id))
1087 throwFailNow(t, AssertIs(*pid2, T_Equal, user.Profile.Id))
1088 } else {
1089 throwFailNow(t, AssertIs(pid1, T_Equal, 0))
1090 throwFailNow(t, AssertIs(pid2, T_Equal, nil))
1091 }
1092 throwFailNow(t, AssertIs(created, T_Equal, user.Created, test_Date))
1093 throwFailNow(t, AssertIs(updated, T_Equal, user.Updated, test_DateTime))
1094
1095 tmp := tmps1[i]
1096 tmp1 := *tmp
1097 throwFailNow(t, AssertIs(tmp1.Id, T_Equal, user.Id))
1098 throwFailNow(t, AssertIs(tmp1.Name, T_Equal, user.UserName))
1099 if user.Profile != nil {
1100 pid := tmp1.Pid
1101 throwFailNow(t, AssertIs(*pid, T_Equal, user.Profile.Id))
1102 } else {
1103 throwFailNow(t, AssertIs(tmp1.Pid, T_Equal, nil))
1104 }
1105
1106 tmp2 := tmps2[i]
1107 throwFailNow(t, AssertIs(tmp2.Id, T_Equal, user.Id))
1108 throwFailNow(t, AssertIs(tmp2.Name, T_Equal, user.UserName))
1109 if user.Profile != nil {
1110 pid := tmp2.Pid
1111 throwFailNow(t, AssertIs(*pid, T_Equal, user.Profile.Id))
1112 } else {
1113 throwFailNow(t, AssertIs(tmp2.Pid, T_Equal, nil))
1114 }
1115 }
1116
1117 type Sec struct {
1118 Id int
1119 Name string
1120 }
1121
1122 var tmp []*Sec
1123 query = fmt.Sprintf("SELECT NULL, NULL FROM %suser%s LIMIT 1", Q, Q)
1124 num, err = dORM.Raw(query).QueryRows(&tmp)
895 throwFail(t, err) 1125 throwFail(t, err)
896 num, err = res.RowsAffected() 1126 throwFail(t, AssertIs(num, T_Equal, 1))
897 throwFail(t, AssertIs(num, T_Equal, 1), err) 1127 throwFail(t, AssertIs(tmp[0], T_Equal, nil))
1128 }
1129
1130 func TestRawValues(t *testing.T) {
1131 Q := dDbBaser.TableQuote()
898 1132
899 var maps []Params 1133 var maps []Params
900 num, err = dORM.Raw(`SELECT "user_name" FROM "user" WHERE "status" = ?`, 1).Values(&maps) 1134 query := fmt.Sprintf("SELECT %suser_name%s FROM %suser%s WHERE %sstatus%s = ?", Q, Q, Q, Q, Q, Q)
1135 num, err := dORM.Raw(query, 1).Values(&maps)
901 throwFail(t, err) 1136 throwFail(t, err)
902 throwFail(t, AssertIs(num, T_Equal, 1)) 1137 throwFail(t, AssertIs(num, T_Equal, 1))
903 if num == 1 { 1138 if num == 1 {
...@@ -905,15 +1140,16 @@ func TestRawValues(t *testing.T) { ...@@ -905,15 +1140,16 @@ func TestRawValues(t *testing.T) {
905 } 1140 }
906 1141
907 var lists []ParamsList 1142 var lists []ParamsList
908 num, err = dORM.Raw(`SELECT "user_name" FROM "user" WHERE "status" = ?`, 1).ValuesList(&lists) 1143 num, err = dORM.Raw(query, 1).ValuesList(&lists)
909 throwFail(t, err) 1144 throwFail(t, err)
910 throwFail(t, AssertIs(num, T_Equal, 1)) 1145 throwFail(t, AssertIs(num, T_Equal, 1))
911 if num == 1 { 1146 if num == 1 {
912 throwFail(t, AssertIs(lists[0][0], T_Equal, "slene")) 1147 throwFail(t, AssertIs(lists[0][0], T_Equal, "slene"))
913 } 1148 }
914 1149
1150 query = fmt.Sprintf("SELECT %sprofile_id%s FROM %suser%s ORDER BY %sid%s ASC", Q, Q, Q, Q, Q, Q)
915 var list ParamsList 1151 var list ParamsList
916 num, err = dORM.Raw(`SELECT "profile_id" FROM "user" ORDER BY id ASC`).ValuesFlat(&list) 1152 num, err = dORM.Raw(query).ValuesFlat(&list)
917 throwFail(t, err) 1153 throwFail(t, err)
918 throwFail(t, AssertIs(num, T_Equal, 3)) 1154 throwFail(t, AssertIs(num, T_Equal, 3))
919 if num == 3 { 1155 if num == 3 {
...@@ -921,7 +1157,6 @@ func TestRawValues(t *testing.T) { ...@@ -921,7 +1157,6 @@ func TestRawValues(t *testing.T) {
921 throwFail(t, AssertIs(list[1], T_Equal, "3")) 1157 throwFail(t, AssertIs(list[1], T_Equal, "3"))
922 throwFail(t, AssertIs(list[2], T_Equal, nil)) 1158 throwFail(t, AssertIs(list[2], T_Equal, nil))
923 } 1159 }
924 }
925 } 1160 }
926 1161
927 func TestRawPrepare(t *testing.T) { 1162 func TestRawPrepare(t *testing.T) {
......
...@@ -115,6 +115,8 @@ func ToStr(value interface{}, args ...int) (s string) { ...@@ -115,6 +115,8 @@ func ToStr(value interface{}, args ...int) (s string) {
115 s = strconv.FormatUint(v, argInt(args).Get(0, 10)) 115 s = strconv.FormatUint(v, argInt(args).Get(0, 10))
116 case string: 116 case string:
117 s = v 117 s = v
118 case []byte:
119 s = string(v)
118 default: 120 default:
119 s = fmt.Sprintf("%v", v) 121 s = fmt.Sprintf("%v", v)
120 } 122 }
......
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!