| 1 |
package mssql |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
_ "database/sql/driver" |
| 6 |
"encoding/binary" |
| 7 |
"fmt" |
| 8 |
"golang.org/x/net/context" |
| 9 |
"math" |
| 10 |
"reflect" |
| 11 |
"strings" |
| 12 |
"time" |
| 13 |
) |
| 14 |
|
| 15 |
type MssqlBulk struct { |
| 16 |
cn *MssqlConn |
| 17 |
metadata []columnStruct |
| 18 |
bulkColumns []columnStruct |
| 19 |
columnsName []string |
| 20 |
tablename string |
| 21 |
numRows int |
| 22 |
|
| 23 |
headerSent bool |
| 24 |
Options MssqlBulkOptions |
| 25 |
Debug bool |
| 26 |
} |
| 27 |
type MssqlBulkOptions struct { |
| 28 |
CheckConstraints bool |
| 29 |
FireTriggers bool |
| 30 |
KeepNulls bool |
| 31 |
KilobytesPerBatch int |
| 32 |
RowsPerBatch int |
| 33 |
Order []string |
| 34 |
Tablock bool |
| 35 |
} |
| 36 |
|
| 37 |
type DataValue interface{} |
| 38 |
|
| 39 |
func (cn *MssqlConn) CreateBulk(table string, columns []string) (_ *MssqlBulk) { |
| 40 |
b := MssqlBulk{cn: cn, tablename: table, headerSent: false, columnsName: columns} |
| 41 |
b.Debug = false |
| 42 |
return &b |
| 43 |
} |
| 44 |
|
| 45 |
func (b *MssqlBulk) sendBulkCommand() (err error) { |
| 46 |
|
| 47 |
err = b.getMetadata() |
| 48 |
if err != nil { |
| 49 |
return err |
| 50 |
} |
| 51 |
|
| 52 |
|
| 53 |
for _, colname := range b.columnsName { |
| 54 |
var bulkCol *columnStruct |
| 55 |
|
| 56 |
for _, m := range b.metadata { |
| 57 |
if m.ColName == colname { |
| 58 |
bulkCol = &m |
| 59 |
break |
| 60 |
} |
| 61 |
} |
| 62 |
if bulkCol != nil { |
| 63 |
|
| 64 |
if bulkCol.ti.TypeId == typeUdt { |
| 65 |
|
| 66 |
bulkCol.ti.TypeId = typeBigVarBin |
| 67 |
} |
| 68 |
b.bulkColumns = append(b.bulkColumns, *bulkCol) |
| 69 |
b.dlogf("Adding column %s %s %#x", colname, bulkCol.ColName, bulkCol.ti.TypeId) |
| 70 |
} else { |
| 71 |
return fmt.Errorf("Column %s does not exist in destination table %s", colname, b.tablename) |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
var col_defs bytes.Buffer |
| 79 |
for i, col := range b.bulkColumns { |
| 80 |
if i != 0 { |
| 81 |
col_defs.WriteString(", ") |
| 82 |
} |
| 83 |
col_defs.WriteString("[" + col.ColName + "] " + makeDecl(col.ti)) |
| 84 |
} |
| 85 |
|
| 86 |
|
| 87 |
var with_opts []string |
| 88 |
|
| 89 |
if b.Options.CheckConstraints { |
| 90 |
with_opts = append(with_opts, "CHECK_CONSTRAINTS") |
| 91 |
} |
| 92 |
if b.Options.FireTriggers { |
| 93 |
with_opts = append(with_opts, "FIRE_TRIGGERS") |
| 94 |
} |
| 95 |
if b.Options.KeepNulls { |
| 96 |
with_opts = append(with_opts, "KEEP_NULLS") |
| 97 |
} |
| 98 |
if b.Options.KilobytesPerBatch > 0 { |
| 99 |
with_opts = append(with_opts, fmt.Sprintf("KILOBYTES_PER_BATCH = %d", b.Options.KilobytesPerBatch)) |
| 100 |
} |
| 101 |
if b.Options.RowsPerBatch > 0 { |
| 102 |
with_opts = append(with_opts, fmt.Sprintf("ROWS_PER_BATCH = %d", b.Options.RowsPerBatch)) |
| 103 |
} |
| 104 |
if len(b.Options.Order) > 0 { |
| 105 |
with_opts = append(with_opts, fmt.Sprintf("ORDER(%s)", strings.Join(b.Options.Order, ","))) |
| 106 |
} |
| 107 |
if b.Options.Tablock { |
| 108 |
with_opts = append(with_opts, "TABLOCK") |
| 109 |
} |
| 110 |
var with_part string |
| 111 |
if len(with_opts) > 0 { |
| 112 |
with_part = fmt.Sprintf("WITH (%s)", strings.Join(with_opts, ",")) |
| 113 |
} |
| 114 |
|
| 115 |
query := fmt.Sprintf("INSERT BULK %s (%s) %s", b.tablename, col_defs.String(), with_part) |
| 116 |
|
| 117 |
stmt, err := b.cn.Prepare(query) |
| 118 |
if err != nil { |
| 119 |
return fmt.Errorf("Prepare failed: %s", err.Error()) |
| 120 |
} |
| 121 |
b.dlogf(query) |
| 122 |
|
| 123 |
_, err = stmt.Exec(nil) |
| 124 |
if err != nil { |
| 125 |
return err |
| 126 |
} |
| 127 |
|
| 128 |
b.headerSent = true |
| 129 |
|
| 130 |
var buf = b.cn.sess.buf |
| 131 |
buf.BeginPacket(packBulkLoadBCP) |
| 132 |
|
| 133 |
|
| 134 |
columnMetadata := b.createColMetadata() |
| 135 |
_, err = buf.Write(columnMetadata) |
| 136 |
|
| 137 |
return |
| 138 |
} |
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
func (b *MssqlBulk) AddRow(row []interface{}) (err error) { |
| 143 |
if b.headerSent == false { |
| 144 |
err = b.sendBulkCommand() |
| 145 |
if err != nil { |
| 146 |
return |
| 147 |
} |
| 148 |
} |
| 149 |
|
| 150 |
if len(row) != len(b.bulkColumns) { |
| 151 |
return fmt.Errorf("Row does not have the same number of columns than the destination table %d %d", |
| 152 |
len(row), len(b.bulkColumns)) |
| 153 |
} |
| 154 |
|
| 155 |
bytes, err := b.makeRowData(row) |
| 156 |
if err != nil { |
| 157 |
return |
| 158 |
} |
| 159 |
|
| 160 |
_, err = b.cn.sess.buf.Write(bytes) |
| 161 |
if err != nil { |
| 162 |
return |
| 163 |
} |
| 164 |
|
| 165 |
b.numRows = b.numRows + 1 |
| 166 |
return |
| 167 |
} |
| 168 |
|
| 169 |
func (b *MssqlBulk) makeRowData(row []interface{}) ([]byte, error) { |
| 170 |
buf := new(bytes.Buffer) |
| 171 |
buf.WriteByte(byte(tokenRow)) |
| 172 |
|
| 173 |
var logcol bytes.Buffer |
| 174 |
for i, col := range b.bulkColumns { |
| 175 |
|
| 176 |
if b.Debug { |
| 177 |
logcol.WriteString(fmt.Sprintf(" col[%d]='%v' ", i, row[i])) |
| 178 |
} |
| 179 |
param, err := b.makeParam(row[i], col) |
| 180 |
if err != nil { |
| 181 |
return nil, fmt.Errorf("bulkcopy: %s", err.Error()) |
| 182 |
} |
| 183 |
|
| 184 |
if col.ti.Writer == nil { |
| 185 |
return nil, fmt.Errorf("no writer for column: %s, TypeId: %#x", |
| 186 |
col.ColName, col.ti.TypeId) |
| 187 |
} |
| 188 |
err = col.ti.Writer(buf, param.ti, param.buffer) |
| 189 |
if err != nil { |
| 190 |
return nil, fmt.Errorf("bulkcopy: %s", err.Error()) |
| 191 |
} |
| 192 |
} |
| 193 |
|
| 194 |
b.dlogf("row[%d] %s\n", b.numRows, logcol.String()) |
| 195 |
|
| 196 |
return buf.Bytes(), nil |
| 197 |
} |
| 198 |
|
| 199 |
func (b *MssqlBulk) Done() (rowcount int64, err error) { |
| 200 |
if b.headerSent == false { |
| 201 |
|
| 202 |
return 0, nil |
| 203 |
} |
| 204 |
var buf = b.cn.sess.buf |
| 205 |
buf.WriteByte(byte(tokenDone)) |
| 206 |
|
| 207 |
binary.Write(buf, binary.LittleEndian, uint16(doneFinal)) |
| 208 |
binary.Write(buf, binary.LittleEndian, uint16(0)) |
| 209 |
|
| 210 |
if b.cn.sess.loginAck.TDSVersion >= verTDS72 { |
| 211 |
binary.Write(buf, binary.LittleEndian, uint64(0)) |
| 212 |
} else { |
| 213 |
binary.Write(buf, binary.LittleEndian, uint32(0)) |
| 214 |
} |
| 215 |
|
| 216 |
buf.FinishPacket() |
| 217 |
|
| 218 |
tokchan := make(chan tokenStruct, 5) |
| 219 |
go processResponse(context.Background(), b.cn.sess, tokchan) |
| 220 |
|
| 221 |
var rowCount int64 |
| 222 |
for token := range tokchan { |
| 223 |
switch token := token.(type) { |
| 224 |
case doneStruct: |
| 225 |
if token.Status&doneCount != 0 { |
| 226 |
rowCount = int64(token.RowCount) |
| 227 |
} |
| 228 |
if token.isError() { |
| 229 |
return 0, token.getError() |
| 230 |
} |
| 231 |
case error: |
| 232 |
return 0, token |
| 233 |
} |
| 234 |
} |
| 235 |
return rowCount, nil |
| 236 |
} |
| 237 |
|
| 238 |
func (b *MssqlBulk) createColMetadata() []byte { |
| 239 |
buf := new(bytes.Buffer) |
| 240 |
buf.WriteByte(byte(tokenColMetadata)) |
| 241 |
binary.Write(buf, binary.LittleEndian, uint16(len(b.bulkColumns))) |
| 242 |
|
| 243 |
for i, col := range b.bulkColumns { |
| 244 |
|
| 245 |
if b.cn.sess.loginAck.TDSVersion >= verTDS72 { |
| 246 |
binary.Write(buf, binary.LittleEndian, uint32(col.UserType)) |
| 247 |
} else { |
| 248 |
binary.Write(buf, binary.LittleEndian, uint16(col.UserType)) |
| 249 |
} |
| 250 |
binary.Write(buf, binary.LittleEndian, uint16(col.Flags)) |
| 251 |
|
| 252 |
writeTypeInfo(buf, &b.bulkColumns[i].ti) |
| 253 |
|
| 254 |
if col.ti.TypeId == typeNText || |
| 255 |
col.ti.TypeId == typeText || |
| 256 |
col.ti.TypeId == typeImage { |
| 257 |
|
| 258 |
tablename_ucs2 := str2ucs2(b.tablename) |
| 259 |
binary.Write(buf, binary.LittleEndian, uint16(len(tablename_ucs2)/2)) |
| 260 |
buf.Write(tablename_ucs2) |
| 261 |
} |
| 262 |
colname_ucs2 := str2ucs2(col.ColName) |
| 263 |
buf.WriteByte(uint8(len(colname_ucs2) / 2)) |
| 264 |
buf.Write(colname_ucs2) |
| 265 |
} |
| 266 |
|
| 267 |
return buf.Bytes() |
| 268 |
} |
| 269 |
|
| 270 |
func (b *MssqlBulk) getMetadata() (err error) { |
| 271 |
stmt, err := b.cn.Prepare("SET FMTONLY ON") |
| 272 |
if err != nil { |
| 273 |
return |
| 274 |
} |
| 275 |
|
| 276 |
_, err = stmt.Exec(nil) |
| 277 |
if err != nil { |
| 278 |
return |
| 279 |
} |
| 280 |
|
| 281 |
|
| 282 |
stmt, err = b.cn.Prepare(fmt.Sprintf("select * from %s SET FMTONLY OFF", b.tablename)) |
| 283 |
if err != nil { |
| 284 |
return |
| 285 |
} |
| 286 |
stmt2 := stmt.(*MssqlStmt) |
| 287 |
cols, err := stmt2.QueryMeta() |
| 288 |
if err != nil { |
| 289 |
return fmt.Errorf("get columns info failed: %v", err.Error()) |
| 290 |
} |
| 291 |
b.metadata = cols |
| 292 |
|
| 293 |
if b.Debug { |
| 294 |
for _, col := range b.metadata { |
| 295 |
b.dlogf("col: %s typeId: %#x size: %d scale: %d prec: %d flags: %d lcid: %#x\n", |
| 296 |
col.ColName, col.ti.TypeId, col.ti.Size, col.ti.Scale, col.ti.Prec, |
| 297 |
col.Flags, col.ti.Collation.lcidAndFlags) |
| 298 |
} |
| 299 |
} |
| 300 |
|
| 301 |
return nil |
| 302 |
} |
| 303 |
|
| 304 |
|
| 305 |
func (s *MssqlStmt) QueryMeta() (cols []columnStruct, err error) { |
| 306 |
if err = s.sendQuery(nil); err != nil { |
| 307 |
return |
| 308 |
} |
| 309 |
tokchan := make(chan tokenStruct, 5) |
| 310 |
go processResponse(context.Background(), s.c.sess, tokchan) |
| 311 |
loop: |
| 312 |
for tok := range tokchan { |
| 313 |
switch token := tok.(type) { |
| 314 |
case doneStruct: |
| 315 |
break loop |
| 316 |
case []columnStruct: |
| 317 |
cols = token |
| 318 |
break loop |
| 319 |
case error: |
| 320 |
return nil, token |
| 321 |
} |
| 322 |
} |
| 323 |
return cols, nil |
| 324 |
} |
| 325 |
|
| 326 |
func (b *MssqlBulk) makeParam(val DataValue, col columnStruct) (res Param, err error) { |
| 327 |
res.ti.Size = col.ti.Size |
| 328 |
res.ti.TypeId = col.ti.TypeId |
| 329 |
|
| 330 |
if val == nil { |
| 331 |
res.ti.Size = 0 |
| 332 |
return |
| 333 |
} |
| 334 |
|
| 335 |
switch col.ti.TypeId { |
| 336 |
|
| 337 |
case typeInt1, typeInt2, typeInt4, typeInt8, typeIntN: |
| 338 |
var intvalue int64 |
| 339 |
|
| 340 |
switch val := val.(type) { |
| 341 |
case int: |
| 342 |
intvalue = int64(val) |
| 343 |
case int32: |
| 344 |
intvalue = int64(val) |
| 345 |
case int64: |
| 346 |
intvalue = val |
| 347 |
default: |
| 348 |
err = fmt.Errorf("mssql: invalid type for int column") |
| 349 |
return |
| 350 |
} |
| 351 |
|
| 352 |
res.buffer = make([]byte, res.ti.Size) |
| 353 |
if col.ti.Size == 1 { |
| 354 |
res.buffer[0] = byte(intvalue) |
| 355 |
} else if col.ti.Size == 2 { |
| 356 |
binary.LittleEndian.PutUint16(res.buffer, uint16(intvalue)) |
| 357 |
} else if col.ti.Size == 4 { |
| 358 |
binary.LittleEndian.PutUint32(res.buffer, uint32(intvalue)) |
| 359 |
} else if col.ti.Size == 8 { |
| 360 |
binary.LittleEndian.PutUint64(res.buffer, uint64(intvalue)) |
| 361 |
} |
| 362 |
case typeFlt4, typeFlt8, typeFltN: |
| 363 |
var floatvalue float64 |
| 364 |
|
| 365 |
switch val := val.(type) { |
| 366 |
case float32: |
| 367 |
floatvalue = float64(val) |
| 368 |
case float64: |
| 369 |
floatvalue = val |
| 370 |
case int: |
| 371 |
floatvalue = float64(val) |
| 372 |
case int64: |
| 373 |
floatvalue = float64(val) |
| 374 |
default: |
| 375 |
err = fmt.Errorf("mssql: invalid type for float column", val) |
| 376 |
return |
| 377 |
} |
| 378 |
|
| 379 |
if col.ti.Size == 4 { |
| 380 |
res.buffer = make([]byte, 4) |
| 381 |
binary.LittleEndian.PutUint32(res.buffer, math.Float32bits(float32(floatvalue))) |
| 382 |
} else if col.ti.Size == 8 { |
| 383 |
res.buffer = make([]byte, 8) |
| 384 |
binary.LittleEndian.PutUint64(res.buffer, math.Float64bits(floatvalue)) |
| 385 |
} |
| 386 |
case typeNVarChar, typeNText, typeNChar: |
| 387 |
|
| 388 |
switch val := val.(type) { |
| 389 |
case string: |
| 390 |
res.buffer = str2ucs2(val) |
| 391 |
case []byte: |
| 392 |
res.buffer = val |
| 393 |
default: |
| 394 |
err = fmt.Errorf("mssql: invalid type for nvarchar column", val) |
| 395 |
return |
| 396 |
} |
| 397 |
res.ti.Size = len(res.buffer) |
| 398 |
|
| 399 |
case typeVarChar, typeBigVarChar, typeText, typeChar, typeBigChar: |
| 400 |
switch val := val.(type) { |
| 401 |
case string: |
| 402 |
res.buffer = []byte(val) |
| 403 |
case []byte: |
| 404 |
res.buffer = val |
| 405 |
default: |
| 406 |
err = fmt.Errorf("mssql: invalid type for varchar column", val) |
| 407 |
return |
| 408 |
} |
| 409 |
res.ti.Size = len(res.buffer) |
| 410 |
|
| 411 |
case typeBit, typeBitN: |
| 412 |
if reflect.TypeOf(val).Kind() != reflect.Bool { |
| 413 |
err = fmt.Errorf("mssql: invalid type for bit column", val) |
| 414 |
return |
| 415 |
} |
| 416 |
res.ti.TypeId = typeBitN |
| 417 |
res.ti.Size = 1 |
| 418 |
res.buffer = make([]byte, 1) |
| 419 |
if val.(bool) { |
| 420 |
res.buffer[0] = 1 |
| 421 |
} |
| 422 |
|
| 423 |
case typeDateTime2N, typeDateTimeOffsetN: |
| 424 |
switch val := val.(type) { |
| 425 |
case time.Time: |
| 426 |
days, ns := dateTime2(val) |
| 427 |
ns /= int64(math.Pow10(int(col.ti.Scale)*-1) * 1000000000) |
| 428 |
|
| 429 |
var data = make([]byte, 5) |
| 430 |
|
| 431 |
data[0] = byte(ns) |
| 432 |
data[1] = byte(ns >> 8) |
| 433 |
data[2] = byte(ns >> 16) |
| 434 |
data[3] = byte(ns >> 24) |
| 435 |
data[4] = byte(ns >> 32) |
| 436 |
|
| 437 |
if col.ti.Scale <= 2 { |
| 438 |
res.ti.Size = 6 |
| 439 |
} else if col.ti.Scale <= 4 { |
| 440 |
res.ti.Size = 7 |
| 441 |
} else { |
| 442 |
res.ti.Size = 8 |
| 443 |
} |
| 444 |
var buf []byte |
| 445 |
buf = make([]byte, res.ti.Size) |
| 446 |
copy(buf, data[0:res.ti.Size-3]) |
| 447 |
|
| 448 |
buf[res.ti.Size-3] = byte(days) |
| 449 |
buf[res.ti.Size-2] = byte(days >> 8) |
| 450 |
buf[res.ti.Size-1] = byte(days >> 16) |
| 451 |
|
| 452 |
if col.ti.TypeId == typeDateTimeOffsetN { |
| 453 |
_, offset := val.Zone() |
| 454 |
var offsetMinute = uint16(offset / 60) |
| 455 |
buf = append(buf, byte(offsetMinute)) |
| 456 |
buf = append(buf, byte(offsetMinute>>8)) |
| 457 |
res.ti.Size = res.ti.Size + 2 |
| 458 |
} |
| 459 |
|
| 460 |
res.buffer = buf |
| 461 |
|
| 462 |
default: |
| 463 |
err = fmt.Errorf("mssql: invalid type for datetime2 column", val) |
| 464 |
return |
| 465 |
} |
| 466 |
case typeDateN: |
| 467 |
switch val := val.(type) { |
| 468 |
case time.Time: |
| 469 |
days, _ := dateTime2(val) |
| 470 |
|
| 471 |
res.ti.Size = 3 |
| 472 |
res.buffer = make([]byte, 3) |
| 473 |
res.buffer[0] = byte(days) |
| 474 |
res.buffer[1] = byte(days >> 8) |
| 475 |
res.buffer[2] = byte(days >> 16) |
| 476 |
default: |
| 477 |
err = fmt.Errorf("mssql: invalid type for date column", val) |
| 478 |
return |
| 479 |
} |
| 480 |
case typeDateTime, typeDateTimeN, typeDateTim4: |
| 481 |
switch val := val.(type) { |
| 482 |
case time.Time: |
| 483 |
if col.ti.Size == 4 { |
| 484 |
res.ti.Size = 4 |
| 485 |
res.buffer = make([]byte, 4) |
| 486 |
|
| 487 |
ref := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC) |
| 488 |
dur := val.Sub(ref) |
| 489 |
days := dur / (24 * time.Hour) |
| 490 |
if days < 0 { |
| 491 |
err = fmt.Errorf("mssql: Date %s is out of range", val) |
| 492 |
return |
| 493 |
} |
| 494 |
mins := val.Hour()*60 + val.Minute() |
| 495 |
|
| 496 |
binary.LittleEndian.PutUint16(res.buffer[0:2], uint16(days)) |
| 497 |
binary.LittleEndian.PutUint16(res.buffer[2:4], uint16(mins)) |
| 498 |
} else if col.ti.Size == 8 { |
| 499 |
res.ti.Size = 8 |
| 500 |
res.buffer = make([]byte, 8) |
| 501 |
|
| 502 |
ref := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC) |
| 503 |
dur := val.Sub(ref) |
| 504 |
days := math.Floor(float64(dur) / float64(24*time.Hour)) |
| 505 |
tm := (val.Hour()*60*60+val.Minute()*60+val.Second())*300 + int(val.Nanosecond()/10000000*3) |
| 506 |
|
| 507 |
binary.LittleEndian.PutUint32(res.buffer[0:4], uint32(days)) |
| 508 |
binary.LittleEndian.PutUint32(res.buffer[4:8], uint32(tm)) |
| 509 |
} else { |
| 510 |
err = fmt.Errorf("mssql: invalid size of column") |
| 511 |
} |
| 512 |
|
| 513 |
default: |
| 514 |
err = fmt.Errorf("mssql: invalid type for datetime column", val) |
| 515 |
} |
| 516 |
|
| 517 |
|
| 518 |
|
| 519 |
|
| 520 |
|
| 521 |
|
| 522 |
|
| 523 |
|
| 524 |
|
| 525 |
|
| 526 |
|
| 527 |
|
| 528 |
|
| 529 |
|
| 530 |
|
| 531 |
|
| 532 |
|
| 533 |
|
| 534 |
|
| 535 |
|
| 536 |
|
| 537 |
|
| 538 |
|
| 539 |
|
| 540 |
|
| 541 |
|
| 542 |
|
| 543 |
|
| 544 |
|
| 545 |
|
| 546 |
case typeBigVarBin: |
| 547 |
switch val := val.(type) { |
| 548 |
case []byte: |
| 549 |
res.ti.Size = len(val) |
| 550 |
res.buffer = val |
| 551 |
default: |
| 552 |
err = fmt.Errorf("mssql: invalid type for Binary column", val) |
| 553 |
return |
| 554 |
} |
| 555 |
|
| 556 |
default: |
| 557 |
err = fmt.Errorf("mssql: type %x not implemented!", col.ti.TypeId) |
| 558 |
} |
| 559 |
return |
| 560 |
|
| 561 |
} |
| 562 |
|
| 563 |
func (b *MssqlBulk) dlogf(format string, v ...interface{}) { |
| 564 |
if b.Debug { |
| 565 |
b.cn.sess.log.Printf(format, v...) |
| 566 |
} |
| 567 |
} |