Debian Codegraph @

queries_test.go

raw symbols SCIP
1 package mssql
2
3 import (
4 "bytes"
5 "context"
6 "database/sql"
7 "database/sql/driver"
8 "fmt"
9 "math"
10 "net"
11 "strings"
12 "testing"
13 "time"
14 )
15
16 func driverWithProcess(t *testing.T) *MssqlDriver {
17 return &MssqlDriver{
18 log: optionalLogger{testLogger{t}},
19 processQueryText: true,
20 }
21 }
22 func driverNoProcess(t *testing.T) *MssqlDriver {
23 return &MssqlDriver{
24 log: optionalLogger{testLogger{t}},
25 processQueryText: false,
26 }
27 }
28
29 func TestSelect(t *testing.T) {
30 conn := open(t)
31 defer conn.Close()
32
33 type testStruct struct {
34 sql string
35 val interface{}
36 }
37
38 longstr := strings.Repeat("x", 10000)
39
40 values := []testStruct{
41 {"1", int64(1)},
42 {"-1", int64(-1)},
43 {"cast(1 as int)", int64(1)},
44 {"cast(-1 as int)", int64(-1)},
45 {"cast(1 as tinyint)", int64(1)},
46 {"cast(255 as tinyint)", int64(255)},
47 {"cast(1 as smallint)", int64(1)},
48 {"cast(-1 as smallint)", int64(-1)},
49 {"cast(1 as bigint)", int64(1)},
50 {"cast(-1 as bigint)", int64(-1)},
51 {"cast(1 as bit)", true},
52 {"cast(0 as bit)", false},
53 {"'abc'", string("abc")},
54 {"cast(0.5 as float)", float64(0.5)},
55 {"cast(0.5 as real)", float64(0.5)},
56 {"cast(1 as decimal)", []byte("1")},
57 {"cast(1.2345 as money)", []byte("1.2345")},
58 {"cast(-1.2345 as money)", []byte("-1.2345")},
59 {"cast(1.2345 as smallmoney)", []byte("1.2345")},
60 {"cast(-1.2345 as smallmoney)", []byte("-1.2345")},
61 {"cast(0.5 as decimal(18,1))", []byte("0.5")},
62 {"cast(-0.5 as decimal(18,1))", []byte("-0.5")},
63 {"cast(-0.5 as numeric(18,1))", []byte("-0.5")},
64 {"cast(4294967296 as numeric(20,0))", []byte("4294967296")},
65 {"cast(-0.5 as numeric(18,2))", []byte("-0.50")},
66 {"N'abc'", string("abc")},
67 {"cast(null as nvarchar(3))", nil},
68 {"NULL", nil},
69 {"cast('2000-01-01' as datetime)", time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)},
70 {"cast('2000-01-01T12:13:14.12' as datetime)",
71 time.Date(2000, 1, 1, 12, 13, 14, 120000000, time.UTC)},
72 {"cast('2014-06-26 11:08:09.673' as datetime)", time.Date(2014, 06, 26, 11, 8, 9, 673000000, time.UTC)},
73 {"cast(NULL as datetime)", nil},
74 {"cast('2000-01-01T12:13:00' as smalldatetime)",
75 time.Date(2000, 1, 1, 12, 13, 0, 0, time.UTC)},
76 {"cast(0x6F9619FF8B86D011B42D00C04FC964FF as uniqueidentifier)",
77 []byte{0x6F, 0x96, 0x19, 0xFF, 0x8B, 0x86, 0xD0, 0x11, 0xB4, 0x2D, 0x00, 0xC0, 0x4F, 0xC9, 0x64, 0xFF}},
78 {"cast(NULL as uniqueidentifier)", nil},
79 {"cast(0x1234 as varbinary(2))", []byte{0x12, 0x34}},
80 {"cast(N'abc' as nvarchar(max))", "abc"},
81 {"cast(null as nvarchar(max))", nil},
82 {"cast('<root/>' as xml)", "<root/>"},
83 {"cast('abc' as text)", "abc"},
84 {"cast(null as text)", nil},
85 {"cast(N'abc' as ntext)", "abc"},
86 {"cast(0x1234 as image)", []byte{0x12, 0x34}},
87 {"cast('abc' as char(3))", "abc"},
88 {"cast('abc' as varchar(3))", "abc"},
89 {"cast(N'проверка' as nvarchar(max))", "проверка"},
90 {"cast(N'Δοκιμή' as nvarchar(max))", "Δοκιμή"},
91 {"cast(cast(N'สวัสดี' as nvarchar(max)) collate Thai_CI_AI as varchar(max))", "สวัสดี"}, // cp874
92 {"cast(cast(N'你好' as nvarchar(max)) collate Chinese_PRC_CI_AI as varchar(max))", "你好"}, // cp936
93 {"cast(cast(N'こんにちは' as nvarchar(max)) collate Japanese_CI_AI as varchar(max))", "こんにちは"}, // cp939
94 {"cast(cast(N'안녕하세요.' as nvarchar(max)) collate Korean_90_CI_AI as varchar(max))", "안녕하세요."}, // cp949
95 {"cast(cast(N'你好' as nvarchar(max)) collate Chinese_Hong_Kong_Stroke_90_CI_AI as varchar(max))", "你好"}, // cp950
96 {"cast(cast(N'cześć' as nvarchar(max)) collate Polish_CI_AI as varchar(max))", "cześć"}, // cp1250
97 {"cast(cast(N'Алло' as nvarchar(max)) collate Cyrillic_General_CI_AI as varchar(max))", "Алло"}, // cp1251
98 {"cast(cast(N'Bonjour' as nvarchar(max)) collate French_CI_AI as varchar(max))", "Bonjour"}, // cp1252
99 {"cast(cast(N'Γεια σας' as nvarchar(max)) collate Greek_CI_AI as varchar(max))", "Γεια σας"}, // cp1253
100 {"cast(cast(N'Merhaba' as nvarchar(max)) collate Turkish_CI_AI as varchar(max))", "Merhaba"}, // cp1254
101 {"cast(cast(N'שלום' as nvarchar(max)) collate Hebrew_CI_AI as varchar(max))", "שלום"}, // cp1255
102 {"cast(cast(N'مرحبا' as nvarchar(max)) collate Arabic_CI_AI as varchar(max))", "مرحبا"}, // cp1256
103 {"cast(cast(N'Sveiki' as nvarchar(max)) collate Lithuanian_CI_AI as varchar(max))", "Sveiki"}, // cp1257
104 {"cast(cast(N'chào' as nvarchar(max)) collate Vietnamese_CI_AI as varchar(max))", "chào"}, // cp1258
105 {fmt.Sprintf("cast(N'%s' as nvarchar(max))", longstr), longstr},
106 {"cast(NULL as sql_variant)", nil},
107 {"cast(cast(0x6F9619FF8B86D011B42D00C04FC964FF as uniqueidentifier) as sql_variant)",
108 []byte{0x6F, 0x96, 0x19, 0xFF, 0x8B, 0x86, 0xD0, 0x11, 0xB4, 0x2D, 0x00, 0xC0, 0x4F, 0xC9, 0x64, 0xFF}},
109 {"cast(cast(1 as bit) as sql_variant)", true},
110 {"cast(cast(10 as tinyint) as sql_variant)", int64(10)},
111 {"cast(cast(-10 as smallint) as sql_variant)", int64(-10)},
112 {"cast(cast(-20 as int) as sql_variant)", int64(-20)},
113 {"cast(cast(-20 as bigint) as sql_variant)", int64(-20)},
114 {"cast(cast('2000-01-01' as datetime) as sql_variant)", time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)},
115 {"cast(cast('2000-01-01T12:13:00' as smalldatetime) as sql_variant)",
116 time.Date(2000, 1, 1, 12, 13, 0, 0, time.UTC)},
117 {"cast(cast(0.125 as real) as sql_variant)", float64(0.125)},
118 {"cast(cast(0.125 as float) as sql_variant)", float64(0.125)},
119 {"cast(cast(1.2345 as smallmoney) as sql_variant)", []byte("1.2345")},
120 {"cast(cast(1.2345 as money) as sql_variant)", []byte("1.2345")},
121 {"cast(cast(0x1234 as varbinary(2)) as sql_variant)", []byte{0x12, 0x34}},
122 {"cast(cast(0x1234 as binary(2)) as sql_variant)", []byte{0x12, 0x34}},
123 {"cast(cast(-0.5 as decimal(18,1)) as sql_variant)", []byte("-0.5")},
124 {"cast(cast(-0.5 as numeric(18,1)) as sql_variant)", []byte("-0.5")},
125 {"cast(cast('abc' as varchar(3)) as sql_variant)", "abc"},
126 {"cast(cast('abc' as char(3)) as sql_variant)", "abc"},
127 {"cast(N'abc' as sql_variant)", "abc"},
128 }
129
130 for _, test := range values {
131 stmt, err := conn.Prepare("select " + test.sql)
132 if err != nil {
133 t.Error("Prepare failed:", test.sql, err.Error())
134 return
135 }
136 defer stmt.Close()
137
138 row := stmt.QueryRow()
139 var retval interface{}
140 err = row.Scan(&retval)
141 if err != nil {
142 t.Error("Scan failed:", test.sql, err.Error())
143 continue
144 }
145 var same bool
146 switch decodedval := retval.(type) {
147 case []byte:
148 switch decodedvaltest := test.val.(type) {
149 case []byte:
150 same = bytes.Equal(decodedval, decodedvaltest)
151 default:
152 same = false
153 }
154 default:
155 same = retval == test.val
156 }
157 if !same {
158 t.Errorf("Values don't match '%s' '%s' for test: %s", retval, test.val, test.sql)
159 continue
160 }
161 }
162 }
163
164 func TestSelectDateTimeOffset(t *testing.T) {
165 type testStruct struct {
166 sql string
167 val time.Time
168 }
169 values := []testStruct{
170 {"cast('2010-11-15T11:56:45.123+01:00' as datetimeoffset(3))",
171 time.Date(2010, 11, 15, 11, 56, 45, 123000000, time.FixedZone("", 60*60))},
172 {"cast(cast('2010-11-15T11:56:45.123+10:00' as datetimeoffset(3)) as sql_variant)",
173 time.Date(2010, 11, 15, 11, 56, 45, 123000000, time.FixedZone("", 10*60*60))},
174 }
175
176 conn := open(t)
177 defer conn.Close()
178 for _, test := range values {
179 row := conn.QueryRow("select " + test.sql)
180 var retval interface{}
181 err := row.Scan(&retval)
182 if err != nil {
183 t.Error("Scan failed:", test.sql, err.Error())
184 continue
185 }
186 retvalDate := retval.(time.Time)
187 if retvalDate.UTC() != test.val.UTC() {
188 t.Errorf("UTC values don't match '%v' '%v' for test: %s", retvalDate, test.val, test.sql)
189 continue
190 }
191 if retvalDate.String() != test.val.String() {
192 t.Errorf("Locations don't match '%v' '%v' for test: %s", retvalDate.String(), test.val.String(), test.sql)
193 continue
194 }
195 }
196 }
197
198 func TestSelectNewTypes(t *testing.T) {
199 conn := open(t)
200 defer conn.Close()
201 var ver string
202 err := conn.QueryRow("select SERVERPROPERTY('productversion')").Scan(&ver)
203 if err != nil {
204 t.Fatalf("cannot select productversion: %s", err)
205 }
206 var n int
207 _, err = fmt.Sscanf(ver, "%d", &n)
208 if err != nil {
209 t.Fatalf("cannot parse productversion: %s", err)
210 }
211 // 8 is SQL 2000, 9 is SQL 2005, 10 is SQL 2008, 11 is SQL 2012
212 if n < 10 {
213 return
214 }
215 // run tests for new data types available only in SQL Server 2008 and later
216 type testStruct struct {
217 sql string
218 val interface{}
219 }
220 values := []testStruct{
221 {"cast('2000-01-01' as date)",
222 time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)},
223 {"cast(NULL as date)", nil},
224 {"cast('00:00:45.123' as time(3))",
225 time.Date(1, 1, 1, 00, 00, 45, 123000000, time.UTC)},
226 {"cast('11:56:45.123' as time(3))",
227 time.Date(1, 1, 1, 11, 56, 45, 123000000, time.UTC)},
228 {"cast('11:56:45' as time(0))",
229 time.Date(1, 1, 1, 11, 56, 45, 0, time.UTC)},
230 {"cast('2010-11-15T11:56:45.123' as datetime2(3))",
231 time.Date(2010, 11, 15, 11, 56, 45, 123000000, time.UTC)},
232 {"cast('2010-11-15T11:56:45' as datetime2(0))",
233 time.Date(2010, 11, 15, 11, 56, 45, 0, time.UTC)},
234 {"cast(cast('2000-01-01' as date) as sql_variant)",
235 time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)},
236 {"cast(cast('00:00:45.123' as time(3)) as sql_variant)",
237 time.Date(1, 1, 1, 00, 00, 45, 123000000, time.UTC)},
238 {"cast(cast('2010-11-15T11:56:45.123' as datetime2(3)) as sql_variant)",
239 time.Date(2010, 11, 15, 11, 56, 45, 123000000, time.UTC)},
240 }
241 for _, test := range values {
242 stmt, err := conn.Prepare("select " + test.sql)
243 if err != nil {
244 t.Error("Prepare failed:", test.sql, err.Error())
245 return
246 }
247 defer stmt.Close()
248
249 row := stmt.QueryRow()
250 var retval interface{}
251 err = row.Scan(&retval)
252 if err != nil {
253 t.Error("Scan failed:", test.sql, err.Error())
254 continue
255 }
256 if retval != test.val {
257 t.Errorf("Values don't match '%s' '%s' for test: %s", retval, test.val, test.sql)
258 continue
259 }
260 }
261 }
262
263 func TestTrans(t *testing.T) {
264 conn := open(t)
265 defer conn.Close()
266
267 var tx *sql.Tx
268 var err error
269 if tx, err = conn.Begin(); err != nil {
270 t.Fatal("Begin failed", err.Error())
271 }
272 if err = tx.Commit(); err != nil {
273 t.Fatal("Commit failed", err.Error())
274 }
275
276 if tx, err = conn.Begin(); err != nil {
277 t.Fatal("Begin failed", err.Error())
278 }
279 if _, err = tx.Exec("create table #abc (fld int)"); err != nil {
280 t.Fatal("Create table failed", err.Error())
281 }
282 if err = tx.Rollback(); err != nil {
283 t.Fatal("Rollback failed", err.Error())
284 }
285 }
286
287 func TestParams(t *testing.T) {
288 longstr := strings.Repeat("x", 10000)
289 longbytes := make([]byte, 10000)
290 values := []interface{}{
291 int64(5),
292 "hello",
293 "",
294 []byte{1, 2, 3},
295 []byte{},
296 float64(1.12313554),
297 true,
298 false,
299 nil,
300 longstr,
301 longbytes,
302 }
303
304 conn := open(t)
305 defer conn.Close()
306
307 for _, val := range values {
308 row := conn.QueryRow("select ?", val)
309 var retval interface{}
310 err := row.Scan(&retval)
311 if err != nil {
312 t.Error("Scan failed", err.Error())
313 return
314 }
315 var same bool
316 switch decodedval := retval.(type) {
317 case []byte:
318 switch decodedvaltest := val.(type) {
319 case []byte:
320 same = bytes.Equal(decodedval, decodedvaltest)
321 default:
322 same = false
323 }
324 default:
325 same = retval == val
326 }
327 if !same {
328 t.Error("Value don't match", retval, val)
329 return
330 }
331 }
332 }
333
334 func TestExec(t *testing.T) {
335 conn := open(t)
336 defer conn.Close()
337
338 res, err := conn.Exec("create table #abc (fld int)")
339 if err != nil {
340 t.Fatal("Exec failed", err.Error())
341 }
342 _ = res
343 }
344
345 func TestShortTimeout(t *testing.T) {
346 t.Skip("TODO: fix this test")
347 if testing.Short() {
348 t.Skip("short")
349 }
350 checkConnStr(t)
351 SetLogger(testLogger{t})
352 dsn := makeConnStr(t)
353 dsnParams := dsn.Query()
354 dsnParams.Set("Connection Timeout", "2")
355 dsn.RawQuery = dsnParams.Encode()
356 conn, err := sql.Open("mssql", dsn.String())
357 if err != nil {
358 t.Fatal("Open connection failed:", err.Error())
359 }
360 defer conn.Close()
361
362 _, err = conn.Exec("waitfor delay '00:00:15'")
363 if err == nil {
364 t.Fatal("Exec should fail with timeout, but no failure occurred")
365 }
366 if neterr, ok := err.(net.Error); !ok || !neterr.Timeout() {
367 t.Fatal("failure not a timeout, failed with", err)
368 }
369
370 // connection should be usable after timeout
371 row := conn.QueryRow("select 1")
372 var val int64
373 err = row.Scan(&val)
374 if err != nil {
375 t.Fatal("Scan failed with", err)
376 }
377 }
378
379 func TestTwoQueries(t *testing.T) {
380 conn := open(t)
381 defer conn.Close()
382
383 rows, err := conn.Query("select 1")
384 if err != nil {
385 t.Fatal("First exec failed", err)
386 }
387 if !rows.Next() {
388 t.Fatal("First query didn't return row")
389 }
390 var i int
391 if err = rows.Scan(&i); err != nil {
392 t.Fatal("Scan failed", err)
393 }
394 if i != 1 {
395 t.Fatalf("Wrong value returned %d, should be 1", i)
396 }
397
398 if rows, err = conn.Query("select 2"); err != nil {
399 t.Fatal("Second query failed", err)
400 }
401 if !rows.Next() {
402 t.Fatal("Second query didn't return row")
403 }
404 if err = rows.Scan(&i); err != nil {
405 t.Fatal("Scan failed", err)
406 }
407 if i != 2 {
408 t.Fatalf("Wrong value returned %d, should be 2", i)
409 }
410 }
411
412 func TestError(t *testing.T) {
413 conn := open(t)
414 defer conn.Close()
415
416 _, err := conn.Query("exec bad")
417 if err == nil {
418 t.Fatal("Query should fail")
419 }
420
421 if sqlerr, ok := err.(Error); !ok {
422 t.Fatalf("Should be sql error, actually %T, %v", err, err)
423 } else {
424 if sqlerr.Number != 2812 { // Could not find stored procedure 'bad'
425 t.Fatalf("Should be specific error code 2812, actually %d %s", sqlerr.Number, sqlerr)
426 }
427 }
428 }
429
430 func TestQueryNoRows(t *testing.T) {
431 conn := open(t)
432 defer conn.Close()
433
434 var rows *sql.Rows
435 var err error
436 if rows, err = conn.Query("create table #abc (fld int)"); err != nil {
437 t.Fatal("Query failed", err)
438 }
439 if rows.Next() {
440 t.Fatal("Query shoulnd't return any rows")
441 }
442 }
443
444 func TestQueryManyNullsRow(t *testing.T) {
445 conn := open(t)
446 defer conn.Close()
447
448 var row *sql.Row
449 var err error
450 if row = conn.QueryRow("select null, null, null, null, null, null, null, null"); err != nil {
451 t.Fatal("Query failed", err)
452 }
453 var v [8]sql.NullInt64
454 if err = row.Scan(&v[0], &v[1], &v[2], &v[3], &v[4], &v[5], &v[6], &v[7]); err != nil {
455 t.Fatal("Scan failed", err)
456 }
457 }
458
459 func TestOrderBy(t *testing.T) {
460 conn := open(t)
461 defer conn.Close()
462
463 tx, err := conn.Begin()
464 if err != nil {
465 t.Fatal("Begin tran failed", err)
466 }
467 defer tx.Rollback()
468
469 _, err = tx.Exec("if (exists(select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME='tbl')) drop table tbl")
470 if err != nil {
471 t.Fatal("Drop table failed", err)
472 }
473
474 _, err = tx.Exec("create table tbl (fld1 int primary key, fld2 int)")
475 if err != nil {
476 t.Fatal("Create table failed", err)
477 }
478 _, err = tx.Exec("insert into tbl (fld1, fld2) values (1, 2)")
479 if err != nil {
480 t.Fatal("Insert failed", err)
481 }
482 _, err = tx.Exec("insert into tbl (fld1, fld2) values (2, 1)")
483 if err != nil {
484 t.Fatal("Insert failed", err)
485 }
486
487 rows, err := tx.Query("select * from tbl order by fld1")
488 if err != nil {
489 t.Fatal("Query failed", err)
490 }
491
492 for rows.Next() {
493 var fld1 int32
494 var fld2 int32
495 err = rows.Scan(&fld1, &fld2)
496 if err != nil {
497 t.Fatal("Scan failed", err)
498 }
499 }
500
501 err = rows.Err()
502 if err != nil {
503 t.Fatal("Rows have errors", err)
504 }
505 }
506
507 func TestScanDecimal(t *testing.T) {
508 conn := open(t)
509 defer conn.Close()
510
511 var f float64
512 err := conn.QueryRow("select cast(0.5 as numeric(25,1))").Scan(&f)
513 if err != nil {
514 t.Error("query row / scan failed:", err.Error())
515 return
516 }
517 if math.Abs(f-0.5) > 0.000001 {
518 t.Error("Value is not 0.5:", f)
519 return
520 }
521
522 var s string
523 err = conn.QueryRow("select cast(-0.05 as numeric(25,2))").Scan(&s)
524 if err != nil {
525 t.Error("query row / scan failed:", err.Error())
526 return
527 }
528 if s != "-0.05" {
529 t.Error("Value is not -0.05:", s)
530 return
531 }
532 }
533
534 func TestAffectedRows(t *testing.T) {
535 conn := open(t)
536 defer conn.Close()
537
538 tx, err := conn.Begin()
539 if err != nil {
540 t.Fatal("Begin tran failed", err)
541 }
542 defer tx.Rollback()
543
544 res, err := tx.Exec("create table #foo (bar int)")
545 if err != nil {
546 t.Fatal("create table failed")
547 }
548 n, err := res.RowsAffected()
549 if err != nil {
550 t.Fatal("rows affected failed")
551 }
552 if n != 0 {
553 t.Error("Expected 0 rows affected, got ", n)
554 }
555
556 res, err = tx.Exec("insert into #foo (bar) values (1)")
557 if err != nil {
558 t.Fatal("insert failed")
559 }
560 n, err = res.RowsAffected()
561 if err != nil {
562 t.Fatal("rows affected failed")
563 }
564 if n != 1 {
565 t.Error("Expected 1 row affected, got ", n)
566 }
567
568 res, err = tx.Exec("insert into #foo (bar) values (?)", 2)
569 if err != nil {
570 t.Fatal("insert failed")
571 }
572 n, err = res.RowsAffected()
573 if err != nil {
574 t.Fatal("rows affected failed")
575 }
576 if n != 1 {
577 t.Error("Expected 1 row affected, got ", n)
578 }
579 }
580
581 func TestIdentity(t *testing.T) {
582 conn := open(t)
583 defer conn.Close()
584
585 tx, err := conn.Begin()
586 if err != nil {
587 t.Fatal("Begin tran failed", err)
588 }
589 defer tx.Rollback()
590
591 res, err := tx.Exec("create table #foo (bar int identity, baz int unique)")
592 if err != nil {
593 t.Fatal("create table failed")
594 }
595
596 res, err = tx.Exec("insert into #foo (baz) values (1)")
597 if err != nil {
598 t.Fatal("insert failed")
599 }
600 n, err := res.LastInsertId()
601 if err != nil {
602 t.Fatal("last insert id failed")
603 }
604 if n != 1 {
605 t.Error("Expected 1 for identity, got ", n)
606 }
607
608 res, err = tx.Exec("insert into #foo (baz) values (20)")
609 if err != nil {
610 t.Fatal("insert failed")
611 }
612 n, err = res.LastInsertId()
613 if err != nil {
614 t.Fatal("last insert id failed")
615 }
616 if n != 2 {
617 t.Error("Expected 2 for identity, got ", n)
618 }
619
620 res, err = tx.Exec("insert into #foo (baz) values (1)")
621 if err == nil {
622 t.Fatal("insert should fail")
623 }
624
625 res, err = tx.Exec("insert into #foo (baz) values (?)", 1)
626 if err == nil {
627 t.Fatal("insert should fail")
628 }
629 }
630
631 func TestDateTimeParam(t *testing.T) {
632 conn := open(t)
633 defer conn.Close()
634 type testStruct struct {
635 t time.Time
636 }
637 values := []testStruct{
638 {time.Date(2004, 6, 3, 12, 13, 14, 150000000, time.UTC)},
639 {time.Date(4, 6, 3, 12, 13, 14, 150000000, time.UTC)},
640 }
641 for _, test := range values {
642 var t2 time.Time
643 err := conn.QueryRow("select ?", test.t).Scan(&t2)
644 if err != nil {
645 t.Error("select / scan failed", err.Error())
646 continue
647 }
648 if test.t.Sub(t2) != 0 {
649 t.Errorf("datetime does not match: '%s' '%s' delta: %d", test.t, t2, test.t.Sub(t2))
650 }
651 }
652
653 }
654
655 func TestUniqueIdentifierParam(t *testing.T) {
656 conn := open(t)
657 defer conn.Close()
658 type testStruct struct {
659 name string
660 uuid interface{}
661 }
662
663 expected := UniqueIdentifier{0x01, 0x23, 0x45, 0x67,
664 0x89, 0xAB,
665 0xCD, 0xEF,
666 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF,
667 }
668
669 values := []testStruct{
670 {
671 "[]byte",
672 []byte{0x67, 0x45, 0x23, 0x01,
673 0xAB, 0x89,
674 0xEF, 0xCD,
675 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}},
676 {
677 "string",
678 "01234567-89ab-cdef-0123-456789abcdef"},
679 }
680
681 for _, test := range values {
682 t.Run(test.name, func(t *testing.T) {
683 var uuid2 UniqueIdentifier
684 err := conn.QueryRow("select ?", test.uuid).Scan(&uuid2)
685 if err != nil {
686 t.Fatal("select / scan failed", err.Error())
687 }
688
689 if expected != uuid2 {
690 t.Errorf("uniqueidentifier does not match: '%s' '%s'", expected, uuid2)
691 }
692 })
693 }
694 }
695
696 func TestBigQuery(t *testing.T) {
697 conn := open(t)
698 defer conn.Close()
699 rows, err := conn.Query(`WITH n(n) AS
700 (
701 SELECT 1
702 UNION ALL
703 SELECT n+1 FROM n WHERE n < 10000
704 )
705 SELECT n, @@version FROM n ORDER BY n
706 OPTION (MAXRECURSION 10000);`)
707 if err != nil {
708 t.Fatal("cannot exec query", err)
709 }
710 rows.Next()
711 rows.Close()
712 var res int
713 err = conn.QueryRow("select 0").Scan(&res)
714 if err != nil {
715 t.Fatal("cannot scan value", err)
716 }
717 if res != 0 {
718 t.Fatal("expected 0, got ", res)
719 }
720 }
721
722 func TestBug32(t *testing.T) {
723 conn := open(t)
724 defer conn.Close()
725
726 tx, err := conn.Begin()
727 if err != nil {
728 t.Fatal("Begin tran failed", err)
729 }
730 defer tx.Rollback()
731
732 _, err = tx.Exec("if (exists(select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME='tbl')) drop table tbl")
733 if err != nil {
734 t.Fatal("Drop table failed", err)
735 }
736
737 _, err = tx.Exec("create table tbl(a int primary key,fld bit null)")
738 if err != nil {
739 t.Fatal("Create table failed", err)
740 }
741
742 _, err = tx.Exec("insert into tbl (a,fld) values (1,nullif(?, ''))", "")
743 if err != nil {
744 t.Fatal("Insert failed", err)
745 }
746 }
747
748 func TestIgnoreEmptyResults(t *testing.T) {
749 conn := open(t)
750 defer conn.Close()
751 rows, err := conn.Query("set nocount on; select 2")
752 if err != nil {
753 t.Fatal("Query failed", err.Error())
754 }
755 if !rows.Next() {
756 t.Fatal("Query didn't return row")
757 }
758 var fld1 int32
759 err = rows.Scan(&fld1)
760 if err != nil {
761 t.Fatal("Scan failed", err)
762 }
763 if fld1 != 2 {
764 t.Fatal("Returned value doesn't match")
765 }
766 }
767
768 func TestMssqlStmt_SetQueryNotification(t *testing.T) {
769 checkConnStr(t)
770 mssqldriver := driverWithProcess(t)
771 cn, err := mssqldriver.Open(makeConnStr(t).String())
772 stmt, err := cn.Prepare("SELECT 1")
773 if err != nil {
774 t.Error("Connection failed", err)
775 }
776
777 sqlstmt := stmt.(*MssqlStmt)
778 sqlstmt.SetQueryNotification("ABC", "service=WebCacheNotifications", time.Hour)
779
780 rows, err := sqlstmt.Query(nil)
781 if err == nil {
782 rows.Close()
783 }
784 // notifications are sent to Service Broker
785 // see for more info: https://github.com/denisenkom/go-mssqldb/pull/90
786 }
787
788 func TestErrorInfo(t *testing.T) {
789 conn := open(t)
790 defer conn.Close()
791
792 _, err := conn.Exec("select bad")
793 if sqlError, ok := err.(Error); ok {
794 if sqlError.SQLErrorNumber() != 207 /*invalid column name*/ {
795 t.Errorf("Query failed with unexpected error number %d %s", sqlError.SQLErrorNumber(), sqlError.SQLErrorMessage())
796 }
797 } else {
798 t.Error("Failed to convert error to SQLErorr", err)
799 }
800 }
801
802 func TestSetLanguage(t *testing.T) {
803 conn := open(t)
804 defer conn.Close()
805
806 _, err := conn.Exec("set language russian")
807 if err != nil {
808 t.Errorf("Query failed with unexpected error %s", err)
809 }
810
811 row := conn.QueryRow("select cast(getdate() as varchar(50))")
812 var val interface{}
813 err = row.Scan(&val)
814 if err != nil {
815 t.Errorf("Query failed with unexpected error %s", err)
816 }
817 t.Log("Returned value", val)
818 }
819
820 func TestConnectionClosing(t *testing.T) {
821 conn := open(t)
822 defer conn.Close()
823 for i := 1; i <= 100; i++ {
824 if conn.Stats().OpenConnections > 1 {
825 t.Errorf("Open connections is expected to stay <= 1, but it is %d", conn.Stats().OpenConnections)
826 return
827 }
828
829 stmt, err := conn.Query("select 1")
830 if err != nil {
831 t.Errorf("Query failed with unexpected error %s", err)
832 }
833 for stmt.Next() {
834 var val interface{}
835 err := stmt.Scan(&val)
836 if err != nil {
837 t.Errorf("Query failed with unexpected error %s", err)
838 }
839 }
840 }
841 }
842
843 func TestBeginTranError(t *testing.T) {
844 t.Skip("TODO: fix this test")
845 checkConnStr(t)
846 drv := driverWithProcess(t)
847 conn, err := drv.open(makeConnStr(t).String())
848 if err != nil {
849 t.Fatalf("Open failed with error %v", err)
850 }
851
852 defer conn.Close()
853 // close actual connection to make begin transaction to fail during sending of a packet
854 conn.sess.buf.transport.Close()
855
856 ctx := context.Background()
857 _, err = conn.begin(ctx, isolationSnapshot)
858 if err != driver.ErrBadConn {
859 t.Errorf("begin should fail with ErrBadConn but it returned %v", err)
860 }
861
862 // reopen connection
863 conn, err = drv.open(makeConnStr(t).String())
864 if err != nil {
865 t.Fatalf("Open failed with error %v", err)
866 }
867 err = conn.sendBeginRequest(ctx, isolationSerializable)
868 if err != nil {
869 t.Fatalf("sendBeginRequest failed with error %v", err)
870 }
871
872 // close connection to cause processBeginResponse to fail
873 conn.sess.buf.transport.Close()
874 _, err = conn.processBeginResponse(ctx)
875 switch err {
876 case nil:
877 t.Error("processBeginResponse should fail but it succeeded")
878 case driver.ErrBadConn:
879 t.Error("processBeginResponse should fail with error different from ErrBadConn but it did")
880 }
881 }
882
883 func TestCommitTranError(t *testing.T) {
884 t.Skip("TODO: fix this test")
885 checkConnStr(t)
886 drv := driverWithProcess(t)
887 conn, err := drv.open(makeConnStr(t).String())
888 if err != nil {
889 t.Fatalf("Open failed with error %v", err)
890 }
891
892 defer conn.Close()
893 // close actual connection to make commit transaction to fail during sending of a packet
894 conn.sess.buf.transport.Close()
895
896 ctx := context.Background()
897 err = conn.Commit()
898 if err != driver.ErrBadConn {
899 t.Errorf("begin should fail with ErrBadConn but it returned %v", err)
900 }
901
902 // reopen connection
903 conn, err = drv.open(makeConnStr(t).String())
904 if err != nil {
905 t.Fatalf("Open failed with error %v", err)
906 }
907 err = conn.sendCommitRequest()
908 if err != nil {
909 t.Fatalf("sendCommitRequest failed with error %v", err)
910 }
911
912 // close connection to cause processBeginResponse to fail
913 conn.sess.buf.transport.Close()
914 err = conn.simpleProcessResp(ctx)
915 switch err {
916 case nil:
917 t.Error("simpleProcessResp should fail but it succeeded")
918 case driver.ErrBadConn:
919 t.Error("simpleProcessResp should fail with error different from ErrBadConn but it did")
920 }
921
922 // reopen connection
923 conn, err = drv.open(makeConnStr(t).String())
924 defer conn.Close()
925 if err != nil {
926 t.Fatalf("Open failed with error %v", err)
927 }
928 // should fail because there is no transaction
929 err = conn.Commit()
930 switch err {
931 case nil:
932 t.Error("Commit should fail but it succeeded")
933 case driver.ErrBadConn:
934 t.Error("Commit should fail with error different from ErrBadConn but it did")
935 }
936 }
937
938 func TestRollbackTranError(t *testing.T) {
939 t.Skip("TODO: fix this test")
940 checkConnStr(t)
941 drv := driverWithProcess(t)
942 conn, err := drv.open(makeConnStr(t).String())
943 if err != nil {
944 t.Fatalf("Open failed with error %v", err)
945 }
946
947 defer conn.Close()
948 // close actual connection to make commit transaction to fail during sending of a packet
949 conn.sess.buf.transport.Close()
950
951 ctx := context.Background()
952 err = conn.Rollback()
953 if err != driver.ErrBadConn {
954 t.Errorf("Rollback should fail with ErrBadConn but it returned %v", err)
955 }
956
957 // reopen connection
958 conn, err = drv.open(makeConnStr(t).String())
959 if err != nil {
960 t.Fatalf("Open failed with error %v", err)
961 }
962 err = conn.sendRollbackRequest()
963 if err != nil {
964 t.Fatalf("sendCommitRequest failed with error %v", err)
965 }
966
967 // close connection to cause processBeginResponse to fail
968 conn.sess.buf.transport.Close()
969 err = conn.simpleProcessResp(ctx)
970 switch err {
971 case nil:
972 t.Error("simpleProcessResp should fail but it succeeded")
973 case driver.ErrBadConn:
974 t.Error("simpleProcessResp should fail with error different from ErrBadConn but it did")
975 }
976
977 // reopen connection
978 conn, err = drv.open(makeConnStr(t).String())
979 defer conn.Close()
980 if err != nil {
981 t.Fatalf("Open failed with error %v", err)
982 }
983 // should fail because there is no transaction
984 err = conn.Rollback()
985 switch err {
986 case nil:
987 t.Error("Commit should fail but it succeeded")
988 case driver.ErrBadConn:
989 t.Error("Commit should fail with error different from ErrBadConn but it did")
990 }
991 }
992
993 func TestSendQueryErrors(t *testing.T) {
994 checkConnStr(t)
995 drv := driverWithProcess(t)
996 conn, err := drv.open(makeConnStr(t).String())
997 if err != nil {
998 t.FailNow()
999 }
1000
1001 defer conn.Close()
1002 stmt, err := conn.prepareContext(context.Background(), "select 1")
1003 if err != nil {
1004 t.FailNow()
1005 }
1006
1007 // should fail because parameter is invalid
1008 _, err = stmt.Query([]driver.Value{conn})
1009 if err == nil {
1010 t.Fail()
1011 }
1012
1013 // close actual connection to make commit transaction to fail during sending of a packet
1014 conn.sess.buf.transport.Close()
1015
1016 // should fail because connection is closed
1017 _, err = stmt.Query([]driver.Value{})
1018 if err != driver.ErrBadConn {
1019 t.Fail()
1020 }
1021
1022 stmt, err = conn.prepareContext(context.Background(), "select ?")
1023 if err != nil {
1024 t.FailNow()
1025 }
1026 // should fail because connection is closed
1027 _, err = stmt.Query([]driver.Value{int64(1)})
1028 if err != driver.ErrBadConn {
1029 t.Fail()
1030 }
1031 }
1032
1033 func TestProcessQueryErrors(t *testing.T) {
1034 t.Skip("TODO: fix this test")
1035 checkConnStr(t)
1036 drv := driverWithProcess(t)
1037 conn, err := drv.open(makeConnStr(t).String())
1038 if err != nil {
1039 t.Fatal("open expected to succeed, but it failed with", err)
1040 }
1041 stmt, err := conn.prepareContext(context.Background(), "select 1")
1042 if err != nil {
1043 t.Fatal("prepareContext expected to succeed, but it failed with", err)
1044 }
1045 err = stmt.sendQuery([]namedValue{})
1046 if err != nil {
1047 t.Fatal("sendQuery expected to succeed, but it failed with", err)
1048 }
1049 // close actual connection to make reading response to fail
1050 conn.sess.buf.transport.Close()
1051 _, err = stmt.processQueryResponse(context.Background())
1052 if err == nil {
1053 t.Error("processQueryResponse expected to fail but it succeeded")
1054 }
1055 // should not fail with ErrBadConn because query was successfully sent to server
1056 if err == driver.ErrBadConn {
1057 t.Error("processQueryResponse expected to fail with error other than ErrBadConn but it failed with it")
1058 }
1059 }
1060
1061 func TestSendExecErrors(t *testing.T) {
1062 checkConnStr(t)
1063 drv := driverWithProcess(t)
1064 conn, err := drv.open(makeConnStr(t).String())
1065 if err != nil {
1066 t.FailNow()
1067 }
1068
1069 defer conn.Close()
1070 stmt, err := conn.prepareContext(context.Background(), "select 1")
1071 if err != nil {
1072 t.FailNow()
1073 }
1074
1075 // should fail because parameter is invalid
1076 _, err = stmt.Exec([]driver.Value{conn})
1077 if err == nil {
1078 t.Fail()
1079 }
1080
1081 // close actual connection to make commit transaction to fail during sending of a packet
1082 conn.sess.buf.transport.Close()
1083
1084 // should fail because connection is closed
1085 _, err = stmt.Exec([]driver.Value{})
1086 if err != driver.ErrBadConn {
1087 t.Fail()
1088 }
1089
1090 stmt, err = conn.prepareContext(context.Background(), "select ?")
1091 if err != nil {
1092 t.FailNow()
1093 }
1094 // should fail because connection is closed
1095 _, err = stmt.Exec([]driver.Value{int64(1)})
1096 if err != driver.ErrBadConn {
1097 t.Fail()
1098 }
1099 }