@@ -23,8 +23,6 @@ package mssql
23
23
24
24
import (
25
25
"database/sql"
26
- "log"
27
- "strings"
28
26
29
27
"upper.io/db.v3"
30
28
"upper.io/db.v3/internal/sqladapter"
@@ -37,6 +35,8 @@ type table struct {
37
35
38
36
d * database
39
37
name string
38
+
39
+ hasIdentityColumn * bool
40
40
}
41
41
42
42
var (
@@ -76,7 +76,6 @@ func (t *table) Insert(item interface{}) (interface{}, error) {
76
76
for j := 0 ; j < len (pKey ); j ++ {
77
77
if pKey [j ] == columnNames [i ] {
78
78
if columnValues [i ] != nil {
79
- log .Printf ("%v -- %v" , pKey [j ], columnValues [i ])
80
79
hasKeys = true
81
80
break
82
81
}
@@ -85,13 +84,34 @@ func (t *table) Insert(item interface{}) (interface{}, error) {
85
84
}
86
85
87
86
if hasKeys {
88
- _ , err = t .d .Exec ("SET IDENTITY_INSERT " + t .Name () + " ON" )
89
- // TODO: Find a way to check if the table has composite keys without an
90
- // identity property.
91
- if err != nil && ! strings .Contains (err .Error (), "does not have the identity property" ) {
92
- return nil , err
87
+ if t .hasIdentityColumn == nil {
88
+ var hasIdentityColumn bool
89
+ var identityColumns int
90
+
91
+ row , err := t .d .QueryRow ("SELECT COUNT(1) FROM sys.identity_columns WHERE OBJECT_NAME(object_id) = ?" , t .Name ())
92
+ if err != nil {
93
+ return nil , err
94
+ }
95
+
96
+ err = row .Scan (& identityColumns )
97
+ if err != nil {
98
+ return nil , err
99
+ }
100
+
101
+ if identityColumns > 0 {
102
+ hasIdentityColumn = true
103
+ }
104
+
105
+ t .hasIdentityColumn = & hasIdentityColumn
106
+ }
107
+
108
+ if * t .hasIdentityColumn {
109
+ _ , err = t .d .Exec ("SET IDENTITY_INSERT " + t .Name () + " ON" )
110
+ if err != nil {
111
+ return nil , err
112
+ }
113
+ defer t .d .Exec ("SET IDENTITY_INSERT " + t .Name () + " OFF" )
93
114
}
94
- defer t .d .Exec ("SET IDENTITY_INSERT " + t .Name () + " OFF" )
95
115
}
96
116
97
117
q := t .d .InsertInto (t .Name ()).
0 commit comments