Debian Codegraph @

mssql.go

raw symbols SCIP
1 package mssql
2
3 import (
4 "database/sql"
5 "database/sql/driver"
6 "encoding/binary"
7 "errors"
8 "fmt"
9 "golang.org/x/net/context" // use the "x/net/context" for backwards compatibility.
10 "io"
11 "math"
12 "net"
13 "reflect"
14 "strings"
15 "time"
16 )
17
18 var driverInstance = &MssqlDriver{processQueryText: true}
19 var driverInstanceNoProcess = &MssqlDriver{processQueryText: false}
20
21 func init() {
22 sql.Register("mssql", driverInstance)
23 sql.Register("sqlserver", driverInstanceNoProcess)
24 }
25
26 // Abstract the dialer for testing and for non-TCP based connections.
27 type dialer interface {
28 Dial(addr string) (net.Conn, error)
29 }
30
31 var createDialer func(p *connectParams) dialer
32
33 type tcpDialer struct {
34 nd *net.Dialer
35 }
36
37 func (d tcpDialer) Dial(addr string) (net.Conn, error) {
38 return d.nd.Dial("tcp", addr)
39 }
40
41 type MssqlDriver struct {
42 log optionalLogger
43
44 processQueryText bool
45 }
46
47 func SetLogger(logger Logger) {
48 driverInstance.SetLogger(logger)
49 driverInstanceNoProcess.SetLogger(logger)
50 }
51
52 func (d *MssqlDriver) SetLogger(logger Logger) {
53 d.log = optionalLogger{logger}
54 }
55
56 type MssqlConn struct {
57 sess *tdsSession
58 transactionCtx context.Context
59
60 processQueryText bool
61 }
62
63 func (c *MssqlConn) simpleProcessResp(ctx context.Context) error {
64 tokchan := make(chan tokenStruct, 5)
65 go processResponse(ctx, c.sess, tokchan)
66 for tok := range tokchan {
67 switch token := tok.(type) {
68 case doneStruct:
69 if token.isError() {
70 return token.getError()
71 }
72 case error:
73 return token
74 }
75 }
76 return nil
77 }
78
79 func (c *MssqlConn) Commit() error {
80 if err := c.sendCommitRequest(); err != nil {
81 return err
82 }
83 return c.simpleProcessResp(c.transactionCtx)
84 }
85
86 func (c *MssqlConn) sendCommitRequest() error {
87 headers := []headerStruct{
88 {hdrtype: dataStmHdrTransDescr,
89 data: transDescrHdr{c.sess.tranid, 1}.pack()},
90 }
91 if err := sendCommitXact(c.sess.buf, headers, "", 0, 0, ""); err != nil {
92 if c.sess.logFlags&logErrors != 0 {
93 c.sess.log.Printf("Failed to send CommitXact with %v", err)
94 }
95 return driver.ErrBadConn
96 }
97 return nil
98 }
99
100 func (c *MssqlConn) Rollback() error {
101 if err := c.sendRollbackRequest(); err != nil {
102 return err
103 }
104 return c.simpleProcessResp(c.transactionCtx)
105 }
106
107 func (c *MssqlConn) sendRollbackRequest() error {
108 headers := []headerStruct{
109 {hdrtype: dataStmHdrTransDescr,
110 data: transDescrHdr{c.sess.tranid, 1}.pack()},
111 }
112 if err := sendRollbackXact(c.sess.buf, headers, "", 0, 0, ""); err != nil {
113 if c.sess.logFlags&logErrors != 0 {
114 c.sess.log.Printf("Failed to send RollbackXact with %v", err)
115 }
116 return driver.ErrBadConn
117 }
118 return nil
119 }
120
121 func (c *MssqlConn) Begin() (driver.Tx, error) {
122 return c.begin(context.Background(), isolationUseCurrent)
123 }
124
125 func (c *MssqlConn) begin(ctx context.Context, tdsIsolation isoLevel) (driver.Tx, error) {
126 err := c.sendBeginRequest(ctx, tdsIsolation)
127 if err != nil {
128 return nil, err
129 }
130 return c.processBeginResponse(ctx)
131 }
132
133 func (c *MssqlConn) sendBeginRequest(ctx context.Context, tdsIsolation isoLevel) error {
134 c.transactionCtx = ctx
135 headers := []headerStruct{
136 {hdrtype: dataStmHdrTransDescr,
137 data: transDescrHdr{0, 1}.pack()},
138 }
139 if err := sendBeginXact(c.sess.buf, headers, tdsIsolation, ""); err != nil {
140 if c.sess.logFlags&logErrors != 0 {
141 c.sess.log.Printf("Failed to send BeginXact with %v", err)
142 }
143 return driver.ErrBadConn
144 }
145 return nil
146 }
147
148 func (c *MssqlConn) processBeginResponse(ctx context.Context) (driver.Tx, error) {
149 if err := c.simpleProcessResp(ctx); err != nil {
150 return nil, err
151 }
152 // successful BEGINXACT request will return sess.tranid
153 // for started transaction
154 return c, nil
155 }
156
157 func (d *MssqlDriver) Open(dsn string) (driver.Conn, error) {
158 return d.open(dsn)
159 }
160
161 func (d *MssqlDriver) open(dsn string) (*MssqlConn, error) {
162 params, err := parseConnectParams(dsn)
163 if err != nil {
164 return nil, err
165 }
166
167 sess, err := connect(d.log, params)
168 if err != nil {
169 // main server failed, try fail-over partner
170 if params.failOverPartner == "" {
171 return nil, err
172 }
173
174 params.host = params.failOverPartner
175 if params.failOverPort != 0 {
176 params.port = params.failOverPort
177 }
178
179 sess, err = connect(d.log, params)
180 if err != nil {
181 // fail-over partner also failed, now fail
182 return nil, err
183 }
184 }
185
186 conn := &MssqlConn{sess, context.Background(), d.processQueryText}
187 conn.sess.log = d.log
188 return conn, nil
189 }
190
191 func (c *MssqlConn) Close() error {
192 return c.sess.buf.transport.Close()
193 }
194
195 type MssqlStmt struct {
196 c *MssqlConn
197 query string
198 paramCount int
199 notifSub *queryNotifSub
200 }
201
202 type queryNotifSub struct {
203 msgText string
204 options string
205 timeout uint32
206 }
207
208 func (c *MssqlConn) Prepare(query string) (driver.Stmt, error) {
209 if len(query) > 10 && strings.EqualFold(query[:10], "INSERTBULK") {
210 return c.prepareCopyIn(query)
211 }
212
213 return c.prepareContext(context.Background(), query)
214 }
215
216 func (c *MssqlConn) prepareContext(ctx context.Context, query string) (*MssqlStmt, error) {
217 paramCount := -1
218 if c.processQueryText {
219 query, paramCount = parseParams(query)
220 }
221 return &MssqlStmt{c, query, paramCount, nil}, nil
222 }
223
224 func (s *MssqlStmt) Close() error {
225 return nil
226 }
227
228 func (s *MssqlStmt) SetQueryNotification(id, options string, timeout time.Duration) {
229 to := uint32(timeout / time.Second)
230 if to < 1 {
231 to = 1
232 }
233 s.notifSub = &queryNotifSub{id, options, to}
234 }
235
236 func (s *MssqlStmt) NumInput() int {
237 return s.paramCount
238 }
239
240 func (s *MssqlStmt) sendQuery(args []namedValue) (err error) {
241 headers := []headerStruct{
242 {hdrtype: dataStmHdrTransDescr,
243 data: transDescrHdr{s.c.sess.tranid, 1}.pack()},
244 }
245
246 if s.notifSub != nil {
247 headers = append(headers, headerStruct{hdrtype: dataStmHdrQueryNotif,
248 data: queryNotifHdr{s.notifSub.msgText, s.notifSub.options, s.notifSub.timeout}.pack()})
249 }
250
251 // no need to check number of parameters here, it is checked by database/sql
252 if s.c.sess.logFlags&logSQL != 0 {
253 s.c.sess.log.Println(s.query)
254 }
255 if s.c.sess.logFlags&logParams != 0 && len(args) > 0 {
256 for i := 0; i < len(args); i++ {
257 s.c.sess.log.Printf("\t@p%d\t%v\n", i+1, args[i])
258 }
259
260 }
261 if len(args) == 0 {
262 if err = sendSqlBatch72(s.c.sess.buf, s.query, headers); err != nil {
263 if s.c.sess.logFlags&logErrors != 0 {
264 s.c.sess.log.Printf("Failed to send SqlBatch with %v", err)
265 }
266 return driver.ErrBadConn
267 }
268 } else {
269 params := make([]Param, len(args)+2)
270 decls := make([]string, len(args))
271 params[0] = makeStrParam(s.query)
272 for i, val := range args {
273 params[i+2], err = s.makeParam(val.Value)
274 if err != nil {
275 return
276 }
277 var name string
278 if len(val.Name) > 0 {
279 name = "@" + val.Name
280 } else {
281 name = fmt.Sprintf("@p%d", val.Ordinal)
282 }
283 params[i+2].Name = name
284 decls[i] = fmt.Sprintf("%s %s", name, makeDecl(params[i+2].ti))
285 }
286 params[1] = makeStrParam(strings.Join(decls, ","))
287 if err = sendRpc(s.c.sess.buf, headers, Sp_ExecuteSql, 0, params); err != nil {
288 if s.c.sess.logFlags&logErrors != 0 {
289 s.c.sess.log.Printf("Failed to send Rpc with %v", err)
290 }
291 return driver.ErrBadConn
292 }
293 }
294 return
295 }
296
297 type namedValue struct {
298 Name string
299 Ordinal int
300 Value driver.Value
301 }
302
303 func convertOldArgs(args []driver.Value) []namedValue {
304 list := make([]namedValue, len(args))
305 for i, v := range args {
306 list[i] = namedValue{
307 Ordinal: i + 1,
308 Value: v,
309 }
310 }
311 return list
312 }
313
314 func (s *MssqlStmt) Query(args []driver.Value) (driver.Rows, error) {
315 return s.queryContext(context.Background(), convertOldArgs(args))
316 }
317
318 func (s *MssqlStmt) queryContext(ctx context.Context, args []namedValue) (driver.Rows, error) {
319 if err := s.sendQuery(args); err != nil {
320 return nil, err
321 }
322 return s.processQueryResponse(ctx)
323 }
324
325 func (s *MssqlStmt) processQueryResponse(ctx context.Context) (res driver.Rows, err error) {
326 tokchan := make(chan tokenStruct, 5)
327 ctx, cancel := context.WithCancel(ctx)
328 go processResponse(ctx, s.c.sess, tokchan)
329 // process metadata
330 var cols []columnStruct
331 loop:
332 for tok := range tokchan {
333 switch token := tok.(type) {
334 // By ignoring DONE token we effectively
335 // skip empty result-sets.
336 // This improves results in queries like that:
337 // set nocount on; select 1
338 // see TestIgnoreEmptyResults test
339 //case doneStruct:
340 //break loop
341 case []columnStruct:
342 cols = token
343 break loop
344 case doneStruct:
345 if token.isError() {
346 return nil, token.getError()
347 }
348 case error:
349 return nil, token
350 }
351 }
352 res = &MssqlRows{sess: s.c.sess, tokchan: tokchan, cols: cols, cancel: cancel}
353 return
354 }
355
356 func (s *MssqlStmt) Exec(args []driver.Value) (driver.Result, error) {
357 return s.exec(context.Background(), convertOldArgs(args))
358 }
359
360 func (s *MssqlStmt) exec(ctx context.Context, args []namedValue) (driver.Result, error) {
361 if err := s.sendQuery(args); err != nil {
362 return nil, err
363 }
364 return s.processExec(ctx)
365 }
366
367 func (s *MssqlStmt) processExec(ctx context.Context) (res driver.Result, err error) {
368 tokchan := make(chan tokenStruct, 5)
369 go processResponse(ctx, s.c.sess, tokchan)
370 var rowCount int64
371 for token := range tokchan {
372 switch token := token.(type) {
373 case doneInProcStruct:
374 if token.Status&doneCount != 0 {
375 rowCount += int64(token.RowCount)
376 }
377 case doneStruct:
378 if token.Status&doneCount != 0 {
379 rowCount += int64(token.RowCount)
380 }
381 if token.isError() {
382 return nil, token.getError()
383 }
384 case error:
385 return nil, token
386 }
387 }
388 return &MssqlResult{s.c, rowCount}, nil
389 }
390
391 type MssqlRows struct {
392 sess *tdsSession
393 cols []columnStruct
394 tokchan chan tokenStruct
395
396 nextCols []columnStruct
397
398 cancel func()
399 }
400
401 func (rc *MssqlRows) Close() error {
402 rc.cancel()
403 for _ = range rc.tokchan {
404 }
405 rc.tokchan = nil
406 return nil
407 }
408
409 func (rc *MssqlRows) Columns() (res []string) {
410 res = make([]string, len(rc.cols))
411 for i, col := range rc.cols {
412 res[i] = col.ColName
413 }
414 return
415 }
416
417 func (rc *MssqlRows) Next(dest []driver.Value) error {
418 if rc.nextCols != nil {
419 return io.EOF
420 }
421 for tok := range rc.tokchan {
422 switch tokdata := tok.(type) {
423 case []columnStruct:
424 rc.nextCols = tokdata
425 return io.EOF
426 case []interface{}:
427 for i := range dest {
428 dest[i] = tokdata[i]
429 }
430 return nil
431 case doneStruct:
432 if tokdata.isError() {
433 return tokdata.getError()
434 }
435 case error:
436 return tokdata
437 }
438 }
439 return io.EOF
440 }
441
442 func (rc *MssqlRows) HasNextResultSet() bool {
443 return rc.nextCols != nil
444 }
445
446 func (rc *MssqlRows) NextResultSet() error {
447 rc.cols = rc.nextCols
448 rc.nextCols = nil
449 if rc.cols == nil {
450 return io.EOF
451 }
452 return nil
453 }
454
455 // It should return
456 // the value type that can be used to scan types into. For example, the database
457 // column type "bigint" this should return "reflect.TypeOf(int64(0))".
458 func (r *MssqlRows) ColumnTypeScanType(index int) reflect.Type {
459 return makeGoLangScanType(r.cols[index].ti)
460 }
461
462 // RowsColumnTypeDatabaseTypeName may be implemented by Rows. It should return the
463 // database system type name without the length. Type names should be uppercase.
464 // Examples of returned types: "VARCHAR", "NVARCHAR", "VARCHAR2", "CHAR", "TEXT",
465 // "DECIMAL", "SMALLINT", "INT", "BIGINT", "BOOL", "[]BIGINT", "JSONB", "XML",
466 // "TIMESTAMP".
467 func (r *MssqlRows) ColumnTypeDatabaseTypeName(index int) string {
468 return makeGoLangTypeName(r.cols[index].ti)
469 }
470
471 // RowsColumnTypeLength may be implemented by Rows. It should return the length
472 // of the column type if the column is a variable length type. If the column is
473 // not a variable length type ok should return false.
474 // If length is not limited other than system limits, it should return math.MaxInt64.
475 // The following are examples of returned values for various types:
476 // TEXT (math.MaxInt64, true)
477 // varchar(10) (10, true)
478 // nvarchar(10) (10, true)
479 // decimal (0, false)
480 // int (0, false)
481 // bytea(30) (30, true)
482 func (r *MssqlRows) ColumnTypeLength(index int) (int64, bool) {
483 return makeGoLangTypeLength(r.cols[index].ti)
484 }
485
486 // It should return
487 // the precision and scale for decimal types. If not applicable, ok should be false.
488 // The following are examples of returned values for various types:
489 // decimal(38, 4) (38, 4, true)
490 // int (0, 0, false)
491 // decimal (math.MaxInt64, math.MaxInt64, true)
492 func (r *MssqlRows) ColumnTypePrecisionScale(index int) (int64, int64, bool) {
493 return makeGoLangTypePrecisionScale(r.cols[index].ti)
494 }
495
496 // The nullable value should
497 // be true if it is known the column may be null, or false if the column is known
498 // to be not nullable.
499 // If the column nullability is unknown, ok should be false.
500 func (r *MssqlRows) ColumnTypeNullable(index int) (nullable, ok bool) {
501 nullable = r.cols[index].Flags&colFlagNullable != 0
502 ok = true
503 return
504 }
505
506 func makeStrParam(val string) (res Param) {
507 res.ti.TypeId = typeNVarChar
508 res.buffer = str2ucs2(val)
509 res.ti.Size = len(res.buffer)
510 return
511 }
512
513 func (s *MssqlStmt) makeParam(val driver.Value) (res Param, err error) {
514 if val == nil {
515 res.ti.TypeId = typeNVarChar
516 res.buffer = nil
517 res.ti.Size = 2
518 return
519 }
520 switch val := val.(type) {
521 case int64:
522 res.ti.TypeId = typeIntN
523 res.buffer = make([]byte, 8)
524 res.ti.Size = 8
525 binary.LittleEndian.PutUint64(res.buffer, uint64(val))
526 case float64:
527 res.ti.TypeId = typeFltN
528 res.ti.Size = 8
529 res.buffer = make([]byte, 8)
530 binary.LittleEndian.PutUint64(res.buffer, math.Float64bits(val))
531 case []byte:
532 res.ti.TypeId = typeBigVarBin
533 res.ti.Size = len(val)
534 res.buffer = val
535 case string:
536 res = makeStrParam(val)
537 case bool:
538 res.ti.TypeId = typeBitN
539 res.ti.Size = 1
540 res.buffer = make([]byte, 1)
541 if val {
542 res.buffer[0] = 1
543 }
544 case time.Time:
545 if s.c.sess.loginAck.TDSVersion >= verTDS73 {
546 res.ti.TypeId = typeDateTimeOffsetN
547 res.ti.Scale = 7
548 res.ti.Size = 10
549 buf := make([]byte, 10)
550 res.buffer = buf
551 days, ns := dateTime2(val)
552 ns /= 100
553 buf[0] = byte(ns)
554 buf[1] = byte(ns >> 8)
555 buf[2] = byte(ns >> 16)
556 buf[3] = byte(ns >> 24)
557 buf[4] = byte(ns >> 32)
558 buf[5] = byte(days)
559 buf[6] = byte(days >> 8)
560 buf[7] = byte(days >> 16)
561 _, offset := val.Zone()
562 offset /= 60
563 buf[8] = byte(offset)
564 buf[9] = byte(offset >> 8)
565 } else {
566 res.ti.TypeId = typeDateTimeN
567 res.ti.Size = 8
568 res.buffer = make([]byte, 8)
569 ref := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC)
570 dur := val.Sub(ref)
571 days := dur / (24 * time.Hour)
572 tm := (300 * (dur % (24 * time.Hour))) / time.Second
573 binary.LittleEndian.PutUint32(res.buffer[0:4], uint32(days))
574 binary.LittleEndian.PutUint32(res.buffer[4:8], uint32(tm))
575 }
576 default:
577 err = fmt.Errorf("mssql: unknown type for %T", val)
578 return
579 }
580 return
581 }
582
583 type MssqlResult struct {
584 c *MssqlConn
585 rowsAffected int64
586 }
587
588 func (r *MssqlResult) RowsAffected() (int64, error) {
589 return r.rowsAffected, nil
590 }
591
592 func (r *MssqlResult) LastInsertId() (int64, error) {
593 s, err := r.c.Prepare("select cast(@@identity as bigint)")
594 if err != nil {
595 return 0, err
596 }
597 defer s.Close()
598 rows, err := s.Query(nil)
599 if err != nil {
600 return 0, err
601 }
602 defer rows.Close()
603 dest := make([]driver.Value, 1)
604 err = rows.Next(dest)
605 if err != nil {
606 return 0, err
607 }
608 if dest[0] == nil {
609 return -1, errors.New("There is no generated identity value")
610 }
611 lastInsertId := dest[0].(int64)
612 return lastInsertId, nil
613 }