| 40 | static char sql_buf[SQL_BUF_LEN]; |
| 41 | |
| 42 | int db_do_query(const db_con_t* _h, const db_key_t* _k, const db_op_t* _op, |
| 43 | const db_val_t* _v, const db_key_t* _c, const int _n, const int _nc, |
| 44 | const db_key_t _o, db_res_t** _r, int (*val2str) (const db_con_t*, |
| 45 | const db_val_t*, char*, int* _len), int (*submit_query)(const db_con_t*, |
| 46 | const str*), int (*store_result)(const db_con_t* _h, db_res_t** _r)) |
| 47 | { |
| 48 | int off, ret; |
| 49 | |
| 50 | if (!_h || !val2str || !submit_query || (_r && !store_result)) { |
| 51 | LM_ERR("invalid parameter value\n"); |
| 52 | goto err_exit; |
| 53 | } |
| 54 | |
| 55 | if (!_c) { |
| 56 | ret = snprintf(sql_buf, SQL_BUF_LEN, "select * from %.*s ", CON_TABLE(_h)->len, CON_TABLE(_h)->s); |
| 57 | if (ret < 0 || ret >= SQL_BUF_LEN) goto error; |
| 58 | off = ret; |
| 59 | } else { |
| 60 | ret = snprintf(sql_buf, SQL_BUF_LEN, "select "); |
| 61 | if (ret < 0 || ret >= SQL_BUF_LEN) goto error; |
| 62 | off = ret; |
| 63 | |
| 64 | ret = db_print_columns(sql_buf + off, SQL_BUF_LEN - off, _c, _nc); |
| 65 | if (ret < 0) goto err_exit; |
| 66 | off += ret; |
| 67 | |
| 68 | ret = snprintf(sql_buf + off, SQL_BUF_LEN - off, "from %.*s ", CON_TABLE(_h)->len, CON_TABLE(_h)->s); |
| 69 | if (ret < 0 || ret >= (SQL_BUF_LEN - off)) goto error; |
| 70 | off += ret; |
| 71 | } |
| 72 | if (_n) { |
| 73 | ret = snprintf(sql_buf + off, SQL_BUF_LEN - off, "where "); |
| 74 | if (ret < 0 || ret >= (SQL_BUF_LEN - off)) goto error; |
| 75 | off += ret; |
| 76 | |
| 77 | ret = db_print_where(_h, sql_buf + off, |
| 78 | SQL_BUF_LEN - off, _k, _op, _v, _n, val2str); |
| 79 | if (ret < 0) goto err_exit; |
| 80 | off += ret; |
| 81 | } |
| 82 | if (_o) { |
| 83 | ret = snprintf(sql_buf + off, SQL_BUF_LEN - off, " order by %.*s", _o->len, _o->s); |
| 84 | if (ret < 0 || ret >= (SQL_BUF_LEN - off)) goto error; |
| 85 | off += ret; |
| 86 | } |
| 87 | /* |
| 88 | * Null-terminate the string for the postgres driver. Its query function |
| 89 | * don't support a length parameter, so they need this for the correct |
| 90 | * function of strlen. This zero is not included in the 'str' length. |
| 91 | * We need to check the length here, otherwise we could overwrite the buffer |
| 92 | * boundaries if off is equal to SQL_BUF_LEN. |
| 93 | */ |
| 94 | if (off + 1 >= SQL_BUF_LEN) goto error; |
| 95 | sql_buf[off + 1] = '\0'; |
| 96 | sql_str.s = sql_buf; |
| 97 | sql_str.len = off; |
| 98 | |
| 99 | if (submit_query(_h, &sql_str) < 0) { |
no test coverage detected