~ubuntu-branches/ubuntu/quantal/mysql-connector-java/quantal

« back to all changes in this revision

Viewing changes to testsuite/simple/StatementsTest.java

  • Committer: Bazaar Package Importer
  • Author(s): Takashi Okamoto
  • Date: 2003-12-30 22:37:53 UTC
  • Revision ID: james.westby@ubuntu.com-20031230223753-5d9n2b0w2ms6puqa
Tags: upstream-3.0.9
ImportĀ upstreamĀ versionĀ 3.0.9

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
   Copyright (C) 2002 MySQL AB
 
3
   
 
4
      This program is free software; you can redistribute it and/or modify
 
5
      it under the terms of the GNU General Public License as published by
 
6
      the Free Software Foundation; either version 2 of the License, or
 
7
      (at your option) any later version.
 
8
   
 
9
      This program is distributed in the hope that it will be useful,
 
10
      but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
      GNU General Public License for more details.
 
13
   
 
14
      You should have received a copy of the GNU General Public License
 
15
      along with this program; if not, write to the Free Software
 
16
      Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
17
      
 
18
 */
 
19
package testsuite.simple;
 
20
 
 
21
import java.sql.SQLException;
 
22
import java.sql.Statement;
 
23
 
 
24
import testsuite.BaseTestCase;
 
25
 
 
26
import com.mysql.jdbc.NotImplemented;
 
27
 
 
28
/** 
 
29
 *
 
30
 * @author  Mark Matthews
 
31
 * @version $Id: StatementsTest.java,v 1.14.2.2 2003/10/07 18:28:23 mmatthew Exp $
 
32
 */
 
33
public class StatementsTest
 
34
    extends BaseTestCase {
 
35
 
 
36
    //~ Instance/static variables .............................................
 
37
 
 
38
    private static final int MAX_COLUMNS_TO_TEST = 40;
 
39
    private static final int STEP = 8;
 
40
    private static final int MAX_COLUMN_LENGTH = 255;
 
41
    private static final int MIN_COLUMN_LENGTH = 10;
 
42
 
 
43
    //~ Constructors ..........................................................
 
44
 
 
45
    /**
 
46
     * Creates a new StatementsTest object.
 
47
     * 
 
48
     * @param name DOCUMENT ME!
 
49
     */
 
50
    public StatementsTest(String name) {
 
51
        super(name);
 
52
    }
 
53
 
 
54
    //~ Methods ...............................................................
 
55
 
 
56
    /**
 
57
     * DOCUMENT ME!
 
58
     * 
 
59
     * @param args DOCUMENT ME!
 
60
     * @throws Exception DOCUMENT ME!
 
61
     */
 
62
    public static void main(String[] args)
 
63
                     throws Exception {
 
64
        new StatementsTest("testStubbed").run();
 
65
        new StatementsTest("testInsert").run();
 
66
        new StatementsTest("testAutoIncrement").run();
 
67
        new StatementsTest("testPreparedStatement").run();
 
68
        new StatementsTest("testPreparedStatementBatch").run();
 
69
        new StatementsTest("testClose").run();
 
70
        new StatementsTest("testSelectColumns").run();
 
71
    }
 
72
 
 
73
    /**
 
74
     * DOCUMENT ME!
 
75
     * 
 
76
     * @throws Exception DOCUMENT ME!
 
77
     */
 
78
    public void setUp()
 
79
               throws Exception {
 
80
        super.setUp();
 
81
 
 
82
        try {
 
83
            stmt.executeUpdate("DROP TABLE statement_test");
 
84
        } /* ignore */ catch (SQLException sqlEx) {
 
85
            ;
 
86
        }
 
87
        
 
88
        try {
 
89
            stmt.executeUpdate("DROP TABLE statement_batch_test");
 
90
        } /* ignore */ catch (SQLException sqlEx) {
 
91
            ;
 
92
        }
 
93
 
 
94
        stmt.executeUpdate(
 
95
                "CREATE TABLE statement_test (id int not null primary key auto_increment, strdata1 varchar(255) not null, strdata2 varchar(255))");
 
96
                
 
97
        stmt.executeUpdate(
 
98
                "CREATE TABLE statement_batch_test " 
 
99
                + "(id int not null primary key auto_increment, " 
 
100
                + "strdata1 varchar(255) not null, strdata2 varchar(255), "
 
101
                + "UNIQUE INDEX (strdata1))");
 
102
 
 
103
 
 
104
        for (int i = 6; i < MAX_COLUMNS_TO_TEST; i += STEP) {
 
105
 
 
106
            StringBuffer insertBuf = new StringBuffer(
 
107
                                             "INSERT INTO statement_col_test_");
 
108
            StringBuffer stmtBuf = new StringBuffer(
 
109
                                           "CREATE TABLE IF NOT EXISTS statement_col_test_");
 
110
            stmtBuf.append(i);
 
111
            insertBuf.append(i);
 
112
            stmtBuf.append(" (");
 
113
            insertBuf.append(" VALUES (");
 
114
 
 
115
            boolean firstTime = true;
 
116
 
 
117
            for (int j = 0; j < i; j++) {
 
118
 
 
119
                if (!firstTime) {
 
120
                    stmtBuf.append(",");
 
121
                    insertBuf.append(",");
 
122
                } else {
 
123
                    firstTime = false;
 
124
                }
 
125
 
 
126
                stmtBuf.append("col_");
 
127
                stmtBuf.append(j);
 
128
                stmtBuf.append(" VARCHAR(");
 
129
                stmtBuf.append(MAX_COLUMN_LENGTH);
 
130
                stmtBuf.append(")");
 
131
                insertBuf.append("'");
 
132
 
 
133
                int numChars = (int) (Math.random() * (MAX_COLUMN_LENGTH - MIN_COLUMN_LENGTH))
 
134
                               + MIN_COLUMN_LENGTH;
 
135
 
 
136
                for (int k = 0; k < numChars; k++) {
 
137
                    insertBuf.append("A");
 
138
                }
 
139
 
 
140
                insertBuf.append("'");
 
141
            }
 
142
 
 
143
            stmtBuf.append(")");
 
144
            insertBuf.append(")");
 
145
            stmt.executeUpdate(stmtBuf.toString());
 
146
            stmt.executeUpdate(insertBuf.toString());
 
147
        }
 
148
 
 
149
        // explicitly set the catalog to exercise code in execute(), executeQuery() and
 
150
        // executeUpdate()
 
151
        // FIXME: Only works on Windows!
 
152
        //conn.setCatalog(conn.getCatalog().toUpperCase());
 
153
    }
 
154
 
 
155
    /**
 
156
     * DOCUMENT ME!
 
157
     * 
 
158
     * @throws Exception DOCUMENT ME!
 
159
     */
 
160
    public void tearDown()
 
161
                  throws Exception {
 
162
        stmt.executeUpdate("DROP TABLE statement_test");
 
163
 
 
164
        for (int i = 0; i < MAX_COLUMNS_TO_TEST; i += STEP) {
 
165
 
 
166
            StringBuffer stmtBuf = new StringBuffer(
 
167
                                           "DROP TABLE IF EXISTS statement_col_test_");
 
168
            stmtBuf.append(i);
 
169
            stmt.executeUpdate(stmtBuf.toString());
 
170
        }
 
171
 
 
172
        try {
 
173
            stmt.executeUpdate("DROP TABLE statement_batch_test");
 
174
        } /* ignore */ catch (SQLException sqlEx) {
 
175
            ;
 
176
        }
 
177
        
 
178
        super.tearDown();
 
179
    }
 
180
 
 
181
    /**
 
182
     * DOCUMENT ME!
 
183
     * 
 
184
     * @throws SQLException DOCUMENT ME!
 
185
     */
 
186
    public void testAccessorsAndMutators()
 
187
                                  throws SQLException {
 
188
        assertTrue("Connection can not be null, and must be same connection", 
 
189
                   stmt.getConnection() == conn);
 
190
 
 
191
        // Set max rows, to exercise code in execute(), executeQuery() and executeUpdate()
 
192
        Statement accessorStmt = null;
 
193
 
 
194
        try {
 
195
            accessorStmt = conn.createStatement();
 
196
            accessorStmt.setMaxRows(1);
 
197
            accessorStmt.setMaxRows(0); // FIXME, test that this actually affects rows returned
 
198
            accessorStmt.setMaxFieldSize(255);
 
199
            assertTrue("Max field size should match what was set", 
 
200
                       accessorStmt.getMaxFieldSize() == 255);
 
201
 
 
202
            try {
 
203
                accessorStmt.setMaxFieldSize(Integer.MAX_VALUE);
 
204
                fail("Should not be able to set max field size > max_packet_size");
 
205
            } /* ignore */ catch (SQLException sqlEx) {
 
206
                ;
 
207
            }
 
208
 
 
209
            accessorStmt.setCursorName("undef");
 
210
            accessorStmt.setEscapeProcessing(true);
 
211
            accessorStmt.setFetchDirection(java.sql.ResultSet.FETCH_FORWARD);
 
212
 
 
213
            int fetchDirection = accessorStmt.getFetchDirection();
 
214
            assertTrue("Set fetch direction != get fetch direction", 
 
215
                       fetchDirection == java.sql.ResultSet.FETCH_FORWARD);
 
216
 
 
217
            try {
 
218
                accessorStmt.setFetchDirection(Integer.MAX_VALUE);
 
219
                fail("Should not be able to set fetch direction to invalid value");
 
220
            } /* ignore */ catch (SQLException sqlEx) {
 
221
                ;
 
222
            }
 
223
 
 
224
            try {
 
225
                accessorStmt.setMaxRows(50000000 + 10);
 
226
                fail("Should not be able to set max rows > 50000000");
 
227
            } /* ignore */ catch (SQLException sqlEx) {
 
228
                ;
 
229
            }
 
230
 
 
231
            try {
 
232
                accessorStmt.setMaxRows(Integer.MIN_VALUE);
 
233
                fail("Should not be able to set max rows < 0");
 
234
            } /* ignore */ catch (SQLException sqlEx) {
 
235
                ;
 
236
            }
 
237
 
 
238
            int fetchSize = stmt.getFetchSize();
 
239
 
 
240
            try {
 
241
                accessorStmt.setMaxRows(4);
 
242
                accessorStmt.setFetchSize(Integer.MAX_VALUE);
 
243
                fail("Should not be able to set FetchSize > max rows");
 
244
            } /* ignore */ catch (SQLException sqlEx) {
 
245
                ;
 
246
            }
 
247
 
 
248
            try {
 
249
                accessorStmt.setFetchSize(-2);
 
250
                fail("Should not be able to set FetchSize < 0");
 
251
            } /* ignore */ catch (SQLException sqlEx) {
 
252
                ;
 
253
            }
 
254
 
 
255
            assertTrue("Fetch size before invalid setFetchSize() calls should match fetch size now", 
 
256
                       fetchSize == stmt.getFetchSize());
 
257
        } finally {
 
258
 
 
259
            if (accessorStmt != null) {
 
260
 
 
261
                try {
 
262
                    accessorStmt.close();
 
263
                } /* ignore */ catch (SQLException sqlEx) {
 
264
                    ;
 
265
                }
 
266
 
 
267
                accessorStmt = null;
 
268
            }
 
269
        }
 
270
    }
 
271
 
 
272
    /**
 
273
     * DOCUMENT ME!
 
274
     * 
 
275
     * @throws SQLException DOCUMENT ME!
 
276
     */
 
277
    public void testSelectColumns()
 
278
                           throws SQLException {
 
279
 
 
280
        for (int i = 6; i < MAX_COLUMNS_TO_TEST; i += STEP) {
 
281
 
 
282
            long start = System.currentTimeMillis();
 
283
            rs = stmt.executeQuery("SELECT * from statement_col_test_" + i);
 
284
 
 
285
            if (rs.next()) {
 
286
                ;
 
287
            }
 
288
 
 
289
            long end = System.currentTimeMillis();
 
290
            System.out.println(i + " columns = " + (end - start));
 
291
        }
 
292
    }
 
293
 
 
294
    /**
 
295
     * DOCUMENT ME!
 
296
     * 
 
297
     * @throws SQLException DOCUMENT ME!
 
298
     */
 
299
    public void testAutoIncrement()
 
300
                           throws SQLException {
 
301
 
 
302
        try {
 
303
            stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, 
 
304
                                        java.sql.ResultSet.CONCUR_READ_ONLY);
 
305
            stmt.setFetchSize(Integer.MIN_VALUE);
 
306
            stmt.executeUpdate(
 
307
                    "INSERT INTO statement_test (strdata1) values ('blah')");
 
308
 
 
309
            int autoIncKeyFromApi = -1;
 
310
            rs = stmt.getGeneratedKeys();
 
311
 
 
312
            if (rs.next()) {
 
313
                autoIncKeyFromApi = rs.getInt(1);
 
314
            } else {
 
315
                fail("Failed to retrieve AUTO_INCREMENT using Statement.getGeneratedKeys()");
 
316
            }
 
317
 
 
318
            rs.close();
 
319
 
 
320
            int autoIncKeyFromFunc = -1;
 
321
            rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");
 
322
 
 
323
            if (rs.next()) {
 
324
                autoIncKeyFromFunc = rs.getInt(1);
 
325
            } else {
 
326
                fail("Failed to retrieve AUTO_INCREMENT using LAST_INSERT_ID()");
 
327
            }
 
328
 
 
329
            if (autoIncKeyFromApi != -1 && autoIncKeyFromFunc != -1) {
 
330
                assertTrue("Key retrieved from API (" + autoIncKeyFromApi
 
331
                           + ") does not match key retrieved from LAST_INSERT_ID() "
 
332
                           + autoIncKeyFromFunc + ") function", 
 
333
                           autoIncKeyFromApi == autoIncKeyFromFunc);
 
334
            } else {
 
335
                fail("AutoIncrement keys were '0'");
 
336
            }
 
337
        } finally {
 
338
 
 
339
            if (rs != null) {
 
340
 
 
341
                try {
 
342
                    rs.close();
 
343
                } catch (Exception ex) { /* ignore */
 
344
                    ;
 
345
                }
 
346
            }
 
347
 
 
348
            rs = null;
 
349
        }
 
350
    }
 
351
 
 
352
    /**
 
353
     * DOCUMENT ME!
 
354
     * 
 
355
     * @throws SQLException DOCUMENT ME!
 
356
     */
 
357
    public void testClose()
 
358
                   throws SQLException {
 
359
 
 
360
        Statement closeStmt = null;
 
361
        boolean exceptionAfterClosed = false;
 
362
 
 
363
        try {
 
364
            closeStmt = conn.createStatement();
 
365
            closeStmt.close();
 
366
 
 
367
            try {
 
368
                closeStmt.executeQuery("SELECT 1");
 
369
            } catch (SQLException sqlEx) {
 
370
                exceptionAfterClosed = true;
 
371
            }
 
372
        } finally {
 
373
 
 
374
            if (closeStmt != null) {
 
375
 
 
376
                try {
 
377
                    closeStmt.close();
 
378
                } catch (SQLException sqlEx) {
 
379
 
 
380
                    /* ignore */
 
381
                }
 
382
            }
 
383
 
 
384
            closeStmt = null;
 
385
        }
 
386
 
 
387
        assertTrue("Operations not allowed on Statement after .close() is called!", 
 
388
                   exceptionAfterClosed);
 
389
    }
 
390
 
 
391
    /**
 
392
     * DOCUMENT ME!
 
393
     * 
 
394
     * @throws SQLException DOCUMENT ME!
 
395
     */
 
396
    public void testInsert()
 
397
                    throws SQLException {
 
398
 
 
399
        try {
 
400
 
 
401
            boolean autoCommit = conn.getAutoCommit();
 
402
 
 
403
            // Test running a query for an update. It should fail.
 
404
            try {
 
405
                conn.setAutoCommit(false);
 
406
                stmt.executeUpdate("SELECT * FROM statement_test");
 
407
            } catch (SQLException sqlEx) {
 
408
                assertTrue("Exception thrown for unknown reason", 
 
409
                           sqlEx.getSQLState().equalsIgnoreCase("S1009"));
 
410
            } finally {
 
411
                conn.setAutoCommit(autoCommit);
 
412
            }
 
413
 
 
414
            // Test running a update for an query. It should fail.
 
415
            try {
 
416
                conn.setAutoCommit(false);
 
417
                stmt.executeQuery(
 
418
                        "UPDATE statement_test SET strdata1='blah' WHERE 1=0");
 
419
            } catch (SQLException sqlEx) {
 
420
                assertTrue("Exception thrown for unknown reason", 
 
421
                           sqlEx.getSQLState().equalsIgnoreCase("S1009"));
 
422
            } finally {
 
423
                conn.setAutoCommit(autoCommit);
 
424
            }
 
425
 
 
426
            for (int i = 0; i < 10; i++) {
 
427
 
 
428
                int updateCount = stmt.executeUpdate(
 
429
                                          "INSERT INTO statement_test (strdata1,strdata2) values ('abcdefg', 'poi')");
 
430
                assertTrue("Update count must be '1', was '" + updateCount
 
431
                           + "'", (updateCount == 1));
 
432
            }
 
433
 
 
434
            stmt.executeUpdate(
 
435
                    "INSERT INTO statement_test (strdata1, strdata2) values ('a', 'a'), ('b', 'b'), ('c', 'c')");
 
436
            rs = stmt.getGeneratedKeys();
 
437
 
 
438
            
 
439
 
 
440
            if (rs.next()) {
 
441
                rs.getInt(1);
 
442
            }
 
443
 
 
444
            rs.close();
 
445
            rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");
 
446
 
 
447
            int updateCountFromServer = 0;
 
448
 
 
449
            if (rs.next()) {
 
450
                updateCountFromServer = rs.getInt(1);
 
451
            }
 
452
 
 
453
            System.out.println(
 
454
                    "Update count from server: " + updateCountFromServer);
 
455
        } finally {
 
456
 
 
457
            if (rs != null) {
 
458
 
 
459
                try {
 
460
                    rs.close();
 
461
                } catch (Exception ex) { /* ignore */
 
462
                    ;
 
463
                }
 
464
            }
 
465
 
 
466
            rs = null;
 
467
        }
 
468
    }
 
469
 
 
470
    /**
 
471
     * DOCUMENT ME!
 
472
     * 
 
473
     * @throws SQLException DOCUMENT ME!
 
474
     */
 
475
    public void testPreparedStatement()
 
476
                               throws SQLException {
 
477
        stmt.executeUpdate(
 
478
                "INSERT INTO statement_test (id, strdata1,strdata2) values (999,'abcdefg', 'poi')");
 
479
        pstmt = conn.prepareStatement(
 
480
                        "UPDATE statement_test SET strdata1=?, strdata2=? where id=?");
 
481
        pstmt.setString(1, "iop");
 
482
        pstmt.setString(2, "higjklmn");
 
483
        pstmt.setInt(3, 999);
 
484
 
 
485
        int updateCount = pstmt.executeUpdate();
 
486
        assertTrue("Update count must be '1', was '" + updateCount + "'", 
 
487
                   (updateCount == 1));
 
488
    }
 
489
 
 
490
    /**
 
491
     * DOCUMENT ME!
 
492
     * 
 
493
     * @throws SQLException DOCUMENT ME!
 
494
     */
 
495
    public void testPreparedStatementBatch()
 
496
                                    throws SQLException {
 
497
        pstmt = conn.prepareStatement(
 
498
                        "INSERT INTO "
 
499
                        + "statement_batch_test (strdata1, strdata2) VALUES (?,?)");
 
500
 
 
501
        for (int i = 0; i < 10; i++) {
 
502
            pstmt.setString(1, "batch_" + i);
 
503
            pstmt.setString(2, "batch_" + i);
 
504
            pstmt.addBatch();
 
505
        }
 
506
 
 
507
        int[] updateCounts = pstmt.executeBatch();
 
508
 
 
509
        for (int i = 0; i < updateCounts.length; i++) {
 
510
            assertTrue("Update count must be '1', was '" + updateCounts[i]
 
511
                       + "'", (updateCounts[i] == 1));
 
512
        }
 
513
    }
 
514
 
 
515
    /**
 
516
     * DOCUMENT ME!
 
517
     * 
 
518
     * @throws SQLException DOCUMENT ME!
 
519
     */
 
520
    public void testStubbed()
 
521
                     throws SQLException {
 
522
 
 
523
        try {
 
524
            stmt.getResultSetHoldability();
 
525
        } /* ignore */ catch (NotImplemented notImplEx) {
 
526
            ;
 
527
        }
 
528
    }
 
529
    
 
530
    /**
 
531
     * Tests that NULLs and '' work correctly.
 
532
     * 
 
533
     * @throws SQLException if an error occurs
 
534
     */
 
535
    public void testNulls() throws SQLException {
 
536
        try {
 
537
                stmt.executeUpdate("DROP TABLE IF EXISTS nullTest");
 
538
                stmt.executeUpdate("CREATE TABLE IF NOT EXISTS nullTest (field_1 CHAR(20), rowOrder INT)");
 
539
                stmt.executeUpdate("INSERT INTO nullTest VALUES (null, 1), ('', 2)");
 
540
        
 
541
                rs = stmt.executeQuery("SELECT field_1 FROM nullTest ORDER BY rowOrder");
 
542
        
 
543
                rs.next();
 
544
        
 
545
                assertTrue("NULL field not returned as NULL", rs.getString("field_1") == null && rs.wasNull());
 
546
        
 
547
                rs.next();
 
548
        
 
549
                assertTrue("Empty field not returned as \"\"", rs.getString("field_1").equals("") && !rs.wasNull());
 
550
        
 
551
                rs.close();     
 
552
        } finally {
 
553
                if (rs != null) {
 
554
                        try {
 
555
                                rs.close();
 
556
                        } catch (Exception ex) {
 
557
                                // ignore
 
558
                        }       
 
559
                }
 
560
                
 
561
                stmt.executeUpdate("DROP TABLE IF EXISTS nullTest");
 
562
        }
 
563
    }
 
564
}