int main(int argc, char*argv[]){ ALGraph G; ALGraph* GPt = &G; initALGraph(GPt,1000); #if 0 initALGraph(GPt,6); insertArc(GPt,0,1,7); insertArc(GPt,0,2,9); insertArc(GPt,0,5,14); insertArc(GPt,1,2,10); insertArc(GPt,1,3,15); insertArc(GPt,2,5,2); insertArc(GPt,2,3,10); insertArc(GPt,5,4,9); insertArc(GPt,3,4,6); insertArc(GPt,4,3,6); #endif #if 1 sqlite3 *db; char *zErrMsg = 0; int rc, ret = 0, j,i, row_count = 0; printf("sqlite3 info:\n libversion:%s\n souceid:%s\n vesion_num:%d\n",sqlite3_libversion(), sqlite3_sourceid(), sqlite3_libversion_number()); sqlite3_stmt *pStmt = NULL; if( argc < 3 ){ fprintf(stderr, "Usage: %s DATABASE SQL-STATEMENT\n", argv[0]); return(1); } rc = sqlite3_open(argv[1], &db); if( rc ){ fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return(1); } rc = sqlite3_prepare(db, argv[2], strlen(argv[2]), &pStmt, NULL); printf("rc =%d\n", rc); if(rc != SQLITE_OK){ fprintf(stderr, "SQL error1: %s\n", zErrMsg); sqlite3_free(zErrMsg); return 1; } printf("pStmt=%p\n",pStmt); ret = sqlite3_column_count(pStmt); printf("BEFORE STEP col count= %d, rc = %d\n", ret, rc); printf("pStmt22=%p\n",pStmt); i = 0; //´òÓ¡colÃû³Æ while(i < ret){ printf("%20s \t %d \t %20s \t %d\n", sqlite3_column_name(pStmt, i), sqlite3_column_type(pStmt, i), sqlite3_column_decltype(pStmt, i), sqlite3_column_bytes(pStmt, i)); i++; } printf("pStmt23=%p\n",pStmt); printf("\n------ ------ ------ ------ ------------ ------ ------ ------\n"); printf("pStmt2=%p\n",pStmt); rc = sqlite3_step(pStmt); printf("pStmt3=%p\n",pStmt); STRACE if(rc != SQLITE_ROW){ fprintf(stderr, "SQL error2: %s,rc =%d\n", zErrMsg, rc); sqlite3_free(zErrMsg); return 1; } STRACE //¿ªÊ¼¶ÁȡÿһÐÐ while(rc == SQLITE_ROW){ //STRACE i = 0;row_count++; // for(j=0;j< ret;j++){ // printf("%s ", sqlite3_column_text(pStmt,j)); // } //printf("%d -> %d w:%d\n", sqlite3_column_int(pStmt,1), sqlite3_column_int(pStmt,2), sqlite3_column_int(pStmt,4)); insertArc(GPt,sqlite3_column_int(pStmt,1), sqlite3_column_int(pStmt,2), sqlite3_column_int(pStmt,4)); #if 0 printf("%d, %s, %s, %s\n", sqlite3_column_int(pStmt, 0), sqlite3_column_text(pStmt, 1), sqlite3_column_text(pStmt, 2), sqlite3_column_text(pStmt, 3)); #endif rc = sqlite3_step(pStmt); } STRACE printf("row_count=%d\n ", row_count); sqlite3_finalize(pStmt); sqlite3_close(db); #endif G.vexnum = row_count; printf("显示出此构造的图:\n"); //displayGraph(G); printf("\n"); int d[MAX_VERTEX_NUM]; int pi[MAX_VERTEX_NUM]; int Q[MAX_VERTEX_NUM+1]; //Q[]的第一个元素只保存堆的大小,不保存元素。所以定义长度时+1 dijkstra(G,1,d,pi,Q); STRACE i= atoi(argv[3]); printf("从源点1到点%d的最短路径信息:\n",i); printf("长度为%d\n",d[i]); printf("路径为: %d ", i); for(j=i;j>1;){ printf("%d ",pi[j]); j=pi[j]; } printf("\n"); // for(i=1;i<G.vexnum;i++){ // printf("从源点1到点%d的最短路径信息:\n",i); // printf("长度为%d\n",d[i]); // printf("路径为: %d ", i); // for(j=i;j>0;){ // printf("%d ",pi[j]); // j=pi[j]; // } //} return 0; }
int main(int argc, char **argv) { char *file = NULL; if (argc != 2) { fprintf(stderr, "error: require exactly one argument, the DB filename\n"); exit(EXIT_FAILURE); } else { file = argv[1]; } /* On Windows stderr is not always unbuffered. */ #if defined(_WIN32) || defined(WIN32) || defined(__MINGW32__) setvbuf(stderr, NULL, _IONBF, 0); #endif sqlite3* db = NULL; if (sqlite3_initialize() != SQLITE_OK) { fprintf(stderr, "error: failed to initialize sqlite\n"); exit(EXIT_FAILURE); } int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; if (sqlite3_open_v2(file, &db, flags, NULL) != SQLITE_OK) { fprintf(stderr, "error: failed to open %s\n", file); exit(EXIT_FAILURE); } buffer *input = buffer_create(); while (TRUE) { printf("#\n"); fflush(stdout); /* Gather input from Emacs. */ unsigned length; int result = scanf("%u ", &length); if (result == EOF) { break; } else if (result != 1) { send_error(SQLITE_ERROR, "middleware parsing error"); break; /* stream out of sync: quit program */ } if (!buffer_read(input, length)) { send_error(SQLITE_NOMEM, "middleware out of memory"); continue; } /* Parse SQL statement. */ sqlite3_stmt *stmt = NULL; result = sqlite3_prepare_v2(db, input->buffer, length, &stmt, NULL); if (result != SQLITE_OK) { send_error(sqlite3_errcode(db), sqlite3_errmsg(db)); continue; } /* Print out rows. */ int first = TRUE, ncolumns = sqlite3_column_count(stmt); printf("("); while (sqlite3_step(stmt) == SQLITE_ROW) { if (first) { printf("("); first = FALSE; } else { printf("\n ("); } int i; for (i = 0; i < ncolumns; i++) { if (i > 0) { printf(" "); } int type = sqlite3_column_type(stmt, i); switch (type) { case SQLITE_INTEGER: printf("%lld", sqlite3_column_int64(stmt, i)); break; case SQLITE_FLOAT: printf("%f", sqlite3_column_double(stmt, i)); break; case SQLITE_NULL: printf("nil"); break; case SQLITE_TEXT: fwrite(sqlite3_column_text(stmt, i), 1, sqlite3_column_bytes(stmt, i), stdout); break; case SQLITE_BLOB: printf("nil"); break; } } printf(")"); } printf(")\n"); if (sqlite3_finalize(stmt) != SQLITE_OK) { /* Despite any error code, the statement is still freed. * http://stackoverflow.com/a/8391872 */ send_error(sqlite3_errcode(db), sqlite3_errmsg(db)); } else { printf("success\n"); } } buffer_free(input); sqlite3_close(db); sqlite3_shutdown(); return EXIT_SUCCESS; }
array_header *proxy_db_exec_prepared_stmt(pool *p, const char *stmt, const char **errstr) { sqlite3_stmt *pstmt; int readonly = FALSE, res; array_header *results = NULL; if (p == NULL || stmt == NULL) { errno = EINVAL; return NULL; } if (prepared_stmts == NULL) { errno = ENOENT; return NULL; } pstmt = pr_table_get(prepared_stmts, stmt, NULL); if (pstmt == NULL) { pr_trace_msg(trace_channel, 19, "unable to find prepared statement for '%s'", stmt); errno = ENOENT; return NULL; } readonly = sqlite3_stmt_readonly(pstmt); if (!readonly) { /* Assume this is an INSERT/UPDATE/DELETE. */ res = sqlite3_step(pstmt); if (res != SQLITE_DONE) { const char *errmsg; errmsg = sqlite3_errmsg(proxy_dbh); if (errstr) { *errstr = pstrdup(p, errmsg); } pr_trace_msg(trace_channel, 2, "error executing '%s': %s", stmt, errmsg); errno = EPERM; return NULL; } /* Indicate success for non-readonly statements by returning an empty * result set. */ pr_trace_msg(trace_channel, 13, "successfully executed '%s'", stmt); results = make_array(p, 0, sizeof(char *)); return results; } results = make_array(p, 0, sizeof(char *)); res = sqlite3_step(pstmt); while (res == SQLITE_ROW) { register unsigned int i; int ncols; ncols = sqlite3_column_count(pstmt); pr_trace_msg(trace_channel, 12, "executing prepared statement '%s' returned row (columns: %d)", stmt, ncols); for (i = 0; i < ncols; i++) { char *val = NULL; pr_signals_handle(); /* By using sqlite3_column_text, SQLite will coerce the column value * into a string. */ val = pstrdup(p, (const char *) sqlite3_column_text(pstmt, i)); pr_trace_msg(trace_channel, 17, "column %s [%u]: %s", sqlite3_column_name(pstmt, i), i, val); *((char **) push_array(results)) = val; } res = sqlite3_step(pstmt); } if (res != SQLITE_DONE) { const char *errmsg; errmsg = sqlite3_errmsg(proxy_dbh); if (errstr != NULL) { *errstr = pstrdup(p, errmsg); } (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION, "executing prepared statement '%s' did not complete successfully: %s", stmt, errmsg); errno = EPERM; return NULL; } pr_trace_msg(trace_channel, 13, "successfully executed '%s'", stmt); return results; }
range* rangefunc_group(range_request* rr, range** r) { range* ret; const char** members; int i, err; sqlite3* db; sqlite3_stmt* tag_stmt; sqlite3_stmt* all_nodes_stmt; apr_pool_t* pool = range_request_pool(rr); libcrange* lr = range_request_lr(rr); ret = range_new(rr); members = range_get_hostnames(pool, r[0]); if (!(db = libcrange_get_cache(lr, "sqlite:nodes"))) { const char* sqlite_db_path = libcrange_getcfg(lr, "sqlitedb"); if (!sqlite_db_path) sqlite_db_path = DEFAULT_SQLITE_DB; err = sqlite3_open(sqlite_db_path, &db); if (err != SQLITE_OK) { fprintf(stderr, "%s: %s\n", sqlite_db_path, sqlite3_errmsg(db)); return ret; } libcrange_set_cache(lr, "sqlite:nodes", db); } /* prepare our selects */ err = sqlite3_prepare(db, ALL_NODES_SQL, strlen(ALL_NODES_SQL), &all_nodes_stmt, NULL); if (err != SQLITE_OK) { fprintf(stderr, "%s: %s\n", ALL_NODES_SQL, sqlite3_errmsg(db)); abort(); } err = sqlite3_prepare(db, RANGE_FROM_TAGS, strlen(RANGE_FROM_TAGS), &tag_stmt, NULL); assert(err == SQLITE_OK); /* for each group */ for (i = 0; members[i]; ++i) { sqlite3_stmt* stmt; if (strcmp(members[i], "ALL") == 0) { stmt = all_nodes_stmt; } else { stmt = tag_stmt; /* bind the current group name */ sqlite3_bind_text(tag_stmt, 1, members[i], strlen(members[i]), SQLITE_STATIC); } while (sqlite3_step(stmt) == SQLITE_ROW) { range* this_group; const char* result = (const char*)sqlite3_column_text(stmt, 0); if (stmt == all_nodes_stmt) { range_add(ret, result); } else { this_group = do_range_expand(rr, result); set_union_inplace(ret->nodes, this_group->nodes); } } sqlite3_reset(stmt); } sqlite3_finalize(all_nodes_stmt); sqlite3_finalize(tag_stmt); return ret; }
int main() { printf("\n********************************\n"); printf("box_conf_change : start\n"); printf("********************************\n"); char url[1024] = {0}; ghttp_request *req; char http_body[1024] = {0}; sqlite3 *db = NULL; sqlite3_stmt *ppstmt = NULL; int rc = 0; char sql_cmd[100] = {0}; char *errorMsg = NULL; const char *box_id = NULL; char box_id_tmp[10] = {0}; int db_cnt = 0; while(db_cnt < 20) { rc = sqlite3_open(box_db, &db); if(rc == SQLITE_ERROR) printf("open box.db failed"); ppstmt = NULL; memset(sql_cmd, 0, sizeof(sql_cmd)); strcpy(sql_cmd, "select box_id from box_info"); sqlite3_prepare(db, sql_cmd, -1, &ppstmt, 0); rc = sqlite3_step(ppstmt); if(rc == SQLITE_ROW) { box_id = sqlite3_column_text(ppstmt, 0); strcpy(box_id_tmp, box_id); printf("box_id : %s\n", box_id_tmp); sqlite3_finalize(ppstmt); sqlite3_close(db); break; } else { printf("select box_id failure!\n"); sqlite3_finalize(ppstmt); sqlite3_close(db); sleep(1); db_cnt++; } } printf("----------------send http request-------------\n"); sprintf(url, "http://www.ailvgobox.com/box_manage_2/box_conf_change_1.php?box_id=%s", box_id_tmp); printf("request_url : %s\n",url); req = ghttp_request_new(); strcpy(http_body, send_http_request(req, url)); ghttp_request_destroy(req); printf("http_body : %s\n", http_body); printf("length of http_body : %d\n", strlen(http_body)); cJSON *node; if(strlen(http_body) <= 2) printf("HTTP failure!\n"); else { printf("HTTP success!\n"); if(strcmp(http_body, "null") == 0) printf("http_body : null, no box_conf_change!\n"); else { node = cJSON_Parse(http_body); ParseJSON(node); } } printf("box_conf_chanage : complete!\n"); if(change_flag == 1) { printf("reboot due to conf change!\n"); sleep(5); system("reboot"); } }
void vca_illegal_parking::process_event() { try { while ( true ) { // Check if there are yet-to-be-fillout_event events in the database. auto sql = global::get_database_handle(); sqlite3_stmt* stmt; ostringstream query; query << "SELECT * FROM events WHERE snapshots_fetched=0" << " and producer='" << name_ << "'"; auto query_cstr = query.str().c_str(); sqlite3_prepare_v2(sql, query_cstr, strlen ( query_cstr ) + 1, &stmt, NULL ); string evt_ts; string evt_id; int retval = sqlite3_step(stmt); if (retval == SQLITE_ROW) { evt_id = string ( reinterpret_cast< const char *> ( sqlite3_column_text ( stmt, 0 ) ) ); evt_ts = string ( reinterpret_cast< const char *> ( sqlite3_column_text ( stmt, 1 ) ) ); sqlite3_finalize(stmt); } else { boost::this_thread::sleep ( seconds ( 5 ) ); continue; } auto evt_time = common::parse_utc_string ( evt_ts ); boost::this_thread::sleep ( seconds ( 10 ) ); LOG ( INFO ) << "filling out event id: " << evt_id << " at: " << evt_ts; // Create directory for event. path evt_dir = operator/ ( working_dir_, common::get_simple_utc_string ( evt_time ) ); create_directories ( evt_dir ); auto pre_event_period = parameters_.get ( "pre_event_period", 300 ); auto post_event_period = parameters_.get ( "post_event_period", 300 ); auto start_time = evt_time - seconds ( pre_event_period ); auto end_time = evt_time + seconds ( post_event_period ); ptime now ( microsec_clock::universal_time() ); auto dt = now - end_time; if ( dt <= seconds ( 0 ) ) { boost::this_thread::sleep ( seconds ( -dt.seconds() ) ); } // Copy snapshots to event directory. auto images = loiter_->list_snapshots_between ( start_time, end_time ); BOOST_FOREACH ( auto const& image, images ) { path to = operator/ ( evt_dir, image.filename() ); copy_file ( image, to, copy_option::overwrite_if_exists ); } } } catch ( std::exception const& e ) { LOG ( INFO ) << e.what(); } }
static void pk_backend_install_packages_thread(PkBackendJob *job, GVariant *params, gpointer user_data) { gchar *dest_dir_name, **pkg_tokens, **pkg_ids; guint i; gdouble percent_step; GSList *repo, *install_list = NULL, *l; sqlite3_stmt *pkglist_stmt = NULL, *collection_stmt = NULL; PkBitfield transaction_flags = 0; PkInfoEnum ret; PkBackendKatjaJobData *job_data = pk_backend_job_get_user_data(job); g_variant_get(params, "(t^a&s)", &transaction_flags, &pkg_ids); pk_backend_job_set_status(job, PK_STATUS_ENUM_DEP_RESOLVE); if ((sqlite3_prepare_v2(job_data->db, "SELECT summary, cat FROM pkglist NATURAL JOIN repos " "WHERE name LIKE @name AND ver LIKE @ver AND arch LIKE @arch AND repo LIKE @repo", -1, &pkglist_stmt, NULL) != SQLITE_OK) || (sqlite3_prepare_v2(job_data->db, "SELECT (c.collection_pkg || ';' || p.ver || ';' || p.arch || ';' || r.repo), p.summary, " "p.full_name, p.ext FROM collections AS c " "JOIN pkglist AS p ON c.collection_pkg = p.name " "JOIN repos AS r ON p.repo_order = r.repo_order " "WHERE c.name LIKE @name AND r.repo LIKE @repo", -1, &collection_stmt, NULL) != SQLITE_OK)) { pk_backend_job_error_code(job, PK_ERROR_ENUM_CANNOT_GET_FILELIST, "%s", sqlite3_errmsg(job_data->db)); goto out; } for (i = 0; pkg_ids[i]; i++) { pkg_tokens = pk_package_id_split(pkg_ids[i]); sqlite3_bind_text(pkglist_stmt, 1, pkg_tokens[PK_PACKAGE_ID_NAME], -1, SQLITE_TRANSIENT); sqlite3_bind_text(pkglist_stmt, 2, pkg_tokens[PK_PACKAGE_ID_VERSION], -1, SQLITE_TRANSIENT); sqlite3_bind_text(pkglist_stmt, 3, pkg_tokens[PK_PACKAGE_ID_ARCH], -1, SQLITE_TRANSIENT); sqlite3_bind_text(pkglist_stmt, 4, pkg_tokens[PK_PACKAGE_ID_DATA], -1, SQLITE_TRANSIENT); if (sqlite3_step(pkglist_stmt) == SQLITE_ROW) { /* If it isn't a collection */ if (g_strcmp0((gchar *) sqlite3_column_text(pkglist_stmt, 1), "collections")) { if (pk_bitfield_contain(transaction_flags, PK_TRANSACTION_FLAG_ENUM_SIMULATE)) { pk_backend_job_package(job, PK_INFO_ENUM_INSTALLING, pkg_ids[i], (gchar *) sqlite3_column_text(pkglist_stmt, 0)); } else { install_list = g_slist_append(install_list, g_strdup(pkg_ids[i])); } } else { sqlite3_bind_text(collection_stmt, 1, pkg_tokens[PK_PACKAGE_ID_NAME], -1, SQLITE_TRANSIENT); sqlite3_bind_text(collection_stmt, 2, pkg_tokens[PK_PACKAGE_ID_DATA], -1, SQLITE_TRANSIENT); while (sqlite3_step(collection_stmt) == SQLITE_ROW) { ret = katja_pkg_is_installed((gchar *) sqlite3_column_text(collection_stmt, 2)); if ((ret == PK_INFO_ENUM_INSTALLING) || (ret == PK_INFO_ENUM_UPDATING)) { if ((pk_bitfield_contain(transaction_flags, PK_TRANSACTION_FLAG_ENUM_SIMULATE)) && !g_strcmp0((gchar *) sqlite3_column_text(collection_stmt, 3), "obsolete")) { /* TODO: Don't just skip obsolete packages but remove them */ } else if (pk_bitfield_contain(transaction_flags, PK_TRANSACTION_FLAG_ENUM_SIMULATE)) { pk_backend_job_package(job, ret, (gchar *) sqlite3_column_text(collection_stmt, 0), (gchar *) sqlite3_column_text(collection_stmt, 1)); } else { install_list = g_slist_append(install_list, g_strdup((gchar *) sqlite3_column_text(collection_stmt, 0))); } } } sqlite3_clear_bindings(collection_stmt); sqlite3_reset(collection_stmt); } } sqlite3_clear_bindings(pkglist_stmt); sqlite3_reset(pkglist_stmt); g_strfreev(pkg_tokens); } if (install_list && !pk_bitfield_contain(transaction_flags, PK_TRANSACTION_FLAG_ENUM_SIMULATE)) { /* / 2 means total percentage for installing and for downloading */ percent_step = 100.0 / g_slist_length(install_list) / 2; /* Download the packages */ pk_backend_job_set_status(job, PK_STATUS_ENUM_DOWNLOAD); dest_dir_name = g_build_filename(LOCALSTATEDIR, "cache", "PackageKit", "downloads", NULL); for (l = install_list, i = 0; l; l = g_slist_next(l), i++) { pk_backend_job_set_percentage(job, percent_step * i); pkg_tokens = pk_package_id_split(l->data); repo = g_slist_find_custom(repos, pkg_tokens[PK_PACKAGE_ID_DATA], katja_cmp_repo); if (repo) katja_pkgtools_download(KATJA_PKGTOOLS(repo->data), job, dest_dir_name, pkg_tokens[PK_PACKAGE_ID_NAME]); g_strfreev(pkg_tokens); } g_free(dest_dir_name); /* Install the packages */ pk_backend_job_set_status(job, PK_STATUS_ENUM_INSTALL); for (l = install_list; l; l = g_slist_next(l), i++) { pk_backend_job_set_percentage(job, percent_step * i); pkg_tokens = pk_package_id_split(l->data); repo = g_slist_find_custom(repos, pkg_tokens[PK_PACKAGE_ID_DATA], katja_cmp_repo); if (repo) katja_pkgtools_install(KATJA_PKGTOOLS(repo->data), job, pkg_tokens[PK_PACKAGE_ID_NAME]); g_strfreev(pkg_tokens); } } g_slist_free_full(install_list, g_free); out: sqlite3_finalize(pkglist_stmt); sqlite3_finalize(collection_stmt); pk_backend_job_finished (job); }
bool QgsStyleV2::load( QString filename ) { mErrorString.clear(); // Open the sqlite database if ( !openDB( filename ) ) { mErrorString = "Unable to open database file specified"; QgsDebugMsg( mErrorString ); return false; } // Make sure there are no Null fields in parenting symbols ang groups char *query = sqlite3_mprintf( "UPDATE symbol SET groupid=0 WHERE groupid IS NULL;" "UPDATE colorramp SET groupid=0 WHERE groupid IS NULL;" "UPDATE symgroup SET parent=0 WHERE parent IS NULL;"); runEmptyQuery( query ); // First create all the main symbols query = sqlite3_mprintf( "SELECT * FROM symbol" ); sqlite3_stmt *ppStmt; int nError = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, NULL ); while ( nError == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW ) { QDomDocument doc; QString symbol_name = QString::fromUtf8(( const char * ) sqlite3_column_text( ppStmt, SymbolName ) ); QString xmlstring = QString::fromUtf8(( const char * ) sqlite3_column_text( ppStmt, SymbolXML ) ); if ( !doc.setContent( xmlstring ) ) { QgsDebugMsg( "Cannot open symbol " + symbol_name ); continue; } QDomElement symElement = doc.documentElement(); QgsSymbolV2 *symbol = QgsSymbolLayerV2Utils::loadSymbol( symElement ); if ( symbol != NULL ) mSymbols.insert( symbol_name, symbol ); } sqlite3_finalize( ppStmt ); query = sqlite3_mprintf( "SELECT * FROM colorramp" ); nError = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, NULL ); while ( nError == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW ) { QDomDocument doc; QString ramp_name = QString::fromUtf8(( const char * ) sqlite3_column_text( ppStmt, ColorrampName ) ); QString xmlstring = QString::fromUtf8(( const char * ) sqlite3_column_text( ppStmt, ColorrampXML ) ); if ( !doc.setContent( xmlstring ) ) { QgsDebugMsg( "Cannot open symbol " + ramp_name ); continue; } QDomElement rampElement = doc.documentElement(); QgsVectorColorRampV2 *ramp = QgsSymbolLayerV2Utils::loadColorRamp( rampElement ); if ( ramp ) mColorRamps.insert( ramp_name, ramp ); } mFileName = filename; return true; }
QStringList QgsStyleV2::findSymbols( QString qword ) { if ( !mCurrentDB ) { QgsDebugMsg( "Sorry! Cannot open database to search" ); return QStringList(); } char *query = sqlite3_mprintf( "SELECT name FROM symbol WHERE xml LIKE '%%%q%%'", qword.toUtf8().constData() ); sqlite3_stmt *ppStmt; int nErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, NULL ); QStringList symbols; while ( nErr == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW ) { symbols << QString::fromUtf8(( const char * ) sqlite3_column_text( ppStmt, 0 ) ); } sqlite3_finalize( ppStmt ); query = sqlite3_mprintf( "SELECT id FROM tag WHERE name LIKE '%%%q%%'", qword.toUtf8().constData() ); nErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, NULL ); QStringList tagids; while ( nErr == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW ) { tagids << QString::fromUtf8(( const char * ) sqlite3_column_text( ppStmt, 0 ) ); } sqlite3_finalize( ppStmt ); QString dummy = tagids.join( ", " ); query = sqlite3_mprintf( "SELECT symbol_id FROM tagmap WHERE tag_id IN (%q)", dummy.toUtf8().constData() ); nErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, NULL ); QStringList symbolids; while ( nErr == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW ) { symbolids << QString::fromUtf8(( const char * ) sqlite3_column_text( ppStmt, 0 ) ); } sqlite3_finalize( ppStmt ); dummy = symbolids.join( ", " ); query = sqlite3_mprintf( "SELECT name FROM symbol WHERE id IN (%q)", dummy.toUtf8().constData() ); nErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, NULL ); while ( nErr == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW ) { QString symbolName = QString::fromUtf8(( const char * ) sqlite3_column_text( ppStmt, 0 ) ); if ( !symbols.contains( symbolName ) ) symbols << symbolName; } sqlite3_finalize( ppStmt ); return symbols; }
static int table_sqlite_lookup(int service, const char *key, char *dst, size_t sz) { sqlite3_stmt *stmt; const char *value; int r, s; stmt = table_sqlite_query(key, service); if (stmt == NULL) return (-1); s = sqlite3_step(stmt); if (s == SQLITE_DONE) { sqlite3_reset(stmt); return (0); } if (s != SQLITE_ROW) { log_warnx("warn: table-sqlite: sqlite3_step: %s", sqlite3_errmsg(db)); sqlite3_reset(stmt); return (-1); } r = 1; switch(service) { case K_ALIAS: do { value = sqlite3_column_text(stmt, 0); if (dst[0] && strlcat(dst, ", ", sz) >= sz) { log_warnx("warn: table-sqlite: result too large"); r = -1; break; } if (strlcat(dst, value, sz) >= sz) { log_warnx("warn: table-sqlite: result too large"); r = -1; break; } s = sqlite3_step(stmt); } while (s == SQLITE_ROW); if (s != SQLITE_ROW && s != SQLITE_DONE) { log_warnx("warn: table-sqlite: sqlite3_step: %s", sqlite3_errmsg(db)); r = -1; } break; case K_CREDENTIALS: if (snprintf(dst, sz, "%s:%s", sqlite3_column_text(stmt, 0), sqlite3_column_text(stmt, 1)) > (ssize_t)sz) { log_warnx("warn: table-sqlite: result too large"); r = -1; } break; case K_USERINFO: if (snprintf(dst, sz, "%s:%i:%i:%s", sqlite3_column_text(stmt, 0), sqlite3_column_int(stmt, 1), sqlite3_column_int(stmt, 2), sqlite3_column_text(stmt, 3)) > (ssize_t)sz) { log_warnx("warn: table-sqlite: result too large"); r = -1; } break; case K_DOMAIN: case K_NETADDR: case K_SOURCE: case K_MAILADDR: case K_ADDRNAME: if (strlcpy(dst, sqlite3_column_text(stmt, 0), sz) >= sz) { log_warnx("warn: table-sqlite: result too large"); r = -1; } break; default: log_warnx("warn: table-sqlite: unknown service %i", service); r = -1; } return (r); }
/* ** Report on the vocabulary. This creates an fts4aux table with a random ** name, but deletes it in the end. */ static void showVocabulary(sqlite3 *db, const char *zTab) { char *zAux; sqlite3_uint64 r; sqlite3_stmt *pStmt; int nDoc = 0; int nToken = 0; int nOccurrence = 0; int nTop; int n, i; sqlite3_randomness(sizeof(r), &r); zAux = sqlite3_mprintf("viewer_%llx", zTab, r); runSql(db, "BEGIN"); pStmt = prepare(db, "SELECT count(*) FROM %Q", zTab); while( sqlite3_step(pStmt)==SQLITE_ROW ) { nDoc = sqlite3_column_int(pStmt, 0); } sqlite3_finalize(pStmt); printf("Number of documents...................... %9d\n", nDoc); runSql(db, "CREATE VIRTUAL TABLE %s USING fts4aux(%Q)", zAux, zTab); pStmt = prepare(db, "SELECT count(*), sum(occurrences) FROM %s WHERE col='*'", zAux); while( sqlite3_step(pStmt)==SQLITE_ROW ) { nToken = sqlite3_column_int(pStmt, 0); nOccurrence = sqlite3_column_int(pStmt, 1); } sqlite3_finalize(pStmt); printf("Total tokens in all documents............ %9d\n", nOccurrence); printf("Total number of distinct tokens.......... %9d\n", nToken); if( nToken==0 ) goto end_vocab; n = 0; pStmt = prepare(db, "SELECT count(*) FROM %s" " WHERE col='*' AND occurrences==1", zAux); while( sqlite3_step(pStmt)==SQLITE_ROW ) { n = sqlite3_column_int(pStmt, 0); } sqlite3_finalize(pStmt); printf("Tokens used exactly once................. %9d %5.2f%%\n", n, n*100.0/nToken); n = 0; pStmt = prepare(db, "SELECT count(*) FROM %s" " WHERE col='*' AND documents==1", zAux); while( sqlite3_step(pStmt)==SQLITE_ROW ) { n = sqlite3_column_int(pStmt, 0); } sqlite3_finalize(pStmt); printf("Tokens used in only one document......... %9d %5.2f%%\n", n, n*100.0/nToken); if( nDoc>=2000 ) { n = 0; pStmt = prepare(db, "SELECT count(*) FROM %s" " WHERE col='*' AND occurrences<=%d", zAux, nDoc/1000); while( sqlite3_step(pStmt)==SQLITE_ROW ) { n = sqlite3_column_int(pStmt, 0); } sqlite3_finalize(pStmt); printf("Tokens used in 0.1%% or less of docs...... %9d %5.2f%%\n", n, n*100.0/nToken); } if( nDoc>=200 ) { n = 0; pStmt = prepare(db, "SELECT count(*) FROM %s" " WHERE col='*' AND occurrences<=%d", zAux, nDoc/100); while( sqlite3_step(pStmt)==SQLITE_ROW ) { n = sqlite3_column_int(pStmt, 0); } sqlite3_finalize(pStmt); printf("Tokens used in 1%% or less of docs........ %9d %5.2f%%\n", n, n*100.0/nToken); } nTop = atoi(findOption("top", 1, "25")); printf("The %d most common tokens:\n", nTop); pStmt = prepare(db, "SELECT term, documents FROM %s" " WHERE col='*'" " ORDER BY documents DESC, term" " LIMIT %d", zAux, nTop); i = 0; while( sqlite3_step(pStmt)==SQLITE_ROW ) { i++; n = sqlite3_column_int(pStmt, 1); printf(" %2d. %-30s %9d docs %5.2f%%\n", i, sqlite3_column_text(pStmt, 0), n, n*100.0/nDoc); } sqlite3_finalize(pStmt); end_vocab: runSql(db, "ROLLBACK"); sqlite3_free(zAux); }
static void dc_job_perform(dc_context_t* context, int thread, int probe_network) { sqlite3_stmt* select_stmt = NULL; dc_job_t job; #define THREAD_STR (thread==DC_IMAP_THREAD? "INBOX" : "SMTP") #define IS_EXCLUSIVE_JOB (DC_JOB_CONFIGURE_IMAP==job.action || DC_JOB_IMEX_IMAP==job.action) memset(&job, 0, sizeof(dc_job_t)); job.param = dc_param_new(); if (context==NULL || context->magic!=DC_CONTEXT_MAGIC) { goto cleanup; } if (probe_network==0) { // processing for first-try and after backoff-timeouts: // process jobs in the order they were added. #define FIELDS "id, action, foreign_id, param, added_timestamp, desired_timestamp, tries" select_stmt = dc_sqlite3_prepare(context->sql, "SELECT " FIELDS " FROM jobs" " WHERE thread=? AND desired_timestamp<=?" " ORDER BY action DESC, added_timestamp;"); sqlite3_bind_int64(select_stmt, 1, thread); sqlite3_bind_int64(select_stmt, 2, time(NULL)); } else { // processing after call to dc_maybe_network(): // process _all_ pending jobs that failed before // in the order of their backoff-times. select_stmt = dc_sqlite3_prepare(context->sql, "SELECT " FIELDS " FROM jobs" " WHERE thread=? AND tries>0" " ORDER BY desired_timestamp, action DESC;"); sqlite3_bind_int64(select_stmt, 1, thread); } while (sqlite3_step(select_stmt)==SQLITE_ROW) { job.job_id = sqlite3_column_int (select_stmt, 0); job.action = sqlite3_column_int (select_stmt, 1); job.foreign_id = sqlite3_column_int (select_stmt, 2); dc_param_set_packed(job.param, (char*)sqlite3_column_text (select_stmt, 3)); job.added_timestamp = sqlite3_column_int64(select_stmt, 4); job.desired_timestamp = sqlite3_column_int64(select_stmt, 5); job.tries = sqlite3_column_int (select_stmt, 6); dc_log_info(context, 0, "%s-job #%i, action %i started...", THREAD_STR, (int)job.job_id, (int)job.action); // some configuration jobs are "exclusive": // - they are always executed in the imap-thread and the smtp-thread is suspended during execution // - they may change the database handle change the database handle; we do not keep old pointers therefore // - they can be re-executed one time AT_ONCE, but they are not save in the database for later execution if (IS_EXCLUSIVE_JOB) { dc_job_kill_action(context, job.action); sqlite3_finalize(select_stmt); select_stmt = NULL; dc_jobthread_suspend(&context->sentbox_thread, 1); dc_jobthread_suspend(&context->mvbox_thread, 1); dc_suspend_smtp_thread(context, 1); } for (int tries = 0; tries <= 1; tries++) { job.try_again = DC_DONT_TRY_AGAIN; // this can be modified by a job using dc_job_try_again_later() switch (job.action) { case DC_JOB_SEND_MSG_TO_SMTP: dc_job_do_DC_JOB_SEND (context, &job); break; case DC_JOB_DELETE_MSG_ON_IMAP: dc_job_do_DC_JOB_DELETE_MSG_ON_IMAP (context, &job); break; case DC_JOB_MARKSEEN_MSG_ON_IMAP: dc_job_do_DC_JOB_MARKSEEN_MSG_ON_IMAP (context, &job); break; case DC_JOB_MARKSEEN_MDN_ON_IMAP: dc_job_do_DC_JOB_MARKSEEN_MDN_ON_IMAP (context, &job); break; case DC_JOB_MOVE_MSG: dc_job_do_DC_JOB_MOVE_MSG (context, &job); break; case DC_JOB_SEND_MDN: dc_job_do_DC_JOB_SEND (context, &job); break; case DC_JOB_CONFIGURE_IMAP: dc_job_do_DC_JOB_CONFIGURE_IMAP (context, &job); break; case DC_JOB_IMEX_IMAP: dc_job_do_DC_JOB_IMEX_IMAP (context, &job); break; case DC_JOB_MAYBE_SEND_LOCATIONS: dc_job_do_DC_JOB_MAYBE_SEND_LOCATIONS (context, &job); break; case DC_JOB_MAYBE_SEND_LOC_ENDED: dc_job_do_DC_JOB_MAYBE_SEND_LOC_ENDED (context, &job); break; case DC_JOB_HOUSEKEEPING: dc_housekeeping (context); break; } if (job.try_again!=DC_AT_ONCE) { break; } } if (IS_EXCLUSIVE_JOB) { dc_jobthread_suspend(&context->sentbox_thread, 0); dc_jobthread_suspend(&context->mvbox_thread, 0); dc_suspend_smtp_thread(context, 0); goto cleanup; } else if (job.try_again==DC_INCREATION_POLL) { // just try over next loop unconditionally, the ui typically interrupts idle when the file (video) is ready dc_log_info(context, 0, "%s-job #%i not yet ready and will be delayed.", THREAD_STR, (int)job.job_id); } else if (job.try_again==DC_AT_ONCE || job.try_again==DC_STANDARD_DELAY) { int tries = job.tries + 1; if( tries < JOB_RETRIES ) { job.tries = tries; time_t time_offset = get_backoff_time_offset(tries); job.desired_timestamp = job.added_timestamp + time_offset; dc_job_update(context, &job); dc_log_info(context, 0, "%s-job #%i not succeeded on try #%i, retry in ADD_TIME+%i (in %i seconds).", THREAD_STR, (int)job.job_id, tries, time_offset, (job.added_timestamp+time_offset)-time(NULL)); if (thread==DC_SMTP_THREAD && tries<(JOB_RETRIES-1)) { pthread_mutex_lock(&context->smtpidle_condmutex); context->perform_smtp_jobs_needed = DC_JOBS_NEEDED_AVOID_DOS; pthread_mutex_unlock(&context->smtpidle_condmutex); } } else { if (job.action==DC_JOB_SEND_MSG_TO_SMTP) { // in all other cases, the messages is already sent dc_set_msg_failed(context, job.foreign_id, job.pending_error); } dc_job_delete(context, &job); } if (probe_network) { // on dc_maybe_network() we stop trying here; // these jobs are already tried once. // otherwise, we just continue with the next job // to give other jobs a chance being tried at least once. goto cleanup; } } else { dc_job_delete(context, &job); } } cleanup: dc_param_unref(job.param); free(job.pending_error); sqlite3_finalize(select_stmt); }
////////////////////////////////////////////////////////////////////////////////////////////////////// // Function:获取一行数据内容 // Input: ioValue, 保存一行数据 // ioNull, 保存空值的标志 0 为空, 1 非空 // Output: // Return: SQLITE_BUSY: 数据库被锁 // SQLITE_ROW: 数据未取完, 需要继续读取数据 // SQLITE_DONE: 数据已经读取完成 // other: 读取数据库记录失败 int CSQLite::Fetch( vector<string> & ioValues, vector<int>& ioNull ) { //清空数组 ioValues.clear(); ioNull.clear(); bool bRelease = true; //是否释放游标 for( unsigned int m = 0; m < m_nLimitNum; m++ ) { m_nState = sqlite3_step( m_pStmt ); if ( SQLITE_DONE == m_nState ) { // no rows m_strErrInfo = sqlite3_errmsg( m_pDb ); goto __Exit; } else if ( SQLITE_ROW == m_nState ) { //循环获取字段的内容 for ( unsigned int i = 0; i < m_nCurFieldNum; i++ ) { const char* pTmp = NULL; //防止空值, modified by yinyong 2007.12.27 pTmp = (const char*)( sqlite3_column_text( m_pStmt, i ) ); //有空值 if ( NULL == pTmp ) { ioValues.push_back( "" ); ioNull.push_back(0); } else { ioValues.push_back( pTmp ); ioNull.push_back(1); } } bRelease = false; goto __Exit; } else if ( SQLITE_BUSY == m_nState ) { if ( m_nLimitNum == m+1 ) { m_strErrInfo = sqlite3_errmsg( m_pDb ); goto __Exit; } sqlite3_busy_handler( m_pDb,NULL,NULL); Sleep( SLEEPTIME ); continue; } else { //other exceptions m_strErrInfo = sqlite3_errmsg( m_pDb ); goto __Exit; } } __Exit: if ( NULL != m_pStmt && bRelease ) { sqlite3_finalize( m_pStmt ); m_pStmt = NULL; } return m_nState; }
bool SqliteDataset::query(const std::string &query) { if(!handle()) throw DbErrors("No Database Connection"); std::string qry = query; int fs = qry.find("select"); int fS = qry.find("SELECT"); if (!( fs >= 0 || fS >=0)) throw DbErrors("MUST be select SQL!"); close(); sqlite3_stmt *stmt = NULL; if (db->setErr(sqlite3_prepare_v2(handle(),query.c_str(),-1,&stmt, NULL),query.c_str()) != SQLITE_OK) throw DbErrors(db->getErrorMsg()); // column headers const unsigned int numColumns = sqlite3_column_count(stmt); result.record_header.resize(numColumns); for (unsigned int i = 0; i < numColumns; i++) result.record_header[i].name = sqlite3_column_name(stmt, i); // returned rows while (sqlite3_step(stmt) == SQLITE_ROW) { // have a row of data sql_record *res = new sql_record; res->resize(numColumns); for (unsigned int i = 0; i < numColumns; i++) { field_value &v = res->at(i); switch (sqlite3_column_type(stmt, i)) { case SQLITE_INTEGER: v.set_asInt64(sqlite3_column_int64(stmt, i)); break; case SQLITE_FLOAT: v.set_asDouble(sqlite3_column_double(stmt, i)); break; case SQLITE_TEXT: v.set_asString((const char *)sqlite3_column_text(stmt, i)); break; case SQLITE_BLOB: v.set_asString((const char *)sqlite3_column_text(stmt, i)); break; case SQLITE_NULL: default: v.set_asString(""); v.set_isNull(); break; } } result.records.push_back(res); } if (db->setErr(sqlite3_finalize(stmt),query.c_str()) == SQLITE_OK) { active = true; ds_state = dsSelect; this->first(); return true; } else { throw DbErrors(db->getErrorMsg()); } }
int load_tranmap_cfg(char *table) { int i=0; _tranmap *tmap=NULL; size_t shmsize; int shmid=0; SysLog(LOG_SYS_SHOW,"开始装载交易映射配置表[%s]\n",table); /** init commmsg **/ shmsize=MAXTRANMAP*sizeof(_tranmap); if((shmid=getshmid(5,shmsize))==-1) { SysLog(LOG_SYS_ERR,"获取交易映射配置共享内存失败\n"); return -1; } tmap = (_tranmap *)shmat(shmid,NULL,0); if(tmap == NULL) { SysLog(LOG_SYS_ERR,"鏈接交易映射配置共享内存失败\n"); return -1; } sprintf(sql,"%s %s","select * from ",table); rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0); if (rc != SQLITE_OK) { fprintf(stderr, "%s : %s\n", sql, sqlite3_errmsg(db)); sqlite3_close(db); return -1; } ncolumn = sqlite3_column_count(stmt); while (sqlite3_step(stmt) == SQLITE_ROW) { for(i = 0 ; i < ncolumn ; i++ ) { vtype = sqlite3_column_type(stmt , i); column_name = sqlite3_column_name(stmt , i); switch( vtype ) { case SQLITE_NULL: fprintf(stdout, "%s: null\n", column_name); break; case SQLITE_INTEGER: fprintf(stdout, "%s: %d\n", column_name,sqlite3_column_int(stmt,i)); break; case SQLITE_FLOAT: fprintf(stdout, "%s: %f\n", column_name,sqlite3_column_double(stmt,i)); break; case SQLITE_BLOB: /* arguably fall through... */ fprintf(stdout, "%s: BLOB\n", column_name); break; case SQLITE_TEXT: fprintf(stdout, "%s: %s\n", column_name,sqlite3_column_text(stmt,i)); break; default: fprintf(stdout, "%s: ERROR [%s]\n", column_name, sqlite3_errmsg(db)); break; } if(i==1) { strcpy(tmap->trancode,sqlite3_column_text(stmt,i)); } if(i==2) { strcpy(tmap->tranname,sqlite3_column_text(stmt,i)); } if(i==3) { strcpy(tmap->tranflow,sqlite3_column_text(stmt,i)); } if(i==4) { tmap->timeout=sqlite3_column_int(stmt,i); } } tmap++; } shmdt(tmap); SysLog(LOG_SYS_SHOW,"装载交易映射配置表[%s]成功\n",table); return 0; }
static int nc_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { (void) offset; (void) fi; filler(buf, ".", NULL, 0); filler(buf, "..", NULL, 0); char *term = (char *)malloc(strlen(path) + 1 + 1); sprintf(term, "%s%%", path); sqlite3 *db; int rc; rc = sqlite3_open(dbf, &db); if (rc != SQLITE_OK) { showError("unable to open database"); free(term); return 1; } sqlite3_stmt *stmt; /* directory */ rc = sqlite3_prepare_v2(db, "SELECT name FROM directory WHERE name LIKE ? ORDER BY name ASC;", -1, &stmt, NULL); if (rc != SQLITE_OK) { showError(sqlite3_errmsg(db)); sqlite3_finalize(stmt); sqlite3_close(db); free(term); return 1; } rc = sqlite3_bind_text(stmt, 1, term, strlen(term), SQLITE_STATIC); if (rc != SQLITE_OK) { showError(sqlite3_errmsg(db)); sqlite3_finalize(stmt); sqlite3_close(db); free(term); return 1; } char *curr; char *next; char *name; char *last = NULL; while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) { curr = strdup((char *)sqlite3_column_text(stmt, 0)); if (strcmp(curr, path) != 0) { next = strchr(curr + strlen(path) + 1, '/'); if (next) { next[0] = '\0'; } if (strstr(curr, path)) { if (strlen(path) == 1) { name = curr + 1; } else { name = curr + strlen(path) + 1; } if (!last || strcmp(name, last) != 0) { filler(buf, name, NULL, 0); if (last) { free(last); } last = strdup(name); } } } free(curr); } if (last) { free(last); } sqlite3_finalize(stmt); free(term); /* file */ rc = sqlite3_prepare_v2(db, "SELECT f.name FROM directory AS d, file as f WHERE d.id=f.directory AND d.name=? ORDER by f.name ASC;", -1, &stmt, NULL); if (rc != SQLITE_OK) { showError(sqlite3_errmsg(db)); sqlite3_finalize(stmt); sqlite3_close(db); return 1; } rc = sqlite3_bind_text(stmt, 1, path, strlen(path), SQLITE_STATIC); if (rc != SQLITE_OK) { showError(sqlite3_errmsg(db)); sqlite3_finalize(stmt); sqlite3_close(db); return 1; } while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) { filler(buf, (char *)sqlite3_column_text(stmt, 0), NULL, 0); } sqlite3_finalize(stmt); sqlite3_close(db); return 0; }
int load_vardef_cfg(char *table) { int i=0,shmid = 0; _vardef *vardef=NULL; size_t shmsize; SysLog(LOG_SYS_SHOW,"开始装载变量定义配置表[%s]\n",table); /** init vardef **/ shmsize=MAXVARDEF*sizeof(_vardef); if((shmid=getshmid(4,shmsize))==-1) { SysLog(LOG_SYS_ERR,"获取交易定义配置共享内存失败\n"); return -1; } vardef = (_vardef *)shmat(shmid,NULL,0); if(vardef == NULL) { SysLog(LOG_SYS_ERR,"链接交易定义配置共享内存失败\n"); return -1; } sprintf(sql,"%s %s","select * from ",table); rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0); if (rc != SQLITE_OK) { fprintf(stderr, "%s : %s\n", sql, sqlite3_errmsg(db)); sqlite3_close(db); return -1; } ncolumn = sqlite3_column_count(stmt); while (sqlite3_step(stmt) == SQLITE_ROW) { for(i = 0 ; i < ncolumn ; i++ ) { vtype = sqlite3_column_type(stmt , i); column_name = sqlite3_column_name(stmt , i); switch( vtype ) { case SQLITE_NULL: fprintf(stdout, "%s: null\n", column_name); break; case SQLITE_INTEGER: fprintf(stdout, "%s: %d\n", column_name,sqlite3_column_int(stmt,i)); break; case SQLITE_FLOAT: fprintf(stdout, "%s: %f\n", column_name,sqlite3_column_double(stmt,i)); break; case SQLITE_BLOB: /* arguably fall through... */ fprintf(stdout, "%s: BLOB\n", column_name); break; case SQLITE_TEXT: fprintf(stdout, "%s: %s\n", column_name,sqlite3_column_text(stmt,i)); break; default: fprintf(stdout, "%s: ERROR [%s]\n", column_name, sqlite3_errmsg(db)); break; } if(i==1) { strcpy(vardef->varname,sqlite3_column_text(stmt,i)); } if(i==2) { strcpy(vardef->varmark,sqlite3_column_text(stmt,i)); } if(i==3) { strcpy(vardef->vartype,sqlite3_column_text(stmt,i)); } if(i==4) { vardef->varlen=sqlite3_column_int(stmt,i); } } vardef++; } shmdt(vardef); SysLog(LOG_SYS_SHOW,"装载变量定义配置表[%s]成功\n",table); return 0; }
int cals_get_alarm_info(const int event_id, GList **alarm_list) { int ret = -1; GList *result = NULL; sqlite3_stmt *stmt = NULL; cal_value * cvalue = NULL; char query[CALS_SQL_MAX_LEN] = {0}; cal_alarm_info_t* alarm_info = NULL; retv_if(NULL == alarm_list, CAL_ERR_ARG_NULL); sprintf(query, "SELECT * FROM %s WHERE event_id=%d", CALS_TABLE_ALARM, event_id); stmt = cals_query_prepare(query); retvm_if(NULL == stmt, CAL_ERR_DB_FAILED, "cals_query_prepare() Failed"); ret = cals_stmt_step(stmt); if (ret < CAL_SUCCESS) { sqlite3_finalize(stmt); ERR("cals_stmt_step() Failed(%d)", ret); return ret; } while (CAL_TRUE == ret) { cvalue = calloc(1, sizeof(cal_value)); if (NULL == cvalue) { sqlite3_finalize(stmt); g_list_foreach(result, _cals_alarm_value_free, NULL); g_list_free(result); ERR("calloc() Failed(%d)", errno); return CAL_ERR_OUT_OF_MEMORY; } cvalue->v_type = CAL_EVENT_ALARM; cvalue->user_data = alarm_info = calloc(1, sizeof(cal_alarm_info_t)); if (NULL == alarm_info) { sqlite3_finalize(stmt); g_list_foreach(result, _cals_alarm_value_free, NULL); g_list_free(result); free(cvalue); ERR("calloc() Failed(%d)", errno); return CAL_ERR_OUT_OF_MEMORY; } alarm_info->event_id = sqlite3_column_int(stmt, 0); alarm_info->alarm_time = sqlite3_column_int64(stmt, 1); alarm_info->remind_tick = sqlite3_column_int(stmt, 2); alarm_info->remind_tick_unit = sqlite3_column_int(stmt, 3); alarm_info->alarm_tone = SAFE_STRDUP(sqlite3_column_text(stmt, 4)); alarm_info->alarm_description = SAFE_STRDUP(sqlite3_column_text(stmt, 5)); alarm_info->alarm_type = sqlite3_column_int(stmt, 6); alarm_info->alarm_id = sqlite3_column_int(stmt, 7); result = g_list_append(result, cvalue); ret = cals_stmt_step(stmt); } sqlite3_finalize(stmt); *alarm_list = result; return CAL_SUCCESS; }
static void pk_backend_get_details_thread(PkBackendJob *job, GVariant *params, gpointer user_data) { gchar **pkg_ids, **pkg_tokens, *homepage = NULL; gsize i; GString *desc; GRegex *expr; GMatchInfo *match_info; GError *err = NULL; sqlite3_stmt *stmt; PkBackendKatjaJobData *job_data = pk_backend_job_get_user_data(job); pk_backend_job_set_status(job, PK_STATUS_ENUM_QUERY); g_variant_get(params, "(^a&s)", &pkg_ids); if ((sqlite3_prepare_v2(job_data->db, "SELECT p.desc, p.cat, p.uncompressed FROM pkglist AS p NATURAL JOIN repos AS r " "WHERE name LIKE @name AND r.repo LIKE @repo AND ext NOT LIKE 'obsolete'", -1, &stmt, NULL) != SQLITE_OK)) { pk_backend_job_error_code(job, PK_ERROR_ENUM_CANNOT_GET_FILELIST, "%s", sqlite3_errmsg(job_data->db)); goto out; } pkg_tokens = pk_package_id_split(pkg_ids[0]); sqlite3_bind_text(stmt, 1, pkg_tokens[PK_PACKAGE_ID_NAME], -1, SQLITE_TRANSIENT); sqlite3_bind_text(stmt, 2, pkg_tokens[PK_PACKAGE_ID_DATA], -1, SQLITE_TRANSIENT); g_strfreev(pkg_tokens); if (sqlite3_step(stmt) != SQLITE_ROW) goto out; desc = g_string_new((gchar *) sqlite3_column_text(stmt, 0)); /* Regular expression for searching a homepage */ expr = g_regex_new("(?:http|ftp):\\/\\/[[:word:]\\/\\-\\.]+[[:word:]\\/](?=\\.?$)", G_REGEX_OPTIMIZE | G_REGEX_DUPNAMES, 0, &err); if (err) { pk_backend_job_error_code(job, PK_ERROR_ENUM_UNKNOWN, "%s", err->message); g_error_free(err); goto out; } if (g_regex_match(expr, desc->str, 0, &match_info)) { homepage = g_match_info_fetch(match_info, 0); /* URL */ /* Remove the last sentence with the copied URL */ for (i = desc->len - 1; i > 0; i--) { if ((desc->str[i - 1] == '.') && (desc->str[i] == ' ')) { g_string_truncate(desc, i); break; } } g_match_info_free(match_info); } g_regex_unref(expr); /* Ready */ pk_backend_job_details(job, pkg_ids[0], NULL, NULL, pk_group_enum_from_string((gchar *) sqlite3_column_text(stmt, 1)), desc->str, homepage, sqlite3_column_int(stmt, 2)); g_free(homepage); if (desc) g_string_free(desc, TRUE); out: sqlite3_finalize(stmt); pk_backend_job_finished(job); }
GNOKII_API void DB_Look(const gchar * const phone) { GString *buf, *phnStr, *timebuf; gint ret1, numError, error; time_t rawtime; struct tm * timeinfo; sqlite3_stmt * stmt; if (phone[0] == '\0') phnStr = g_string_new(""); else { phnStr = g_string_sized_new(32); g_string_printf(phnStr, "AND phone = '%s'", phone); } time(&rawtime); timeinfo = localtime(&rawtime); timebuf = g_string_sized_new(25); g_string_printf(timebuf, "'%02d:%02d:%02d'", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); sqlite3_exec(ppDbOutbox, "BEGIN TRANSACTION;", NULL, NULL, NULL); /* poll for outgoing messages */ buf = g_string_sized_new(256); g_string_printf(buf, "SELECT id, number, text, dreport FROM outbox \ WHERE processed=0 \ AND %s >= not_before \ AND %s <= not_after \ %s", timebuf->str, timebuf->str, phnStr->str); g_string_free(phnStr, TRUE); ret1 = sqlite3_prepare_v2(ppDbOutbox, buf->str, -1, &stmt, NULL); if (ret1 != SQLITE_OK) { g_print(_("%d: Parsing query %s failed!"), __LINE__, buf->str); g_print(_("Error: %s"), sqlite3_errmsg(ppDbInbox)); return; } g_string_printf(timebuf, "'%02d-%02d-%02d %02d:%02d:%02d'", timeinfo->tm_year, timeinfo->tm_mon, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec ); ret1 = sqlite3_step(stmt); while (ret1 == SQLITE_ROW) { int gerror = 0; gn_sms sms; gn_sms_default_submit(&sms); memset(&sms.remote.number, 0, sizeof (sms.remote.number)); sms.delivery_report = sqlite3_column_int(stmt, 3); strncpy(sms.remote.number, sqlite3_column_text(stmt, 1), sizeof (sms.remote.number) - 1); sms.remote.number[sizeof (sms.remote.number) - 1] = '\0'; if (sms.remote.number[0] == '+') sms.remote.type = GN_GSM_NUMBER_International; else sms.remote.type = GN_GSM_NUMBER_Unknown; strncpy((gchar *) sms.user_data[0].u.text, sqlite3_column_text(stmt, 2), 10 * GN_SMS_MAX_LENGTH + 1); sms.user_data[0].u.text[10 * GN_SMS_MAX_LENGTH] = '\0'; sms.user_data[0].length = strlen((gchar *) sms.user_data[0].u.text); sms.user_data[0].type = GN_SMS_DATA_Text; sms.user_data[1].type = GN_SMS_DATA_None; if (!gn_char_def_alphabet(sms.user_data[0].u.text)) sms.dcs.u.general.alphabet = GN_SMS_DCS_UCS2; gn_log_xdebug("Sending SMS: %s, %s\n", sms.remote.number, sms.user_data[0].u.text); numError = 0; do { error = WriteSMS(&sms); sleep(1); } while ((error == GN_ERR_TIMEOUT || error == GN_ERR_FAILED) && numError++ < 3); /* mark sended */ g_string_printf(buf, "UPDATE outbox SET processed=1, error='%d', \ processed_date=%s \ WHERE id=%d", gerror, timebuf->str, sqlite3_column_int(stmt, 0) ); sqlite3_exec(ppDbOutbox, buf->str, NULL, NULL, NULL); ret1 = sqlite3_step(stmt); } /* rollback if found any errors */ if (ret1 != SQLITE_DONE) { g_print(_("%d: SELECT FROM outbox command failed.\n"), __LINE__); g_print(_("Error: %s\n"), sqlite3_errmsg(ppDbOutbox)); sqlite3_finalize(stmt); sqlite3_exec(ppDbOutbox, "ROLLBACK TRANSACTION;", NULL, NULL, NULL); g_string_free(timebuf, TRUE); g_string_free(buf, TRUE); return; } sqlite3_finalize(stmt); sqlite3_exec(ppDbOutbox, "COMMIT;", NULL, NULL, NULL); g_string_free(timebuf, TRUE); g_string_free(buf, TRUE); }
static void pk_backend_get_updates_thread(PkBackendJob *job, GVariant *params, gpointer user_data) { gchar *pkg_id, *full_name, *desc, **pkg_tokens; const gchar *pkg_metadata_filename; GFile *pkg_metadata_dir; GFileEnumerator *pkg_metadata_enumerator; GFileInfo *pkg_metadata_file_info; GError *err = NULL; sqlite3_stmt *stmt; PkBackendKatjaJobData *job_data = pk_backend_job_get_user_data(job); pk_backend_job_set_status(job, PK_STATUS_ENUM_QUERY); if ((sqlite3_prepare_v2(job_data->db, "SELECT p1.full_name, p1.name, p1.ver, p1.arch, r.repo, p1.summary, p1.ext " "FROM pkglist AS p1 NATURAL JOIN repos AS r " "WHERE p1.name LIKE @name AND p1.repo_order = " "(SELECT MIN(p2.repo_order) FROM pkglist AS p2 WHERE p2.name = p1.name GROUP BY p2.name)", -1, &stmt, NULL) != SQLITE_OK)) { pk_backend_job_error_code(job, PK_ERROR_ENUM_CANNOT_GET_FILELIST, "%s", sqlite3_errmsg(job_data->db)); goto out; } /* Read the package metadata directory and comprare all installed packages with ones in the cache */ pkg_metadata_dir = g_file_new_for_path("/var/log/packages"); pkg_metadata_enumerator = g_file_enumerate_children(pkg_metadata_dir, "standard::name", G_FILE_QUERY_INFO_NONE, NULL, &err); g_object_unref(pkg_metadata_dir); if (err) { pk_backend_job_error_code(job, PK_ERROR_ENUM_NO_CACHE, "/var/log/packages: %s", err->message); g_error_free(err); goto out; } while ((pkg_metadata_file_info = g_file_enumerator_next_file(pkg_metadata_enumerator, NULL, NULL))) { pkg_metadata_filename = g_file_info_get_name(pkg_metadata_file_info); pkg_tokens = katja_cut_pkg(pkg_metadata_filename); /* Select the package from the database */ sqlite3_bind_text(stmt, 1, pkg_tokens[0], -1, SQLITE_TRANSIENT); /* If there are more packages with the same name, remember the one from the repository with the lowest order */ if ((sqlite3_step(stmt) == SQLITE_ROW) || g_slist_find_custom(repos, ((gchar *) sqlite3_column_text(stmt, 4)), katja_cmp_repo)) { full_name = g_strdup((gchar *) sqlite3_column_text(stmt, 0)); if (!g_strcmp0((gchar *) sqlite3_column_text(stmt, 6), "obsolete")) { /* Remove if obsolete */ pkg_id = pk_package_id_build(pkg_tokens[PK_PACKAGE_ID_NAME], pkg_tokens[PK_PACKAGE_ID_VERSION], pkg_tokens[PK_PACKAGE_ID_ARCH], "obsolete"); /* TODO: * 1: Use the repository name instead of "obsolete" above and check in pk_backend_update_packages() if the package is obsolete or not * 2: Get description from /var/log/packages, not from the database */ desc = g_strdup((gchar *) sqlite3_column_text(stmt, 5)); pk_backend_job_package(job, PK_INFO_ENUM_REMOVING, pkg_id, desc); g_free(desc); g_free(pkg_id); } else if (g_strcmp0(pkg_metadata_filename, full_name)) { /* Update available */ pkg_id = pk_package_id_build((gchar *) sqlite3_column_text(stmt, 1), (gchar *) sqlite3_column_text(stmt, 2), (gchar *) sqlite3_column_text(stmt, 3), (gchar *) sqlite3_column_text(stmt, 4)); desc = g_strdup((gchar *) sqlite3_column_text(stmt, 5)); pk_backend_job_package(job, PK_INFO_ENUM_NORMAL, pkg_id, desc); g_free(desc); g_free(pkg_id); } g_free(full_name); } sqlite3_clear_bindings(stmt); sqlite3_reset(stmt); g_strfreev(pkg_tokens); g_object_unref(pkg_metadata_file_info); } g_object_unref(pkg_metadata_enumerator); out: sqlite3_finalize(stmt); pk_backend_job_finished (job); }
int main(int argc, char **argv) { if(argc < 2 || 0 == strcmp(argv[1],"--help") || 0 == strcmp(argv[1], "-h")) { fprintf(stderr, "Usage: %s <dbname> [metadb]\n", argv[0]); exit(1); } sqlite3 *db = NULL; int rc; char *dbname = argv[1]; rc = sqlite3_open_v2(dbname, &db, SQLITE_OPEN_READONLY, NULL); if(SQLITE_OK != rc) { fprintf(stderr, "Can't open database %s (%i): %s\n", dbname, rc, sqlite3_errmsg(db)); sqlite3_close(db); exit(1); } int have_meta = 0; if(argc > 2) { char attach_sql[1024]; char *exec_errmsg; snprintf(attach_sql,sizeof(attach_sql),"ATTACH \"%s\" AS meta", argv[2]); rc = sqlite3_exec(db, attach_sql, NULL, NULL, &exec_errmsg); if(SQLITE_OK != rc) { fprintf(stderr, "Error attaching meta db (%i): %s\n", rc, exec_errmsg); sqlite3_free(exec_errmsg); sqlite3_close(db); exit(1); } have_meta = 1; } const char *tbl_list_sql = "SELECT tbl_name,NULL AS label,NULL AS color,NULL AS clusterid " "FROM sqlite_master WHERE type='table'"; if(have_meta) { tbl_list_sql = "SELECT sqlite_master.tbl_name AS tbl_name, meta.cluster.label AS label, meta.cluster.color AS color, meta.cluster.clusterid AS clusterid \n" "FROM sqlite_master \n" "LEFT JOIN meta.tbl_cluster ON sqlite_master.tbl_name=meta.tbl_cluster.tbl_name \n" "LEFT JOIN meta.cluster ON meta.tbl_cluster.clusterid=meta.cluster.clusterid \n" "LEFT JOIN meta.ignorelist ON sqlite_master.tbl_name=meta.ignorelist.tbl_name \n" "WHERE meta.ignorelist.tbl_name IS NULL \n" " AND main.sqlite_master.type='table'\n" "GROUP BY sqlite_master.tbl_name\n" "ORDER BY meta.cluster.clusterid\n"; } sqlite3_stmt *tbl_list_stmt; // fprintf(stderr, "%s\n", tbl_list_sql); rc = sqlite3_prepare_v2(db, tbl_list_sql, -1, &tbl_list_stmt, NULL); if(SQLITE_OK != rc) { fprintf(stderr, "Can't prepare table list statement (%i): %s\n", rc, sqlite3_errmsg(db)); sqlite3_close(db); exit(1); } printf("digraph sqliteschema {\n"); printf("node [shape=plaintext];\n"); if(have_meta) { const char settings_sql[] = "SELECT setting FROM meta.graphsettings"; sqlite3_stmt *settings_stmt; rc = sqlite3_prepare_v2(db, settings_sql, -1, &settings_stmt, NULL); if(SQLITE_OK != rc) { fprintf(stderr, "Warning: Cannot find meta.graphsettings (%i): %s\n", rc, sqlite3_errmsg(db)); } else { while(SQLITE_ROW == (rc = sqlite3_step(settings_stmt))) { printf("%s\n", sqlite3_column_text(settings_stmt,0)); } sqlite3_finalize(settings_stmt); } } else { printf("rankdir=LR\n"); printf("splines=true\n"); printf("overlap=scale\n"); } const int cols = 4; int curr_cluster = -1; while(SQLITE_ROW == (rc = sqlite3_step(tbl_list_stmt))) { const char *tbl_name = (char *)sqlite3_column_text(tbl_list_stmt, 0); int cluster_id = SQLITE_NULL==sqlite3_column_type(tbl_list_stmt,3)?-1:sqlite3_column_int(tbl_list_stmt,3); if(cluster_id != curr_cluster && curr_cluster != -1) { printf("}\n"); } if(cluster_id != curr_cluster && cluster_id != -1) { printf("subgraph cluster_%i {\n", cluster_id); if(SQLITE_NULL!=sqlite3_column_type(tbl_list_stmt,1)) { printf("label=\"%s\"\n", sqlite3_column_text(tbl_list_stmt,1)); } if(SQLITE_NULL!=sqlite3_column_type(tbl_list_stmt,2)) { printf("color=\"%s\"\n", sqlite3_column_text(tbl_list_stmt,2)); } } curr_cluster=cluster_id; char *tbl_info_sql = sqlite3_mprintf("PRAGMA table_info(%q)", tbl_name); sqlite3_stmt *tbl_info_stmt; rc = sqlite3_prepare_v2(db, tbl_info_sql, -1, &tbl_info_stmt, NULL); if(SQLITE_OK != rc) { fprintf(stderr, "Can't prepare table info statement on table %s (%i): %s\n", tbl_name, rc, sqlite3_errmsg(db)); sqlite3_close(db); exit(1); } printf("%s [label=<<TABLE CELLSPACING=\"0\"><TR><TD COLSPAN=\"%i\"><U>%s</U></TD></TR>", tbl_name, cols, tbl_name); int curr_row = 0; int in_brace = 0; while(SQLITE_ROW == (rc = sqlite3_step(tbl_info_stmt))) { if(0 == curr_row%cols) { in_brace = 1; printf("<TR>"); } printf("<TD PORT=\"%s\">%s</TD>", sqlite3_column_text(tbl_info_stmt, 1), sqlite3_column_text(tbl_info_stmt, 1)); curr_row++; if(0 == curr_row%cols) { in_brace = 0; printf("</TR>"); } } if(in_brace) { printf("</TR>"); } printf("</TABLE>>];\n"); sqlite3_free(tbl_info_sql); sqlite3_finalize(tbl_info_stmt); } if(curr_cluster != -1) { printf("}\n"); } sqlite3_reset(tbl_list_stmt); while(SQLITE_ROW == (rc = sqlite3_step(tbl_list_stmt))) { const char *tbl_name = (char *)sqlite3_column_text(tbl_list_stmt, 0); char *fkey_info_sql = sqlite3_mprintf("PRAGMA foreign_key_list(%q)", tbl_name); sqlite3_stmt *fkey_info_stmt; rc = sqlite3_prepare_v2(db, fkey_info_sql, -1, &fkey_info_stmt, NULL); if(SQLITE_OK != rc) { fprintf(stderr, "Can't prepare foreign key statement on table %s (%i): %s\n", tbl_name, rc, sqlite3_errmsg(db)); sqlite3_close(db); exit(1); } while(SQLITE_ROW == (rc = sqlite3_step(fkey_info_stmt))) { printf("%s:%s -> %s:%s;\n", tbl_name, sqlite3_column_text(fkey_info_stmt, 3), sqlite3_column_text(fkey_info_stmt, 2), sqlite3_column_text(fkey_info_stmt, 4)); } sqlite3_free(fkey_info_sql); sqlite3_finalize(fkey_info_stmt); } printf("}\n"); sqlite3_finalize(tbl_list_stmt); sqlite3_close(db); return 0; }
DLL_FUNCTION(const char*) BU_SQLite_Column_Text(sqlite3_stmt* pStmt, int32_t iCol) { #pragma comment(linker, "/EXPORT:BU_SQLite_Column_Text=_BU_SQLite_Column_Text@8") return (const char*)sqlite3_column_text(pStmt, iCol); }
int load_commmsg_cfg(char *table) { key_t key; int shmid,i=0; _commmsg *cmsg=NULL; size_t shmsize; /** init commmsg **/ shmsize=MAXCOMMMSG*sizeof(_commmsg); if((shmid=getshmid(9,shmsize))==-1) { SysLog(LOG_SYS_ERR,"获取共享内存失败\n"); return -1; } SysLog(LOG_SYS_SHOW,"开始加载配置文件\n"); cmsg = (_commmsg *)shmat(shmid,NULL,0); if(cmsg == NULL) { SysLog(LOG_SYS_ERR,"链接共享内存失败\n"); return -1; } sprintf(sql,"%s %s","select * from ",table); rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0); if (rc != SQLITE_OK) { fprintf(stderr, "%s : %s\n", sql, sqlite3_errmsg(db)); sqlite3_close(db); return -1; } ncolumn = sqlite3_column_count(stmt); while (sqlite3_step(stmt) == SQLITE_ROW) { for(i = 0 ; i < ncolumn ; i++ ) { vtype = sqlite3_column_type(stmt , i); column_name = sqlite3_column_name(stmt , i); switch( vtype ) { case SQLITE_NULL: fprintf(stdout, "%s: null\n", column_name); break; case SQLITE_INTEGER: fprintf(stdout, "%s: %d\n", column_name,sqlite3_column_int(stmt,i)); break; case SQLITE_FLOAT: fprintf(stdout, "%s: %f\n", column_name,sqlite3_column_double(stmt,i)); break; case SQLITE_BLOB: /* arguably fall through... */ fprintf(stdout, "%s: BLOB\n", column_name); break; case SQLITE_TEXT: fprintf(stdout, "%s: %s\n", column_name,sqlite3_column_text(stmt,i)); break; default: fprintf(stdout, "%s: ERROR [%s]\n", column_name, sqlite3_errmsg(db)); break; } if(i==1) { strcpy(cmsg->commname,sqlite3_column_text(stmt,i)); } if(i==2) { cmsg->len=sqlite3_column_int(stmt,i); } if(i==3) { strcpy(cmsg->commvar,sqlite3_column_text(stmt,i)); } if(i==4) { strcpy(cmsg->commmark,sqlite3_column_text(stmt,i)); } } cmsg++; } SysLog(LOG_SYS_SHOW,"加载配置文件成功\n"); shmdt(cmsg); return 0; }
int db_search_files(struct search_node *snode, struct evbuffer *buf, size_t *count) { int err; const char *tail; sqlite3_stmt *stmt = 0; size_t i; struct { char name_term[MAX_NAME_TERM_LEN + 1]; size_t name_len; uint64_t minsize; uint64_t maxsize; uint64_t srcavail; uint64_t srccomplete; uint64_t minbitrate; uint64_t minlength; struct search_node *ext_node; struct search_node *codec_node; struct search_node *type_node; } params; char query[MAX_SEARCH_QUERY_LEN + 1] = " SELECT f.hash,f.name,f.size,f.type,f.ext,f.srcavail,f.srccomplete,f.rating,f.rated_count," " (SELECT sid FROM sources WHERE fid=f.fid LIMIT 1) AS sid," " f.mlength,f.mbitrate,f.mcodec " " FROM fnames n" " JOIN files f ON f.fid = n.docid" " WHERE fnames MATCH ?"; memset(¶ms, 0, sizeof params); while (snode) { if ((ST_AND <= snode->type) && (ST_NOT >= snode->type)) { if (!snode->left_visited) { if (snode->string_term) { params.name_len++; DB_CHECK(params.name_len < sizeof params.name_term); strcat(params.name_term, "("); } snode->left_visited = 1; snode = snode->left; continue; } else if (!snode->right_visited) { if (snode->string_term) { const char *oper = 0; switch (snode->type) { case ST_AND: params.name_len += 5; oper = " AND "; break; case ST_OR: params.name_len += 4; oper = " OR "; break; case ST_NOT: params.name_len += 5; oper = " NOT "; break; default: DB_CHECK(0); } DB_CHECK(params.name_len < sizeof params.name_term); strcat(params.name_term, oper); } snode->right_visited = 1; snode = snode->right; continue; } else { if (snode->string_term) { params.name_len++; DB_CHECK(params.name_len < sizeof params.name_term); strcat(params.name_term, ")"); } } } else { switch (snode->type) { case ST_STRING: params.name_len += snode->str_len; DB_CHECK(params.name_len < sizeof params.name_term); strncat(params.name_term, snode->str_val, snode->str_len); break; case ST_EXTENSION: params.ext_node = snode; break; case ST_CODEC: params.codec_node = snode; break; case ST_MINSIZE: params.minsize = snode->int_val; break; case ST_MAXSIZE: params.maxsize = snode->int_val; break; case ST_SRCAVAIL: params.srcavail = snode->int_val; break; case ST_SRCCOMLETE: params.srccomplete = snode->int_val; break; case ST_MINBITRATE: params.minbitrate = snode->int_val; break; case ST_MINLENGTH: params.minlength = snode->int_val; break; case ST_TYPE: params.type_node = snode; break; default: DB_CHECK(0); } } snode = snode->parent; } if (params.ext_node) { strcat(query, " AND f.ext=?"); } if (params.codec_node) { strcat(query, " AND f.mcodec=?"); } if (params.minsize) { strcat(query, " AND f.size>?"); } if (params.maxsize) { strcat(query, " AND f.size<?"); } if (params.srcavail) { strcat(query, " AND f.srcavail>?"); } if (params.srccomplete) { strcat(query, " AND f.srccomplete>?"); } if (params.minbitrate) { strcat(query, " AND f.mbitrate>?"); } if (params.minlength) { strcat(query, " AND f.mlength>?"); } if (params.type_node) { strcat(query, " AND f.type=?"); } strcat(query, " LIMIT ?"); DB_CHECK(SQLITE_OK == sqlite3_prepare_v2(s_db, query, strlen(query) + 1, &stmt, &tail)); i = 1; DB_CHECK(SQLITE_OK == sqlite3_bind_text(stmt, i++, params.name_term, params.name_len + 1, SQLITE_STATIC)); if (params.ext_node) { DB_CHECK(SQLITE_OK == sqlite3_bind_text(stmt, i++, params.ext_node->str_val, params.ext_node->str_len, SQLITE_STATIC)); } if (params.codec_node) { DB_CHECK(SQLITE_OK == sqlite3_bind_text(stmt, i++, params.codec_node->str_val, params.codec_node->str_len, SQLITE_STATIC)); } if (params.minsize) { DB_CHECK(SQLITE_OK == sqlite3_bind_int64(stmt, i++, params.minsize)); } if (params.maxsize) { DB_CHECK(SQLITE_OK == sqlite3_bind_int64(stmt, i++, params.maxsize)); } if (params.srcavail) { DB_CHECK(SQLITE_OK == sqlite3_bind_int64(stmt, i++, params.srcavail)); } if (params.srccomplete) { DB_CHECK(SQLITE_OK == sqlite3_bind_int64(stmt, i++, params.srccomplete)); } if (params.minbitrate) { DB_CHECK(SQLITE_OK == sqlite3_bind_int64(stmt, i++, params.minbitrate)); } if (params.minlength) { DB_CHECK(SQLITE_OK == sqlite3_bind_int64(stmt, i++, params.minlength)); } if (params.type_node) { uint8_t type = get_ed2k_file_type(params.type_node->str_val, params.type_node->str_len); DB_CHECK(SQLITE_OK == sqlite3_bind_int(stmt, i++, type)); } DB_CHECK(SQLITE_OK == sqlite3_bind_int(stmt, i++, *count)); i = 0; while (((err = sqlite3_step(stmt)) == SQLITE_ROW) && (i < *count)) { struct search_file sfile; uint64_t sid; int col = 0; memset(&sfile, 0, sizeof sfile); sfile.hash = (const unsigned char *) sqlite3_column_blob(stmt, col++); sfile.name_len = sqlite3_column_bytes(stmt, col); sfile.name_len = sfile.name_len > MAX_FILENAME_LEN ? MAX_FILENAME_LEN : sfile.name_len; sfile.name = (const char *) sqlite3_column_text(stmt, col++); sfile.size = sqlite3_column_int64(stmt, col++); sfile.type = sqlite3_column_int(stmt, col++); sfile.ext_len = sqlite3_column_bytes(stmt, col); sfile.ext_len = sfile.ext_len > MAX_FILEEXT_LEN ? MAX_FILEEXT_LEN : sfile.ext_len; sfile.ext = (const char *) sqlite3_column_text(stmt, col++); sfile.srcavail = sqlite3_column_int(stmt, col++); sfile.srccomplete = sqlite3_column_int(stmt, col++); sfile.rating = sqlite3_column_int(stmt, col++); sfile.rated_count = sqlite3_column_int(stmt, col++); sid = sqlite3_column_int64(stmt, col++); sfile.client_id = GET_SID_ID(sid); sfile.client_port = GET_SID_PORT(sid); sfile.media_length = sqlite3_column_int(stmt, col++); sfile.media_bitrate = sqlite3_column_int(stmt, col++); sfile.media_codec_len = sqlite3_column_bytes(stmt, col); sfile.media_codec_len = sfile.media_codec_len > MAX_FILEEXT_LEN ? MAX_FILEEXT_LEN : sfile.media_codec_len; sfile.media_codec = (const char *) sqlite3_column_text(stmt, col++); write_search_file(buf, &sfile); ++i; } DB_CHECK((i == *count) || (SQLITE_DONE == err)); *count = i; return 1; failed: if (stmt) sqlite3_finalize(stmt); ED2KD_LOGERR("failed perform search query (%s)", sqlite3_errmsg(s_db)); return 0; }
int load_flow_cfg(char *table) { key_t key; int i=0,shmid; _flow *flow=NULL; size_t shmsize; /** init commmsg **/ shmsize=MAXFLOW*sizeof(_flow); if((shmid=getshmid(8,shmsize))==-1) { SysLog(LOG_SYS_ERR,"获取流程配置共享内存失败\n"); return -1; } SysLog(LOG_SYS_SHOW,"开始装载流程配置表[%s]\n",table); flow = (_flow *)shmat(shmid,NULL,0); if(flow == NULL) { SysLog(LOG_SYS_ERR,"链接流程配置共享内存失败\n"); return -1; } sprintf(sql,"%s %s","select * from ",table); rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0); if (rc != SQLITE_OK) { fprintf(stderr, "%s : %s\n", sql, sqlite3_errmsg(db)); sqlite3_close(db); return -1; } ncolumn = sqlite3_column_count(stmt); while (sqlite3_step(stmt) == SQLITE_ROW) { for(i = 0 ; i < ncolumn ; i++ ) { vtype = sqlite3_column_type(stmt , i); column_name = sqlite3_column_name(stmt , i); switch( vtype ) { case SQLITE_NULL: fprintf(stdout, "%s: null\n", column_name); break; case SQLITE_INTEGER: fprintf(stdout, "%s: %d\n", column_name,sqlite3_column_int(stmt,i)); break; case SQLITE_FLOAT: fprintf(stdout, "%s: %f\n", column_name,sqlite3_column_double(stmt,i)); break; case SQLITE_BLOB: /* arguably fall through... */ fprintf(stdout, "%s: BLOB\n", column_name); break; case SQLITE_TEXT: fprintf(stdout, "%s: %s\n", column_name,sqlite3_column_text(stmt,i)); break; default: fprintf(stdout, "%s: ERROR [%s]\n", column_name, sqlite3_errmsg(db)); break; } if(i==1) strcpy(flow->flowname,sqlite3_column_text(stmt,i)); if(i==2) strcpy(flow->flowmark,sqlite3_column_text(stmt,i)); if(i==3) strcpy(flow->flowso,sqlite3_column_text(stmt,i)); if(i==4) strcpy(flow->flowfunc,sqlite3_column_text(stmt,i)); if(i==5) strcpy(flow->funcpar1,sqlite3_column_text(stmt,i)); if(i==6) strcpy(flow->errflow,sqlite3_column_text(stmt,i)); } flow++; } shmdt(flow); SysLog(LOG_SYS_SHOW,"装载流程配置表[%s]成功\n",table); return 0; }
static int build_record(sqlite3_stmt *ppStmt, DbRecord *recordp, struct sqlite_workspace* w){ int i, j, cols = sqlite3_column_count(ppStmt); char *num_delim = "~"; char *element_delim= "/"; char *w_buf; char *out_ptr, *in_ptr; if(*(w->count) == 36781) printf("ha!\n"); for(i = 0, w->f = fieldlist; i < cols && w->f->name != NULL; (w->f)++, i++){ //switch(sqlite3_column_type(ppStmt, i)){ if(w->f->array){ j=0; memcpy(w->buf, sqlite3_column_text(ppStmt, i), sqlite3_column_bytes(ppStmt, i)+1); w_buf = w->buf; while((out_ptr=strsep(&(w_buf), element_delim)) != NULL){ if(j >= w->f->array_len) break; in_ptr=strsep(&out_ptr, num_delim); switch(w->f->type){ case UNSIGNED_LONG: *(((int*)((char*)recordp+(w->f->offset)))+j) = atoi(in_ptr); break; case STRING: memcpy((char*)recordp+(w->f->offset)+(j*(w->f->size)), in_ptr, MIN(w->f->size-1, strlen(in_ptr)+1)); if(strlen(in_ptr)+1 > w->f->size) *((char*)recordp+(w->f->offset)+(j*(w->f->size))+(w->f->size)-1) = '\0'; //if(j > 1) // printf("%s\n", in_ptr); break; case DATE: strptime(in_ptr, "%Y%m%d", ((struct tm*)((char*)recordp+(w->f->offset)))+j); break; case DOUBLE: *(((double*)((char*)recordp+(w->f->offset)))+j) = strtod(in_ptr, NULL); break; default: abort(); } ++j; } //if(j+1 < w->f->array_len) } else{ switch(w->f->type){ case UNSIGNED_LONG: *(int*)((char*)recordp+(w->f->offset)) = sqlite3_column_int(ppStmt, i); break; case STRING: //printf("%lu\n", *(w->count)); //if(*(w->count) > 36781) // printf("%s\n", sqlite3_column_text(ppStmt, i)); memcpy((char*)recordp+(w->f->offset), sqlite3_column_text(ppStmt, i), MIN(w->f->size-1,sqlite3_column_bytes(ppStmt, i))); *((char*)recordp+(w->f->offset)+MIN(w->f->size-1, sqlite3_column_bytes(ppStmt, i))) = '\0'; break; case DATE: strptime((char*)sqlite3_column_text(ppStmt, i), "%Y%m%d", (struct tm*)((char*)recordp+(w->f->offset))); break; case DOUBLE: *(double*)((char*)recordp+(w->f->offset)) = sqlite3_column_double(ppStmt, i); break; default: abort(); } } } if(i < cols){ printf("Description file has fewer slots than sqlite query columns."); abort(); } if(w->f->name != NULL){ printf("Description file has more slots that sqlite query columns."); abort(); } return(0); }
int load_xmlcfg(char *xmltype,char *table) { int i = 0; _xmlcfg *xmlcfg = NULL; int shmid = 0; size_t shmsize = MAXXMLCFG*sizeof(_xmlcfg); SysLog(LOG_SYS_SHOW,"开始装载XML配置表[%s]\n",table); if((shmid = getshmid(6,shmsize))==-1) { SysLog(LOG_SYS_ERR,"获取XML配置共享内存失败\n"); return -1; } if((xmlcfg = shmat(shmid,NULL,0))==(void *)-1) { SysLog(LOG_SYS_ERR,"链接XML配置共享内存失败\n"); return -1; } sprintf(sql,"%s %s","select * from ",table); rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0); if (rc != SQLITE_OK) { fprintf(stderr, "%s : %s\n", sql, sqlite3_errmsg(db)); sqlite3_close(db); return -1; } ncolumn = sqlite3_column_count(stmt); while (sqlite3_step(stmt) == SQLITE_ROW) { for(i = 0 ; i < ncolumn ; i++ ) { vtype = sqlite3_column_type(stmt , i); column_name = sqlite3_column_name(stmt , i); switch( vtype ) { case SQLITE_NULL: fprintf(stdout, "%s: null\n", column_name); break; case SQLITE_INTEGER: fprintf(stdout, "%s: %d\n", column_name,sqlite3_column_int(stmt,i)); break; case SQLITE_FLOAT: fprintf(stdout, "%s: %f\n", column_name,sqlite3_column_double(stmt,i)); break; case SQLITE_BLOB: /* arguably fall through... */ fprintf(stdout, "%s: BLOB\n", column_name); break; case SQLITE_TEXT: fprintf(stdout, "%s: %s\n", column_name,sqlite3_column_text(stmt,i)); break; default: fprintf(stdout, "%s: ERROR [%s]\n", column_name, sqlite3_errmsg(db)); break; } if(i==1) strcpy(xmlcfg->xmlname,sqlite3_column_text(stmt,i)); if(i==2) strcpy(xmlcfg->mark,sqlite3_column_text(stmt,i)); if(i==3) strcpy(xmlcfg->fullpath,sqlite3_column_text(stmt,i)); if(i==4) strcpy(xmlcfg->varname,sqlite3_column_text(stmt,i)); if(i==5) strcpy(xmlcfg->isneed,sqlite3_column_text(stmt,i)); if(i==6) strcpy(xmlcfg->sign,sqlite3_column_text(stmt,i)); if(i==7) strcpy(xmlcfg->loop,sqlite3_column_text(stmt,i)); if(i==7) xmlcfg->depth=sqlite3_column_int(stmt,i); } xmlcfg++; } shmdt(xmlcfg); SysLog(LOG_SYS_SHOW,"装载XML配置表[%s]成功\n",table); return 0; }
/* public native void dbopen(String path, int flags, String locale); */ static void dbopen(JNIEnv* env, jobject object, jstring pathString, jint flags) { int err; sqlite3 * handle = NULL; sqlite3_stmt * statement = NULL; char const * path8 = env->GetStringUTFChars(pathString, NULL); int sqliteFlags; // Error code handling for SQLite exec char* zErrMsg = NULL; // register the logging func on sqlite. needs to be done BEFORE any sqlite3 func is called. registerLoggingFunc(path8); // convert our flags into the sqlite flags if (flags & CREATE_IF_NECESSARY) { sqliteFlags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; } else if (flags & OPEN_READONLY) { sqliteFlags = SQLITE_OPEN_READONLY; } else { sqliteFlags = SQLITE_OPEN_READWRITE; } err = sqlite3_open_v2(path8, &handle, sqliteFlags, NULL); if (err != SQLITE_OK) { LOGE("sqlite3_open_v2(\"%s\", &handle, %d, NULL) failed\n", path8, sqliteFlags); throw_sqlite3_exception(env, handle); goto done; } // WAL is a new rollback method available in SQLite v3.7+. WAL speeds up writes to // SQLite databases. WAL cannot be used with Read Only databases or databases opened // in read only mode. // Check if DB can use WAL mode; Open in WAL mode for non-ReadOnly DBs if(!(flags & OPEN_READONLY) && (use_wal_mode(path8))) { // Configure databases to run in WAL mode. err = sqlite3_exec(handle,"PRAGMA journal_mode = WAL;", NULL, NULL,&zErrMsg); if (SQLITE_OK != err) { LOGE("sqlite3_exec - Failed to set WAL mode for [%s] \n", path8); err = sqlite3_exec(handle,"PRAGMA journal_mode = DELETE;", NULL, NULL,&zErrMsg); if(SQLITE_OK != err) { LOGE("sqlite3_exec - Failed to set DELETE mode for [%s] \n", path8); throw_sqlite3_exception(env, handle); goto done; } } else { LOGI("WAL succesfuly enabled for [%s] \n", path8); // Set autocheckpoint = 100 pages err = sqlite3_wal_autocheckpoint(handle, 100); if (SQLITE_OK != err) { LOGE("sqlite3_exec to set WAL autocheckpoint failed\n"); throw_sqlite3_exception(env, handle); goto done; } else if (use_wal_mode(path8) == 2) { /* Try to disable fsyncs. We don't care if it fails */ sqlite3_exec(handle,"PRAGMA synchronous = OFF;", NULL, NULL,&zErrMsg); } } } // The soft heap limit prevents the page cache allocations from growing // beyond the given limit, no matter what the max page cache sizes are // set to. The limit does not, as of 3.5.0, affect any other allocations. sqlite3_soft_heap_limit(SQLITE_SOFT_HEAP_LIMIT); // Set the default busy handler to retry for 1000ms and then return SQLITE_BUSY err = sqlite3_busy_timeout(handle, 1000 /* ms */); if (err != SQLITE_OK) { LOGE("sqlite3_busy_timeout(handle, 1000) failed for \"%s\"\n", path8); throw_sqlite3_exception(env, handle); goto done; } #ifdef DB_INTEGRITY_CHECK static const char* integritySql = "pragma integrity_check(1);"; err = sqlite3_prepare_v2(handle, integritySql, -1, &statement, NULL); if (err != SQLITE_OK) { LOGE("sqlite_prepare_v2(handle, \"%s\") failed for \"%s\"\n", integritySql, path8); throw_sqlite3_exception(env, handle); goto done; } // first is OK or error message err = sqlite3_step(statement); if (err != SQLITE_ROW) { LOGE("integrity check failed for \"%s\"\n", integritySql, path8); throw_sqlite3_exception(env, handle); goto done; } else { const char *text = (const char*)sqlite3_column_text(statement, 0); if (strcmp(text, "ok") != 0) { LOGE("integrity check failed for \"%s\": %s\n", integritySql, path8, text); jniThrowException(env, "android/database/sqlite/SQLiteDatabaseCorruptException", text); goto done; } } #endif err = register_android_functions(handle, UTF16_STORAGE); if (err) { throw_sqlite3_exception(env, handle); goto done; } LOGV("Opened '%s' - %p\n", path8, handle); env->SetIntField(object, offset_db_handle, (int) handle); handle = NULL; // The caller owns the handle now. done: // Release allocated resources if (path8 != NULL) env->ReleaseStringUTFChars(pathString, path8); if (statement != NULL) sqlite3_finalize(statement); if (handle != NULL) sqlite3_close(handle); }
static CopyRowResult copyRow(JNIEnv* env, CursorWindow* window, sqlite3_stmt* statement, int numColumns, int startPos, int addedRows) { // Allocate a new field directory for the row. status_t status = window->allocRow(); if (status) { LOG_WINDOW("Failed allocating fieldDir at startPos %d row %d, error=%d", startPos, addedRows, status); return CPR_FULL; } // Pack the row into the window. CopyRowResult result = CPR_OK; for (int i = 0; i < numColumns; i++) { int type = sqlite3_column_type(statement, i); if (type == SQLITE_TEXT) { // TEXT data const char* text = reinterpret_cast<const char*>( sqlite3_column_text(statement, i)); // SQLite does not include the NULL terminator in size, but does // ensure all strings are NULL terminated, so increase size by // one to make sure we store the terminator. size_t sizeIncludingNull = sqlite3_column_bytes(statement, i) + 1; status = window->putString(addedRows, i, text, sizeIncludingNull); if (status) { LOG_WINDOW("Failed allocating %u bytes for text at %d,%d, error=%d", sizeIncludingNull, startPos + addedRows, i, status); result = CPR_FULL; break; } LOG_WINDOW("%d,%d is TEXT with %u bytes", startPos + addedRows, i, sizeIncludingNull); } else if (type == SQLITE_INTEGER) { // INTEGER data int64_t value = sqlite3_column_int64(statement, i); status = window->putLong(addedRows, i, value); if (status) { LOG_WINDOW("Failed allocating space for a long in column %d, error=%d", i, status); result = CPR_FULL; break; } LOG_WINDOW("%d,%d is INTEGER 0x%016llx", startPos + addedRows, i, value); } else if (type == SQLITE_FLOAT) { // FLOAT data double value = sqlite3_column_double(statement, i); status = window->putDouble(addedRows, i, value); if (status) { LOG_WINDOW("Failed allocating space for a double in column %d, error=%d", i, status); result = CPR_FULL; break; } LOG_WINDOW("%d,%d is FLOAT %lf", startPos + addedRows, i, value); } else if (type == SQLITE_BLOB) { // BLOB data const void* blob = sqlite3_column_blob(statement, i); size_t size = sqlite3_column_bytes(statement, i); status = window->putBlob(addedRows, i, blob, size); if (status) { LOG_WINDOW("Failed allocating %u bytes for blob at %d,%d, error=%d", size, startPos + addedRows, i, status); result = CPR_FULL; break; } LOG_WINDOW("%d,%d is Blob with %u bytes", startPos + addedRows, i, size); } else if (type == SQLITE_NULL) { // NULL field status = window->putNull(addedRows, i); if (status) { LOG_WINDOW("Failed allocating space for a null in column %d, error=%d", i, status); result = CPR_FULL; break; } LOG_WINDOW("%d,%d is NULL", startPos + addedRows, i); } else { // Unknown data ALOGE("Unknown column type when filling database window"); throw_sqlite3_exception(env, "Unknown column type when filling window"); result = CPR_ERROR; break; } } // Free the last row if if was not successfully copied. if (result != CPR_OK) { window->freeLastRow(); } return result; }