| 1 | package mssql |
| 2 | |
| 3 | import ( |
| 4 | "database/sql/driver" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | ) |
| 8 | |
| 9 | type copyin struct { |
| 10 | cn *MssqlConn |
| 11 | bulkcopy *MssqlBulk |
| 12 | closed bool |
| 13 | } |
| 14 | |
| 15 | type SerializableBulkConfig struct { |
| 16 | TableName string |
| 17 | ColumnsName []string |
| 18 | Options MssqlBulkOptions |
| 19 | } |
| 20 | |
| 21 | func (d *MssqlDriver) OpenConnection(dsn string) (*MssqlConn, error) { |
| 22 | return d.open(dsn) |
| 23 | } |
| 24 | |
| 25 | func (c *MssqlConn) prepareCopyIn(query string) (_ driver.Stmt, err error) { |
| 26 | config_json := query[11:] |
| 27 | |
| 28 | bulkconfig := SerializableBulkConfig{} |
| 29 | err = json.Unmarshal([]byte(config_json), &bulkconfig) |
| 30 | if err != nil { |
| 31 | return |
| 32 | } |
| 33 | |
| 34 | bulkcopy := c.CreateBulk(bulkconfig.TableName, bulkconfig.ColumnsName) |
| 35 | bulkcopy.Options = bulkconfig.Options |
| 36 | |
| 37 | ci := ©in{ |
| 38 | cn: c, |
| 39 | bulkcopy: bulkcopy, |
| 40 | } |
| 41 | |
| 42 | return ci, nil |
| 43 | } |
| 44 | |
| 45 | func CopyIn(table string, options MssqlBulkOptions, columns ...string) string { |
| 46 | bulkconfig := &SerializableBulkConfig{TableName: table, Options: options, ColumnsName: columns} |
| 47 | |
| 48 | config_json, err := json.Marshal(bulkconfig) |
| 49 | if err != nil { |
| 50 | panic(err) |
| 51 | } |
| 52 | |
| 53 | stmt := "INSERTBULK " + string(config_json) |
| 54 | |
| 55 | return stmt |
| 56 | } |
| 57 | |
| 58 | func (ci *copyin) NumInput() int { |
| 59 | return -1 |
| 60 | } |
| 61 | |
| 62 | func (ci *copyin) Query(v []driver.Value) (r driver.Rows, err error) { |
| 63 | return nil, errors.New("ErrNotSupported") |
| 64 | } |
| 65 | |
| 66 | func (ci *copyin) Exec(v []driver.Value) (r driver.Result, err error) { |
| 67 | if ci.closed { |
| 68 | return nil, errors.New("errCopyInClosed") |
| 69 | } |
| 70 | |
| 71 | if len(v) == 0 { |
| 72 | rowCount, err := ci.bulkcopy.Done() |
| 73 | ci.closed = true |
| 74 | return driver.RowsAffected(rowCount), err |
| 75 | } |
| 76 | |
| 77 | t := make([]interface{}, len(v)) |
| 78 | for i, val := range v { |
| 79 | t[i] = val |
| 80 | } |
| 81 | |
| 82 | err = ci.bulkcopy.AddRow(t) |
| 83 | if err != nil { |
| 84 | return |
| 85 | } |
| 86 | |
| 87 | return driver.RowsAffected(0), nil |
| 88 | } |
| 89 | |
| 90 | func (ci *copyin) Close() (err error) { |
| 91 | return nil |
| 92 | } |