//----[ WinMain ]------------------------------------------------------------ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int) { sqlite3* db; sqlite3_open(":memory:", &db); char* errmsg; // create the data structure char sql[2048]; sqlite3_snprintf(2048, sql, "CREATE VIRTUAL TABLE entity_tree USING rtree(id, min_x, max_x, min_z, max_z)"); if (SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, &errmsg)) { DEBUG_INFO("%s", errmsg); return 0; } sqlite3_snprintf(2048, sql, "CREATE TABLE entities (id INTEGER PRIMARY KEY, x REAL, z REAL, entity_ptr BLOB)"); if (SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, &errmsg)) { DEBUG_INFO("%s", errmsg); return 0; } sqlite3_create_function(db, "collision", 2, SQLITE_ANY, NULL, // user data ptr collisionFunctionForSqlite, NULL, NULL); // not an aggregating function static const size_t ENTITIES = 1024; static const size_t SIZE = 4096; enum Statement { STATEMENT_UPDATE_BOUNDARIES, STATEMENT_INSERT_ENTITY, STATEMENT_UPDATE_ENTITY, STATEMENT_QUERY_OVERLAP, STATEMENT_QUERY_COLLISION, NUMBER_OF_STATEMENTS, }; struct Entity { int id; Number x, z; Number collision_rad_sq; Number visible_rad_sq; Number radius; }; const char* statements_text[NUMBER_OF_STATEMENTS] = { "REPLACE INTO entity_tree VALUES (?,?,?,?,?)", "INSERT INTO entities VALUES (?,?,?,?)", // id, x, z, entity_ptr (blob) "UPDATE entities SET x=?, z=? WHERE id=?", // x, z, id "SELECT id FROM entity_tree WHERE id>? AND max_x>=? AND min_x<=? AND max_z>=? AND min_z<=?", // min/max x then min/max z // searcher's id, min x, max x, min z, max z "SELECT entities.id, entity_ptr FROM entities,entity_tree WHERE entities.id=entity_tree.id AND entity_tree.id>? AND collision(entities.x, entities.z) AND max_x>=? AND min_x<=? AND max_z>=? AND min_z<=?" }; sqlite3_stmt* statements[NUMBER_OF_STATEMENTS]; for (int i = 0; i <NUMBER_OF_STATEMENTS; ++i) { int rc; if (SQLITE_OK != (rc=sqlite3_prepare_v2(db, statements_text[i], strlen(statements_text[i]), &statements[i], NULL))) { DEBUG_INFO("%i - %s", i, sqlite3_errmsg(db)); sqlite3_close(db); return false; } } Entity* entities = new Entity[ENTITIES]; for (int i = 0; i < ENTITIES; ++i) { entities[i].id = i; entities[i].x = randf() * SIZE; entities[i].z = randf() * SIZE; float f = 0.5 + randf() * 1.0; entities[i].radius = f; entities[i].collision_rad_sq = f*f; f = 1.5f*randf() + f; entities[i].visible_rad_sq = f*f; sqlite3_bind_double(statements[STATEMENT_INSERT_ENTITY], 1, i); sqlite3_bind_double(statements[STATEMENT_INSERT_ENTITY], 2, entities[i].x.toFloat()); sqlite3_bind_double(statements[STATEMENT_INSERT_ENTITY], 3, entities[i].z.toFloat()); sqlite3_bind_blob(statements[STATEMENT_INSERT_ENTITY], 4, &entities[i], 4, SQLITE_TRANSIENT); sqlite3_step(statements[STATEMENT_INSERT_ENTITY]); sqlite3_reset(statements[STATEMENT_INSERT_ENTITY]); sqlite3_bind_int(statements[STATEMENT_UPDATE_BOUNDARIES], 1, entities[i].id); sqlite3_bind_double(statements[STATEMENT_UPDATE_BOUNDARIES], 2, (entities[i].x - entities[i].radius).toFloat()); sqlite3_bind_double(statements[STATEMENT_UPDATE_BOUNDARIES], 3, (entities[i].x + entities[i].radius).toFloat()); sqlite3_bind_double(statements[STATEMENT_UPDATE_BOUNDARIES], 4, (entities[i].z - entities[i].radius).toFloat()); sqlite3_bind_double(statements[STATEMENT_UPDATE_BOUNDARIES], 5, (entities[i].z + entities[i].radius).toFloat()); sqlite3_step(statements[STATEMENT_UPDATE_BOUNDARIES]); sqlite3_reset(statements[STATEMENT_UPDATE_BOUNDARIES]); } dcx::dcxWin32Clock clock; unsigned int counter = 0; double starter = clock.getAccurateSystemTime(); double ender = starter + 5.0; double time=ender; unsigned int visible_tally = 0; collider_comparisons = 0; #define TIMETRIAL #ifdef TIMETRIAL while ((time = clock.getAccurateSystemTime()) < ender) { #else while (counter < 1) { #endif for (int i = 0; i < ENTITIES; ++i) { collider_x = entities[i].x = randf()*SIZE; collider_z = entities[i].z = randf()*SIZE; collider_rsq = entities[i].collision_rad_sq; sqlite3_bind_int(statements[STATEMENT_UPDATE_ENTITY], 3, entities[i].id); sqlite3_bind_double(statements[STATEMENT_UPDATE_ENTITY], 1, collider_x.toFloat()); sqlite3_bind_double(statements[STATEMENT_UPDATE_ENTITY], 2, collider_z.toFloat()); sqlite3_step(statements[STATEMENT_UPDATE_ENTITY]); sqlite3_reset(statements[STATEMENT_UPDATE_ENTITY]); float minx = (entities[i].x - entities[i].radius).toFloat(); float maxx = (entities[i].x + entities[i].radius).toFloat(); float minz = (entities[i].x - entities[i].radius).toFloat(); float maxz = (entities[i].x + entities[i].radius).toFloat(); sqlite3_bind_int(statements[STATEMENT_UPDATE_BOUNDARIES], 1, entities[i].id); sqlite3_bind_double(statements[STATEMENT_UPDATE_BOUNDARIES], 2, minx); sqlite3_bind_double(statements[STATEMENT_UPDATE_BOUNDARIES], 3, maxx); sqlite3_bind_double(statements[STATEMENT_UPDATE_BOUNDARIES], 4, minz); sqlite3_bind_double(statements[STATEMENT_UPDATE_BOUNDARIES], 5, maxz); sqlite3_step(statements[STATEMENT_UPDATE_BOUNDARIES]); sqlite3_reset(statements[STATEMENT_UPDATE_BOUNDARIES]); #if 0 sqlite3_bind_int(statements[STATEMENT_QUERY_OVERLAP], 1, entities[i].id); sqlite3_bind_double(statements[STATEMENT_QUERY_OVERLAP], 2, (collider_x - entities[i].radius).toFloat()); sqlite3_bind_double(statements[STATEMENT_QUERY_OVERLAP], 3, (collider_x + entities[i].radius).toFloat()); sqlite3_bind_double(statements[STATEMENT_QUERY_OVERLAP], 4, (collider_z - entities[i].radius).toFloat()); sqlite3_bind_double(statements[STATEMENT_QUERY_OVERLAP], 5, (collider_z + entities[i].radius).toFloat()); while (SQLITE_ROW == sqlite3_step(statements[STATEMENT_QUERY_OVERLAP])) { Entity* entity = (Entity*)sqlite3_column_blob(statements[STATEMENT_QUERY_OVERLAP], 1); ++visible_tally; #ifndef TIMETRIAL DEBUG_INFO("collision = %i with %i @ %.02f, %.02f", entities[i].id, sqlite3_column_int(statements[STATEMENT_QUERY_OVERLAP], 0), entity->x.toFloat(), entity->z.toFloat()); #endif } sqlite3_reset(statements[STATEMENT_QUERY_OVERLAP]); #endif sqlite3_bind_int(statements[STATEMENT_QUERY_COLLISION], 1, entities[i].id); sqlite3_bind_double(statements[STATEMENT_QUERY_COLLISION], 2, (collider_x - entities[i].radius).toFloat()); sqlite3_bind_double(statements[STATEMENT_QUERY_COLLISION], 3, (collider_x + entities[i].radius).toFloat()); sqlite3_bind_double(statements[STATEMENT_QUERY_COLLISION], 4, (collider_z - entities[i].radius).toFloat()); sqlite3_bind_double(statements[STATEMENT_QUERY_COLLISION], 5, (collider_z + entities[i].radius).toFloat()); while (SQLITE_ROW == sqlite3_step(statements[STATEMENT_QUERY_COLLISION])) { Entity* entity = (Entity*)sqlite3_column_blob(statements[STATEMENT_QUERY_COLLISION], 1); ++visible_tally; #ifndef TIMETRIAL DEBUG_INFO("collision = %i with %i @ %.02f, %.02f", entities[i].id, sqlite3_column_int(statements[STATEMENT_QUERY_COLLISION], 0), entity->x.toFloat(), entity->z.toFloat()); #endif } sqlite3_reset(statements[STATEMENT_QUERY_COLLISION]); #ifndef TIMETRIAL DEBUG_INFO("comparisons = %i", collider_comparisons); #endif } ++counter; } for (int i = 0; i <NUMBER_OF_STATEMENTS; ++i) { sqlite3_finalize(statements[i]); } sqlite3_close(db); delete[] entities; DEBUG_INFO("%f queries/second; %f visible/entity (comparisons=%i)", counter / (time-starter), visible_tally/double(counter), collider_comparisons); #if 0 char sql[2048]; // create the data structure sqlite3_snprintf(2048, sql, "CREATE TABLE IF NOT EXISTS objects ("\ "id INTEGER PRIMARY KEY,"\ "x INTEGER,"\ "z INTEGER"\ ")"); char* errmsg; if (SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, &errmsg)) { DEBUG_INFO("%s", errmsg); return 0; } sqlite3_snprintf(2048, sql, "CREATE INDEX IF NOT EXISTS "\ "index_x "\ "ON objects (x)"); if (SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, &errmsg)) { DEBUG_INFO("%s", errmsg); sqlite3_close(db); return false; } sqlite3_snprintf(2048, sql, "CREATE INDEX IF NOT EXISTS "\ "index_z "\ "ON objects (z)"); if (SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, &errmsg)) { DEBUG_INFO("%s", errmsg); sqlite3_close(db); return false; } sqlite3_snprintf(2048, sql, "CREATE TABLE IF NOT EXISTS has_seen ("\ "a INTEGER,"\ "b INTEGER"\ ")"); if (SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, &errmsg)) { DEBUG_INFO("%s", errmsg); sqlite3_close(db); return false; } sqlite3_snprintf(2048, sql, "CREATE INDEX IF NOT EXISTS "\ "index_a "\ "ON has_seen (a)"); if (SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, &errmsg)) { DEBUG_INFO("%s", errmsg); sqlite3_close(db); return false; } sqlite3_snprintf(2048, sql, "CREATE INDEX IF NOT EXISTS "\ "index_b "\ "ON has_seen (b)"); if (SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, &errmsg)) { DEBUG_INFO("%s", errmsg); sqlite3_close(db); return false; } sqlite3_snprintf(2048, sql, "CREATE TABLE IF NOT EXISTS results ("\ "id INTEGER PRIMARY KEY,"\ "x INTEGER,"\ "z INTEGER"\ ")"); if (SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, &errmsg)) { DEBUG_INFO("%s", errmsg); return 0; } sqlite3_exec(db, "PRAGMA case_sensitive_like=ON;", NULL, NULL, NULL); sqlite3_exec(db, "PRAGMA synchronous=OFF;", NULL, NULL, NULL); sqlite3_exec(db, "PRAGMA count_changes=OFF;", NULL, NULL, NULL); static const int COUNT = 256; static const int SIZE = 64; // insert a bunch of random objects for (int i = 0; i < COUNT; ++i) { sqlite3_snprintf(2048, sql, "INSERT INTO objects (id, x, z) VALUES "\ "(%i, %i, %i)", i, rand_uint32()%SIZE, rand_uint32()%SIZE); if (SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, &errmsg)) { DEBUG_INFO("%s", errmsg); sqlite3_close(db); return false; } } enum Statement { STATEMENT_CURRENT_VISIBILITY_QUERY, STATEMENT_NEW_VISIBILITY_QUERY, STATEMENT_INSERT_HAS_SEEN, NUMBER_OF_STATEMENTS, }; const char* statements_text[NUMBER_OF_STATEMENTS] = { "SELECT id, x, z FROM objects WHERE (x BETWEEN ? AND ?) AND (z BETWEEN ? AND ?)", "SELECT id FROM objects WHERE (x BETWEEN ? AND ?) AND (z BETWEEN ? AND ?) EXCEPT SELECT (a) FROM has_seen WHERE (b=?)", "INSERT INTO has_seen (a,b) VALUES (?,?)" }; sqlite3_stmt* statements[NUMBER_OF_STATEMENTS]; for (int i = 0; i <NUMBER_OF_STATEMENTS; ++i) { int rc; if (SQLITE_OK != (rc=sqlite3_prepare_v2(db, statements_text[i], strlen(statements_text[i]), &statements[i], NULL))) { DEBUG_INFO("%i-%s", i, sqlite3_errmsg(db)); sqlite3_close(db); return false; } } dcx::dcxWin32Clock clock; unsigned int counter = 0; double starter = clock.getAccurateSystemTime(); double ender = starter + 1.0; double time=ender; unsigned int visible_tally = 0; #define TIMETRIAL #ifdef TIMETRIAL while ((time = clock.getAccurateSystemTime()) < ender) { #else while (counter < 64) { #endif double x = counter; double z = counter; sqlite3_bind_int(statements[STATEMENT_NEW_VISIBILITY_QUERY], 1, x -8); sqlite3_bind_int(statements[STATEMENT_NEW_VISIBILITY_QUERY], 2, x +8); sqlite3_bind_int(statements[STATEMENT_NEW_VISIBILITY_QUERY], 3, z - 8); sqlite3_bind_int(statements[STATEMENT_NEW_VISIBILITY_QUERY], 4, z + 8); sqlite3_bind_int(statements[STATEMENT_NEW_VISIBILITY_QUERY], 5, COUNT); //sqlite3_bind_int(statements[STATEMENT_CURRENT_VISIBILITY_QUERY], 1, x -8); //sqlite3_bind_int(statements[STATEMENT_CURRENT_VISIBILITY_QUERY], 2, x +8); //sqlite3_bind_int(statements[STATEMENT_CURRENT_VISIBILITY_QUERY], 3, z - 8); //sqlite3_bind_int(statements[STATEMENT_CURRENT_VISIBILITY_QUERY], 4, z + 8); #ifndef TIMETRIAL char buffer[512]; sprintf_s(buffer, 512, "\n==== %f, %f ============\n", x, z); OutputDebugString(buffer); #endif while (sqlite3_step(statements[STATEMENT_NEW_VISIBILITY_QUERY]) == SQLITE_ROW) { #ifndef TIMETRIAL char buffer[512]; sprintf_s(buffer, 512, " %lu %8f, %8f\n", sqlite3_column_int(statements[STATEMENT_NEW_VISIBILITY_QUERY], 0), sqlite3_column_double(statements[STATEMENT_NEW_VISIBILITY_QUERY], 1), sqlite3_column_double(statements[STATEMENT_NEW_VISIBILITY_QUERY], 2)); OutputDebugString(buffer); #endif //sqlite3_bind_int(statements[STATEMENT_INSERT_HAS_SEEN], 1, sqlite3_column_int(statements[STATEMENT_NEW_VISIBILITY_QUERY],0)); //sqlite3_bind_int(statements[STATEMENT_INSERT_HAS_SEEN], 2, COUNT); //sqlite3_step(statements[STATEMENT_INSERT_HAS_SEEN]); //sqlite3_reset(statements[STATEMENT_INSERT_HAS_SEEN]); visible_tally++; } sqlite3_reset(statements[STATEMENT_NEW_VISIBILITY_QUERY]); sqlite3_reset(statements[STATEMENT_CURRENT_VISIBILITY_QUERY]); ++counter; } for (int i = 0; i <NUMBER_OF_STATEMENTS; ++i) { sqlite3_finalize(statements[i]); } sqlite3_close(db); DEBUG_INFO("%f queries/second; %f visible/entity (tally=%i)", counter / (time-starter), visible_tally/double(counter), visible_tally); #endif // sqlite3* db; // sqlite3_open(":memory:", &db); // // char sql[2048]; // // // create the data structure // sqlite3_snprintf(2048, // sql, // "CREATE TABLE IF NOT EXISTS objects ("\ // "id INTEGER PRIMARY KEY,"\ // "x REAL,"\ // "z REAL"\ // ")"); // char* errmsg; // if (SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, &errmsg)) { // DEBUG_INFO("%s", errmsg); // return 0; // } // sqlite3_snprintf(2048, // sql, // "CREATE INDEX IF NOT EXISTS "\ // "index_x "\ // "ON objects (x)"); // if (SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, &errmsg)) { // DEBUG_INFO("%s", errmsg); // sqlite3_close(db); // return false; // } // sqlite3_snprintf(2048, // sql, // "CREATE INDEX IF NOT EXISTS "\ // "index_z "\ // "ON objects (z)"); // if (SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, &errmsg)) { // DEBUG_INFO("%s", errmsg); // sqlite3_close(db); // return false; // } // sqlite3_exec(db, "PRAGMA case_sensitive_like=ON;", NULL, NULL, NULL); // sqlite3_exec(db, "PRAGMA synchronous=OFF;", NULL, NULL, NULL); // sqlite3_exec(db, "PRAGMA count_changes=OFF;", NULL, NULL, NULL); // // static const int COUNT = 16000; // static const float SIZE = 2048; // // insert a bunch of random objects // for (int i = 0; i < COUNT; ++i) { // sqlite3_snprintf(2048, // sql, // "INSERT INTO objects (id, x, z) VALUES "\ // "(%i, %f, %f)", // i, // randf()*SIZE, // randf()*SIZE); // if (SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, &errmsg)) { // DEBUG_INFO("%s", errmsg); // sqlite3_close(db); // return false; // } // } // // // create a query // sqlite3_snprintf(2048, // sql, // "SELECT id, x, z FROM objects "\ // "WHERE x>=? AND x<=? AND z>=? AND z<=?"); // sqlite3_stmt* stmt = NULL; // if (SQLITE_OK != sqlite3_prepare_v2(db, // sql, // sizeof(sql), // &stmt, // NULL)) { // return false; // } // // dcx::dcxWin32Clock clock; // unsigned int counter = 0; // double starter = clock.getAccurateSystemTime(); // double ender = starter + 1; // double time; // unsigned int visible_tally = 0; // while ((time = clock.getAccurateSystemTime()) < ender) { // //while (counter < 64) { // double x = 32.0f; // double z = randf()*SIZE; // sqlite3_bind_double(stmt, 1, x - 8.0); // sqlite3_bind_double(stmt, 2, x + 8.0); // sqlite3_bind_double(stmt, 3, z - 8.0); // sqlite3_bind_double(stmt, 4, z + 8.0); // //char buffer[512]; // //sprintf_s(buffer, 512, "\n==== %f, %f ============\n", x, z); // //OutputDebugString(buffer); // while (sqlite3_step(stmt) == SQLITE_ROW) { // //char buffer[512]; // //sprintf_s(buffer, 512, " %lu %8f, %8f\n", sqlite3_column_int(stmt, 0), sqlite3_column_double(stmt, 1), sqlite3_column_double(stmt, 2)); // //OutputDebugString(buffer); // visible_tally++; // } // sqlite3_reset(stmt); // ++counter; // } // sqlite3_finalize(stmt); // sqlite3_close(db); // DEBUG_INFO("%f queries/second; %f visible/entity", counter / (time-starter), visible_tally/double(counter)); }
bool QgsDistanceArea::setEllipsoid( const QString& ellipsoid ) { QString radius, parameter2; // // SQLITE3 stuff - get parameters for selected ellipsoid // sqlite3 *myDatabase; const char *myTail; sqlite3_stmt *myPreparedStatement; int myResult; // Shortcut if ellipsoid is none. if ( ellipsoid == GEO_NONE ) { mEllipsoid = GEO_NONE; return true; } // Check if we have a custom projection, and set from text string. // Format is "PARAMETER:<semi-major axis>:<semi minor axis> // Numbers must be with (optional) decimal point and no other separators (C locale) // Distances in meters. Flattening is calculated. if ( ellipsoid.startsWith( "PARAMETER" ) ) { QStringList paramList = ellipsoid.split( ':' ); bool semiMajorOk, semiMinorOk; double semiMajor = paramList[1].toDouble( & semiMajorOk ); double semiMinor = paramList[2].toDouble( & semiMinorOk ); if ( semiMajorOk && semiMinorOk ) { return setEllipsoid( semiMajor, semiMinor ); } else { return false; } } // Continue with PROJ.4 list of ellipsoids. //check the db is available myResult = sqlite3_open_v2( QgsApplication::srsDbFilePath().toUtf8().data(), &myDatabase, SQLITE_OPEN_READONLY, nullptr ); if ( myResult ) { QgsMessageLog::logMessage( QObject::tr( "Can't open database: %1" ).arg( sqlite3_errmsg( myDatabase ) ) ); // XXX This will likely never happen since on open, sqlite creates the // database if it does not exist. return false; } // Set up the query to retrieve the projection information needed to populate the ELLIPSOID list QString mySql = "select radius, parameter2 from tbl_ellipsoid where acronym='" + ellipsoid + '\''; myResult = sqlite3_prepare( myDatabase, mySql.toUtf8(), mySql.toUtf8().length(), &myPreparedStatement, &myTail ); // XXX Need to free memory from the error msg if one is set if ( myResult == SQLITE_OK ) { if ( sqlite3_step( myPreparedStatement ) == SQLITE_ROW ) { radius = QString( reinterpret_cast< const char * >( sqlite3_column_text( myPreparedStatement, 0 ) ) ); parameter2 = QString( reinterpret_cast< const char * >( sqlite3_column_text( myPreparedStatement, 1 ) ) ); } } // close the sqlite3 statement sqlite3_finalize( myPreparedStatement ); sqlite3_close( myDatabase ); // row for this ellipsoid wasn't found? if ( radius.isEmpty() || parameter2.isEmpty() ) { QgsDebugMsg( QString( "setEllipsoid: no row in tbl_ellipsoid for acronym '%1'" ).arg( ellipsoid ) ); return false; } // get major semiaxis if ( radius.left( 2 ) == "a=" ) mSemiMajor = radius.mid( 2 ).toDouble(); else { QgsDebugMsg( QString( "setEllipsoid: wrong format of radius field: '%1'" ).arg( radius ) ); return false; } // get second parameter // one of values 'b' or 'f' is in field parameter2 // second one must be computed using formula: invf = a/(a-b) if ( parameter2.left( 2 ) == "b=" ) { mSemiMinor = parameter2.mid( 2 ).toDouble(); mInvFlattening = mSemiMajor / ( mSemiMajor - mSemiMinor ); } else if ( parameter2.left( 3 ) == "rf=" ) { mInvFlattening = parameter2.mid( 3 ).toDouble(); mSemiMinor = mSemiMajor - ( mSemiMajor / mInvFlattening ); } else { QgsDebugMsg( QString( "setEllipsoid: wrong format of parameter2 field: '%1'" ).arg( parameter2 ) ); return false; } QgsDebugMsg( QString( "setEllipsoid: a=%1, b=%2, 1/f=%3" ).arg( mSemiMajor ).arg( mSemiMinor ).arg( mInvFlattening ) ); // get spatial ref system for ellipsoid QString proj4 = "+proj=longlat +ellps=" + ellipsoid + " +no_defs"; QgsCoordinateReferenceSystem destCRS; destCRS.createFromProj4( proj4 ); //TODO: createFromProj4 used to save to the user database any new CRS // this behavior was changed in order to separate creation and saving. // Not sure if it necessary to save it here, should be checked by someone // familiar with the code (should also give a more descriptive name to the generated CRS) if ( destCRS.srsid() == 0 ) { QString myName = QString( " * %1 (%2)" ) .arg( QObject::tr( "Generated CRS", "A CRS automatically generated from layer info get this prefix for description" ), destCRS.toProj4() ); destCRS.saveAsUserCRS( myName ); } // // set transformation from project CRS to ellipsoid coordinates mCoordTransform->setDestCRS( destCRS ); mEllipsoid = ellipsoid; // precalculate some values for area calculations computeAreaInit(); return true; }
/* gets the message_id, screen_name and the message */ double get_message_id(int stat,char *sno,char **ptr_screen_name,char **ptr_message) { char *db_name = ".twit_ui_db"; char *statement_t = "select t_id,u_screen_name,t_text from tweets where sno="; char *statement_d = "select d_id,ds_screen_name,d_text from dms where sno="; char *statement_d_sent = "select d_id,dr_screen_name,d_text from dms_sent where sno="; char *final_statement; sqlite3 *db_handle; sqlite3_stmt *temp; double max_id; int sql_errors; char *statement; if(stat == 0) statement = statement_t; else if (stat == 1) statement = statement_d; else if (stat == 2) statement = statement_d_sent; final_statement = malloc(strlen(statement) + 20); sprintf(final_statement,"%s%s;",statement,sno); /* for debugging purposes clear(); printw("%s",final_statement); refresh(); sleep(2); */ if((sql_errors = sqlite3_open(db_name,&db_handle))!= SQLITE_OK) { sqlite3_close(db_handle); sqlite3_finalize(temp); return sql_errors; } if((sql_errors = sqlite3_prepare_v2(db_handle,final_statement,strlen(final_statement),&temp,NULL)) != SQLITE_OK) { sqlite3_close(db_handle); sqlite3_finalize(temp); return sql_errors; } if((sql_errors = sqlite3_step(temp)) != SQLITE_ROW) { sqlite3_close(db_handle); sqlite3_finalize(temp); return sql_errors ; } max_id = sqlite3_column_double(temp,0); sprintf(*ptr_screen_name,"%s",(char *)sqlite3_column_text(temp,1)); sprintf(*ptr_message,"%s",(char *)sqlite3_column_text(temp,2)); /* debug debug debug printw("%.0f",max_id); refresh(); sleep(2); */ sqlite3_close(db_handle); sqlite3_finalize(temp); free(final_statement); return max_id; }
void db_primitive_speed_tests() { printf( "db_primitive_speed_tests()\n" ); // Try to create the database. If it doesnt exist, it would be created // pass a pointer to the pointer to sqlite3, in short sqlite3** int retval = sqlite3_open(DB_MAINTENANCE_FILE,&handle); // If connection failed, handle returns NULL if(retval) { printf("DATABASE CONNECTION FAILED\n"); return; } printf("Connection successful\n"); const char *magnus = "SELECT COUNT(*) from games, positions_2569 WHERE games.white = 'Carlsen, Magnus' " "AND positions_2569.position_hash=44349918 AND games.game_id = positions_2569.game_id"; const char *stamp = "SELECT COUNT(*) from games, positions_3386 WHERE positions_3386.position_hash=2007903353 " "AND games.game_id = positions_3386.game_id"; const char *sicilian="SELECT COUNT(*) from games, positions_391 WHERE positions_391.position_hash=1592470315 " "AND games.game_id = positions_391.game_id"; char buf[1000]; sqlite3_stmt *stmt; // A prepared statement for fetching tables printf( "Database is %s\n", DB_MAINTENANCE_FILE ); int results[5][3]; time_t start_time; time ( &start_time ); for( int i=0; i<5*3; i++ ) { const char *query, *txt; switch(i%3) { case 0: query = magnus; txt="Magnus"; break; case 1: query = stamp; txt="Stamp"; break; case 2: query = sicilian; txt="Sicilian"; break; } sprintf( buf, "Test %d, %s; begin", i/3+1, txt ); report( buf ); retval = sqlite3_prepare_v2( handle, query, -1, &stmt, 0 ); if( retval ) { printf("SELECTING DATA FROM DB FAILED 1\n"); } retval = sqlite3_step(stmt); if( retval != SQLITE_ROW ) printf("SELECTING DATA FROM DB FAILED 2\n"); else { const char *val = (const char*)sqlite3_column_text(stmt,0); printf("Game count=%d\n", atoi(val) ); } sprintf( buf, "Test %d, %s; end", i/3+1, txt ); int expired = report( buf ); results[i/3][i%3] = expired; sqlite3_finalize(stmt); } for( int i=0; i<5*3; i++ ) { int expired = results[i%5][i/5]; if( i%5 == 0 ) { const char *txt; switch(i/5) { case 0: txt="Magnus:"; break; case 1: txt="Stamp:"; break; case 2: txt="Sicilian:"; break; } printf( "%-10s", txt ); } char buf[100]; sprintf( buf, "%d:%02d", expired/60, expired%60 ); printf( "%8s", buf ); if( (i+1)%5 == 0 ) printf( "\n" ); else printf( "," ); } time_t end_time; time ( &end_time ); int total_elapsed = (end_time-start_time); printf( "Total elapsed: %d:%02d\n", total_elapsed/60, total_elapsed%60 ); // Close the handle to free memory sqlite3_close(handle); }
// A real database test void db_primitive_show_games( bool connect ) { printf( "db_primitive_show_games()\n" ); int retval; if( connect ) { // Try to create the database. If it doesnt exist, it would be created // pass a pointer to the pointer to sqlite3, in short sqlite3** retval = sqlite3_open(DB_MAINTENANCE_FILE,&handle); // If connection failed, handle returns NULL if(retval) { printf("DATABASE CONNECTION FAILED\n"); return; } printf("Connection successful\n"); } thc::ChessRules cr; //cr.Forsyth("r1bqk2r/ppp1bppp/2n1pn2/3p4/Q1PP4/P3PN2/1P1N1PPP/R1B1KB1R b KQkq - 0 7"); // Bogo indian position after 8 moves or so 46 games cr.Forsyth("rnbqk2r/pppp1ppp/4pn2/8/1bPP4/2N5/PP2PPPP/R1BQKBNR w KQkq - 2 4"); // Nimzo-Indian start position 24000 games uint32_t hash = cr.HashCalculate(); // select matching rows from the table char buf[100]; sqlite3_stmt *stmt; // A prepared statement for fetching tables sprintf( buf, "SELECT * from positions WHERE position_hash=%d", hash ); retval = sqlite3_prepare_v2( handle, buf, -1, &stmt, 0 ); if( retval ) { printf("SELECTING DATA FROM DB FAILED\n"); } // Read the number of rows fetched int cols = sqlite3_column_count(stmt); std::vector<int> games; report( "Fetching games begin"); while(1) { // fetch a row's status retval = sqlite3_step(stmt); if(retval == SQLITE_ROW) { // SQLITE_ROW means fetched a row // sqlite3_column_text returns a const void* , typecast it to const char* for(int col=0 ; col<cols;col++) { const char *val = (const char*)sqlite3_column_text(stmt,col); //printf("%s:%s\t",sqlite3_column_name(stmt,col),val); if( col == 0 ) { int game_id = atoi(val); games.push_back(game_id); } } //printf("\n"); } else if(retval == SQLITE_DONE) { // All rows finished break; } else { // Some error encountered printf("SOME ERROR ENCOUNTERED\n"); } } report("Fetching games end"); FILE *pgn_out = fopen("/Users/billforster/Documents/games.txt","wt"); report("Dumping games begin"); if( pgn_out ) { for( int i=0; i<games.size(); i++ ) { char buf[100]; if( i%100 == 0 || i==games.size()-1 ) { sprintf( buf,"Game %d",i+1); report(buf); } dump_game( pgn_out, games[i] ); } fclose(pgn_out); } report("Dumping games end"); // Close the handle to free memory sqlite3_close(handle); }
int main(int argc, char **argv) { sqlite3 *db; sphyraena sphy; int i, r; int dbarg = -1; int loadmemory = 0; int pinned_memory = 0; for(i = 1; i < argc; i++) { if(argv[i][0] == '-') switch(argv[i][1]) { case 'd' : dbarg = i + 1; printf("Using database %s\n", argv[i+1]); break; case 'm' : loadmemory = 1; printf("Loading database into memory\n"); break; case 'p' : pinned_memory = 1; printf("Using pinned memory\n"); break; default : printhelp(argv); } } if(dbarg == -1) { printhelp(argv); exit(1); } if(loadmemory) { sqlite3_open(":memory:", &db); char sql[256]; sprintf(sql, "ATTACH DATABASE '%s' AS loadfrom", argv[dbarg]); r = sqlite3_exec(db, sql, NULL, NULL, NULL); sqlite3_exec(db, "CREATE TABLE 'test' AS SELECT * FROM loadfrom.test", NULL, NULL, NULL); sqlite3_exec(db, "DETACH loadfrom", NULL, NULL, NULL); } else { r = sqlite3_open(argv[dbarg], &db); } if(r) { eprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); exit(1); } sphyraena_init(&sphy, db, DATA_SIZE, RESULTS_SIZE, pinned_memory); int err = sphyraena_init(&sphy, db, DATA_SIZE, RESULTS_SIZE, pinned_memory); if(err != SPHYRAENA_SUCCESS) { eprintf(stderr, "Failing to complete init\n"); sqlite3_close(db); exit(1); } #ifndef RUNTEST sphyraena_timer_start(); sphyraena_prepare_data(&sphy, "SELECT * FROM test"); const char* sql = "SELECT id, uniformi FROM test WHERE uniformi < 90"; char* err; sphyraena_timer_start(); r = sqlite3_exec(db, sql, NULL, NULL, &err); double native = sphyraena_timer_end("native execution"); if(err != NULL) { eprintf(stderr, "exec error: %s\n", err); exit(1); } sphyraena_timer_start(); sphyraena_transfer_data(&sphy); sphyraena_select(&sphy, sql, 0); double vm = sphyraena_timer_end("vm execution"); sphyraena_timer_start(); sphyraena_transfer_results(&sphy); double results = sphyraena_timer_end("transfer results"); printf("stream\n"); printf("speedup: %fx\n", native / vm); printf("speedup with results: %fx\n", native / (vm + results)); sphyraena_print_results(&sphy, 40); #else sphyraena_test_queries(&sphy); /* this code tests speedup as a function of stream width sphyraena_test_sizes(&sphy, 0, 1); sphy.stream_width = 2; sphyraena_test_sizes(&sphy, 1, 0); sphy.stream_width = 4; sphyraena_test_sizes(&sphy, 1, 0); sphy.stream_width = 8; sphyraena_test_sizes(&sphy, 1, 0);*/ #endif sphyraena_cleanup(&sphy); sqlite3_close(db); return 0; }
void alarm_server (void) { time_t t, now; struct tm * nowtime; uint8 day[7] = {0}; time(&t); nowtime = localtime(&t); if (nowtime->tm_sec > 0 && nowtime->tm_sec < 60) { sleep(60 - nowtime->tm_sec); } while(1) { DEBUG(" Alarm=======> Alarm server is running!\n"); time(&t); sqlite3 *db = NULL; int rc; char * Errormsg; int row; int col; char ** result; rc = sqlite3_open("/opt/smarthome/smarthome.db", &db); if (rc) { DEBUG("can not open: %s\n ", sqlite3_errmsg(db)); sqlite3_close(db); continue; } else { DEBUG("Open database successfuly!\n"); char sql[300] = "create table alarm_data(" "ID integer primary key, " "sett integer," "hour integer, " "minute integer, " "roomid integer," "yinyue integer," "sun integer, " "mon integer, " "tue integer, " "wed integer, " "thu integer, " "fri integer, " "sat integer, " "tishi varchar(40))"; sqlite3_exec(db, sql, 0, 0, &Errormsg); //读出数据库表中所有数据 strcpy(sql, "select * from alarm_data"); sqlite3_get_table(db, sql, &result, &row, &col, &Errormsg); sqlite3_close(db); time(&now); nowtime = localtime(&now); DEBUG("*******************************\n"); DEBUG("The Time Now is %d:%d\t%d\n", nowtime->tm_hour, nowtime->tm_min, nowtime->tm_wday); DEBUG("*******************************\n"); int i = 0; for (i = 1; i < row + 1; i ++) { DEBUG("-----------------------------debug alarm!\n"); int j = 0; for (j = 0; j < col; j ++) { printf("%s\t", result[i * col + j]); } DEBUG("\n"); if (atoi(result[i * col + 3]) == nowtime->tm_min) { if (atoi(result[i * col + 2]) == nowtime->tm_hour) { day[0] = atoi(result[i * col + 6]); day[1] = atoi(result[i * col + 7]); day[2] = atoi(result[i * col + 8]); day[3] = atoi(result[i * col + 9]); day[4] = atoi(result[i * col + 10]); day[5] = atoi(result[i * col + 11]); day[6] = atoi(result[i * col + 12]); if (day[nowtime->tm_wday] == 1) { alarm_cycle(atoi(result[i * col + 4]), atoi(result[i * col + 5]), result[i * col + 13]); } } } } } //睡眠1分钟 DEBUG(" Alarm=======> before sleep!\n"); sleep(50); time(&now); t += 60; sleep(t - now); } }
AccountManager::~AccountManager() { if (db) sqlite3_close(db); }
/* This function opens the database if it already exists, or creates a new one * if it does not exist. If necessary, a conversion to the latest format is * performed. * This function sets the KMO error string. It returns NULL on failure. */ maildb * maildb_sqlite_new(char *db_name) { int version = 0; sqlite3 *db = NULL; kmod_log_msg(2, "maildb_sqlite_new() called.\n"); /* Open or create the database. */ if (sqlite3_open(db_name, &db)) { kmo_seterror("cannot open %s: %s", db_name, sqlite3_errmsg(db)); goto ERR; } /* Get the database version. */ maildb_get_version(db, &version); /* Initialize new database. */ if (version == 0) { kmod_log_msg(1, "Initializing new KMOD database.\n"); if (maildb_sqlite_initialize(db)) goto ERR; } /* Convert database to version 2. */ else if (version == 1) { kmod_log_msg(1, "Converting KMOD database from version 1 to version 2.\n"); if (maildb_convert_to_version_2(db)) goto ERR; } /* Convert database to version 3. */ else if (version == 2) { kmod_log_msg(1, "Converting KMOD database from version 2 to version 3.\n"); if (maildb_convert_to_version_3(db)) goto ERR; } /* Convert database to version 4. */ else if (version == 3) { kmod_log_msg(1, "Converting KMOD database from version 3 to version 4.\n"); if (maildb_convert_to_version_4(db)) goto ERR; } /* Database is at current version. */ else if (version == 4) { kmod_log_msg(1, "The KMOD database is at version 4.\n"); } /* Database is too recent -- we can't deal with it since we would corrupt it. */ else { kmo_seterror("database version %d is unsupported (latest supported version is %d)", version, 4); goto ERR; } /* Initialize the maildb object. */ maildb *mdb = (maildb *) kmo_calloc(sizeof(maildb)); mdb->db = db; mdb->ops = &maildb_sqlite_ops; /* All good. */ return mdb; ERR: if (db) sqlite3_close(db); return NULL; }
int main(int argc, char *argv[]) { const char * sSQL1 = "create table users(userid varchar(40) PRIMARY KEY, age int, birthday datetime);"; char * pErrMsg = 0; int result = 0; char str; char * SQL; // 连接数据库 sqlite3 * db = 0; int ret = sqlite3_open("E:\\SQLite\\test.db", &db); if (ret != SQLITE_OK) { fprintf(stderr, "无法打开数据库: %s", sqlite3_errmsg(db)); return(1); } else printf("数据库连接成功!\n"); // 执行建表SQL sqlite3_exec(db, sSQL1, 0, 0, &pErrMsg); if (ret != SQLITE_OK){ fprintf(stderr, "SQL error: %s\n", pErrMsg); sqlite3_free(pErrMsg); } // 执行插入记录SQL result = sqlite3_exec(db, "insert into users values('ll',20,'2011-7-23');", 0, 0, &pErrMsg); if (result == SQLITE_OK){ printf("插入数据成功\n"); } result = sqlite3_exec(db, "insert into users values('sdd',20,'2012-9-20');", 0, 0, &pErrMsg); if (result == SQLITE_OK){ printf("插入数据成功\n"); } result = sqlite3_exec(db, "update users set age = 23 where userid = 'll';",0,0,&pErrMsg); if (result == SQLITE_OK){ printf("修改数据成功\n"); } // 插入数据 result = sqlite3_exec(db, "insert into users values('hello',23,'2016-5-21');",0,0,&pErrMsg); if (result == SQLITE_OK){ printf("插入数据成功\n"); } // 查询数据表 printf("查询数据库内容\n"); sqlite3_exec(db, "select * from users;", select_callback, 0, &pErrMsg); // 按条件查找 printf("请输出需要查找的的字段名:"); scanf_s("%s\n",&str); SQL = "select * from users where name like '_str%';"; sqlite3_exec(db,SQL,select_callback,0,&pErrMsg); // 关闭数据库 sqlite3_close(db); db = 0; printf("数据库关闭成功!\n"); return 0; }
void QgsSpatiaLiteSourceSelect::closeSpatiaLiteDb( sqlite3 * handle ) { if ( handle ) sqlite3_close( handle ); }
/** * convert current project to offline project * returns offline project file path */ bool QgsOfflineEditing::convertToOfflineProject( const QString& offlineDataPath, const QString& offlineDbFile, const QStringList& layerIds ) { if ( layerIds.isEmpty() ) { return false; } QString dbPath = QDir( offlineDataPath ).absoluteFilePath( offlineDbFile ); if ( createSpatialiteDB( dbPath ) ) { spatialite_init( 0 ); sqlite3* db; int rc = sqlite3_open( dbPath.toStdString().c_str(), &db ); if ( rc != SQLITE_OK ) { showWarning( tr( "Could not open the spatialite database" ) ); } else { // create logging tables createLoggingTables( db ); mProgressDialog->setTitle( "Converting to offline project" ); mProgressDialog->show(); // copy selected vector layers to SpatiaLite for ( int i = 0; i < layerIds.count(); i++ ) { mProgressDialog->setCurrentLayer( i + 1, layerIds.count() ); QgsMapLayer* layer = QgsMapLayerRegistry::instance()->mapLayer( layerIds.at( i ) ); copyVectorLayer( qobject_cast<QgsVectorLayer*>( layer ), db, dbPath ); } mProgressDialog->hide(); sqlite3_close( db ); // save offline project QString projectTitle = QgsProject::instance()->title(); if ( projectTitle.isEmpty() ) { projectTitle = QFileInfo( QgsProject::instance()->fileName() ).fileName(); } projectTitle += " (offline)"; QgsProject::instance()->title( projectTitle ); QgsProject::instance()->writeEntry( PROJECT_ENTRY_SCOPE_OFFLINE, PROJECT_ENTRY_KEY_OFFLINE_DB_PATH, dbPath ); return true; } } return false; // Workflow: // copy layers to spatialite // create spatialite db at offlineDataPath // create table for each layer // add new spatialite layer // copy features // save as offline project // mark offline layers // remove remote layers // mark as offline project }
void QgsOfflineEditing::synchronize( QgsLegendInterface* legendInterface ) { // open logging db sqlite3* db = openLoggingDb(); if ( db == NULL ) { return; } mProgressDialog->setTitle( "Synchronizing to remote layers" ); mProgressDialog->show(); // restore and sync remote layers QList<QgsMapLayer*> offlineLayers; QMap<QString, QgsMapLayer*> mapLayers = QgsMapLayerRegistry::instance()->mapLayers(); for ( QMap<QString, QgsMapLayer*>::iterator layer_it = mapLayers.begin() ; layer_it != mapLayers.end(); ++layer_it ) { QgsMapLayer* layer = layer_it.value(); if ( layer->customProperty( CUSTOM_PROPERTY_IS_OFFLINE_EDITABLE, false ).toBool() ) { offlineLayers << layer; } } for ( int l = 0; l < offlineLayers.count(); l++ ) { QgsMapLayer* layer = offlineLayers[l]; mProgressDialog->setCurrentLayer( l + 1, offlineLayers.count() ); QString remoteSource = layer->customProperty( CUSTOM_PROPERTY_REMOTE_SOURCE, "" ).toString(); QString remoteProvider = layer->customProperty( CUSTOM_PROPERTY_REMOTE_PROVIDER, "" ).toString(); QString remoteName = layer->name(); remoteName.remove( QRegExp( " \\(offline\\)$" ) ); QgsVectorLayer* remoteLayer = new QgsVectorLayer( remoteSource, remoteName, remoteProvider ); if ( remoteLayer->isValid() ) { // TODO: only add remote layer if there are log entries? QgsVectorLayer* offlineLayer = qobject_cast<QgsVectorLayer*>( layer ); // copy style copySymbology( offlineLayer, remoteLayer ); // register this layer with the central layers registry QgsMapLayerRegistry::instance()->addMapLayer( remoteLayer, true ); // apply layer edit log QString qgisLayerId = layer->id(); QString sql = QString( "SELECT \"id\" FROM 'log_layer_ids' WHERE \"qgis_id\" = '%1'" ).arg( qgisLayerId ); int layerId = sqlQueryInt( db, sql, -1 ); if ( layerId != -1 ) { remoteLayer->startEditing(); // TODO: only get commitNos of this layer? int commitNo = getCommitNo( db ); for ( int i = 0; i < commitNo; i++ ) { // apply commits chronologically applyAttributesAdded( remoteLayer, db, layerId, i ); applyAttributeValueChanges( offlineLayer, remoteLayer, db, layerId, i ); applyGeometryChanges( remoteLayer, db, layerId, i ); } applyFeaturesAdded( offlineLayer, remoteLayer, db, layerId ); applyFeaturesRemoved( remoteLayer, db, layerId ); if ( remoteLayer->commitChanges() ) { // update fid lookup updateFidLookup( remoteLayer, db, layerId ); // clear edit log for this layer sql = QString( "DELETE FROM 'log_added_attrs' WHERE \"layer_id\" = %1" ).arg( layerId ); sqlExec( db, sql ); sql = QString( "DELETE FROM 'log_added_features' WHERE \"layer_id\" = %1" ).arg( layerId ); sqlExec( db, sql ); sql = QString( "DELETE FROM 'log_removed_features' WHERE \"layer_id\" = %1" ).arg( layerId ); sqlExec( db, sql ); sql = QString( "DELETE FROM 'log_feature_updates' WHERE \"layer_id\" = %1" ).arg( layerId ); sqlExec( db, sql ); sql = QString( "DELETE FROM 'log_geometry_updates' WHERE \"layer_id\" = %1" ).arg( layerId ); sqlExec( db, sql ); // reset commitNo QString sql = QString( "UPDATE 'log_indices' SET 'last_index' = 0 WHERE \"name\" = 'commit_no'" ); sqlExec( db, sql ); } else { showWarning( remoteLayer->commitErrors().join( "\n" ) ); } } // remove offline layer QgsMapLayerRegistry::instance()->removeMapLayer( qgisLayerId, true ); // disable offline project QString projectTitle = QgsProject::instance()->title(); projectTitle.remove( QRegExp( " \\(offline\\)$" ) ); QgsProject::instance()->title( projectTitle ); QgsProject::instance()->removeEntry( PROJECT_ENTRY_SCOPE_OFFLINE, PROJECT_ENTRY_KEY_OFFLINE_DB_PATH ); remoteLayer->reload(); //update with other changes } } mProgressDialog->hide(); sqlite3_close( db ); }
void close_db() { sqlite3_close(db); }
SqliteConnection::~SqliteConnection () { if (database) sqlite3_close ((sqlite3*) database); }
/* This function frees the database. */ static void maildb_sqlite_destroy(maildb *mdb) { sqlite3 *db = (sqlite3 *) mdb->db; sqlite3_close(db); free(mdb); }
static void magnatune_get_db_done(GObject *source_object, GAsyncResult *res, gpointer user_data) { gchar *db_path = NULL; gchar *new_db_path = NULL; gchar *content = NULL; gsize length = 0; gboolean ret = FALSE; gboolean first_run = FALSE; GError *err = NULL; GError *err_fn = NULL; OperationSpec *os = NULL; GrlMagnatuneSource *source = NULL; GRL_DEBUG("magnatune_get_db_done"); os = (OperationSpec *) user_data; ret = grl_net_wc_request_finish(GRL_NET_WC(source_object), res, &content, &length, &err_fn); g_object_unref(source_object); if (ret == FALSE) { err = g_error_new(GRL_CORE_ERROR, GRL_CORE_ERROR_MEDIA_NOT_FOUND, _("Failed to get database from magnatune: %s"), err_fn->message); g_error_free(err_fn); if (os != NULL) os->callback(os->source, os->operation_id, NULL, 0, os->user_data, err); } else { db_path = g_build_filename(g_get_user_data_dir(), "grilo-plugins", GRL_SQL_DB, NULL); /* If this is a first run, new database must be ready to use */ if (g_file_test(db_path, G_FILE_TEST_EXISTS) == FALSE) { new_db_path = db_path; first_run = TRUE; } else { g_free(db_path); new_db_path = g_build_filename(g_get_user_data_dir(), "grilo-plugins", GRL_SQL_NEW_DB, NULL); } GRL_WARNING("Saving database to path '%s'", new_db_path); ret = g_file_set_contents(new_db_path, content, length, &err_fn); if (ret == FALSE) { err = g_error_new(GRL_CORE_ERROR, GRL_CORE_ERROR_MEDIA_NOT_FOUND, _("Failed to save database from magnatune: “%s”"), err_fn->message); g_error_free(err_fn); if (os != NULL) os->callback(os->source, os->operation_id, NULL, 0, os->user_data, err); } else if (first_run == TRUE) { source = GRL_MAGNATUNE_SOURCE(os->source); if (source->priv->db == NULL) { GRL_DEBUG("Opening database connection."); if (sqlite3_open(db_path, &source->priv->db) != SQLITE_OK) { GRL_WARNING("Failed to open database '%s': %s", db_path, sqlite3_errmsg(source->priv->db)); sqlite3_close(source->priv->db); source->priv->db = NULL; } } } g_free(new_db_path); } if (ret == TRUE && os != NULL) { /* execute application's request */ os->magnatune_cb(os); } }
int pkg_create_repo(char *path, bool force, bool filelist, void (progress)(struct pkg *pkg, void *data), void *data) { FTS *fts = NULL; struct thd_data thd_data; int num_workers; size_t len; pthread_t *tids = NULL; struct digest_list_entry *dlist = NULL, *cur_dig, *dtmp; sqlite3 *sqlite = NULL; char *errmsg = NULL; int retcode = EPKG_OK; char *repopath[2]; char repodb[MAXPATHLEN + 1]; char repopack[MAXPATHLEN + 1]; char *manifest_digest; FILE *psyml, *fsyml, *mandigests; psyml = fsyml = mandigests = NULL; if (!is_dir(path)) { pkg_emit_error("%s is not a directory", path); return (EPKG_FATAL); } repopath[0] = path; repopath[1] = NULL; len = sizeof(num_workers); if (sysctlbyname("hw.ncpu", &num_workers, &len, NULL, 0) == -1) num_workers = 6; if ((fts = fts_open(repopath, FTS_PHYSICAL|FTS_NOCHDIR, NULL)) == NULL) { pkg_emit_errno("fts_open", path); retcode = EPKG_FATAL; goto cleanup; } snprintf(repodb, sizeof(repodb), "%s/%s", path, repo_packagesite_file); if ((psyml = fopen(repodb, "w")) == NULL) { retcode = EPKG_FATAL; goto cleanup; } if (filelist) { snprintf(repodb, sizeof(repodb), "%s/%s", path, repo_filesite_file); if ((fsyml = fopen(repodb, "w")) == NULL) { retcode = EPKG_FATAL; goto cleanup; } } snprintf(repodb, sizeof(repodb), "%s/%s", path, repo_digests_file); if ((mandigests = fopen(repodb, "w")) == NULL) { retcode = EPKG_FATAL; goto cleanup; } snprintf(repodb, sizeof(repodb), "%s/%s", path, repo_db_file); snprintf(repopack, sizeof(repopack), "%s/repo.txz", path); pack_extract(repopack, repo_db_file, repodb); if ((retcode = pkgdb_repo_open(repodb, force, &sqlite, true)) != EPKG_OK) goto cleanup; if ((retcode = pkgdb_repo_init(sqlite, true)) != EPKG_OK) goto cleanup; thd_data.root_path = path; thd_data.max_results = num_workers; thd_data.num_results = 0; thd_data.stop = false; thd_data.fts = fts; thd_data.read_files = filelist; pthread_mutex_init(&thd_data.fts_m, NULL); thd_data.results = NULL; thd_data.thd_finished = 0; pthread_mutex_init(&thd_data.results_m, NULL); pthread_cond_init(&thd_data.has_result, NULL); pthread_cond_init(&thd_data.has_room, NULL); /* Launch workers */ tids = calloc(num_workers, sizeof(pthread_t)); for (int i = 0; i < num_workers; i++) { pthread_create(&tids[i], NULL, (void *)&read_pkg_file, &thd_data); } for (;;) { struct pkg_result *r; const char *origin; long manifest_pos, files_pos; pthread_mutex_lock(&thd_data.results_m); while ((r = thd_data.results) == NULL) { if (thd_data.thd_finished == num_workers) { break; } pthread_cond_wait(&thd_data.has_result, &thd_data.results_m); } if (r != NULL) { LL_DELETE(thd_data.results, thd_data.results); thd_data.num_results--; pthread_cond_signal(&thd_data.has_room); } pthread_mutex_unlock(&thd_data.results_m); if (r == NULL) { break; } if (r->retcode != EPKG_OK) { continue; } /* do not add if package if already in repodb (possibly at a different pkg_path) */ retcode = pkgdb_repo_cksum_exists(sqlite, r->cksum); if (retcode == EPKG_FATAL) { goto cleanup; } else if (retcode == EPKG_OK) { continue; } if (progress != NULL) progress(r->pkg, data); manifest_pos = ftell(psyml); pkg_emit_manifest_file(r->pkg, psyml, PKG_MANIFEST_EMIT_COMPACT, &manifest_digest); if (filelist) { files_pos = ftell(fsyml); pkg_emit_filelist(r->pkg, fsyml); } else { files_pos = 0; } pkg_get(r->pkg, PKG_ORIGIN, &origin); cur_dig = malloc(sizeof (struct digest_list_entry)); cur_dig->origin = strdup(origin); cur_dig->digest = manifest_digest; cur_dig->manifest_pos = manifest_pos; cur_dig->files_pos = files_pos; LL_PREPEND(dlist, cur_dig); retcode = pkgdb_repo_add_package(r->pkg, r->path, sqlite, manifest_digest, false, true); if (retcode == EPKG_END) { continue; } else if (retcode != EPKG_OK) { goto cleanup; } pkg_free(r->pkg); free(r); } /* Now sort all digests */ LL_SORT(dlist, digest_sort_compare_func); cleanup: if (pkgdb_repo_close(sqlite, retcode == EPKG_OK) != EPKG_OK) { retcode = EPKG_FATAL; } LL_FOREACH_SAFE(dlist, cur_dig, dtmp) { if (retcode == EPKG_OK) { fprintf(mandigests, "%s:%s:%ld:%ld\n", cur_dig->origin, cur_dig->digest, cur_dig->manifest_pos, cur_dig->files_pos); } free(cur_dig->digest); free(cur_dig->origin); free(cur_dig); } if (tids != NULL) { // Cancel running threads if (retcode != EPKG_OK) { pthread_mutex_lock(&thd_data.fts_m); thd_data.stop = true; pthread_mutex_unlock(&thd_data.fts_m); } // Join on threads to release thread IDs for (int i = 0; i < num_workers; i++) { pthread_join(tids[i], NULL); } free(tids); } if (fts != NULL) fts_close(fts); if (fsyml != NULL) fclose(fsyml); if (psyml != NULL) fclose(psyml); if (mandigests != NULL) fclose(mandigests); if (sqlite != NULL) sqlite3_close(sqlite); if (errmsg != NULL) sqlite3_free(errmsg); sqlite3_shutdown(); return (retcode); }
// Close the SQLite database connection. Database::~Database(void) throw() // nothrow { int ret = sqlite3_close(mpSQLite); // Never throw an exception in a destructor SQLITECPP_ASSERT (SQLITE_OK == ret, sqlite3_errmsg(mpSQLite)); // See SQLITECPP_ENABLE_ASSERT_HANDLER }
void QgsScopedSqlite::close_() { if ( db_ ) sqlite3_close( db_ ); }
static int handle_request(struct mg_connection *conn) { char * json_data; cJSON *root; char *json; char *title; char *description; int completed; if (!strcmp(conn->request_method, "POST") && !strncmp(conn->uri, "/api/v1",strlen("/api/v1"))) { printf("api v1\n"); json_data = get_post_data(conn); if(json_data == NULL) { printf("Error json data: NULL\n"); mg_printf_data(conn, "%s","Error jason data:NULL"); free(json_data); return MG_TRUE; // Tell mongoose to close this connection } printf("input json data: %s\n", json_data); root = cJSON_Parse(json_data); if (root == NULL) { mg_printf_data(conn, "%s","Error jason data:Wrong format"); free(json_data); return MG_TRUE; } if (!strncmp(conn->uri,"/api/v1/cars", strlen("/api/v1/cars"))) { int id; char *name; int price; sqlite3 *db; char *err_msg = 0; id = cJSON_GetObjectItem(root,"Id")->valueint; name = cJSON_GetObjectItem(root,"Name")->valuestring; price = cJSON_GetObjectItem(root,"Price")->valueint; printf("id = %d,Name = %s, Price=%d",id,name,price); int rc = sqlite3_open("quanta.db", &db); if (rc != SQLITE_OK) { fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return MG_TRUE; // Tell mongoose to close this connection } char sql[100]; sprintf(sql,"INSERT INTO Cars VALUES(%d, '%s', %d);",id,name,price); rc = sqlite3_exec(db, sql, 0, 0, &err_msg); if (rc != SQLITE_OK ) { fprintf(stderr, "SQL error: %s\n", err_msg); sqlite3_free(err_msg); sqlite3_close(db); return MG_TRUE; // Tell mongoose to close this connection } sqlite3_free(err_msg); sqlite3_close(db); } else { description = cJSON_GetObjectItem(root,"description")->valuestring; title = cJSON_GetObjectItem(root,"title")->valuestring; completed = cJSON_GetObjectItem(root,"completed")->valueint; printf("title = %s,description = %s, completed = %d\n",title,description,completed); } json = cJSON_PrintUnformatted(root); write_json_result(conn, 0, json); free(json_data); return MG_TRUE; // Tell mongoose to close this connection } else if (!strcmp(conn->request_method, "GET") && !strncmp(conn->uri, "/api/v1",strlen("/api/v1"))) { sqlite3 *db; char *err_msg = 0; char sql[100]; int id; char response_buff[100]; printf("get api v1\n"); if(!strncmp(conn->uri,"/api/v1/cars",strlen("/api/v1/cars"))) { sscanf(conn->uri,"/api/v1/cars/%d/",&id); int rc = sqlite3_open("quanta.db", &db); if (rc != SQLITE_OK) { fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return MG_TRUE; // Tell mongoose to close this connection } sprintf(sql,"SELECT * FROM Cars WHERE Id = %d",id); rc = sqlite3_exec(db,sql, callback, response_buff, &err_msg); if (rc != SQLITE_OK ) { fprintf(stderr, "Failed to select data\n"); fprintf(stderr, "SQL error: %s\n", err_msg); sqlite3_free(err_msg); sqlite3_close(db); return MG_TRUE; // Tell mongoose to close this connection } else { mg_printf_data(conn,"%s",response_buff); return MG_TRUE; // Tell mongoose to close this connection } sqlite3_close(db); } else { mg_printf_data(conn, "%s","Not Support"); return MG_TRUE; // Tell mongoose to close this connection } } else if (!strcmp(conn->request_method, "DELETE") && !strncmp(conn->uri, "/api/v1/cars/",strlen("/api/v1/cars/"))) { char sql[100]; int id; sqlite3 *db; char *err_msg = 0; sscanf(conn->uri,"/api/v1/cars/%d",&id); if (id != 0) { int rc = sqlite3_open("quanta.db", &db); if (rc != SQLITE_OK) { fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return MG_TRUE; // Tell mongoose to close this connection } sprintf(sql,"DELETE FROM Cars WHERE ID = %d;",id); rc = sqlite3_exec(db,sql, 0, 0, &err_msg); if (rc != SQLITE_OK ) { fprintf(stderr, "Failed to select data\n"); fprintf(stderr, "SQL error: %s\n", err_msg); sqlite3_free(err_msg); sqlite3_close(db); return MG_TRUE; // Tell mongoose to close this connection } sqlite3_free(err_msg); sqlite3_close(db); mg_printf_data(conn, "Delete %d record from Cars table",id); return MG_TRUE; // Tell mongoose to close this connection } } else if (!strcmp(conn->request_method, "PUT") && !strncmp(conn->uri, "/api/v1/cars/",strlen("/api/v1/cars/"))) { char sql[100]; int id; sqlite3 *db; char *err_msg = 0; char *json_data; sscanf(conn->uri,"/api/v1/cars/%d",&id); if (id != 0) { json_data = get_post_data(conn); if(json_data == NULL) { printf("Error json data: NULL\n"); mg_printf_data(conn, "%s","Error jason data:NULL"); free(json_data); return MG_TRUE; // Tell mongoose to close this connection } printf("input json data: %s\n", json_data); root = cJSON_Parse(json_data); if (root == NULL) { mg_printf_data(conn, "%s","Error jason data:Wrong format"); free(json_data); return MG_TRUE; } char *name; int price; name = cJSON_GetObjectItem(root,"Name")->valuestring; price = cJSON_GetObjectItem(root,"Price")->valueint; printf("id = %d,Name = %s, Price=%d",id,name,price); int rc = sqlite3_open("quanta.db", &db); if (rc != SQLITE_OK) { fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return MG_TRUE; // Tell mongoose to close this connection } char sql[100]; sprintf(sql,"UPDATE Cars SET Name = '%s', Price = %d WHERE ID = %d;",name,price,id); rc = sqlite3_exec(db, sql, 0, 0, &err_msg); if (rc != SQLITE_OK ) { fprintf(stderr, "SQL error: %s\n", err_msg); sqlite3_free(err_msg); sqlite3_close(db); return MG_TRUE; // Tell mongoose to close this connection } sqlite3_free(err_msg); sqlite3_close(db); mg_printf_data(conn, "UPDATE Cars table %d record",id); free(json_data); return MG_TRUE; // Tell mongoose to close this connection } } else { printf("else %d\n",__LINE__); mg_printf_data(conn, "%s","Not Support"); return MG_TRUE; // Tell mongoose to close this connection } return MG_TRUE; // Tell mongoose to close this connection }
/** * 析构函数 * */ ZYSDbc::~ZYSDbc() { if (m_pDb) { sqlite3_close(m_pDb); m_pDb = NULL; } }
// A test program int db_primitive_random_test_program() { // Create an int variable for storing the return code for each call int retval; // A prepered statement for fetching tables sqlite3_stmt *stmt; // Create a handle for database connection, create a pointer to sqlite3 sqlite3 *handle; // try to create the database. If it doesnt exist, it would be created // pass a pointer to the pointer to sqlite3, in short sqlite3** retval = sqlite3_open(DB_MAINTENANCE_FILE,&handle); // If connection failed, handle returns NULL if(retval) { printf("Database connection failed\n"); return -1; } printf("Connection successful\n"); // Create the SQL query for creating a table const char *create_table = "CREATE TABLE IF NOT EXISTS positions (game_id INTEGER, position_hash INTEGER)"; // Execute the query for creating the table retval = sqlite3_exec(handle,create_table,0,0,0); if( retval ) { printf("sqlite3_exec(CREATE) Failed\n"); return -1; } // Delete previous data retval = sqlite3_exec( handle, "DELETE FROM positions",0,0,0); if( retval ) { printf("sqlite3_exec(DELETE) Failed\n"); return -1; } // Insert first row and second row char *errmsg; retval = sqlite3_exec( handle, "INSERT INTO positions VALUES(2,33334444)",0,0,&errmsg); if( retval ) { printf("sqlite3_exec(INSERT 1) Failed %s\n", errmsg ); return -1; } retval = sqlite3_exec( handle, "INSERT INTO positions VALUES(2,4444)",0,0,0); if( retval ) { printf("sqlite3_exec(INSERT 2) Failed\n"); return -1; } // select those rows from the table retval = sqlite3_prepare_v2( handle, "SELECT * from positions", -1, &stmt, 0 ); if( retval ) { printf("Selecting data from DB Failed\n"); return -1; } // Read the number of rows fetched int cols = sqlite3_column_count(stmt); while(1) { // fetch a row's status retval = sqlite3_step(stmt); if(retval == SQLITE_ROW) { // SQLITE_ROW means fetched a row // sqlite3_column_text returns a const void* , typecast it to const char* for(int col=0 ; col<cols;col++) { int val = sqlite3_column_int(stmt,col); printf("%s = 0x%08x\t",sqlite3_column_name(stmt,col),val); } printf("\n"); } else if(retval == SQLITE_DONE) { // All rows finished printf("All rows fetched\n"); break; } else { // Some error encountered printf("Some error encountered\n"); return -1; } } // Close the handle to free memory sqlite3_close(handle); return 0; }
bool SettingsManager::save(const QString& path) { QByteArray data = path.toLatin1(); if(sqlite3_open(data.constData(), &(m_db))) { sqlite3_close(m_db); return false; } #if defined(SQLITE_HAS_CODEC) char tmp[9]; // Grab the obfuscated key sqlite3_obfuscate_key(tmp); if(SQLITE_OK != sqlite3_key((sqlite3*) m_db, tmp, 8)) { memset(tmp, 0, 9); sqlite3_close(m_db); return false; } // Clear the key so it isn't stored in memory memset(tmp, 0, 9); #endif QMap<QString, QString>::iterator siter; QString query = "BEGIN TRANSACTION;\n"; sqllite_resultset_t rs; int rc; for(siter = m_globals.begin(); siter != m_globals.end(); siter++) { QString k = siter.key(); QString v = siter.value(); query += QString("UPDATE Settings SET value='%1' WHERE key='%2';\n"). arg(add_slashes(v)). arg(add_slashes(k)); } QMap<int, QMap<QString, QMap<QString,QStringList> > >::iterator fiter; query += QString("DELETE FROM DeviceLists;\n"); //rs.rows.clear(); //sqlite3_exec((sqlite3*)m_db, qPrintable(query), NULL, NULL, NULL); for(fiter = m_favorites.begin(); fiter != m_favorites.end(); fiter++) { QMap<QString, QMap<QString,QStringList> >::iterator liter; int chip = fiter.key(); for(liter = fiter.value().begin(); liter != fiter.value().end(); liter++) { QString category = liter.key(); QMap<QString,QStringList> lists = liter.value(); QMap<QString,QStringList>::iterator viter; for(viter = lists.begin(); viter != lists.end(); viter++) { QString list = viter.key(); QStringList items = viter.value(); for(int i = 0; i < items.count(); i++) { QString item = items.at(i); query += QString("INSERT INTO DeviceLists (chip,category,key,value) VALUES('%1', '%2', '%3', '%4');\n"). arg(chip). arg(add_slashes(category)). arg(add_slashes(list)). arg(add_slashes(item)); //qDebug() << query; //sqlite3_exec((sqlite3*)m_db, qPrintable(query), NULL, NULL, NULL); } } } } query += "END TRANSACTION;\n"; data = query.toLatin1(); rc = sqlite3_exec((sqlite3*)m_db, data.constData(), NULL, NULL, NULL); sqlite3_close(m_db); if(rc == SQLITE_OK) { // Settings no longer modified after writing back to dB m_settings_modified = false; return true; } return false; }
int main(int argc, const char *const *argv, const char *const *env) { const char *db_filename = "last_message.db"; int dying = 0; sqlite3 *sql = NULL; lmSQL lmdb = {}; apr_socket_t *acc = NULL; apr_pollset_t *pollset = NULL; APR_DO_OR_DIE(apr_app_initialize(&argc, &argv, &env)); atexit(&apr_terminate); apr_pool_t *pool; APR_DO_OR_DIE(apr_pool_create(&pool, NULL)); if (argc > 2) { return print_usage(); } if (argc == 2) { if (strcmp(argv[1], "--help") == 0) { return print_usage(); } db_filename = argv[1]; } int err; if ((err = sqlite3_open(db_filename, &sql)) != SQLITE_OK) { fprintf(stderr, "Can't open DB (%s): %s.\n", db_filename, sqlite3_errstr(err)); return 1; } int rc; char *rc_msg; const char *CREATE_MESSAGE_TABLES = "CREATE TABLE IF NOT EXISTS messages (" " msgid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," " name BLOB NOT NULL," " left INTEGER NOT NULL," " message BLOB NOT NULL" ");"; rc = sqlite3_exec(sql, CREATE_MESSAGE_TABLES, NULL, NULL, &rc_msg); if (rc != SQLITE_OK) { FAIL("Can't create 'messages' table: %s.\n", rc_msg); sqlite3_close(sql); return 1; } const char *CREATE_MESSAGE_SEEN = "CREATE TABLE IF NOT EXISTS seen (" " name BLOB PRIMARY KEY NOT NULL," " msgid INTEGER NOT NULL" ");"; rc = sqlite3_exec(sql, CREATE_MESSAGE_SEEN, NULL, NULL, &rc_msg); if (rc != SQLITE_OK) { FAIL("Can't create 'seen' table: %s.\n", rc_msg); sqlite3_close(sql); return 1; } lmdb.sql = sql; #define LM_SQLITE_PREP(thing, statement) \ do { \ int prep = \ sqlite3_prepare_v2(sql, (statement), -1, (thing), NULL); \ if (prep != SQLITE_OK) { \ FAIL("SQL compilation error: (%s) while compiling " \ "(%s).\n", \ sqlite3_errmsg(sql), statement); \ goto die; \ } \ } while (0) LM_SQLITE_PREP(&lmdb.put, "INSERT INTO messages (name, left, message) " "VALUES (?, ?, ?);"); LM_SQLITE_PREP(&lmdb.get, "SELECT msgid, left, message " "FROM messages " "WHERE name = ? " "ORDER BY msgid ASC;"); LM_SQLITE_PREP(&lmdb.seen_add, "INSERT INTO seen (name, msgid) " "VALUES (?, ?);"); LM_SQLITE_PREP(&lmdb.seen_del, "DELETE FROM seen " "WHERE name = ?;"); LM_SQLITE_PREP(&lmdb.seen_get, "SELECT msgid FROM seen " "WHERE name = ?;"); LM_SQLITE_PREP(&lmdb.drop, "DELETE FROM messages " "WHERE msgid <= ? " " AND name = ?;"); APR_DO_OR_DIE(apr_socket_create(&acc, APR_INET, SOCK_STREAM, 0, pool)); APR_DO_OR_DIE(apr_socket_opt_set(acc, APR_SO_REUSEADDR, 1)); apr_sockaddr_t *l_addr; APR_DO_OR_DIE( apr_sockaddr_info_get(&l_addr, NULL, APR_INET, 1066, 0, pool)); APR_DO_OR_DIE(apr_socket_bind(acc, l_addr)); APR_DO_OR_DIE(apr_socket_listen(acc, 8)); apr_pollfd_t apr_accept_desc; memset(&apr_accept_desc, 0, sizeof apr_accept_desc); apr_accept_desc.p = pool; apr_accept_desc.desc_type = APR_POLL_SOCKET; apr_accept_desc.desc.s = acc; apr_accept_desc.reqevents = APR_POLLIN; apr_accept_desc.client_data = NULL; APR_DO_OR_DIE(apr_pollset_create(&pollset, 256, pool, 0)); APR_DO_OR_DIE(apr_pollset_add(pollset, &apr_accept_desc)); apr_signal(SIGTERM, shutdown_on_signal); apr_signal(SIGINT, shutdown_on_signal); apr_int32_t signalled_len = 0; const apr_pollfd_t *signalled = NULL; apr_status_t poll_err = 0; for (;;) { if (global_shutting_down) { goto goodnight; } if (!APR_STATUS_IS_EINTR(poll_err)) { APR_DO_OR_DIE(poll_err); } for (apr_int32_t i = 0; i < signalled_len; i++) { const apr_pollfd_t *s = signalled + i; if (s->desc.s == acc) { DEBUG("accept\n"); do_client_accept(acc, pollset, pool, &lmdb); } else { do_client_state_machine(s, pollset); } } poll_err = apr_pollset_poll(pollset, -1, &signalled_len, &signalled); } if (0) { goodnight: fprintf(stderr, "Goodnight!\n"); } if (0) { die: dying = 1; } sqlite3_finalize(lmdb.put); lmdb.put = 0; sqlite3_finalize(lmdb.get); lmdb.get = 0; sqlite3_finalize(lmdb.seen_add); lmdb.seen_add = 0; sqlite3_finalize(lmdb.seen_del); lmdb.seen_del = 0; sqlite3_finalize(lmdb.seen_get); lmdb.seen_get = 0; sqlite3_finalize(lmdb.drop); lmdb.drop = 0; if (sqlite3_close(sql) != SQLITE_OK) { fprintf(stderr, "Error closing DB (%s): %s.\n", db_filename, sqlite3_errmsg(sql)); return 1; } apr_pollset_destroy(pollset); apr_socket_close(acc); return dying; }
bool SettingsManager::load(const QString& path) { QByteArray data = path.toLatin1(); if(sqlite3_open(data.constData(), &(m_db))) { sqlite3_close(m_db); return false; } #if defined(SQLITE_HAS_CODEC) char tmp[9]; // Grab the obfuscated key sqlite3_obfuscate_key(tmp); tmp[8] = 0; if(SQLITE_OK != sqlite3_key((sqlite3*) m_db, tmp, 8)) { memset(tmp, 0, 9); sqlite3_close(m_db); return false; } // Clear the key so it isn't stored in memory memset(tmp, 0, 9); #endif sqllite_resultset_t rs; int rc; const char* query = "SELECT key,value FROM Settings"; rc = sqlite3_exec((sqlite3*)m_db, query, sqlite_callback, &rs, NULL); for(int i = 0; i < rs.rows.size(); i++) { QString key = strip_slashes(rs.rows[i][0].value); QString value = strip_slashes(rs.rows[i][1].value); m_globals[key] = strip_slashes(value); } bool allow_protected_settings = false; if(m_globals.end() != m_globals.find("permissions.protected_settings_visible")) { QString val = m_globals["permissions.protected_settings_visible"]; if(val == "1") { allow_protected_settings = true; } } query = "SELECT chip,key,value FROM DeviceSettings"; rs.rows.clear(); rc = sqlite3_exec((sqlite3*)m_db, query, sqlite_callback, &rs, NULL); for(int i = 0; i < rs.rows.size(); i++) { QString chip = strip_slashes(rs.rows[i][0].value); QString key = strip_slashes(rs.rows[i][1].value); QString value = strip_slashes(rs.rows[i][2].value); int chip_id = chip.toInt(0,10); m_device_settings[chip_id][key] = value; } query = "SELECT chip,key,value FROM DeviceSettings WHERE key='name'"; rs.rows.clear(); rc = sqlite3_exec((sqlite3*)m_db, query, sqlite_callback, &rs, NULL); for(int i = 0; i < rs.rows.size(); i++) { QString chip = strip_slashes(rs.rows[i][0].value); QString key = strip_slashes(rs.rows[i][1].value); QString value = strip_slashes(rs.rows[i][2].value); int chip_id = chip.toInt(0,10); /* Ensure the driver exists before adding this chip */ if(m_device_settings[chip_id].contains("scripts.c.path")) { QString driver_path = m_device_settings[chip_id]["scripts.c.path"]; if(QDir(driver_path).exists()) { m_device_list[chip_id] = value; } } } if(allow_protected_settings) { query = "SELECT chip,category,key,value FROM DeviceLists"; } else { query = "SELECT chip,category,key,value FROM DeviceLists WHERE protected='0'"; } rs.rows.clear(); rc = sqlite3_exec((sqlite3*)m_db, query, sqlite_callback, &rs, NULL); for(int i = 0;i < rs.rows.size(); i++) { int chip = rs.rows[i][0].value.toInt(); QString category = strip_slashes(rs.rows[i][1].value); QString list = strip_slashes(rs.rows[i][2].value); QString entry = strip_slashes(rs.rows[i][3].value); //qDebug() << "Loading " << chip << "." << category << "." << list << "." << entry << "\n"; //m_favorites[chip][category].insert(list,entry); m_favorites[chip][category][list].append(entry); } sqlite3_close(m_db); return true; }
//--------------------------------------------------------------- // START FUNC DECL int srt_join( char *docroot, sqlite3 *in_db, char *src_tbl, char *src_lnk, char *src_val, char *dst_tbl, char *dst_lnk, char *dst_fld, char *op ) // STOP FUNC DECL { int status = 0; sqlite3 *db = NULL; char *src_val_X = NULL; size_t src_val_nX = 0; char *src_lnk_X = NULL; size_t src_lnk_nX = 0; char *nn_dst_val_X = NULL; size_t nn_dst_val_nX = 0; char *dst_val_X = NULL; size_t dst_val_nX = 0; char *dst_lnk_X = NULL; size_t dst_lnk_nX = 0; FLD_META_TYPE src_val_meta, src_lnk_meta; FLD_META_TYPE dst_lnk_meta; long long src_nR, dst_nR; // counts all rows char str_meta_data[1024]; int ijoin_op; bool is_any_null = false; int src_tbl_id, dst_tbl_id; bool b_is_tbl; FILE *ofp = NULL, *nn_ofp = NULL; char *opfile = NULL, *nn_opfile = NULL; //---------------------------------------------------------------- zero_string(str_meta_data, 1024); status = mk_mjoin_op(op, &ijoin_op); cBYE(status); status = open_db_if_needed(docroot, in_db, &db); cBYE(status); zero_fld_meta(&src_val_meta); zero_fld_meta(&src_lnk_meta); zero_fld_meta(&dst_lnk_meta); //---------------------------------------------------------------- // Get meta-data for all necessary fields status = is_tbl(docroot, db, src_tbl, &b_is_tbl, &src_tbl_id); cBYE(status); if ( b_is_tbl == false ) { fprintf(stderr, "tbl [%s] not found\n", src_tbl); go_BYE(-1); } status = is_tbl(docroot, db, dst_tbl, &b_is_tbl, &dst_tbl_id); cBYE(status); if ( b_is_tbl == false ) { fprintf(stderr, "tbl [%s] not found\n", src_tbl); go_BYE(-1); } status = fld_meta(docroot, db, src_tbl, src_lnk, -1, &src_lnk_meta); cBYE(status); if ( ( src_val != NULL ) && ( *src_val != '\0' ) ) { status = fld_meta(docroot, db, src_tbl, src_val, -1, &src_val_meta); cBYE(status); } status = fld_meta(docroot, db, dst_tbl, dst_lnk, -1, &dst_lnk_meta); cBYE(status); status = internal_get_nR(db, src_tbl_id, &src_nR); cBYE(status); status = internal_get_nR(db, dst_tbl_id, &dst_nR); cBYE(status); //---------------------------------------------------------------- // Get pointer access to all necessary fields status = rs_mmap(src_lnk_meta.filename, &src_lnk_X, &src_lnk_nX, 0); cBYE(status); if ( ( src_val != NULL ) && ( *src_val != '\0' ) ) { status = rs_mmap(src_val_meta.filename, &src_val_X, &src_val_nX, 0); cBYE(status); } status = rs_mmap(dst_lnk_meta.filename, &dst_lnk_X, &dst_lnk_nX, 0); cBYE(status); //-------------------------------------------------------- // Create output data files status = open_temp_file(&ofp, &opfile); cBYE(status); fclose_if_non_null(ofp); status = open_temp_file(&nn_ofp, &nn_opfile); cBYE(status); fclose_if_non_null(nn_ofp); if ( ( src_val != NULL ) && ( *src_val != '\0' ) ) { status = mk_file(opfile, src_val_meta.n_sizeof * dst_nR); cBYE(status); status = rs_mmap(opfile, &dst_val_X, &dst_val_nX, 1); cBYE(status); } status = mk_file(nn_opfile, sizeof(char) * dst_nR); cBYE(status); status = rs_mmap(nn_opfile, &nn_dst_val_X, &nn_dst_val_nX, 1); cBYE(status); //-------------------------------------------------------- // Core join if ( ( strcmp(src_lnk_meta.fldtype, "int") == 0 ) && ( strcmp(src_lnk_meta.fldtype, "int") == 0 ) && ( strcmp(dst_lnk_meta.fldtype, "int") == 0 ) ) { status = core_srt_join_I_I_I( (int *)src_lnk_X, (int *)src_val_X, src_nR, (int *)dst_lnk_X, (int *)dst_val_X, nn_dst_val_X, 0, dst_nR, ijoin_op, &is_any_null); } else if ( ( strcmp(src_lnk_meta.fldtype, "int") == 0 ) && ( strcmp(src_lnk_meta.fldtype, "int") == 0 ) && ( strcmp(dst_lnk_meta.fldtype, "long long") == 0 ) ) { status = core_srt_join_I_I_L( (int *)src_lnk_X, (int *)src_val_X, src_nR, (long long *)dst_lnk_X, (int *)dst_val_X, nn_dst_val_X, 0, dst_nR, ijoin_op, &is_any_null); } else if ( ( strcmp(src_lnk_meta.fldtype, "int") == 0 ) && ( strcmp(src_lnk_meta.fldtype, "long long") == 0 ) && ( strcmp(dst_lnk_meta.fldtype, "int") == 0 ) ) { status = core_srt_join_I_L_I( (int *)src_lnk_X, (long long *)src_val_X, src_nR, (int *)dst_lnk_X, (long long *)dst_val_X, nn_dst_val_X, 0, dst_nR, ijoin_op, &is_any_null); } else if ( ( strcmp(src_lnk_meta.fldtype, "int") == 0 ) && ( strcmp(src_lnk_meta.fldtype, "long long") == 0 ) && ( strcmp(dst_lnk_meta.fldtype, "long long") == 0 ) ) { status = core_srt_join_I_L_L((int *)src_lnk_X, (long long *)src_val_X, src_nR, (long long *)dst_lnk_X, (long long *)dst_val_X, nn_dst_val_X, 0, dst_nR, ijoin_op, &is_any_null); } else if ( ( strcmp(src_lnk_meta.fldtype, "long long") == 0 ) && ( strcmp(src_lnk_meta.fldtype, "int") == 0 ) && ( strcmp(dst_lnk_meta.fldtype, "int") == 0 ) ) { status = core_srt_join_L_I_I( (long long *)src_lnk_X, (int *)src_val_X, src_nR, (int *)dst_lnk_X, (int *)dst_val_X, nn_dst_val_X, 0, dst_nR, ijoin_op, &is_any_null); } else if ( ( strcmp(src_lnk_meta.fldtype, "long long") == 0 ) && ( strcmp(src_lnk_meta.fldtype, "int") == 0 ) && ( strcmp(dst_lnk_meta.fldtype, "long long") == 0 ) ) { status = core_srt_join_L_I_L( (long long *)src_lnk_X, (int *)src_val_X, src_nR, (long long *)dst_lnk_X, (int *)dst_val_X, nn_dst_val_X, 0, dst_nR, ijoin_op, &is_any_null); } else if ( ( strcmp(src_lnk_meta.fldtype, "long long") == 0 ) && ( strcmp(src_lnk_meta.fldtype, "long long") == 0 ) && ( strcmp(dst_lnk_meta.fldtype, "int") == 0 ) ) { status = core_srt_join_L_L_I( (long long *)src_lnk_X, (long long *)src_val_X, src_nR, (int *)dst_lnk_X, (long long *)dst_val_X, nn_dst_val_X, 0, dst_nR, ijoin_op, &is_any_null); } else if ( ( strcmp(src_lnk_meta.fldtype, "long long") == 0 ) && ( strcmp(src_lnk_meta.fldtype, "long long") == 0 ) && ( strcmp(dst_lnk_meta.fldtype, "long long") == 0 ) ) { status = core_srt_join_L_L_L( (long long *)src_lnk_X, (long long *)src_val_X, src_nR, (long long *)dst_lnk_X, (long long *)dst_val_X, nn_dst_val_X, 0, dst_nR, ijoin_op, &is_any_null); } else { go_BYE(-1); } //-------------------------------------------------------- // Add output field to meta data if ( ( src_val != NULL ) && ( *src_val != '\0' ) ) { sprintf(str_meta_data,"filename=%s:n_sizeof=%d:fldtype=%s", opfile, src_val_meta.n_sizeof, src_val_meta.fldtype); status = add_fld(docroot, db, dst_tbl, dst_fld, str_meta_data); cBYE(status); if ( is_any_null == true ) { status = add_aux_fld(docroot, db, dst_tbl, dst_fld, nn_opfile, "nn"); cBYE(status); } else { unlink(nn_opfile); free_if_non_null(nn_opfile); } } else { sprintf(str_meta_data,"filename=%s:n_sizeof=%ld:fldtype=bool", nn_opfile, sizeof(char)); status = add_fld(docroot, db, dst_tbl, dst_fld, str_meta_data); cBYE(status); } BYE: if ( in_db == NULL ) { sqlite3_close(db); } rs_munmap(src_val_X, src_val_nX); rs_munmap(src_lnk_X, src_lnk_nX); rs_munmap(dst_val_X, dst_val_nX); rs_munmap(nn_dst_val_X, nn_dst_val_nX); rs_munmap(dst_lnk_X, dst_lnk_nX); free_if_non_null(nn_opfile); free_if_non_null(opfile); return(status); }
Database::~Database(){ sqlite3_close(connection); }
int main(int argc, char **argv){ sqlite3 *db; char *zErrMsg = 0; int rc; if( argc!=3 ){ fprintf(stderr, "Usage: %s DATABASE 'select S(1,2,3,4,5,6)'\n", argv[0]); exit(1); } rc = sqlite3_open(argv[1], &db); if( rc ){ fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); exit(1); } if (sqlite3_create_function(db, "msign", 1, SQLITE_UTF8, NULL, &msignFunc, NULL, NULL) != 0) fprintf(stderr,"Problem with msign\n"); if (sqlite3_create_function(db, "T", -1, SQLITE_UTF8, NULL, &TFunc, NULL, NULL) != 0) fprintf(stderr,"Problem with T using just TFunc \n"); if (sqlite3_create_function(db, "F", 1, SQLITE_UTF8, NULL, &FFunc, NULL, NULL) != 0) fprintf(stderr,"Problem with F using just FFunc \n"); if (sqlite3_create_function(db, "I", 2, SQLITE_UTF8, NULL, &IFunc, NULL, NULL) != 0) fprintf(stderr,"Problem with I using just IFunc \n"); /* * With 2 or more arguments call the simple function ssum. Simple functions * can be used within an expression. Aggregate functions can only be used * in a select. */ if (sqlite3_create_function(db, "S", -1, SQLITE_UTF8, NULL, &SFunc, NULL, NULL) != 0) fprintf(stderr,"Problem with S using just SFunc \n"); /* * With one argument call the aggregate function. */ if (sqlite3_create_function(db, "S", 1, SQLITE_UTF8, NULL, NULL, &SStep, &SFinalize) != 0) fprintf(stderr,"Problem with S using SStep and SFinalize\n"); if (sqlite3_create_function(db, "L", 1, SQLITE_UTF8, NULL, NULL, &listStep, &listFinalize) != 0) fprintf(stderr,"Problem with list using listStep and listFinalize\n"); rc = sqlite3_exec(db, argv[2], callback, 0, &zErrMsg); if( rc!=SQLITE_OK ){ fprintf(stderr, "SQL error: %s\n", zErrMsg); } sqlite3_close(db); return 0; }
/** * \fn close() * \brief Close the database. * * \param * \return void */ void DatabaseUTF::close() { sqlite3_close(database); }