File: CopyTest.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 (260 lines) | stat: -rw-r--r-- 8,934 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
/*-------------------------------------------------------------------------
*
* Copyright (c) 2008, PostgreSQL Global Development Group
*
* IDENTIFICATION
*   $PostgreSQL: pgjdbc/org/postgresql/test/jdbc2/CopyTest.java,v 1.2 2009/07/01 05:00:40 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.test.jdbc2;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.IOException;

import junit.framework.TestCase;

import org.postgresql.PGConnection;
import org.postgresql.copy.*;
import org.postgresql.test.TestUtil;
import org.postgresql.util.PSQLState;

/**
 * @author kato@iki.fi
 *
 */
public class CopyTest extends TestCase {

    private Connection con;
    private CopyManager copyAPI;
    private String[] origData =
    { "First Row\t1\t1.10\n", // 0's required to match DB output for numeric(5,2)
      "Second Row\t2\t-22.20\n",
      "\\N\t\\N\t\\N\n",
      "\t4\t444.40\n" };
    private int dataRows = origData.length;

    public CopyTest(String name) {
        super(name);
    }

    private byte[] getData(String[] origData) {
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(buf);
        for(int i=0; i<origData.length; i++)
            ps.print(origData[i]);
        return buf.toByteArray();
    }

    protected void setUp() throws Exception {
        con = TestUtil.openDB();

        TestUtil.createTable(con, "copytest", "stringvalue text, intvalue int, numvalue numeric(5,2)");

        copyAPI = ((PGConnection)con).getCopyAPI();
    }

    protected void tearDown() throws Exception {
        TestUtil.dropTable(con, "copytest");
        TestUtil.closeDB(con);
    }

    private int getCount() throws SQLException {
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT count(*) FROM copytest");
        rs.next();
        int result = rs.getInt(1);
        rs.close();
        return result;
    }
    
    public void testCopyInByRow() throws SQLException {
        String sql = "COPY copytest FROM STDIN";
        CopyIn cp = copyAPI.copyIn(sql);
        for(int i=0; i<origData.length; i++) {
            byte[] buf = origData[i].getBytes();
            cp.writeToCopy(buf, 0, buf.length);
        }

        long count1 = cp.endCopy();
        long count2 = cp.getHandledRowCount();
        long expectedResult = -1;
        if (TestUtil.haveMinimumServerVersion(con, "8.2")) {
            expectedResult = dataRows;
        }
        assertEquals(expectedResult, count1);
        assertEquals(expectedResult, count2);

        try {
            cp.cancelCopy();
        } catch(SQLException se) { // should fail with obsolete operation
            if(! PSQLState.OBJECT_NOT_IN_STATE.getState().equals(se.getSQLState()) )
                 fail("should have thrown object not in state exception.");
        }
        int rowCount = getCount();
        assertEquals(dataRows, rowCount);
    }

    public void testCopyInAsOutputStream() throws SQLException, IOException {
        String sql = "COPY copytest FROM STDIN";
        OutputStream os = new PGCopyOutputStream((PGConnection)con, sql, 1000);
        for(int i=0; i<origData.length; i++) {
            byte[] buf = origData[i].getBytes();
            os.write(buf);
        }
        os.close();
        int rowCount = getCount();
        assertEquals(dataRows, rowCount);
    }

    public void testCopyInFromInputStream() throws SQLException, IOException {
        String sql = "COPY copytest FROM STDIN";
        copyAPI.copyIn(sql, new ByteArrayInputStream(getData(origData)), 3);
        int rowCount = getCount();
        assertEquals(dataRows, rowCount);
    }

    public void testCopyInFromStreamFail() throws SQLException {
        String sql = "COPY copytest FROM STDIN";
        try {
            copyAPI.copyIn(sql, new InputStream() {
                public int read() { throw new RuntimeException("COPYTEST"); }
            }, 3 );
        } catch(Exception e) {
            if(e.toString().indexOf("COPYTEST") == -1)
                fail("should have failed trying to read from our bogus stream.");
        }
        int rowCount = getCount();
        assertEquals(0, rowCount);
    }

    public void testSkipping() {
        String sql = "COPY copytest FROM STDIN";
        String at = "init";
        int rowCount = -1;
        int skip = 0;
        int skipChar = 1;
        try {
            while(skipChar > 0) {
                at = "buffering";
                InputStream ins = new ByteArrayInputStream(getData(origData));
                at = "skipping";
                ins.skip(skip++);
                skipChar = ins.read();
                at = "copying";
                copyAPI.copyIn(sql, ins, 3);
                at = "using connection after writing copy";
                rowCount = getCount();
            }
        } catch(Exception e) {
            if( !( skipChar=='\t' ) ) // error expected when field separator consumed
                fail("testSkipping at " + at + " round " + skip + ": " + e.toString());
        }
        assertEquals(dataRows*(skip-1), rowCount);
    }
    
    public void testCopyOutByRow() throws SQLException, IOException {
        testCopyInByRow(); // ensure we have some data.
        String sql = "COPY copytest TO STDOUT";
        CopyOut cp = copyAPI.copyOut(sql);
        int count = 0;
        byte buf[];
        while ( (buf = cp.readFromCopy()) != null) {
            count++;
        }
        assertEquals(false, cp.isActive());
        assertEquals(dataRows, count);

        long rowCount = cp.getHandledRowCount();
        long expectedResult = -1;
        if (TestUtil.haveMinimumServerVersion(con, "8.2")) {
            expectedResult = dataRows;
        }
        assertEquals(expectedResult, rowCount);

        assertEquals(dataRows, getCount());
    }

    public void testCopyOut() throws SQLException, IOException {
        testCopyInByRow(); // ensure we have some data.
        String sql = "COPY copytest TO STDOUT";
        ByteArrayOutputStream copydata = new ByteArrayOutputStream();
        copyAPI.copyOut(sql, copydata);
        assertEquals(dataRows, getCount());
        // deep comparison of data written and read
        byte[] copybytes = copydata.toByteArray();
        assertTrue(copybytes != null);
        for(int i=0, l=0; i<origData.length; i++) {
            byte[] origBytes = origData[i].getBytes();
            assertTrue(origBytes != null);
            assertTrue("Copy is shorter than original", copybytes.length >= l + origBytes.length);
            for(int j=0; j<origBytes.length; j++, l++)
                assertEquals("content changed at byte#" + j + ": " +origBytes[j] +copybytes[l], origBytes[j], copybytes[l]);
        }
    }

    public void testNonCopyOut() throws SQLException, IOException {
        String sql = "SELECT 1";
        try {
            copyAPI.copyOut(sql, new ByteArrayOutputStream());
            fail("Can't use a non-copy query.");
        } catch (SQLException sqle) {
        }
        // Ensure connection still works.
        assertEquals(0, getCount());
    }

    public void testNonCopyIn() throws SQLException, IOException {
        String sql = "SELECT 1";
        try {
            copyAPI.copyIn(sql, new ByteArrayInputStream(new byte[0]));
            fail("Can't use a non-copy query.");
        } catch (SQLException sqle) {
        }
        // Ensure connection still works.
        assertEquals(0, getCount());
    }

    public void testStatementCopyIn() throws SQLException {
        Statement stmt = con.createStatement();
        try {
            stmt.execute("COPY copytest FROM STDIN");
            fail("Should have failed because copy doesn't work from a Statement.");
        } catch (SQLException sqle) { }
        stmt.close();

        assertEquals(0, getCount());
    }

    public void testStatementCopyOut() throws SQLException {
        testCopyInByRow(); // ensure we have some data.

        Statement stmt = con.createStatement();
        try {
            stmt.execute("COPY copytest TO STDOUT");
            fail("Should have failed because copy doesn't work from a Statement.");
        } catch (SQLException sqle) { }
        stmt.close();

        assertEquals(dataRows, getCount());
    }

    public void testCopyQuery() throws SQLException, IOException {
        if (!TestUtil.haveMinimumServerVersion(con, "8.2"))
            return;

        testCopyInByRow(); // ensure we have some data.

        long count = copyAPI.copyOut("COPY (SELECT generate_series(1,1000)) TO STDOUT", new ByteArrayOutputStream());
        assertEquals(1000, count);
    }

}