File: TestPostgreSQLDatabase.cxx

package info (click to toggle)
vtk7 7.1.1%2Bdfsg1-12
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 125,776 kB
  • sloc: cpp: 1,539,582; ansic: 106,521; python: 78,038; tcl: 47,013; xml: 8,142; yacc: 5,040; java: 4,439; perl: 3,132; lex: 1,926; sh: 1,500; makefile: 122; objc: 83
file content (536 lines) | stat: -rw-r--r-- 14,394 bytes parent folder | download | duplicates (2)
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
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestPostgreSQLDatabase.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
/*-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
// .SECTION Thanks
// Thanks to Andrew Wilson from Sandia National Laboratories for implementing
// this test.

#include "vtkPostgreSQLDatabase.h"
#include "vtkSQLQuery.h"
#include "vtkRowQueryToTable.h"
#include "vtkSQLDatabaseSchema.h"
#include "vtkStdString.h"
#include "vtkTable.h"
#include "vtkVariant.h"
#include "vtkVariantArray.h"
#include "vtkStringArray.h"
#include "vtkToolkits.h"
#include "DatabaseSchemaWith2Tables.h"
#include "vtkIOPostgresSQLTestingCxxConfigure.h"
#include <vector>

int TestPostgreSQLDatabase( int /*argc*/, char* /*argv*/[] )
{
  // This test requires the user in VTK_PSQL_TEST_URL to have
  // permission to create and drop the database named in that URL
  // as well as tables in that database. That user must also be
  // able to connect to the "template1" database (which initdb
  // creates and should be present on all systems -- we do NOT
  // support non-standard configurations where this is not true).
  vtkPostgreSQLDatabase* db = vtkPostgreSQLDatabase::SafeDownCast(
    vtkSQLDatabase::CreateFromURL( VTK_PSQL_TEST_URL ) );
  vtkStdString realDatabase = db->GetDatabaseName();
  db->SetDatabaseName( "template1" ); // This is guaranteed to exist
  bool status = db->Open();
  if ( ! status )
  {
    cerr
      << "Couldn't open database.\nError message: \""
      << db->GetLastErrorText() << "\"\n";
    db->Delete();
    return 1;
  }

  vtkStringArray* dbNames = db->GetDatabases();
  cout << "Database list:\n";
  for ( int dbi = 0; dbi < dbNames->GetNumberOfValues(); ++ dbi )
  {
    cout << "+ " << dbNames->GetValue( dbi ) << endl;
  }
  dbNames->Delete();
  if ( ! db->CreateDatabase( realDatabase.c_str(), true ) )
  {
    cerr << "Error: " << db->GetLastErrorText() << endl;
  }

  vtkSQLQuery* query = db->GetQueryInstance();

  // Force a database connection close
  // This also forces us to connect to the database named in the test URL.
  vtkStdString fauxDatabase = realDatabase + "blarney";
  db->SetDatabaseName( fauxDatabase.c_str() );
  db->SetDatabaseName( realDatabase.c_str() );

  if (!db->Open())
  {
    cerr << "Error: " << db->GetLastErrorText() << endl;
  }

  // Test that bad queries fail without segfaulting...
  vtkStdString dropQuery( "DROP TABLE people" );
  cout << dropQuery << endl;
  query->SetQuery( dropQuery.c_str() );
  if ( ! query->Execute() )
  {
    cout << "Drop query did not succeed (this result *** was *** expected). The last message: " << endl;
    cout << "   " << query->GetLastErrorText() << endl;
  }
  else
  {
    cerr << "The query \"DROP TABLE people\" succeeded when it should not have.\n";
  }

  // Test table creation, insertion, queries
  vtkStdString createQuery( "CREATE TABLE people (name TEXT, age INTEGER, weight FLOAT)" );
  cout << createQuery << endl;
  query->SetQuery( createQuery.c_str() );
  if ( ! query->Execute() )
  {
    cerr << "Create query failed" << endl;
    query->Delete();
    db->Delete();
    return 1;
  }

  for ( int i = 0; i < 40; ++ i )
  {
    char insertQuery[200];
    sprintf( insertQuery, "INSERT INTO people VALUES('John Manyjars %d', %d, %d)", i, i, 10 * i );
    cout << insertQuery << endl;
    query->SetQuery( insertQuery );
    if ( ! query->Execute() )
    {
      cerr << "Insert query " << i << " failed" << endl;
      query->Delete();
      db->Delete();
      return 1;
    }
  }


  const char* queryText = "SELECT name, age, weight FROM people WHERE age <= 20";
  query->SetQuery( queryText );
  cerr << endl << "Running query: " << query->GetQuery() << endl;

  cerr << endl << "Using vtkSQLQuery directly to execute query:" << endl;
  if ( ! query->Execute() )
  {
    cerr << "Query failed" << endl;
    query->Delete();
    db->Delete();
    return 1;
  }

  for ( int col = 0; col < query->GetNumberOfFields(); ++ col )
  {
    if ( col > 0 )
    {
      cerr << ", ";
    }
    cerr << query->GetFieldName( col );
  }
  cerr << endl;
  while ( query->NextRow() )
  {
    for ( int field = 0; field < query->GetNumberOfFields(); ++ field )
    {
      if ( field > 0 )
      {
        cerr << ", ";
      }
      cerr << query->DataValue( field ).ToString().c_str();
    }
    cerr << endl;
  }

  cerr << endl << "Using vtkSQLQuery to execute query and retrieve by row:" << endl;
  if ( ! query->Execute() )
  {
    cerr << "Query failed" << endl;
    query->Delete();
    db->Delete();
    return 1;
  }
  for ( int col = 0; col < query->GetNumberOfFields(); ++ col )
  {
    if ( col > 0 )
    {
      cerr << ", ";
    }
    cerr << query->GetFieldName( col );
  }
  cerr << endl;
  vtkVariantArray* va = vtkVariantArray::New();
  while ( query->NextRow( va ) )
  {
    for ( int field = 0; field < va->GetNumberOfValues(); ++ field )
    {
      if ( field > 0 )
      {
        cerr << ", ";
      }
      cerr << va->GetValue( field ).ToString().c_str();
    }
    cerr << endl;
  }
  va->Delete();

  cerr << endl << "Using vtkRowQueryToTable to execute query:" << endl;
  vtkRowQueryToTable* reader = vtkRowQueryToTable::New();
  reader->SetQuery( query );
  reader->Update();
  vtkTable* table = reader->GetOutput();
  for ( vtkIdType col = 0; col < table->GetNumberOfColumns(); ++ col )
  {
    table->GetColumn( col )->Print( cerr );
  }
  cerr << endl;
  for ( vtkIdType row = 0; row < table->GetNumberOfRows(); ++ row )
  {
    for ( vtkIdType col = 0; col < table->GetNumberOfColumns(); ++ col )
    {
      vtkVariant v = table->GetValue( row, col );
      cerr << "row " << row << ", col " << col << " - "
        << v.ToString() << " (" << vtkImageScalarTypeNameMacro( v.GetType() ) << ")" << endl;
    }
  }

  query->SetQuery( "DROP TABLE people" );
  if ( ! query->Execute() )
  {
    cerr << "DROP TABLE people query failed" << endl;
    reader->Delete();
    query->Delete();
    db->Delete();
    return 1;
  }

  reader->Delete();
  query->Delete();
  db->Delete();

// ----------------------------------------------------------------------
// Testing transformation of a schema into a PostgreSQL database

  // 1. Create the schema
  DatabaseSchemaWith2Tables schema;

  // 2. Convert the schema into a PostgreSQL database
  cerr << "@@ Converting the schema into a PostgreSQL database...";

  db = vtkPostgreSQLDatabase::SafeDownCast( vtkSQLDatabase::CreateFromURL( VTK_PSQL_TEST_URL ) );
  status = db->Open();

  if ( ! status )
  {
    cerr
      << "Couldn't open database.\nError: \""
      << db->GetLastErrorText() << "\"\n";
    db->Delete();
    return 1;
  }

  status = db->EffectSchema( schema.GetSchema() );
  if ( ! status )
  {
    cerr << "Could not effect test schema.\n";
    db->Delete();
    return 1;
  }
  cerr << " done." << endl;

  // 3. Count tables of the newly created database
  cerr << "@@ Counting tables of the newly created database... ";

  query = db->GetQueryInstance();
  query->SetQuery( "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'" );
  if ( ! query->Execute() )
  {
    cerr << "Query failed" << endl;
    query->Delete();
    db->Delete();
    return 1;
  }

  std::vector<vtkStdString> tables;
  while ( query->NextRow() )
  {
    tables.push_back( query->DataValue( 0 ).ToString() );
  }

  int numTbl = tables.size();

  if ( numTbl != schema->GetNumberOfTables() )
  {
    cerr << "Found an incorrect number of tables: "
         << numTbl
         << " != "
         << schema->GetNumberOfTables()
         << endl;
    query->Delete();
    db->Delete();
    return 1;
  }

  cerr << numTbl
       << " found.\n";

  // 4. Inspect these tables
  cerr << "@@ Inspecting these tables..." << "\n";
  int tblHandle = schema.GetTableBHandle();
  vtkStdString queryStr;
  for ( tblHandle = 0; tblHandle < numTbl; ++ tblHandle )
  {
    vtkStdString tblName( schema->GetTableNameFromHandle( tblHandle ) );
    cerr << "   Table: "
         << tblName
         << "\n";

    if ( tblName != tables[tblHandle] )
    {
      cerr << "Fetched an incorrect name: "
           << tables[tblHandle]
           << " != "
           << tblName
           << endl;
      query->Delete();
      db->Delete();
      return 1;
    }

    // Check columns
    queryStr = "SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = '";
    queryStr += tblName;
    queryStr += "' order by ordinal_position";
    query->SetQuery( queryStr );
    if ( ! query->Execute() )
    {
      cerr << "Query failed" << endl;
      query->Delete();
      db->Delete();
      return 1;
    }

    int numFields = query->GetNumberOfFields();
    int colHandle = 0;
    for ( ; query->NextRow(); ++ colHandle )
    {
      for ( int field = 0; field < numFields; ++ field )
      {
        if ( field )
        {
          cerr << ", ";
        }
        else // if ( field )
        {
          vtkStdString colName ( schema->GetColumnNameFromHandle( tblHandle, colHandle ) );
          if ( colName != query->DataValue( field ).ToString() )
          {
            cerr << "Found an incorrect column name: "
                 << query->DataValue( field ).ToString()
                 << " != "
                 << colName
                 << endl;
            query->Delete();
            db->Delete();
            return 1;
          }
          cerr << "     Column: ";
        }
        cerr << query->DataValue( field ).ToString().c_str();
      }
      cerr << endl;
    }

    if ( colHandle != schema->GetNumberOfColumnsInTable( tblHandle ) )
    {
      cerr << "Found an incorrect number of columns: "
           << colHandle
           << " != "
           << schema->GetNumberOfColumnsInTable( tblHandle )
           << endl;
      query->Delete();
      db->Delete();
      return 1;
    }
  }

  // 5. Populate these tables using the trigger mechanism
  cerr << "@@ Populating table atable...";

  queryStr = "INSERT INTO atable (somename,somenmbr) VALUES ( 'Bas-Rhin', 67 )";
  query->SetQuery( queryStr );
  if ( ! query->Execute() )
  {
    cerr << "Query failed" << endl;
    query->Delete();
    db->Delete();
    return 1;
  }

  queryStr = "INSERT INTO atable (somename,somenmbr) VALUES ( 'Hautes-Pyrenees', 65 )";
  query->SetQuery( queryStr );
  if ( ! query->Execute() )
  {
    cerr << "Query failed" << endl;
    query->Delete();
    db->Delete();
    return 1;
  }

  queryStr = "INSERT INTO atable (somename,somenmbr) VALUES ( 'Vosges', 88 )";
  query->SetQuery( queryStr );
  if ( ! query->Execute() )
  {
    cerr << "Query failed" << endl;
    query->Delete();
    db->Delete();
    return 1;
  }

  cerr << " done." << endl;

  // 6. Check that the trigger-dependent table has indeed been populated
  cerr << "@@ Checking trigger-dependent table btable...\n";

  queryStr = "SELECT somevalue FROM btable ORDER BY somevalue DESC";
  query->SetQuery( queryStr );
  if ( ! query->Execute() )
  {
    cerr << "Query failed" << endl;
    query->Delete();
    db->Delete();
    return 1;
  }

  cerr << "   Entries in column somevalue of table btable, in descending order:\n";
  static const char *dpts[] = { "88", "67", "65" };
  int numDpt = 0;
  for ( ; query->NextRow(); ++ numDpt )
  {
    if ( query->DataValue( 0 ).ToString() != dpts[numDpt] )
    {
      cerr << "Found an incorrect value: "
           << query->DataValue( 0 ).ToString()
           << " != "
           << dpts[numDpt]
           << endl;
      query->Delete();
      db->Delete();
      return 1;
    }
    cerr << "     "
         << query->DataValue( 0 ).ToString()
         << "\n";
  }

  if ( numDpt != 3 )
  {
    cerr << "Found an incorrect number of entries: "
         << numDpt
         << " != "
         << 3
         << endl;
    query->Delete();
    db->Delete();
    return 1;
  }

  cerr << " done." << endl;

  // 7. Test EscapeString.
  cerr << "@@ Escaping a naughty string...";

  queryStr =
    "INSERT INTO atable (somename,somenmbr) VALUES ( " +
    query->EscapeString( vtkStdString( "Str\"ang'eS\ntring" ), true ) +
    ", 2 )";
  query->SetQuery( queryStr );
  if ( ! query->Execute() )
  {
    cerr << "Query failed" << endl;
    query->Delete();
    db->Delete();
    return 1;
  }

  cerr << " done." << endl;

  // 8. Read back the escaped string to verify it worked.
  cerr << "@@ Reading it back... <";

  queryStr = "SELECT somename FROM atable WHERE somenmbr=2";
  query->SetQuery( queryStr );
  if ( ! query->Execute() )
  {
    cerr << "Query failed" << endl;
    query->Delete();
    db->Delete();
    return 1;
  }

  if ( ! query->NextRow() )
  {
    cerr << "Query returned no results" << endl;
    query->Delete();
    db->Delete();
    return 1;
  }

  cerr << query->DataValue( 0 ).ToString().c_str() << "> ";
  cerr << " done." << endl;

  // 9. Drop tables
  cerr << "@@ Dropping these tables...";

  for ( std::vector<vtkStdString>::iterator it = tables.begin();
        it != tables.end(); ++ it )
  {
    queryStr = "DROP TABLE ";
    queryStr += *it;
    query->SetQuery( queryStr );

    if ( ! query->Execute() )
    {
      cerr << "Query failed" << endl;
      query->Delete();
      db->Delete();
      return 1;
    }
  }

  cerr << " done." << endl;

  // 10. Delete the database until we run the test again
  cerr << "@@ Dropping the database...";

  if ( ! db->DropDatabase( realDatabase.c_str() ) )
  {
    cout << "Drop of \"" << realDatabase.c_str() << "\" failed.\n";
    cerr << "\"" << db->GetLastErrorText() << "\"" << endl;
  }

  cerr << " done." << endl;

  // Clean up
  db->Delete();
  query->Delete();

  return 0;
}