-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
oracle_test.go
341 lines (312 loc) · 9.09 KB
/
oracle_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
package oracle
import (
"database/sql"
"encoding/json"
"log"
"os"
"reflect"
"strconv"
"strings"
"testing"
"time"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
)
var (
dbNamingCase *gorm.DB
dbIgnoreCase *gorm.DB
dbErrors = make([]error, 2)
)
func init() {
if wait := os.Getenv("GORM_ORA_WAIT_MIN"); wait != "" {
if min, e := strconv.Atoi(wait); e == nil {
log.Println("wait for oracle database initialization to complete...")
time.Sleep(time.Duration(min) * time.Minute)
}
}
var err error
if dbNamingCase, err = openTestConnection(true, true); err != nil {
dbErrors[0] = err
}
if dbIgnoreCase, err = openTestConnection(true, false); err != nil {
dbErrors[1] = err
}
}
func openTestConnection(ignoreCase, namingCase bool) (db *gorm.DB, err error) {
dsn := getTestDSN()
db, err = gorm.Open(New(Config{
DSN: dsn,
IgnoreCase: ignoreCase,
NamingCaseSensitive: namingCase,
}), getTestGormConfig())
if db != nil && err == nil {
log.Println("open oracle database connection success!")
}
return
}
func getTestDSN() (dsn string) {
dsn = os.Getenv("GORM_ORA_DSN")
if dsn == "" {
server := os.Getenv("GORM_ORA_SERVER")
port, _ := strconv.Atoi(os.Getenv("GORM_ORA_PORT"))
if server == "" || port < 1 {
return
}
language := os.Getenv("GORM_ORA_LANG")
if language == "" {
language = "SIMPLIFIED CHINESE"
}
territory := os.Getenv("GORM_ORA_TERRITORY")
if territory == "" {
territory = "CHINA"
}
dsn = BuildUrl(server, port,
os.Getenv("GORM_ORA_SID"),
os.Getenv("GORM_ORA_USER"),
os.Getenv("GORM_ORA_PASS"),
map[string]string{
"CONNECTION TIMEOUT": "90",
"LANGUAGE": language,
"TERRITORY": territory,
"SSL": "false",
})
}
return
}
func getTestGormConfig() *gorm.Config {
logWriter := new(log.Logger)
logWriter.SetOutput(os.Stdout)
return &gorm.Config{
Logger: logger.New(
logWriter,
logger.Config{LogLevel: logger.Info},
),
DisableForeignKeyConstraintWhenMigrating: false,
IgnoreRelationshipsWhenMigrating: false,
NamingStrategy: schema.NamingStrategy{
IdentifierMaxLength: 30,
},
}
}
func TestCountLimit0(t *testing.T) {
db, err := dbNamingCase, dbErrors[0]
if err != nil {
t.Fatal(err)
}
if db == nil {
t.Log("db is nil!")
return
}
model := TestTableUser{}
migrator := db.Set("gorm:table_comments", "用户信息表").Migrator()
if migrator.HasTable(model) {
if err = migrator.DropTable(model); err != nil {
t.Fatalf("DropTable() error = %v", err)
}
}
if err = migrator.AutoMigrate(model); err != nil {
t.Fatalf("AutoMigrate() error = %v", err)
}
t.Log("AutoMigrate() success!")
var count int64
result := db.Model(&model).Limit(-1).Count(&count)
if err = result.Error; err != nil {
t.Fatal(err)
}
t.Logf("Limit(-1) count = %d", count)
if countSql := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
return tx.Model(&model).Limit(-1).Count(&count)
}); strings.Contains(countSql, "ORDER BY") {
t.Error(`The "count(*)" statement contains the "ORDER BY" clause!`)
}
}
func TestLimit(t *testing.T) {
db, err := dbNamingCase, dbErrors[0]
if err != nil {
t.Fatal(err)
}
if db == nil {
t.Log("db is nil!")
return
}
TestMergeCreate(t)
type args struct {
offset, limit int
order string
}
tests := []struct {
name string
args args
}{
{name: "OffsetLimit0", args: args{offset: 0, limit: 0}},
{name: "Offset10", args: args{offset: 10, limit: 0}},
{name: "Limit10", args: args{offset: 0, limit: 10}},
{name: "Offset10Limit10", args: args{offset: 10, limit: 10}},
{name: "Offset10Limit10Order", args: args{offset: 10, limit: 10, order: `"id"`}},
{name: "Offset10Limit10OrderDESC", args: args{offset: 10, limit: 10, order: `"id" DESC`}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var data []TestTableUser
result := db.Model(&TestTableUser{}).
Offset(tt.args.offset).
Limit(tt.args.limit).
Order(tt.args.order).
Find(&data)
if err = result.Error; err != nil {
t.Fatal(err)
}
dataBytes, _ := json.MarshalIndent(data, "", " ")
t.Logf("Offset(%d) Limit(%d) got size = %d, data = %s",
tt.args.offset, tt.args.limit, len(data), dataBytes)
})
}
}
func TestAddSessionParams(t *testing.T) {
db, err := dbIgnoreCase, dbErrors[1]
if err != nil {
t.Fatal(err)
}
if db == nil {
t.Log("db is nil!")
return
}
var sqlDB *sql.DB
if sqlDB, err = db.DB(); err != nil {
t.Fatal(err)
}
type args struct {
params map[string]string
}
tests := []struct {
name string
args args
}{
{name: "TimeParams", args: args{params: map[string]string{
"TIME_ZONE": "+08:00", // alter session set TIME_ZONE = '+08:00';
"NLS_DATE_FORMAT": "YYYY-MM-DD", // alter session set NLS_DATE_FORMAT = 'YYYY-MM-DD';
"NLS_TIME_FORMAT": "HH24:MI:SSXFF", // alter session set NLS_TIME_FORMAT = 'HH24:MI:SS.FF3';
"NLS_TIMESTAMP_FORMAT": "YYYY-MM-DD HH24:MI:SSXFF", // alter session set NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF3';
"NLS_TIME_TZ_FORMAT": "HH24:MI:SS.FF TZR", // alter session set NLS_TIME_TZ_FORMAT = 'HH24:MI:SS.FF3 TZR';
"NLS_TIMESTAMP_TZ_FORMAT": "YYYY-MM-DD HH24:MI:SSXFF TZR", // alter session set NLS_TIMESTAMP_TZ_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF3 TZR';
}}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
//queryTime := `SELECT SYSDATE FROM DUAL`
queryTime := `SELECT CAST(SYSDATE AS VARCHAR(30)) AS D FROM DUAL`
var timeStr string
if err = db.Raw(queryTime).Row().Scan(&timeStr); err != nil {
t.Fatal(err)
}
t.Logf("SYSDATE 1: %s", timeStr)
var keys []string
if keys, err = AddSessionParams(sqlDB, tt.args.params); err != nil {
t.Fatalf("AddSessionParams() error = %v", err)
}
if err = db.Raw(queryTime).Row().Scan(&timeStr); err != nil {
t.Fatal(err)
}
defer DelSessionParams(sqlDB, keys)
t.Logf("SYSDATE 2: %s", timeStr)
t.Logf("keys: %#v", keys)
})
}
}
func TestGetStringExpr(t *testing.T) {
db, err := dbNamingCase, dbErrors[0]
if err != nil {
t.Fatal(err)
}
if db == nil {
t.Log("db is nil!")
return
}
type args struct {
prepareSQL string
value string
quote bool
}
tests := []struct {
name string
args args
wantSQL string
}{
{"1", args{`SELECT ? AS HELLO FROM DUAL`, "Hi!", true}, `SELECT 'Hi!' AS HELLO FROM DUAL`},
{"2", args{`SELECT '?' AS HELLO FROM DUAL`, "Hi!", false}, `SELECT 'Hi!' AS HELLO FROM DUAL`},
{"3", args{`SELECT ? AS HELLO FROM DUAL`, "What's your name?", true}, `SELECT q'[What's your name?]' AS HELLO FROM DUAL`},
{"4", args{`SELECT '?' AS HELLO FROM DUAL`, "What's your name?", false}, `SELECT 'What''s your name?' AS HELLO FROM DUAL`},
{"5", args{`SELECT ? AS HELLO FROM DUAL`, "What's up]'?", true}, `SELECT q'{What's up]'?}' AS HELLO FROM DUAL`},
{"6", args{`SELECT ? AS HELLO FROM DUAL`, "What's up]'}'?", true}, `SELECT q'<What's up]'}'?>' AS HELLO FROM DUAL`},
{"7", args{`SELECT ? AS HELLO FROM DUAL`, "What's up]'}'>'?", true}, `SELECT q'(What's up]'}'>'?)' AS HELLO FROM DUAL`},
{"8", args{`SELECT ? AS HELLO FROM DUAL`, "What's up)'}'>'?", true}, `SELECT q'[What's up)'}'>'?]' AS HELLO FROM DUAL`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotSQL := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
return tx.Raw(tt.args.prepareSQL, GetStringExpr(tt.args.value, tt.args.quote))
})
if !reflect.DeepEqual(gotSQL, tt.wantSQL) {
t.Fatalf("ToSQL = %v, want %v", gotSQL, tt.wantSQL)
}
var results []map[string]interface{}
if err = db.Raw(gotSQL).Find(&results).Error; err != nil {
t.Fatalf("finds all records from raw sql got error: %v", err)
}
t.Log("result:", results)
})
}
}
func TestVarcharSizeIsCharLength(t *testing.T) {
dsn := getTestDSN()
db, err := gorm.Open(New(Config{
DSN: dsn,
IgnoreCase: true,
NamingCaseSensitive: true,
VarcharSizeIsCharLength: true,
}), getTestGormConfig())
if db != nil && err == nil {
log.Println("open oracle database connection success!")
} else {
t.Fatal(err)
}
model := TestTableUserVarcharSize{}
migrator := db.Set("gorm:table_comments", "TestVarcharSizeIsCharLength").Migrator()
if migrator.HasTable(model) {
if err = migrator.DropTable(model); err != nil {
t.Fatalf("DropTable() error = %v", err)
}
}
if err = migrator.AutoMigrate(model); err != nil {
t.Fatalf("AutoMigrate() error = %v", err)
}
t.Log("AutoMigrate() success!")
type args struct {
value string
}
tests := []struct {
name string
args args
wantErr bool
}{
{"50", args{strings.Repeat("姓名", 25)}, false},
{"60", args{strings.Repeat("姓名", 30)}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotErr := db.Create(&TestTableUserVarcharSize{TestTableUser{Name: tt.args.value}}).Error
if (gotErr != nil) != tt.wantErr {
t.Error(gotErr)
} else if gotErr != nil {
t.Log(gotErr)
}
})
}
}
type TestTableUserVarcharSize struct {
TestTableUser
}
func (TestTableUserVarcharSize) TableName() string {
return "test_user_varchar_size"
}