~ubuntu-branches/ubuntu/wily/libpgjava/wily

« back to all changes in this revision

Viewing changes to src/interfaces/jdbc/org/postgresql/jdbc1/AbstractJdbc1Statement.java

  • Committer: Bazaar Package Importer
  • Author(s): Arnaud Vandyck
  • Date: 2005-04-21 14:25:11 UTC
  • mfrom: (1.2.1 upstream) (2.1.1 warty)
  • Revision ID: james.westby@ubuntu.com-20050421142511-wibh5vc31fkrorx7
Tags: 7.4.7-3
Built with sources...

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
package org.postgresql.jdbc1;
 
2
 
 
3
import org.postgresql.core.BaseConnection;
 
4
import org.postgresql.core.BaseResultSet;
 
5
import org.postgresql.core.BaseStatement;
 
6
import org.postgresql.core.Field;
 
7
import org.postgresql.core.QueryExecutor;
 
8
import org.postgresql.largeobject.LargeObject;
 
9
import org.postgresql.largeobject.LargeObjectManager;
 
10
import org.postgresql.util.PGbytea;
 
11
import org.postgresql.util.PGobject;
 
12
import org.postgresql.util.PSQLException;
 
13
import org.postgresql.util.PSQLState;
 
14
import java.io.IOException;
 
15
import java.io.InputStream;
 
16
import java.io.InputStreamReader;
 
17
import java.io.OutputStream;
 
18
import java.io.UnsupportedEncodingException;
 
19
import java.math.BigDecimal;
 
20
import java.sql.CallableStatement;
 
21
import java.sql.ResultSet;
 
22
import java.sql.SQLException;
 
23
import java.sql.SQLWarning;
 
24
import java.sql.Time;
 
25
import java.sql.Timestamp;
 
26
import java.sql.Types;
 
27
import java.util.Vector;
 
28
 
 
29
/* $Header: /cvsroot/pgsql/src/interfaces/jdbc/org/postgresql/jdbc1/Attic/AbstractJdbc1Statement.java,v 1.41.2.8 2004/10/21 19:13:55 jurka Exp $
 
30
 * This class defines methods of the jdbc1 specification.  This class is
 
31
 * extended by org.postgresql.jdbc2.AbstractJdbc2Statement which adds the jdbc2
 
32
 * methods.  The real Statement class (for jdbc1) is org.postgresql.jdbc1.Jdbc1Statement
 
33
 */
 
34
public abstract class AbstractJdbc1Statement implements BaseStatement
 
35
{
 
36
        // The connection who created us
 
37
        protected BaseConnection connection;
 
38
 
 
39
        /** The warnings chain. */
 
40
        protected SQLWarning warnings = null;
 
41
 
 
42
        /** Maximum number of rows to return, 0 = unlimited */
 
43
        protected int maxrows = 0;
 
44
 
 
45
        /** Number of rows to get in a batch. */
 
46
        protected int fetchSize = 0;
 
47
 
 
48
        /** Timeout (in seconds) for a query (not used) */
 
49
        protected int timeout = 0;
 
50
 
 
51
        protected boolean replaceProcessingEnabled = true;
 
52
 
 
53
        /** The current results */
 
54
        protected BaseResultSet result = null;
 
55
 
 
56
        // Static variables for parsing SQL when replaceProcessing is true.
 
57
        private static final short IN_SQLCODE = 0;
 
58
        private static final short IN_STRING = 1;
 
59
        private static final short BACKSLASH = 2;
 
60
        private static final short ESC_TIMEDATE = 3;
 
61
 
 
62
        // Some performance caches
 
63
        private StringBuffer sbuf = new StringBuffer(32);
 
64
 
 
65
        protected String[] m_sqlFragments;              // Query fragments.
 
66
        private String[] m_executeSqlFragments;         // EXECUTE(...) if useServerPrepare
 
67
        protected Object[] m_binds = new Object[0];     // Parameter values
 
68
        
 
69
        protected String[] m_bindTypes = new String[0]; // Parameter types, for PREPARE(...)
 
70
        protected String m_statementName = null;        // Allocated PREPARE statement name for server-prepared statements
 
71
        protected String m_cursorName = null;           // Allocated DECLARE cursor name for cursor-based fetch
 
72
 
 
73
        // Constants for allowXXX and m_isSingleStatement vars, below.
 
74
        // The idea is to defer the cost of examining the query until we really need to know,
 
75
        // but don't reexamine it every time thereafter.
 
76
 
 
77
        private static final short UNKNOWN = 0;      // Don't know yet, examine the query.
 
78
        private static final short NO = 1;           // Don't use feature
 
79
        private static final short YES = 2;          // Do use feature
 
80
        
 
81
        private short m_isSingleDML = UNKNOWN;         // Is the query a single SELECT/UPDATE/INSERT/DELETE?
 
82
        private short m_isSingleSelect = UNKNOWN;      // Is the query a single SELECT?
 
83
        private short m_isSingleStatement = UNKNOWN;   // Is the query a single statement?
 
84
 
 
85
        private boolean m_useServerPrepare = false;
 
86
 
 
87
        private boolean isClosed = false;
 
88
 
 
89
    // m_preparedCount is used for naming of auto-cursors and must
 
90
    // be synchronized so that multiple threads using the same
 
91
    // connection don't stomp over each others cursors.
 
92
        private static int m_preparedCount = 1;
 
93
    private synchronized static int next_preparedCount()
 
94
    {
 
95
        return m_preparedCount++;
 
96
    }
 
97
 
 
98
        //Used by the callablestatement style methods
 
99
        private static final String JDBC_SYNTAX = "{[? =] call <some_function> ([? [,?]*]) }";
 
100
        private static final String RESULT_ALIAS = "result";
 
101
        private String originalSql = "";
 
102
        private boolean isFunction;
 
103
        // functionReturnType contains the user supplied value to check
 
104
        // testReturn contains a modified version to make it easier to
 
105
        // check the getXXX methods..
 
106
        private int functionReturnType;
 
107
        private int testReturn;
 
108
        // returnTypeSet is true when a proper call to registerOutParameter has been made
 
109
        private boolean returnTypeSet;
 
110
        protected Object callResult;
 
111
        protected int maxfieldSize = 0;
 
112
 
 
113
        public abstract BaseResultSet createResultSet(Field[] fields, Vector tuples, String status, int updateCount, long insertOID) throws SQLException;
 
114
 
 
115
        public AbstractJdbc1Statement (BaseConnection connection)
 
116
        {
 
117
                this.connection = connection;
 
118
        }
 
119
 
 
120
        public AbstractJdbc1Statement (BaseConnection connection, String p_sql) throws SQLException
 
121
        {
 
122
                this.connection = connection;
 
123
                parseSqlStmt(p_sql);  // this allows Callable stmt to override
 
124
        }
 
125
 
 
126
        public BaseConnection getPGConnection() {
 
127
                return connection;
 
128
        }
 
129
 
 
130
        public String getFetchingCursorName() {
 
131
                return m_cursorName;
 
132
        }
 
133
 
 
134
        public int getFetchSize() {
 
135
                return fetchSize;
 
136
        }
 
137
 
 
138
        protected void parseSqlStmt (String p_sql) throws SQLException
 
139
        {
 
140
                String l_sql = p_sql;
 
141
 
 
142
                l_sql = replaceProcessing(l_sql);
 
143
 
 
144
                if (this instanceof CallableStatement)
 
145
                {
 
146
                        l_sql = modifyJdbcCall(l_sql);
 
147
                }
 
148
 
 
149
                Vector v = new Vector();
 
150
                boolean inQuotes = false;
 
151
                int lastParmEnd = 0, i;
 
152
 
 
153
                m_isSingleSelect = m_isSingleDML = UNKNOWN;
 
154
                m_isSingleStatement = YES;
 
155
 
 
156
                for (i = 0; i < l_sql.length(); ++i)
 
157
                {
 
158
                        int c = l_sql.charAt(i);
 
159
 
 
160
                        if (c == '\'')
 
161
                                inQuotes = !inQuotes;
 
162
                        if (c == '?' && !inQuotes)
 
163
                        {
 
164
                                v.addElement(l_sql.substring (lastParmEnd, i));
 
165
                                lastParmEnd = i + 1;
 
166
                        }
 
167
                        if (c == ';' && !inQuotes)
 
168
                                m_isSingleStatement = m_isSingleSelect = m_isSingleDML = NO;
 
169
                }
 
170
                v.addElement(l_sql.substring (lastParmEnd, l_sql.length()));
 
171
 
 
172
                m_sqlFragments = new String[v.size()];
 
173
                m_binds = new Object[v.size() - 1];
 
174
                m_bindTypes = new String[v.size() - 1];
 
175
 
 
176
                for (i = 0 ; i < m_sqlFragments.length; ++i)
 
177
                        m_sqlFragments[i] = (String)v.elementAt(i);
 
178
 
 
179
        }
 
180
 
 
181
        /*
 
182
         * Deallocate resources allocated for the current query
 
183
         * in preparation for replacing it with a new query.
 
184
         */
 
185
        private void deallocateQuery()
 
186
        {               
 
187
                //If we have already created a server prepared statement, we need
 
188
                //to deallocate the existing one
 
189
                if (m_statementName != null)
 
190
                {
 
191
                        try
 
192
                        {
 
193
                                connection.execSQL("DEALLOCATE " + m_statementName);
 
194
                        }
 
195
                        catch (Exception e)
 
196
                        {
 
197
                        }
 
198
                }
 
199
 
 
200
                m_statementName = null;
 
201
                m_cursorName = null; // automatically closed at end of txn anyway
 
202
                m_executeSqlFragments = null;
 
203
                m_isSingleStatement = m_isSingleSelect = m_isSingleDML = UNKNOWN;
 
204
        }
 
205
  
 
206
        /*
 
207
         * Execute a SQL statement that retruns a single ResultSet
 
208
         *
 
209
         * @param sql typically a static SQL SELECT statement
 
210
         * @return a ResulSet that contains the data produced by the query
 
211
         * @exception SQLException if a database access error occurs
 
212
         */
 
213
        public java.sql.ResultSet executeQuery(String p_sql) throws SQLException
 
214
        {
 
215
                deallocateQuery();
 
216
 
 
217
                String l_sql = replaceProcessing(p_sql);
 
218
                m_sqlFragments = new String[] {l_sql};
 
219
                m_binds = new Object[0];
 
220
 
 
221
                return executeQuery();
 
222
        }
 
223
 
 
224
        /*
 
225
         * A Prepared SQL query is executed and its ResultSet is returned
 
226
         *
 
227
         * @return a ResultSet that contains the data produced by the
 
228
         *               *      query - never null
 
229
         * @exception SQLException if a database access error occurs
 
230
         */
 
231
        public java.sql.ResultSet executeQuery() throws SQLException
 
232
        {
 
233
                this.execute();
 
234
 
 
235
                while (result != null && !result.reallyResultSet())
 
236
                        result = (BaseResultSet) result.getNext();
 
237
                if (result == null)
 
238
                        throw new PSQLException("postgresql.stat.noresult", PSQLState.NO_DATA);
 
239
                return (ResultSet) result;
 
240
        }
 
241
 
 
242
        /*
 
243
         * Execute a SQL INSERT, UPDATE or DELETE statement.  In addition
 
244
         * SQL statements that return nothing such as SQL DDL statements
 
245
         * can be executed
 
246
         *
 
247
         * @param sql a SQL statement
 
248
         * @return either a row count, or 0 for SQL commands
 
249
         * @exception SQLException if a database access error occurs
 
250
         */
 
251
        public int executeUpdate(String p_sql) throws SQLException
 
252
        {
 
253
                deallocateQuery();
 
254
 
 
255
                String l_sql = replaceProcessing(p_sql);
 
256
                m_sqlFragments = new String[] {l_sql};
 
257
                m_binds = new Object[0];
 
258
 
 
259
                return executeUpdate();
 
260
        }
 
261
 
 
262
        /*
 
263
         * Execute a SQL INSERT, UPDATE or DELETE statement.  In addition,
 
264
         * SQL statements that return nothing such as SQL DDL statements can
 
265
         * be executed.
 
266
         *
 
267
         * @return either the row count for INSERT, UPDATE or DELETE; or
 
268
         *               *      0 for SQL statements that return nothing.
 
269
         * @exception SQLException if a database access error occurs
 
270
         */
 
271
        public int executeUpdate() throws SQLException
 
272
        {
 
273
                this.execute();
 
274
                if (result.reallyResultSet())
 
275
                        throw new PSQLException("postgresql.stat.result");
 
276
                return this.getUpdateCount();
 
277
        }
 
278
 
 
279
        /*
 
280
         * Execute a SQL statement that may return multiple results. We
 
281
         * don't have to worry about this since we do not support multiple
 
282
         * ResultSets.   You can use getResultSet or getUpdateCount to
 
283
         * retrieve the result.
 
284
         *
 
285
         * @param sql any SQL statement
 
286
         * @return true if the next result is a ResulSet, false if it is
 
287
         *      an update count or there are no more results
 
288
         * @exception SQLException if a database access error occurs
 
289
         */
 
290
        public boolean execute(String p_sql) throws SQLException
 
291
        {
 
292
                deallocateQuery();
 
293
 
 
294
                String l_sql = replaceProcessing(p_sql);
 
295
                m_sqlFragments = new String[] {l_sql};
 
296
                m_binds = new Object[0];
 
297
 
 
298
                return execute();
 
299
        }
 
300
 
 
301
        /*
 
302
         * Check if the current query is a single statement.
 
303
         */
 
304
        private boolean isSingleStatement()
 
305
        {
 
306
                if (m_isSingleStatement != UNKNOWN)
 
307
                        return m_isSingleStatement == YES;
 
308
                
 
309
                // Crude detection of multiple statements. This could be
 
310
                // improved by parsing the whole query for quotes, but is
 
311
                // it worth it given that the only queries that get here are
 
312
                // unparameterized queries?
 
313
                
 
314
                for (int i = 0; i < m_sqlFragments.length; ++i) { // a bit redundant, but ..
 
315
                        if (m_sqlFragments[i].indexOf(';') != -1) {
 
316
                                m_isSingleStatement = NO;
 
317
                                return false;
 
318
                        }
 
319
                }
 
320
                
 
321
                m_isSingleStatement = YES;
 
322
                return true;
 
323
        }
 
324
 
 
325
        /*
 
326
         * Helper for isSingleSelect() and isSingleDML(): computes values
 
327
         * of m_isSingleDML and m_isSingleSelect.
 
328
         */
 
329
        private void analyzeStatementType()
 
330
        {
 
331
                if (!isSingleStatement()) {
 
332
                        m_isSingleSelect = m_isSingleDML = NO;
 
333
                        return;
 
334
                }
 
335
                
 
336
                String compare = m_sqlFragments[0].trim().toLowerCase();
 
337
                if (compare.startsWith("select")) {
 
338
                        m_isSingleSelect = m_isSingleDML = YES;
 
339
                        return;
 
340
                }
 
341
 
 
342
                m_isSingleSelect = NO;
 
343
 
 
344
                if (!compare.startsWith("update") &&
 
345
                        !compare.startsWith("delete") &&
 
346
                        !compare.startsWith("insert")) {
 
347
                        m_isSingleDML = NO;
 
348
                        return;
 
349
                }
 
350
                
 
351
                m_isSingleDML = YES;
 
352
        }
 
353
 
 
354
        /*
 
355
         * Check if the current query is a single SELECT.
 
356
         */
 
357
        private boolean isSingleSelect()
 
358
        {
 
359
                if (m_isSingleSelect == UNKNOWN)
 
360
                        analyzeStatementType();
 
361
 
 
362
                return m_isSingleSelect == YES;
 
363
        }
 
364
 
 
365
        /*
 
366
         * Check if the current query is a single SELECT/UPDATE/INSERT/DELETE.
 
367
         */
 
368
        private boolean isSingleDML()
 
369
        {
 
370
                if (m_isSingleDML == UNKNOWN)
 
371
                        analyzeStatementType();
 
372
 
 
373
                return m_isSingleDML == YES;
 
374
        }
 
375
 
 
376
        /*
 
377
         * Return the query fragments to use for a server-prepared statement.
 
378
         * The first query executed will include a PREPARE and EXECUTE;
 
379
         * subsequent queries will just be an EXECUTE.
 
380
         */
 
381
        private String[] transformToServerPrepare() {
 
382
                if (m_statementName != null)
 
383
                        return m_executeSqlFragments;
 
384
               
 
385
                // First time through.
 
386
                m_statementName = "JDBC_STATEMENT_" + next_preparedCount();
 
387
               
 
388
                // Set up m_executeSqlFragments
 
389
                m_executeSqlFragments = new String[m_sqlFragments.length];
 
390
                m_executeSqlFragments[0] = "EXECUTE " + m_statementName;                                
 
391
                if (m_sqlFragments.length > 1) {
 
392
                        m_executeSqlFragments[0] += "(";
 
393
                        for (int i = 1; i < m_bindTypes.length; i++)
 
394
                                m_executeSqlFragments[i] = ", ";
 
395
                        m_executeSqlFragments[m_bindTypes.length] = ")";
 
396
                }
 
397
               
 
398
                // Set up the PREPARE.
 
399
                String[] prepareSqlFragments = new String[m_sqlFragments.length];
 
400
                System.arraycopy(m_sqlFragments, 0, prepareSqlFragments, 0, m_sqlFragments.length);
 
401
               
 
402
                synchronized (sbuf) {
 
403
                        sbuf.setLength(0);
 
404
                        sbuf.append("PREPARE ");
 
405
                        sbuf.append(m_statementName);
 
406
                        if (m_sqlFragments.length > 1) {
 
407
                                sbuf.append("(");
 
408
                                for (int i = 0; i < m_bindTypes.length; i++) {
 
409
                                        if (i != 0) sbuf.append(", ");
 
410
                                        sbuf.append(m_bindTypes[i]);                                                    
 
411
                                }
 
412
                                sbuf.append(")");
 
413
                        }
 
414
                        sbuf.append(" AS ");
 
415
                        sbuf.append(m_sqlFragments[0]);
 
416
                        for (int i = 1; i < m_sqlFragments.length; i++) {
 
417
                                sbuf.append(" $");
 
418
                                sbuf.append(i);
 
419
                                sbuf.append(" ");
 
420
                                sbuf.append(m_sqlFragments[i]);
 
421
                        }
 
422
                        sbuf.append("; ");
 
423
                        sbuf.append(m_executeSqlFragments[0]);
 
424
                       
 
425
                        prepareSqlFragments[0] = sbuf.toString();
 
426
                }
 
427
               
 
428
                System.arraycopy(m_executeSqlFragments, 1, prepareSqlFragments, 1, prepareSqlFragments.length - 1);
 
429
                return prepareSqlFragments;
 
430
        }
 
431
        
 
432
        /*
 
433
         * Return the current query transformed into a cursor-based statement.
 
434
         * This uses a new cursor on each query.
 
435
         */
 
436
        private String[] transformToCursorFetch() 
 
437
        {
 
438
                
 
439
                // Pinch the prepared count for our own nefarious purposes.
 
440
                m_cursorName = "JDBC_CURS_" + next_preparedCount();
 
441
                
 
442
                // Create a cursor declaration and initial fetch statement from the original query.
 
443
                int len = m_sqlFragments.length;
 
444
                String[] cursorBasedSql = new String[len];
 
445
                System.arraycopy(m_sqlFragments, 0, cursorBasedSql, 0, len);
 
446
                cursorBasedSql[0] = "DECLARE " + m_cursorName + " CURSOR FOR " + cursorBasedSql[0];
 
447
                cursorBasedSql[len-1] += "; FETCH FORWARD " + fetchSize + " FROM " + m_cursorName;
 
448
                
 
449
                // Make the cursor based query the one that will be used.
 
450
                if (org.postgresql.Driver.logDebug)
 
451
                        org.postgresql.Driver.debug("using cursor based sql with cursor name " + m_cursorName);
 
452
                
 
453
                return cursorBasedSql;
 
454
        }
 
455
 
 
456
        /**
 
457
         * Do transformations to a query for server-side prepare or setFetchSize() cursor
 
458
         * work.
 
459
         * @return the query fragments to execute
 
460
         */
 
461
        private String[] getQueryFragments()
 
462
        {
 
463
                // nb: isSingleXXX() are relatively expensive, avoid calling them unless we must.
 
464
                
 
465
                // We check the "mutable" bits of these conditions (which may change without
 
466
                // a new query being created) here; isSingleXXX() only concern themselves with
 
467
                // the query structure itself.
 
468
 
 
469
                // We prefer cursor-based-fetch over server-side-prepare here.          
 
470
                // Eventually a v3 implementation should let us do both at once.
 
471
                if (fetchSize > 0 && !connection.getAutoCommit() && isSingleSelect())
 
472
                        return transformToCursorFetch();
 
473
 
 
474
                if (isUseServerPrepare() && isSingleDML())
 
475
                        return transformToServerPrepare();
 
476
                
 
477
                // Not server-prepare or cursor-fetch, just return a plain query.
 
478
                return m_sqlFragments;
 
479
        }                                       
 
480
        
 
481
        /*
 
482
         * Some prepared statements return multiple results; the execute method
 
483
         * handles these complex statements as well as the simpler form of
 
484
         * statements handled by executeQuery and executeUpdate
 
485
         *
 
486
         * @return true if the next result is a ResultSet; false if it is an
 
487
         *               update count or there are no more results
 
488
         * @exception SQLException if a database access error occurs
 
489
         */
 
490
        public boolean execute() throws SQLException
 
491
        {
 
492
                if (isFunction && !returnTypeSet)
 
493
                        throw new PSQLException("postgresql.call.noreturntype", PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL);
 
494
                if (isFunction)
 
495
                { // set entry 1 to dummy entry..
 
496
                        m_binds[0] = ""; // dummy entry which ensured that no one overrode
 
497
                        m_bindTypes[0] = PG_TEXT;
 
498
                        // and calls to setXXX (2,..) really went to first arg in a function call..
 
499
                }
 
500
 
 
501
                // New in 7.1, if we have a previous resultset then force it to close
 
502
                // This brings us nearer to compliance, and helps memory management.
 
503
                // Internal stuff will call ExecSQL directly, bypassing this.
 
504
 
 
505
                if (result != null)
 
506
                {
 
507
                        java.sql.ResultSet rs = getResultSet();
 
508
                        if (rs != null)
 
509
                                rs.close();
 
510
                }
 
511
 
 
512
                // Get the actual query fragments to run (might be a transformed version of
 
513
                // the original fragments)
 
514
                String[] fragments = getQueryFragments();
 
515
 
 
516
                // New in 7.1, pass Statement so that ExecSQL can customise to it                
 
517
                result = QueryExecutor.execute(fragments,
 
518
                                                                           m_binds,
 
519
                                                                           this);
 
520
 
 
521
                //If we are executing a callable statement function set the return data
 
522
                if (isFunction)
 
523
                {
 
524
                        if (!result.reallyResultSet())
 
525
                                throw new PSQLException("postgresql.call.noreturnval", PSQLState.NO_DATA);
 
526
                        if (!result.next ())
 
527
                                throw new PSQLException ("postgresql.call.noreturnval", PSQLState.NO_DATA);
 
528
                        callResult = result.getObject(1);
 
529
                        int columnType = result.getMetaData().getColumnType(1);
 
530
                        if (columnType != functionReturnType)
 
531
                                throw new PSQLException ("postgresql.call.wrongrtntype", PSQLState.DATA_TYPE_MISMATCH,
 
532
                                                                                 new Object[]{
 
533
                                                                                         "java.sql.Types=" + columnType, "java.sql.Types=" + functionReturnType });
 
534
                        result.close ();
 
535
                        return true;
 
536
                }
 
537
                else
 
538
                {
 
539
                        return (result != null && result.reallyResultSet());
 
540
                }
 
541
        }
 
542
        
 
543
        /*
 
544
         * setCursorName defines the SQL cursor name that will be used by
 
545
         * subsequent execute methods.  This name can then be used in SQL
 
546
         * positioned update/delete statements to identify the current row
 
547
         * in the ResultSet generated by this statement.  If a database
 
548
         * doesn't support positioned update/delete, this method is a
 
549
         * no-op.
 
550
         *
 
551
         * <p><B>Note:</B> By definition, positioned update/delete execution
 
552
         * must be done by a different Statement than the one which
 
553
         * generated the ResultSet being used for positioning.  Also, cursor
 
554
         * names must be unique within a Connection.
 
555
         *
 
556
         * <p>We throw an additional constriction.      There can only be one
 
557
         * cursor active at any one time.
 
558
         *
 
559
         * @param name the new cursor name
 
560
         * @exception SQLException if a database access error occurs
 
561
         */
 
562
        public void setCursorName(String name) throws SQLException
 
563
        {
 
564
                connection.setCursorName(name);
 
565
        }
 
566
 
 
567
 
 
568
        /*
 
569
         * getUpdateCount returns the current result as an update count,
 
570
         * if the result is a ResultSet or there are no more results, -1
 
571
         * is returned.  It should only be called once per result.
 
572
         *
 
573
         * @return the current result as an update count.
 
574
         * @exception SQLException if a database access error occurs
 
575
         */
 
576
        public int getUpdateCount() throws SQLException
 
577
        {
 
578
                if (result == null)
 
579
                        return -1;
 
580
                if (isFunction)
 
581
                        return 1;
 
582
                if (result.reallyResultSet())
 
583
                        return -1;
 
584
                return result.getResultCount();
 
585
        }
 
586
 
 
587
        /*
 
588
         * getMoreResults moves to a Statement's next result.  If it returns
 
589
         * true, this result is a ResulSet.
 
590
         *
 
591
         * @return true if the next ResultSet is valid
 
592
         * @exception SQLException if a database access error occurs
 
593
         */
 
594
        public boolean getMoreResults() throws SQLException
 
595
        {
 
596
                result = (BaseResultSet) result.getNext();
 
597
                return (result != null && result.reallyResultSet());
 
598
        }
 
599
 
 
600
 
 
601
 
 
602
        /*
 
603
         * Returns the status message from the current Result.<p>
 
604
         * This is used internally by the driver.
 
605
         *
 
606
         * @return status message from backend
 
607
         */
 
608
        public String getResultStatusString()
 
609
        {
 
610
                if (result == null)
 
611
                        return null;
 
612
                return result.getStatusString();
 
613
        }
 
614
 
 
615
        /*
 
616
         * The maxRows limit is set to limit the number of rows that
 
617
         * any ResultSet can contain.  If the limit is exceeded, the
 
618
         * excess rows are silently dropped.
 
619
         *
 
620
         * @return the current maximum row limit; zero means unlimited
 
621
         * @exception SQLException if a database access error occurs
 
622
         */
 
623
        public int getMaxRows() throws SQLException
 
624
        {
 
625
                return maxrows;
 
626
        }
 
627
 
 
628
        /*
 
629
         * Set the maximum number of rows
 
630
         *
 
631
         * @param max the new max rows limit; zero means unlimited
 
632
         * @exception SQLException if a database access error occurs
 
633
         * @see getMaxRows
 
634
         */
 
635
        public void setMaxRows(int max) throws SQLException
 
636
        {
 
637
                if (max<0) throw new PSQLException("postgresql.input.rows.gt0");
 
638
                maxrows = max;
 
639
        }
 
640
 
 
641
        /*
 
642
         * If escape scanning is on (the default), the driver will do escape
 
643
         * substitution before sending the SQL to the database.
 
644
         *
 
645
         * @param enable true to enable; false to disable
 
646
         * @exception SQLException if a database access error occurs
 
647
         */
 
648
        public void setEscapeProcessing(boolean enable) throws SQLException
 
649
        {
 
650
                replaceProcessingEnabled = enable;
 
651
        }
 
652
 
 
653
        /*
 
654
         * The queryTimeout limit is the number of seconds the driver
 
655
         * will wait for a Statement to execute.  If the limit is
 
656
         * exceeded, a SQLException is thrown.
 
657
         *
 
658
         * @return the current query timeout limit in seconds; 0 = unlimited
 
659
         * @exception SQLException if a database access error occurs
 
660
         */
 
661
        public int getQueryTimeout() throws SQLException
 
662
        {
 
663
                return timeout;
 
664
        }
 
665
 
 
666
        /*
 
667
         * Sets the queryTimeout limit
 
668
         *
 
669
         * @param seconds - the new query timeout limit in seconds
 
670
         * @exception SQLException if a database access error occurs
 
671
         */
 
672
        public void setQueryTimeout(int seconds) throws SQLException
 
673
        {
 
674
                if (seconds<0) throw new PSQLException("postgresql.input.query.gt0");
 
675
                timeout = seconds;
 
676
        }
 
677
 
 
678
        /**
 
679
         * This adds a warning to the warning chain.
 
680
         * @param msg message to add
 
681
         */
 
682
        public void addWarning(String msg)
 
683
        {
 
684
                if (warnings != null)
 
685
                        warnings.setNextWarning(new SQLWarning(msg));
 
686
                else
 
687
                        warnings = new SQLWarning(msg);
 
688
        }
 
689
 
 
690
        /*
 
691
         * The first warning reported by calls on this Statement is
 
692
         * returned.  A Statement's execute methods clear its SQLWarning
 
693
         * chain.  Subsequent Statement warnings will be chained to this
 
694
         * SQLWarning.
 
695
         *
 
696
         * <p>The Warning chain is automatically cleared each time a statement
 
697
         * is (re)executed.
 
698
         *
 
699
         * <p><B>Note:</B>      If you are processing a ResultSet then any warnings
 
700
         * associated with ResultSet reads will be chained on the ResultSet
 
701
         * object.
 
702
         *
 
703
         * @return the first SQLWarning on null
 
704
         * @exception SQLException if a database access error occurs
 
705
         */
 
706
        public SQLWarning getWarnings() throws SQLException
 
707
        {
 
708
                return warnings;
 
709
        }
 
710
 
 
711
        /*
 
712
         * The maxFieldSize limit (in bytes) is the maximum amount of
 
713
         * data returned for any column value; it only applies to
 
714
         * BINARY, VARBINARY, LONGVARBINARY, CHAR, VARCHAR and LONGVARCHAR
 
715
         * columns.  If the limit is exceeded, the excess data is silently
 
716
         * discarded.
 
717
         *
 
718
         * @return the current max column size limit; zero means unlimited
 
719
         * @exception SQLException if a database access error occurs
 
720
         */
 
721
        public int getMaxFieldSize() throws SQLException
 
722
        {
 
723
                return maxfieldSize;
 
724
        }
 
725
 
 
726
        /*
 
727
         * Sets the maxFieldSize 
 
728
         *
 
729
         * @param max the new max column size limit; zero means unlimited
 
730
         * @exception SQLException if a database access error occurs
 
731
         */
 
732
        public void setMaxFieldSize(int max) throws SQLException
 
733
        {
 
734
                if (max < 0) throw new PSQLException("postgresql.input.field.gt0");
 
735
                maxfieldSize = max;
 
736
        }
 
737
 
 
738
        /*
 
739
         * After this call, getWarnings returns null until a new warning
 
740
         * is reported for this Statement.
 
741
         *
 
742
         * @exception SQLException if a database access error occurs
 
743
         */
 
744
        public void clearWarnings() throws SQLException
 
745
        {
 
746
                warnings = null;
 
747
        }
 
748
 
 
749
        /*
 
750
         * Cancel can be used by one thread to cancel a statement that
 
751
         * is being executed by another thread.
 
752
         * <p>
 
753
         * Not implemented, this method is a no-op.
 
754
         *
 
755
         * @exception SQLException only because thats the spec.
 
756
         */
 
757
        public void cancel() throws SQLException
 
758
        {
 
759
                throw new PSQLException("postgresql.unimplemented", PSQLState.NOT_IMPLEMENTED);
 
760
        }
 
761
 
 
762
        /*
 
763
         * getResultSet returns the current result as a ResultSet.      It
 
764
         * should only be called once per result.
 
765
         *
 
766
         * @return the current result set; null if there are no more
 
767
         * @exception SQLException if a database access error occurs (why?)
 
768
         */
 
769
        public java.sql.ResultSet getResultSet() throws SQLException
 
770
        {
 
771
                if (result != null && result.reallyResultSet())
 
772
                        return (ResultSet) result;
 
773
                return null;
 
774
        }
 
775
 
 
776
        /*
 
777
         * In many cases, it is desirable to immediately release a
 
778
         * Statement's database and JDBC resources instead of waiting
 
779
         * for this to happen when it is automatically closed.  The
 
780
         * close method provides this immediate release.
 
781
         *
 
782
         * <p><B>Note:</B> A Statement is automatically closed when it is
 
783
         * garbage collected.  When a Statement is closed, its current
 
784
         * ResultSet, if one exists, is also closed.
 
785
         *
 
786
         * @exception SQLException if a database access error occurs (why?)
 
787
         */
 
788
        public void close() throws SQLException
 
789
        {
 
790
                // closing an already closed Statement is a no-op.
 
791
                if (isClosed)
 
792
                        return;
 
793
 
 
794
                // Force the ResultSet to close
 
795
                java.sql.ResultSet rs = getResultSet();
 
796
                if (rs != null)
 
797
                        rs.close();
 
798
 
 
799
                deallocateQuery();
 
800
 
 
801
                // Disasociate it from us (For Garbage Collection)
 
802
                result = null;
 
803
                isClosed = true;
 
804
        }
 
805
 
 
806
        /**
 
807
         * This finalizer ensures that statements that have allocated server-side
 
808
         * resources free them when they become unreferenced.
 
809
         */
 
810
        protected void finalize() {
 
811
                try { close(); }
 
812
                catch (SQLException e) {}
 
813
        }
 
814
 
 
815
        /*
 
816
         * Filter the SQL string of Java SQL Escape clauses.
 
817
         *
 
818
         * Currently implemented Escape clauses are those mentioned in 11.3
 
819
         * in the specification. Basically we look through the sql string for
 
820
         * {d xxx}, {t xxx} or {ts xxx} in non-string sql code. When we find
 
821
         * them, we just strip the escape part leaving only the xxx part.
 
822
         * So, something like "select * from x where d={d '2001-10-09'}" would
 
823
         * return "select * from x where d= '2001-10-09'".
 
824
         */
 
825
        protected String replaceProcessing(String p_sql)
 
826
        {
 
827
                if (replaceProcessingEnabled)
 
828
                {
 
829
                        // Since escape codes can only appear in SQL CODE, we keep track
 
830
                        // of if we enter a string or not.
 
831
                        StringBuffer newsql = new StringBuffer(p_sql.length());
 
832
                        short state = IN_SQLCODE;
 
833
 
 
834
                        int i = -1;
 
835
                        int len = p_sql.length();
 
836
                        while (++i < len)
 
837
                        {
 
838
                                char c = p_sql.charAt(i);
 
839
                                switch (state)
 
840
                                {
 
841
                                        case IN_SQLCODE:
 
842
                                                if (c == '\'')                            // start of a string?
 
843
                                                        state = IN_STRING;
 
844
                                                else if (c == '{')                        // start of an escape code?
 
845
                                                        if (i + 1 < len)
 
846
                                                        {
 
847
                                                                char next = p_sql.charAt(i + 1);
 
848
                                                                if (next == 'd')
 
849
                                                                {
 
850
                                                                        state = ESC_TIMEDATE;
 
851
                                                                        i++;
 
852
                                                                        break;
 
853
                                                                }
 
854
                                                                else if (next == 't')
 
855
                                                                {
 
856
                                                                        state = ESC_TIMEDATE;
 
857
                                                                        i += (i + 2 < len && p_sql.charAt(i + 2) == 's') ? 2 : 1;
 
858
                                                                        break;
 
859
                                                                }
 
860
                                                        }
 
861
                                                newsql.append(c);
 
862
                                                break;
 
863
 
 
864
                                        case IN_STRING:
 
865
                                                if (c == '\'')                             // end of string?
 
866
                                                        state = IN_SQLCODE;
 
867
                                                else if (c == '\\')                        // a backslash?
 
868
                                                        state = BACKSLASH;
 
869
 
 
870
                                                newsql.append(c);
 
871
                                                break;
 
872
 
 
873
                                        case BACKSLASH:
 
874
                                                state = IN_STRING;
 
875
 
 
876
                                                newsql.append(c);
 
877
                                                break;
 
878
 
 
879
                                        case ESC_TIMEDATE:
 
880
                                                if (c == '}')
 
881
                                                        state = IN_SQLCODE;               // end of escape code.
 
882
                                                else
 
883
                                                        newsql.append(c);
 
884
                                                break;
 
885
                                } // end switch
 
886
                        }
 
887
 
 
888
                        return newsql.toString();
 
889
                }
 
890
                else
 
891
                {
 
892
                        return p_sql;
 
893
                }
 
894
        }
 
895
 
 
896
        /*
 
897
         *
 
898
         * The following methods are postgres extensions and are defined
 
899
         * in the interface BaseStatement
 
900
         *
 
901
         */
 
902
 
 
903
        /*
 
904
         * Returns the Last inserted/updated oid.  Deprecated in 7.2 because
 
905
                        * range of OID values is greater than a java signed int.
 
906
         * @deprecated Replaced by getLastOID in 7.2
 
907
         */
 
908
        public int getInsertedOID() throws SQLException
 
909
        {
 
910
                if (result == null)
 
911
                        return 0;
 
912
                return (int) result.getLastOID();
 
913
        }
 
914
 
 
915
        /*
 
916
         * Returns the Last inserted/updated oid.
 
917
         * @return OID of last insert
 
918
                        * @since 7.2
 
919
         */
 
920
        public long getLastOID() throws SQLException
 
921
        {
 
922
                if (result == null)
 
923
                        return 0;
 
924
                return result.getLastOID();
 
925
        }
 
926
 
 
927
        /*
 
928
         * Set a parameter to SQL NULL
 
929
         *
 
930
         * <p><B>Note:</B> You must specify the parameters SQL type (although
 
931
         * PostgreSQL ignores it)
 
932
         *
 
933
         * @param parameterIndex the first parameter is 1, etc...
 
934
         * @param sqlType the SQL type code defined in java.sql.Types
 
935
         * @exception SQLException if a database access error occurs
 
936
         */
 
937
        public void setNull(int parameterIndex, int sqlType) throws SQLException
 
938
        {
 
939
        String l_pgType;
 
940
                switch (sqlType)
 
941
                {
 
942
                        case Types.INTEGER:
 
943
                                l_pgType = PG_INTEGER;
 
944
                                break;
 
945
                        case Types.TINYINT:
 
946
                        case Types.SMALLINT:
 
947
                                l_pgType = PG_INT2;
 
948
                                break;
 
949
                        case Types.BIGINT:
 
950
                                l_pgType = PG_INT8;
 
951
                                break;
 
952
                        case Types.REAL:
 
953
                        case Types.FLOAT:
 
954
                                l_pgType = PG_FLOAT;
 
955
                                break;
 
956
                        case Types.DOUBLE:
 
957
                                l_pgType = PG_DOUBLE;
 
958
                                break;
 
959
                        case Types.DECIMAL:
 
960
                        case Types.NUMERIC:
 
961
                                l_pgType = PG_NUMERIC;
 
962
                                break;
 
963
                        case Types.CHAR:
 
964
                        case Types.VARCHAR:
 
965
                        case Types.LONGVARCHAR:
 
966
                                l_pgType = PG_TEXT;
 
967
                                break;
 
968
                        case Types.DATE:
 
969
                                l_pgType = PG_DATE;
 
970
                                break;
 
971
                        case Types.TIME:
 
972
                                l_pgType = PG_TIME;
 
973
                                break;
 
974
                        case Types.TIMESTAMP:
 
975
                                l_pgType = PG_TIMESTAMPTZ;
 
976
                                break;
 
977
                        case Types.BIT:
 
978
                                l_pgType = PG_BOOLEAN;
 
979
                                break;
 
980
                        case Types.BINARY:
 
981
                        case Types.VARBINARY:
 
982
                        case Types.LONGVARBINARY:
 
983
                                l_pgType = PG_BYTEA;
 
984
                                break;
 
985
                        case Types.OTHER:
 
986
                                l_pgType = PG_TEXT;
 
987
                                break;
 
988
                        default:
 
989
                                l_pgType = PG_TEXT;
 
990
                }
 
991
                bind(parameterIndex, "null", l_pgType);
 
992
        }
 
993
 
 
994
        /*
 
995
         * Set a parameter to a Java boolean value.  The driver converts this
 
996
         * to a SQL BIT value when it sends it to the database.
 
997
         *
 
998
         * @param parameterIndex the first parameter is 1...
 
999
         * @param x the parameter value
 
1000
         * @exception SQLException if a database access error occurs
 
1001
         */
 
1002
        public void setBoolean(int parameterIndex, boolean x) throws SQLException
 
1003
        {
 
1004
                bind(parameterIndex, x ? "'1'" : "'0'", PG_BOOLEAN);
 
1005
        }
 
1006
 
 
1007
        /*
 
1008
         * Set a parameter to a Java byte value.  The driver converts this to
 
1009
         * a SQL TINYINT value when it sends it to the database.
 
1010
         *
 
1011
         * @param parameterIndex the first parameter is 1...
 
1012
         * @param x the parameter value
 
1013
         * @exception SQLException if a database access error occurs
 
1014
         */
 
1015
        public void setByte(int parameterIndex, byte x) throws SQLException
 
1016
        {
 
1017
                bind(parameterIndex, Integer.toString(x), PG_INT2);
 
1018
        }
 
1019
 
 
1020
        /*
 
1021
         * Set a parameter to a Java short value.  The driver converts this
 
1022
         * to a SQL SMALLINT value when it sends it to the database.
 
1023
         *
 
1024
         * @param parameterIndex the first parameter is 1...
 
1025
         * @param x the parameter value
 
1026
         * @exception SQLException if a database access error occurs
 
1027
         */
 
1028
        public void setShort(int parameterIndex, short x) throws SQLException
 
1029
        {
 
1030
                bind(parameterIndex, Integer.toString(x), PG_INT2);
 
1031
        }
 
1032
 
 
1033
        /*
 
1034
         * Set a parameter to a Java int value.  The driver converts this to
 
1035
         * a SQL INTEGER value when it sends it to the database.
 
1036
         *
 
1037
         * @param parameterIndex the first parameter is 1...
 
1038
         * @param x the parameter value
 
1039
         * @exception SQLException if a database access error occurs
 
1040
         */
 
1041
        public void setInt(int parameterIndex, int x) throws SQLException
 
1042
        {
 
1043
                bind(parameterIndex, Integer.toString(x), PG_INTEGER);
 
1044
        }
 
1045
 
 
1046
        /*
 
1047
         * Set a parameter to a Java long value.  The driver converts this to
 
1048
         * a SQL BIGINT value when it sends it to the database.
 
1049
         *
 
1050
         * @param parameterIndex the first parameter is 1...
 
1051
         * @param x the parameter value
 
1052
         * @exception SQLException if a database access error occurs
 
1053
         */
 
1054
        public void setLong(int parameterIndex, long x) throws SQLException
 
1055
        {
 
1056
                bind(parameterIndex, Long.toString(x), PG_INT8);
 
1057
        }
 
1058
 
 
1059
        /*
 
1060
         * Set a parameter to a Java float value.  The driver converts this
 
1061
         * to a SQL FLOAT value when it sends it to the database.
 
1062
         *
 
1063
         * @param parameterIndex the first parameter is 1...
 
1064
         * @param x the parameter value
 
1065
         * @exception SQLException if a database access error occurs
 
1066
         */
 
1067
        public void setFloat(int parameterIndex, float x) throws SQLException
 
1068
        {
 
1069
                bind(parameterIndex, Float.toString(x), PG_FLOAT);
 
1070
        }
 
1071
 
 
1072
        /*
 
1073
         * Set a parameter to a Java double value.      The driver converts this
 
1074
         * to a SQL DOUBLE value when it sends it to the database
 
1075
         *
 
1076
         * @param parameterIndex the first parameter is 1...
 
1077
         * @param x the parameter value
 
1078
         * @exception SQLException if a database access error occurs
 
1079
         */
 
1080
        public void setDouble(int parameterIndex, double x) throws SQLException
 
1081
        {
 
1082
                bind(parameterIndex, Double.toString(x), PG_DOUBLE);
 
1083
        }
 
1084
 
 
1085
        /*
 
1086
         * Set a parameter to a java.lang.BigDecimal value.  The driver
 
1087
         * converts this to a SQL NUMERIC value when it sends it to the
 
1088
         * database.
 
1089
         *
 
1090
         * @param parameterIndex the first parameter is 1...
 
1091
         * @param x the parameter value
 
1092
         * @exception SQLException if a database access error occurs
 
1093
         */
 
1094
        public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException
 
1095
        {
 
1096
                if (x == null)
 
1097
                        setNull(parameterIndex, Types.DECIMAL);
 
1098
                else
 
1099
                {
 
1100
                        bind(parameterIndex, x.toString(), PG_NUMERIC);
 
1101
                }
 
1102
        }
 
1103
 
 
1104
        /*
 
1105
         * Set a parameter to a Java String value.      The driver converts this
 
1106
         * to a SQL VARCHAR or LONGVARCHAR value (depending on the arguments
 
1107
         * size relative to the driver's limits on VARCHARs) when it sends it
 
1108
         * to the database.
 
1109
         *
 
1110
         * @param parameterIndex the first parameter is 1...
 
1111
         * @param x the parameter value
 
1112
         * @exception SQLException if a database access error occurs
 
1113
         */
 
1114
        public void setString(int parameterIndex, String x) throws SQLException
 
1115
        {
 
1116
                setString(parameterIndex, x, PG_TEXT);
 
1117
        }
 
1118
 
 
1119
        public void setString(int parameterIndex, String x, String type) throws SQLException
 
1120
        {
 
1121
                // if the passed string is null, then set this column to null
 
1122
                if (x == null)
 
1123
                        setNull(parameterIndex, Types.VARCHAR);
 
1124
                else
 
1125
                {
 
1126
                        // use the shared buffer object. Should never clash but this makes
 
1127
                        // us thread safe!
 
1128
                        synchronized (sbuf)
 
1129
                        {
 
1130
                                sbuf.setLength(0);
 
1131
                                sbuf.ensureCapacity(2 + x.length() + (int)(x.length() / 10));
 
1132
                                sbuf.append('\'');
 
1133
                                escapeString(x, sbuf);
 
1134
                                sbuf.append('\'');
 
1135
                                bind(parameterIndex, sbuf.toString(), type);
 
1136
                        }
 
1137
                }
 
1138
        }
 
1139
 
 
1140
    private void escapeString(String p_input, StringBuffer p_output) {
 
1141
        for (int i = 0 ; i < p_input.length() ; ++i)
 
1142
        {
 
1143
            char c = p_input.charAt(i);
 
1144
                        switch (c)
 
1145
                        {
 
1146
                            case '\\':
 
1147
                            case '\'':
 
1148
                                        p_output.append('\\');
 
1149
                                        p_output.append(c);
 
1150
                                        break;
 
1151
                            case '\0':
 
1152
                                        throw new IllegalArgumentException("\\0 not allowed");
 
1153
                                default:
 
1154
                                        p_output.append(c);
 
1155
                        }
 
1156
        }
 
1157
    }
 
1158
 
 
1159
 
 
1160
        /*
 
1161
         * Set a parameter to a Java array of bytes.  The driver converts this
 
1162
         * to a SQL VARBINARY or LONGVARBINARY (depending on the argument's
 
1163
         * size relative to the driver's limits on VARBINARYs) when it sends
 
1164
         * it to the database.
 
1165
         *
 
1166
         * <p>Implementation note:
 
1167
         * <br>With org.postgresql, this creates a large object, and stores the
 
1168
         * objects oid in this column.
 
1169
         *
 
1170
         * @param parameterIndex the first parameter is 1...
 
1171
         * @param x the parameter value
 
1172
         * @exception SQLException if a database access error occurs
 
1173
         */
 
1174
        public void setBytes(int parameterIndex, byte x[]) throws SQLException
 
1175
        {
 
1176
                if (connection.haveMinimumCompatibleVersion("7.2"))
 
1177
                {
 
1178
                        //Version 7.2 supports the bytea datatype for byte arrays
 
1179
                        if (null == x)
 
1180
                        {
 
1181
                                setNull(parameterIndex, Types.VARBINARY);
 
1182
                        }
 
1183
                        else
 
1184
                        {
 
1185
                                setString(parameterIndex, PGbytea.toPGString(x), PG_BYTEA);
 
1186
                        }
 
1187
                }
 
1188
                else
 
1189
                {
 
1190
                        //Version 7.1 and earlier support done as LargeObjects
 
1191
                        LargeObjectManager lom = connection.getLargeObjectAPI();
 
1192
                        int oid = lom.create();
 
1193
                        LargeObject lob = lom.open(oid);
 
1194
                        lob.write(x);
 
1195
                        lob.close();
 
1196
                        setInt(parameterIndex, oid);
 
1197
                }
 
1198
        }
 
1199
 
 
1200
        /*
 
1201
         * Set a parameter to a java.sql.Date value.  The driver converts this
 
1202
         * to a SQL DATE value when it sends it to the database.
 
1203
         *
 
1204
         * @param parameterIndex the first parameter is 1...
 
1205
         * @param x the parameter value
 
1206
         * @exception SQLException if a database access error occurs
 
1207
         */
 
1208
        public void setDate(int parameterIndex, java.sql.Date x) throws SQLException
 
1209
        {
 
1210
                if (null == x)
 
1211
                {
 
1212
                        setNull(parameterIndex, Types.DATE);
 
1213
                }
 
1214
                else
 
1215
                {
 
1216
                        bind(parameterIndex, "'" + x.toString() + "'", PG_DATE);
 
1217
                }
 
1218
        }
 
1219
 
 
1220
        /*
 
1221
         * Set a parameter to a java.sql.Time value.  The driver converts
 
1222
         * this to a SQL TIME value when it sends it to the database.
 
1223
         *
 
1224
         * @param parameterIndex the first parameter is 1...));
 
1225
         * @param x the parameter value
 
1226
         * @exception SQLException if a database access error occurs
 
1227
         */
 
1228
        public void setTime(int parameterIndex, Time x) throws SQLException
 
1229
        {
 
1230
                if (null == x)
 
1231
                {
 
1232
                        setNull(parameterIndex, Types.TIME);
 
1233
                }
 
1234
                else
 
1235
                {
 
1236
                        bind(parameterIndex, "'" + x.toString() + "'", PG_TIME);
 
1237
                }
 
1238
        }
 
1239
 
 
1240
        /*
 
1241
         * Set a parameter to a java.sql.Timestamp value.  The driver converts
 
1242
         * this to a SQL TIMESTAMP value when it sends it to the database.
 
1243
         *
 
1244
         * @param parameterIndex the first parameter is 1...
 
1245
         * @param x the parameter value
 
1246
         * @exception SQLException if a database access error occurs
 
1247
         */
 
1248
        public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException
 
1249
        {
 
1250
                if (null == x)
 
1251
                {
 
1252
                        setNull(parameterIndex, Types.TIMESTAMP);
 
1253
                }
 
1254
                else
 
1255
                {
 
1256
                        // Use the shared StringBuffer
 
1257
                        synchronized (sbuf)
 
1258
                        {
 
1259
                                sbuf.setLength(0);
 
1260
                                sbuf.ensureCapacity(32);
 
1261
                                sbuf.append("'");
 
1262
                                //format the timestamp
 
1263
                                //we do our own formating so that we can get a format
 
1264
                                //that works with both timestamp with time zone and
 
1265
                                //timestamp without time zone datatypes.
 
1266
                                //The format is '2002-01-01 23:59:59.123456-0130'
 
1267
                                //we need to include the local time and timezone offset
 
1268
                                //so that timestamp without time zone works correctly
 
1269
                                int l_year = x.getYear() + 1900;
 
1270
 
 
1271
                                // always use four digits for the year so very
 
1272
                                // early years, like 2, don't get misinterpreted
 
1273
                                int l_yearlen = String.valueOf(l_year).length();
 
1274
                                for (int i=4; i>l_yearlen; i--) {
 
1275
                                        sbuf.append("0");
 
1276
                                }
 
1277
 
 
1278
                                sbuf.append(l_year);
 
1279
                                sbuf.append('-');
 
1280
                                int l_month = x.getMonth() + 1;
 
1281
                                if (l_month < 10)
 
1282
                                        sbuf.append('0');
 
1283
                                sbuf.append(l_month);
 
1284
                                sbuf.append('-');
 
1285
                                int l_day = x.getDate();
 
1286
                                if (l_day < 10)
 
1287
                                        sbuf.append('0');
 
1288
                                sbuf.append(l_day);
 
1289
                                sbuf.append(' ');
 
1290
                                int l_hours = x.getHours();
 
1291
                                if (l_hours < 10)
 
1292
                                        sbuf.append('0');
 
1293
                                sbuf.append(l_hours);
 
1294
                                sbuf.append(':');
 
1295
                                int l_minutes = x.getMinutes();
 
1296
                                if (l_minutes < 10)
 
1297
                                        sbuf.append('0');
 
1298
                                sbuf.append(l_minutes);
 
1299
                                sbuf.append(':');
 
1300
                                int l_seconds = x.getSeconds();
 
1301
                                if (l_seconds < 10)
 
1302
                                        sbuf.append('0');
 
1303
                                sbuf.append(l_seconds);
 
1304
                                // Make decimal from nanos.
 
1305
                                char[] l_decimal = {'0', '0', '0', '0', '0', '0', '0', '0', '0'};
 
1306
                                char[] l_nanos = Integer.toString(x.getNanos()).toCharArray();
 
1307
                                System.arraycopy(l_nanos, 0, l_decimal, l_decimal.length - l_nanos.length, l_nanos.length);
 
1308
                                sbuf.append('.');
 
1309
                                if (connection.haveMinimumServerVersion("7.2"))
 
1310
                                {
 
1311
                                        sbuf.append(l_decimal, 0, 6);
 
1312
                                }
 
1313
                                else
 
1314
                                {
 
1315
                                        // Because 7.1 include bug that "hh:mm:59.999" becomes "hh:mm:60.00".
 
1316
                                        sbuf.append(l_decimal, 0, 2);
 
1317
                                }
 
1318
                                //add timezone offset
 
1319
                                int l_offset = -(x.getTimezoneOffset());
 
1320
                                int l_houros = l_offset / 60;
 
1321
                                if (l_houros >= 0)
 
1322
                                {
 
1323
                                        sbuf.append('+');
 
1324
                                }
 
1325
                                else
 
1326
                                {
 
1327
                                        sbuf.append('-');
 
1328
                                }
 
1329
                                if (l_houros > -10 && l_houros < 10)
 
1330
                                        sbuf.append('0');
 
1331
                                if (l_houros >= 0)
 
1332
                                {
 
1333
                                        sbuf.append(l_houros);
 
1334
                                }
 
1335
                                else
 
1336
                                {
 
1337
                                        sbuf.append(-l_houros);
 
1338
                                }
 
1339
                                int l_minos = l_offset - (l_houros * 60);
 
1340
                                if (l_minos != 0)
 
1341
                                {
 
1342
                                        if (l_minos > -10 && l_minos < 10)
 
1343
                                                sbuf.append('0');
 
1344
                                        if (l_minos >= 0)
 
1345
                                        {
 
1346
                                                sbuf.append(l_minos);
 
1347
                                        }
 
1348
                                        else
 
1349
                                        {
 
1350
                                                sbuf.append(-l_minos);
 
1351
                                        }
 
1352
                                }
 
1353
                                sbuf.append("'");
 
1354
                                bind(parameterIndex, sbuf.toString(), PG_TIMESTAMPTZ);
 
1355
                        }
 
1356
 
 
1357
                }
 
1358
        }
 
1359
 
 
1360
        private void setCharacterStreamPost71(int parameterIndex, InputStream x, int length, String encoding) throws SQLException
 
1361
        {
 
1362
 
 
1363
                if (x == null)
 
1364
                {
 
1365
                        setNull(parameterIndex, Types.VARCHAR);
 
1366
                                return;
 
1367
                }
 
1368
 
 
1369
                //Version 7.2 supports AsciiStream for all PG text types (char, varchar, text)
 
1370
                //As the spec/javadoc for this method indicate this is to be used for
 
1371
                //large String values (i.e. LONGVARCHAR)  PG doesn't have a separate
 
1372
                //long varchar datatype, but with toast all text datatypes are capable of
 
1373
                //handling very large values.  Thus the implementation ends up calling
 
1374
                //setString() since there is no current way to stream the value to the server
 
1375
                try
 
1376
                {
 
1377
                        InputStreamReader l_inStream = new InputStreamReader(x, encoding);
 
1378
                        char[] l_chars = new char[length];
 
1379
                        int l_charsRead = 0;
 
1380
                        while (true)
 
1381
                        {
 
1382
                                int n = l_inStream.read(l_chars, l_charsRead, length - l_charsRead);
 
1383
                                if (n == -1)
 
1384
                                        break;
 
1385
 
 
1386
                                l_charsRead += n;
 
1387
 
 
1388
                                if (l_charsRead == length)
 
1389
                                        break;
 
1390
                        }
 
1391
 
 
1392
                        setString(parameterIndex, new String(l_chars, 0, l_charsRead), PG_TEXT);
 
1393
                }
 
1394
                catch (UnsupportedEncodingException l_uee)
 
1395
                {
 
1396
                        throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, l_uee);
 
1397
                }
 
1398
                catch (IOException l_ioe)
 
1399
                {
 
1400
                        throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, l_ioe);
 
1401
                }
 
1402
        }
 
1403
 
 
1404
        /*
 
1405
         * When a very large ASCII value is input to a LONGVARCHAR parameter,
 
1406
         * it may be more practical to send it via a java.io.InputStream.
 
1407
         * JDBC will read the data from the stream as needed, until it reaches
 
1408
         * end-of-file.  The JDBC driver will do any necessary conversion from
 
1409
         * ASCII to the database char format.
 
1410
         *
 
1411
         * <P><B>Note:</B> This stream object can either be a standard Java
 
1412
         * stream object or your own subclass that implements the standard
 
1413
         * interface.
 
1414
         *
 
1415
         * @param parameterIndex the first parameter is 1...
 
1416
         * @param x the parameter value
 
1417
         * @param length the number of bytes in the stream
 
1418
         * @exception SQLException if a database access error occurs
 
1419
         */
 
1420
        public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException
 
1421
        {
 
1422
                if (connection.haveMinimumCompatibleVersion("7.2"))
 
1423
                {
 
1424
                        setCharacterStreamPost71(parameterIndex, x, length, "ASCII");
 
1425
                }
 
1426
                else
 
1427
                {
 
1428
                        //Version 7.1 supported only LargeObjects by treating everything
 
1429
                        //as binary data
 
1430
                        setBinaryStream(parameterIndex, x, length);
 
1431
                }
 
1432
        }
 
1433
 
 
1434
        /*
 
1435
         * When a very large Unicode value is input to a LONGVARCHAR parameter,
 
1436
         * it may be more practical to send it via a java.io.InputStream.
 
1437
         * JDBC will read the data from the stream as needed, until it reaches
 
1438
         * end-of-file.  The JDBC driver will do any necessary conversion from
 
1439
         * UNICODE to the database char format.
 
1440
         *
 
1441
         * <P><B>Note:</B> This stream object can either be a standard Java
 
1442
         * stream object or your own subclass that implements the standard
 
1443
         * interface.
 
1444
         *
 
1445
         * @param parameterIndex the first parameter is 1...
 
1446
         * @param x the parameter value
 
1447
         * @exception SQLException if a database access error occurs
 
1448
         */
 
1449
        public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException
 
1450
        {
 
1451
                if (connection.haveMinimumCompatibleVersion("7.2"))
 
1452
                {
 
1453
                        setCharacterStreamPost71(parameterIndex, x, length, "UTF-8");
 
1454
                }
 
1455
                else
 
1456
                {
 
1457
                        //Version 7.1 supported only LargeObjects by treating everything
 
1458
                        //as binary data
 
1459
                        setBinaryStream(parameterIndex, x, length);
 
1460
                }
 
1461
        }
 
1462
 
 
1463
        /*
 
1464
         * When a very large binary value is input to a LONGVARBINARY parameter,
 
1465
         * it may be more practical to send it via a java.io.InputStream.
 
1466
         * JDBC will read the data from the stream as needed, until it reaches
 
1467
         * end-of-file.
 
1468
         *
 
1469
         * <P><B>Note:</B> This stream object can either be a standard Java
 
1470
         * stream object or your own subclass that implements the standard
 
1471
         * interface.
 
1472
         *
 
1473
         * @param parameterIndex the first parameter is 1...
 
1474
         * @param x the parameter value
 
1475
         * @exception SQLException if a database access error occurs
 
1476
         */
 
1477
        public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException
 
1478
        {
 
1479
                if (connection.haveMinimumCompatibleVersion("7.2"))
 
1480
                {
 
1481
                        if (x == null)
 
1482
                        {
 
1483
                                setNull(parameterIndex, Types.VARBINARY);
 
1484
                                return;
 
1485
                        }
 
1486
 
 
1487
                        //Version 7.2 supports BinaryStream for for the PG bytea type
 
1488
                        //As the spec/javadoc for this method indicate this is to be used for
 
1489
                        //large binary values (i.e. LONGVARBINARY)      PG doesn't have a separate
 
1490
                        //long binary datatype, but with toast the bytea datatype is capable of
 
1491
                        //handling very large values.  Thus the implementation ends up calling
 
1492
                        //setBytes() since there is no current way to stream the value to the server
 
1493
                        byte[] l_bytes = new byte[length];
 
1494
                        int l_bytesRead = 0;
 
1495
                        try
 
1496
                        {
 
1497
                                while (true)
 
1498
                                {
 
1499
                                        int n = x.read(l_bytes, l_bytesRead, length - l_bytesRead);
 
1500
                                        if (n == -1)
 
1501
                                                break;
 
1502
 
 
1503
                                        l_bytesRead += n;
 
1504
 
 
1505
                                        if (l_bytesRead == length)
 
1506
                                                break;
 
1507
 
 
1508
                                }
 
1509
                        }
 
1510
                        catch (IOException l_ioe)
 
1511
                        {
 
1512
                                throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, l_ioe);
 
1513
                        }
 
1514
                        if (l_bytesRead == length)
 
1515
                        {
 
1516
                                setBytes(parameterIndex, l_bytes);
 
1517
                        }
 
1518
                        else
 
1519
                        {
 
1520
                                //the stream contained less data than they said
 
1521
                                byte[] l_bytes2 = new byte[l_bytesRead];
 
1522
                                System.arraycopy(l_bytes, 0, l_bytes2, 0, l_bytesRead);
 
1523
                                setBytes(parameterIndex, l_bytes2);
 
1524
                        }
 
1525
                }
 
1526
                else
 
1527
                {
 
1528
                        //Version 7.1 only supported streams for LargeObjects
 
1529
                        //but the jdbc spec indicates that streams should be
 
1530
                        //available for LONGVARBINARY instead
 
1531
                        LargeObjectManager lom = connection.getLargeObjectAPI();
 
1532
                        int oid = lom.create();
 
1533
                        LargeObject lob = lom.open(oid);
 
1534
                        OutputStream los = lob.getOutputStream();
 
1535
                        try
 
1536
                        {
 
1537
                                // could be buffered, but then the OutputStream returned by LargeObject
 
1538
                                // is buffered internally anyhow, so there would be no performance
 
1539
                                // boost gained, if anything it would be worse!
 
1540
                                int c = x.read();
 
1541
                                int p = 0;
 
1542
                                while (c > -1 && p < length)
 
1543
                                {
 
1544
                                        los.write(c);
 
1545
                                        c = x.read();
 
1546
                                        p++;
 
1547
                                }
 
1548
                                los.close();
 
1549
                        }
 
1550
                        catch (IOException se)
 
1551
                        {
 
1552
                                throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, se);
 
1553
                        }
 
1554
                        // lob is closed by the stream so don't call lob.close()
 
1555
                        setInt(parameterIndex, oid);
 
1556
                }
 
1557
        }
 
1558
 
 
1559
 
 
1560
        /*
 
1561
         * In general, parameter values remain in force for repeated used of a
 
1562
         * Statement.  Setting a parameter value automatically clears its
 
1563
         * previous value.      However, in coms cases, it is useful to immediately
 
1564
         * release the resources used by the current parameter values; this
 
1565
         * can be done by calling clearParameters
 
1566
         *
 
1567
         * @exception SQLException if a database access error occurs
 
1568
         */
 
1569
        public void clearParameters() throws SQLException
 
1570
        {
 
1571
                int i;
 
1572
 
 
1573
                for (i = 0 ; i < m_binds.length ; i++)
 
1574
                {
 
1575
                        m_binds[i] = null;
 
1576
                        m_bindTypes[i] = null;
 
1577
                }
 
1578
        }
 
1579
 
 
1580
        // Helper method that extracts numeric values from an arbitary Object.
 
1581
        private String numericValueOf(Object x)
 
1582
        {
 
1583
                if (x instanceof Boolean)
 
1584
                        return ((Boolean)x).booleanValue() ? "1" :"0";
 
1585
                else if (x instanceof Integer || x instanceof Long || 
 
1586
                                 x instanceof Double || x instanceof Short ||
 
1587
                                 x instanceof Number || x instanceof Float)
 
1588
                        return x.toString();
 
1589
                else
 
1590
                        //ensure the value is a valid numeric value to avoid
 
1591
                        //sql injection attacks
 
1592
                        return new BigDecimal(x.toString()).toString();
 
1593
        }               
 
1594
 
 
1595
        /*
 
1596
         * Set the value of a parameter using an object; use the java.lang
 
1597
         * equivalent objects for integral values.
 
1598
         *
 
1599
         * <P>The given Java object will be converted to the targetSqlType before
 
1600
         * being sent to the database.
 
1601
         *
 
1602
         * <P>note that this method may be used to pass database-specific
 
1603
         * abstract data types.  This is done by using a Driver-specific
 
1604
         * Java type and using a targetSqlType of java.sql.Types.OTHER
 
1605
         *
 
1606
         * @param parameterIndex the first parameter is 1...
 
1607
         * @param x the object containing the input parameter value
 
1608
         * @param targetSqlType The SQL type to be send to the database
 
1609
         * @param scale For java.sql.Types.DECIMAL or java.sql.Types.NUMERIC
 
1610
         *               *      types this is the number of digits after the decimal.  For
 
1611
         *               *      all other types this value will be ignored.
 
1612
         * @exception SQLException if a database access error occurs
 
1613
         */
 
1614
        public void setObject(int parameterIndex, Object x, int targetSqlType, int scale) throws SQLException
 
1615
        {
 
1616
                if (x == null)
 
1617
                {
 
1618
                        setNull(parameterIndex, targetSqlType);
 
1619
                        return ;
 
1620
                }
 
1621
                switch (targetSqlType)
 
1622
                {
 
1623
                        case Types.INTEGER:
 
1624
                                bind(parameterIndex, numericValueOf(x), PG_INTEGER);
 
1625
                                break;
 
1626
                        case Types.TINYINT:
 
1627
                        case Types.SMALLINT:
 
1628
                                bind(parameterIndex, numericValueOf(x), PG_INT2);
 
1629
                                break;
 
1630
                        case Types.BIGINT:
 
1631
                                bind(parameterIndex, numericValueOf(x), PG_INT8);
 
1632
                                break;
 
1633
                        case Types.REAL:
 
1634
                        case Types.FLOAT:
 
1635
                                bind(parameterIndex, numericValueOf(x), PG_FLOAT);
 
1636
                                break;
 
1637
                        case Types.DOUBLE:
 
1638
                                bind(parameterIndex, numericValueOf(x), PG_DOUBLE);
 
1639
                                break;
 
1640
                        case Types.DECIMAL:
 
1641
                        case Types.NUMERIC:
 
1642
                                bind(parameterIndex, numericValueOf(x), PG_NUMERIC);
 
1643
                                break;
 
1644
                        case Types.CHAR:
 
1645
                        case Types.VARCHAR:
 
1646
                        case Types.LONGVARCHAR:
 
1647
                                setString(parameterIndex, x.toString());
 
1648
                                break;
 
1649
                        case Types.DATE:
 
1650
                                if (x instanceof java.sql.Date) 
 
1651
                                        setDate(parameterIndex, (java.sql.Date)x);
 
1652
                                else
 
1653
                                {
 
1654
                                        java.sql.Date tmpd = (x instanceof java.util.Date) ? new java.sql.Date(((java.util.Date)x).getTime()) : dateFromString(x.toString());
 
1655
                                        setDate(parameterIndex, tmpd);
 
1656
                                }
 
1657
                                break;
 
1658
                        case Types.TIME:
 
1659
                                if (x instanceof java.sql.Time)
 
1660
                                        setTime(parameterIndex, (java.sql.Time)x);
 
1661
                                else
 
1662
                                {
 
1663
                                        java.sql.Time tmpt = (x instanceof java.util.Date) ? new java.sql.Time(((java.util.Date)x).getTime()) : timeFromString(x.toString());
 
1664
                                        setTime(parameterIndex, tmpt);
 
1665
                                }
 
1666
                                break;
 
1667
                        case Types.TIMESTAMP:
 
1668
                                if (x instanceof java.sql.Timestamp)
 
1669
                                        setTimestamp(parameterIndex ,(java.sql.Timestamp)x);
 
1670
                                else
 
1671
                                {
 
1672
                                        java.sql.Timestamp tmpts = (x instanceof java.util.Date) ? new java.sql.Timestamp(((java.util.Date)x).getTime()) : timestampFromString(x.toString());
 
1673
                                        setTimestamp(parameterIndex, tmpts);
 
1674
                                }
 
1675
                                break;
 
1676
                        case Types.BIT:
 
1677
                                if (x instanceof Boolean)
 
1678
                                {
 
1679
                                        bind(parameterIndex, ((Boolean)x).booleanValue() ? "'1'" : "'0'", PG_BOOLEAN);
 
1680
                                }
 
1681
                                else if (x instanceof String)
 
1682
                                {
 
1683
                                        bind(parameterIndex, Boolean.valueOf(x.toString()).booleanValue() ? "'1'" : "'0'", PG_BOOLEAN);
 
1684
                                }
 
1685
                                else if (x instanceof Number)
 
1686
                                {
 
1687
                                        bind(parameterIndex, ((Number)x).intValue()!=0 ? "'1'" : "'0'", PG_BOOLEAN);
 
1688
                                }
 
1689
                                else
 
1690
                                {
 
1691
                                        throw new PSQLException("postgresql.prep.type", PSQLState.INVALID_PARAMETER_TYPE);
 
1692
                                }
 
1693
                                break;
 
1694
                        case Types.BINARY:
 
1695
                        case Types.VARBINARY:
 
1696
                        case Types.LONGVARBINARY:
 
1697
                                setObject(parameterIndex, x);
 
1698
                                break;
 
1699
                        case Types.OTHER:
 
1700
                                if (x instanceof PGobject)
 
1701
                                        setString(parameterIndex, ((PGobject)x).getValue(), ((PGobject)x).getType());
 
1702
                                else
 
1703
                                        throw new PSQLException("postgresql.prep.type", PSQLState.INVALID_PARAMETER_TYPE);
 
1704
                                break;
 
1705
                        default:
 
1706
                                throw new PSQLException("postgresql.prep.type", PSQLState.INVALID_PARAMETER_TYPE);
 
1707
                }
 
1708
        }
 
1709
 
 
1710
        public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException
 
1711
        {
 
1712
                setObject(parameterIndex, x, targetSqlType, 0);
 
1713
        }
 
1714
 
 
1715
        /*
 
1716
         * This stores an Object into a parameter.
 
1717
         */
 
1718
        public void setObject(int parameterIndex, Object x) throws SQLException
 
1719
        {
 
1720
                if (x == null)
 
1721
                {
 
1722
                        setNull(parameterIndex, Types.OTHER);
 
1723
                        return ;
 
1724
                }
 
1725
                if (x instanceof String)
 
1726
                        setString(parameterIndex, (String)x);
 
1727
                else if (x instanceof BigDecimal)
 
1728
                        setBigDecimal(parameterIndex, (BigDecimal)x);
 
1729
                else if (x instanceof Short)
 
1730
                        setShort(parameterIndex, ((Short)x).shortValue());
 
1731
                else if (x instanceof Integer)
 
1732
                        setInt(parameterIndex, ((Integer)x).intValue());
 
1733
                else if (x instanceof Long)
 
1734
                        setLong(parameterIndex, ((Long)x).longValue());
 
1735
                else if (x instanceof Float)
 
1736
                        setFloat(parameterIndex, ((Float)x).floatValue());
 
1737
                else if (x instanceof Double)
 
1738
                        setDouble(parameterIndex, ((Double)x).doubleValue());
 
1739
                else if (x instanceof byte[])
 
1740
                        setBytes(parameterIndex, (byte[])x);
 
1741
                else if (x instanceof java.sql.Date)
 
1742
                        setDate(parameterIndex, (java.sql.Date)x);
 
1743
                else if (x instanceof Time)
 
1744
                        setTime(parameterIndex, (Time)x);
 
1745
                else if (x instanceof Timestamp)
 
1746
                        setTimestamp(parameterIndex, (Timestamp)x);
 
1747
                else if (x instanceof Boolean)
 
1748
                        setBoolean(parameterIndex, ((Boolean)x).booleanValue());
 
1749
                else if (x instanceof PGobject)
 
1750
                        setString(parameterIndex, ((PGobject)x).getValue(), PG_TEXT);
 
1751
                else
 
1752
                        // Try to store as a string in database
 
1753
                        setString(parameterIndex, x.toString(), PG_TEXT);
 
1754
        }
 
1755
 
 
1756
        /*
 
1757
         * Before executing a stored procedure call you must explicitly
 
1758
         * call registerOutParameter to register the java.sql.Type of each
 
1759
         * out parameter.
 
1760
         *
 
1761
         * <p>Note: When reading the value of an out parameter, you must use
 
1762
         * the getXXX method whose Java type XXX corresponds to the
 
1763
         * parameter's registered SQL type.
 
1764
         *
 
1765
         * ONLY 1 RETURN PARAMETER if {?= call ..} syntax is used
 
1766
         *
 
1767
         * @param parameterIndex the first parameter is 1, the second is 2,...
 
1768
         * @param sqlType SQL type code defined by java.sql.Types; for
 
1769
         * parameters of type Numeric or Decimal use the version of
 
1770
         * registerOutParameter that accepts a scale value
 
1771
         * @exception SQLException if a database-access error occurs.
 
1772
         */
 
1773
        public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException
 
1774
        {
 
1775
                if (parameterIndex != 1)
 
1776
                        throw new PSQLException ("postgresql.call.noinout", PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL);
 
1777
                if (!isFunction)
 
1778
                        throw new PSQLException ("postgresql.call.procasfunc", PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL,originalSql);
 
1779
 
 
1780
                // functionReturnType contains the user supplied value to check
 
1781
                // testReturn contains a modified version to make it easier to
 
1782
                // check the getXXX methods..
 
1783
                functionReturnType = sqlType;
 
1784
                testReturn = sqlType;
 
1785
                if (functionReturnType == Types.CHAR ||
 
1786
                                functionReturnType == Types.LONGVARCHAR)
 
1787
                        testReturn = Types.VARCHAR;
 
1788
                else if (functionReturnType == Types.FLOAT)
 
1789
                        testReturn = Types.REAL; // changes to streamline later error checking
 
1790
                returnTypeSet = true;
 
1791
        }
 
1792
 
 
1793
        /*
 
1794
         * You must also specify the scale for numeric/decimal types:
 
1795
         *
 
1796
         * <p>Note: When reading the value of an out parameter, you must use
 
1797
         * the getXXX method whose Java type XXX corresponds to the
 
1798
         * parameter's registered SQL type.
 
1799
         *
 
1800
         * @param parameterIndex the first parameter is 1, the second is 2,...
 
1801
         * @param sqlType use either java.sql.Type.NUMERIC or java.sql.Type.DECIMAL
 
1802
         * @param scale a value greater than or equal to zero representing the
 
1803
         * desired number of digits to the right of the decimal point
 
1804
         * @exception SQLException if a database-access error occurs.
 
1805
         */
 
1806
        public void registerOutParameter(int parameterIndex, int sqlType,
 
1807
                                                                         int scale) throws SQLException
 
1808
        {
 
1809
                registerOutParameter (parameterIndex, sqlType); // ignore for now..
 
1810
        }
 
1811
 
 
1812
        /*
 
1813
         * An OUT parameter may have the value of SQL NULL; wasNull
 
1814
         * reports whether the last value read has this special value.
 
1815
         *
 
1816
         * <p>Note: You must first call getXXX on a parameter to read its
 
1817
         * value and then call wasNull() to see if the value was SQL NULL.
 
1818
         * @return true if the last parameter read was SQL NULL
 
1819
         * @exception SQLException if a database-access error occurs.
 
1820
         */
 
1821
        public boolean wasNull() throws SQLException
 
1822
        {
 
1823
                // check to see if the last access threw an exception
 
1824
                return (callResult == null);
 
1825
        }
 
1826
 
 
1827
        /*
 
1828
         * Get the value of a CHAR, VARCHAR, or LONGVARCHAR parameter as a
 
1829
         * Java String.
 
1830
         *
 
1831
         * @param parameterIndex the first parameter is 1, the second is 2,...
 
1832
         * @return the parameter value; if the value is SQL NULL, the result is null
 
1833
         * @exception SQLException if a database-access error occurs.
 
1834
         */
 
1835
        public String getString(int parameterIndex) throws SQLException
 
1836
        {
 
1837
                checkIndex (parameterIndex, Types.VARCHAR, "String");
 
1838
                return (String)callResult;
 
1839
        }
 
1840
 
 
1841
 
 
1842
        /*
 
1843
         * Get the value of a BIT parameter as a Java boolean.
 
1844
         *
 
1845
         * @param parameterIndex the first parameter is 1, the second is 2,...
 
1846
         * @return the parameter value; if the value is SQL NULL, the result is false
 
1847
         * @exception SQLException if a database-access error occurs.
 
1848
         */
 
1849
        public boolean getBoolean(int parameterIndex) throws SQLException
 
1850
        {
 
1851
                checkIndex (parameterIndex, Types.BIT, "Boolean");
 
1852
                if (callResult == null)
 
1853
                        return false;
 
1854
                return ((Boolean)callResult).booleanValue ();
 
1855
        }
 
1856
 
 
1857
        /*
 
1858
         * Get the value of a TINYINT parameter as a Java byte.
 
1859
         *
 
1860
         * @param parameterIndex the first parameter is 1, the second is 2,...
 
1861
         * @return the parameter value; if the value is SQL NULL, the result is 0
 
1862
         * @exception SQLException if a database-access error occurs.
 
1863
         */
 
1864
        public byte getByte(int parameterIndex) throws SQLException
 
1865
        {
 
1866
                checkIndex (parameterIndex, Types.TINYINT, "Byte");
 
1867
                // We expect the above checkIndex call to fail because
 
1868
                // we don't have an equivalent pg type for TINYINT.
 
1869
                // Possibly "char" (not char(N)), could be used, but
 
1870
                // for the moment we just bail out.
 
1871
                //
 
1872
                throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR);
 
1873
        }
 
1874
 
 
1875
        /*
 
1876
         * Get the value of a SMALLINT parameter as a Java short.
 
1877
         *
 
1878
         * @param parameterIndex the first parameter is 1, the second is 2,...
 
1879
         * @return the parameter value; if the value is SQL NULL, the result is 0
 
1880
         * @exception SQLException if a database-access error occurs.
 
1881
         */
 
1882
        public short getShort(int parameterIndex) throws SQLException
 
1883
        {
 
1884
                checkIndex (parameterIndex, Types.SMALLINT, "Short");
 
1885
                if (callResult == null)
 
1886
                        return 0;
 
1887
                return (short)((Short)callResult).intValue ();
 
1888
        }
 
1889
 
 
1890
 
 
1891
        /*
 
1892
         * Get the value of an INTEGER parameter as a Java int.
 
1893
         *
 
1894
         * @param parameterIndex the first parameter is 1, the second is 2,...
 
1895
         * @return the parameter value; if the value is SQL NULL, the result is 0
 
1896
         * @exception SQLException if a database-access error occurs.
 
1897
         */
 
1898
        public int getInt(int parameterIndex) throws SQLException
 
1899
        {
 
1900
                checkIndex (parameterIndex, Types.INTEGER, "Int");
 
1901
                if (callResult == null)
 
1902
                        return 0;
 
1903
                return ((Integer)callResult).intValue ();
 
1904
        }
 
1905
 
 
1906
        /*
 
1907
         * Get the value of a BIGINT parameter as a Java long.
 
1908
         *
 
1909
         * @param parameterIndex the first parameter is 1, the second is 2,...
 
1910
         * @return the parameter value; if the value is SQL NULL, the result is 0
 
1911
         * @exception SQLException if a database-access error occurs.
 
1912
         */
 
1913
        public long getLong(int parameterIndex) throws SQLException
 
1914
        {
 
1915
                checkIndex (parameterIndex, Types.BIGINT, "Long");
 
1916
                if (callResult == null)
 
1917
                        return 0;
 
1918
                return ((Long)callResult).longValue ();
 
1919
        }
 
1920
 
 
1921
        /*
 
1922
         * Get the value of a FLOAT parameter as a Java float.
 
1923
         *
 
1924
         * @param parameterIndex the first parameter is 1, the second is 2,...
 
1925
         * @return the parameter value; if the value is SQL NULL, the result is 0
 
1926
         * @exception SQLException if a database-access error occurs.
 
1927
         */
 
1928
        public float getFloat(int parameterIndex) throws SQLException
 
1929
        {
 
1930
                checkIndex (parameterIndex, Types.REAL, "Float");
 
1931
                if (callResult == null)
 
1932
                        return 0;
 
1933
                return ((Float)callResult).floatValue ();
 
1934
        }
 
1935
 
 
1936
        /*
 
1937
         * Get the value of a DOUBLE parameter as a Java double.
 
1938
         *
 
1939
         * @param parameterIndex the first parameter is 1, the second is 2,...
 
1940
         * @return the parameter value; if the value is SQL NULL, the result is 0
 
1941
         * @exception SQLException if a database-access error occurs.
 
1942
         */
 
1943
        public double getDouble(int parameterIndex) throws SQLException
 
1944
        {
 
1945
                checkIndex (parameterIndex, Types.DOUBLE, "Double");
 
1946
                if (callResult == null)
 
1947
                        return 0;
 
1948
                return ((Double)callResult).doubleValue ();
 
1949
        }
 
1950
 
 
1951
        /*
 
1952
         * Get the value of a NUMERIC parameter as a java.math.BigDecimal
 
1953
         * object.
 
1954
         *
 
1955
         * @param parameterIndex the first parameter is 1, the second is 2,...
 
1956
         * @param scale a value greater than or equal to zero representing the
 
1957
         * desired number of digits to the right of the decimal point
 
1958
         * @return the parameter value; if the value is SQL NULL, the result is null
 
1959
         * @exception SQLException if a database-access error occurs.
 
1960
         * @deprecated in Java2.0
 
1961
         */
 
1962
        public BigDecimal getBigDecimal(int parameterIndex, int scale)
 
1963
        throws SQLException
 
1964
        {
 
1965
                checkIndex (parameterIndex, Types.NUMERIC, "BigDecimal");
 
1966
                return ((BigDecimal)callResult);
 
1967
        }
 
1968
 
 
1969
        /*
 
1970
         * Get the value of a SQL BINARY or VARBINARY parameter as a Java
 
1971
         * byte[]
 
1972
         *
 
1973
         * @param parameterIndex the first parameter is 1, the second is 2,...
 
1974
         * @return the parameter value; if the value is SQL NULL, the result is null
 
1975
         * @exception SQLException if a database-access error occurs.
 
1976
         */
 
1977
        public byte[] getBytes(int parameterIndex) throws SQLException
 
1978
        {
 
1979
                checkIndex (parameterIndex, Types.VARBINARY, Types.BINARY, "Bytes");
 
1980
                return ((byte [])callResult);
 
1981
        }
 
1982
 
 
1983
 
 
1984
        /*
 
1985
         * Get the value of a SQL DATE parameter as a java.sql.Date object
 
1986
         *
 
1987
         * @param parameterIndex the first parameter is 1, the second is 2,...
 
1988
         * @return the parameter value; if the value is SQL NULL, the result is null
 
1989
         * @exception SQLException if a database-access error occurs.
 
1990
         */
 
1991
        public java.sql.Date getDate(int parameterIndex) throws SQLException
 
1992
        {
 
1993
                checkIndex (parameterIndex, Types.DATE, "Date");
 
1994
                return (java.sql.Date)callResult;
 
1995
        }
 
1996
 
 
1997
        /*
 
1998
         * Get the value of a SQL TIME parameter as a java.sql.Time object.
 
1999
         *
 
2000
         * @param parameterIndex the first parameter is 1, the second is 2,...
 
2001
         * @return the parameter value; if the value is SQL NULL, the result is null
 
2002
         * @exception SQLException if a database-access error occurs.
 
2003
         */
 
2004
        public java.sql.Time getTime(int parameterIndex) throws SQLException
 
2005
        {
 
2006
                checkIndex (parameterIndex, Types.TIME, "Time");
 
2007
                return (java.sql.Time)callResult;
 
2008
        }
 
2009
 
 
2010
        /*
 
2011
         * Get the value of a SQL TIMESTAMP parameter as a java.sql.Timestamp object.
 
2012
         *
 
2013
         * @param parameterIndex the first parameter is 1, the second is 2,...
 
2014
         * @return the parameter value; if the value is SQL NULL, the result is null
 
2015
         * @exception SQLException if a database-access error occurs.
 
2016
         */
 
2017
        public java.sql.Timestamp getTimestamp(int parameterIndex)
 
2018
        throws SQLException
 
2019
        {
 
2020
                checkIndex (parameterIndex, Types.TIMESTAMP, "Timestamp");
 
2021
                return (java.sql.Timestamp)callResult;
 
2022
        }
 
2023
 
 
2024
        // getObject returns a Java object for the parameter.
 
2025
        // See the JDBC spec's "Dynamic Programming" chapter for details.
 
2026
        /*
 
2027
         * Get the value of a parameter as a Java object.
 
2028
         *
 
2029
         * <p>This method returns a Java object whose type coresponds to the
 
2030
         * SQL type that was registered for this parameter using
 
2031
         * registerOutParameter.
 
2032
         *
 
2033
         * <P>Note that this method may be used to read datatabase-specific,
 
2034
         * abstract data types. This is done by specifying a targetSqlType
 
2035
         * of java.sql.types.OTHER, which allows the driver to return a
 
2036
         * database-specific Java type.
 
2037
         *
 
2038
         * <p>See the JDBC spec's "Dynamic Programming" chapter for details.
 
2039
         *
 
2040
         * @param parameterIndex the first parameter is 1, the second is 2,...
 
2041
         * @return A java.lang.Object holding the OUT parameter value.
 
2042
         * @exception SQLException if a database-access error occurs.
 
2043
         */
 
2044
        public Object getObject(int parameterIndex)
 
2045
        throws SQLException
 
2046
        {
 
2047
                checkIndex (parameterIndex);
 
2048
                return callResult;
 
2049
        }
 
2050
 
 
2051
        //This method is implemeted in jdbc2
 
2052
        public int getResultSetConcurrency() throws SQLException
 
2053
        {
 
2054
                return 0;
 
2055
        }
 
2056
 
 
2057
        /*
 
2058
         * Returns the SQL statement with the current template values
 
2059
         * substituted.
 
2060
         */
 
2061
        public String toString()
 
2062
        {
 
2063
                if (m_sqlFragments == null)
 
2064
                        return super.toString();
 
2065
 
 
2066
                synchronized (sbuf)
 
2067
                {
 
2068
                        sbuf.setLength(0);
 
2069
                        int i;
 
2070
 
 
2071
                        for (i = 0 ; i < m_binds.length ; ++i)
 
2072
                        {
 
2073
                                sbuf.append (m_sqlFragments[i]);
 
2074
                                if (m_binds[i] == null)
 
2075
                                        sbuf.append( '?' );
 
2076
                                else
 
2077
                                        sbuf.append (m_binds[i]);
 
2078
                        }
 
2079
                        sbuf.append(m_sqlFragments[m_binds.length]);
 
2080
                        return sbuf.toString();
 
2081
                }
 
2082
        }
 
2083
 
 
2084
        /*
 
2085
     * Note if s is a String it should be escaped by the caller to avoid SQL
 
2086
     * injection attacks.  It is not done here for efficency reasons as
 
2087
     * most calls to this method do not require escaping as the source
 
2088
     * of the string is known safe (i.e. Integer.toString())
 
2089
         */
 
2090
        private void bind(int paramIndex, Object s, String type) throws SQLException
 
2091
        {
 
2092
                if (paramIndex < 1 || paramIndex > m_binds.length)
 
2093
                        throw new PSQLException("postgresql.prep.range", PSQLState.INVALID_PARAMETER_VALUE);
 
2094
                if (paramIndex == 1 && isFunction) // need to registerOut instead
 
2095
                        throw new PSQLException ("postgresql.call.funcover");
 
2096
                m_binds[paramIndex - 1] = s;
 
2097
                m_bindTypes[paramIndex - 1] = type;
 
2098
        }
 
2099
 
 
2100
        /**
 
2101
         * this method will turn a string of the form
 
2102
         * {? = call <some_function> (?, [?,..]) }
 
2103
         * into the PostgreSQL format which is
 
2104
         * select <some_function> (?, [?, ...]) as result
 
2105
         * or select * from <some_function> (?, [?, ...]) as result (7.3)
 
2106
         *
 
2107
         */
 
2108
        private String modifyJdbcCall(String p_sql) throws SQLException
 
2109
        {
 
2110
                //Check that this is actually a call which should start with a {
 
2111
        //if not do nothing and treat this as a standard prepared sql
 
2112
                if (!p_sql.trim().startsWith("{")) {
 
2113
                        return p_sql;
 
2114
                }
 
2115
 
 
2116
                // syntax checking is not complete only a few basics :(
 
2117
                originalSql = p_sql; // save for error msgs..
 
2118
                String l_sql = p_sql;
 
2119
                int index = l_sql.indexOf ("="); // is implied func or proc?
 
2120
                boolean isValid = true;
 
2121
                if (index > -1)
 
2122
                {
 
2123
                        isFunction = true;
 
2124
                        isValid = l_sql.indexOf ("?") < index; // ? before =
 
2125
                }
 
2126
                l_sql = l_sql.trim ();
 
2127
                if (l_sql.startsWith ("{") && l_sql.endsWith ("}"))
 
2128
                {
 
2129
                        l_sql = l_sql.substring (1, l_sql.length() - 1);
 
2130
                }
 
2131
                else
 
2132
                        isValid = false;
 
2133
                index = l_sql.indexOf ("call");
 
2134
                if (index == -1 || !isValid)
 
2135
                        throw new PSQLException ("postgresql.call.malformed",PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL,
 
2136
                                                                         new Object[]{l_sql, JDBC_SYNTAX});
 
2137
                l_sql = l_sql.replace ('{', ' '); // replace these characters
 
2138
                l_sql = l_sql.replace ('}', ' ');
 
2139
                l_sql = l_sql.replace (';', ' ');
 
2140
 
 
2141
                // this removes the 'call' string and also puts a hidden '?'
 
2142
                // at the front of the line for functions, this will
 
2143
                // allow the registerOutParameter to work correctly
 
2144
                // because in the source sql there was one more ? for the return
 
2145
                // value that is not needed by the postgres syntax.  But to make
 
2146
                // sure that the parameter numbers are the same as in the original
 
2147
                // sql we add a dummy parameter in this case
 
2148
                l_sql = (isFunction ? "?" : "") + l_sql.substring (index + 4);
 
2149
                if (connection.haveMinimumServerVersion("7.3")) {
 
2150
                        l_sql = "select * from " + l_sql + " as " + RESULT_ALIAS + ";";
 
2151
                } else {
 
2152
                        l_sql = "select " + l_sql + " as " + RESULT_ALIAS + ";";
 
2153
                }
 
2154
                return l_sql;
 
2155
        }
 
2156
 
 
2157
        /** helperfunction for the getXXX calls to check isFunction and index == 1
 
2158
         * Compare BOTH type fields against the return type.
 
2159
         */
 
2160
        protected void checkIndex (int parameterIndex, int type1, int type2, String getName)
 
2161
        throws SQLException
 
2162
        {
 
2163
                checkIndex (parameterIndex);            
 
2164
                if (type1 != this.testReturn && type2 != this.testReturn)
 
2165
                        throw new PSQLException("postgresql.call.wrongget", PSQLState.MOST_SPECIFIC_TYPE_DOES_NOT_MATCH,
 
2166
                                                new Object[]{"java.sql.Types=" + testReturn,
 
2167
                                                             getName,
 
2168
                                                             "java.sql.Types=" + type1});
 
2169
        }
 
2170
 
 
2171
        /** helperfunction for the getXXX calls to check isFunction and index == 1
 
2172
         */
 
2173
        protected void checkIndex (int parameterIndex, int type, String getName)
 
2174
        throws SQLException
 
2175
        {
 
2176
                checkIndex (parameterIndex);
 
2177
                if (type != this.testReturn)
 
2178
                        throw new PSQLException("postgresql.call.wrongget", PSQLState.MOST_SPECIFIC_TYPE_DOES_NOT_MATCH,
 
2179
                                                new Object[]{"java.sql.Types=" + testReturn,
 
2180
                                                             getName,
 
2181
                                                             "java.sql.Types=" + type});
 
2182
        }
 
2183
 
 
2184
        /** helperfunction for the getXXX calls to check isFunction and index == 1
 
2185
         * @param parameterIndex index of getXXX (index)
 
2186
         * check to make sure is a function and index == 1
 
2187
         */
 
2188
        private void checkIndex (int parameterIndex) throws SQLException
 
2189
        {
 
2190
                if (!isFunction)
 
2191
                        throw new PSQLException("postgresql.call.noreturntype", PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL);
 
2192
                if (parameterIndex != 1)
 
2193
                        throw new PSQLException("postgresql.call.noinout", PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL);
 
2194
        }
 
2195
 
 
2196
 
 
2197
 
 
2198
    public void setUseServerPrepare(boolean flag) throws SQLException {
 
2199
        //Server side prepared statements were introduced in 7.3
 
2200
        if (connection.haveMinimumServerVersion("7.3")) {
 
2201
                        if (m_useServerPrepare != flag)
 
2202
                                deallocateQuery();
 
2203
                        m_useServerPrepare = flag;
 
2204
                } else {
 
2205
                        //This is a pre 7.3 server so no op this method
 
2206
                        //which means we will never turn on the flag to use server
 
2207
                        //prepared statements and thus regular processing will continue
 
2208
                }
 
2209
        }
 
2210
 
 
2211
        public boolean isUseServerPrepare()
 
2212
        {
 
2213
                return m_useServerPrepare;
 
2214
        }
 
2215
 
 
2216
        private java.sql.Date dateFromString (String s) throws SQLException
 
2217
        {
 
2218
                int timezone = 0;
 
2219
                long millis = 0;
 
2220
                long localoffset = 0;
 
2221
                int timezoneLocation = (s.indexOf('+') == -1) ? s.lastIndexOf("-") : s.indexOf('+');
 
2222
                //if the last index of '-' or '+' is past 8. we are guaranteed that it is a timezone marker
 
2223
                //shortest = yyyy-m-d
 
2224
                //longest = yyyy-mm-dd
 
2225
                try
 
2226
                {
 
2227
                        timezone = (timezoneLocation>7) ? timezoneLocation : s.length();
 
2228
                        millis = java.sql.Date.valueOf(s.substring(0,timezone)).getTime();
 
2229
                }
 
2230
                catch (Exception e)
 
2231
                {
 
2232
                        throw new PSQLException("postgresql.format.baddate", PSQLState.BAD_DATETIME_FORMAT, s , "yyyy-MM-dd[-tz]");
 
2233
                }
 
2234
                timezone = 0;
 
2235
                if (timezoneLocation>7 && timezoneLocation+3 == s.length())
 
2236
                {
 
2237
                        timezone = Integer.parseInt(s.substring(timezoneLocation+1,s.length()));
 
2238
                        localoffset = java.util.Calendar.getInstance().getTimeZone().getRawOffset();
 
2239
                        if (java.util.Calendar.getInstance().getTimeZone().inDaylightTime(new java.sql.Date(millis)))
 
2240
                                localoffset += 60*60*1000;
 
2241
                        if (s.charAt(timezoneLocation)=='+')
 
2242
                                timezone*=-1;
 
2243
                }
 
2244
                millis = millis + timezone*60*60*1000 + localoffset;
 
2245
                return new java.sql.Date(millis);
 
2246
        }
 
2247
        
 
2248
        private java.sql.Time timeFromString (String s) throws SQLException
 
2249
        {
 
2250
                int timezone = 0;
 
2251
                long millis = 0;
 
2252
                long localoffset = 0;
 
2253
                int timezoneLocation = (s.indexOf('+') == -1) ? s.lastIndexOf("-") : s.indexOf('+');
 
2254
                //if the index of the last '-' or '+' is greater than 0 that means this time has a timezone.
 
2255
                //everything earlier than that position, we treat as the time and parse it as such.
 
2256
                try
 
2257
                {
 
2258
                        timezone = (timezoneLocation==-1) ? s.length() : timezoneLocation;      
 
2259
                        millis = java.sql.Time.valueOf(s.substring(0,timezone)).getTime();
 
2260
                }
 
2261
                catch (Exception e)
 
2262
                {
 
2263
                        throw new PSQLException("postgresql.format.badtime", PSQLState.BAD_DATETIME_FORMAT, s, "HH:mm:ss[-tz]");
 
2264
                }
 
2265
                timezone = 0;
 
2266
                if (timezoneLocation != -1 && timezoneLocation+3 == s.length())
 
2267
                {
 
2268
                        timezone = Integer.parseInt(s.substring(timezoneLocation+1,s.length()));
 
2269
                        localoffset = java.util.Calendar.getInstance().getTimeZone().getRawOffset();
 
2270
                        if (java.util.Calendar.getInstance().getTimeZone().inDaylightTime(new java.sql.Date(millis)))
 
2271
                                localoffset += 60*60*1000;
 
2272
                        if (s.charAt(timezoneLocation)=='+')
 
2273
                                timezone*=-1;
 
2274
                }
 
2275
                millis = millis + timezone*60*60*1000 + localoffset;
 
2276
                return new java.sql.Time(millis);
 
2277
        }
 
2278
        
 
2279
        private java.sql.Timestamp timestampFromString (String s) throws SQLException
 
2280
        {
 
2281
                int timezone = 0;
 
2282
                long millis = 0;
 
2283
                long localoffset = 0;
 
2284
                int nanosVal = 0;
 
2285
                int timezoneLocation = (s.indexOf('+') == -1) ? s.lastIndexOf("-") : s.indexOf('+');
 
2286
                int nanospos = s.indexOf(".");
 
2287
                //if there is a '.', that means there are nanos info, and we take the timestamp up to that point
 
2288
                //if not, then we check to see if the last +/- (to indicate a timezone) is greater than 8
 
2289
                //8 is because the shortest date, will have last '-' at position 7. e.g yyyy-x-x
 
2290
                try
 
2291
                {
 
2292
                        if (nanospos != -1)
 
2293
                                timezone = nanospos;
 
2294
                        else if (timezoneLocation > 8)
 
2295
                                timezone = timezoneLocation;
 
2296
                        else 
 
2297
                                timezone = s.length();
 
2298
                        millis = java.sql.Timestamp.valueOf(s.substring(0,timezone)).getTime();
 
2299
                }
 
2300
                catch (Exception e)
 
2301
                {
 
2302
                        throw new PSQLException("postgresql.format.badtimestamp", PSQLState.BAD_DATETIME_FORMAT, s, "yyyy-MM-dd HH:mm:ss[.xxxxxx][-tz]");
 
2303
                }
 
2304
                timezone = 0;
 
2305
                if (nanospos != -1)
 
2306
                {
 
2307
                        int tmploc = (timezoneLocation > 8) ? timezoneLocation : s.length();
 
2308
                        nanosVal = Integer.parseInt(s.substring(nanospos+1,tmploc));
 
2309
                        int diff = 8-((tmploc-1)-(nanospos+1));
 
2310
                        for (int i=0;i<diff;i++)
 
2311
                                nanosVal*=10;
 
2312
                }
 
2313
                if (timezoneLocation>8 && timezoneLocation+3 == s.length())
 
2314
                {
 
2315
                        timezone = Integer.parseInt(s.substring(timezoneLocation+1,s.length()));
 
2316
                        localoffset = java.util.Calendar.getInstance().getTimeZone().getRawOffset();
 
2317
                        if (java.util.Calendar.getInstance().getTimeZone().inDaylightTime(new java.sql.Date(millis)))
 
2318
                                localoffset += 60*60*1000;
 
2319
                        if (s.charAt(timezoneLocation)=='+')
 
2320
                                timezone*=-1;
 
2321
                }
 
2322
                millis = millis + timezone*60*60*1000 + localoffset;
 
2323
                java.sql.Timestamp tmpts = new java.sql.Timestamp(millis);
 
2324
                tmpts.setNanos(nanosVal);
 
2325
                return tmpts;
 
2326
        }
 
2327
                        
 
2328
        
 
2329
        private static final String PG_TEXT = "text";
 
2330
        private static final String PG_INTEGER = "integer";
 
2331
        private static final String PG_INT2 = "int2";
 
2332
        private static final String PG_INT8 = "int8";
 
2333
        private static final String PG_NUMERIC = "numeric";
 
2334
        private static final String PG_FLOAT = "float";
 
2335
        private static final String PG_DOUBLE = "double precision";
 
2336
        private static final String PG_BOOLEAN = "boolean";
 
2337
        private static final String PG_DATE = "date";
 
2338
        private static final String PG_TIME = "time";
 
2339
        private static final String PG_TIMESTAMPTZ = "timestamptz";
 
2340
    private static final String PG_BYTEA = "bytea";
 
2341
 
 
2342
 
 
2343
}