File: AbstractJdbc2Array.java

package info (click to toggle)
libpgjava 8.4-701-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 3,532 kB
  • ctags: 4,162
  • sloc: java: 33,948; xml: 3,158; makefile: 14; sh: 10
file content (693 lines) | stat: -rw-r--r-- 22,452 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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
/*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2008, PostgreSQL Global Development Group
*
* IDENTIFICATION
*   $PostgreSQL: pgjdbc/org/postgresql/jdbc2/AbstractJdbc2Array.java,v 1.25 2009/03/03 05:33:04 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.jdbc2;

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.Types;
import java.util.ArrayList;
import java.util.Map;
import java.util.Vector;

/**
 * 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 abstract class AbstractJdbc2Array
{

    /**
     * Array list implementation specific for storing PG array elements.
     */
    private static class PgArrayList extends ArrayList
    {

        private static final long serialVersionUID = 2052783752654562677L;

        /**
         * How many dimensions.
         */
        int dimensionsCount = 1;

    }

    /**
     * A database connection.
     */
    private BaseConnection connection = null;

    /**
     * The OID of this field.
     */
    private int oid;

    /**
     * Field value as String.
     */
    private String fieldString = null;

    /**
     * Whether Object[] should be used instead primitive arrays. Object[] can
     * contain null elements. It should be set to <Code>true</Code> if
     * {@link BaseConnection#haveMinimumCompatibleVersion(String)} returns
     * <Code>true</Code> for argument "8.3".
     */
    private final boolean useObjects;

    /**
     * Are we connected to an 8.2 or higher server?  Only 8.2 or higher
     * supports null array elements.
     */
    private final boolean haveMinServer82;

    /**
     * Value of field as {@link PgArrayList}. Will be initialized only once
     * within {@link #buildArrayList()}.
     */
    private PgArrayList arrayList;

    /**
     * Create a new Array.
     *
     * @param connection a database connection
     * @param oid the oid of the array datatype
     * @param fieldString the array data in string form
     */
    public AbstractJdbc2Array(BaseConnection connection, int oid, String fieldString) throws SQLException {
        this.connection = connection;
        this.oid = oid;
        this.fieldString = fieldString;
        this.useObjects = connection.haveMinimumCompatibleVersion("8.3");
        this.haveMinServer82 = connection.haveMinimumServerVersion("8.2");
    }

    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
    {

        // for now maps aren't supported.
        if (map != null && !map.isEmpty())
        {
            throw org.postgresql.Driver.notImplemented(this.getClass(), "getArrayImpl(long,int,Map)");
        }

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

        buildArrayList();

        if (count == 0)
            count = arrayList.size();

        // array index out of range
        if ((--index) + count > arrayList.size())
        {
            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(arrayList.size()) }), PSQLState.DATA_ERROR);
        }

        return buildArray(arrayList, (int) index, count);
    }

    /**
     * Build {@link ArrayList} from field's string input. As a result
     * of this method {@link #arrayList} is build. Method can be called
     * many times in order to make sure that array list is ready to use, however
     * {@link #arrayList} will be set only once during first call.
     */
    private synchronized void buildArrayList() throws SQLException
    {
        if (arrayList != null)
            return;

        arrayList = new PgArrayList();

        char delim = connection.getTypeInfo().getArrayDelimiter(oid);

        if (fieldString != null)
        {

            char[] chars = fieldString.toCharArray();
            StringBuffer buffer = null;
            boolean insideString = false;
            boolean wasInsideString = false; // needed for checking if NULL
            // value occured
            Vector dims = new Vector(); // array dimension arrays
            PgArrayList curArray = arrayList; // currently processed array

            // 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++)
            {

                // escape character that we need to skip
                if (chars[i] == '\\')
                    i++;

                // subarray start
                else if (!insideString && chars[i] == '{')
                {
                    if (dims.size() == 0)
                    {
                        dims.add(arrayList);
                    }
                    else
                    {
                        PgArrayList a = new PgArrayList();
                        PgArrayList p = ((PgArrayList) dims.lastElement());
                        p.add(a);
                        dims.add(a);
                    }
                    curArray = (PgArrayList) dims.lastElement();

                    // number of dimensions
                    {
                        for (int t = i + 1; t < chars.length; t++) {
                            if (Character.isWhitespace(chars[t])) continue;
                            else if (chars[t] == '{') curArray.dimensionsCount++;
                            else break;
                        }
                    }

                    buffer = new StringBuffer();
                    continue;
                }

                // quoted element
                else if (chars[i] == '"')
                {
                    insideString = !insideString;
                    wasInsideString = true;
                    continue;
                }

                // white space
                else if (!insideString && Character.isWhitespace(chars[i]))
                {
                    continue;
                }

                // array end or element end
                else if ((!insideString && (chars[i] == delim || chars[i] == '}')) || i == chars.length - 1)
                {

                    // when character that is a part of array element
                    if (chars[i] != '"' && chars[i] != '}' && chars[i] != delim && buffer != null)
                    {
                        buffer.append(chars[i]);
                    }

                    String b = buffer == null ? null : buffer.toString();

                    // add element to current array
                    if (b != null && (b.length() > 0 || wasInsideString))
                    {
                        curArray.add(!wasInsideString && haveMinServer82 && b.equals("NULL") ? null : b);
                    }

                    wasInsideString = false;
                    buffer = new StringBuffer();

                    // when end of an array
                    if (chars[i] == '}')
                    {
                        dims.remove(dims.size() - 1);

                        // when multi-dimension
                        if (dims.size() > 0)
                        {
                            curArray = (PgArrayList) dims.lastElement();
                        }

                        buffer = null;
                    }

                    continue;
                }

                if (buffer != null)
                    buffer.append(chars[i]);
            }
        }
    }

    /**
     * Convert {@link ArrayList} to array.
     *
     * @param input list to be converted into array
     */
    private Object buildArray (PgArrayList input, int index, int count) throws SQLException
    {

        if (count < 0)
            count = input.size();

        // array to be returned
        Object ret = null;

        // how many dimensions
        int dims = input.dimensionsCount;

        // dimensions length array (to be used with java.lang.reflect.Array.newInstance(Class<?>, int[]))
        int[] dimsLength = dims > 1 ? new int[dims] : null;
        if (dims > 1) {
            for (int i = 0; i < dims; i++) {
                dimsLength[i] = (i == 0 ? count : 0);
            }
        }

        // array elements counter
        int length = 0;

        // array elements type
        final int type = connection.getTypeInfo().getSQLType(connection.getTypeInfo().getPGArrayElement(oid));

        if (type == Types.BIT)
        {
            boolean[] pa = null; // primitive array
            Object[] oa = null; // objects array

            if (dims > 1 || useObjects)
            {
ret = oa = (dims > 1 ? (Object[]) java.lang.reflect.Array.newInstance(useObjects ? Boolean.class : boolean.class, dimsLength) : new Boolean[count]);
            }
            else
            {
                ret = pa = new boolean[count];
            }

            // add elements
            for (; count > 0; count--)
            {
                Object o = input.get(index++);

                if (dims > 1 || useObjects)
                {
                    oa[length++] = o == null ? null : (dims > 1 ? buildArray((PgArrayList) o, 0, -1) : new Boolean(AbstractJdbc2ResultSet.toBoolean((String) o)));
                }
                else
                {
                    pa[length++] = o == null ? false : AbstractJdbc2ResultSet.toBoolean((String) o);
                }
            }
        }

        else if (type == Types.SMALLINT || type == Types.INTEGER)
        {
            int[] pa = null;
            Object[] oa = null;

            if (dims > 1 || useObjects)
            {
ret = oa = (dims > 1 ? (Object[]) java.lang.reflect.Array.newInstance(useObjects ? Integer.class : int.class, dimsLength) : new Integer[count]);
            }
            else
            {
                ret = pa = new int[count];
            }

            for (; count > 0; count--)
            {
                Object o = input.get(index++);

                if (dims > 1 || useObjects)
                {
                    oa[length++] = o == null ? null : (dims > 1 ? buildArray((PgArrayList) o, 0, -1) : new Integer(AbstractJdbc2ResultSet.toInt((String) o)));
                }
                else
                {
                    pa[length++] = o == null ? 0 : AbstractJdbc2ResultSet.toInt((String) o);
                }
            }
        }

        else if (type == Types.BIGINT)
        {
            long[] pa = null;
            Object[] oa = null;

            if (dims > 1 || useObjects)
            {
ret = oa = (dims > 1 ? (Object[]) java.lang.reflect.Array.newInstance(useObjects ? Long.class : long.class, dimsLength) : new Long[count]);
            }

            else
            {
                ret = pa = new long[count];
            }

            for (; count > 0; count--)
            {
                Object o = input.get(index++);

                if (dims > 1 || useObjects)
                {
                    oa[length++] = o == null ? null : (dims > 1 ? buildArray((PgArrayList) o, 0, -1) : new Long(AbstractJdbc2ResultSet.toLong((String) o)));
                }
                else
                {
                    pa[length++] = o == null ? 0l : AbstractJdbc2ResultSet.toLong((String) o);
                }
            }
        }

        else if (type == Types.NUMERIC)
        {
            Object[] oa = null;
            ret = oa = (dims > 1 ? (Object[]) java.lang.reflect.Array.newInstance(BigDecimal.class, dimsLength) : new BigDecimal[count]);

            for (; count > 0; count--)
            {
                Object v = input.get(index++);
                oa[length++] = dims > 1 && v != null ? buildArray((PgArrayList) v, 0, -1) : (v == null ? null : AbstractJdbc2ResultSet.toBigDecimal((String) v, -1));
            }
        }

        else if (type == Types.REAL)
        {
            float[] pa = null;
            Object[] oa = null;

            if (dims > 1 || useObjects)
            {
ret = oa = (dims > 1 ? (Object[]) java.lang.reflect.Array.newInstance(useObjects ? Float.class : float.class, dimsLength) : new Float[count]);
            }
            else
            {
                ret = pa = new float[count];
            }

            for (; count > 0; count--)
            {
                Object o = input.get(index++);

                if (dims > 1 || useObjects)
                {
                    oa[length++] = o == null ? null : (dims > 1 ? buildArray((PgArrayList) o, 0, -1) : new Float(AbstractJdbc2ResultSet.toFloat((String) o)));
                }
                else
                {
                    pa[length++] = o == null ? 0f : AbstractJdbc2ResultSet.toFloat((String) o);
                }
            }
        }

        else if (type == Types.DOUBLE)
        {
            double[] pa = null;
            Object[] oa = null;

            if (dims > 1 || useObjects)
            {
ret = oa = (dims > 1 ? (Object[]) java.lang.reflect.Array.newInstance(useObjects ? Double.class : double.class, dimsLength) : new Double[count]);
            }
            else
            {
                ret = pa = new double[count];
            }

            for (; count > 0; count--)
            {
                Object o = input.get(index++);

                if (dims > 1 || useObjects)
                {
                    oa[length++] = o == null ? null : (dims > 1 ? buildArray((PgArrayList) o, 0, -1) : new Double(AbstractJdbc2ResultSet.toDouble((String) o)));
                }
                else
                {
                    pa[length++] = o == null ? 0d : AbstractJdbc2ResultSet.toDouble((String) o);
                }
            }
        }

        else if (type == Types.CHAR || type == Types.VARCHAR)
        {
            Object[] oa = null;
            ret = oa = (dims > 1 ? (Object[]) java.lang.reflect.Array.newInstance(String.class, dimsLength) : new String[count]);

            for (; count > 0; count--)
            {
                Object v = input.get(index++);
                oa[length++] = dims > 1 && v != null ? buildArray((PgArrayList) v, 0, -1) : v;
            }
        }

        else if (type == Types.DATE)
        {
            Object[] oa = null;
            ret = oa = (dims > 1 ? (Object[]) java.lang.reflect.Array.newInstance(java.sql.Date.class, dimsLength) : new java.sql.Date[count]);

            for (; count > 0; count--)
            {
                Object v = input.get(index++);
                oa[length++] = dims > 1 && v != null ? buildArray((PgArrayList) v, 0, -1) : (v == null ? null : connection.getTimestampUtils().toDate(null, (String) v));
            }
        }

        else if (type == Types.TIME)
        {
            Object[] oa = null;
            ret = oa = (dims > 1 ? (Object[]) java.lang.reflect.Array.newInstance(java.sql.Time.class, dimsLength) : new java.sql.Time[count]);

            for (; count > 0; count--)
            {
                Object v = input.get(index++);
                oa[length++] = dims > 1 && v != null ? buildArray((PgArrayList) v, 0, -1) : (v == null ? null : connection.getTimestampUtils().toTime(null, (String) v));
            }
        }

        else if (type == Types.TIMESTAMP)
        {
            Object[] oa = null;
            ret = oa = (dims > 1 ? (Object[]) java.lang.reflect.Array.newInstance(java.sql.Timestamp.class, dimsLength) : new java.sql.Timestamp[count]);

            for (; count > 0; count--)
            {
                Object v = input.get(index++);
                oa[length++] = dims > 1 && v != null ? buildArray((PgArrayList) v, 0, -1) : (v == null ? null : connection.getTimestampUtils().toTimestamp(null, (String) v));
            }
        }

        // other datatypes not currently supported
        else
        {
            if (connection.getLogger().logDebug())
                connection.getLogger().debug("getArrayImpl(long,int,Map) with " + getBaseTypeName());

            throw org.postgresql.Driver.notImplemented(this.getClass(), "getArrayImpl(long,int,Map)");
        }

        return ret;
    }

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

    public String getBaseTypeName() throws SQLException
    {
        buildArrayList();
        int elementOID = connection.getTypeInfo().getPGArrayElement(oid);
        return connection.getTypeInfo().getPGType(elementOID);
    }

    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);
    }

    public ResultSet getResultSetImpl(long index, int count, Map map) throws SQLException
    {

        // for now maps aren't supported.
        if (map != null && !map.isEmpty())
        {
            throw org.postgresql.Driver.notImplemented(this.getClass(), "getResultSetImpl(long,int,Map)");
        }

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

        buildArrayList();

        if (count == 0)
        {
            count = arrayList.size();
        }

        // array index out of range
        if ((--index) + count > arrayList.size())
        {
            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(arrayList.size()) }), PSQLState.DATA_ERROR);
        }

        Vector rows = new Vector();

        Field[] fields = new Field[2];

        // one dimensional array
        if (arrayList.dimensionsCount <= 1)
        {
            // array element type
            final int baseOid = connection.getTypeInfo().getPGArrayElement(oid);
            fields[0] = new Field("INDEX", Oid.INT4);
            fields[1] = new Field("VALUE", baseOid);

            for (int i = 0; i < count; i++)
            {
                int offset = (int)index + i;
                byte[][] t = new byte[2][0];
                String v = (String) arrayList.get(offset);
                t[0] = connection.encodeString(Integer.toString(offset + 1));
                t[1] = v == null ? null : connection.encodeString(v);
                rows.add(t);
            }
        }

        // when multi-dimensional
        else
        {
            fields[0] = new Field("INDEX", Oid.INT4);
            fields[1] = new Field("VALUE", oid);
            for (int i = 0; i < count; i++)
            {
                int offset = (int)index + i;
                byte[][] t = new byte[2][0];
                Object v = arrayList.get(offset);

                t[0] = connection.encodeString(Integer.toString(offset + 1));
                t[1] = v == null ? null : connection.encodeString(toString((PgArrayList) v));
                rows.add(t);
            }
        }

        BaseStatement stat = (BaseStatement) connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        return (ResultSet) stat.createDriverResultSet(fields, rows);
    }

    public String toString()
    {
        return fieldString;
    }

    /**
     * Convert array list to PG String representation (e.g. {0,1,2}).
     */
    private String toString(PgArrayList list) throws SQLException
    {
        StringBuffer b = new StringBuffer().append('{');

        char delim = connection.getTypeInfo().getArrayDelimiter(oid);

        for (int i = 0; i < list.size(); i++)
        {
            Object v = list.get(i);

            if (i > 0)
                b.append(delim);

            if (v == null)
                b.append("NULL");

            else if (v instanceof PgArrayList)
                b.append(toString((PgArrayList) v));

            else
                escapeArrayElement(b, (String)v);
        }

        b.append('}');

        return b.toString();
    }

    public static void escapeArrayElement(StringBuffer b, String s)
    {
        b.append('"');
        for (int j = 0; j < s.length(); j++) {
            char c = s.charAt(j);
            if (c == '"' || c == '\\') {
                b.append('\\');
            }

            b.append(c);
        }
        b.append('"');
    }

}