/* ** Create a new phantom with the given UUID and return its artifact ID. */ int content_new(const char *zUuid, int isPrivate){ int rid; static Stmt s1, s2, s3; assert( g.repositoryOpen ); db_begin_transaction(); if( uuid_is_shunned(zUuid) ){ db_end_transaction(0); return 0; } db_static_prepare(&s1, "INSERT INTO blob(rcvid,size,uuid,content)" "VALUES(0,-1,:uuid,NULL)" ); db_bind_text(&s1, ":uuid", zUuid); db_exec(&s1); rid = db_last_insert_rowid(); db_static_prepare(&s2, "INSERT INTO phantom VALUES(:rid)" ); db_bind_int(&s2, ":rid", rid); db_exec(&s2); if( g.markPrivate || isPrivate ){ db_multi_exec("INSERT INTO private VALUES(%d)", rid); }else{ db_static_prepare(&s3, "INSERT INTO unclustered VALUES(:rid)" ); db_bind_int(&s3, ":rid", rid); db_exec(&s3); } bag_insert(&contentCache.missing, rid); db_end_transaction(0); return rid; }
int db_prepare(sqlite3 **db){ char query[DIM]; char name[DIM] = {0}; char password[DIM] = {0}; char aux1[DIM] = {0}; char pass[MD5_DIGEST_LENGTH]; int nbytes = 0; sprintf(query, "CREATE TABLE IF NOT EXISTS users(userID INTEGER PRIMARY KEY AUTOINCREMENT, user TEXT, password TEXT, ROL INTEGER);"); if(db_exec(db, query, CREATE_TABLE) < 0){ sqlite3_close(*db); PDEBUG("DB: Error al crear la tabla\n"); return -1; } printf("Nombre del administrador: \n"); nbytes = read(0, &query, DIM); query[nbytes - 1] = '\0'; // eliminamos el intro addslahses(query, DIM, name); // escapamos las comillas simples printf("Contraseña del administrador: \n"); echo_off(); bzero(query, DIM); nbytes = read(0, &query, DIM); query[nbytes - 1] = '\0'; // eliminamos el intro echo_on(); // creamos la suma PDEBUG("DB: Caluclando la suma MD5\n"); MD5((unsigned char*) query, DIM, (unsigned char*)pass); // obtenemos la suma MD5 en caracteres ascii md5_sum((unsigned char*) pass, MD5_DIGEST_LENGTH, DIM, aux1); addslahses((char *)aux1, DIM, password); //creamos la query PDEBUG("DB: Insertando al administrador del sistema\n"); sprintf(query, "INSERT INTO users (user, password, rol) VALUES ('%s', '%s', %i);", name, password, ADMIN); if(db_exec(db, query, INSERT) <0){ sqlite3_close(*db); PDEBUG("DB: Error al insertar el usuario administrador\n"); return -1; } PDEBUG("DB: Creando la tabla del log\n"); sprintf(query, "CREATE TABLE IF NOT EXISTS log(postID INTEGER PRIMARY KEY AUTOINCREMENT, author TEXT, text TEXT, time LONG);"); if(db_exec(db, query, CREATE_TABLE) < 0){ sqlite3_close(*db); PDEBUG("DB: Error al crear la tabla\n"); return -1; } return 0; }
void insertOrUpdate(sqlite3* & db, const std::string & table, const MemberMap & m, int64_t & id) { if (id > 0) { stringstream upd; MemberMap::const_iterator it = m.begin(); MemberMap::const_iterator end = m.end(); upd << "update " << table << " set "; for (size_t i = 0; it != end; i++) { upd << it->first; upd << "="; upd << "'" << it->second << "'"; if (i < m.size() - 1) { upd << ", "; } it++; } upd << " where id=" << id << ";"; db_exec(db, upd.str()); } else { stringstream ins; MemberMap::const_iterator it = m.begin(); MemberMap::const_iterator end = m.end(); ins << "insert into " << table << " ("; for (size_t i = 0; it != end; i++) { ins << it->first; if (i < m.size() - 1) { ins << ", "; } it++; } ins << ") values ("; it = m.begin(); for (size_t i = 0; it != end; i++) { ins << "'" << it->second << "'"; if (i < m.size() - 1) { ins << ", "; } it++; } ins << ");"; db_exec(db, ins.str()); id = sqlite3_last_insert_rowid(db); } }
/* ** Change the storage of rid so that it is a delta of srcid. ** ** If rid is already a delta from some other place then no ** conversion occurs and this is a no-op unless force==1. ** ** Never generate a delta that carries a private artifact into a public ** artifact. Otherwise, when we go to send the public artifact on a ** sync operation, the other end of the sync will never be able to receive ** the source of the delta. It is OK to delta private->private and ** public->private and public->public. Just no private->public delta. ** ** If srcid is a delta that depends on rid, then srcid is ** converted to undeltaed text. ** ** If either rid or srcid contain less than 50 bytes, or if the ** resulting delta does not achieve a compression of at least 25% ** the rid is left untouched. ** ** Return 1 if a delta is made and 0 if no delta occurs. */ int content_deltify(int rid, int srcid, int force){ int s; Blob data, src, delta; Stmt s1, s2; int rc = 0; if( srcid==rid ) return 0; if( !force && findSrcid(rid)>0 ) return 0; if( content_is_private(srcid) && !content_is_private(rid) ){ return 0; } s = srcid; while( (s = findSrcid(s))>0 ){ if( s==rid ){ content_undelta(srcid); break; } } content_get(srcid, &src); if( blob_size(&src)<50 ){ blob_reset(&src); return 0; } content_get(rid, &data); if( blob_size(&data)<50 ){ blob_reset(&src); blob_reset(&data); return 0; } blob_delta_create(&src, &data, &delta); if( blob_size(&delta) <= blob_size(&data)*0.75 ){ blob_compress(&delta, &delta); db_prepare(&s1, "UPDATE blob SET content=:data WHERE rid=%d", rid); db_prepare(&s2, "REPLACE INTO delta(rid,srcid)VALUES(%d,%d)", rid, srcid); db_bind_blob(&s1, ":data", &delta); db_begin_transaction(); db_exec(&s1); db_exec(&s2); db_end_transaction(0); db_finalize(&s1); db_finalize(&s2); verify_before_commit(rid); rc = 1; } blob_reset(&src); blob_reset(&data); blob_reset(&delta); return rc; }
/* Prepares and executes INSERT, UPDATE, DELETE queries */ int db_pexec(ConnHandle *c, char *q, ... ) { va_list ap; int i, res; char *p, *s, *result, *escstr; result = (char*) strdup(""); s = (char *) malloc (sizeof(char*)); // find '?' and replace with arg value va_start(ap, q); for(p=q; *p; p++) { if( *p != '?' ) { i = strlen(result)+2; s = (char*) realloc(s, i); snprintf(s, i,"%s%c", result, *p); } else { escstr = db_escape(c, va_arg(ap, char*)); i = strlen(escstr)+strlen(result)+1; s = (char*) realloc(s, i); snprintf(s, i, "%s%s", result, escstr); free(escstr); } free(result); result = (char *) strdup(s); } va_end(ap); // execute prepared query res = db_exec(c, result); // free temporary vars free(s); free(result); return res; }
/* Opens a connection to the db server */ ConnHandle * db_connect(const char *db, const char *user, const char *password, const char *host, int port, int ssl) { ConnHandle *c = (ConnHandle *) malloc (sizeof(ConnHandle)); if( mysql_init(&c->conn)==NULL ) { syslog(LOG_CRIT, "ERROR: [db_connect] Unable to initialize database."); free(c); return NULL; } if(ssl) mysql_ssl_set(&c->conn, NULL, NULL, NULL, NULL, NULL); if( !mysql_real_connect(&c->conn,host,user,password,db,port,NULL,0) ) { syslog(LOG_CRIT,"ERROR: [db_connect] Unable to connect to database. %s", mysql_error(&c->conn)); mysql_close(&c->conn); free(c); return NULL; } // SET NAMES utf8 mysql_set_character_set(&c->conn, "utf8"); #ifdef DEBUG0 syslog(LOG_INFO, "DEBUG: [lmsd] Connected with params: db='%s' host='%s' user='******' port='%d' passwd='*'.", db, host, user, port); #endif db_exec(c, "SET NAMES utf8"); return c; }
int delete_queue(const char* uuid) { struct ast_json* j_tmp; char* tmp; char* sql; int ret; if(uuid == NULL) { // invalid parameter. return false; } j_tmp = ast_json_object_create(); tmp = get_utc_timestamp(); ast_json_object_set(j_tmp, "tm_delete", ast_json_string_create(tmp)); ast_json_object_set(j_tmp, "in_use", ast_json_integer_create(E_DL_USE_NO)); ast_free(tmp); tmp = db_get_update_str(j_tmp); AST_JSON_UNREF(j_tmp); ast_asprintf(&sql, "update queue set %s where uuid=\"%s\";", tmp, uuid); ast_free(tmp); ret = db_exec(sql); ast_free(sql); if(ret == false) { ast_log(LOG_WARNING, "Could not delete queue. uuid[%s]\n", uuid); return false; } // send notification send_manager_evt_out_queue_delete(uuid); return true; }
void csync_db_sql(const char *err, const char *fmt, ...) { char *sql; va_list ap; int rc, busyc = 0; va_start(ap, fmt); VASPRINTF(&sql, fmt, ap); va_end(ap); in_sql_query++; csync_db_maybegin(); csync_debug(2, "SQL: %s\n", sql); while (1) { rc = db_exec(db, sql); if ( rc != DB_BUSY ) break; if (busyc++ > get_dblock_timeout()) { db = 0; csync_fatal(DEADLOCK_MESSAGE); } csync_debug(2, "Database is busy, sleeping a sec.\n"); sleep(1); } if ( rc != DB_OK && err ) csync_fatal("Database Error: %s [%d]: %s on executing %s\n", err, rc, db_errmsg(db), sql); free(sql); csync_db_maycommit(); in_sql_query--; }
/* * Load attributes from domain_attrs table */ int db_load_domain_attrs(domain_t* d) { int_str name, v; str avp_val; db_res_t* res; db_rec_t* rec; unsigned short flags; load_attrs_cmd->match[0].v.lstr = d->did; if (db_exec(&res, load_attrs_cmd) < 0) { ERR("Error while querying database\n"); return -1; } rec = db_first(res); while(rec) { if (rec->fld[0].flags & DB_NULL || rec->fld[1].flags & DB_NULL || rec->fld[3].flags & DB_NULL) { ERR("Skipping row containing NULL entries\n"); goto skip; } if ((rec->fld[3].v.int4 & SRDB_LOAD_SER) == 0) goto skip; /* Get AVP name */ name.s = rec->fld[0].v.lstr; /* Test for NULL value */ if (rec->fld[2].flags & DB_NULL) { avp_val.s = 0; avp_val.len = 0; } else { avp_val = rec->fld[2].v.lstr; } flags = AVP_CLASS_DOMAIN | AVP_NAME_STR; if (rec->fld[1].v.int4 == AVP_VAL_STR) { /* String AVP */ v.s = avp_val; flags |= AVP_VAL_STR; } else { /* Integer AVP */ str2int(&avp_val, (unsigned*)&v.n); } if (add_avp_list(&d->attrs, flags, name, v) < 0) { ERR("Error while adding domain attribute %.*s to domain %.*s, " "skipping\n", name.s.len, ZSW(name.s.s), d->did.len, ZSW(d->did.s)); } skip: rec = db_next(res); } db_res_free(res); return 0; }
/* ** Make sure an artifact is public. */ void content_make_public(int rid){ static Stmt s1; db_static_prepare(&s1, "DELETE FROM private WHERE rid=:rid" ); db_bind_int(&s1, ":rid", rid); db_exec(&s1); }
/* Retrieve did directly from database, without using memory cache. Use 0 as * the value of first parameter if you only want to know whether the entry is * in the database. The function returns 1 if there is such entry, 0 if not, * and -1 on error. The result is allocated using pkg_malloc and must be * freed. */ int db_get_did(str* did, str* domain) { db_res_t* res = NULL; db_rec_t* rec; if (!domain) { ERR("BUG:Invalid parameter value\n"); goto err; } get_did_cmd->match[0].v.lstr = *domain; if (db_exec(&res, get_did_cmd) < 0) { ERR("Error in database query\n"); goto err; } rec = db_first(res); if (rec) { /* Test flags first, we are only interested in rows * that are not disabled */ if (rec->fld[1].flags & DB_NULL || (rec->fld[1].v.bitmap & SRDB_DISABLED)) { db_res_free(res); return 0; } if (did) { if (rec->fld[0].flags & DB_NULL) { did->len = 0; did->s = 0; WARN("Domain '%.*s' has NULL did\n", domain->len, ZSW(domain->s)); } else { did->s = pkg_malloc(rec->fld[0].v.lstr.len); if (!did->s) { ERR("No memory left\n"); goto err; } memcpy(did->s, rec->fld[0].v.lstr.s, rec->fld[0].v.lstr.len); did->len = rec->fld[0].v.lstr.len; } } db_res_free(res); return 1; } else { db_res_free(res); return 0; } err: if (res) db_res_free(res); return -1; }
static void db_open (void) { gchar *filename; gint res; filename = common_create_data_filename ("liferea.db"); debug1 (DEBUG_DB, "Opening DB file %s...", filename); res = sqlite3_open_v2 (filename, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL); if (SQLITE_OK != res) g_error ("Data base file %s could not be opened (error code %d: %s)...", filename, res, sqlite3_errmsg (db)); g_free (filename); sqlite3_extended_result_codes (db, TRUE); db_exec("PRAGMA journal_mode=WAL"); db_exec("PRAGMA page_size=32768"); db_exec("PRAGMA synchronous=NORMAL"); }
int cmd(string who){ mixed rows; string ret; db = db_connect("localhost", "errors"); if(who == "all") rows = db_exec(db, "select Reporter, count(*) as bing from errors " "where Status = 'DENIED' " "group by Reporter order by bing desc"); else rows = db_exec(db, sprintf("select Reporter, count(*) from errors " "where Reporter = '%s' and Status = 'DENIED' " "group by Reporter", who)); if(intp(rows)){ ret = sprintf("%-15s %s\n", "player", "reports"); ret += implode(allocate(rows, function(int i){ mixed *tmp = db_fetch(db, i+1); return sprintf("%-15s %s", tmp[0], ""+tmp[1]); }), "\n");
void db_queue_exec(void) { uint16_t i; static char cmd[CMD_BUF_LEN]; for(i = 0; i < CMD_BUF_LEN; i++) { out_char_queue(&db_cmd_queue, (cmd + i)); if('\n' == cmd[i]) { cmd[i + 1] = 0; break; } } db_exec(cmd); }
int do_binds(char *sql) { char *txt="X"; int ok; ok = db_compile(db,sql) && db_bind(db,":txt",dbChar,0,txt,-1) && db_open(db) && db_exec(db); if (!ok) { printf("compile failed: %s, SQL:%s\n",db->error,sql); } ok = db_fetch(db); printf("compiled ok, fetch = %d\n",ok); if (!ok) return 0; printf("text:'%s'\n",db_text(db->out.cols)); return 1; }
int db_userExists(char* name, sqlite3** db){ char query[DIM]; char aux[DIM]; addslahses((char *)name, DIM, aux); sprintf(query, "SELECT * FROM users WHERE user='******';", aux); if(db_exec(db, query, COUNT_ROWS) < 0){ sqlite3_close(*db); PDEBUG("DB: Error al comprobar si el usuario existe\n"); return -1; } return numRows; }
int db_addUser(char* name, char* password, int rol, sqlite3** db){ char query[DIM]; char aux[DIM]; // creamos la suma PDEBUG("DB: Caluclando la suma MD5\n"); MD5((unsigned char*) password, DIM, (unsigned char*)query); // obtenemos la suma MD5 en caracteres ascii md5_sum((unsigned char*) query, MD5_DIGEST_LENGTH, DIM, aux); addslahses((char *)aux, DIM, password); strcpy(query, name); addslahses((char *)query, DIM, aux); PDEBUG("DB: ¿Existe ya el usuario?\n"); sprintf(query, "SELECT * FROM users WHERE user='******';", aux); if(db_exec(db, query, COUNT_ROWS) <0){ sqlite3_close(*db); PDEBUG("DB: Error al insertar el usuario administrador\n"); return -1; } if(numRows > 0){ return 1; } PDEBUG("DB: Insertando el usuario\n"); sprintf(query, "INSERT INTO users (user, password, rol) VALUES ('%s', '%s', %i);", aux, password, rol); if(db_exec(db, query, INSERT) <0){ sqlite3_close(*db); PDEBUG("DB: Error al insertar el usuario administrador\n"); return -1; } return 0; }
int db_getLogPar(int socketID, sqlite3** db, char* str){ char query[DIM]; socket = socketID; sprintf(query, "SELECT author, text, time FROM log %s;", str); if(db_exec(db, query, GET_LOG) < 0){ sqlite3_close(*db); PDEBUG("DB: Error al listar el usuario administrador\n"); return -1; } return numRows; }
int db_listUser(int socketID, sqlite3** db){ char query[DIM]; socket = socketID; sprintf(query, "SELECT user, rol FROM users;"); if(db_exec(db, query, LIST_USER) < 0){ sqlite3_close(*db); PDEBUG("DB: Error al listar el usuario administrador\n"); return -1; } return numRows; }
/* ** Make sure the content at rid is the original content and is not a ** delta. */ void content_undelta(int rid){ if( findSrcid(rid)>0 ){ Blob x; if( content_get(rid, &x) ){ Stmt s; db_prepare(&s, "UPDATE blob SET content=:c, size=%d WHERE rid=%d", blob_size(&x), rid); blob_compress(&x, &x); db_bind_blob(&s, ":c", &x); db_exec(&s); db_finalize(&s); blob_reset(&x); db_multi_exec("DELETE FROM delta WHERE rid=%d", rid); } } }
bool DBPermObj::AddToWhitelist(std::string & dbuser, std::string & pattern) { char * q = new char [ pattern.length() + 1024 ]; db_struct db; snprintf(q, pattern.length() + 1024, "SELECT queryid FROM query WHERE " "proxyid = %d and db_name = '%s' and query = '%s'", proxy_id, db_name.c_str(), pattern.c_str()); /* read new queryid from the database */ if (! db_query(&db, q ,pattern.length() + 1024)) { /* Failed */ logevent(STORAGE,"DB config erorr: %s\n",db_error()); delete [] q; db_cleanup(&db); return false; } /* Download result from server */ if (db_fetch_row(&db)) { // nothing to do here, query is aready in whitelist delete [] q; db_cleanup(&db); return true; } // add pattern to the whitelist snprintf(q, pattern.length() + 1024, "INSERT into query " "(proxyid, perm, db_name, query) " "VALUES (%d,1,'%s','%s')", proxy_id, db_name.c_str(), pattern.c_str()); /* read new urls from the database */ if (! db_exec(q)) { /* Make query */ logevent(STORAGE,"DB config erorr: %s\n",db_error()); delete [] q; return false; } delete [] q; q = NULL; return true; }
int db_deleteUser(char* name, sqlite3** db){ char query[DIM]; char aux[DIM]; strcpy(query, name); addslahses((char *)query, DIM, aux); PDEBUG("DB: Insertando el usuario"); sprintf(query, "DELETE FROM users WHERE user='******';", aux); if(db_exec(db, query, COUNT_ROWS) <0){ sqlite3_close(*db); PDEBUG("DB: Error al borrar el usuario administrador\n"); return -1; } return numRows; }
static void db_vacuum (void) { sqlite3_stmt *stmt; gint res, page_count, freelist_count; /* Determine fragmentation ratio using PRAGMA page_count PRAGMA freelist_count as suggested by adriatic in this blog post http://jeff.ecchi.ca/blog/2011/12/24/investigating-lifereas-startup-performance/#comment-19989 and perform VACUUM only when needed. */ db_prepare_stmt (&stmt, "PRAGMA page_count"); sqlite3_reset (stmt); res = sqlite3_step (stmt); if (SQLITE_ROW != res) g_error ("Could not determine page count (error code %d)!", res); page_count = sqlite3_column_int (stmt, 0); sqlite3_finalize (stmt); db_prepare_stmt (&stmt, "PRAGMA freelist_count"); sqlite3_reset (stmt); res = sqlite3_step (stmt); if (SQLITE_ROW != res) g_error ("Could not determine free list count (error code %d)!", res); freelist_count = sqlite3_column_int (stmt, 0); sqlite3_finalize (stmt); float fragmentation = (100 * (float)freelist_count/page_count); if (fragmentation > VACUUM_ON_FRAGMENTATION_RATIO) { debug2 (DEBUG_DB, "Performing VACUUM as freelist count/page count ratio %2.2f > %d", fragmentation, VACUUM_ON_FRAGMENTATION_RATIO); debug_start_measurement (DEBUG_DB); db_exec ("VACUUM;"); debug_end_measurement (DEBUG_DB, "VACUUM"); } else { debug2 (DEBUG_DB, "No VACUUM as freelist count/page count ratio %2.2f <= %d", fragmentation, VACUUM_ON_FRAGMENTATION_RATIO); } }
int db_addLog(sms msj, sqlite3** db){ char query[DIM] = {0}; long tm = (long)time(0); char aux1[DIM] = {0}; char aux2[DIM] = {0}; addslahses(msj.name, NAME_LEN, aux1); addslahses(msj.text, SMS_LEN, aux2); PDEBUG("DB: Insertando en el log\n"); sprintf(query, "INSERT INTO LOG (author, text, time) VALUES ('%s', '%s', %ld);", aux1, aux2, tm); if(db_exec(db, query, INSERT) <0){ sqlite3_close(*db); PDEBUG("DB: Error al insertar el mensaje en el log\n"); return -1; } return 0; }
void csync_db_open(const char *file) { int rc = db_open(file, db_type, &db); if ( rc != DB_OK ) csync_fatal("Can't open database: %s\n", file); db_set_logger(db, csync_debug); /* ignore errors on table creation */ in_sql_query++; if (db_schema_version(db) < DB_SCHEMA_VERSION) if (db_upgrade_to_schema(db, DB_SCHEMA_VERSION) != DB_OK) csync_fatal("Cannot create database tables (version requested = %d): %s\n", DB_SCHEMA_VERSION, db_errmsg(db)); if (!db_sync_mode) db_exec(db, "PRAGMA synchronous = OFF"); in_sql_query--; // return db; }
int update_queue(struct ast_json* j_queue) { char* tmp; char* sql; struct ast_json* j_tmp; int ret; const char* uuid; uuid = ast_json_string_get(ast_json_object_get(j_queue, "uuid")); if(uuid == NULL) { ast_log(LOG_WARNING, "Could not get uuid.\n"); return false; } tmp = db_get_update_str(j_queue); if(tmp == NULL) { ast_log(LOG_WARNING, "Could not get update str.\n"); return false; } ast_asprintf(&sql, "update queue set %s where in_use=%d and uuid=\"%s\";", tmp, E_DL_USE_OK, uuid); ast_free(tmp); ret = db_exec(sql); ast_free(sql); if(ret == false) { ast_log(LOG_WARNING, "Could not update queue info. uuid[%s]\n", uuid); return false; } j_tmp = get_queue(uuid); if(j_tmp == NULL) { ast_log(LOG_WARNING, "Could not get update queue info. uuid[%s]\n", uuid); return false; } send_manager_evt_out_queue_update(j_tmp); AST_JSON_UNREF(j_tmp); return true; }
static int exec_transl(str *group_name, db_cmd_t **cmd, db_res_t **res) { db_fld_t cols[5]; db_fld_t params[2]; memset(cols, 0, sizeof(cols)); cols[0].name = transl_cfg_table_fld; cols[0].type = DB_CSTR; cols[1].name = transl_cfg_table_group_name_field_fld; cols[1].type = DB_CSTR; cols[2].name = transl_cfg_table_name_field_fld; cols[2].type = DB_CSTR; cols[3].name = transl_cfg_table_value_field_fld; cols[3].type = DB_CSTR; memset(params, 0, sizeof(params)); params[0].name = transl_group_name_fld; params[0].type = DB_STR; params[0].op = DB_EQ; DBG(MODULE_NAME": exec_transl('%.*s', ...)\n", group_name->len, group_name->s); *cmd = db_cmd(DB_GET, db_cntx, transl_tbl, cols, params, NULL); if (!*cmd) { ERR(MODULE_NAME": Error preparing query '%s'\n", transl_tbl); return -1; } (*cmd)->match[0].flags &= ~DB_NULL; (*cmd)->match[0].v.lstr = *group_name; // FIXME: proprietary code! db_setopt(*cmd, "key", "pKey"); db_setopt(*cmd, "key_omit", 1); if (db_exec(res, *cmd) < 0) { ERR(MODULE_NAME": Error executing query '%s'\n", transl_tbl); db_cmd_free(*cmd); return -1; } return 0; }
static gint db_get_schema_version (void) { guint schemaVersion; sqlite3_stmt *stmt; if (!db_table_exists ("info")) { db_exec ("CREATE TABLE info ( " " name TEXT, " " value TEXT, " " PRIMARY KEY (name) " ");"); db_set_schema_version (-1); } db_prepare_stmt (&stmt, "SELECT value FROM info WHERE name = 'schemaVersion'"); sqlite3_step (stmt); schemaVersion = sqlite3_column_int (stmt, 0); sqlite3_finalize (stmt); return schemaVersion; }
int db_checkUser(char* name, char* password, sqlite3** db){ char query[DIM]; char aux[DIM]; // creamos la suma PDEBUG("DB: Caluclando la suma MD5\n"); MD5((unsigned char*) password, DIM, (unsigned char*)query); // obtenemos la suma MD5 en caracteres ascii md5_sum((unsigned char*) query, MD5_DIGEST_LENGTH, DIM, aux); addslahses((char *)aux, DIM, password); strcpy(query, name); addslahses((char *)query, DIM, aux); sprintf(query, "SELECT rol FROM users WHERE user='******' AND password='******';", aux, password); rol = 0; if(db_exec(db, query, GET_ROL) < 0){ sqlite3_close(*db); PDEBUG("DB: Error al comprobar si el usuario existe\n"); return -1; } return rol; }
int onDbVarGet(Socket *sock, vssHttp *req, SocketMap *map) { // Генерация статистики по серверу char buf[1024],id[80],name[80]; httpSrv *srv = (void*)sock->pool; strSetLength(&srv->buf,0); // ClearResulted vss r=req->B; vssGetVar2Buffer(req->args,"id",id,sizeof(id)); vssGetVar2Buffer(req->args,"name",name,sizeof(name)); //strCat(&srv->buf,r.data,r.len); char *sql = srv->buf; printf("DB->REQ: get a var '%s' for id '%s'\n",name,id); if (db_compile(db, var_get_sql) && db_bind(db,"id",dbChar,0,id,strlen(id)) && db_bind(db,"name",dbChar,0,name,strlen(name)) && db_open(db) && db_exec(db) && db_fetch(db) ) { // ok - respons a data printf("Yes!\n"); char *t = db_text(db->out.cols); printf("Resp:%s\n",t); SocketSendHttp(sock,req,t,-1); // send result of first column } else { //error printf("ERR:%s\n",db->error); SocketPrintHttp(sock,req,"-%s",db->error); } return 1; }