/** * Retrieve a result set * \param _h handle to the database * \param _r result set that should be retrieved * \return zero on success, negative value on failure */ static int db_mysql_store_result(const db1_con_t* _h, db1_res_t** _r) { int code; if ((!_h) || (!_r)) { LM_ERR("invalid parameter value\n"); return -1; } *_r = db_mysql_new_result(); if (*_r == 0) { LM_ERR("no memory left\n"); return -2; } RES_RESULT(*_r) = mysql_store_result(CON_CONNECTION(_h)); if (!RES_RESULT(*_r)) { if (mysql_field_count(CON_CONNECTION(_h)) == 0) { (*_r)->col.n = 0; (*_r)->n = 0; goto done; } else { LM_ERR("driver error: %s\n", mysql_error(CON_CONNECTION(_h))); code = mysql_errno(CON_CONNECTION(_h)); if (code == CR_SERVER_GONE_ERROR || code == CR_SERVER_LOST) { counter_inc(mysql_cnts_h.driver_err); } db_mysql_free_result(_h, *_r); *_r = 0; return -3; } } if (db_mysql_convert_result(_h, *_r) < 0) { LM_ERR("error while converting result\n"); LM_DBG("freeing result set at %p\n", _r); /* all mem on Kamailio API side is already freed by * db_mysql_convert_result in case of error, but we also need * to free the mem from the mysql lib side, internal pkg for it * and *_r */ db_mysql_free_result(_h, *_r); *_r = 0; #if (MYSQL_VERSION_ID >= 40100) while( mysql_more_results(CON_CONNECTION(_h)) && mysql_next_result(CON_CONNECTION(_h)) == 0 ) { MYSQL_RES *res = mysql_store_result( CON_CONNECTION(_h) ); mysql_free_result(res); } #endif return -4; } done: #if (MYSQL_VERSION_ID >= 40100) while( mysql_more_results(CON_CONNECTION(_h)) && mysql_next_result(CON_CONNECTION(_h)) == 0 ) { MYSQL_RES *res = mysql_store_result( CON_CONNECTION(_h) ); mysql_free_result(res); } #endif return 0; }
static inline int wrapper_single_mysql_real_query(const db_con_t *conn, const str *query) { int code, error; if (CON_DISCON(conn)) return -1; code = mysql_real_query(CON_CONNECTION(conn), query->s, query->len); if (code == 0) return 0; error = mysql_errno(CON_CONNECTION(conn)); switch (error) { case CR_SERVER_GONE_ERROR: case CR_SERVER_LOST: case CR_COMMANDS_OUT_OF_SYNC: return -1; /* reconnection error -> <0 */ default: LM_CRIT("driver error (%i): %s\n", error, mysql_error(CON_CONNECTION(conn))); /* do not rely on libmysqlclient implementation * specification says non-zero code on error, not positive code */ return 1; } }
int db_sqlite_query(const db_con_t* _h, const db_key_t* _k, const db_op_t* _op, const db_val_t* _v, const db_key_t* _c, const int _n, const int _nc, const db_key_t _o, db_res_t** _r) { int ret=-1; #ifdef SQLITE_BIND db_ps_t ps; CON_SET_CURR_PS(_h, &ps); #else CON_RESET_CURR_PS(_h); #endif CON_RAW_QUERY(_h) = 0; ret = db_do_query(_h, _k, _op, _v, _c, _n, _nc, _o, NULL, db_sqlite_val2str, db_sqlite_submit_dummy_query, NULL); if (ret != 0) { if (_r) *_r = NULL; return ret; } if (db_copy_rest_of_count(&query_holder, &count_str)) { LM_ERR("failed to build row counter query\n"); return -1; } again: ret=sqlite3_prepare_v2(CON_CONNECTION(_h), query_holder.s, query_holder.len, &CON_SQLITE_PS(_h), NULL); if (ret==SQLITE_BUSY) goto again; if (ret!=SQLITE_OK) LM_ERR("failed to prepare: (%s)\n", sqlite3_errmsg(CON_CONNECTION(_h))); #ifdef SQLITE_BIND if (db_sqlite_bind_values(CON_SQLITE_PS(_h), _v, _n) != SQLITE_OK) { LM_ERR("failed to bind values\n"); return -1; } #endif if (_r) { ret = db_sqlite_store_result(_h, _r, _v, _n); CON_SQLITE_PS(_h) = NULL; } else { /* need to fetch now the total number of rows in query * because later won't have the query string */ CON_PS_ROWS(_h) = db_sqlite_get_query_rows(_h, &count_str, _v, _n); } return ret; }
/** * \brief Send a SQL query to the server. * * Send a SQL query to the database server. This methods tries to reconnect * to the server if the connection is gone and the auto_reconnect parameter is * enabled. It also issues a mysql_ping before the query to connect again after * a long waiting period because for some older mysql versions the auto reconnect * don't work sufficient. If auto_reconnect is enabled and the server supports it, * then the mysql_ping is probably not necessary, but its safer to do it in this * cases too. * * \param _h handle for the db * \param _s executed query * \return zero on success, negative value on failure */ static int db_mysql_submit_query(const db1_con_t* _h, const str* _s) { time_t t; int i, code; if (!_h || !_s || !_s->s) { LM_ERR("invalid parameter value\n"); return -1; } if (my_ping_interval) { t = time(0); if ((t - CON_TIMESTAMP(_h)) > my_ping_interval) { if (mysql_ping(CON_CONNECTION(_h))) { LM_WARN("driver error on ping: %s\n", mysql_error(CON_CONNECTION(_h))); counter_inc(mysql_cnts_h.driver_err); } } /* * We're doing later a query anyway that will reset the timout of the server, * so it makes sense to set the timestamp value to the actual time in order * to prevent unnecessary pings. */ CON_TIMESTAMP(_h) = t; } /* screws up the terminal when the query contains a BLOB :-( (by bogdan) * LM_DBG("submit_query(): %.*s\n", _s->len, _s->s); */ /* When a server connection is lost and a query is attempted, most of * the time the query will return a CR_SERVER_LOST, then at the second * attempt to execute it, the mysql lib will reconnect and succeed. * However is a few cases, the first attempt returns CR_SERVER_GONE_ERROR * the second CR_SERVER_LOST and only the third succeeds. * Thus the 3 in the loop count. Increasing the loop count over this * value shouldn't be needed, but it doesn't hurt either, since the loop * will most of the time stop at the second or sometimes at the third * iteration. In the case of CR_SERVER_GONE_ERROR and CR_SERVER_LOST the * driver error counter is increased */ for (i=0; i < (db_mysql_auto_reconnect ? 3 : 1); i++) { if (mysql_real_query(CON_CONNECTION(_h), _s->s, _s->len) == 0) { return 0; } code = mysql_errno(CON_CONNECTION(_h)); if (code != CR_SERVER_GONE_ERROR && code != CR_SERVER_LOST) { break; } counter_inc(mysql_cnts_h.driver_err); } LM_ERR("driver error on query: %s\n", mysql_error(CON_CONNECTION(_h))); return -2; }
int db_postgres_async_resume(db_con_t *_h, int fd, db_res_t **_r, void *_priv) { struct pool_con *con = (struct pool_con *)_priv; PGresult *res = NULL; #ifdef EXTRA_DEBUG if (!db_match_async_con(fd, _h)) { LM_BUG("no conn match for fd %d", fd); abort(); } #endif db_switch_to_async(_h, con); if( PQconsumeInput(CON_CONNECTION(_h)) == 0) { LM_ERR("Unable to consume input\n"); db_switch_to_sync(_h); db_store_async_con(_h, con); return -1; } if(PQisBusy(CON_CONNECTION(_h))) { async_status = ASYNC_CONTINUE; db_switch_to_sync(_h); return 1; } while (1) { if ((res = PQgetResult(CON_CONNECTION(_h)))) { CON_RESULT(_h) = res; } else { break; } } if (_r) { if (db_postgres_store_result(_h, _r) != 0) { LM_ERR("failed to store result\n"); db_switch_to_sync(_h); db_store_async_con(_h, con); return -2; } } db_switch_to_sync(_h); db_store_async_con(_h, con); return 0; }
/** * Update some rows in the specified table * \param _h structure representing database connection * \param _k key names * \param _o operators * \param _v values of the keys that must match * \param _uk updated columns * \param _uv updated values of the columns * \param _n number of key=value pairs * \param _un number of columns to update * \return zero on success, negative value on failure */ int db_sqlite_update(const db_con_t* _h, const db_key_t* _k, const db_op_t* _o, const db_val_t* _v, const db_key_t* _uk, const db_val_t* _uv, const int _n, const int _un) { int ret; sqlite3_stmt* stmt; #ifdef SQLITE_BIND db_ps_t ps; CON_SET_CURR_PS(_h, &ps); #else CON_RESET_CURR_PS(_h); #endif ret = db_do_update(_h, _k, _o, _v, _uk, _uv, _n, _un, db_sqlite_val2str, db_sqlite_submit_dummy_query); if (ret != 0) { return ret; } again: ret=sqlite3_prepare_v2(CON_CONNECTION(_h), query_holder.s, query_holder.len, &stmt, NULL); if (ret==SQLITE_BUSY) goto again; if (ret!=SQLITE_OK) LM_ERR("failed to prepare: (%s)\n", sqlite3_errmsg(CON_CONNECTION(_h))); #ifdef SQLITE_BIND if (db_sqlite_bind_values(stmt, _uv, _un) != SQLITE_OK && db_sqlite_bind_values(stmt, _v, _n)) { LM_ERR("failed to bind values\n"); return -1; } #endif again2: ret = sqlite3_step(stmt); if (ret==SQLITE_BUSY) goto again2; if (ret != SQLITE_DONE) { LM_ERR("insert query failed %s\n", sqlite3_errmsg(CON_CONNECTION(_h))); return -1; } sqlite3_finalize(stmt); return 0; }
/* * Delete a row from the specified table * _h: structure representing database connection * _k: key names * _o: operators * _v: values of the keys that must match * _n: number of key=value pairs */ int db_delete(db_con_t* _h, db_key_t* _k, db_op_t* _o, db_val_t* _v, int _n) { int off, ret; if (!_h) { LOG(L_ERR, "db_delete: Invalid parameter value\n"); return -1; } ret = snprintf(sql_buf, SQL_BUF_LEN, "delete from %s", CON_TABLE(_h)); if (ret < 0 || ret >= SQL_BUF_LEN) goto error; off = ret; if (_n) { ret = snprintf(sql_buf + off, SQL_BUF_LEN - off, " where "); if (ret < 0 || ret >= (SQL_BUF_LEN - off)) goto error; off += ret; ret = print_where(CON_CONNECTION(_h), sql_buf + off, SQL_BUF_LEN - off, _k, _o, _v, _n); if (ret < 0) return -1; off += ret; } *(sql_buf + off) = '\0'; if (submit_query(_h, sql_buf) < 0) { LOG(L_ERR, "db_delete: Error while submitting query\n"); return -2; } return 0; error: LOG(L_ERR, "db_delete: Error in snprintf\n"); return -1; }
/* * Send an SQL query to the server */ static int db_mysql_submit_query(db_con_t* _h, const char* _s) { time_t t; int i, code; if ((!_h) || (!_s)) { LM_ERR("invalid parameter value\n"); return -1; } if (ping_interval) { t = time(0); if ((t - CON_TIMESTAMP(_h)) > ping_interval) { if (mysql_ping(CON_CONNECTION(_h))) { LM_DBG("mysql_ping failed\n"); } } CON_TIMESTAMP(_h) = t; } /* screws up the terminal when the query contains a BLOB :-( (by bogdan) * DBG("submit_query(): %s\n", _s); */ /* When a server connection is lost and a query is attempted, most of * the time the query will return a CR_SERVER_LOST, then at the second * attempt to execute it, the mysql lib will reconnect and succeed. * However is a few cases, the first attempt returns CR_SERVER_GONE_ERROR * the second CR_SERVER_LOST and only the third succeeds. * Thus the 3 in the loop count. Increasing the loop count over this * value shouldn't be needed, but it doesn't hurt either, since the loop * will most of the time stop at the second or sometimes at the third * iteration. */ for (i=0; i<(auto_reconnect ? 3 : 1); i++) { if (mysql_query(CON_CONNECTION(_h), _s)==0) { return 0; } code = mysql_errno(CON_CONNECTION(_h)); if (code != CR_SERVER_GONE_ERROR && code != CR_SERVER_LOST) { break; } } LM_ERR("driver error: %s\n", mysql_error(CON_CONNECTION(_h))); return -2; }
/** * Returns the last inserted ID. * \param _h database handle * \return returns the ID as integer or returns 0 if the previous statement * does not use an AUTO_INCREMENT value. */ int db_mysql_last_inserted_id(const db1_con_t* _h) { if (!_h) { LM_ERR("invalid parameter value\n"); return -1; } return mysql_insert_id(CON_CONNECTION(_h)); }
/** * Returns the last inserted ID. * \param _h database handle * \return returns the ID as integer or returns 0 if the previous statement * does not use an AUTO_INCREMENT value. */ int db_last_inserted_id(const db_con_t* _h) { if (!_h) { LM_ERR("invalid parameter value\n"); return -1; } return sqlite3_last_insert_rowid(CON_CONNECTION(_h)); }
/** * Returns the affected rows of the last query. * \param _h database handle * \return returns the affected rows as integer or -1 on error. */ int db_mysql_affected_rows(const db1_con_t* _h) { if (!_h) { LM_ERR("invalid parameter value\n"); return -1; } return (int)mysql_affected_rows(CON_CONNECTION(_h)); }
/** * Execute a raw SQL query. * \param _h handle for the database * \param _s raw query string * \param _r result set for storage * \return zero on success, negative value on failure */ int db_sqlite_raw_query(const db_con_t* _h, const str* _s, db_res_t** _r) { int ret=-1; char* errmsg; str select_str={"select", 6}; CON_RESET_CURR_PS(_h); if (!str_strstr(_s, &select_str)) { /* not a select statement; can execute the query and exit*/ if (sqlite3_exec(CON_CONNECTION(_h), query_holder.s, NULL, NULL, &errmsg)) { LM_ERR("query failed: %s\n", errmsg); return -2; } return 0; } CON_RAW_QUERY(_h) = 1; if (db_copy_rest_of_count(_s, &count_str)) { LM_ERR("failed to build count str!\n"); return -1; } again: ret=sqlite3_prepare_v2(CON_CONNECTION(_h), _s->s, _s->len, &CON_SQLITE_PS(_h), NULL); if (ret==SQLITE_BUSY) goto again; if (ret!=SQLITE_OK) LM_ERR("failed to prepare: (%s)\n", sqlite3_errmsg(CON_CONNECTION(_h))); if (_r) { ret = db_sqlite_store_result(_h, _r, NULL, 0); } else { /* need to fetch now the total number of rows in query * because later won't have the query string */ CON_PS_ROWS(_h) = db_sqlite_get_query_rows(_h, &count_str, NULL, 0); } return ret; }
/* * Retrieve result set */ static int store_result(db_con_t* _h, db_res_t** _r) { if ((!_h) || (!_r)) { LOG(L_ERR, "store_result: Invalid parameter value\n"); return -1; } *_r = new_result(); if (*_r == 0) { LOG(L_ERR, "store_result: No memory left\n"); return -2; } MYRES_RESULT(*_r) = mysql_store_result(CON_CONNECTION(_h)); if (!MYRES_RESULT(*_r)) { if (mysql_field_count(CON_CONNECTION(_h)) == 0) { (*_r)->col.n = 0; (*_r)->n = 0; return 0; } else { LOG(L_ERR, "store_result: %s\n", mysql_error(CON_CONNECTION(_h))); free_result(*_r); *_r = 0; return -3; } } if (convert_result(_h, *_r) < 0) { LOG(L_ERR, "store_result: Error while converting result\n"); mysql_free_result(MYRES_RESULT(*_r)); pkg_free((*_r)->data); pkg_free(*_r); /* This cannot be used because if convert_result fails, * free_result will try to free rows and columns too * and free will be called two times */ /* free_result(*_r); */ return -4; } return 0; }
/* * Query table for specified rows * _h: structure representing database connection * _k: key names * _op: operators * _v: values of the keys that must match * _c: column names to return * _n: number of key=values pairs to compare * _nc: number of columns to return * _o: order by the specified column */ int db_query(db_con_t* _h, db_key_t* _k, db_op_t* _op, db_val_t* _v, db_key_t* _c, int _n, int _nc, db_key_t _o, db_res_t** _r) { int off, ret; if (!_h) { LOG(L_ERR, "db_query: Invalid parameter value\n"); return -1; } if (!_c) { ret = snprintf(sql_buf, SQL_BUF_LEN, "select * from %s ", CON_TABLE(_h)); if (ret < 0 || ret >= SQL_BUF_LEN) goto error; off = ret; } else { ret = snprintf(sql_buf, SQL_BUF_LEN, "select "); if (ret < 0 || ret >= SQL_BUF_LEN) goto error; off = ret; ret = print_columns(sql_buf + off, SQL_BUF_LEN - off, _c, _nc); if (ret < 0) return -1; off += ret; ret = snprintf(sql_buf + off, SQL_BUF_LEN - off, "from %s ", CON_TABLE(_h)); if (ret < 0 || ret >= (SQL_BUF_LEN - off)) goto error; off += ret; } if (_n) { ret = snprintf(sql_buf + off, SQL_BUF_LEN - off, "where "); if (ret < 0 || ret >= (SQL_BUF_LEN - off)) goto error; off += ret; ret = print_where(CON_CONNECTION(_h), sql_buf + off, SQL_BUF_LEN - off, _k, _op, _v, _n); if (ret < 0) return -1;; off += ret; } if (_o) { ret = snprintf(sql_buf + off, SQL_BUF_LEN - off, "order by %s", _o); if (ret < 0 || ret >= (SQL_BUF_LEN - off)) goto error; off += ret; } *(sql_buf + off) = '\0'; if (submit_query(_h, sql_buf) < 0) { LOG(L_ERR, "db_query: Error while submitting query\n"); return -2; } return store_result(_h, _r); error: LOG(L_ERR, "db_query: Error in snprintf\n"); return -1; }
/* * Retrieve result set */ static int db_mysql_store_result(db_con_t* _h, db_res_t** _r) { if ((!_h) || (!_r)) { LM_ERR("invalid parameter value\n"); return -1; } *_r = db_new_result(); if (*_r == 0) { LM_ERR("no memory left\n"); return -2; } CON_RESULT(_h) = mysql_store_result(CON_CONNECTION(_h)); if (!CON_RESULT(_h)) { if (mysql_field_count(CON_CONNECTION(_h)) == 0) { (*_r)->col.n = 0; (*_r)->n = 0; goto done; } else { LM_ERR("driver error: %s\n", mysql_error(CON_CONNECTION(_h))); db_mysql_free_dbresult(*_r); *_r = 0; return -3; } } if (db_mysql_convert_result(_h, *_r) < 0) { LM_ERR("error while converting result\n"); pkg_free(*_r); *_r = 0; /* all mem on openser API side is already freed by * db_mysql_convert_result in case of error, but we also need * to free the mem from the mysql lib side */ mysql_free_result(CON_RESULT(_h)); #if (MYSQL_VERSION_ID >= 40100) while( mysql_next_result( CON_CONNECTION(_h) ) > 0 ) { MYSQL_RES *res = mysql_store_result( CON_CONNECTION(_h) ); mysql_free_result( res ); } #endif CON_RESULT(_h) = 0; return -4; } done: #if (MYSQL_VERSION_ID >= 40100) while( mysql_next_result( CON_CONNECTION(_h) ) > 0 ) { MYSQL_RES *res = mysql_store_result( CON_CONNECTION(_h) ); mysql_free_result( res ); } #endif return 0; }
static int commit_transaction(db_con_t * _h) { PGresult *mr; mr = PQexec(CON_CONNECTION(_h), "COMMIT"); if(!mr || PQresultStatus(mr) != PGRES_COMMAND_OK) { PLOG("commit_transaction", "error"); return -1; } PQclear(mr); return(0); }
/** * Convert rows from mysql to db API representation */ static inline int db_mysql_convert_rows(const db_con_t* _h, db_res_t* _r) { int row; if ((!_h) || (!_r)) { LM_ERR("invalid parameter\n"); return -1; } if (CON_HAS_PS(_h)) { RES_ROW_N(_r) = mysql_stmt_num_rows(CON_PS_STMT(_h)); } else { RES_ROW_N(_r) = mysql_num_rows(CON_RESULT(_h)); } if (!RES_ROW_N(_r)) { LM_DBG("no rows returned from the query\n"); RES_ROWS(_r) = 0; return 0; } if (db_allocate_rows( _r, RES_ROW_N(_r))!=0) { LM_ERR("no private memory left\n"); return -2; } for(row = 0; row < RES_ROW_N(_r); row++) { if (CON_HAS_PS(_h)) { mysql_stmt_fetch(CON_PS_STMT(_h)); //if(mysql_stmt_fetch(CON_PS_STMT(_h))!=1) // LM_ERR("STMT ERR=%s\n",mysql_stmt_error(CON_PS_STMT(_h))); } else { CON_ROW(_h) = mysql_fetch_row(CON_RESULT(_h)); if (!CON_ROW(_h)) { LM_ERR("driver error: %s\n", mysql_error(CON_CONNECTION(_h))); RES_ROW_N(_r) = row; db_free_rows(_r); return -3; } } if (db_mysql_convert_row(_h, _r, &(RES_ROWS(_r)[row])) < 0) { LM_ERR("error while converting row #%d\n", row); RES_ROW_N(_r) = row; db_free_rows(_r); return -4; } } return 0; }
static int disconnect_db(db_con_t* _h) { if(! _h) { DLOG("disconnect_db", "null db_con_t, ignored!\n"); return(0); } /* ** free lingering memory tree if it exists */ if(CON_SQLURL(_h)) { aug_free(CON_SQLURL(_h)); CON_SQLURL(_h) = (char *) 0; } /* ** ignore if there is no current connection */ if(CON_CONNECTED(_h) != 1) { DLOG("disconnect_db", "not connected, ignored!\n"); return 0; } /* ** make sure we are trying to close a connection that was opened ** by our process ID */ if(CON_PID(_h) == getpid()) { PQfinish(CON_CONNECTION(_h)); CON_CONNECTED(_h) = 0; } else { DLOG("disconnect_db", "attempt to release connection not owned, ignored!\n"); } return 0; }
/*! * \brief Convert rows from mysql to db API representation * \param _h database connection * \param _r database result set * \return 0 on success, negative on failure */ static inline int db_mysql_convert_rows(const db1_con_t* _h, db1_res_t* _r) { int row; if ((!_h) || (!_r)) { LM_ERR("invalid parameter\n"); return -1; } RES_ROW_N(_r) = mysql_num_rows(RES_RESULT(_r)); if (!RES_ROW_N(_r)) { LM_DBG("no rows returned from the query\n"); RES_ROWS(_r) = 0; return 0; } if (db_allocate_rows(_r) < 0) { LM_ERR("could not allocate rows"); RES_ROW_N(_r) = 0; return -2; } for(row = 0; row < RES_ROW_N(_r); row++) { RES_ROW(_r) = mysql_fetch_row(RES_RESULT(_r)); if (!RES_ROW(_r)) { LM_ERR("driver error: %s\n", mysql_error(CON_CONNECTION(_h))); RES_ROW_N(_r) = row; db_free_rows(_r); return -3; } if (db_mysql_convert_row(_h, _r, &(RES_ROWS(_r)[row])) < 0) { LM_ERR("error while converting row #%d\n", row); RES_ROW_N(_r) = row; db_free_rows(_r); return -4; } } return 0; }
static inline int db_sqlite_get_query_rows(const db_con_t* _h, const str* query, const db_val_t* _v, const int _n) { int ret; sqlite3_stmt* stmt; again: ret=sqlite3_prepare_v2(CON_CONNECTION(_h), query->s, query->len, &stmt, NULL); if (ret == SQLITE_BUSY) goto again; if (ret != SQLITE_OK) { LM_ERR("failed to prepare query\n"); return -1; } #ifdef SQLITE_BIND if (db_sqlite_bind_values(stmt, _v, _n) != SQLITE_OK) { LM_ERR("failed to bind values\n"); return -1; } #endif again2: ret=sqlite3_step(stmt); if (ret == SQLITE_BUSY) goto again2; if (ret != SQLITE_ROW) { LM_ERR("failed to fetch query size\n"); return -1; } ret=sqlite3_column_int(stmt, 0); sqlite3_finalize(stmt); return ret; }
/* * Just like insert, but replace the row if it exists */ int db_replace(db_con_t* handle, db_key_t* keys, db_val_t* vals, int n) { int off, ret; if (!handle || !keys || !vals) { LOG(L_ERR, "db_replace: Invalid parameter value\n"); return -1; } ret = snprintf(sql_buf, SQL_BUF_LEN, "replace %s (", CON_TABLE(handle)); if (ret < 0 || ret >= SQL_BUF_LEN) goto error; off = ret; ret = print_columns(sql_buf + off, SQL_BUF_LEN - off, keys, n); if (ret < 0) return -1; off += ret; ret = snprintf(sql_buf + off, SQL_BUF_LEN - off, ") values ("); if (ret < 0 || ret >= (SQL_BUF_LEN - off)) goto error; off += ret; ret = print_values(CON_CONNECTION(handle), sql_buf + off, SQL_BUF_LEN - off, vals, n); if (ret < 0) return -1; off += ret; *(sql_buf + off++) = ')'; *(sql_buf + off) = '\0'; if (submit_query(handle, sql_buf) < 0) { LOG(L_ERR, "db_replace: Error while submitting query\n"); return -2; } return 0; error: LOG(L_ERR, "db_replace: Error in snprintf\n"); return -1; }
/* * Convert rows from mysql to db API representation */ static inline int db_mysql_convert_rows(db_con_t* _h, db_res_t* _r) { int n, i; if ((!_h) || (!_r)) { LM_ERR("invalid parameter\n"); return -1; } n = mysql_num_rows(CON_RESULT(_h)); RES_ROW_N(_r) = n; if (!n) { RES_ROWS(_r) = 0; return 0; } RES_ROWS(_r) = (struct db_row*)pkg_malloc(sizeof(db_row_t) * n); if (!RES_ROWS(_r)) { LM_ERR("no private memory left\n"); return -2; } for(i = 0; i < n; i++) { CON_ROW(_h) = mysql_fetch_row(CON_RESULT(_h)); if (!CON_ROW(_h)) { LM_ERR("driver error: %s\n", mysql_error(CON_CONNECTION(_h))); RES_ROW_N(_r) = i; db_free_rows(_r); return -3; } if (db_mysql_convert_row(_h, _r, &(RES_ROWS(_r)[i])) < 0) { LM_ERR("error while converting row #%d\n", i); RES_ROW_N(_r) = i; db_free_rows(_r); return -4; } } return 0; }
/* * Insert a row into specified table * _h: structure representing database connection * _k: key names * _v: values of the keys * _n: number of key=value pairs */ int db_insert(db_con_t* _h, db_key_t* _k, db_val_t* _v, int _n) { int off, ret; if ((!_h) || (!_k) || (!_v) || (!_n)) { LOG(L_ERR, "db_insert: Invalid parameter value\n"); return -1; } ret = snprintf(sql_buf, SQL_BUF_LEN, "insert into %s (", CON_TABLE(_h)); if (ret < 0 || ret >= SQL_BUF_LEN) goto error; off = ret; ret = print_columns(sql_buf + off, SQL_BUF_LEN - off, _k, _n); if (ret < 0) return -1; off += ret; ret = snprintf(sql_buf + off, SQL_BUF_LEN - off, ") values ("); if (ret < 0 || ret >= (SQL_BUF_LEN - off)) goto error; off += ret; ret = print_values(CON_CONNECTION(_h), sql_buf + off, SQL_BUF_LEN - off, _v, _n); if (ret < 0) return -1; off += ret; *(sql_buf + off++) = ')'; *(sql_buf + off) = '\0'; if (submit_query(_h, sql_buf) < 0) { LOG(L_ERR, "db_insert: Error while submitting query\n"); return -2; } return 0; error: LOG(L_ERR, "db_insert: Error in snprintf\n"); return -1; }
/* * Reconnect if connection is broken */ static int reconnect(const db1_con_t* _h) { int ret = 0; SQLCHAR outstr[1024]; SQLSMALLINT outstrlen; char conn_str[MAX_CONN_STR_LEN]; LM_ERR("Attempting DB reconnect\n"); /* Disconnect */ SQLDisconnect (CON_CONNECTION(_h)); /* Reconnect */ if (!db_unixodbc_build_conn_str(CON_ID(_h), conn_str)) { LM_ERR("failed to build connection string\n"); return ret; } ret = SQLDriverConnect(CON_CONNECTION(_h), (void *)1, (SQLCHAR*)conn_str, SQL_NTS, outstr, sizeof(outstr), &outstrlen, SQL_DRIVER_COMPLETE); if (!SQL_SUCCEEDED(ret)) { LM_ERR("failed to connect\n"); db_unixodbc_extract_error("SQLDriverConnect", CON_CONNECTION(_h), SQL_HANDLE_DBC, NULL); return ret; } ret = SQLAllocHandle(SQL_HANDLE_STMT, CON_CONNECTION(_h), &CON_RESULT(_h)); if (!SQL_SUCCEEDED(ret)) { LM_ERR("Statement allocation error %d\n", (int)(long)CON_CONNECTION(_h)); db_unixodbc_extract_error("SQLAllocStmt", CON_CONNECTION(_h), SQL_HANDLE_DBC,NULL); return ret; } return ret; }
/* * Used when converting result from a query */ int db_postgres_val2str(const db_con_t* _con, const db_val_t* _v, char* _s, int* _len) { int l, ret; int pgret; char *tmp_s; size_t tmp_len; char* old_s; if ((!_v) || (!_s) || (!_len) || (!*_len)) { LM_ERR("invalid parameter value\n"); return -1; } if (VAL_NULL(_v)) { if ( *_len < (l=(int)sizeof("NULL")-1)) { LM_ERR("buffer too short to print NULL\n"); return -1; } memcpy(_s, "NULL", l); *_len = l; return 0; } switch(VAL_TYPE(_v)) { case DB_INT: if (db_int2str(VAL_INT(_v), _s, _len) < 0) { LM_ERR("failed to convert string to int\n"); return -2; } else { return 0; } break; case DB_BIGINT: if (db_bigint2str(VAL_BIGINT(_v), _s, _len) < 0) { LM_ERR("failed to convert string to big int\n"); return -2; } else { return 0; } break; case DB_BITMAP: if (db_int2str(VAL_BITMAP(_v), _s, _len) < 0) { LM_ERR("failed to convert string to int\n"); return -3; } else { return 0; } break; case DB_DOUBLE: if (db_double2str(VAL_DOUBLE(_v), _s, _len) < 0) { LM_ERR("failed to convert string to double\n"); return -3; } else { return 0; } break; case DB_STRING: l = strlen(VAL_STRING(_v)); if (*_len < (l * 2 + 3)) { LM_ERR("destination STRING buffer too short (have %d, need %d)\n", *_len, l * 2 + 3); return -4; } else { old_s = _s; *_s++ = '\''; ret = PQescapeStringConn(CON_CONNECTION(_con), _s, VAL_STRING(_v), l, &pgret); if(pgret!=0) { LM_ERR("PQescapeStringConn failed\n"); return -4; } LM_DBG("PQescapeStringConn: in: %d chars," " out: %d chars\n", l, ret); _s += ret; *_s++ = '\''; *_s = '\0'; /* FIXME */ *_len = _s - old_s; return 0; } break; case DB_STR: l = VAL_STR(_v).len; if (*_len < (l * 2 + 3)) { LM_ERR("destination STR buffer too short (have %d, need %d)\n", *_len, l * 2 + 3); return -5; } else { old_s = _s; *_s++ = '\''; ret = PQescapeStringConn(CON_CONNECTION(_con), _s, VAL_STRING(_v), l, &pgret); if(pgret!=0) { LM_ERR("PQescapeStringConn failed \n"); return -5; } LM_DBG("PQescapeStringConn: in: %d chars, out: %d chars\n", l, ret); _s += ret; *_s++ = '\''; *_s = '\0'; /* FIXME */ *_len = _s - old_s; return 0; } break; case DB_DATETIME: if (db_time2str(VAL_TIME(_v), _s, _len) < 0) { LM_ERR("failed to convert string to time_t\n"); return -6; } else { return 0; } break; case DB_BLOB: l = VAL_BLOB(_v).len; /* this estimation is not always correct, thus we need to check later again */ if (*_len < (l * 2 + 3)) { LM_ERR("destination BLOB buffer too short (have %d, need %d)\n", *_len, l * 2 + 3); return -7; } else { *_s++ = '\''; tmp_s = (char*)PQescapeByteaConn(CON_CONNECTION(_con), (unsigned char*)VAL_STRING(_v), (size_t)l, (size_t*)&tmp_len); if(tmp_s==NULL) { LM_ERR("PQescapeBytea failed\n"); return -7; } if (tmp_len > *_len) { LM_ERR("escaped result too long\n"); return -7; } memcpy(_s, tmp_s, tmp_len); PQfreemem(tmp_s); tmp_len = strlen(_s); *(_s + tmp_len) = '\''; *(_s + tmp_len + 1) = '\0'; *_len = tmp_len + 2; return 0; } break; default: LM_DBG("unknown data type\n"); return -7; } }
/*! * \brief Get and convert columns from a result * * Get and convert columns from a result, fills the result structure * with data from the database. * \param _h database connection * \param _r database result set * \return 0 on success, negative on failure */ int db_mysql_get_columns(const db1_con_t* _h, db1_res_t* _r) { int col; MYSQL_FIELD* fields; if ((!_h) || (!_r)) { LM_ERR("invalid parameter\n"); return -1; } RES_COL_N(_r) = mysql_field_count(CON_CONNECTION(_h)); if (!RES_COL_N(_r)) { LM_ERR("no columns returned from the query\n"); return -2; } else { LM_DBG("%d columns returned from the query\n", RES_COL_N(_r)); } if (db_allocate_columns(_r, RES_COL_N(_r)) != 0) { RES_COL_N(_r) = 0; LM_ERR("could not allocate columns\n"); return -3; } fields = mysql_fetch_fields(RES_RESULT(_r)); for(col = 0; col < RES_COL_N(_r); col++) { RES_NAMES(_r)[col] = (str*)pkg_malloc(sizeof(str)); if (! RES_NAMES(_r)[col]) { LM_ERR("no private memory left\n"); db_free_columns(_r); return -4; } LM_DBG("allocate %lu bytes for RES_NAMES[%d] at %p\n", (unsigned long)sizeof(str), col, RES_NAMES(_r)[col]); /* The pointer that is here returned is part of the result structure. */ RES_NAMES(_r)[col]->s = fields[col].name; RES_NAMES(_r)[col]->len = strlen(fields[col].name); LM_DBG("RES_NAMES(%p)[%d]=[%.*s]\n", RES_NAMES(_r)[col], col, RES_NAMES(_r)[col]->len, RES_NAMES(_r)[col]->s); switch(fields[col].type) { case MYSQL_TYPE_TINY: case MYSQL_TYPE_SHORT: case MYSQL_TYPE_LONG: case MYSQL_TYPE_INT24: case MYSQL_TYPE_TIMESTAMP: LM_DBG("use DB1_INT result type\n"); RES_TYPES(_r)[col] = DB1_INT; break; case MYSQL_TYPE_LONGLONG: LM_DBG("use DB1_BIGINT result type\n"); RES_TYPES(_r)[col] = DB1_BIGINT; break; case MYSQL_TYPE_FLOAT: case MYSQL_TYPE_DOUBLE: LM_DBG("use DB1_DOUBLE result type\n"); RES_TYPES(_r)[col] = DB1_DOUBLE; break; case MYSQL_TYPE_DATETIME: LM_DBG("use DB1_DATETIME result type\n"); RES_TYPES(_r)[col] = DB1_DATETIME; break; case MYSQL_TYPE_BLOB: LM_DBG("use DB1_BLOB result type\n"); RES_TYPES(_r)[col] = DB1_BLOB; break; case FIELD_TYPE_SET: LM_DBG("use DB1_BITMAP result type\n"); RES_TYPES(_r)[col] = DB1_BITMAP; break; case MYSQL_TYPE_DECIMAL: #if MYSQL_VERSION_ID > 49999 case MYSQL_TYPE_NEWDECIMAL: #endif case MYSQL_TYPE_STRING: case MYSQL_TYPE_VAR_STRING: LM_DBG("use DB1_STRING result type\n"); RES_TYPES(_r)[col] = DB1_STRING; break; default: LM_WARN("unhandled data type column (%.*s) type id (%d), " "use DB1_STRING as default\n", RES_NAMES(_r)[col]->len, RES_NAMES(_r)[col]->s, fields[col].type); RES_TYPES(_r)[col] = DB1_STRING; break; } } return 0; }
/** * Execute a raw SQL query. * \param _h handle for the database * \param _s raw query string * \param _r result set for storage * \return zero on success, negative value on failure */ int db_sqlite_raw_query(const db_con_t* _h, const str* _s, db_res_t** _r) { static char sql_str[SQL_BUF_LEN]; int ret=-1, i=0; char* errmsg; str select_str={"select", 6}; str _scpy; CON_RESET_CURR_PS(_h); while (i < _s->len && !isalpha(_s->s[i])) i++; /* if any blank spaces or anything else before the actual query */ if (i) { _scpy.s = _s->s+i; _scpy.len = _s->len-i; } else { _scpy = *_s; } if (_scpy.len >= select_str.len && str_strncasecmp(&_scpy, &select_str, select_str.len)) { /* not a select statement; can execute the query and exit*/ if (_s->len + 1 > SQL_BUF_LEN) { LM_ERR("query too big! try reducing the size of your query!" "Current max size [%d]!\n", SQL_BUF_LEN); return -1; } memcpy(sql_str, _s->s, _s->len); sql_str[_s->len] = '\0'; if (sqlite3_exec(CON_CONNECTION(_h), sql_str, NULL, NULL, &errmsg)) { LM_ERR("query failed: %s\n", errmsg); return -2; } return 0; } CON_RAW_QUERY(_h) = 1; if (db_copy_rest_of_count(&_scpy, &count_str)) { LM_ERR("failed to build count str!\n"); return -1; } again: ret=sqlite3_prepare_v2(CON_CONNECTION(_h), _s->s, _s->len, &CON_SQLITE_PS(_h), NULL); if (ret==SQLITE_BUSY) goto again; if (ret!=SQLITE_OK) LM_ERR("failed to prepare: (%s)\n", sqlite3_errmsg(CON_CONNECTION(_h))); if (_r) { ret = db_sqlite_store_result(_h, _r, NULL, 0); } else { /* need to fetch now the total number of rows in query * because later won't have the query string */ CON_PS_ROWS(_h) = db_sqlite_get_query_rows(_h, &count_str, NULL, 0); } return ret; }
/** * Get and convert columns from a result */ int db_mysql_get_columns(const db_con_t* _h, db_res_t* _r) { int col; MYSQL_FIELD* fields; if ((!_h) || (!_r)) { LM_ERR("invalid parameter\n"); return -1; } if (CON_HAS_PS(_h)) { RES_COL_N(_r) = CON_MYSQL_PS(_h)->cols_out; } else { RES_COL_N(_r) = mysql_field_count(CON_CONNECTION(_h)); } if (!RES_COL_N(_r)) { LM_ERR("no columns returned from the query\n"); return -2; } else { LM_DBG("%d columns returned from the query\n", RES_COL_N(_r)); } if (db_allocate_columns(_r, RES_COL_N(_r)) != 0) { LM_ERR("could not allocate columns\n"); return -3; } fields = mysql_fetch_fields(CON_RESULT(_h)); for(col = 0; col < RES_COL_N(_r); col++) { /* The pointer that is here returned is part of the result structure */ RES_NAMES(_r)[col]->s = fields[col].name; RES_NAMES(_r)[col]->len = strlen(fields[col].name); LM_DBG("RES_NAMES(%p)[%d]=[%.*s]\n", RES_NAMES(_r)[col], col, RES_NAMES(_r)[col]->len, RES_NAMES(_r)[col]->s); switch(fields[col].type) { case MYSQL_TYPE_TINY: case MYSQL_TYPE_SHORT: case MYSQL_TYPE_LONG: case MYSQL_TYPE_INT24: case MYSQL_TYPE_DECIMAL: #if MYSQL_VERSION_ID > 49999 case MYSQL_TYPE_NEWDECIMAL: #endif case MYSQL_TYPE_TIMESTAMP: LM_DBG("use DB_INT result type\n"); RES_TYPES(_r)[col] = DB_INT; break; case MYSQL_TYPE_FLOAT: case MYSQL_TYPE_DOUBLE: LM_DBG("use DB_DOUBLE result type\n"); RES_TYPES(_r)[col] = DB_DOUBLE; break; case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_DATE: LM_DBG("use DB_DATETIME result type\n"); RES_TYPES(_r)[col] = DB_DATETIME; break; case MYSQL_TYPE_TINY_BLOB: case MYSQL_TYPE_MEDIUM_BLOB: case MYSQL_TYPE_LONG_BLOB: case MYSQL_TYPE_BLOB: LM_DBG("use DB_BLOB result type\n"); RES_TYPES(_r)[col] = DB_BLOB; break; case FIELD_TYPE_SET: LM_DBG("use DB_BITMAP result type\n"); RES_TYPES(_r)[col] = DB_BITMAP; break; case MYSQL_TYPE_STRING: case MYSQL_TYPE_VAR_STRING: LM_DBG("use DB_STRING result type\n"); RES_TYPES(_r)[col] = DB_STRING; break; case MYSQL_TYPE_LONGLONG: LM_DBG("use DB_BIGINT result type\n"); RES_TYPES(_r)[col] = DB_BIGINT; break; default: LM_WARN("unhandled data type column (%.*s) type id (%d), " "use DB_STRING as default\n", RES_NAMES(_r)[col]->len, RES_NAMES(_r)[col]->s, fields[col].type); RES_TYPES(_r)[col] = DB_STRING; break; } } return 0; }
/** * Insert a row into a specified table, update on duplicate key. * \param _h structure representing database connection * \param _k key names * \param _v values of the keys * \param _n number of key=value pairs */ int db_insert_update(const db_con_t* _h, const db_key_t* _k, const db_val_t* _v, const int _n) { #define SQL_BUF_LEN 65536 int off, ret; static str sql_str; static char sql_buf[SQL_BUF_LEN]; sqlite3_stmt* stmt; if ((!_h) || (!_k) || (!_v) || (!_n)) { LM_ERR("invalid parameter value\n"); return -1; } #ifdef SQLITE_BIND db_ps_t ps; CON_SET_CURR_PS(_h, &ps); #endif ret = snprintf(sql_buf, SQL_BUF_LEN, "insert into %.*s (", CON_TABLE(_h)->len, CON_TABLE(_h)->s); if (ret < 0 || ret >= SQL_BUF_LEN) goto error; off = ret; ret = db_print_columns(sql_buf + off, SQL_BUF_LEN - off, _k, _n); if (ret < 0) return -1; off += ret; ret = snprintf(sql_buf + off, SQL_BUF_LEN - off, ") values ("); if (ret < 0 || ret >= (SQL_BUF_LEN - off)) goto error; off += ret; ret = db_print_values(_h, sql_buf + off, SQL_BUF_LEN - off, _v, _n, db_sqlite_val2str); if (ret < 0) return -1; off += ret; *(sql_buf + off++) = ')'; ret = snprintf(sql_buf + off, SQL_BUF_LEN - off, " on duplicate key update "); if (ret < 0 || ret >= (SQL_BUF_LEN - off)) goto error; off += ret; ret = db_print_set(_h, sql_buf + off, SQL_BUF_LEN - off, _k, _v, _n, db_sqlite_val2str); if (ret < 0) return -1; off += ret; sql_str.s = sql_buf; sql_str.len = off; again: ret=sqlite3_prepare_v2(CON_CONNECTION(_h), sql_str.s, sql_str.len, &stmt, NULL); if (ret==SQLITE_BUSY) goto again; if (ret!=SQLITE_OK) LM_ERR("failed to prepare: (%s)\n", sqlite3_errmsg(CON_CONNECTION(_h))); #ifdef SQLITE_BIND if (db_sqlite_bind_values(stmt, _v, _n) != SQLITE_OK) { LM_ERR("failed to bind values\n"); return -1; } #endif again2: ret = sqlite3_step(stmt); if (ret==SQLITE_BUSY) goto again2; if (ret != SQLITE_DONE) { LM_ERR("insert query failed %s\n", sqlite3_errmsg(CON_CONNECTION(_h))); return -1; } sqlite3_finalize(stmt); return 0; #undef SQL_BUF_LEN error: LM_ERR("error while preparing insert_update operation\n"); return -1; }
/* * Get and convert columns from a result */ int db_mysql_get_columns(db_con_t* _h, db_res_t* _r) { int n, i; MYSQL_FIELD* fields; if ((!_h) || (!_r)) { LM_ERR("invalid parameter\n"); return -1; } n = mysql_field_count(CON_CONNECTION(_h)); if (!n) { LM_ERR("no columns\n"); return -2; } RES_NAMES(_r) = (db_key_t*)pkg_malloc(sizeof(db_key_t) * n); if (!RES_NAMES(_r)) { LM_ERR("no private memory left\n"); return -3; } RES_TYPES(_r) = (db_type_t*)pkg_malloc(sizeof(db_type_t) * n); if (!RES_TYPES(_r)) { LM_ERR("no private memory left\n"); pkg_free(RES_NAMES(_r)); return -4; } RES_COL_N(_r) = n; fields = mysql_fetch_fields(CON_RESULT(_h)); for(i = 0; i < n; i++) { RES_NAMES(_r)[i] = fields[i].name; switch(fields[i].type) { case FIELD_TYPE_TINY: case FIELD_TYPE_SHORT: case FIELD_TYPE_LONG: case FIELD_TYPE_INT24: case FIELD_TYPE_LONGLONG: case FIELD_TYPE_DECIMAL: case FIELD_TYPE_TIMESTAMP: RES_TYPES(_r)[i] = DB_INT; break; case FIELD_TYPE_FLOAT: case FIELD_TYPE_DOUBLE: RES_TYPES(_r)[i] = DB_DOUBLE; break; case FIELD_TYPE_DATETIME: RES_TYPES(_r)[i] = DB_DATETIME; break; case FIELD_TYPE_BLOB: case FIELD_TYPE_TINY_BLOB: case FIELD_TYPE_MEDIUM_BLOB: case FIELD_TYPE_LONG_BLOB: RES_TYPES(_r)[i] = DB_BLOB; break; case FIELD_TYPE_SET: RES_TYPES(_r)[i] = DB_BITMAP; break; default: RES_TYPES(_r)[i] = DB_STRING; break; } } return 0; }