File: classBrowse.cpp

package info (click to toggle)
unixodbc 2.2.14p2-5
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 14,620 kB
  • sloc: ansic: 104,255; cpp: 38,573; sh: 15,958; makefile: 2,728; sql: 1
file content (583 lines) | stat: -rw-r--r-- 16,333 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
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
/**************************************************
 *
 *
 **************************************************
 * This code was created by Peter Harvey @ CodeByDesign.
 * Released under GPL 30.NOV.00
 *
 * Contributions from...
 * -----------------------------------------------
 * Peter Harvey		- pharvey@codebydesign.com
 **************************************************/
#include "classBrowse.h"

char *szHelpQuery = \
"Use this area to quickly specify a simple data filter.\n\n" \
"1. Leave the Expression cells blank to get all data in the table or enter filter Expression(s) to limit the amount of data returned. Expression examples; \n='MyText'\n>23\n" \
"2. Enter Y in the Show cells to get data in that column.\n" \
"3. Control-Click and drag column headers to rearrange the column order.\n" \
"4. Click the Run button to get your results.";

char *szHelpData = \
"This area contains the results from your Query. You can;\n" \
"1. Browse the data.\n" \
"2. Export the data in a variety of formats.\n\n" \
"Editing the data is not availible right *now*. Consider using the isql window (click on the Data Source) for this.";

classBrowse::classBrowse( SQLHDBC hDbc, QString qsTable, QWidget *parent, const char *name )
	: QWidget( parent, name, 0 )
{
    qsDataFileName = "";
    this->hDbc	 	= hDbc;
    this->qsTable	= qsTable;
 
    layoutMain = new QVBoxLayout( this );

#ifdef QT_V4LAYOUT
    tableQuery = new Q3Table( 1, 1, this );
#else
    tableQuery = new QTable( 1, 1, this );
#endif
    tableQuery->setColumnMovingEnabled ( TRUE );
    tableQuery->setMinimumSize( 100, 100 );
    
#ifdef QT_V4LAYOUT
    tableData = new Q3Table( 1, 1, this );
#else
    tableData = new QTable( 1, 1, this );
#endif
    tableData->setColumnMovingEnabled ( TRUE );


    labelFilter = new QLabel( "FILTER", this );
#ifdef QT_V4LAYOUT
    labelFilter->setPalette( QPalette( QColor(Qt::lightGray) ) );
    labelFilter->setAlignment( Qt::AlignCenter );
#else
    labelFilter->setPalette( QPalette( QColor(lightGray) ) );
    labelFilter->setAlignment( AlignCenter );
#endif
    layoutMain->addWidget( labelFilter );

    layoutMain->addWidget( tableQuery );

    labelResults = new QLabel( "RESULTS", this );
#ifdef QT_V4LAYOUT
    labelResults->setPalette( QPalette( QColor(Qt::lightGray) ) );
    labelResults->setAlignment( Qt::AlignCenter );
#else
    labelResults->setPalette( QPalette( QColor(lightGray) ) );
    labelResults->setAlignment( AlignCenter );
#endif
    layoutMain->addWidget( labelResults );

    layoutMain->addWidget( tableData, 10 );

    InitQuery();

	setMinimumSize( 50, 50 );
	setMaximumSize( 32767, 32767 );

    QWhatsThis::add( tableQuery, szHelpQuery );
    QWhatsThis::add( tableData, szHelpData );
}

classBrowse::~classBrowse()
{
}

void classBrowse::resizeEvent( QResizeEvent *p )
{
    resize( p->size() );
}


void classBrowse::Clear()         // CLEAR QUERY AND DATA
{
    ClearCells( tableData );
    InitQuery();
}

bool classBrowse::Save()        // DATA
{
    QString qsLabel;

    if ( qsDataFileName == "" )
        return SaveAs();

    // TRY TO SAVE THE FILE
    QFile hFile( qsDataFileName );

    if ( !hFile.open( IO_WriteOnly ) )
	    return FALSE;

    WriteHTML( &hFile, TRUE );

    hFile.close();
    
    qsLabel = "RESULTS (";
    qsLabel += qsDataFileName;
    qsLabel += ")";
    labelResults->setText( qsLabel );

    return TRUE;
}

bool classBrowse::SaveAs()      // DATA
{
    QString qsLabel;

    // LET USER PICK A FILE
    QString qsFile = QFileDialog::getSaveFileName( qsDataFileName );
    if ( qsFile.isNull() )
	    return FALSE;

    // TRY TO SAVE THE FILE
    QFile hFile( qsFile );

    if ( !hFile.open( IO_WriteOnly ) )
	    return FALSE;

    WriteHTML( &hFile, TRUE );

    hFile.close();

    qsDataFileName = qsFile;

    qsLabel = "RESULTS (";
    qsLabel += qsDataFileName;
    qsLabel += ")";
    labelResults->setText( qsLabel );
    
    return TRUE;
}

void classBrowse::InitQuery()
{
	SQLHSTMT        hstmt;
	SQLRETURN		nReturn             = -1;
	SQLCHAR         szTableName[101]	= "";
	SQLCHAR         szColumnName[101]	= "";
	SQLCHAR         szColumnType[101]	= "";
	QString         qsError;
    SQLLEN          nCols               = 0;
    SQLINTEGER      nCol                = 0;
#ifdef QT_V4LAYOUT
    Q3Header         *headerQuery;
    Q3Header         *headerData;
#else
    QHeader         *headerQuery;
    QHeader         *headerData;
#endif

	// CREATE A STATEMENT
	nReturn = SQLAllocStmt( hDbc, &hstmt );
	if ( nReturn != SQL_SUCCESS )
	{
		QMessageBox::warning( this, "Table browser",  "Failed to SQLAllocStmt" );
		return;
	}

	// EXECUTE OUR SQL/CALL
#ifdef QT_V4LAYOUT
	strcpy( (char *)szTableName, qsTable.ascii() );
#else
	strcpy( (char *)szTableName, qsTable.data() );
#endif

	if ( SQL_SUCCESS != (nReturn=SQLColumns( hstmt, 0, 0, 0, 0, szTableName, SQL_NTS, 0, 0 )) )
	{
		QMessageBox::warning( this, "Table browser",  "Failed to SQLColumns" );
		return;
	}

    // PREPARE THE TABLES
    nCol = 0;

    // not all drivers can do this 
    nCols = 0;
    SQLRowCount( hstmt, &nCols );
    if ( nCols <= 0 )
    {
        // work out the number of colums we need
        nCols = 0 ;
        while ( SQL_SUCCEEDED( SQLFetch( hstmt )))
            nCols ++;

        SQLFreeStmt( hstmt, SQL_CLOSE );

        // repeat the SQLTables call
        if ( SQL_SUCCESS != (nReturn=SQLColumns( hstmt, 0, 0, 0, 0, szTableName, SQL_NTS, 0, 0 )) )
        {
            QMessageBox::warning( this, "Table browser",  "Failed to SQLColumns" );
            return;
        }
    }
    tableQuery->setNumCols( nCols );
    tableQuery->setNumRows( 2 );
    tableData->setNumCols( nCols );
    tableData->setNumRows( 0 );
    headerQuery = tableQuery->verticalHeader();
    headerQuery->setLabel( 0, QString( tr("Expression") ) );
    headerQuery->setLabel( 1, QString( tr("Show") ) );
    headerQuery = tableQuery->horizontalHeader();
    headerData = tableData->horizontalHeader();

	// GET RESULTS
	nReturn = SQLFetch( hstmt );
	while ( (nReturn == SQL_SUCCESS || nReturn == SQL_SUCCESS_WITH_INFO) && nCol < nCols )
	{
		nReturn = SQLGetData( hstmt, SQLColumns_COLUMN_NAME, SQL_C_CHAR, &szColumnName[0], sizeof(szColumnName), 0 );
		if ( nReturn != SQL_SUCCESS )
			strcpy( (char *)szColumnName, "Unknown" );

        headerQuery->setLabel( nCol, QString((char*)szColumnName) );
        headerData->setLabel( nCol, QString((char*)szColumnName) );

		nReturn = SQLGetData( hstmt, SQLColumns_TYPE_NAME, SQL_C_CHAR, &szColumnType[0], sizeof(szColumnType), 0 );

		nReturn = SQLFetch( hstmt );
        nCol++;
	}

	// FREE STATEMENT
	nReturn = SQLFreeStmt( hstmt, SQL_DROP );
	if ( nReturn != SQL_SUCCESS )
		QMessageBox::warning( this, "Table browser",  "Failed to SQLFreeStmt" );

    SelectAllColumns();
}

void classBrowse::Exec()        // RUN QUERY
{
    SQLHSTMT    hStmt;
    SQLLEN      nRows;
    SWORD       nColumns;
	char	    szState[10];
	char	    szBuf[700];
	char	    szErrString[800];
	SQLRETURN   nRetVal;
    SQLCHAR     szSQL[32000];

//printf( "[PAH][%s][%d]\n", __FILE__, __LINE__ );

    if ( !CreateSQL() ) 
        return;
    
    ClearCells( tableData );

//    QMessageBox::information( (QWidget *)this, "Table browse", qsSQL );

	// CREATE A STATEMENT
    nRetVal = SQLAllocStmt( hDbc, &hStmt );
    if( SQL_SUCCESS != nRetVal )
    {
		QMessageBox::critical( (QWidget *)this, "Table browse", "Failed: SQLAllocStmt " );
        return;
    }

    strcpy( (char*)szSQL, qsSQL );

    if( SQL_SUCCESS != (nRetVal=SQLPrepare(hStmt, szSQL, SQL_NTS)) )
    {
        nRetVal = SQLError(SQL_NULL_HENV, hDbc, hStmt, (SQLCHAR*)szState, NULL, (SQLCHAR*)szBuf, 700, NULL );
    	if (nRetVal == SQL_SUCCESS)
    		QMessageBox::critical( (QWidget *)this, "Table browse", szBuf);
    	else
    		QMessageBox::critical( (QWidget *)this, "Table browse", "Failed: SQLPrepare " );
        SQLFreeStmt( hStmt, SQL_DROP );
		
        QMessageBox::information( (QWidget *)this, "Table browse", qsSQL );
        return;
    }

    // EXECUTE
    if( SQL_SUCCESS != (nRetVal=SQLExecute(hStmt)) )
    {
    	nRetVal = SQLError(SQL_NULL_HENV, hDbc, hStmt, (SQLCHAR*)szState, NULL, (SQLCHAR*)szBuf, 700, NULL );
    	if (nRetVal == SQL_SUCCESS)
    		QMessageBox::critical( (QWidget *)this, "Table browse", szBuf);
    	else
    		QMessageBox::critical( (QWidget *)this, "Table browse", "Failed: SQLExecute " );
        SQLFreeStmt( hStmt, SQL_DROP );
        return;
    }

    // GET NUMBER OF ROWS AFFECTED
    if ( (nRetVal = SQLRowCount( hStmt, &nRows )) != SQL_SUCCESS )
        nRows = 0;

    // Default Values
    if ( nRows == SQL_NO_ROW_NUMBER )
        nRows = 10000; // give a resonable number back
    // Note this code could be changed to use a ListView and therefore would not need to
    // know the result set size upfront....

    // GET NUMBER OF COLUMNS RETURNED
    if ( (nRetVal = SQLNumResultCols( hStmt, &nColumns )) != SQL_SUCCESS )
        nColumns = 0;

//printf( "[PAH][%s][%d]\n", __FILE__, __LINE__ );
    if ( nRows > 0 )
        tableData->setNumRows( nRows );

    tableData->setNumCols( nColumns );
//printf( "[PAH][%s][%d] nColumns=%d nRows=%d\n", __FILE__, __LINE__, nColumns, nRows );
//printf( "[PAH][%s][%d]\n", __FILE__, __LINE__ );

    // GET A RESULTS HEADER (column headers)
    ExecHeader( hStmt, nColumns );

    // GET A RESULTS BODY (data)
    nRows = ExecBody( hStmt, nColumns );

    // Show the correct number of rows to make the gui look correct
    if ( nRows > 0 )
        tableData->setNumRows( nRows );

    // FREE STATEMENT
    nRetVal = SQLFreeStmt( hStmt, SQL_DROP );
    if( SQL_SUCCESS != nRetVal )
		QMessageBox::critical( (QWidget *)this, "Table browse", "Failed: SQLFreeStmt " );

    //printf( "[PAH][%s][%d]\n", __FILE__, __LINE__ );
}

void classBrowse::ExecHeader( SQLHSTMT hStmt, SWORD nColumns )
{
	int				nCol;
	SQLCHAR			szColumnName[101]	= "";	
#ifdef QT_V4LAYOUT
    Q3Header         *header;
#else
    QHeader         *header;
#endif
    
//printf( "[PAH][%s][%d]\n", __FILE__, __LINE__ );

    header = tableData->horizontalHeader();
	for( nCol = 0; nCol < nColumns; nCol++ )
	{
		SQLColAttribute( hStmt, nCol+1, SQL_DESC_LABEL, szColumnName, sizeof(szColumnName), 0, 0 );
        header->setLabel( nCol, QString( (char*)szColumnName ) );
	}

//printf( "[PAH][%s][%d]\n", __FILE__, __LINE__ );

}

int classBrowse::ExecBody( SQLHSTMT hStmt, SWORD nColumns )
{
    int         	nRetVal            	= 0;
    SQLUSMALLINT    nCol            	= 0;
	SQLLEN  		nIndicator;
	char			szColumn[300];
	int				nRow 				= 0;

//printf( "[PAH][%s][%d]\n", __FILE__, __LINE__ );

    // PROCESS ALL ROWS
    while( SQL_SUCCESS == (nRetVal=SQLFetch(hStmt)) || SQL_SUCCESS_WITH_INFO == nRetVal )
    {
		nRow++;
        // PROCESS ALL COLUMNS
        for( nCol = 1; nCol <= nColumns; nCol++ )
        {
            nRetVal = SQLGetData( hStmt, nCol, SQL_C_CHAR, (SQLPOINTER)szColumn, sizeof(szColumn)-1, &nIndicator );
            if ( nRetVal == SQL_SUCCESS && nIndicator != SQL_NULL_DATA )
                tableData->setText( nRow-1, nCol-1, QString( szColumn ) );
            else
                // Print a dash to represent NULL data as opposed to real blanks
                tableData->setText( nRow-1, nCol-1, QString( "-" ) );

        }
    }

//printf( "[PAH][%s][%d]\n", __FILE__, __LINE__ );
    return nRow ; // return the actual number of rows in the result set
}


bool classBrowse::CreateSQL()
{
    int nCol  = 0;
    int nCols = tableQuery->numCols();
#ifdef QT_V4LAYOUT
    Q3Header *header = tableQuery->horizontalHeader();
#else
    QHeader *header = tableQuery->horizontalHeader();
#endif
    QString qsColumns           = "";
    QString qsWhereExpressions  = "";
    QString qsAnd               = "";
    QString qsWhere             = " \nWHERE ";
    QString qsComma             = "";
    QString qsColumn            = "";
    QString qsExpression        = "";
    QString qsShow              = "";

//printf( "[PAH][%s][%d]\n", __FILE__, __LINE__ );

    for ( nCol=0; nCol<nCols; nCol++ ) 
    {
        qsColumn            = header->label( nCol );
        qsColumn.prepend('"').append('"') ;  // Quote column name in case it matches SQL keyword
        qsExpression        = tableQuery->text( QUERY_ROW_EXPRESSION, nCol );
        qsShow              = tableQuery->text( QUERY_ROW_SHOW, nCol );

#ifdef QT_V4LAYOUT
        if ( !qsShow.isNull() && qsShow != "" )
#else
        if ( qsShow && qsShow != "" )
#endif
        {
            qsColumns += qsComma;
            qsColumns += qsColumn;
            qsComma = ", ";
        }

#ifdef QT_V4LAYOUT
        if ( !qsExpression.isNull() && qsExpression != "" ) 
#else
        if ( qsExpression && qsExpression != "" ) 
#endif
        {
            qsWhereExpressions += qsWhere;
            qsWhereExpressions += qsAnd;
            qsWhereExpressions += qsColumn;
           qsWhereExpressions += " ";
            qsWhereExpressions += qsExpression;
            qsAnd = " \nAND ";
            qsWhere = "";
        }
    }
    
    if ( qsColumns == "" )
    {
		QMessageBox::warning( (QWidget *)this, "Table browse", "No columns to show. Please specify which columns you want to show." );
        return FALSE;
    }

    qsSQL = "SELECT \n";
    qsSQL += qsColumns; 
    qsSQL += "\nFROM ";
    qsSQL += qsTable;
    qsSQL += qsWhereExpressions;
// ORDER BY is not need here and could cause some queries to fail because of to many columns or
// the total byte size of the columns is to large.
// The columns will be ordered by the order they appear after the select.
// If the GUI is changed to allow different orders, some form of order by would be needed then.
//
//    qsSQL += " ORDER BY ";
//    qsSQL += qsColumns;

//printf( "[PAH][%s][%d]\n", __FILE__, __LINE__ );

    return TRUE;
}

void classBrowse::SelectAllColumns()
{
    int nCol  = 0;
    int nCols = tableQuery->numCols();
#ifdef QT_V4LAYOUT
    Q3Header *header;
#else
    QHeader *header;
#endif

    header = tableQuery->horizontalHeader();
    for ( nCol=0; nCol<nCols; nCol++ ) 
    {
        tableQuery->setText( QUERY_ROW_SHOW, nCol, "Y" );
    }
}

void classBrowse::UnSelectAllColumns()
{
    int nCol  = 0;
    int nCols = tableQuery->numCols();
#ifdef QT_V4LAYOUT
    Q3Header *header;
#else
    QHeader *header;
#endif

    header = tableQuery->horizontalHeader();
    for ( nCol=0; nCol<nCols; nCol++ ) 
    {
        tableQuery->setText( QUERY_ROW_SHOW, nCol, "" );
    }
}

void classBrowse::WriteHTML( QFile *hFile, bool bPage )
{
    int nCol  = 0;
    int nCols = tableData->numCols();
    int nRow  = 0;
    int nRows = tableData->numRows();
#ifdef QT_V4LAYOUT
    Q3Header *header;
#else
    QHeader *header;
#endif

    header = tableData->horizontalHeader();

    if ( bPage )
        hFile->writeBlock( "<HTML><BODY>", sizeof("<HTML><BODY>")-1 );
    
    hFile->writeBlock( "<TABLE>", sizeof("<TABLE>")-1 );

    // HEADER
    hFile->writeBlock( "\n<TR>", sizeof("\n<TR>")-1 );
    for ( nCol=0; nCol<nCols; nCol++ ) 
    {
        hFile->writeBlock( "<TD>", sizeof("<TD>")-1 );
        hFile->writeBlock( header->label( nCol ), header->label( nCol ).length() );
        hFile->writeBlock( "</TD>", sizeof("</TD>")-1 );
    }
    hFile->writeBlock( "</TR>", sizeof("</TR>")-1 );

    // BODY
    for ( nRow=0; nRow<nRows; nRow++ )
    {
        hFile->writeBlock( "\n<TR>", sizeof("\n<TR>")-1 );
        for ( nCol=0; nCol<nCols; nCol++ ) 
        {
            hFile->writeBlock( "\n<TD>", sizeof("\n<TD>")-1 );
            hFile->writeBlock( tableData->text( nRow, nCol ), tableData->text( nRow, nCol ).length() );
            hFile->writeBlock( "</TD>", sizeof("</TD>")-1 );
        }
        hFile->writeBlock( "</TR>", sizeof("</TR>")-1 );
    }

    hFile->writeBlock( "\n</TABLE>", sizeof("\n</TABLE>")-1 );

    if ( bPage )
        hFile->writeBlock( "</BODY></HTML>", sizeof("</BODY></HTML>")-1 );
}



#ifdef QT_V4LAYOUT
void classBrowse::ClearCells( Q3Table *table )
#else
void classBrowse::ClearCells( QTable *table )
#endif
{
    int nCol  = 0;
    int nCols = table->numCols();
    int nRow  = 0;
    int nRows = table->numRows();

    for ( nRow=0; nRow<nRows; nRow++ )
    {
        for ( nCol=0; nCol<nCols; nCol++ ) 
        {
            table->clearCell( nRow, nCol );
        }
    }
}