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; }
svn_boolean_t svn_sqlite__column_boolean(svn_sqlite__stmt_t *stmt, int column) { return sqlite3_column_int64(stmt->s3stmt, column) != 0; }
/* * Pattern Rule Grammar * -------------------- * * line := blank | "#" comment | rule * * rule := pattern *[ whitespace ] actions * * whitespace := SPACE | TAB * * pattern := "/" extended_regex "/" * * actions := action [ ";" actions ] * * action := thread | limit | report | on_exceed | on_expire * * quote := "'" | '"' * * index := number | quote text quote * * indices := index [ "," index ] * * thread := "t=" indices * * limit := "l=" indices "," max "/" period [ unit ] * * report := "r=" mail *[ "," mail ] * * on_exceed := "c=" quoted_shell_command * * on_expire := "C=" quoted_shell_command * * quoted_shell_command := quote text quote */ static int init_rule(char *line) { Vector fields; const char *next; struct pattern_rule *rule; int i, rc = -1, err; char *field, error[128]; if (*line != '/') goto error0; if ((rule = calloc(1, sizeof (*rule))) == NULL) goto error0; if ((rule->pattern = TokenNext(line, &next, "/", TOKEN_KEEP_ASIS)) == NULL) goto error1; if ((fields = TextSplit(next, ";", TOKEN_KEEP_ASIS)) == NULL) goto error1; if ((err = regcomp(&rule->re, rule->pattern, REG_EXTENDED|REG_NEWLINE)) != 0) { (void) regerror(err, &rule->re, error, sizeof (error)); (void) fprintf(stderr, "pattern /%s/: %s (%d)\n", rule->pattern, error, err); goto error2; } /* Assume new previously unknown pattern. */ if ((err = sqlite3_bind_text(ctx.insert_pattern, 1, rule->pattern, -1, SQLITE_STATIC)) != SQLITE_OK) { sql_error(__FILE__, __LINE__, ctx.insert_pattern); goto error2; } if ((err = sql_step(ctx.db, ctx.insert_pattern)) != SQLITE_DONE) { sql_error(__FILE__, __LINE__, ctx.insert_pattern); goto error2; } rule->id_pattern = sqlite3_last_insert_rowid(ctx.db); (void) sqlite3_clear_bindings(ctx.insert_pattern); sqlite3_reset(ctx.insert_pattern); /* Last insert rowid is zero if no row was inserted, thus it * already exists and we need to find the pattern number (OID). */ if (rule->id_pattern == 0) { if ((err = sqlite3_bind_text(ctx.find_pattern, 1, rule->pattern, -1, SQLITE_STATIC)) != SQLITE_OK) { sql_error(__FILE__, __LINE__, ctx.find_pattern); goto error2; } if ((err = sql_step(ctx.db, ctx.find_pattern)) != SQLITE_ROW) { sql_error(__FILE__, __LINE__, ctx.find_pattern); goto error2; } if ((rule->id_pattern = sqlite3_column_int64(ctx.find_pattern, 0)) == 0) { sql_error(__FILE__, __LINE__, ctx.find_pattern); goto error2; } (void) sqlite3_clear_bindings(ctx.find_pattern); sqlite3_reset(ctx.find_pattern); } for (i = 0; i < VectorLength(fields); i++) { field = VectorGet(fields, i); field += strspn(field, " \t"); switch (*field) { case 'c': if (field[1] == '=') { free(rule->on_exceed); rule->on_exceed = VectorReplace(fields, i, NULL); } break; case 'C': if (field[1] == '=') { free(rule->on_expire); rule->on_expire = VectorReplace(fields, i, NULL); } break; case 'r': if (field[1] == '=') { free(rule->report); rule->report = VectorReplace(fields, i, NULL); } break; case 't': if (field[1] == '=') rule->thread = strtol(field+2, NULL, 10); break; case 'l': if (field[1] == '=') continue; } (void) VectorRemove(fields, i--); } field[strcspn(field, "\r\n")] = '\0'; /* What remains of fields should be an empty vector or an array of l= actions. */ rule->limits = (char **) VectorBase(fields); fields = NULL; rule->node.data = rule; rule->node.free = free_rule; listInsertAfter(&pattern_rules, NULL, &rule->node); rc = 0; error2: VectorDestroy(fields); error1: if (rc != 0) free_rule(rule); error0: return rc; }
static GList* daemon_data_sqlite_data_real_GetLog (DaemonDataIDataAccess* base, const gchar* channel, const gchar* server, GError** error) { DaemonDataSqliteData * self; GList* result = NULL; gchar* _tmp0_; gchar* commandText; sqlite3_stmt* statement = NULL; sqlite3_stmt* _tmp1_ = NULL; gchar* _tmp2_; gchar* _tmp3_; gint _result_; GList* results; GError * _inner_error_ = NULL; self = (DaemonDataSqliteData*) base; g_return_val_if_fail (channel != NULL, NULL); g_return_val_if_fail (server != NULL, NULL); _tmp0_ = g_strdup ("SELECT * FROM Log WHERE Channel = @1 AND Server = @2 ORDER BY Timestam" \ "p DESC LIMIT 50"); commandText = _tmp0_; sqlite3_prepare_v2 (self->priv->_database, commandText, -1, &_tmp1_, NULL); _sqlite3_finalize0 (statement); statement = _tmp1_; _tmp2_ = g_strdup (channel); sqlite3_bind_text (statement, 1, _tmp2_, -1, g_free); _tmp3_ = g_strdup (server); sqlite3_bind_text (statement, 2, _tmp3_, -1, g_free); _result_ = 0; results = NULL; { gboolean _tmp4_; _tmp4_ = TRUE; while (TRUE) { gint _tmp5_; if (!_tmp4_) { if (!(_result_ == SQLITE_ROW)) { break; } } _tmp4_ = FALSE; _tmp5_ = sqlite3_step (statement); _result_ = _tmp5_; switch (_result_) { case SQLITE_DONE: { { break; } } case SQLITE_ROW: { { const gchar* _tmp6_ = NULL; gchar* _tmp7_; gchar* username; const gchar* _tmp8_ = NULL; gchar* _tmp9_; gchar* data; const gchar* _tmp10_ = NULL; gchar* _tmp11_; gchar* eventChannel; const gchar* _tmp12_ = NULL; gchar* _tmp13_; gchar* eventServer; gint64 _tmp14_; GDateTime* _tmp15_ = NULL; GDateTime* timestamp; gint _tmp16_; DaemonDataEventTypes type; DaemonEventsLogEvent* current; DaemonEventsLogEvent* _tmp21_; _tmp6_ = sqlite3_column_text (statement, 0); _tmp7_ = g_strdup (_tmp6_); username = _tmp7_; _tmp8_ = sqlite3_column_text (statement, 1); _tmp9_ = g_strdup (_tmp8_); data = _tmp9_; _tmp10_ = sqlite3_column_text (statement, 2); _tmp11_ = g_strdup (_tmp10_); eventChannel = _tmp11_; _tmp12_ = sqlite3_column_text (statement, 3); _tmp13_ = g_strdup (_tmp12_); eventServer = _tmp13_; _tmp14_ = sqlite3_column_int64 (statement, 4); _tmp15_ = daemon_helpers_date_time_converter_FromUnixTimestamp (_tmp14_); timestamp = _tmp15_; _tmp16_ = sqlite3_column_int (statement, 5); type = (DaemonDataEventTypes) _tmp16_; current = NULL; switch (type) { case DAEMON_DATA_EVENT_TYPES_Joined: { { DaemonEventsStatusEvent* _tmp17_ = NULL; _tmp17_ = daemon_events_status_event_new_WithTimestamp (username, DAEMON_EVENTS_STATUS_CHANGE_Join, eventChannel, eventServer, timestamp); _g_object_unref0 (current); current = (DaemonEventsLogEvent*) _tmp17_; break; } } case DAEMON_DATA_EVENT_TYPES_Left: { { DaemonEventsStatusEvent* _tmp18_ = NULL; _tmp18_ = daemon_events_status_event_new_WithTimestamp (username, DAEMON_EVENTS_STATUS_CHANGE_Leave, eventChannel, eventServer, timestamp); _g_object_unref0 (current); current = (DaemonEventsLogEvent*) _tmp18_; break; } } case DAEMON_DATA_EVENT_TYPES_ChangedName: { { DaemonEventsChangeNameEvent* _tmp19_ = NULL; _tmp19_ = daemon_events_change_name_event_new_WithTimestamp (username, data, eventChannel, eventServer, timestamp); _g_object_unref0 (current); current = (DaemonEventsLogEvent*) _tmp19_; break; } } case DAEMON_DATA_EVENT_TYPES_Message: { { DaemonEventsMessageEvent* _tmp20_ = NULL; _tmp20_ = daemon_events_message_event_new_WithTimestamp (username, data, eventChannel, eventServer, timestamp); _g_object_unref0 (current); current = (DaemonEventsLogEvent*) _tmp20_; break; } } default: break; } _tmp21_ = _g_object_ref0 (current); results = g_list_append (results, _tmp21_); _g_object_unref0 (current); _g_date_time_unref0 (timestamp); _g_free0 (eventServer); _g_free0 (eventChannel); _g_free0 (data); _g_free0 (username); break; } } default: { { const gchar* _tmp22_ = NULL; GError* _tmp23_ = NULL; _tmp22_ = sqlite3_errmsg (self->priv->_database); _tmp23_ = g_error_new_literal (DAEMON_DATA_DATA_ACCESS_ERROR, DAEMON_DATA_DATA_ACCESS_ERROR_ReadError, _tmp22_); _inner_error_ = _tmp23_; if (_inner_error_->domain == DAEMON_DATA_DATA_ACCESS_ERROR) { g_propagate_error (error, _inner_error_); __g_list_free__g_object_unref0_0 (results); _sqlite3_finalize0 (statement); _g_free0 (commandText); return NULL; } else { __g_list_free__g_object_unref0_0 (results); _sqlite3_finalize0 (statement); _g_free0 (commandText); g_critical ("file %s: line %d: uncaught error: %s (%s, %d)", __FILE__, __LINE__, _inner_error_->message, g_quark_to_string (_inner_error_->domain), _inner_error_->code); g_clear_error (&_inner_error_); return NULL; } } } } } } result = results; _sqlite3_finalize0 (statement); _g_free0 (commandText); return result; }
long CCResultSet::longForColumnIndex(int columnIdx) { return (long)sqlite3_column_int64(m_statement->getStatement(), columnIdx); }
/*! \brief Load geometry (polygon BUD/PAR layers) \return number of invalid features */ int VFKDataBlockSQLite::LoadGeometryPolygon() { VFKReaderSQLite *poReader = (VFKReaderSQLite*) m_poReader; VFKDataBlockSQLite *poDataBlockLines1 = NULL; VFKDataBlockSQLite *poDataBlockLines2 = NULL; bool bIsPar = false; if (EQUAL (m_pszName, "PAR")) { poDataBlockLines1 = (VFKDataBlockSQLite *) m_poReader->GetDataBlock("HP"); poDataBlockLines2 = poDataBlockLines1; bIsPar = true; } else { poDataBlockLines1 = (VFKDataBlockSQLite *) m_poReader->GetDataBlock("OB"); poDataBlockLines2 = (VFKDataBlockSQLite *) m_poReader->GetDataBlock("SBP"); bIsPar = false; } if( NULL == poDataBlockLines1 ) { CPLError(CE_Warning, CPLE_FileIO, "Data block %s not found. Unable to build geometry for %s.", bIsPar ? "HP" : "OB", m_pszName); return -1; } if( NULL == poDataBlockLines2 ) { CPLError(CE_Warning, CPLE_FileIO, "Data block %s not found. Unable to build geometry for %s.", "SBP", m_pszName); return -1; } poDataBlockLines1->LoadGeometry(); poDataBlockLines2->LoadGeometry(); if( LoadGeometryFromDB() ) // Try to load geometry from DB. return 0; const char *vrColumn[2] = { NULL, NULL }; GUIntBig vrValue[2] = { 0, 0 }; if (bIsPar) { vrColumn[0] = "PAR_ID_1"; vrColumn[1] = "PAR_ID_2"; } else { vrColumn[0] = "OB_ID"; vrColumn[1] = "PORADOVE_CISLO_BODU"; vrValue[1] = 1; } CPLString osSQL; osSQL.Printf("SELECT ID,%s,rowid FROM %s", FID_COLUMN, m_pszName); sqlite3_stmt *hStmt = poReader->PrepareStatement(osSQL.c_str()); if (poReader->IsSpatial()) poReader->ExecuteSQL("BEGIN"); VFKFeatureSQLiteList poLineList; /* first is to be considered as exterior */ PointListArray poRingList; std::vector<OGRLinearRing *> poLinearRingList; OGRPolygon ogrPolygon; int nInvalidNoLines = 0; int nInvalidNoRings = 0; int nGeometries = 0; while(poReader->ExecuteSQL(hStmt) == OGRERR_NONE) { /* read values */ const GUIntBig id = sqlite3_column_int64(hStmt, 0); const long iFID = static_cast<long>(sqlite3_column_int64(hStmt, 1)); const int rowId = sqlite3_column_int(hStmt, 2); VFKFeatureSQLite *poFeature = (VFKFeatureSQLite *) GetFeatureByIndex(rowId - 1); CPLAssert(NULL != poFeature && poFeature->GetFID() == iFID); if( bIsPar ) { vrValue[0] = vrValue[1] = id; poLineList = poDataBlockLines1->GetFeatures(vrColumn, vrValue, 2); } else { // std::vector<VFKFeatureSQLite *> poLineListOb; osSQL.Printf("SELECT ID FROM %s WHERE BUD_ID = " CPL_FRMT_GUIB, poDataBlockLines1->GetName(), id); if (poReader->IsSpatial()) { CPLString osColumn; osColumn.Printf(" AND %s IS NULL", GEOM_COLUMN); osSQL += osColumn; } sqlite3_stmt *hStmtOb = poReader->PrepareStatement(osSQL.c_str()); while(poReader->ExecuteSQL(hStmtOb) == OGRERR_NONE) { const GUIntBig idOb = sqlite3_column_int64(hStmtOb, 0); vrValue[0] = idOb; VFKFeatureSQLite *poLineSbp = poDataBlockLines2->GetFeature(vrColumn, vrValue, 2); if (poLineSbp) poLineList.push_back(poLineSbp); } } size_t nLines = poLineList.size(); if (nLines < 1) { CPLDebug("OGR-VFK", "%s: unable to collect rings for polygon fid = %ld (no lines)", m_pszName, iFID); nInvalidNoLines++; continue; } /* clear */ ogrPolygon.empty(); poRingList.clear(); /* collect rings from lines */ bool bFound = false; int nCount = 0; const int nCountMax = static_cast<int>(nLines) * 2; while( poLineList.size() > 0 && nCount < nCountMax ) { bool bNewRing = !bFound; bFound = false; int i = 1; for (VFKFeatureSQLiteList::iterator iHp = poLineList.begin(), eHp = poLineList.end(); iHp != eHp; ++iHp, ++i) { const OGRLineString *pLine = (OGRLineString *) (*iHp)->GetGeometry(); if (pLine && AppendLineToRing(&poRingList, pLine, bNewRing)) { bFound = true; poLineList.erase(iHp); break; } } nCount++; } CPLDebug("OGR-VFK", "%s: fid = %ld nlines = %d -> nrings = %d", m_pszName, iFID, (int)nLines, (int)poRingList.size()); if (poLineList.size() > 0) { CPLDebug("OGR-VFK", "%s: unable to collect rings for polygon fid = %ld", m_pszName, iFID); nInvalidNoRings++; continue; } /* build rings */ poLinearRingList.clear(); OGRLinearRing *poOgrRing = NULL; int i = 1; for( PointListArray::const_iterator iRing = poRingList.begin(), eRing = poRingList.end(); iRing != eRing; ++iRing) { PointList *poList = *iRing; poLinearRingList.push_back(new OGRLinearRing()); poOgrRing = poLinearRingList.back(); CPLAssert(NULL != poOgrRing); for( PointList::iterator iPoint = poList->begin(), ePoint = poList->end(); iPoint != ePoint; ++iPoint) { OGRPoint *poPoint = &(*iPoint); poOgrRing->addPoint(poPoint); } i++; } /* find exterior ring */ if( poLinearRingList.size() > 1 ) { std::vector<OGRLinearRing *>::iterator exteriorRing; exteriorRing = poLinearRingList.begin(); double dMaxArea = -1.0; for( std::vector<OGRLinearRing *>::iterator iRing = poLinearRingList.begin(), eRing = poLinearRingList.end(); iRing != eRing; ++iRing ) { poOgrRing = *iRing; if (!IsRingClosed(poOgrRing)) continue; /* skip unclosed rings */ const double dArea = poOgrRing->get_Area(); if (dArea > dMaxArea) { dMaxArea = dArea; exteriorRing = iRing; } } if (exteriorRing != poLinearRingList.begin()) { std::swap(*poLinearRingList.begin(), *exteriorRing); } } /* build polygon from rings */ int nBridges = 0; for( std::vector<OGRLinearRing *>::iterator iRing = poLinearRingList.begin(), eRing = poLinearRingList.end(); iRing != eRing; ++iRing ) { poOgrRing = *iRing; /* check if ring is closed */ if (IsRingClosed(poOgrRing)) { ogrPolygon.addRing(poOgrRing); } else { if (poOgrRing->getNumPoints() == 2) { CPLDebug("OGR-VFK", "%s: Polygon (fid = %ld) bridge removed", m_pszName, iFID); nBridges++; } else { CPLDebug("OGR-VFK", "%s: Polygon (fid = %ld) unclosed ring skipped", m_pszName, iFID); } } delete poOgrRing; *iRing = NULL; } /* set polygon */ ogrPolygon.setCoordinateDimension(2); /* force 2D */ if (ogrPolygon.getNumInteriorRings() + nBridges != (int) poLinearRingList.size() - 1 || !poFeature->SetGeometry(&ogrPolygon)) { nInvalidNoRings++; continue; } /* store also geometry in DB */ if (poReader->IsSpatial() && SaveGeometryToDB(&ogrPolygon, rowId) != OGRERR_FAILURE) nGeometries++; } /* free ring list */ for (PointListArray::iterator iRing = poRingList.begin(), eRing = poRingList.end(); iRing != eRing; ++iRing) { delete (*iRing); *iRing = NULL; } CPLDebug("OGR-VFK", "%s: nolines = %d norings = %d", m_pszName, nInvalidNoLines, nInvalidNoRings); /* update number of geometries in VFK_DB_TABLE table */ UpdateVfkBlocks(nGeometries); if (poReader->IsSpatial()) poReader->ExecuteSQL("COMMIT"); return nInvalidNoLines + nInvalidNoRings; }
Track* TrackDAOSqlite3Impl::getTrack( Track* criterion ) { Track* track = NULL; Artist* artist_criterion; Album* album_criterion; int column = 0; QueryCriteriaList queryCriteriaList; std::string* sql; checkDb(); if( criterion != NULL ) { if( criterion->id >= 0 ) { QueryCriteria qc = {"TrackId", ":trackid", QueryCriteria::LONG}; qc.value = &criterion->id; queryCriteriaList.push_back(qc); } if( !criterion->filename.empty() ) { QueryCriteria qc = {"Filename", ":filename", QueryCriteria::TEXT}; qc.value = criterion->filename.c_str(); queryCriteriaList.push_back(qc); } if( !criterion->name.empty() ) { QueryCriteria qc = {"Name", ":name", QueryCriteria::TEXT}; qc.value = criterion->name.c_str(); queryCriteriaList.push_back(qc); } if( !criterion->artFilename.empty() ) { QueryCriteria qc = {"Art_Filename", ":artfilename", QueryCriteria::TEXT}; qc.value = criterion->artFilename.c_str(); queryCriteriaList.push_back(qc); } if( criterion->artist && criterion->artist->id >= 0 ) { QueryCriteria qc = {"ArtistId", ":artistid", QueryCriteria::LONG}; qc.value = &criterion->artist->id; queryCriteriaList.push_back(qc); } if( criterion->album && criterion->album->artist && criterion->album->artist->id >= 0 ) { QueryCriteria qc = {"AlbumArtistId", ":albumartistid", QueryCriteria::LONG}; qc.value = &criterion->album->artist->id; queryCriteriaList.push_back(qc); } if( criterion->album && criterion->album->id >= 0 ) { QueryCriteria qc = {"AlbumId", ":albumid", QueryCriteria::LONG}; qc.value = &criterion->album->id; queryCriteriaList.push_back(qc); } if( criterion->discNumber > 0 ) { QueryCriteria qc = {"DiscNumber", ":discnumber", QueryCriteria::INT}; qc.value = &criterion->discNumber; queryCriteriaList.push_back(qc); } if( criterion->trackNumber > 0 ) { QueryCriteria qc = {"TrackNumber", ":tracknumber", QueryCriteria::INT}; qc.value = &criterion->trackNumber; queryCriteriaList.push_back(qc); } if( criterion->replayGain > -99.0 ) { QueryCriteria qc = {"ReplayGain", ":replaygain", QueryCriteria::DOUBLE}; qc.value = &criterion->replayGain; queryCriteriaList.push_back(qc); } } sql = buildSqlFromQueryCriteria( "Tracks", queryCriteriaList ); sqlite3_stmt* pStmt = prepare( sql->c_str() ); bindVariablesFromQueryCriteria( pStmt, queryCriteriaList ); if( step( pStmt ) == SQLITE_ROW ) { track = new Track(); artist_criterion = new Artist(); album_criterion = new Album(); album_criterion->artist = new Artist(); track->id = sqlite3_column_int64( pStmt, column++ ); track->filename.assign( (const char*) sqlite3_column_text( pStmt, column++ ) ); column++; //track->checksum.assign( (const char*)sqlite3_column_text( pStmt, column++; ) ); track->name.assign( (const char*) sqlite3_column_text( pStmt, column++ ) ); track->artFilename.assign( (const char*) sqlite3_column_text( pStmt, column++ ) ); artist_criterion->id = sqlite3_column_int64( pStmt, column++ ); album_criterion->artist->id = sqlite3_column_int64( pStmt, column++ ); album_criterion->id = sqlite3_column_int64( pStmt, column++ ); track->trackNumber = sqlite3_column_int( pStmt, column++ ); track->discNumber = sqlite3_column_int( pStmt, column++ ); track->replayGain = sqlite3_column_double( pStmt, column++ ); if( artist_criterion->id >= 0 ) { track->artist = artistDAO->getArtist( artist_criterion ); } if( album_criterion->id >= 0 ) { track->album = albumDAO->getAlbum( album_criterion ); } delete album_criterion->artist; delete album_criterion; delete artist_criterion; } finalize( pStmt ); delete sql; return track; }
int pkgdb_register_pkg(struct pkgdb *db, struct pkg *pkg) { struct pkg **deps; struct pkg_file **files; struct pkg_conflict **conflicts; struct pkg_script **scripts; struct pkg_option **options; sqlite3 *s; sqlite3_stmt *stmt_pkg = NULL; sqlite3_stmt *stmt_sel_pkg = NULL; sqlite3_stmt *stmt_dep = NULL; sqlite3_stmt *stmt_conflict = NULL; sqlite3_stmt *stmt_file = NULL; sqlite3_stmt *stmt_script = NULL; sqlite3_stmt *stmt_option = NULL; sqlite3_stmt *stmt_dirs = NULL; int i; int ret; int retcode = EPKG_OK; const char *path; int64_t package_id; char *errmsg; const char sql_begin[] = "BEGIN TRANSACTION;"; const char sql_pkg[] = "" "INSERT INTO pkg_mtree( " "origin, name, version, comment, desc, mtree, message, arch, " "osversion, maintainer, www, prefix, flatsize) " "VALUES( ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13);"; const char sql_sel_pkg[] = "" "SELECT id FROM packages " "WHERE origin = ?1;"; const char sql_dep[] = "" "INSERT INTO deps (origin, name, version, package_id) " "VALUES (?1, ?2, ?3, ?4);"; const char sql_conflict[] = "" "INSERT INTO conflicts (name, package_id) " "VALUES (?1, ?2);"; const char sql_file[] = "" "INSERT INTO files (path, sha256, package_id) " "VALUES (?1, ?2, ?3);"; const char sql_script[] = "" "INSERT INTO scripts (script, type, package_id) " "VALUES (?1, ?2, ?3);"; const char sql_option[] = "" "INSERT INTO options (option, value, package_id) " "VALUES (?1, ?2, ?3);"; const char sql_dir[] = "" "INSERT INTO pkg_dirs(origin, path) " "VALUES (?1, ?2);"; if (pkgdb_has_flag(db, PKGDB_FLAG_IN_FLIGHT)) { pkg_error_set(EPKG_FATAL, "tried to register a package with an in-flight SQL command"); return (EPKG_FATAL); } s = db->sqlite; if (sqlite3_exec(s, sql_begin, NULL, NULL, &errmsg) != SQLITE_OK) { pkg_error_set(EPKG_FATAL, "sqlite: %s", errmsg); sqlite3_free(errmsg); return (EPKG_FATAL); } PKGDB_SET_FLAG(db, PKGDB_FLAG_IN_FLIGHT); /* * Insert package record */ if (sqlite3_prepare_v2(s, sql_pkg, -1, &stmt_pkg, NULL) != SQLITE_OK) { retcode = ERROR_SQLITE(s); goto cleanup; } sqlite3_bind_text(stmt_pkg, 1, pkg_get(pkg, PKG_ORIGIN), -1, SQLITE_STATIC); sqlite3_bind_text(stmt_pkg, 2, pkg_get(pkg, PKG_NAME), -1, SQLITE_STATIC); sqlite3_bind_text(stmt_pkg, 3, pkg_get(pkg, PKG_VERSION), -1, SQLITE_STATIC); sqlite3_bind_text(stmt_pkg, 4, pkg_get(pkg, PKG_COMMENT), -1, SQLITE_STATIC); sqlite3_bind_text(stmt_pkg, 5, pkg_get(pkg, PKG_DESC), -1, SQLITE_STATIC); sqlite3_bind_text(stmt_pkg, 6, pkg_get(pkg, PKG_MTREE), -1, SQLITE_STATIC); sqlite3_bind_text(stmt_pkg, 7, pkg_get(pkg, PKG_MESSAGE), -1, SQLITE_STATIC); sqlite3_bind_text(stmt_pkg, 8, pkg_get(pkg, PKG_ARCH), -1, SQLITE_STATIC); sqlite3_bind_text(stmt_pkg, 9, pkg_get(pkg, PKG_OSVERSION), -1, SQLITE_STATIC); sqlite3_bind_text(stmt_pkg, 10, pkg_get(pkg, PKG_MAINTAINER), -1, SQLITE_STATIC); sqlite3_bind_text(stmt_pkg, 11, pkg_get(pkg, PKG_WWW), -1, SQLITE_STATIC); sqlite3_bind_text(stmt_pkg, 12, pkg_get(pkg, PKG_PREFIX), -1, SQLITE_STATIC); sqlite3_bind_int64(stmt_pkg, 13, pkg_flatsize(pkg)); if ((ret = sqlite3_step(stmt_pkg)) != SQLITE_DONE) { if ( ret == SQLITE_CONSTRAINT) retcode = pkg_error_set(EPKG_FATAL, "constraint violation on " "pkg with %s", pkg_get(pkg, PKG_ORIGIN)); else retcode = ERROR_SQLITE(s); goto cleanup; } /* * Get the generated package_id */ if (sqlite3_prepare_v2(s, sql_sel_pkg, -1, &stmt_sel_pkg, NULL) != SQLITE_OK) { retcode = ERROR_SQLITE(s); goto cleanup; } sqlite3_bind_text(stmt_sel_pkg, 1, pkg_get(pkg, PKG_ORIGIN), -1, SQLITE_STATIC); ret = sqlite3_step(stmt_sel_pkg); if (ret == SQLITE_ROW) { package_id = sqlite3_column_int64(stmt_sel_pkg, 0); ret = SQLITE_DONE; } else { retcode = ERROR_SQLITE(s); goto cleanup; } /* * Insert dependencies list */ if (sqlite3_prepare_v2(s, sql_dep, -1, &stmt_dep, NULL) != SQLITE_OK) { retcode = ERROR_SQLITE(s); goto cleanup; } deps = pkg_deps(pkg); for (i = 0; deps[i] != NULL; i++) { sqlite3_bind_text(stmt_dep, 1, pkg_get(deps[i], PKG_ORIGIN), -1, SQLITE_STATIC); sqlite3_bind_text(stmt_dep, 2, pkg_get(deps[i], PKG_NAME), -1, SQLITE_STATIC); sqlite3_bind_text(stmt_dep, 3, pkg_get(deps[i], PKG_VERSION), -1, SQLITE_STATIC); sqlite3_bind_int64(stmt_dep, 4, package_id); if ((ret = sqlite3_step(stmt_dep)) != SQLITE_DONE) { if ( ret == SQLITE_CONSTRAINT) retcode = pkg_error_set(EPKG_FATAL, "constraint violation on " "deps with %s", pkg_get(deps[i], PKG_ORIGIN)); else retcode = ERROR_SQLITE(s); goto cleanup; } sqlite3_reset(stmt_dep); } /* * Insert conflicts list */ if (sqlite3_prepare_v2(s, sql_conflict, -1, &stmt_conflict, NULL) != SQLITE_OK) { retcode = ERROR_SQLITE(s); goto cleanup; } conflicts = pkg_conflicts(pkg); for (i = 0; conflicts[i] != NULL; i++) { sqlite3_bind_text(stmt_conflict, 1, pkg_conflict_glob(conflicts[i]), -1, SQLITE_STATIC); sqlite3_bind_int64(stmt_conflict, 2, package_id); if ((ret = sqlite3_step(stmt_conflict)) != SQLITE_DONE) { if ( ret == SQLITE_CONSTRAINT) retcode = pkg_error_set(EPKG_FATAL, "constraint violation on " "conflicts with %s", pkg_conflict_glob(conflicts[i])); else retcode = ERROR_SQLITE(s); goto cleanup; } sqlite3_reset(stmt_conflict); } /* * Insert file * and dirs */ if (sqlite3_prepare_v2(s, sql_file, -1, &stmt_file, NULL) != SQLITE_OK) { retcode = ERROR_SQLITE(s); goto cleanup; } if (sqlite3_prepare_v2(s, sql_dir, -1, &stmt_dirs, NULL) != SQLITE_OK) { retcode = ERROR_SQLITE(s); goto cleanup; } files = pkg_files(pkg); for (i = 0; files[i] != NULL; i++) { path = pkg_file_path(files[i]); if (path[strlen(path) - 1 ] != '/') { sqlite3_bind_text(stmt_file, 1, pkg_file_path(files[i]), -1, SQLITE_STATIC); sqlite3_bind_text(stmt_file, 2, pkg_file_sha256(files[i]), -1, SQLITE_STATIC); sqlite3_bind_int64(stmt_file, 3, package_id); if ((ret = sqlite3_step(stmt_file)) != SQLITE_DONE) { if ( ret == SQLITE_CONSTRAINT) retcode = pkg_error_set(EPKG_FATAL, "constraint violation on " "path with %s", pkg_file_path(files[i])); else retcode = ERROR_SQLITE(s); goto cleanup; } sqlite3_reset(stmt_file); } else { sqlite3_bind_text(stmt_dirs, 1, pkg_get(pkg, PKG_ORIGIN), -1, SQLITE_STATIC); sqlite3_bind_text(stmt_dirs, 2, pkg_file_path(files[i]), -1, SQLITE_STATIC); if ((ret = sqlite3_step(stmt_dirs)) != SQLITE_DONE) { if ( ret == SQLITE_CONSTRAINT) retcode = pkg_error_set(EPKG_FATAL, "constraint violation on " "dirs with %s", pkg_file_path(files[i])); else retcode = ERROR_SQLITE(s); goto cleanup; } sqlite3_reset(stmt_dirs); } } /* * Insert scripts */ if (sqlite3_prepare_v2(s, sql_script, -1, &stmt_script, NULL) != SQLITE_OK) { retcode = ERROR_SQLITE(s); goto cleanup; } scripts = pkg_scripts(pkg); for (i = 0; scripts[i] != NULL; i++) { sqlite3_bind_text(stmt_script, 1, pkg_script_data(scripts[i]), -1, SQLITE_STATIC); sqlite3_bind_int(stmt_script, 2, pkg_script_type(scripts[i])); sqlite3_bind_int64(stmt_script, 3, package_id); if (sqlite3_step(stmt_script) != SQLITE_DONE) { if ( ret == SQLITE_CONSTRAINT) retcode = pkg_error_set(EPKG_FATAL, "constraint violation on " "scripts with %s", pkg_script_data(scripts[i])); else retcode = ERROR_SQLITE(s); goto cleanup; } sqlite3_reset(stmt_script); } /* * Insert options */ options = pkg_options(pkg); if (sqlite3_prepare_v2(s, sql_option, -1, &stmt_option, NULL) != SQLITE_OK) { retcode = ERROR_SQLITE(s); goto cleanup; } for (i = 0; options[i] != NULL; i++) { sqlite3_bind_text(stmt_option, 1, pkg_option_opt(options[i]), -1, SQLITE_STATIC); sqlite3_bind_text(stmt_option, 2, pkg_option_value(options[i]), -1, SQLITE_STATIC); sqlite3_bind_int64(stmt_option, 3, package_id); if (sqlite3_step(stmt_option) != SQLITE_DONE) { retcode = ERROR_SQLITE(s); goto cleanup; } sqlite3_reset(stmt_option); } cleanup: if (stmt_pkg != NULL) sqlite3_finalize(stmt_pkg); if (stmt_sel_pkg != NULL) sqlite3_finalize(stmt_sel_pkg); if (stmt_dep != NULL) sqlite3_finalize(stmt_dep); if (stmt_conflict != NULL) sqlite3_finalize(stmt_conflict); if (stmt_file != NULL) sqlite3_finalize(stmt_file); if (stmt_script != NULL) sqlite3_finalize(stmt_script); if (stmt_option != NULL) sqlite3_finalize(stmt_option); if (stmt_dirs != NULL) sqlite3_finalize(stmt_dirs); return (retcode); }
DatabaseResult Database::exec(const String sqlStmt) { DatabaseColumn dbCol; DatabaseRow dbRow; DatabaseResult dbRes; if(sqliteStatus != SQLITE_OK) throw DatabaseNotOpenException() << DebugInfo(TRACE(), DebugInfo::Error); sqliteStatus = sqlite3_prepare_v2(db, sqlStmt.data(), -1, &dbStmt, NULL); if(sqliteStatus != SQLITE_OK) throw DatabaseStatementInvalidException() << DebugInfo(String(sqlStmt) << "\n\"" << sqlite3_errmsg(db) << "\"\n" << TRACE(), DebugInfo::Error); int iCol = 0, colType = -1; int colCount = sqlite3_column_count(dbStmt); int stepRet = sqlite3_step(dbStmt); bool isNoResult = true; if(stepRet == SQLITE_ROW) isNoResult = false; while(stepRet == SQLITE_ROW) { for(iCol=0; iCol<colCount; ++iCol) { colType = sqlite3_column_type(dbStmt, iCol); if(colType == SQLITE_INTEGER) { dbCol = DatabaseColumn(sqlite3_column_int(dbStmt, iCol)); dbCol.setInt64Data(sqlite3_column_int64(dbStmt, iCol)); } else if(colType == SQLITE_FLOAT) { dbCol = DatabaseColumn(sqlite3_column_double(dbStmt, iCol)); } else if(colType == SQLITE_TEXT) { dbCol = DatabaseColumn(String(sqlite3_column_text(dbStmt, iCol))); } else if(colType == SQLITE_BLOB) { dbCol = DatabaseColumn((unsigned char*)sqlite3_column_blob(dbStmt, iCol)); } else if(colType == SQLITE_NULL) { dbCol = DatabaseColumn(true); } dbRow.addColumn(dbCol); } dbRes.addRowData(dbRow); dbRow = DatabaseRow(); stepRet = sqlite3_step(dbStmt); } sqlite3_finalize(dbStmt); if(stepRet != SQLITE_DONE) throw DatabaseResultNotDoneException() << DebugInfo(sqlite3_errmsg(db) << TRACE(), DebugInfo::Error); if(isNoResult == true) dbRes.setRowChanged(sqlite3_changes(db)); return dbRes; }
bool QgsSpatiaLiteFeatureIterator::getFeature( sqlite3_stmt *stmt, QgsFeature &feature ) { bool subsetAttributes = mRequest.flags() & QgsFeatureRequest::SubsetOfAttributes; int ret = sqlite3_step( stmt ); if ( ret == SQLITE_DONE ) { // there are no more rows to fetch return false; } if ( ret != SQLITE_ROW ) { // some unexpected error occurred QgsMessageLog::logMessage( QObject::tr( "SQLite error getting feature: %1" ).arg( QString::fromUtf8( sqlite3_errmsg( mHandle->handle() ) ) ), QObject::tr( "SpatiaLite" ) ); return false; } // one valid row has been fetched from the result set if ( !mFetchGeometry ) { // no geometry was required feature.setGeometryAndOwnership( 0, 0 ); } feature.initAttributes( mSource->mFields.count() ); feature.setFields( &mSource->mFields ); // allow name-based attribute lookups int ic; int n_columns = sqlite3_column_count( stmt ); for ( ic = 0; ic < n_columns; ic++ ) { if ( ic == 0 ) { // first column always contains the ROWID (or the primary key) QgsFeatureId fid = sqlite3_column_int64( stmt, ic ); QgsDebugMsgLevel( QString( "fid=%1" ).arg( fid ), 3 ); feature.setFeatureId( fid ); } else if ( mFetchGeometry && ic == mGeomColIdx ) { getFeatureGeometry( stmt, ic, feature ); } else { if ( subsetAttributes ) { if ( ic <= mRequest.subsetOfAttributes().size() ) { int attrIndex = mRequest.subsetOfAttributes()[ic-1]; feature.setAttribute( attrIndex, getFeatureAttribute( stmt, ic, mSource->mFields[attrIndex].type() ) ); } } else { int attrIndex = ic - 1; feature.setAttribute( attrIndex, getFeatureAttribute( stmt, ic, mSource->mFields[attrIndex].type() ) ); } } } return true; }
int pkgdb_it_next(struct pkgdb_it *it, struct pkg **pkg_p, int flags) { struct pkg *pkg; int ret; if (it == NULL) return (ERROR_BAD_ARG("it")); switch (sqlite3_step(it->stmt)) { case SQLITE_ROW: if (*pkg_p == NULL) pkg_new(pkg_p, PKG_INSTALLED); else pkg_reset(*pkg_p, PKG_INSTALLED); pkg = *pkg_p; pkg->rowid = sqlite3_column_int64(it->stmt, 0); pkg_set(pkg, PKG_ORIGIN, sqlite3_column_text(it->stmt, 1)); pkg_set(pkg, PKG_NAME, sqlite3_column_text(it->stmt, 2)); pkg_set(pkg, PKG_VERSION, sqlite3_column_text(it->stmt, 3)); pkg_set(pkg, PKG_COMMENT, sqlite3_column_text(it->stmt, 4)); pkg_set(pkg, PKG_DESC, sqlite3_column_text(it->stmt, 5)); pkg_set(pkg, PKG_MESSAGE, sqlite3_column_text(it->stmt, 6)); pkg_set(pkg, PKG_ARCH, sqlite3_column_text(it->stmt, 7)); pkg_set(pkg, PKG_OSVERSION, sqlite3_column_text(it->stmt, 8)); pkg_set(pkg, PKG_MAINTAINER, sqlite3_column_text(it->stmt, 9)); pkg_set(pkg, PKG_WWW, sqlite3_column_text(it->stmt, 10)); pkg_set(pkg, PKG_PREFIX, sqlite3_column_text(it->stmt, 11)); pkg_setflatsize(pkg, sqlite3_column_int64(it->stmt, 12)); if (it->type == IT_UPGRADE) { pkg->type = PKG_UPGRADE; pkg_set(pkg, PKG_NEWVERSION, sqlite3_column_text(it->stmt, 13)); pkg_setnewflatsize(pkg, sqlite3_column_int64(it->stmt, 14)); pkg_setnewpkgsize(pkg, sqlite3_column_int64(it->stmt, 15)); pkg_set(pkg, PKG_REPOPATH, sqlite3_column_text(it->stmt, 16)); } if (flags & PKG_LOAD_DEPS) if ((ret = pkgdb_loaddeps(it->db, pkg)) != EPKG_OK) return (ret); if (flags & PKG_LOAD_RDEPS) if ((ret = pkgdb_loadrdeps(it->db, pkg)) != EPKG_OK) return (ret); if (flags & PKG_LOAD_CONFLICTS) if ((ret = pkgdb_loadconflicts(it->db, pkg)) != EPKG_OK) return (ret); if (flags & PKG_LOAD_FILES) if ((ret = pkgdb_loadfiles(it->db, pkg)) != EPKG_OK) return (ret); if (flags & PKG_LOAD_SCRIPTS) if ((ret = pkgdb_loadscripts(it->db, pkg)) != EPKG_OK) return (ret); if (flags & PKG_LOAD_OPTIONS) if ((ret = pkgdb_loadoptions(it->db, pkg)) != EPKG_OK) return (ret); if (flags & PKG_LOAD_MTREE) if ((ret = pkgdb_loadmtree(it->db, pkg)) != EPKG_OK) return (ret); return (EPKG_OK); case SQLITE_DONE: return (EPKG_END); default: return (ERROR_SQLITE(it->db->sqlite)); } }
int overlay_rhizome_add_advertisements(int interface_number,overlay_buffer *e) { int pass; int bytes=e->sizeLimit-e->length; int overhead=1+8+1+3+1+1+1; /* maximum overhead */ int slots=(bytes-overhead)/RHIZOME_BAR_BYTES; if (slots>30) slots=30; int slots_used=0; int bytes_used=0; int bytes_available=bytes-overhead-1 /* one byte held for expanding RFS */; int bundles_advertised=0; if (slots<1) return WHY("No room for node advertisements"); if (!rhizome_db) return WHY("Rhizome not enabled"); if (ob_append_byte(e,OF_TYPE_RHIZOME_ADVERT)) return WHY("could not add rhizome bundle advertisement header"); ob_append_byte(e,1); /* TTL */ int rfs_offset=e->length; /* remember where the RFS byte gets stored so that we can patch it later */ ob_append_byte(e,1+8+1+1+1+RHIZOME_BAR_BYTES*slots_used/* RFS */); /* Stuff in dummy address fields */ ob_append_byte(e,OA_CODE_BROADCAST); { int i; for(i=0;i<8;i++) ob_append_byte(e,random()&0xff); } /* BPI for broadcast */ ob_append_byte(e,OA_CODE_PREVIOUS); ob_append_byte(e,OA_CODE_SELF); /* Randomly choose whether to advertise manifests or BARs first. */ int skipmanifests=random()&1; /* Version of rhizome advert block: 1 = manifests then BARs, 2 = BARs only */ ob_append_byte(e,1+skipmanifests); /* XXX Should add priority bundles here. XXX Should prioritise bundles for subscribed groups, Serval-authorised files etc over common bundles. XXX Should wait a while after going through bundle list so that we don't waste CPU on db queries if there are not many bundles. Actually, we probably just shouldn't be sending bundles blindly on every tick. XXX How do we indicate group membership with BARs? Or do groups actively poll? */ if (debug&DEBUG_RHIZOME) WHY("Group handling not completely thought out here yet."); /* Get number of bundles available if required */ bundles_available=sqlite_exec_int64("SELECT COUNT(BAR) FROM MANIFESTS;"); if (bundles_available==-1||(bundle_offset[0]>=bundles_available)) bundle_offset[0]=0; if (bundles_available==-1||(bundle_offset[1]>=bundles_available)) bundle_offset[1]=0; for(pass=skipmanifests;pass<2;pass++) { sqlite3_stmt *statement; char query[1024]; switch(pass) { case 0: /* Full manifests */ snprintf(query,1024,"SELECT MANIFEST,ROWID FROM MANIFESTS LIMIT %d,%d", bundle_offset[pass],slots); break; case 1: /* BARs */ snprintf(query,1024,"SELECT BAR,ROWID FROM MANIFESTS LIMIT %d,%d", bundle_offset[pass],slots); break; } switch (sqlite3_prepare_v2(rhizome_db,query,-1,&statement,NULL)) { case SQLITE_OK: case SQLITE_DONE: case SQLITE_ROW: break; default: sqlite3_finalize(statement); sqlite3_close(rhizome_db); rhizome_db=NULL; WHY(query); WHY(sqlite3_errmsg(rhizome_db)); return WHY("Could not prepare sql statement for fetching BARs for advertisement."); } while((bytes_used<bytes_available)&&(sqlite3_step(statement)==SQLITE_ROW)&& (e->length+RHIZOME_BAR_BYTES<=e->sizeLimit)) { sqlite3_blob *blob; int column_type=sqlite3_column_type(statement, 0); switch(column_type) { case SQLITE_BLOB: if (sqlite3_blob_open(rhizome_db,"main","manifests", pass?"bar":"manifest", sqlite3_column_int64(statement,1) /* rowid */, 0 /* read only */,&blob)!=SQLITE_OK) { WHY("Couldn't open blob"); continue; } int blob_bytes=sqlite3_blob_bytes(blob); if (pass&&(blob_bytes!=RHIZOME_BAR_BYTES)) { if (debug&DEBUG_RHIZOME) fprintf(stderr,"Found a BAR that is the wrong size - ignoring\n"); continue; } /* Only include manifests that are <=1KB inline. Longer ones are only advertised by BAR */ if (blob_bytes>1024) continue; int overhead=0; if (!pass) overhead=2; if (ob_makespace(e,overhead+blob_bytes)) { if (debug&DEBUG_RHIZOME) fprintf(stderr,"Stopped cramming %s into Rhizome advertisement frame.\n", pass?"BARs":"manifests"); break; } if (!pass) { /* put manifest length field and manifest ID */ e->bytes[e->length]=(blob_bytes>>8)&0xff; e->bytes[e->length+1]=(blob_bytes>>0)&0xff; if (debug&DEBUG_RHIZOME) fprintf(stderr,"length bytes written at offset 0x%x\n",e->length); } if (sqlite3_blob_read(blob,&e->bytes[e->length+overhead],blob_bytes,0) !=SQLITE_OK) { if (debug&DEBUG_RHIZOME) WHY("Couldn't read from blob"); sqlite3_blob_close(blob); continue; } e->length+=overhead+blob_bytes; bytes_used+=overhead+blob_bytes; bundles_advertised++; sqlite3_blob_close(blob); } } sqlite3_finalize(statement); if (!pass) { /* Mark end of whole manifests by writing 0xff, which is more than the MSB of a manifest's length is allowed to be. */ ob_append_byte(e,0xff); } }
sqlite3_int64 Query::ColumnInt64(int index) { return sqlite3_column_int64(statement, index); }
static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ fulltext_cursor *c = (fulltext_cursor *) pCursor; *pRowid = sqlite3_column_int64(c->pStmt, 0); return SQLITE_OK; }
/*! \brief Load geometry (linestring SBP layer) \return number of invalid features */ int VFKDataBlockSQLite::LoadGeometryLineStringSBP() { int nInvalid = 0; VFKDataBlockSQLite *poDataBlockPoints = (VFKDataBlockSQLite *) m_poReader->GetDataBlock("SOBR"); if (NULL == poDataBlockPoints) { CPLError(CE_Failure, CPLE_FileIO, "Data block %s not found.\n", m_pszName); return nInvalid; } int nGeometries = 0; VFKReaderSQLite *poReader = (VFKReaderSQLite*) m_poReader; poDataBlockPoints->LoadGeometry(); if (LoadGeometryFromDB()) /* try to load geometry from DB */ return 0; CPLString osSQL; osSQL.Printf("UPDATE %s SET %s = -1", m_pszName, FID_COLUMN); poReader->ExecuteSQL(osSQL.c_str()); bool bValid = true; int iIdx = 0; VFKFeatureSQLite *poLine = NULL; for( int i = 0; i < 2; i++ ) { /* first collect linestrings related to HP, OB or DPM then collect rest of linestrings */ if( i == 0 ) osSQL.Printf("SELECT BP_ID,PORADOVE_CISLO_BODU,PARAMETRY_SPOJENI,_rowid_ FROM '%s' WHERE " "HP_ID IS NOT NULL OR OB_ID IS NOT NULL OR DPM_ID IS NOT NULL " "ORDER BY HP_ID,OB_ID,DPM_ID,PORADOVE_CISLO_BODU", m_pszName); else osSQL.Printf("SELECT BP_ID,PORADOVE_CISLO_BODU,PARAMETRY_SPOJENI,_rowid_ FROM '%s' WHERE " "OB_ID IS NULL AND HP_ID IS NULL AND DPM_ID IS NULL " "ORDER BY ID,PORADOVE_CISLO_BODU", m_pszName); sqlite3_stmt *hStmt = poReader->PrepareStatement(osSQL.c_str()); if (poReader->IsSpatial()) poReader->ExecuteSQL("BEGIN"); std::vector<int> rowIdFeat; CPLString szFType; OGRLineString oOGRLine; while(poReader->ExecuteSQL(hStmt) == OGRERR_NONE) { // read values const GUIntBig id = sqlite3_column_int64(hStmt, 0); const GUIntBig ipcb = sqlite3_column_int64(hStmt, 1); szFType = (char *) sqlite3_column_text(hStmt, 2); int rowId = sqlite3_column_int(hStmt, 3); if (ipcb == 1) { VFKFeatureSQLite *poFeature = (VFKFeatureSQLite *) GetFeatureByIndex(iIdx); if( poFeature == NULL ) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot retrieve feature %d", iIdx); break; } poFeature->SetRowId(rowId); /* set geometry & reset */ CPLString szFTypeLine; if( poLine && !SetGeometryLineString( poLine, &oOGRLine, bValid, szFTypeLine, rowIdFeat, nGeometries) ) { nInvalid++; } bValid = true; poLine = poFeature; szFTypeLine = szFType; iIdx++; } VFKFeatureSQLite *poPoint = (VFKFeatureSQLite *) poDataBlockPoints->GetFeature("ID", id); if( poPoint ) { OGRPoint *pt = (OGRPoint *) poPoint->GetGeometry(); if (pt) { oOGRLine.addPoint(pt); } else { CPLDebug("OGR-VFK", "Geometry (point ID = " CPL_FRMT_GUIB ") not valid", id); bValid = false; } } else { CPLDebug("OGR-VFK", "Point ID = " CPL_FRMT_GUIB " not found (rowid = %d)", id, rowId); bValid = false; } /* add vertex to the linestring */ rowIdFeat.push_back(rowId); } /* add last line */ if( poLine && !SetGeometryLineString( poLine, &oOGRLine, bValid, szFType.c_str(), rowIdFeat, nGeometries) ) { nInvalid++; } poLine = NULL; if (poReader->IsSpatial()) poReader->ExecuteSQL("COMMIT"); } /* update number of geometries in VFK_DB_TABLE table */ UpdateVfkBlocks(nGeometries); return nInvalid; }
int database::fillTable(sqlite3_stmt* stmt, DBDataTable* dataTable) { int numColumns = sqlite3_column_count(stmt); dataTable->setColumnCount(numColumns); int addedRows = 0; while (1) { int err = sqlite3_step(stmt); if (err == SQLITE_ROW) { dataTable->addRow(); for (int i = 0; i < numColumns; i++) { int type = sqlite3_column_type(stmt, i); if (type == SQLITE_TEXT) { // TEXT data dataTable->setColumnType(i, DBDataType_String); const char* text = reinterpret_cast<const char*>(sqlite3_column_text(stmt, i)); size_t sizeIncludingNull = sqlite3_column_bytes(stmt, i) + 1; if (!dataTable->putString(addedRows, i, text, sizeIncludingNull)) { // NCDBH_SQL_LOGD("Failed allocating %u bytes for text at %d,%d", sizeIncludingNull, addedRows, i); std::cout << "failed allocating bytes\n"; break; } // NCDBH_SQL_LOGD("%d,%d is TEXT with %u bytes", addedRows, i, sizeIncludingNull); } else if (type == SQLITE_INTEGER) { // INTEGER data dataTable->setColumnType(i, DBDataType_Integer); int64_t value = sqlite3_column_int64(stmt, i); if (!dataTable->putLong(addedRows, i, value)) { // NCDBH_SQL_LOGD("Failed allocating space for a long in column %d", i); break; } // NCDBH_SQL_LOGD("%d,%d is INTEGER 0x%016llx", addedRows, i, value); } else if (type == SQLITE_FLOAT) { // FLOAT data dataTable->setColumnType(i, DBDataType_Float); double value = sqlite3_column_double(stmt, i); if (!dataTable->putDouble(addedRows, i, value)) { // NCDBH_SQL_LOGD("Failed allocating space for a double in column %d", i); break; } // NCDBH_SQL_LOGD("%d,%d is FLOAT %lf", addedRows, i, value); } else if (type == SQLITE_BLOB) { // BLOB data dataTable->setColumnType(i, DBDataType_Blob); const void* blob = sqlite3_column_blob(stmt, i); size_t size = sqlite3_column_bytes(stmt, i); if (!dataTable->putBlob(addedRows, i, blob, size)) { // NCDBH_SQL_LOGD("Failed allocating %u bytes for blob at %d,%d", size, addedRows, i); break; } // NCDBH_SQL_LOGD("%d,%d is Blob with %u bytes", addedRows, i, size); } else if (type == SQLITE_NULL) { // NULL field dataTable->setColumnType(i, DBDataType_Null); if (!dataTable->putNull(addedRows, i)) { // NCDBH_SQL_LOGD("Failed allocating space for a null in column %d", i); break; } // NCDBH_SQL_LOGD("%d,%d is NULL", addedRows, i); } else { // Unknown data // NCDBH_SQL_LOGE("Unknown column type when filling database data table"); std::cout << "Unknown column type when filling database data table"; break; } } addedRows++; } else if (err == SQLITE_DONE) { // complete! std::cout << "complete!\n"; break; } else if (err == SQLITE_LOCKED || err == SQLITE_BUSY) { // retry? break; } else { // exception? std::cout << "query error with : " << err << "\n"; break; } } return addedRows; }
/*! \brief Load geometry (linestring HP/DPM layer) \return number of invalid features */ int VFKDataBlockSQLite::LoadGeometryLineStringHP() { int nInvalid = 0; VFKReaderSQLite *poReader = (VFKReaderSQLite*) m_poReader; VFKDataBlockSQLite *poDataBlockLines = (VFKDataBlockSQLite *) m_poReader->GetDataBlock("SBP"); if (NULL == poDataBlockLines) { CPLError(CE_Failure, CPLE_FileIO, "Data block %s not found.", m_pszName); return nInvalid; } poDataBlockLines->LoadGeometry(); if (LoadGeometryFromDB()) /* try to load geometry from DB */ return 0; CPLString osColumn; osColumn.Printf("%s_ID", m_pszName); const char *vrColumn[2] = { osColumn.c_str(), "PORADOVE_CISLO_BODU" }; GUIntBig vrValue[2] = { 0, 1 }; // Reduce to first segment. CPLString osSQL; osSQL.Printf("SELECT ID,%s,rowid FROM %s", FID_COLUMN, m_pszName); /* TODO: handle points in DPM */ if (EQUAL(m_pszName, "DPM")) osSQL += " WHERE SOURADNICE_X IS NULL"; sqlite3_stmt *hStmt = poReader->PrepareStatement(osSQL.c_str()); if (poReader->IsSpatial()) poReader->ExecuteSQL("BEGIN"); int nGeometries = 0; while( poReader->ExecuteSQL(hStmt) == OGRERR_NONE ) { /* read values */ vrValue[0] = sqlite3_column_int64(hStmt, 0); const long iFID = static_cast<long>(sqlite3_column_int64(hStmt, 1)); const int rowId = sqlite3_column_int(hStmt, 2); VFKFeatureSQLite *poFeature = (VFKFeatureSQLite *) GetFeatureByIndex(rowId - 1); CPLAssert(NULL != poFeature && poFeature->GetFID() == iFID); VFKFeatureSQLite *poLine = poDataBlockLines->GetFeature(vrColumn, vrValue, 2, TRUE); OGRGeometry *poOgrGeometry = NULL; if( !poLine ) { poOgrGeometry = NULL; } else { poOgrGeometry = poLine->GetGeometry(); } if (!poOgrGeometry || !poFeature->SetGeometry(poOgrGeometry)) { CPLDebug("OGR-VFK", "VFKDataBlockSQLite::LoadGeometryLineStringHP(): name=%s fid=%ld " "id=" CPL_FRMT_GUIB " -> %s geometry", m_pszName, iFID, vrValue[0], poOgrGeometry ? "invalid" : "empty"); nInvalid++; continue; } /* store also geometry in DB */ if (poReader->IsSpatial() && SaveGeometryToDB(poOgrGeometry, rowId) != OGRERR_FAILURE && poOgrGeometry) nGeometries++; } /* update number of geometries in VFK_DB_TABLE table */ UpdateVfkBlocks(nGeometries); if (poReader->IsSpatial()) poReader->ExecuteSQL("COMMIT"); return nInvalid; }
DWORD SamDbGetObjectRecordInfoBySID_inlock( PSAM_DIRECTORY_CONTEXT pDirectoryContext, PCSTR pszObjectSID, PLONG64 pllObjectRecordId, SAMDB_OBJECT_CLASS* pObjectClass ) { DWORD dwError = 0; sqlite3_stmt* pSqlStatement = NULL; LONG64 llObjectRecordId = 0; SAMDB_OBJECT_CLASS objectClass = SAMDB_OBJECT_CLASS_UNKNOWN; BAIL_ON_INVALID_POINTER(pszObjectSID); if (!pDirectoryContext->pDbContext->pQueryObjectRecordInfoStmt) { PCSTR pszQueryTemplate = "SELECT " SAM_DB_COL_RECORD_ID "," \ SAM_DB_COL_OBJECT_CLASS \ " FROM " SAM_DB_OBJECTS_TABLE \ " WHERE " SAM_DB_COL_OBJECT_SID " = ?1"; dwError = sqlite3_prepare_v2( pDirectoryContext->pDbContext->pDbHandle, pszQueryTemplate, -1, &pDirectoryContext->pDbContext->pQueryObjectRecordInfoStmt, NULL); BAIL_ON_SAMDB_SQLITE_ERROR_DB( dwError, pDirectoryContext->pDbContext->pDbHandle); } pSqlStatement = pDirectoryContext->pDbContext->pQueryObjectRecordInfoStmt; dwError = sqlite3_bind_text( pSqlStatement, 1, pszObjectSID, -1, SQLITE_TRANSIENT); BAIL_ON_SAMDB_SQLITE_ERROR_STMT(dwError, pSqlStatement); if ((dwError = sqlite3_step(pSqlStatement) == SQLITE_ROW)) { if (sqlite3_column_count(pSqlStatement) != 2) { dwError = LW_ERROR_DATA_ERROR; BAIL_ON_SAMDB_ERROR(dwError); } llObjectRecordId = sqlite3_column_int64( pSqlStatement, 0); objectClass = sqlite3_column_int( pSqlStatement, 1); dwError = LW_ERROR_SUCCESS; } else if (dwError == SQLITE_DONE) { dwError = LW_ERROR_NO_SUCH_OBJECT; } BAIL_ON_SAMDB_SQLITE_ERROR_STMT(dwError, pSqlStatement); *pllObjectRecordId = llObjectRecordId; *pObjectClass = objectClass; cleanup: if (pDirectoryContext->pDbContext->pQueryObjectRecordInfoStmt) { sqlite3_reset(pDirectoryContext->pDbContext->pQueryObjectRecordInfoStmt); } return dwError; error: *pllObjectRecordId = 0; *pObjectClass = SAMDB_OBJECT_CLASS_UNKNOWN; goto cleanup; }
/*! \brief Load geometry from DB \return true if geometry successfully loaded otherwise false */ bool VFKDataBlockSQLite::LoadGeometryFromDB() { VFKReaderSQLite *poReader = (VFKReaderSQLite*) m_poReader; if (!poReader->IsSpatial()) /* check if DB is spatial */ return false; CPLString osSQL; osSQL.Printf("SELECT num_geometries FROM %s WHERE table_name = '%s'", VFK_DB_TABLE, m_pszName); sqlite3_stmt *hStmt = poReader->PrepareStatement(osSQL.c_str()); if (poReader->ExecuteSQL(hStmt) != OGRERR_NONE) return false; const int nGeometries = sqlite3_column_int(hStmt, 0); sqlite3_finalize(hStmt); if( nGeometries < 1 ) return false; const bool bSkipInvalid = EQUAL(m_pszName, "OB") || EQUAL(m_pszName, "OP") || EQUAL(m_pszName, "OBBP"); /* load geometry from DB */ osSQL.Printf("SELECT %s,rowid,%s FROM %s ", GEOM_COLUMN, FID_COLUMN, m_pszName); if (EQUAL(m_pszName, "SBP")) osSQL += "WHERE PORADOVE_CISLO_BODU = 1 "; osSQL += "ORDER BY "; osSQL += FID_COLUMN; hStmt = poReader->PrepareStatement(osSQL.c_str()); int rowId = 0; int nInvalid = 0; int nGeometriesCount = 0; while(poReader->ExecuteSQL(hStmt) == OGRERR_NONE) { rowId++; // =sqlite3_column_int(hStmt, 1); #ifdef DEBUG const GIntBig iFID = sqlite3_column_int64(hStmt, 2); #endif VFKFeatureSQLite *poFeature = (VFKFeatureSQLite *) GetFeatureByIndex(rowId - 1); CPLAssert(NULL != poFeature && poFeature->GetFID() == iFID); // read geometry from DB const int nBytes = sqlite3_column_bytes(hStmt, 0); OGRGeometry *poGeometry = NULL; if (nBytes > 0 && OGRGeometryFactory::createFromWkb((GByte*) sqlite3_column_blob(hStmt, 0), NULL, &poGeometry, nBytes) == OGRERR_NONE) { nGeometriesCount++; if (!poFeature->SetGeometry(poGeometry)) { nInvalid++; } delete poGeometry; } else { nInvalid++; } } CPLDebug("OGR-VFK", "%s: %d geometries loaded from DB", m_pszName, nGeometriesCount); if (nGeometriesCount != nGeometries) { CPLError(CE_Warning, CPLE_AppDefined, "%s: %d geometries loaded (should be %d)", m_pszName, nGeometriesCount, nGeometries); } if (nInvalid > 0 && !bSkipInvalid) { CPLError(CE_Warning, CPLE_AppDefined, "%s: %d features with invalid or empty geometry", m_pszName, nInvalid); } return true; }
const char * dbop3_first(DBOP *dbop, const char *name, regex_t *preg, int flags) { int rc; char *key; STRBUF *sql = strbuf_open_tempbuf(); dbop->done = 0; /* This is turned on when it receives SQLITE_DONE. */ strbuf_puts(sql, "select rowid, * from "); strbuf_puts(sql, dbop->tblname); if (name) { strbuf_puts(sql, " where key "); if (dbop->ioflags & DBOP_PREFIX) { /* * In sqlite3, 'like' ignores case. 'glob' does not ignore case. */ strbuf_puts(sql, "glob '"); strbuf_puts(sql, name); strbuf_puts(sql, "*'"); } else { strbuf_puts(sql, "= '"); strbuf_puts(sql, name); strbuf_puts(sql, "'"); } strlimcpy(dbop->key, name, sizeof(dbop->key)); dbop->keylen = strlen(name); } strbuf_puts(sql, " order by key"); if (dbop->stmt) { rc = sqlite3_finalize(dbop->stmt); if (rc != SQLITE_OK) die("dbop3_finalize failed. (rc = %d)", rc); dbop->stmt = NULL; } rc = sqlite3_prepare_v2(dbop->db3, strbuf_value(sql), -1, &dbop->stmt, NULL); if (rc != SQLITE_OK) die("dbop3_first: sqlite3_prepare_v2 failed. (rc = %d)", rc); /* * 0: rowid * 1: key * 2: dat * 3: flags */ for (;;) { /* Once it receives SQLITE_DONE, do not never return value */ if (dbop->done) return NULL; rc = sqlite3_step(dbop->stmt); if (rc == SQLITE_DONE) goto finish; else if (rc == SQLITE_ROW) { dbop->readcount++; dbop->lastrowid = sqlite3_column_int64(dbop->stmt, 0); key = (char *)sqlite3_column_text(dbop->stmt, 1); if (name) { if (dbop->ioflags & DBOP_PREFIX) { if (strncmp(key, dbop->key, dbop->keylen)) goto finish; } else { if (strcmp(key, dbop->key)) goto finish; } if (dbop->preg && regexec(dbop->preg, key, 0, 0, 0) != 0) continue; } else { /* skip meta records */ if (ismeta(key) && !(dbop->openflags & DBOP_RAW)) continue; if (dbop->preg && regexec(dbop->preg, key, 0, 0, 0) != 0) continue; } break; } else { die("dbop3_first: something is wrong (rc = %d).", rc); } } strbuf_clear(dbop->sb); strbuf_puts0(dbop->sb, (char *)sqlite3_column_text(dbop->stmt, 2)); dbop->lastsize = strbuf_getlen(dbop->sb) - 1; dbop->lastflag = (char *)sqlite3_column_text(dbop->stmt, 3); if (dbop->lastflag) strbuf_puts(dbop->sb, dbop->lastflag); dbop->lastdat = strbuf_value(dbop->sb); if (dbop->lastflag) dbop->lastflag = dbop->lastdat + dbop->lastsize + 1; dbop->lastkey = key; dbop->lastkeysize = strlen(dbop->lastkey); strbuf_release_tempbuf(sql); if (flags & DBOP_KEY) { strlimcpy(dbop->prev, key, sizeof(dbop->prev)); return key; } return dbop->lastdat; finish: strbuf_release_tempbuf(sql); dbop->done = 1; dbop->lastdat = NULL; dbop->lastsize = 0; dbop->lastflag = NULL; return dbop->lastdat; }
/* ** Check that the contents of the FTS index match that of the %_content ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return ** some other SQLite error code if an error occurs while attempting to ** determine this. */ int sqlite3Fts5StorageIntegrity(Fts5Storage *p){ Fts5Config *pConfig = p->pConfig; int rc; /* Return code */ int *aColSize; /* Array of size pConfig->nCol */ i64 *aTotalSize; /* Array of size pConfig->nCol */ Fts5IntegrityCtx ctx; sqlite3_stmt *pScan; memset(&ctx, 0, sizeof(Fts5IntegrityCtx)); ctx.pConfig = p->pConfig; aTotalSize = (i64*)sqlite3_malloc64(pConfig->nCol*(sizeof(int)+sizeof(i64))); if( !aTotalSize ) return SQLITE_NOMEM; aColSize = (int*)&aTotalSize[pConfig->nCol]; memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol); /* Generate the expected index checksum based on the contents of the ** %_content table. This block stores the checksum in ctx.cksum. */ rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0); if( rc==SQLITE_OK ){ int rc2; while( SQLITE_ROW==sqlite3_step(pScan) ){ int i; ctx.iRowid = sqlite3_column_int64(pScan, 0); ctx.szCol = 0; if( pConfig->bColumnsize ){ rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize); } if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){ rc = sqlite3Fts5TermsetNew(&ctx.pTermset); } for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){ if( pConfig->abUnindexed[i] ) continue; ctx.iCol = i; ctx.szCol = 0; if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){ rc = sqlite3Fts5TermsetNew(&ctx.pTermset); } if( rc==SQLITE_OK ){ rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT, (const char*)sqlite3_column_text(pScan, i+1), sqlite3_column_bytes(pScan, i+1), (void*)&ctx, fts5StorageIntegrityCallback ); } if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){ rc = FTS5_CORRUPT; } aTotalSize[i] += ctx.szCol; if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){ sqlite3Fts5TermsetFree(ctx.pTermset); ctx.pTermset = 0; } } sqlite3Fts5TermsetFree(ctx.pTermset); ctx.pTermset = 0; if( rc!=SQLITE_OK ) break; } rc2 = sqlite3_reset(pScan); if( rc==SQLITE_OK ) rc = rc2; } /* Test that the "totals" (sometimes called "averages") record looks Ok */ if( rc==SQLITE_OK ){ int i; rc = fts5StorageLoadTotals(p, 0); for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){ if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT; } } /* Check that the %_docsize and %_content tables contain the expected ** number of rows. */ if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){ i64 nRow = 0; rc = fts5StorageCount(p, "content", &nRow); if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT; } if( rc==SQLITE_OK && pConfig->bColumnsize ){ i64 nRow = 0; rc = fts5StorageCount(p, "docsize", &nRow); if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT; } /* Pass the expected checksum down to the FTS index module. It will ** verify, amongst other things, that it matches the checksum generated by ** inspecting the index itself. */ if( rc==SQLITE_OK ){ rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum); } sqlite3_free(aTotalSize); return rc; }
const char * dbop3_next(DBOP *dbop) { int rc; char *key, *dat; /* * 0: rowid * 1: key * 2: dat * 3: flags */ for (;;) { /* Once it receives SQLITE_DONE, do not never return value */ if (dbop->done) return NULL; rc = sqlite3_step(dbop->stmt); if (rc == SQLITE_DONE) goto finish; else if (rc == SQLITE_ROW) { dbop->readcount++; dbop->lastrowid = sqlite3_column_int64(dbop->stmt, 0); key = (char *)sqlite3_column_text(dbop->stmt, 1); dat = (char *)sqlite3_column_text(dbop->stmt, 2); /* skip meta records */ if (!(dbop->openflags & DBOP_RAW)) { if (dbop->ioflags & DBOP_KEY && ismeta(key)) continue; else if (ismeta(dat)) continue; } if (dbop->ioflags & DBOP_KEY) { if (!strcmp(dbop->prev, key)) continue; if (strlen(key) > MAXKEYLEN) die("primary key too long."); strlimcpy(dbop->prev, key, sizeof(dbop->prev)); } if (dbop->ioflags & DBOP_PREFIX) { if (strncmp(key, dbop->key, dbop->keylen)) goto finish; } else if (dbop->keylen) { if (strcmp(key, dbop->key)) goto finish; } if (dbop->preg && regexec(dbop->preg, key, 0, 0, 0) != 0) continue; break; } else { die("dbop3_next: something is wrong (rc = %d).", rc); } } strbuf_clear(dbop->sb); strbuf_puts0(dbop->sb, (char *)sqlite3_column_text(dbop->stmt, 2)); dbop->lastsize = strbuf_getlen(dbop->sb) - 1; dbop->lastflag = (char *)sqlite3_column_text(dbop->stmt, 3); if (dbop->lastflag) strbuf_puts(dbop->sb, dbop->lastflag); dbop->lastdat = strbuf_value(dbop->sb); if (dbop->lastflag) dbop->lastflag = dbop->lastdat + dbop->lastsize + 1; dbop->lastkey = key; dbop->lastkeysize = strlen(dbop->lastkey); if (dbop->ioflags & DBOP_KEY) { strlimcpy(dbop->prev, key, sizeof(dbop->prev)); return key; } return dbop->lastdat; finish: dbop->done = 1; dbop->lastdat = NULL; dbop->lastsize = 0; return dbop->lastdat; }
int rspamd_sqlite3_run_prstmt (rspamd_mempool_t *pool, sqlite3 *db, GArray *stmts, gint idx, ...) { gint retcode; va_list ap; sqlite3_stmt *stmt; gint i, rowid, nargs, j; gint64 len; gpointer p; struct rspamd_sqlite3_prstmt *nst; const char *argtypes; if (idx < 0 || idx >= (gint)stmts->len) { return -1; } nst = &g_array_index (stmts, struct rspamd_sqlite3_prstmt, idx); stmt = nst->stmt; g_assert (nst != NULL); msg_debug_pool ("executing `%s`", nst->sql); argtypes = nst->args; sqlite3_clear_bindings (stmt); sqlite3_reset (stmt); va_start (ap, idx); nargs = 1; for (i = 0, rowid = 1; argtypes[i] != '\0'; i ++) { switch (argtypes[i]) { case 'T': for (j = 0; j < nargs; j ++, rowid ++) { sqlite3_bind_text (stmt, rowid, va_arg (ap, const char*), -1, SQLITE_STATIC); } nargs = 1; break; case 'V': case 'B': for (j = 0; j < nargs; j ++, rowid ++) { len = va_arg (ap, gint64); sqlite3_bind_text (stmt, rowid, va_arg (ap, const char*), len, SQLITE_STATIC); } nargs = 1; break; case 'I': for (j = 0; j < nargs; j ++, rowid ++) { sqlite3_bind_int64 (stmt, rowid, va_arg (ap, gint64)); } nargs = 1; break; case 'S': for (j = 0; j < nargs; j ++, rowid ++) { sqlite3_bind_int (stmt, rowid, va_arg (ap, gint)); } nargs = 1; break; case '*': nargs = va_arg (ap, gint); break; } } va_end (ap); retcode = sqlite3_step (stmt); if (retcode == nst->result) { argtypes = nst->ret; for (i = 0; argtypes != NULL && argtypes[i] != '\0'; i ++) { switch (argtypes[i]) { case 'T': *va_arg (ap, char**) = g_strdup (sqlite3_column_text (stmt, i)); break; case 'I': *va_arg (ap, gint64*) = sqlite3_column_int64 (stmt, i); break; case 'S': *va_arg (ap, int*) = sqlite3_column_int (stmt, i); break; case 'L': *va_arg (ap, gint64*) = sqlite3_last_insert_rowid (db); break; case 'B': len = sqlite3_column_bytes (stmt, i); g_assert (len >= 0); p = g_malloc (len); memcpy (p, sqlite3_column_blob (stmt, i), len); *va_arg (ap, gint64*) = len; *va_arg (ap, gpointer*) = p; break; } } if (!(nst->flags & RSPAMD_SQLITE3_STMT_MULTIPLE)) { sqlite3_clear_bindings (stmt); sqlite3_reset (stmt); } return SQLITE_OK; } else if (retcode != SQLITE_DONE && retcode != SQLITE_OK && retcode != SQLITE_ROW) { msg_warn_pool ("failed to execute query %s: %d, %s", nst->sql, retcode, sqlite3_errmsg (db)); } if (!(nst->flags & RSPAMD_SQLITE3_STMT_MULTIPLE)) { sqlite3_clear_bindings (stmt); sqlite3_reset (stmt); } return retcode; }
result_t SQLite::execute(const char *sql, int sLen, obj_ptr<DBResult_base> &retVal) { if (!m_db) return CHECK_ERROR(CALL_E_INVALID_CALL); sqlite3_stmt *stmt = 0; const char *pStr1; if (sqlite3_prepare_v2(m_db, sql, sLen, &stmt, &pStr1)) { result_t hr = CHECK_ERROR(Runtime::setError(sqlite3_errmsg(m_db))); if (stmt) sqlite3_finalize(stmt); return hr; } if (!stmt) return CHECK_ERROR(Runtime::setError("Query was empty")); int columns = sqlite3_column_count(stmt); obj_ptr<DBResult> res; if (columns > 0) { int i; res = new DBResult(columns); for (i = 0; i < columns; i++) { std::string s = sqlite3_column_name(stmt, i); res->setField(i, s); } while (true) { int r = sqlite3_step_sleep(stmt, SQLITE_SLEEP_TIME); if (r == SQLITE_ROW) { res->beginRow(); for (i = 0; i < columns; i++) { Variant v; switch (sqlite3_column_type(stmt, i)) { case SQLITE_NULL: break; case SQLITE_INTEGER: v = (int64_t) sqlite3_column_int64(stmt, i); break; case SQLITE_FLOAT: v = sqlite3_column_double(stmt, i); break; default: const char *type = sqlite3_column_decltype(stmt, i); if (type && (!qstricmp(type, "blob") || !qstricmp(type, "tinyblob") || !qstricmp(type, "mediumblob") || !qstricmp(type, "longblob"))) { const char *data = (const char *) sqlite3_column_blob(stmt, i); int size = sqlite3_column_bytes(stmt, i); v = new Buffer(std::string(data, size)); } else if (type && (!qstricmp(type, "datetime") || !qstricmp(type, "date") || !qstricmp(type, "time"))) { const char *data = (const char *) sqlite3_column_text(stmt, i); int size = sqlite3_column_bytes(stmt, i); v.parseDate(data, size); } else { const char *data = (const char *) sqlite3_column_text(stmt, i); int size = sqlite3_column_bytes(stmt, i); v = std::string(data, size); } break; } res->rowValue(i, v); } res->endRow(); } else if (r == SQLITE_DONE) break; else { sqlite3_finalize(stmt); return CHECK_ERROR(Runtime::setError(sqlite3_errmsg(m_db))); } } } else { int r = sqlite3_step_sleep(stmt, SQLITE_SLEEP_TIME); if (r == SQLITE_DONE) res = new DBResult(sqlite3_changes(m_db), sqlite3_last_insert_rowid(m_db)); else { sqlite3_finalize(stmt); return CHECK_ERROR(Runtime::setError(sqlite3_errmsg(m_db))); } } sqlite3_finalize(stmt); retVal = res; return 0; }
int64_t CCResultSet::int64ForColumnIndex(int columnIdx) { return (int64_t)sqlite3_column_int64(m_statement->getStatement(), columnIdx); }
static int cdb_get(struct custdb_handle *ch, const ChopstixPhone *phone, ChopstixCustomer *cust) { char *phonestr; int64_t cust_ID = 0; sqlite3_stmt *q = NULL; ChopstixCredit *cc; int dupcount = 0; CHECKSQL(ch); /* get phonestr before zeroing, in case user sends same structure in */ if ((phonestr = phone2str(phone)) == NULL) goto fail; bzero(cust, sizeof(*cust)); /* * CUSTOMER */ q = SQLARG(ch)->q.cdb.get_cust; /* 1 = first parameter in prepared query */ if (sqlite3_bind_text(q, 1, phonestr, strlen(phonestr), SQLITE_STATIC)) { sql_err(SQLARG(ch), "cannot bind phone number to query"); goto fail; } while (sqlite3_step(q) == SQLITE_ROW) { dupcount++; /* start by freeing, incase multiple customers match the same phone */ free_ChopstixCustomer(cust); /* ID, Phone, PhoneExt, Address, Intersection, Special */ cust_ID = sqlite3_column_int64(q, 0); cust->name = sql_strdup(sqlite3_column_text(q, 1)); str2phone(sqlite3_column_text(q, 2), &cust->phone); str2phoneext(sqlite3_column_text(q, 3), &cust->phone); cust->addr.addr = sql_strdup(sqlite3_column_text(q, 4)); cust->addr.apt = sql_strdup(sqlite3_column_text(q, 5)); cust->addr.entry = sql_strdup(sqlite3_column_text(q, 6)); cust->isect.cross = sql_strdup(sqlite3_column_text(q, 7)); if ((cust->special = calloc(1, sizeof(cust->special)))) *cust->special = sql_strdup(sqlite3_column_text(q, 8)); cust->reps = sqlite3_column_int(q, 9); } sqlite3_reset(q); if (dupcount > 1) sql_warn(SQLARG(ch), "%d duplicate entries", dupcount); if (cust_ID == 0) { errno = ENOENT; return -1; } /* * CREDITS */ q = SQLARG(ch)->q.cdb.get_cred; /* 1 = first parameter in prepared query */ if (sqlite3_bind_int(q, 1, cust_ID)) { sql_err(SQLARG(ch), "cannot bind customer ID to query"); goto fail; } if ((cust->credit = calloc(1, sizeof(*cust->credit))) == NULL) goto fail; cust->credit->len = 0; while (sqlite3_step(q) == SQLITE_ROW) { /* increase buffer */ if ((cc = realloc(cust->credit->val, (cust->credit->len + 1) * sizeof(ChopstixCredit))) == NULL) goto fail; cust->credit->len++; cust->credit->val = cc; /* Credit, Remain, Reason */ cust->credit->val[cust->credit->len - 1].credit = sqlite3_column_int(q, 0); cust->credit->val[cust->credit->len - 1].remain = sqlite3_column_int(q, 1); cust->credit->val[cust->credit->len - 1].reason = sql_strdup(sqlite3_column_text(q, 2)); } sqlite3_reset(SQLARG(ch)->q.cdb.get_cred); return 0; fail: free_ChopstixCustomer(cust); if (q) sqlite3_reset(q); return -1; }
apr_int64_t svn_sqlite__column_int64(svn_sqlite__stmt_t *stmt, int column) { return sqlite3_column_int64(stmt->s3stmt, column); }
static void registerLogFile(sqlite3 *db, const char *filename) { sqlite3_stmt *statement; int res; const unsigned char *name; int64 completed; int64 file_size; int64 file_modtime; if (filename) { struct stat st; res = stat(filename, &st); if (res != 0) error("Couldn't stat() %s", filename); file_size = st.st_size; file_modtime = st.st_mtime; statement = prepareStatement(db, "SELECT name, serial, completed FROM event_log" " WHERE size = ? AND modtime = ?"); res = sqlite3_bind_int64(statement, 1, file_size); if (res != SQLITE_OK) sqlite_error(res, db, "event_log bind of size failed."); res = sqlite3_bind_int64(statement, 2, file_modtime); if (res != SQLITE_OK) sqlite_error(res, db, "event_log bind of modtime failed."); res = sqlite3_step(statement); switch(res) { case SQLITE_DONE: evlog(LOG_SOMETIMES, "No log file matching '%s' found in database.", filename); break; case SQLITE_ROW: name = sqlite3_column_text(statement, 0); logSerial = sqlite3_column_int64(statement, 1); completed = sqlite3_column_int64(statement, 2); evlog(force ? LOG_OFTEN : LOG_ALWAYS, "Log file matching '%s' already in event_log, named \"%s\" (serial %lu, completed %lu).", filename, name, logSerial, completed); if (force) { evlog(LOG_OFTEN, "Continuing anyway because -f specified."); } else { evlog(LOG_ALWAYS, "Exiting. Specify -f to force events into SQL anyway."); exit(0); } break; default: sqlite_error(res, db, "select from event_log failed."); } finalizeStatement(db, statement); } else { /* stdin */ filename = "<stdin>"; file_size = 0; file_modtime = 0; } statement = prepareStatement(db, "INSERT into event_log (name, size, modtime, completed)" " VALUES (?, ?, ?, 0)"); res = sqlite3_bind_text(statement, 1, filename, -1, SQLITE_STATIC); if (res != SQLITE_OK) sqlite_error(res, db, "event_log insert bind of name failed."); res = sqlite3_bind_int64(statement, 2, file_size); if (res != SQLITE_OK) sqlite_error(res, db, "event_log insert bind of size failed."); res = sqlite3_bind_int64(statement, 3, file_modtime); if (res != SQLITE_OK) sqlite_error(res, db, "event_log insert bind of modtime failed."); res = sqlite3_step(statement); if (res != SQLITE_DONE) sqlite_error(res, db, "insert into event_log failed."); logSerial = sqlite3_last_insert_rowid(db); evlog(LOG_SOMETIMES, "Log file %s added to event_log with serial %lu", filename, logSerial); finalizeStatement(db, statement); }
int search(media_t* items, uint32_t* num_results, const char* terms) { char buffer[1024]; sqlite3_stmt* query; int retval; uint32_t count; if (terms == NULL) { strcpy(buffer, "SELECT COUNT(*) FROM main"); } else { if ((sizeof(buffer)-50) < sizeof(terms)) { log_debug(ERROR,"search(): terms exceeds buffer"); return MI_EXIT_ERROR; } strcpy(buffer, "SELECT COUNT(*) FROM main WHERE "); strcat(buffer, terms); } log_debug(INFO,"search(): starting query"); log_debug(INFO,buffer); if (sqlite3_prepare_v2(db_handle,buffer,-1,&query,NULL) != SQLITE_OK) { log_debug(ERROR,"search(): error executing query"); log_debug(ERROR,sqlite3_errmsg(db_handle)); return MI_EXIT_ERROR; } retval = sqlite3_step(query); if (retval == SQLITE_ROW) *num_results = (uint32_t)sqlite3_column_int(query,0); else if (retval == SQLITE_DONE) { log_debug(INFO,"search(): no results for query"); sqlite3_finalize(query); return MI_NO_RESULTS; } else { log_debug(ERROR,"search(): unknown error"); log_debug(ERROR,sqlite3_errmsg(db_handle)); sqlite3_finalize(query); return MI_EXIT_ERROR; } if (*num_results == 0) { log_debug(INFO,"search(): no results for query"); sqlite3_finalize(query); return MI_NO_RESULTS; } if (terms == NULL) { strcpy(buffer, "SELECT * FROM main"); } else { strcpy(buffer, "SELECT * FROM main WHERE "); strcat(buffer, terms); } log_debug(INFO,"search(): starting query"); log_debug(INFO,buffer); if (sqlite3_prepare_v2(db_handle,buffer,-1,&query,NULL) != SQLITE_OK) { log_debug(ERROR,"search(): error executing query"); log_debug(ERROR,sqlite3_errmsg(db_handle)); return MI_EXIT_ERROR; } items = malloc(sizeof(media_t)*(*num_results)); count = 0; log_debug(INFO,"search(): staring row processing"); while (1) { retval = sqlite3_step(query); if (retval == SQLITE_ROW) { items[count].code = (uint32_t)sqlite3_column_int(query,0); items[count].type = (medium_t)sqlite3_column_int(query,1); strcpy(items[count].name, (char *)sqlite3_column_text(query,2)); strcpy(items[count].location,(char *)sqlite3_column_text(query,3)); items[count].update = (time_t)sqlite3_column_int64(query,4); count++; sprintf(buffer,"search(): loaded row %u", count); log_debug(INFO,buffer); } else if (retval == SQLITE_DONE) { /* all done */ log_debug(INFO,"search(): row processing done"); sprintf(buffer,"%u rows processed out of %u rows actual",count,*num_results); log_debug(INFO,buffer); break; } else { /* error of some sort */ log_debug(ERROR,"search(): error during row processing"); log_debug(ERROR,sqlite3_errmsg(db_handle)); sprintf(buffer,"%u rows processed out of %u rows actual",count,*num_results); log_debug(INFO,buffer); *num_results = 0; free(items); items = NULL; sqlite3_finalize(query); return MI_EXIT_ERROR; } } sqlite3_finalize(query); *num_results = count; return MI_EXIT_OK; }
boost::shared_ptr<RoutingNode> SQLiteDatabaseConnection::getNodeByID(boost::uint64_t id) { boost::shared_ptr<RoutingNode> retVal; int rc; if(_getNodeByIDStatement == NULL) { rc = sqlite3_prepare_v2(_db, "SELECT ID, LAT, LON FROM NODES WHERE ID=?;", -1, &_getNodeByIDStatement, NULL); if (rc != SQLITE_OK) { std::cerr << "Failed to create getNodeByIDStatement." << " Resultcode: " << rc << std::endl; return boost::shared_ptr<RoutingNode>(); } } // Parameter an das Statement binden RoutingNode node; node.setID(id); if (node.isIDInLongFormat()) { sqlite3_bind_int64(_getNodeByIDStatement, 1, RoutingNode::convertIDToShortFormat(id)); } else { sqlite3_bind_int64(_getNodeByIDStatement, 1, id); } // Statement ausfuehren, in einer Schleife immer neue Zeilen holen while ((rc = sqlite3_step(_getNodeByIDStatement)) != SQLITE_DONE) { //Es können verschiedene Fehler aufgetreten sein. if (!sqlite_functions::handleSQLiteResultcode(rc)) break; //Erstelle einen neuen Knoten auf dem Heap. //Verwirrend: Hier ist der erste Parameter mit Index 0 und nicht 1 (!!). RoutingNode* newNode = new RoutingNode(sqlite3_column_int64(_getNodeByIDStatement, 0), sqlite3_column_double(_getNodeByIDStatement, 1), sqlite3_column_double(_getNodeByIDStatement, 2)); //Gib ihn an einen boost::shared_ptr weiter. newNode jetzt nicht mehr verwenden oder delete drauf anwenden! boost::shared_ptr<RoutingNode> ptr(newNode); //den boost::shared_ptr zur Liste hinzufügen retVal = ptr; } if (rc != SQLITE_DONE) { std::cerr << "Failed to execute getNodeByIDStatement." << " Resultcode: " << rc << std::endl; return boost::shared_ptr<RoutingNode>(); } rc = sqlite3_reset(_getNodeByIDStatement); if(rc != SQLITE_OK) { std::cerr << "Failed to reset getNodeByIDStatement." << " Resultcode: " << rc << std::endl; } return retVal; }