static int test_prep_exec(FILE *f, sqlite3 *db, const char *q) { sqlite3_stmt *stmt; int result, col, prepare; if ((prepare = sqlite3_prepare_v2(db, q, -1, &stmt, 0)) == SQLITE_OK) { fprintf(f,"Statement prepared.\n"); for (col = 0; col < sqlite3_column_count(stmt); col++) { fprintf(f, "%s ", sqlite3_column_name(stmt, col)); } fprintf(f, "\n"); while ((result = sqlite3_step(stmt)) == SQLITE_ROW) { fprintf(f, "\n"); for (col = 0; col < sqlite3_column_count(stmt); col++) { switch (sqlite3_column_type(stmt, col)) { case 1: fprintf(f, "%i ", sqlite3_column_int(stmt, col)); break; case 2: fprintf(f, "%f ", sqlite3_column_double(stmt, col)); break; case 3: fprintf(f, "%s ", sqlite3_column_text(stmt, col)); break; case 4: fprintf(f, "%s ", (char *)sqlite3_column_blob(stmt, col)); break; case 5: fprintf(f, "(null) "); break; } } } switch (result) { case SQLITE_DONE: fprintf(f, "\n\nDone\n"); break; case SQLITE_OK: fprintf(f, "\n\nOK\n"); break; case SQLITE_ERROR: fprintf(f, "\n\nSQL error or missing database\n"); break; case SQLITE_MISUSE: fprintf(f, "\n\nLibrary used incorrectly\n"); break; default: fprintf(f, "\n\nError code: %i.\nPlease advise Sqlite error codes (http://www.sqlite.org/c3ref/c_abort.html)", result); } fprintf(f, "\n"); } else { fprintf(f, "Error in preparation of query: error no %i\n", prepare); fprintf(f, "\nExtended error code %i.\n", sqlite3_extended_errcode(db)); fprintf(f, "\nExtended error message:\n%s\n\n", sqlite3_errmsg(db)); return prepare; } deinit_temp_structs(); sqlite3_finalize(stmt); return result; }
int delete_restore_point(char *mountpoint,time_t update_time) { time_t next_update_time; int err = 0,cols, col; sqlite3 *handle; char *query, *old_path; const char *val; sqlite3_stmt *stmt; query = (char*) malloc(4*SZ); old_path=(char*) malloc(SZ); err=get_db_handle(mountpoint,&handle); if(err) { printf("\nGot error while trying handle for /"); perror("\n Error getting db handle"); goto error; } snprintf(query,4*SZ,"select max(rp_time) from (select rp_time from %s where rp_time<%ld);",RP_TABLE,update_time); printf("\nquery = %s",query); err = sqlite3_prepare_v2(handle,query,-1,&stmt,0); if(err) { printf("Selecting data from DB Failed in restorepoint\n"); perror("Error"); goto error; } // Read the number of rows fetched cols = sqlite3_column_count(stmt); printf("\nrpcols=%d",cols); err = sqlite3_step(stmt); if(err == SQLITE_ROW) { /* for(col=0 ; col<cols;col++) { val = (const char*)sqlite3_column_text(stmt,col); printf("%d:%s = %s\t",col,sqlite3_column_name(stmt,col),val); } */ val=(const char*)sqlite3_column_text(stmt,0); printf("\nval=%s",val); if(val == NULL) { sqlite3_finalize(stmt); sqlite3_close(handle); next_update_time = 0; } else { next_update_time = atoi(val); } } else { next_update_time = -1; goto error; } snprintf(query,4*SZ,"select * from %s where rp_time=%ld and access_time>%ld ;",BACKUP_TABLE,update_time,next_update_time); printf("\nquery = %s",query); err = sqlite3_prepare_v2(handle,query,-1,&stmt,0); if(err) { printf("Selecting data from DB Failed in restorepoint\n"); perror("Error"); goto error; } // Read the number of rows fetched cols = sqlite3_column_count(stmt); printf("\nrpcols=%d",cols); while(1) { // fetch a row’s status err = sqlite3_step(stmt); if(err == SQLITE_ROW) { printf("\n"); for(col=0 ; col<cols;col++) { val = (const char*)sqlite3_column_text(stmt,col); printf("%d:%s = %s\t",col,sqlite3_column_name(stmt,col),val); } printf("\n"); val=(const char*)sqlite3_column_text(stmt,3); get_old_path(old_path,mountpoint,val); printf("\nDeleting %s",old_path); err = unlink(old_path); if(err) { perror("Error unlinking file"); } } else if(err == SQLITE_DONE) { // All rows finished printf("All rows fetched\n"); break; } else { goto error; } } sqlite3_finalize(stmt); snprintf(query,4*SZ,"delete from %s where rp_time=%ld and access_time>%ld ;",BACKUP_TABLE,update_time,next_update_time); printf("\n%s",query); fprintf(flog,"\n%s",query); err = sqlite3_exec(handle,query,0,0,0); if(err) { printf("Error executing query"); goto error; } snprintf(query,4*SZ,"update %s set rp_time=%ld where rp_time=%ld;",BACKUP_TABLE,next_update_time,update_time); printf("\n%s",query); fprintf(flog,"\n%s",query); err = sqlite3_exec(handle,query,0,0,0); if(err) { printf("Error executing query"); goto error; } snprintf(query,4*SZ,"delete from %s where rp_time=%ld;",RP_TABLE,update_time); printf("\n%s",query); fprintf(flog,"\n%s",query); err = sqlite3_exec(handle,query,0,0,0); if(err) { printf("Error executing query"); goto error; } error: sqlite3_finalize(stmt); sqlite3_close(handle); free(query); free(old_path); return err; }
time_t get_rp_time(char *rpname) { int err = 0,cols; sqlite3 *handle; char *query; const char *val; sqlite3_stmt *stmt; query = (char*) malloc(4*SZ); err=get_db_handle("/",&handle); if(err) { printf("\nGot error while trying handle for /"); perror("\n Error getting db handle"); err = -1; goto error; } sprintf(query,"select rp_time from %s where rp_name='%s';",RP_TABLE,rpname); err = sqlite3_prepare_v2(handle,query,-1,&stmt,0); if(err) { printf("Selecting data from DB Failed in restorepoint\n"); perror("Error"); err = -1; goto error; } // Read the number of rows fetched cols = sqlite3_column_count(stmt); printf("\nrpcols=%d",cols); err = sqlite3_step(stmt); if(err == SQLITE_ROW) { /* for(col=0 ; col<cols;col++) { val = (const char*)sqlite3_column_text(stmt,col); printf("%d:%s = %s\t",col,sqlite3_column_name(stmt,col),val); } */ val=(const char*)sqlite3_column_text(stmt,0); printf("\nval=%s",val); if(val == NULL) { sqlite3_finalize(stmt); sqlite3_close(handle); err = -1; goto error; } err = atoi(val); } else { err = -1; goto error; } error: sqlite3_finalize(stmt); sqlite3_close(handle); free(query); return err; }
static int db_select_parameter_callback(enum db_select_statement_id sid, db_callback callback, void *callback_arg, ...) { /* The life-cycle of a prepared statement object usually goes like this: * * 1. Create the prepared statement object using sqlite3_prepare_v2(). * 2. Bind values to parameters using the sqlite3_bind_*() interfaces. * 3. Run the SQL by calling sqlite3_step() one or more times. * 4. Reset the prepared statement using sqlite3_reset() then go back to step 2. Do this zero or more times. * 5. Destroy the object using sqlite3_finalize(). */ int retval; const int loglevel = config_get_debuglevel(); #define BUFFERSIZE 64 char debug_buffer[BUFFERSIZE] = {0,}; int debug_loglen = BUFFERSIZE; char *debug_log = NULL; if (1 <= loglevel) { debug_log = malloc(BUFFERSIZE); if (NULL == debug_log) { logerror("ERROR: malloc"); qexit(EXIT_FAILURE); } *debug_log = '\0'; } assert(dbhandler); assert(sid < DB_SELECT_ID_MAX); const char *sql = db_select_statement[sid]; sqlite3_stmt *ppstmt; if ( !db_prepared_stmt[sid] ) db_prepared_stmt[sid] = ppstmt = db_statement_prepare(sid); else ppstmt = db_prepared_stmt[sid]; /* evaluate the remaining arguments */ int col = 1; // column position index va_list args; va_start(args, callback_arg); while (*sql) { if ('%' == *sql++) { switch(*sql++) { case 'p': /* found pointer value "%p". The next argument is the * type "void *" */ { assert(0); // TODO need to extend "%p" to "%NNNp" with NNN being decimal number describing the size of 'p' const void *v = va_arg(args, void *); retval = sqlite3_bind_blob(ppstmt, col++, v, -1, SQLITE_STATIC); if ( SQLITE_OK != retval ) { printlog("ERROR: in sql '%s' bind column %d returned: %s", sql, col, sqlite3_errstr(retval)); qexit(EXIT_FAILURE); } if (1 <= loglevel) { snprintf(debug_buffer, BUFFERSIZE-1, ", %p", v); strnbcat(&debug_log, &debug_loglen, debug_buffer); } break; } case 'f': /* found double value "%f". The next argument is the * type "double" */ { double d = va_arg(args, double); retval = sqlite3_bind_double(ppstmt, col++, d); if ( SQLITE_OK != retval ) { printlog("ERROR: in sql '%s' bind column %d returned: %s", sql, col, sqlite3_errstr(retval)); qexit(EXIT_FAILURE); } if (1 <= loglevel) { snprintf(debug_buffer, BUFFERSIZE-1, ", %f", d); strnbcat(&debug_log, &debug_loglen, debug_buffer); } break; } case 's': /* found string value "%s". The next argument is the * type "const char *" */ { const char *s = va_arg(args, char *); retval = sqlite3_bind_text(ppstmt, col++, s, -1, SQLITE_STATIC); if ( SQLITE_OK != retval ) { printlog("ERROR: in sql '%s' bind column %d returned: %s", sql, col, sqlite3_errstr(retval)); qexit(EXIT_FAILURE); } if (1 <= loglevel) { snprintf(debug_buffer, BUFFERSIZE-1, ", %s", s); strnbcat(&debug_log, &debug_loglen, debug_buffer); } break; } case 'd': // fall through case 'i': /* found integer value "%i". The next argument is the * type "int" */ { int i = va_arg(args, int); retval = sqlite3_bind_int(ppstmt, col++, i); if ( SQLITE_OK != retval ) { printlog("ERROR: in sql '%s' bind column %d returned: %s", sql, col, sqlite3_errstr(retval)); qexit(EXIT_FAILURE); } if (1 <= loglevel) { snprintf(debug_buffer, BUFFERSIZE-1, ", %d", i); strnbcat(&debug_log, &debug_loglen, debug_buffer); } break; } case 'l': /* found 64bit integer value "%l". The next argument is the * type "long long int" */ { long long int l = va_arg(args, long long int); retval = sqlite3_bind_int64(ppstmt, col++, l); if ( SQLITE_OK != retval ) { printlog("ERROR: in sql '%s' bind column %d returned: %s", sql, col, sqlite3_errstr(retval)); qexit(EXIT_FAILURE); } if (1 <= loglevel) { snprintf(debug_buffer, BUFFERSIZE-1, ", %lld", l); strnbcat(&debug_log, &debug_loglen, debug_buffer); } break; } case '%': /* found double percent sign "%%". just go on */ break; case '\0': /* percentage sign has been the last character in the string * rewind the string, so the outer while() catches the end of * the string. */ sql--; break; default: /* unknown character found. exit */ printlog("ERROR: unknown character found in sql string '%s', position %ld: %c", db_select_statement[sid], (long int)(sql - db_select_statement[sid]), *sql); qexit(EXIT_FAILURE); } } } va_end(args); debug(1, "db selected %d: '%s%s'", sid, db_select_statement[sid], debug_log); free(debug_log); int try_num = 0; do { retval = sqlite3_step(ppstmt); if (SQLITE_BUSY == retval) try_num++; else if (SQLITE_ROW == retval) { /* there is data available, fetch data and recall step() */ debug(1, "data available: sql '%s'", db_select_statement[sid]); assert(callback); if ( !callback ) { printlog("ERROR: data available but no callback function defined for sql '%s'", db_select_statement[sid]); /* go on with the loop until no more data is available */ } else { /* prepare the callback data */ const int ncol_result = sqlite3_column_count(ppstmt); int *type = calloc(ncol_result, sizeof(*type)); if ( !type ) { printlog("ERROR: not enough memory"); qexit(EXIT_FAILURE); } union callback_result_t *results = calloc(ncol_result, sizeof(*results)); if ( !results ) { printlog("ERROR: not enough memory"); qexit(EXIT_FAILURE); } const char **cols = calloc(ncol_result, sizeof(*cols)); if ( !cols ) { printlog("ERROR: not enough memory"); qexit(EXIT_FAILURE); } int i; for (i = 0; i<ncol_result; i++) { int mytype = type[i] = sqlite3_column_type(ppstmt, i); switch(mytype) { case SQLITE_INTEGER: results[i].integer = sqlite3_column_int64(ppstmt, i); break; case SQLITE_FLOAT: results[i].floating = sqlite3_column_double(ppstmt, i); break; case SQLITE_TEXT: results[i].text = sqlite3_column_text(ppstmt, i); break; case SQLITE_BLOB: results[i].blob = sqlite3_column_blob(ppstmt, i); break; case SQLITE_NULL: break; default: printlog("ERROR: unknown type %d", mytype); qexit(EXIT_FAILURE); } cols[i] = sqlite3_column_name(ppstmt, i); } retval = callback(callback_arg, ncol_result, type, results, cols); //TODO: reuse arrays for the next row free(type); free(results); free(cols); if (retval) { retval = SQLITE_ABORT; break; } } } else break; } while (try_num < DB_MAX_RETRIES); switch(retval) { case SQLITE_BUSY: printlog("ERROR: db busy! Exceeded max calls (%d) to fetch data", try_num); break; case SQLITE_ROW: /* error: there has been data available, * but the program broke out of the loop? */ assert(0); break; case SQLITE_ERROR: /* there has been a data error. Print out and reset() the statement */ { const char *sql = db_select_statement[sid]; printlog("ERROR: stepping sql statement '%s': %s", sql, sqlite3_errstr(retval)); if (db_exit_on_error) { printlog("exiting.."); qexit(EXIT_FAILURE); } else { retval = sqlite3_reset(ppstmt); if (SQLITE_OK != retval) { printlog("ERROR: resetting sql statement '%s': %s", sql, sqlite3_errstr(retval)); } } } break; case SQLITE_MISUSE: /* the statement has been incorrect */ printlog("ERROR: misuse of prepared sql statement '%s'", db_select_statement[sid]); if (db_exit_on_error) { printlog("exiting.."); qexit(EXIT_FAILURE); } break; case SQLITE_ABORT: printlog("ERROR: abort in callback function during steps of sql '%s'", db_select_statement[sid]); qexit(EXIT_FAILURE); break; case SQLITE_OK: case SQLITE_DONE: /* the statement has finished successfully */ retval = sqlite3_reset(ppstmt); if (SQLITE_OK != retval) { const char *sql = db_select_statement[sid]; printlog("ERROR: resetting sql statement '%s': %s", sql, sqlite3_errstr(retval)); qexit(EXIT_FAILURE); } break; } // if ( !db_prepared_stmt[sid] ) // db_statement_finalize(ppstmt); return 0; }
bool ossimGpkgTileRecord::init( sqlite3_stmt* pStmt ) { static const char M[] = "ossimGpkgTileRecord::init"; bool status = false; if ( pStmt ) { const ossim_int32 EXPECTED_COLUMNS = 5; ossim_int32 nCol = sqlite3_column_count( pStmt ); if ( nCol != EXPECTED_COLUMNS ) { ossimNotify(ossimNotifyLevel_WARN) << M << " WARNING:\nUnexpected number of columns: " << nCol << "Expected column count: " << EXPECTED_COLUMNS << std::endl; } if ( nCol >= EXPECTED_COLUMNS ) { ossim_int32 columnsFound = 0; ossim_int32 type = 0; std::string colName; for ( ossim_int32 i = 0; i < nCol; ++i ) { colName = sqlite3_column_name(pStmt, i); type = sqlite3_column_type(pStmt, i); if ( colName.size() ) { if ( ( colName == "id" ) && ( type == SQLITE_INTEGER ) ) { m_id = sqlite3_column_int(pStmt, i); ++columnsFound; } else if ( ( colName == "zoom_level" ) && ( type == SQLITE_INTEGER ) ) { m_zoom_level = sqlite3_column_int(pStmt, i); ++columnsFound; } else if ( ( colName == "tile_column" ) && ( type == SQLITE_INTEGER ) ) { m_tile_column = sqlite3_column_int(pStmt, i); ++columnsFound; } else if ( ( colName == "tile_row" ) && ( type == SQLITE_INTEGER ) ) { m_tile_row = sqlite3_column_int(pStmt, i); ++columnsFound; } else if ( ( colName == "tile_data" ) && ( type == SQLITE_BLOB ) ) { ++columnsFound; if ( m_copy_tile_flag ) { ossim_int32 bytes = sqlite3_column_bytes( pStmt, i ); if ( bytes ) { //--- // Copy the tile data as it will go away on the next: // sqlite3_step(), sqlite3_reset() or sqlite3_finalize() //--- m_tile_data.resize( bytes ); std::memcpy( (void*)&m_tile_data.front(), sqlite3_column_blob( pStmt, i ), bytes ); } } } else { ossimNotify(ossimNotifyLevel_WARN) << M << " Unexpected column type[" << i << "]: " << type << std::endl; break; } } // Matches: if ( colName.size() ) if ( columnsFound == EXPECTED_COLUMNS ) { status = true; break; } } // Matches: for ( int i = 0; i < nCol; ++i ) } } // Matches: if ( pStmt ) #if 0 /* Please leave for debug. (drb) */ static bool tracedTile = false; if ( status && !tracedTile ) { tracedTile = true; std::ofstream os; std::string file = "debug-tile."; swith( getTileType() ) { case OSSIM_GPKG_PNG: { file += "png"; break; } case OSSIM_GPKG_JPEG: { file += "jpg"; break; } default: break; } os.open( file.c_str(), ios::out | ios::binary); if ( os.good() ) { os.write( (char*)&m_tile_data.front(), m_tile_data.size() ); } os.close(); }
static void Database_query (LIScrArgs* args) { int i; int col; int row; int ret; int size; const char* query; const char* str; sqlite3* self; LIArcPacket* packet; LIScrData* data; sqlite3_stmt* statement; self = args->self; if (!liscr_args_geti_string (args, 0, &query) && !liscr_args_gets_string (args, "query", &query)) return; /* Create a statement. */ if (sqlite3_prepare_v2 (self, query, -1, &statement, NULL) != SQLITE_OK) { lisys_error_set (EINVAL, "SQL prepare: %s", sqlite3_errmsg (self)); lisys_error_report (); return; } /* Bind variables. */ if (liscr_args_geti_table (args, 1) || liscr_args_gets_table (args, "bind")) { for (i = 1 ; i < sqlite3_bind_parameter_count (statement) + 1 ; i++) { /* We got a table that has the bound variables in fields matching the indices of the bound variables. We can simply loop through the table and use the binding index as the key. */ lua_pushnumber (args->lua, i); lua_gettable (args->lua, -2); switch (lua_type (args->lua, -1)) { /* Bind numbers as doubles. */ case LUA_TNUMBER: if (sqlite3_bind_double (statement, i, lua_tonumber (args->lua, -1)) != SQLITE_OK) { lisys_error_set (EINVAL, "SQL bind: %s", sqlite3_errmsg (self)); lisys_error_report (); sqlite3_finalize (statement); return; } break; /* Bind strings as text. */ case LUA_TSTRING: if (sqlite3_bind_text (statement, i, lua_tostring (args->lua, -1), -1, SQLITE_TRANSIENT) != SQLITE_OK) { lisys_error_set (EINVAL, "SQL bind: %s", sqlite3_errmsg (self)); lisys_error_report (); sqlite3_finalize (statement); return; } break; /* Bind packets as blobs. */ case LUA_TUSERDATA: data = liscr_isdata (args->lua, -1, LISCR_SCRIPT_PACKET); if (data == NULL) break; packet = liscr_data_get_data (data); if (packet->writer != NULL) { if (sqlite3_bind_blob (statement, i, packet->writer->memory.buffer, packet->writer->memory.length, SQLITE_TRANSIENT) != SQLITE_OK) { lisys_error_set (EINVAL, "SQL bind: %s", sqlite3_errmsg (self)); lisys_error_report (); sqlite3_finalize (statement); return; } } else { if (sqlite3_bind_blob (statement, i, packet->reader->buffer, packet->reader->length, SQLITE_TRANSIENT) != SQLITE_OK) { lisys_error_set (EINVAL, "SQL bind: %s", sqlite3_errmsg (self)); lisys_error_report (); sqlite3_finalize (statement); return; } } break; /* Bind any other values as NULL. */ default: if (sqlite3_bind_null (statement, i) != SQLITE_OK) { lisys_error_set (EINVAL, "SQL bind: %s", sqlite3_errmsg (self)); lisys_error_report (); sqlite3_finalize (statement); return; } break; } lua_pop (args->lua, 1); } lua_pop (args->lua, 1); } /* Execute the statement and process results. */ for (row = 0, ret = sqlite3_step (statement) ; ret != SQLITE_DONE ; ret = sqlite3_step (statement), row++) { /* Check for errors. */ if (ret != SQLITE_ROW) { lisys_error_set (EINVAL, "SQL step: %s", sqlite3_errmsg (self)); lisys_error_report (); sqlite3_finalize (statement); return; } if (!row) liscr_args_set_output (args, LISCR_ARGS_OUTPUT_TABLE_FORCE); /* Create a row table. */ lua_newtable (args->lua); /* Push the columns to the table. */ for (col = 0 ; col < sqlite3_column_count (statement) ; col++) { switch (sqlite3_column_type (statement, col)) { case SQLITE_INTEGER: lua_pushnumber (args->lua, col + 1); lua_pushnumber (args->lua, sqlite3_column_int (statement, col)); lua_settable (args->lua, -3); break; case SQLITE_FLOAT: lua_pushnumber (args->lua, col + 1); lua_pushnumber (args->lua, sqlite3_column_double (statement, col)); lua_settable (args->lua, -3); break; case SQLITE_TEXT: str = (const char*) sqlite3_column_text (statement, col); size = sqlite3_column_bytes (statement, col); lua_pushnumber (args->lua, col + 1); if (size > 0 && str != NULL) lua_pushstring (args->lua, str); else lua_pushstring (args->lua, str); lua_settable (args->lua, -3); break; case SQLITE_BLOB: str = sqlite3_column_blob (statement, col); size = sqlite3_column_bytes (statement, col); packet = liarc_packet_new_readable (str, size); if (packet != NULL) { lua_pushnumber (args->lua, col + 1); data = liscr_data_new (args->script, args->lua, packet, LISCR_SCRIPT_PACKET, liarc_packet_free); if (data != NULL) lua_settable (args->lua, -3); else { lua_pop (args->lua, 1); liarc_packet_free (packet); } } break; case SQLITE_NULL: break; default: lisys_assert (0 && "invalid column type"); break; } } /* Add the row to the return values. */ liscr_args_seti_stack (args); } if (!row) liscr_args_set_output (args, LISCR_ARGS_OUTPUT_TABLE_FORCE); sqlite3_finalize (statement); }
/* ** Run multiple commands of SQL. Similar to sqlite3_exec(), but does not ** stop if an error is encountered. */ static void runSql(sqlite3 *db, const char *zSql, unsigned runFlags){ const char *zMore; sqlite3_stmt *pStmt; while( zSql && zSql[0] ){ zMore = 0; pStmt = 0; sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zMore); if( zMore==zSql ) break; if( runFlags & SQL_TRACE ){ const char *z = zSql; int n; while( z<zMore && ISSPACE(z[0]) ) z++; n = (int)(zMore - z); while( n>0 && ISSPACE(z[n-1]) ) n--; if( n==0 ) break; if( pStmt==0 ){ printf("TRACE: %.*s (error: %s)\n", n, z, sqlite3_errmsg(db)); }else{ printf("TRACE: %.*s\n", n, z); } } zSql = zMore; if( pStmt ){ if( (runFlags & SQL_OUTPUT)==0 ){ while( SQLITE_ROW==sqlite3_step(pStmt) ){} }else{ int nCol = -1; while( SQLITE_ROW==sqlite3_step(pStmt) ){ int i; if( nCol<0 ){ nCol = sqlite3_column_count(pStmt); }else if( nCol>0 ){ printf("--------------------------------------------\n"); } for(i=0; i<nCol; i++){ int eType = sqlite3_column_type(pStmt,i); printf("%s = ", sqlite3_column_name(pStmt,i)); switch( eType ){ case SQLITE_NULL: { printf("NULL\n"); break; } case SQLITE_INTEGER: { printf("INT %s\n", sqlite3_column_text(pStmt,i)); break; } case SQLITE_FLOAT: { printf("FLOAT %s\n", sqlite3_column_text(pStmt,i)); break; } case SQLITE_TEXT: { printf("TEXT [%s]\n", sqlite3_column_text(pStmt,i)); break; } case SQLITE_BLOB: { printf("BLOB (%d bytes)\n", sqlite3_column_bytes(pStmt,i)); break; } } } } } sqlite3_finalize(pStmt); } } }
bool SQLiteResultPrivate::fetchNext(SqlCachedResult::ValueCache &values, int idx, bool initialFetch) { int res; int i; if (skipRow) { // already fetched Q_ASSERT(!initialFetch); skipRow = false; for(int i=0;i<firstRow.count();i++) values[i]=firstRow[i]; return skippedStatus; } skipRow = initialFetch; if(initialFetch) { firstRow.clear(); firstRow.resize(sqlite3_column_count(stmt)); } if (!stmt) { q->setLastError(QSqlError(QCoreApplication::translate("SQLiteResult", "Unable to fetch row"), QCoreApplication::translate("SQLiteResult", "No query"), QSqlError::ConnectionError)); q->setAt(QSql::AfterLastRow); return false; } res = sqlite3_step(stmt); switch(res) { case SQLITE_ROW: // check to see if should fill out columns if (rInf.isEmpty()) // must be first call. initColumns(false); if (idx < 0 && !initialFetch) return true; for (i = 0; i < rInf.count(); ++i) { switch (sqlite3_column_type(stmt, i)) { case SQLITE_BLOB: values[i + idx] = QByteArray(static_cast<const char *>( sqlite3_column_blob(stmt, i)), sqlite3_column_bytes(stmt, i)); break; case SQLITE_INTEGER: values[i + idx] = sqlite3_column_int64(stmt, i); break; case SQLITE_FLOAT: switch(q->numericalPrecisionPolicy()) { case QSql::LowPrecisionInt32: values[i + idx] = sqlite3_column_int(stmt, i); break; case QSql::LowPrecisionInt64: values[i + idx] = sqlite3_column_int64(stmt, i); break; case QSql::LowPrecisionDouble: case QSql::HighPrecision: default: values[i + idx] = sqlite3_column_double(stmt, i); break; }; break; case SQLITE_NULL: values[i + idx] = QVariant(QVariant::String); break; default: values[i + idx] = QString(reinterpret_cast<const QChar *>( sqlite3_column_text16(stmt, i)), sqlite3_column_bytes16(stmt, i) / sizeof(QChar)); break; } } return true; case SQLITE_DONE: if (rInf.isEmpty()) // must be first call. initColumns(true); q->setAt(QSql::AfterLastRow); sqlite3_reset(stmt); return false; case SQLITE_CONSTRAINT: case SQLITE_ERROR: // SQLITE_ERROR is a generic error code and we must call sqlite3_reset() // to get the specific error message. res = sqlite3_reset(stmt); q->setLastError(qMakeError(access, QCoreApplication::translate("SQLiteResult", "Unable to fetch row"), QSqlError::ConnectionError, res)); q->setAt(QSql::AfterLastRow); return false; case SQLITE_MISUSE: case SQLITE_BUSY: default: // something wrong, don't get col info, but still return false q->setLastError(qMakeError(access, QCoreApplication::translate("SQLiteResult", "Unable to fetch row"), QSqlError::ConnectionError, res)); sqlite3_reset(stmt); q->setAt(QSql::AfterLastRow); return false; } return false; }
static int dbd_sqlite3_select_internal(apr_pool_t *pool, apr_dbd_t *sql, apr_dbd_results_t **results, sqlite3_stmt *stmt, int seek) { int ret, retry_count = 0, column_count; size_t i, num_tuples = 0; int increment = 0; apr_dbd_row_t *row = NULL; apr_dbd_row_t *lastrow = NULL; apr_dbd_column_t *column; char *hold = NULL; column_count = sqlite3_column_count(stmt); if (!*results) { *results = apr_pcalloc(pool, sizeof(apr_dbd_results_t)); } (*results)->stmt = stmt; (*results)->sz = column_count; (*results)->random = seek; (*results)->next_row = 0; (*results)->tuples = 0; (*results)->col_names = apr_pcalloc(pool, column_count * sizeof(char *)); (*results)->pool = pool; do { ret = sqlite3_step(stmt); if (ret == SQLITE_BUSY) { if (retry_count++ > MAX_RETRY_COUNT) { ret = SQLITE_ERROR; } else { apr_dbd_mutex_unlock(); apr_sleep(MAX_RETRY_SLEEP); apr_dbd_mutex_lock(); } } else if (ret == SQLITE_ROW) { int length; row = apr_palloc(pool, sizeof(apr_dbd_row_t)); row->res = *results; increment = sizeof(apr_dbd_column_t *); length = increment * (*results)->sz; row->columns = apr_palloc(pool, length); row->columnCount = column_count; for (i = 0; i < (*results)->sz; i++) { column = apr_palloc(pool, sizeof(apr_dbd_column_t)); row->columns[i] = column; /* copy column name once only */ if ((*results)->col_names[i] == NULL) { (*results)->col_names[i] = apr_pstrdup(pool, sqlite3_column_name(stmt, i)); } column->name = (*results)->col_names[i]; column->size = sqlite3_column_bytes(stmt, i); column->type = sqlite3_column_type(stmt, i); column->value = NULL; switch (column->type) { case SQLITE_FLOAT: case SQLITE_INTEGER: case SQLITE_TEXT: hold = (char *) sqlite3_column_text(stmt, i); if (hold) { column->value = apr_pstrmemdup(pool, hold, column->size); } break; case SQLITE_BLOB: hold = (char *) sqlite3_column_blob(stmt, i); if (hold) { column->value = apr_pstrmemdup(pool, hold, column->size); } break; case SQLITE_NULL: break; } } row->rownum = num_tuples++; row->next_row = 0; (*results)->tuples = num_tuples; if ((*results)->next_row == 0) { (*results)->next_row = row; } if (lastrow != 0) { lastrow->next_row = row; } lastrow = row; } } while (ret == SQLITE_ROW || ret == SQLITE_BUSY); if (dbd_sqlite3_is_success(ret)) { ret = 0; } return ret; }
int CCResultSet::columnCount() { return sqlite3_column_count(m_statement->getStatement()); }
/* * runs a query from the query list or returns -1 in int *body_lentgh * should no query be waiting. */ char *query_list_run_query( sqlite3 *database, int *body_length, int *sock, int *monitorid) { sqlite3_stmt *stmt = NULL; int o, columns, colcount=0; const char *zErrmsg = NULL; char *z; char *FullAlloc; unsigned int FullLength = 0; if ( query_start == NULL) { *body_length = -1; return NULL; } struct query_entry *backup; backup = query_start; pthread_mutex_lock(&query_mutex); query_start = query_start->next; pthread_mutex_unlock(&query_mutex); /* we fetched the first item, run a SQL query on it */ o = sqlite3_prepare(database, backup->data, strlen(backup->data), &stmt, &zErrmsg); /* internal query by a monitor ? */ if (backup->monitorid != 0) *monitorid = backup->monitorid; DEBUG(1) syslog(LOG_DEBUG,"query_list_run_query: running %s, monitorid = %i", backup->data, backup->monitorid); columns = sqlite3_column_count( stmt ); FullAlloc = (char *) malloc(sizeof(char)); while(sqlite3_step(stmt) == SQLITE_ROW) { while (colcount < columns) { z=(char *) sqlite3_column_text(stmt, colcount); if (z == NULL) break; FullAlloc = (char *) realloc(FullAlloc, sizeof(char) * (FullLength + strlen(z) + strlen("0000") + 2)); char lenstr[5]; sprintf(lenstr,"%04i", (int) strlen(z)); memcpy(FullAlloc+FullLength, lenstr, 4); int x = 0; while (x < strlen(z)) { // FIXME ! FullAlloc[FullLength+x+ 4] = z[x]; x++; } FullLength=FullLength + strlen(z) + 4; // FIXME ! colcount = colcount + 1; } colcount = 0; } sqlite3_finalize( stmt ); *sock = backup->sock; free(backup->data); free(backup); /* When the result was NULL, we return an identifier */ if (FullLength == 0) { char *str = strdup("No Results."); char *strg = malloc(sizeof(char)*100); sprintf(strg, "%04i%s",(int) strlen(str),str); *body_length= 4+ strlen(str)+1; free(FullAlloc); return(strg); } *body_length = FullLength; return FullAlloc; }
void DBBrowserDB::updateSchema( ) { // qDebug ("Getting list of tables"); sqlite3_stmt *vm; const char *tail; QStringList r; int err=0; QString num; int idxnum =0; int tabnum = 0; idxmap.clear(); tbmap.clear(); lastErrorMessage = QString("no error"); QString statement = "SELECT name, sql " "FROM sqlite_master " "WHERE type='table' ;"; err=sqlite3_prepare(_db, (const char *) statement,statement.length(), &vm, &tail); if (err == SQLITE_OK) { logSQL(statement, kLogMsg_App); while ( sqlite3_step(vm) == SQLITE_ROW ) { num.setNum(tabnum); QString val1, val2; val1 = QString((const char *) sqlite3_column_text(vm, 0)); val2 = QString((const char *) sqlite3_column_text(vm, 1)); tbmap[num] = DBBrowserTable(GetDecodedQString(val1), GetDecodedQString(val2)); tabnum++; } sqlite3_finalize(vm); } else { qDebug ("could not get list of tables: %d, %s",err,sqlite3_errmsg(_db)); } //now get the field list for each table in tbmap tableMap::Iterator it; for ( it = tbmap.begin(); it != tbmap.end(); ++it ) { statement = "PRAGMA TABLE_INFO("; statement.append( (const char *) GetEncodedQString(it.data().getname())); statement.append(");"); logSQL(statement, kLogMsg_App); err=sqlite3_prepare(_db,statement,statement.length(), &vm, &tail); if (err == SQLITE_OK) { it.data(). fldmap.clear(); int e = 0; while ( sqlite3_step(vm) == SQLITE_ROW ) { if (sqlite3_column_count(vm)==6) { QString val1, val2; int ispk= 0; val1 = QString((const char *) sqlite3_column_text(vm, 1)); val2 = QString((const char *) sqlite3_column_text(vm, 2)); ispk = sqlite3_column_int(vm, 5); if (ispk==1) { val2.append(QString(" PRIMARY KEY")); } it.data().addField(e,GetDecodedQString(val1),GetDecodedQString(val2)); e++; } } sqlite3_finalize(vm); } else { lastErrorMessage = QString ("could not get types"); } } statement = "SELECT name, sql " "FROM sqlite_master " "WHERE type='index' "; /*"ORDER BY name;"*/ //finally get indices err=sqlite3_prepare(_db,statement,statement.length(), &vm, &tail); logSQL(statement, kLogMsg_App); if (err == SQLITE_OK) { while ( sqlite3_step(vm) == SQLITE_ROW ) { QString val1, val2; val1 = QString((const char *) sqlite3_column_text(vm, 0)); val2 = QString((const char *) sqlite3_column_text(vm, 1)); num.setNum(idxnum); idxmap[num] = DBBrowserIndex(GetDecodedQString(val1),GetDecodedQString(val2)); idxnum ++; } sqlite3_finalize(vm); } else { lastErrorMessage = QString ("could not get list of indices"); } }
void OGRGeoPackageLayer::BuildFeatureDefn( const char *pszLayerName, sqlite3_stmt *hStmt ) { m_poFeatureDefn = new OGRSQLiteFeatureDefn( pszLayerName ); SetDescription( m_poFeatureDefn->GetName() ); m_poFeatureDefn->SetGeomType(wkbNone); m_poFeatureDefn->Reference(); int nRawColumns = sqlite3_column_count( hStmt ); panFieldOrdinals = (int *) CPLMalloc( sizeof(int) * nRawColumns ); int iCol; for( iCol = 0; iCol < nRawColumns; iCol++ ) { OGRFieldDefn oField( OGRSQLiteParamsUnquote(sqlite3_column_name( hStmt, iCol )), OFTString ); // In some cases, particularly when there is a real name for // the primary key/_rowid_ column we will end up getting the // primary key column appearing twice. Ignore any repeated names. if( m_poFeatureDefn->GetFieldIndex( oField.GetNameRef() ) != -1 ) continue; if( EQUAL(oField.GetNameRef(), "FID") ) { CPLFree(m_pszFidColumn); m_pszFidColumn = CPLStrdup(oField.GetNameRef()); iFIDCol = iCol; } if( m_pszFidColumn != NULL && EQUAL(m_pszFidColumn, oField.GetNameRef())) continue; // The rowid is for internal use, not a real column. if( EQUAL(oField.GetNameRef(),"_rowid_") ) continue; int nColType = sqlite3_column_type( hStmt, iCol ); const char * pszDeclType = sqlite3_column_decltype(hStmt, iCol); // Recognize a geometry column from trying to build the geometry // Usefull for OGRSQLiteSelectLayer if( nColType == SQLITE_BLOB && m_poFeatureDefn->GetGeomFieldCount() == 0 ) { const int nBytes = sqlite3_column_bytes( hStmt, iCol ); if( nBytes > 4 ) { const GByte* pabyGpkg = (const GByte*)sqlite3_column_blob( hStmt, iCol ); GPkgHeader oHeader; if( GPkgHeaderFromWKB(pabyGpkg, &oHeader) == OGRERR_NONE ) { OGRGeomFieldDefn oGeomField(oField.GetNameRef(), wkbUnknown); /* Read the SRS */ OGRSpatialReference *poSRS = m_poDS->GetSpatialRef(oHeader.iSrsId); if ( poSRS ) { oGeomField.SetSpatialRef(poSRS); poSRS->Dereference(); } OGRwkbGeometryType eGeomType = wkbUnknown; if( pszDeclType != NULL ) { eGeomType = GPkgGeometryTypeToWKB(pszDeclType, (oHeader.iDims == 3)); if( eGeomType != wkbNone ) oGeomField.SetType( eGeomType ); } #ifdef SQLITE_HAS_COLUMN_METADATA const char* pszTableName = sqlite3_column_table_name( hStmt, iCol ); if( oGeomField.GetType() == wkbUnknown && pszTableName != NULL ) { OGRGeoPackageLayer* poLayer = (OGRGeoPackageLayer*) m_poDS->GetLayerByName(pszTableName); if( poLayer != NULL && poLayer->GetLayerDefn()->GetGeomFieldCount() > 0) { oGeomField.SetType( poLayer->GetLayerDefn()->GetGeomFieldDefn(0)->GetType() ); } } #endif m_poFeatureDefn->AddGeomFieldDefn(&oGeomField); iGeomCol = iCol; continue; } } } switch( nColType ) { case SQLITE_INTEGER: oField.SetType( OFTInteger ); break; case SQLITE_FLOAT: oField.SetType( OFTReal ); break; case SQLITE_BLOB: oField.SetType( OFTBinary ); break; default: /* leave it as OFTString */; } if (pszDeclType != NULL) { OGRFieldType eFieldType = GPkgFieldToOGR(pszDeclType); if( (int)eFieldType <= OFTMaxType ) oField.SetType(eFieldType); } m_poFeatureDefn->AddFieldDefn( &oField ); panFieldOrdinals[m_poFeatureDefn->GetFieldCount() - 1] = iCol; } }
SQRes SQLite::exec(LPCSTR sql) const { SQRes sqres; SQLiteResult* result = NEW SQLiteResult(); sqres.set(result); result->m_columnNow = -1; result->m_error = false; if(!m_sqlite) { result->m_error = true; result->m_message = "Not DB."; return sqres; } //SQL文が入っているかチェック if(!sql) return sqres; String work; if(m_sjis) { #ifdef _WIN32 SJIStoUTF8(work,sql); #endif sql = work; } sqlite3_stmt *stmt = NULL; INT rc = -1; while(sql[0]) { if(stmt) { while(sqlite3_step(stmt) == SQLITE_ROW); sqlite3_finalize(stmt); } rc = sqlite3_prepare(m_sqlite, sql, -1, &stmt, &sql); if(rc != SQLITE_OK) { result->m_error = true; result->m_message = sqlite3_errmsg(m_sqlite); break; } INT cols = sqlite3_column_count(stmt); if(cols) { INT i; bool first = true; result->m_error = false; std::list<std::vector<String> > columnData; while(1) { int w; for(w=0;w<100;w++) { rc = sqlite3_step(stmt); if(rc != SQLITE_BUSY && rc != SQLITE_LOCKED) break; Sleep(100); } if(w == 100) { result->m_error = true; result->m_message = sqlite3_errmsg(m_sqlite); if (m_debugFile) { fprintf(m_debugFile, "QUARY [%s]\n%s\n", sql, result->m_message.c_str()); } break; } if(first) { first = false; result->m_feildName.resize(cols); for(i=0;i<cols;i++) { if(m_sjis) UTF8toSJIS(result->m_feildName[i],sqlite3_column_name(stmt, i)); else result->m_feildName[i] = sqlite3_column_name(stmt, i); result->m_feildReverse[result->m_feildName[i]] = i; } } if(rc != SQLITE_ROW) break; std::vector<String> data(cols); for(i=0;i<cols;i++) { LPCSTR value = (LPCSTR)sqlite3_column_text(stmt,i); if(value) { if(m_sjis) UTF8toSJIS(data[i],value); else data[i] = value; } } columnData.push_back(data); } result->m_arrayData.reserve(columnData.size()); std::list<std::vector<String> >::iterator it; foreach(it,columnData) { result->m_arrayData.push_back(*it); } } }
static int step_tolua(lua_State *L) { SQLiteLuaStmt *ptr = (SQLiteLuaStmt *)checkudata(L, 1, &stmtmetakey, "sqlite.stmt"); if (ptr->stmt == NULL) { lua_pushnil(L); lua_pushliteral(L, "closed database"); return 2; } if (ptr->iseof) { lua_pushnil(L); lua_pushliteral(L, "attempt to step a halted statement"); return 2; } int result = sqlite3_step(ptr->stmt); if (result == SQLITE_ROW) { int col = sqlite3_column_count(ptr->stmt); lua_createtable(L, col, 0); for (int i = 0; i < col; ++i) { switch (sqlite3_column_type(ptr->stmt, i)) { case SQLITE_INTEGER: { i64 l = sqlite3_column_int64(ptr->stmt, i); if (l > UINT_MAX || l < INT_MIN) { char bytes[9]; bytes[0] = 'L'; for (int i = 1; i < 9; ++i) { bytes[9 - i] = (char)(l & 0xff); l >>= 8; } lua_pushlstring(L, bytes, 9); } else { lua_pushnumber(L, (double)l); } } break; case SQLITE_FLOAT: { double d = sqlite3_column_double(ptr->stmt, i); lua_pushnumber(L, d); } break; case SQLITE_TEXT: { const char *str = (const char *)sqlite3_column_text(ptr->stmt, i); if (str == NULL) { lua_pushnil(L); } else { lua_pushstring(L, str); } } break; case SQLITE_BLOB: { const char *blob = (const char *)sqlite3_column_blob(ptr->stmt, i); if (blob == NULL) { lua_pushnil(L); } else { int len = sqlite3_column_bytes(ptr->stmt, i); lua_pushlstring(L, blob, (size_t)len); } } break; default: lua_pushnil(L); }
GAIAGEO_DECLARE int gaiaExportDxf (gaiaDxfWriterPtr dxf, sqlite3 * db_handle, const char *sql, const char *layer_col_name, const char *geom_col_name, const char *label_col_name, const char *text_height_col_name, const char *text_rotation_col_name, gaiaGeomCollPtr geom_filter) { /* exporting a complex DXF by executing an arbitrary SQL query */ sqlite3_stmt *stmt = NULL; int ret; int params; int first_row = 1; int layer_col = -1; int geom_col = -1; int label_col = -1; int text_height_col = -1; int text_rotation_col = -1; int i; unsigned char *p_blob; const unsigned char *blob; int len; const char *layer; const char *label = NULL; gaiaGeomCollPtr geom; gaiaDxfExportPtr aux = NULL; gaiaDxfExportLayerPtr lyr; if (dxf == NULL) return 0; if (dxf->error) return 0; if (dxf->out == NULL) return 0; if (db_handle == NULL) return 0; if (sql == NULL) return 0; if (layer_col_name == NULL) return 0; if (geom_col_name == NULL) return 0; /* attempting to create the SQL prepared statement */ ret = sqlite3_prepare_v2 (db_handle, sql, strlen (sql), &stmt, NULL); if (ret != SQLITE_OK) { spatialite_e ("exportDXF - CREATE STATEMENT error: %s\n", sqlite3_errmsg (db_handle)); goto stop; } params = sqlite3_bind_parameter_count (stmt); if (params > 0 && geom_filter != NULL) { /* parameter binding - Spatial Filter */ sqlite3_reset (stmt); sqlite3_clear_bindings (stmt); for (i = 1; i <= params; i++) { gaiaToSpatiaLiteBlobWkb (geom_filter, &p_blob, &len); ret = sqlite3_bind_blob (stmt, i, p_blob, len, free); if (ret != SQLITE_OK) { spatialite_e ("exportDXF - parameter BIND error: %s\n", sqlite3_errmsg (db_handle)); goto stop; } } } /* pass #1 - sniffing the result set */ while (1) { /* scrolling the result set rows */ ret = sqlite3_step (stmt); if (ret == SQLITE_DONE) break; /* end of result set */ if (ret == SQLITE_ROW) { if (first_row) { /* this one is the first row of the resultset */ for (i = 0; i < sqlite3_column_count (stmt); i++) { /* attempting to identify the resultset columns */ if (strcasecmp (layer_col_name, sqlite3_column_name (stmt, i)) == 0) layer_col = i; if (strcasecmp (geom_col_name, sqlite3_column_name (stmt, i)) == 0) geom_col = i; if (label_col_name != NULL) { if (strcasecmp (label_col_name, sqlite3_column_name (stmt, i)) == 0) label_col = i; } if (text_height_col_name != NULL) { if (strcasecmp (text_height_col_name, sqlite3_column_name (stmt, i)) == 0) text_height_col = i; } if (text_rotation_col_name != NULL) { if (strcasecmp (text_rotation_col_name, sqlite3_column_name (stmt, i)) == 0) text_rotation_col = i; } } if (layer_col < 0) { spatialite_e ("exportDXF - Layer Column not found into the resultset\n"); goto stop; } if (geom_col < 0) { spatialite_e ("exportDXF - Geometry Column not found into the resultset\n"); goto stop; } first_row = 0; aux = alloc_aux_exporter (); } layer = (const char *) sqlite3_column_text (stmt, layer_col); blob = sqlite3_column_blob (stmt, geom_col); len = sqlite3_column_bytes (stmt, geom_col); geom = gaiaFromSpatiaLiteBlobWkb (blob, len); if (geom) { update_aux_exporter (aux, layer, geom); gaiaFreeGeomColl (geom); } } } /* pass #2 - exporting the DXF file */ gaiaDxfWriteHeader (dxf, aux->minx, aux->miny, 0, aux->maxx, aux->maxy, 0); gaiaDxfWriteTables (dxf); lyr = aux->first; while (lyr != NULL) { gaiaDxfWriteLayer (dxf, lyr->layer_name); lyr = lyr->next; } gaiaDxfWriteEndSection (dxf); gaiaDxfWriteEntities (dxf); sqlite3_reset (stmt); while (1) { /* scrolling the result set rows */ int ival; double height = 10.0; double rotation = 0.0; ret = sqlite3_step (stmt); if (ret == SQLITE_DONE) break; /* end of result set */ if (ret == SQLITE_ROW) { layer = (const char *) sqlite3_column_text (stmt, layer_col); if (label_col >= 0) label = (const char *) sqlite3_column_text (stmt, label_col); if (text_height_col >= 0) { if (sqlite3_column_type (stmt, text_height_col) == SQLITE_INTEGER) { ival = sqlite3_column_int (stmt, text_height_col); height = ival; } if (sqlite3_column_type (stmt, text_height_col) == SQLITE_FLOAT) height = sqlite3_column_double (stmt, text_height_col); } if (text_rotation_col >= 0) { if (sqlite3_column_type (stmt, text_rotation_col) == SQLITE_INTEGER) { ival = sqlite3_column_int (stmt, text_rotation_col); rotation = ival; } if (sqlite3_column_type (stmt, text_height_col) == SQLITE_FLOAT) rotation = sqlite3_column_double (stmt, text_rotation_col); } blob = sqlite3_column_blob (stmt, geom_col); len = sqlite3_column_bytes (stmt, geom_col); geom = gaiaFromSpatiaLiteBlobWkb (blob, len); if (geom) { gaiaDxfWriteGeometry (dxf, layer, label, height, rotation, geom); gaiaFreeGeomColl (geom); } } } gaiaDxfWriteEndSection (dxf); gaiaDxfWriteFooter (dxf); sqlite3_finalize (stmt); if (aux != NULL) destroy_aux_exporter (aux); return dxf->count; stop: if (stmt != NULL) sqlite3_finalize (stmt); if (aux != NULL) destroy_aux_exporter (aux); return 0; }
int sqlite3_exec_utf16(sqlite3 *db, const WCHAR *zSql, sqlite3_callback_utf16 xCallback, void *pArg, BindHandle * bind) { int rc = SQLITE_OK; const WCHAR *zLeftover; sqlite3_stmt *pStmt = 0; WCHAR **azCols = 0; int nRetry = 0; int nCallback; if (zSql==0) { return SQLITE_OK; } while((rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0]) { int nCol; WCHAR **azVals = 0; pStmt = 0; rc = sqlite3_prepare16(db, zSql, -1, &pStmt, (const void **) &zLeftover); if (rc!=SQLITE_OK) { continue; } if(!pStmt) { zSql = zLeftover; continue; } if (bind) { for (int i = 0; i < (int)bind->BindObjects.size(); i ++) { switch (bind->BindObjects[i].Type) { case typeString: sqlite3_bind_text16(pStmt, i + 1, (void*) bind->BindObjects[i].String, -1, SQLITE_TRANSIENT); break; default: sqlite3_bind_text16(pStmt, i + 1, (void*) L"(unknown type)", -1, SQLITE_TRANSIENT); break; } } } nCallback = 0; nCol = sqlite3_column_count(pStmt); while (true) { int i; rc = sqlite3_step(pStmt); if (xCallback && (SQLITE_ROW==rc || (SQLITE_DONE==rc && !nCallback ))) { if (0==nCallback) { if (azCols==0) { azCols = (WCHAR**) sqlite3_malloc(2*nCol*sizeof(const WCHAR*) + 1); if (azCols==0) { goto exec_out; } } for (i=0; i<nCol; i++) { azCols[i] = (WCHAR *)sqlite3_column_name16(pStmt, i); } nCallback++; } if (rc==SQLITE_ROW) { azVals = &azCols[nCol]; for (i=0; i<nCol; i++) { azVals[i] = (WCHAR *)sqlite3_column_text16(pStmt, i); } } if (xCallback(pArg, nCol, azVals, azCols)) { rc = SQLITE_ABORT; goto exec_out; } } if (rc!=SQLITE_ROW) { rc = sqlite3_finalize(pStmt); pStmt = 0; if (rc!=SQLITE_SCHEMA) { nRetry = 0; zSql = zLeftover; while (isspace((unsigned char)zSql[0])) { zSql++; } } break; } } sqlite3_free(azCols); azCols = 0; } exec_out: if (pStmt) { sqlite3_finalize(pStmt); } if (azCols) { sqlite3_free(azCols); } return rc; }
SqliteQuery::SqliteQuery(sqlite3_stmt *preparedStatement, bool eof, sqlite3 *db) : preparedStatement_(preparedStatement), db_ (db), eof_(eof) { cols_ = sqlite3_column_count(preparedStatement_); }