3 * Test the C++ version of LIBPQ, the POSTGRES frontend library.
4 * tests the binary cursor interface
8 populate a database by doing the following (use testlibpq5.sql):
10 CREATE TABLE test1 (i int4, d float4, p polygon);
12 INSERT INTO test1 values (1, 3.567, '(3.0, 4.0, 1.0, 2.0)'::polygon);
14 INSERT INTO test1 values (2, 89.05, '(4.0, 3.0, 2.0, 1.0)'::polygon);
16 the expected output is:
20 d = (4 bytes) 3.567000,
21 p = (4 bytes) 2 points boundbox = (hi=3.000000/4.000000, lo = 1.000000,2.000000)
24 d = (4 bytes) 89.050003,
25 p = (4 bytes) 2 points boundbox = (hi=4.000000/3.000000, lo = 2.000000,1.000000)
33 #include "postgres.h" // for Postgres types
34 #include "utils/geo_decls.h" // for the POLYGON type
39 // Begin, by connecting to the backend using hardwired constants
40 // and a test database created by the user prior to the invokation
41 // of this test program. Connect using cursor interface.
42 const char* dbName = "dbname=template1"; // change this to the name of your test database
43 PgCursor data(dbName, "mycursor");
45 // check to see that the backend connection was successfully made
46 if ( data.ConnectionBad() ) {
47 cerr << "Connection to database '" << dbName << "' failed." << endl
48 << data.ErrorMessage();
52 // Declare a binary cursor for all the tuples in database 'test1'
53 if ( !data.Declare("select * from test1", 1) ) {
54 cerr << "DECLARE CURSOR command failed" << endl;
58 // fetch all instances from the current cursor
59 if ( !data.Fetch() ) {
60 cerr << "FETCH ALL command didn't return tuples properly" << endl;
64 // Find the field numbers for the columns 'i', 'd', and 'p'
65 int i_fnum = data.FieldNum("i");
66 int d_fnum = data.FieldNum("d");
67 int p_fnum = data.FieldNum("p");
71 printf("type[%d] = %d, size[%d] = %d\n",
73 i, data.FieldSize(i));
77 // Print out the information about the extracted tuple
78 for (int i=0; i < data.Tuples(); i++) {
79 // we hard-wire this to the 3 fields we know about
80 int* ival = (int*)data.GetValue(i,i_fnum);
81 float* dval = (float*)data.GetValue(i,d_fnum);
82 int plen = data.GetLength(i,p_fnum);
84 // Allocate correct memory space for the Polygon struct and copy
85 // the extracted data into it.
86 // plen doesn't include the length field so need to increment by VARHDSZ
87 POLYGON* pval = (POLYGON*) malloc(plen + VARHDRSZ);
89 memmove((char*)&pval->npts, data.GetValue(i,p_fnum), plen);
91 // Display Polygon Information
92 cout << "tuple " << i << ": got" << endl
93 << " i = (" << data.GetLength(i,i_fnum) << " bytes) " << *ival << "," << endl
94 << " d = (" << data.GetLength(i,d_fnum) << " bytes) " << *dval << "," << endl
95 << " p = (" << data.GetLength(i,d_fnum) << " bytes) " << pval->npts << " points"
96 << "\tboundbox = (hi=" << pval->boundbox.high.x << "/" << pval->boundbox.high.y << ","
97 << "lo = " << pval->boundbox.low.x << "," << pval->boundbox.low.y << ")" << endl;
99 // Deallocate memory allocated for the Polygon structure