File: AbstractJdbc2Array.java

package info (click to toggle)
libpgjava 8.1-405-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 3,484 kB
  • ctags: 4,266
  • sloc: java: 32,071; xml: 3,017; sql: 21; makefile: 18; sh: 10
file content (413 lines) | stat: -rw-r--r-- 16,603 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2005, PostgreSQL Global Development Group
*
* IDENTIFICATION
*   $PostgreSQL: pgjdbc/org/postgresql/jdbc2/AbstractJdbc2Array.java,v 1.15.2.1 2005/12/04 21:41:21 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.jdbc2;

import org.postgresql.Driver;
import org.postgresql.core.*;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import org.postgresql.util.GT;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Map;
import java.util.Vector;
import java.util.GregorianCalendar;

/**
 * Array is used collect one column of query result data.
 *
 * <p>Read a field of type Array into either a natively-typed
 * Java array object or a ResultSet.  Accessor methods provide
 * the ability to capture array slices.
 *
 * <p>Other than the constructor all methods are direct implementations
 * of those specified for java.sql.Array.  Please refer to the javadoc
 * for java.sql.Array for detailed descriptions of the functionality
 * and parameters of the methods of this class.
 *
 * @see ResultSet#getArray
 */


public class AbstractJdbc2Array
{
    private BaseConnection conn = null;
    private Field field = null;
    private BaseResultSet rs;
    private int idx = 0;
    private String rawString = null;

    /**
     * Create a new Array
     *
     * @param conn a database connection
     * @param idx 1-based index of the query field to load into this Array
     * @param field the Field descriptor for the field to load into this Array
     * @param rs the ResultSet from which to get the data for this Array
     */
    public AbstractJdbc2Array(BaseConnection conn, int idx, Field field, BaseResultSet rs )
    throws SQLException
    {
        this.conn = conn;
        this.field = field;
        this.rs = rs;
        this.idx = idx;
        this.rawString = rs.getFixedString(idx);
    }

    public Object getArray() throws SQLException
    {
        return getArrayImpl( 1, 0, null );
    }

    public Object getArray(long index, int count) throws SQLException
    {
        return getArrayImpl( index, count, null );
    }

    public Object getArrayImpl(Map map) throws SQLException
    {
        return getArrayImpl( 1, 0, map );
    }

    public Object getArrayImpl(long index, int count, Map map) throws SQLException
    {
        if ( map != null && !map.isEmpty()) // For now maps aren't supported.
            throw org.postgresql.Driver.notImplemented(this.getClass(), "getArrayImpl(long,int,Map)");

        if (index < 1)
            throw new PSQLException(GT.tr("The array index is out of range: {0}", new Long(index)), PSQLState.DATA_ERROR);
        Object retVal = null;

        ArrayList array = new ArrayList();

        /* Check if the String is also not an empty array
              * otherwise there will be an exception thrown below
              * in the ResultSet.toX with an empty string.
              * -- Doug Fields <dfields-pg-jdbc@pexicom.com> Feb 20, 2002 */

        if ( rawString != null && !rawString.equals("{}") )
        {
            char[] chars = rawString.toCharArray();
            StringBuffer sbuf = new StringBuffer();
            boolean foundOpen = false;
            boolean insideString = false;

            /**
             * Starting with 8.0 non-standard (beginning index
             * isn't 1) bounds the dimensions are returned in the
             * data formatted like so "[0:3]={0,1,2,3,4}".
             * Older versions simply do not return the bounds.
             *
             * Right now we ignore these bounds, but we could
             * consider allowing these index values to be used
             * even though the JDBC spec says 1 is the first
             * index.  I'm not sure what a client would like
             * to see, so we just retain the old behavior.
             */
            int startOffset = 0;
            if (chars[0] == '[')
            {
                while (chars[startOffset] != '=')
                {
                    startOffset++;
                }
                startOffset++; // skip =
            }

            for ( int i = startOffset; i < chars.length; i++ )
            {
                if ( chars[i] == '\\' )
                    //escape character that we need to skip
                    i++;
                else if (!insideString && chars[i] == '{' )
                {
                    if ( foundOpen )  // Only supports 1-D arrays for now
                        throw new PSQLException(GT.tr("Multi-dimensional arrays are currently not supported."),
                                                PSQLState.NOT_IMPLEMENTED);
                    foundOpen = true;
                    continue;
                }
                else if (chars[i] == '"')
                {
                    insideString = !insideString;
                    continue;
                }
                else if (!insideString && (chars[i] == ',' || chars[i] == '}') ||
                         i == chars.length - 1)
                {
                    if ( chars[i] != '"' && chars[i] != '}' && chars[i] != ',' )
                        sbuf.append(chars[i]);
                    array.add( sbuf.toString() );
                    sbuf = new StringBuffer();
                    continue;
                }
                sbuf.append( chars[i] );
            }
        }
        String[] arrayContents = (String[]) array.toArray( new String[array.size()] );
        if ( count == 0 )
            count = arrayContents.length;
        index--;
        if ( index + count > arrayContents.length )
            throw new PSQLException(GT.tr("The array index is out of range: {0}, number of elements: {1}.", new Object[]{new Long(index + count), new Long(arrayContents.length)}), PSQLState.DATA_ERROR);

        int i = 0;
        GregorianCalendar cal = null;
        switch ( getBaseType() )
        {
        case Types.BIT:
            retVal = new boolean[ count ];
            for ( ; count > 0; count-- )
                ((boolean[])retVal)[i++] = AbstractJdbc2ResultSet.toBoolean( arrayContents[(int)index++] );
            break;
        case Types.SMALLINT:
        case Types.INTEGER:
            retVal = new int[ count ];
            for ( ; count > 0; count-- )
                ((int[])retVal)[i++] = AbstractJdbc2ResultSet.toInt( arrayContents[(int)index++] );
            break;
        case Types.BIGINT:
            retVal = new long[ count ];
            for ( ; count > 0; count-- )
                ((long[])retVal)[i++] = AbstractJdbc2ResultSet.toLong( arrayContents[(int)index++] );
            break;
        case Types.NUMERIC:
            retVal = new BigDecimal[ count ];
            for ( ; count > 0; count-- )
                ((BigDecimal[])retVal)[i++] = AbstractJdbc2ResultSet.toBigDecimal( arrayContents[(int)index++], -1 );
            break;
        case Types.REAL:
            retVal = new float[ count ];
            for ( ; count > 0; count-- )
                ((float[])retVal)[i++] = AbstractJdbc2ResultSet.toFloat( arrayContents[(int)index++] );
            break;
        case Types.DOUBLE:
            retVal = new double[ count ];
            for ( ; count > 0; count-- )
                ((double[])retVal)[i++] = AbstractJdbc2ResultSet.toDouble( arrayContents[(int)index++] );
            break;
        case Types.CHAR:
        case Types.VARCHAR:
            retVal = new String[ count ];
            for ( ; count > 0; count-- )
                ((String[])retVal)[i++] = arrayContents[(int)index++];
            break;
        case Types.DATE:
            retVal = new java.sql.Date[ count ];
            for ( ; count > 0; count-- )
                ((java.sql.Date[])retVal)[i++] = conn.getTimestampUtils().toDate(null, arrayContents[(int)index++] );
            break;
        case Types.TIME:
            retVal = new java.sql.Time[ count ];
            for ( ; count > 0; count-- )
                ((java.sql.Time[])retVal)[i++] = conn.getTimestampUtils().toTime(null, arrayContents[(int)index++] );
            break;
        case Types.TIMESTAMP:
            retVal = new Timestamp[ count ];
            for ( ; count > 0; count-- )
                ((java.sql.Timestamp[])retVal)[i++] = conn.getTimestampUtils().toTimestamp(null, arrayContents[(int)index++] );
            break;

            // Other datatypes not currently supported.  If you are really using other types ask
            // yourself if an array of non-trivial data types is really good database design.
        default:
            if (Driver.logDebug)
                Driver.debug("getArrayImpl(long,int,Map) with "+getBaseTypeName());
            throw org.postgresql.Driver.notImplemented(this.getClass(), "getArrayImpl(long,int,Map)");
        }
        return retVal;
    }

    public int getBaseType() throws SQLException
    {
        return conn.getSQLType(getBaseTypeName());
    }

    public String getBaseTypeName() throws SQLException
    {
        String fType = conn.getPGType(field.getOID());
        if ( fType.charAt(0) == '_' )
            fType = fType.substring(1);
        return fType;
    }

    public java.sql.ResultSet getResultSet() throws SQLException
    {
        return getResultSetImpl( 1, 0, null );
    }

    public java.sql.ResultSet getResultSet(long index, int count) throws SQLException
    {
        return getResultSetImpl( index, count, null );
    }

    public java.sql.ResultSet getResultSetImpl(Map map) throws SQLException
    {
        return getResultSetImpl( 1, 0, map );
    }

    private void fillIntegerResultSet(long index, int[] intArray, Vector rows) throws SQLException
    {
        for ( int i = 0; i < intArray.length; i++ )
        {
            byte[][] tuple = new byte[2][0];
            tuple[0] = conn.encodeString( Integer.toString((int)index + i) ); // Index
            tuple[1] = conn.encodeString( Integer.toString(intArray[i]) ); // Value
            rows.addElement(tuple);
        }
    }

    private void fillStringResultSet(long index, String[] strArray, Vector rows) throws SQLException
    {
        for ( int i = 0; i < strArray.length; i++ )
        {
            byte[][] tuple = new byte[2][0];
            tuple[0] = conn.encodeString( Integer.toString((int)index + i) ); // Index
            tuple[1] = conn.encodeString( strArray[i] ); // Value
            rows.addElement(tuple);
        }
    }

    public java.sql.ResultSet getResultSetImpl(long index, int count, java.util.Map map) throws SQLException
    {
        Object array = getArrayImpl( index, count, map );
        Vector rows = new Vector();
        Field[] fields = new Field[2];
        fields[0] = new Field("INDEX", Oid.INT2, 2);
        switch ( getBaseType() )
        {
        case Types.BIT:
            boolean[] booleanArray = (boolean[]) array;
            fields[1] = new Field("VALUE", Oid.BOOL, 1);
            for ( int i = 0; i < booleanArray.length; i++ )
            {
                byte[][] tuple = new byte[2][0];
                tuple[0] = conn.encodeString( Integer.toString((int)index + i) ); // Index
                tuple[1] = conn.encodeString( (booleanArray[i] ? "YES" : "NO") ); // Value
                rows.addElement(tuple);
            }
            break;
        case Types.SMALLINT:
            fields[1] = new Field("VALUE", Oid.INT2, 2);
            fillIntegerResultSet(index, (int[])array, rows);
            break;
        case Types.INTEGER:
            fields[1] = new Field("VALUE", Oid.INT4, 4);
            fillIntegerResultSet(index, (int[])array, rows);
            break;
        case Types.BIGINT:
            long[] longArray = (long[]) array;
            fields[1] = new Field("VALUE", Oid.INT8, 8);
            for ( int i = 0; i < longArray.length; i++ )
            {
                byte[][] tuple = new byte[2][0];
                tuple[0] = conn.encodeString( Integer.toString((int)index + i) ); // Index
                tuple[1] = conn.encodeString( Long.toString(longArray[i]) ); // Value
                rows.addElement(tuple);
            }
            break;
        case Types.NUMERIC:
            BigDecimal[] bdArray = (BigDecimal[]) array;
            fields[1] = new Field("VALUE", Oid.NUMERIC, -1);
            for ( int i = 0; i < bdArray.length; i++ )
            {
                byte[][] tuple = new byte[2][0];
                tuple[0] = conn.encodeString( Integer.toString((int)index + i) ); // Index
                tuple[1] = conn.encodeString( bdArray[i].toString() ); // Value
                rows.addElement(tuple);
            }
            break;
        case Types.REAL:
            float[] floatArray = (float[]) array;
            fields[1] = new Field("VALUE", Oid.FLOAT4, 4);
            for ( int i = 0; i < floatArray.length; i++ )
            {
                byte[][] tuple = new byte[2][0];
                tuple[0] = conn.encodeString( Integer.toString((int)index + i) ); // Index
                tuple[1] = conn.encodeString( Float.toString(floatArray[i]) ); // Value
                rows.addElement(tuple);
            }
            break;
        case Types.DOUBLE:
            double[] doubleArray = (double[]) array;
            fields[1] = new Field("VALUE", Oid.FLOAT8, 8);
            for ( int i = 0; i < doubleArray.length; i++ )
            {
                byte[][] tuple = new byte[2][0];
                tuple[0] = conn.encodeString( Integer.toString((int)index + i) ); // Index
                tuple[1] = conn.encodeString( Double.toString(doubleArray[i]) ); // Value
                rows.addElement(tuple);
            }
            break;
        case Types.CHAR:
            fields[1] = new Field("VALUE", Oid.BPCHAR, 1);
            fillStringResultSet(index, (String[])array, rows);
            break;
        case Types.VARCHAR:
            fields[1] = new Field("VALUE", Oid.VARCHAR, -1);
            fillStringResultSet(index, (String[])array, rows);
            break;
        case Types.DATE:
            java.sql.Date[] dateArray = (java.sql.Date[]) array;
            fields[1] = new Field("VALUE", Oid.DATE, 4);
            for ( int i = 0; i < dateArray.length; i++ )
            {
                byte[][] tuple = new byte[2][0];
                tuple[0] = conn.encodeString( Integer.toString((int)index + i) ); // Index
                tuple[1] = conn.encodeString( conn.getTimestampUtils().toString(null, dateArray[i]) ); // Value
                rows.addElement(tuple);
            }
            break;
        case Types.TIME:
            java.sql.Time[] timeArray = (java.sql.Time[]) array;
            fields[1] = new Field("VALUE", Oid.TIME, 8);
            for ( int i = 0; i < timeArray.length; i++ )
            {
                byte[][] tuple = new byte[2][0];
                tuple[0] = conn.encodeString( Integer.toString((int)index + i) ); // Index
                tuple[1] = conn.encodeString( conn.getTimestampUtils().toString(null, timeArray[i]) ); // Value
                rows.addElement(tuple);
            }
            break;
        case Types.TIMESTAMP:
            java.sql.Timestamp[] timestampArray = (java.sql.Timestamp[]) array;
            fields[1] = new Field("VALUE", Oid.TIMESTAMPTZ, 8);
            for ( int i = 0; i < timestampArray.length; i++ )
            {
                byte[][] tuple = new byte[2][0];
                tuple[0] = conn.encodeString( Integer.toString((int)index + i) ); // Index
                tuple[1] = conn.encodeString( conn.getTimestampUtils().toString(null, timestampArray[i]) ); // Value
                rows.addElement(tuple);
            }
            break;

            // Other datatypes not currently supported.  If you are really using other types ask
            // yourself if an array of non-trivial data types is really good database design.
        default:
            if (Driver.logDebug)
                Driver.debug("getResultSetImpl(long,int,Map) with "+getBaseTypeName());
            throw org.postgresql.Driver.notImplemented(this.getClass(), "getResultSetImpl(long,int,Map)");
        }
        BaseStatement stat = (BaseStatement) conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        return (ResultSet) stat.createDriverResultSet(fields, rows);
    }

    public String toString()
    {
        return rawString;
    }
}