Asterisk - The Open Source Telephony Project  GIT-master-09303e8
Data Structures | Macros | Enumerations | Functions
res_odbc.h File Reference

ODBC resource manager. More...

#include <sql.h>
#include <sqlext.h>
#include <sqltypes.h>
#include "asterisk/linkedlists.h"
#include "asterisk/strings.h"

Go to the source code of this file.

Data Structures

struct  odbc_cache_tables::_columns
 
struct  odbc_cache_columns
 These structures are used for adaptive capabilities. More...
 
struct  odbc_cache_tables
 
struct  odbc_obj
 ODBC container. More...
 

Macros

#define ast_odbc_release_table(ptr)   if (ptr) { AST_RWLIST_UNLOCK(&(ptr)->columns); }
 Release a table returned from ast_odbc_find_table. More...
 
#define ast_odbc_request_obj(a, b)   _ast_odbc_request_obj(a, b, __FILE__, __PRETTY_FUNCTION__, __LINE__)
 
#define ast_odbc_request_obj2(a, b)   _ast_odbc_request_obj2(a, b, __FILE__, __PRETTY_FUNCTION__, __LINE__)
 

Enumerations

enum  { RES_ODBC_SANITY_CHECK = (1 << 0), RES_ODBC_INDEPENDENT_CONNECTION = (1 << 1), RES_ODBC_CONNECTED = (1 << 2) }
 Flags for use with. More...
 
enum  odbc_status { ODBC_SUCCESS =0, ODBC_FAIL =-1 }
 

Functions

struct odbc_obj_ast_odbc_request_obj (const char *name, int check, const char *file, const char *function, int lineno)
 Get a ODBC connection object. More...
 
struct odbc_obj_ast_odbc_request_obj2 (const char *name, struct ast_flags flags, const char *file, const char *function, int lineno)
 Retrieves a connected ODBC object. More...
 
SQLRETURN ast_odbc_ast_str_SQLGetData (struct ast_str **buf, int pmaxlen, SQLHSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLSMALLINT TargetType, SQLLEN *StrLen_or_Ind)
 Wrapper for SQLGetData to use with dynamic strings. More...
 
int ast_odbc_backslash_is_escape (struct odbc_obj *obj)
 Checks if the database natively supports backslash as an escape character. More...
 
unsigned int ast_odbc_class_get_forcecommit (struct odbc_class *class)
 Get the transaction forcecommit setting for an ODBC class. More...
 
unsigned int ast_odbc_class_get_isolation (struct odbc_class *class)
 Get the transaction isolation setting for an ODBC class. More...
 
const char * ast_odbc_class_get_name (struct odbc_class *class)
 Get the name of an ODBC class. More...
 
int ast_odbc_clear_cache (const char *database, const char *tablename)
 Remove a cache entry from memory This function may be called to clear entries created and cached by the ast_odbc_find_table() API call. More...
 
SQLHSTMT ast_odbc_direct_execute (struct odbc_obj *obj, SQLHSTMT(*exec_cb)(struct odbc_obj *obj, void *data), void *data)
 Executes an non prepared statement and returns the resulting statement handle. More...
 
SQLRETURN ast_odbc_execute_sql (struct odbc_obj *obj, SQLHSTMT *stmt, const char *sql)
 Execute a nonprepared SQL query. More...
 
struct odbc_cache_columnsast_odbc_find_column (struct odbc_cache_tables *table, const char *colname)
 Find a column entry within a cached table structure. More...
 
struct odbc_cache_tablesast_odbc_find_table (const char *database, const char *tablename)
 Find or create an entry describing the table specified. More...
 
unsigned int ast_odbc_get_max_connections (const char *name)
 Return the current configured maximum number of connections for a class. More...
 
const char * ast_odbc_isolation2text (int iso)
 Convert from numeric transaction isolation values to their textual counterparts. More...
 
int ast_odbc_prepare (struct odbc_obj *obj, SQLHSTMT *stmt, const char *sql)
 Prepares a SQL query on a statement. More...
 
SQLHSTMT ast_odbc_prepare_and_execute (struct odbc_obj *obj, SQLHSTMT(*prepare_cb)(struct odbc_obj *obj, void *data), void *data)
 Prepares, executes, and returns the resulting statement handle. More...
 
struct ast_strast_odbc_print_errors (SQLSMALLINT handle_type, SQLHANDLE handle, const char *operation)
 Shortcut for printing errors to logs after a failed SQL operation. More...
 
void ast_odbc_release_obj (struct odbc_obj *obj)
 Releases an ODBC object previously allocated by ast_odbc_request_obj() More...
 
int ast_odbc_sanity_check (struct odbc_obj *obj)
 Checks an ODBC object to ensure it is still connected. More...
 
int ast_odbc_smart_execute (struct odbc_obj *obj, SQLHSTMT stmt)
 Executes a prepared statement handle. More...
 
int ast_odbc_text2isolation (const char *txt)
 Convert from textual transaction isolation values to their numeric constants. More...
 

Detailed Description

ODBC resource manager.

Definition in file res_odbc.h.

Macro Definition Documentation

◆ ast_odbc_release_table

#define ast_odbc_release_table (   ptr)    if (ptr) { AST_RWLIST_UNLOCK(&(ptr)->columns); }

Release a table returned from ast_odbc_find_table.

Definition at line 216 of file res_odbc.h.

Referenced by update2_odbc(), and update_odbc().

◆ ast_odbc_request_obj

#define ast_odbc_request_obj (   a,
  b 
)    _ast_odbc_request_obj(a, b, __FILE__, __PRETTY_FUNCTION__, __LINE__)

◆ ast_odbc_request_obj2

#define ast_odbc_request_obj2 (   a,
  b 
)    _ast_odbc_request_obj2(a, b, __FILE__, __PRETTY_FUNCTION__, __LINE__)

Enumeration Type Documentation

◆ anonymous enum

anonymous enum

Flags for use with.

See also
ast_odbc_request_obj2
Enumerator
RES_ODBC_SANITY_CHECK 
RES_ODBC_INDEPENDENT_CONNECTION 
RES_ODBC_CONNECTED 

Definition at line 39 of file res_odbc.h.

◆ odbc_status

Enumerator
ODBC_SUCCESS 
ODBC_FAIL 

Definition at line 36 of file res_odbc.h.

Function Documentation

◆ _ast_odbc_request_obj()

struct odbc_obj* _ast_odbc_request_obj ( const char *  name,
int  check,
const char *  file,
const char *  function,
int  lineno 
)

Get a ODBC connection object.

The "check" parameter is leftover from an earlier implementation where database connections were cached by res_odbc. Since connections are managed by unixODBC now, this parameter is only kept around for API compatibility.

Parameters
nameThe name of the res_odbc.conf section describing the database to connect to
checkunused
Returns
A connection to the database. Call ast_odbc_release_obj() when finished.

Definition at line 984 of file res_odbc.c.

References _ast_odbc_request_obj2(), and RES_ODBC_SANITY_CHECK.

985 {
986  struct ast_flags flags = { check ? RES_ODBC_SANITY_CHECK : 0 };
987  /* XXX New flow means that the "check" parameter doesn't do anything. We're requesting
988  * a connection from ODBC. We'll either get a new one, which obviously is already connected, or
989  * we'll get one from the ODBC connection pool. In that case, it will ensure to only give us a
990  * live connection
991  */
992  return _ast_odbc_request_obj2(name, flags, file, function, lineno);
993 }
unsigned int flags
Definition: utils.h:200
struct odbc_obj * _ast_odbc_request_obj2(const char *name, struct ast_flags flags, const char *file, const char *function, int lineno)
Retrieves a connected ODBC object.
Definition: res_odbc.c:917
static const char name[]
Definition: cdr_mysql.c:74
Structure used to handle boolean flags.
Definition: utils.h:199

◆ _ast_odbc_request_obj2()

struct odbc_obj* _ast_odbc_request_obj2 ( const char *  name,
struct ast_flags  flags,
const char *  file,
const char *  function,
int  lineno 
)

Retrieves a connected ODBC object.

Deprecated:

This is only around for backwards-compatibility with older versions of Asterisk.

Definition at line 917 of file res_odbc.c.

References ao2_alloc, ao2_bump, ao2_callback, ao2_ref, aoro2_class_cb(), ast_cond_wait, ast_debug, AST_LIST_REMOVE_HEAD, ast_mutex_lock, ast_mutex_unlock, connection_dead(), odbc_class::list, NULL, ODBC_FAIL, odbc_obj_connect(), odbc_obj_destructor(), and odbc_obj::parent.

Referenced by _ast_odbc_request_obj().

918 {
919  struct odbc_obj *obj = NULL;
920  struct odbc_class *class;
921 
922  if (!(class = ao2_callback(class_container, 0, aoro2_class_cb, (char *) name))) {
923  ast_debug(1, "Class '%s' not found!\n", name);
924  return NULL;
925  }
926 
927  ast_mutex_lock(&class->lock);
928 
929  while (!obj) {
930  obj = AST_LIST_REMOVE_HEAD(&class->connections, list);
931 
932  if (!obj) {
933  if (class->connection_cnt < class->maxconnections) {
934  /* If no connection is immediately available establish a new
935  * one if allowed. If we try and fail we give up completely as
936  * we could go into an infinite loop otherwise.
937  */
938  obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
939  if (!obj) {
940  break;
941  }
942 
943  obj->parent = ao2_bump(class);
944  if (odbc_obj_connect(obj) == ODBC_FAIL) {
945  ao2_ref(obj->parent, -1);
946  ao2_ref(obj, -1);
947  obj = NULL;
948  break;
949  }
950 
951  class->connection_cnt++;
952  ast_debug(2, "Created ODBC handle %p on class '%s', new count is %zd\n", obj,
953  name, class->connection_cnt);
954  } else {
955  /* Otherwise if we're not allowed to create a new one we
956  * wait for another thread to give up the connection they
957  * own.
958  */
959  ast_cond_wait(&class->cond, &class->lock);
960  }
961  } else if (connection_dead(obj, class)) {
962  /* If the connection is dead try to grab another functional one from the
963  * pool instead of trying to resurrect this one.
964  */
965  ao2_ref(obj, -1);
966  obj = NULL;
967  class->connection_cnt--;
968  ast_debug(2, "ODBC handle %p dead - removing from class '%s', new count is %zd\n",
969  obj, name, class->connection_cnt);
970  } else {
971  /* We successfully grabbed a connection from the pool and all is well!
972  */
973  obj->parent = ao2_bump(class);
974  ast_debug(2, "Reusing ODBC handle %p from class '%s'\n", obj, name);
975  }
976  }
977 
978  ast_mutex_unlock(&class->lock);
979  ao2_ref(class, -1);
980 
981  return obj;
982 }
#define ao2_callback(c, flags, cb_fn, arg)
Definition: astobj2.h:1716
static int aoro2_class_cb(void *obj, void *arg, int flags)
Definition: res_odbc.c:847
#define ast_cond_wait(cond, mutex)
Definition: lock.h:203
#define ast_mutex_lock(a)
Definition: lock.h:187
#define NULL
Definition: resample.c:96
#define ao2_bump(obj)
Definition: astobj2.h:491
static void odbc_obj_destructor(void *data)
Definition: res_odbc.c:194
#define ast_debug(level,...)
Log a DEBUG message.
Definition: logger.h:444
ODBC container.
Definition: res_odbc.h:46
static int connection_dead(struct odbc_obj *connection, struct odbc_class *class)
Definition: res_odbc.c:881
#define ao2_ref(o, delta)
Definition: astobj2.h:464
#define AST_LIST_REMOVE_HEAD(head, field)
Removes and returns the head entry from a list.
Definition: linkedlists.h:832
struct odbc_class * parent
Definition: res_odbc.h:48
static odbc_status odbc_obj_connect(struct odbc_obj *obj)
Definition: res_odbc.c:1022
struct odbc_class::@459 list
#define ao2_alloc(data_size, destructor_fn)
Definition: astobj2.h:411
static const char name[]
Definition: cdr_mysql.c:74
static struct ao2_container * class_container
Definition: res_odbc.c:105
#define ast_mutex_unlock(a)
Definition: lock.h:188

◆ ast_odbc_ast_str_SQLGetData()

SQLRETURN ast_odbc_ast_str_SQLGetData ( struct ast_str **  buf,
int  pmaxlen,
SQLHSTMT  StatementHandle,
SQLUSMALLINT  ColumnNumber,
SQLSMALLINT  TargetType,
SQLLEN *  StrLen_or_Ind 
)

Wrapper for SQLGetData to use with dynamic strings.

Parameters
bufAddress of the pointer to the ast_str structure.
pmaxlenThe maximum size of the resulting string, or 0 for no limit.
StatementHandleThe statement handle from which to retrieve data.
ColumnNumberColumn number (1-based offset) for which to retrieve data.
TargetTypeThe SQL constant indicating what kind of data is to be retrieved (usually SQL_CHAR)
StrLen_or_IndA pointer to a length indicator, specifying the total length of data.

Definition at line 507 of file res_odbc.c.

References ast_str_buffer(), ast_str_make_space, ast_str_size(), and ast_str_update().

Referenced by acf_odbc_read(), and cli_odbc_read().

508 {
509  SQLRETURN res;
510 
511  if (pmaxlen == 0) {
512  if (SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), 0, StrLen_or_Ind) == SQL_SUCCESS_WITH_INFO) {
513  ast_str_make_space(buf, *StrLen_or_Ind + 1);
514  }
515  } else if (pmaxlen > 0) {
516  ast_str_make_space(buf, pmaxlen);
517  }
518  res = SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), ast_str_size(*buf), StrLen_or_Ind);
519  ast_str_update(*buf);
520 
521  return res;
522 }
size_t ast_str_size(const struct ast_str *buf)
Returns the current maximum length (without reallocation) of the current buffer.
Definition: strings.h:699
#define ast_str_make_space(buf, new_len)
Definition: strings.h:780
char * ast_str_buffer(const struct ast_str *buf)
Returns the string buffer within the ast_str buf.
Definition: strings.h:714
void ast_str_update(struct ast_str *buf)
Update the length of the buffer, after using ast_str merely as a buffer.
Definition: strings.h:663

◆ ast_odbc_backslash_is_escape()

int ast_odbc_backslash_is_escape ( struct odbc_obj obj)

Checks if the database natively supports backslash as an escape character.

Parameters
objThe ODBC object
Returns
Returns 1 if backslash is a native escape character, 0 if an ESCAPE clause is needed to support '\'

Definition at line 842 of file res_odbc.c.

References odbc_class::backslash_is_escape, and odbc_obj::parent.

Referenced by odbc_log(), realtime_multi_odbc(), and realtime_odbc().

843 {
844  return obj->parent->backslash_is_escape;
845 }
struct odbc_class * parent
Definition: res_odbc.h:48
unsigned int backslash_is_escape
Definition: res_odbc.c:74

◆ ast_odbc_class_get_forcecommit()

unsigned int ast_odbc_class_get_forcecommit ( struct odbc_class class)

Get the transaction forcecommit setting for an ODBC class.

Definition at line 554 of file res_odbc.c.

Referenced by create_transaction().

555 {
556  return class->forcecommit;
557 }

◆ ast_odbc_class_get_isolation()

unsigned int ast_odbc_class_get_isolation ( struct odbc_class class)

Get the transaction isolation setting for an ODBC class.

Definition at line 549 of file res_odbc.c.

Referenced by create_transaction().

550 {
551  return class->isolation;
552 }

◆ ast_odbc_class_get_name()

const char* ast_odbc_class_get_name ( struct odbc_class class)

Get the name of an ODBC class.

Definition at line 559 of file res_odbc.c.

Referenced by ast_odbc_retrieve_transaction_obj().

560 {
561  return class->name;
562 }

◆ ast_odbc_clear_cache()

int ast_odbc_clear_cache ( const char *  database,
const char *  tablename 
)

Remove a cache entry from memory This function may be called to clear entries created and cached by the ast_odbc_find_table() API call.

Parameters
databaseName of an ODBC class (used to ensure like-named tables in different databases are not confused)
tablenameTablename for which a cached record should be removed
Return values
0if the cache entry was removed, or -1 if no matching entry was found.
Since
1.6.1

Definition at line 352 of file res_odbc.c.

References AST_LIST_REMOVE_CURRENT, AST_RWLIST_TRAVERSE_SAFE_BEGIN, AST_RWLIST_TRAVERSE_SAFE_END, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, odbc_cache_tables::connection, destroy_table_cache(), odbc_class::list, and odbc_cache_tables::table.

Referenced by unload_odbc().

353 {
354  struct odbc_cache_tables *tableptr;
355 
357  AST_RWLIST_TRAVERSE_SAFE_BEGIN(&odbc_tables, tableptr, list) {
358  if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
360  destroy_table_cache(tableptr);
361  break;
362  }
363  }
366  return tableptr ? 0 : -1;
367 }
#define AST_RWLIST_WRLOCK(head)
Write locks a list.
Definition: linkedlists.h:51
#define AST_RWLIST_UNLOCK(head)
Attempts to unlock a read/write based list.
Definition: linkedlists.h:150
char * connection
Definition: res_odbc.h:71
static void destroy_table_cache(struct odbc_cache_tables *table)
Definition: res_odbc.c:201
#define AST_LIST_REMOVE_CURRENT(field)
Removes the current entry from a list during a traversal.
Definition: linkedlists.h:556
#define AST_RWLIST_TRAVERSE_SAFE_BEGIN
Definition: linkedlists.h:544
#define AST_RWLIST_TRAVERSE_SAFE_END
Definition: linkedlists.h:616

◆ ast_odbc_direct_execute()

SQLHSTMT ast_odbc_direct_execute ( struct odbc_obj obj,
SQLHSTMT(*)(struct odbc_obj *obj, void *data)  exec_cb,
void *  data 
)

Executes an non prepared statement and returns the resulting statement handle.

Parameters
objThe ODBC object
exec_cbA function callback, which, when called, should return a statement handle with result columns bound.
dataA parameter to be passed to the exec_cb parameter function, indicating which statement handle is to be prepared.
Return values
astatement handle
NULLon error

Definition at line 369 of file res_odbc.c.

References ast_free, ast_log, ast_mutex_lock, ast_mutex_unlock, ast_tvdiff_ms(), ast_tvnow(), odbc_class::lock, LOG_WARNING, odbc_class::logging, odbc_class::longest_query_execution_time, odbc_class::name, NULL, odbc_obj::parent, odbc_class::slowquerylimit, odbc_obj::sql_text, and odbc_class::sql_text.

Referenced by acf_odbc_read(), acf_odbc_write(), cli_odbc_read(), cli_odbc_write(), connection_dead(), and odbc_log().

370 {
371  struct timeval start;
372  SQLHSTMT stmt;
373 
374  if (obj->parent->logging) {
375  start = ast_tvnow();
376  }
377 
378  stmt = exec_cb(obj, data);
379 
380  if (obj->parent->logging) {
381  long execution_time = ast_tvdiff_ms(ast_tvnow(), start);
382 
383  if (obj->parent->slowquerylimit && execution_time > obj->parent->slowquerylimit) {
384  ast_log(LOG_WARNING, "SQL query '%s' took %ld milliseconds to execute on class '%s', this may indicate a database problem\n",
385  obj->sql_text, execution_time, obj->parent->name);
386  }
387 
388  ast_mutex_lock(&obj->parent->lock);
389  if (execution_time > obj->parent->longest_query_execution_time || !obj->parent->sql_text) {
390  obj->parent->longest_query_execution_time = execution_time;
391  /* Due to the callback nature of the res_odbc API it's not possible to ensure that
392  * the SQL text is removed from the connection in all cases, so only if it becomes the
393  * new longest executing query do we steal the SQL text. In other cases what will happen
394  * is that the SQL text will be freed if the connection is released back to the class or
395  * if a new query is done on the connection.
396  */
397  ast_free(obj->parent->sql_text);
398  obj->parent->sql_text = obj->sql_text;
399  obj->sql_text = NULL;
400  }
401  ast_mutex_unlock(&obj->parent->lock);
402  }
403 
404  return stmt;
405 }
ast_mutex_t lock
Definition: res_odbc.c:86
char name[80]
Definition: res_odbc.c:67
char * sql_text
Definition: res_odbc.c:100
unsigned int logging
Definition: res_odbc.c:92
#define LOG_WARNING
Definition: logger.h:274
unsigned int slowquerylimit
Definition: res_odbc.c:102
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:150
#define ast_mutex_lock(a)
Definition: lock.h:187
int64_t ast_tvdiff_ms(struct timeval end, struct timeval start)
Computes the difference (in milliseconds) between two struct timeval instances.
Definition: time.h:98
#define NULL
Definition: resample.c:96
#define ast_log
Definition: astobj2.c:42
struct odbc_class * parent
Definition: res_odbc.h:48
#define ast_free(a)
Definition: astmm.h:182
char * sql_text
Definition: res_odbc.h:54
long longest_query_execution_time
Definition: res_odbc.c:98
#define ast_mutex_unlock(a)
Definition: lock.h:188

◆ ast_odbc_execute_sql()

SQLRETURN ast_odbc_execute_sql ( struct odbc_obj obj,
SQLHSTMT *  stmt,
const char *  sql 
)

Execute a nonprepared SQL query.

Parameters
objThe ODBC object
sqlThe SQL query
Note
This should be used in place of SQLExecDirect

Definition at line 478 of file res_odbc.c.

References ast_atomic_fetchadd_int(), ast_free, ast_strdup, odbc_class::logging, odbc_obj::parent, odbc_class::queries_executed, and odbc_obj::sql_text.

Referenced by execute(), and execute_cb().

479 {
480  if (obj->parent->logging) {
481  ast_free(obj->sql_text);
482  obj->sql_text = ast_strdup(sql);
484  }
485 
486  return SQLExecDirect(stmt, (unsigned char *)sql, SQL_NTS);
487 }
unsigned int logging
Definition: res_odbc.c:92
#define ast_strdup(str)
A wrapper for strdup()
Definition: astmm.h:243
int ast_atomic_fetchadd_int(volatile int *p, int v)
Atomically add v to *p and return the previous value of *p.
Definition: lock.h:755
struct odbc_class * parent
Definition: res_odbc.h:48
#define ast_free(a)
Definition: astmm.h:182
char * sql_text
Definition: res_odbc.h:54
int queries_executed
Definition: res_odbc.c:96

◆ ast_odbc_find_column()

struct odbc_cache_columns* ast_odbc_find_column ( struct odbc_cache_tables table,
const char *  colname 
)

Find a column entry within a cached table structure.

Parameters
tableCached table structure, as returned from ast_odbc_find_table()
colnameThe column name requested
Return values
Astructure describing the column type, or NULL, if the column is not found.
Since
1.6.1

Definition at line 341 of file res_odbc.c.

References AST_RWLIST_TRAVERSE, odbc_cache_tables::columns, odbc_class::list, odbc_cache_columns::name, and NULL.

Referenced by update2_prepare(), and update_odbc().

342 {
343  struct odbc_cache_columns *col;
344  AST_RWLIST_TRAVERSE(&table->columns, col, list) {
345  if (strcasecmp(col->name, colname) == 0) {
346  return col;
347  }
348  }
349  return NULL;
350 }
#define NULL
Definition: resample.c:96
These structures are used for adaptive capabilities.
Definition: res_odbc.h:59
#define AST_RWLIST_TRAVERSE
Definition: linkedlists.h:493
struct odbc_cache_tables::_columns columns

◆ ast_odbc_find_table()

struct odbc_cache_tables* ast_odbc_find_table ( const char *  database,
const char *  tablename 
)

Find or create an entry describing the table specified.

Parameters
databaseName of an ODBC class on which to query the table
tablenameTablename to describe
Return values
Astructure describing the table layout, or NULL, if the table is not found or another error occurs. When a structure is returned, the contained columns list will be rdlock'ed, to ensure that it will be retained in memory. The information will be cached until a reload event or when ast_odbc_clear_cache() is called with the relevant parameters.
Since
1.6.1
Parameters
databaseName of an ODBC class on which to query the table
tablenameTablename to describe
Return values
Astructure describing the table layout, or NULL, if the table is not found or another error occurs. When a structure is returned, the contained columns list will be rdlock'ed, to ensure that it will be retained in memory.

XXX This creates a connection and disconnects it. In some situations, the caller of this function has its own connection and could donate it to this function instead of needing to create another one.

XXX The automatic readlock of the columns is awkward. It's done because it's possible for multiple threads to have references to the table, and the table is not refcounted. Possible changes here would be

  • Eliminate the table cache entirely. The use of ast_odbc_find_table() is generally questionable. The only real good use right now is from ast_realtime_require_field() in order to make sure the DB has the expected columns in it. Since that is only used sparingly, the need to cache tables is questionable. Instead, the table structure can be fetched from the DB directly each time, resulting in a single owner of the data.
  • Make odbc_cache_tables a refcounted object.
Since
1.6.1

Definition at line 241 of file res_odbc.c.

References ast_calloc, ast_debug, AST_LIST_INSERT_TAIL, ast_log, ast_odbc_release_obj(), ast_odbc_request_obj, AST_RWLIST_HEAD_INIT, AST_RWLIST_INSERT_TAIL, AST_RWLIST_RDLOCK, AST_RWLIST_TRAVERSE, AST_RWLIST_UNLOCK, odbc_cache_tables::columns, odbc_obj::con, odbc_cache_tables::connection, odbc_cache_columns::decimals, destroy_table_cache(), error(), odbc_class::list, LOG_ERROR, LOG_WARNING, odbc_cache_columns::name, NULL, odbc_cache_columns::nullable, odbc_cache_columns::octetlen, odbc_cache_columns::radix, odbc_cache_columns::size, odbc_cache_tables::table, and odbc_cache_columns::type.

Referenced by require_odbc(), update2_odbc(), and update_odbc().

242 {
243  struct odbc_cache_tables *tableptr;
244  struct odbc_cache_columns *entry;
245  char columnname[80];
246  SQLLEN sqlptr;
247  SQLHSTMT stmt = NULL;
248  int res = 0, error = 0;
249  struct odbc_obj *obj;
250 
252  AST_RWLIST_TRAVERSE(&odbc_tables, tableptr, list) {
253  if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
254  break;
255  }
256  }
257  if (tableptr) {
258  AST_RWLIST_RDLOCK(&tableptr->columns);
260  return tableptr;
261  }
262 
263  if (!(obj = ast_odbc_request_obj(database, 0))) {
264  ast_log(LOG_WARNING, "Unable to retrieve database handle for table description '%s@%s'\n", tablename, database);
266  return NULL;
267  }
268 
269  /* Table structure not already cached; build it now. */
270  do {
271  res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
272  if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
273  ast_log(LOG_WARNING, "SQL Alloc Handle failed on connection '%s'!\n", database);
274  break;
275  }
276 
277  res = SQLColumns(stmt, NULL, 0, NULL, 0, (unsigned char *)tablename, SQL_NTS, (unsigned char *)"%", SQL_NTS);
278  if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
279  SQLFreeHandle(SQL_HANDLE_STMT, stmt);
280  ast_log(LOG_ERROR, "Unable to query database columns on connection '%s'.\n", database);
281  break;
282  }
283 
284  if (!(tableptr = ast_calloc(sizeof(char), sizeof(*tableptr) + strlen(database) + 1 + strlen(tablename) + 1))) {
285  ast_log(LOG_ERROR, "Out of memory creating entry for table '%s' on connection '%s'\n", tablename, database);
286  break;
287  }
288 
289  tableptr->connection = (char *)tableptr + sizeof(*tableptr);
290  tableptr->table = (char *)tableptr + sizeof(*tableptr) + strlen(database) + 1;
291  strcpy(tableptr->connection, database); /* SAFE */
292  strcpy(tableptr->table, tablename); /* SAFE */
293  AST_RWLIST_HEAD_INIT(&(tableptr->columns));
294 
295  while ((res = SQLFetch(stmt)) != SQL_NO_DATA && res != SQL_ERROR) {
296  SQLGetData(stmt, 4, SQL_C_CHAR, columnname, sizeof(columnname), &sqlptr);
297 
298  if (!(entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(columnname) + 1))) {
299  ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s' on connection '%s'\n", columnname, tablename, database);
300  error = 1;
301  break;
302  }
303  entry->name = (char *)entry + sizeof(*entry);
304  strcpy(entry->name, columnname);
305 
306  SQLGetData(stmt, 5, SQL_C_SHORT, &entry->type, sizeof(entry->type), NULL);
307  SQLGetData(stmt, 7, SQL_C_LONG, &entry->size, sizeof(entry->size), NULL);
308  SQLGetData(stmt, 9, SQL_C_SHORT, &entry->decimals, sizeof(entry->decimals), NULL);
309  SQLGetData(stmt, 10, SQL_C_SHORT, &entry->radix, sizeof(entry->radix), NULL);
310  SQLGetData(stmt, 11, SQL_C_SHORT, &entry->nullable, sizeof(entry->nullable), NULL);
311  SQLGetData(stmt, 16, SQL_C_LONG, &entry->octetlen, sizeof(entry->octetlen), NULL);
312 
313  /* Specification states that the octenlen should be the maximum number of bytes
314  * returned in a char or binary column, but it seems that some drivers just set
315  * it to NULL. (Bad Postgres! No biscuit!) */
316  if (entry->octetlen == 0) {
317  entry->octetlen = entry->size;
318  }
319 
320  ast_debug(3, "Found %s column with type %hd with len %ld, octetlen %ld, and numlen (%hd,%hd)\n", entry->name, entry->type, (long) entry->size, (long) entry->octetlen, entry->decimals, entry->radix);
321  /* Insert column info into column list */
322  AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
323  }
324  SQLFreeHandle(SQL_HANDLE_STMT, stmt);
325 
327  AST_RWLIST_RDLOCK(&(tableptr->columns));
328  break;
329  } while (1);
330 
332 
333  if (error) {
334  destroy_table_cache(tableptr);
335  tableptr = NULL;
336  }
338  return tableptr;
339 }
SQLHDBC con
Definition: res_odbc.h:47
struct odbc_obj::@288 list
#define LOG_WARNING
Definition: logger.h:274
#define AST_RWLIST_UNLOCK(head)
Attempts to unlock a read/write based list.
Definition: linkedlists.h:150
SQLSMALLINT nullable
Definition: res_odbc.h:65
char * connection
Definition: res_odbc.h:71
#define AST_RWLIST_HEAD_INIT(head)
Initializes an rwlist head structure.
Definition: linkedlists.h:638
#define NULL
Definition: resample.c:96
static void destroy_table_cache(struct odbc_cache_tables *table)
Definition: res_odbc.c:201
These structures are used for adaptive capabilities.
Definition: res_odbc.h:59
SQLINTEGER octetlen
Definition: res_odbc.h:66
#define AST_RWLIST_RDLOCK(head)
Read locks a list.
Definition: linkedlists.h:77
#define ast_debug(level,...)
Log a DEBUG message.
Definition: logger.h:444
#define ast_log
Definition: astobj2.c:42
ODBC container.
Definition: res_odbc.h:46
#define AST_RWLIST_TRAVERSE
Definition: linkedlists.h:493
void ast_odbc_release_obj(struct odbc_obj *obj)
Releases an ODBC object previously allocated by ast_odbc_request_obj()
Definition: res_odbc.c:813
#define LOG_ERROR
Definition: logger.h:285
#define AST_LIST_INSERT_TAIL(head, elm, field)
Appends a list entry to the tail of a list.
Definition: linkedlists.h:730
#define ast_calloc(num, len)
A wrapper for calloc()
Definition: astmm.h:204
SQLINTEGER size
Definition: res_odbc.h:62
#define ast_odbc_request_obj(a, b)
Definition: res_odbc.h:122
#define AST_RWLIST_INSERT_TAIL
Definition: linkedlists.h:740
SQLSMALLINT decimals
Definition: res_odbc.h:63
SQLSMALLINT radix
Definition: res_odbc.h:64
Definition: search.h:40
int error(const char *format,...)
Definition: utils/frame.c:999
SQLSMALLINT type
Definition: res_odbc.h:61
struct odbc_cache_tables::_columns columns

◆ ast_odbc_get_max_connections()

unsigned int ast_odbc_get_max_connections ( const char *  name)

Return the current configured maximum number of connections for a class.

Definition at line 857 of file res_odbc.c.

References ao2_callback, and ao2_ref.

Referenced by release_obj_or_dsn().

858 {
859  struct odbc_class *class;
860  unsigned int max_connections;
861 
862  class = ao2_callback(class_container, 0, aoro2_class_cb, (char *) name);
863  if (!class) {
864  return 0;
865  }
866 
867  max_connections = class->maxconnections;
868  ao2_ref(class, -1);
869 
870  return max_connections;
871 }
#define ao2_callback(c, flags, cb_fn, arg)
Definition: astobj2.h:1716
static int aoro2_class_cb(void *obj, void *arg, int flags)
Definition: res_odbc.c:847
#define ao2_ref(o, delta)
Definition: astobj2.h:464
static const char name[]
Definition: cdr_mysql.c:74
static struct ao2_container * class_container
Definition: res_odbc.c:105

◆ ast_odbc_isolation2text()

const char* ast_odbc_isolation2text ( int  iso)

Convert from numeric transaction isolation values to their textual counterparts.

Definition at line 132 of file res_odbc.c.

Referenced by acf_transaction_read().

133 {
134  if (iso == SQL_TXN_READ_COMMITTED) {
135  return "read_committed";
136  } else if (iso == SQL_TXN_READ_UNCOMMITTED) {
137  return "read_uncommitted";
138  } else if (iso == SQL_TXN_SERIALIZABLE) {
139  return "serializable";
140  } else if (iso == SQL_TXN_REPEATABLE_READ) {
141  return "repeatable_read";
142  } else {
143  return "unknown";
144  }
145 }

◆ ast_odbc_prepare()

int ast_odbc_prepare ( struct odbc_obj obj,
SQLHSTMT *  stmt,
const char *  sql 
)

Prepares a SQL query on a statement.

Parameters
objThe ODBC object
stmtThe statement sql The SQL query
Note
This should be used in place of SQLPrepare

Definition at line 463 of file res_odbc.c.

References ast_atomic_fetchadd_int(), ast_free, ast_strdup, odbc_class::logging, odbc_obj::parent, odbc_class::prepares_executed, and odbc_obj::sql_text.

Referenced by config_odbc_prepare(), custom_prepare(), generic_prepare(), length_determination_odbc_prepare(), and update2_prepare().

464 {
465  if (obj->parent->logging) {
466  /* It is possible for this connection to be reused without being
467  * released back to the class, so we free what may already exist
468  * and place the new SQL in.
469  */
470  ast_free(obj->sql_text);
471  obj->sql_text = ast_strdup(sql);
473  }
474 
475  return SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
476 }
unsigned int logging
Definition: res_odbc.c:92
#define ast_strdup(str)
A wrapper for strdup()
Definition: astmm.h:243
int ast_atomic_fetchadd_int(volatile int *p, int v)
Atomically add v to *p and return the previous value of *p.
Definition: lock.h:755
int prepares_executed
Definition: res_odbc.c:94
struct odbc_class * parent
Definition: res_odbc.h:48
#define ast_free(a)
Definition: astmm.h:182
char * sql_text
Definition: res_odbc.h:54

◆ ast_odbc_prepare_and_execute()

SQLHSTMT ast_odbc_prepare_and_execute ( struct odbc_obj obj,
SQLHSTMT(*)(struct odbc_obj *obj, void *data)  prepare_cb,
void *  data 
)

Prepares, executes, and returns the resulting statement handle.

Parameters
objThe ODBC object
prepare_cbA function callback, which, when called, should return a statement handle prepared, with any necessary parameters or result columns bound.
dataA parameter to be passed to the prepare_cb parameter function, indicating which statement handle is to be prepared.
Return values
astatement handle
NULLon error

Definition at line 407 of file res_odbc.c.

References ast_atomic_fetchadd_int(), ast_free, ast_log, ast_mutex_lock, ast_mutex_unlock, ast_odbc_print_errors(), ast_tvdiff_ms(), ast_tvnow(), odbc_class::lock, LOG_WARNING, odbc_class::logging, odbc_class::longest_query_execution_time, odbc_class::name, NULL, odbc_obj::parent, odbc_class::queries_executed, odbc_class::slowquerylimit, odbc_obj::sql_text, and odbc_class::sql_text.

Referenced by config_odbc(), destroy_odbc(), free_zone(), odbc_log(), realtime_multi_odbc(), realtime_odbc(), store_odbc(), update2_odbc(), and update_odbc().

408 {
409  struct timeval start;
410  int res = 0;
411  SQLHSTMT stmt;
412 
413  if (obj->parent->logging) {
414  start = ast_tvnow();
415  }
416 
417  /* This prepare callback may do more than just prepare -- it may also
418  * bind parameters, bind results, etc. The real key, here, is that
419  * when we disconnect, all handles become invalid for most databases.
420  * We must therefore redo everything when we establish a new
421  * connection. */
422  stmt = prepare_cb(obj, data);
423  if (!stmt) {
424  return NULL;
425  }
426 
427  res = SQLExecute(stmt);
428  if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
429  if (res == SQL_ERROR) {
430  ast_odbc_print_errors(SQL_HANDLE_STMT, stmt, "SQL Execute");
431  }
432 
433  ast_log(LOG_WARNING, "SQL Execute error %d!\n", res);
434  SQLFreeHandle(SQL_HANDLE_STMT, stmt);
435  stmt = NULL;
436  } else if (obj->parent->logging) {
437  long execution_time = ast_tvdiff_ms(ast_tvnow(), start);
438 
439  if (obj->parent->slowquerylimit && execution_time > obj->parent->slowquerylimit) {
440  ast_log(LOG_WARNING, "SQL query '%s' took %ld milliseconds to execute on class '%s', this may indicate a database problem\n",
441  obj->sql_text, execution_time, obj->parent->name);
442  }
443 
444  ast_mutex_lock(&obj->parent->lock);
445 
446  /* If this takes the record on longest query execution time, update the parent class
447  * with the information.
448  */
449  if (execution_time > obj->parent->longest_query_execution_time || !obj->parent->sql_text) {
450  obj->parent->longest_query_execution_time = execution_time;
451  ast_free(obj->parent->sql_text);
452  obj->parent->sql_text = obj->sql_text;
453  obj->sql_text = NULL;
454  }
455  ast_mutex_unlock(&obj->parent->lock);
456 
458  }
459 
460  return stmt;
461 }
ast_mutex_t lock
Definition: res_odbc.c:86
char name[80]
Definition: res_odbc.c:67
char * sql_text
Definition: res_odbc.c:100
unsigned int logging
Definition: res_odbc.c:92
struct ast_str * ast_odbc_print_errors(SQLSMALLINT handle_type, SQLHANDLE handle, const char *operation)
Shortcut for printing errors to logs after a failed SQL operation.
Definition: res_odbc.c:524
#define LOG_WARNING
Definition: logger.h:274
unsigned int slowquerylimit
Definition: res_odbc.c:102
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:150
#define ast_mutex_lock(a)
Definition: lock.h:187
int64_t ast_tvdiff_ms(struct timeval end, struct timeval start)
Computes the difference (in milliseconds) between two struct timeval instances.
Definition: time.h:98
#define NULL
Definition: resample.c:96
int ast_atomic_fetchadd_int(volatile int *p, int v)
Atomically add v to *p and return the previous value of *p.
Definition: lock.h:755
#define ast_log
Definition: astobj2.c:42
struct odbc_class * parent
Definition: res_odbc.h:48
#define ast_free(a)
Definition: astmm.h:182
char * sql_text
Definition: res_odbc.h:54
int queries_executed
Definition: res_odbc.c:96
long longest_query_execution_time
Definition: res_odbc.c:98
#define ast_mutex_unlock(a)
Definition: lock.h:188

◆ ast_odbc_print_errors()

struct ast_str* ast_odbc_print_errors ( SQLSMALLINT  handle_type,
SQLHANDLE  handle,
const char *  operation 
)

Shortcut for printing errors to logs after a failed SQL operation.

Parameters
handle_typeThe type of SQL handle on which to gather diagnostics
handleThe SQL handle to gather diagnostics from
operationThe name of the failed operation.
Returns
The error string that was printed to the logs

Definition at line 524 of file res_odbc.c.

References ast_log, ast_str_append(), ast_str_reset(), ast_str_strlen(), ast_str_thread_get(), errors_buf, and LOG_WARNING.

Referenced by acf_transaction_write(), ast_odbc_prepare_and_execute(), ast_odbc_smart_execute(), commit_exec(), create_transaction(), custom_prepare(), release_transaction(), rollback_exec(), and update2_prepare().

525 {
526  struct ast_str *errors = ast_str_thread_get(&errors_buf, 16);
527  SQLINTEGER nativeerror = 0;
528  SQLSMALLINT diagbytes = 0;
529  SQLSMALLINT i;
530  unsigned char state[10];
531  unsigned char diagnostic[256];
532 
533  ast_str_reset(errors);
534  i = 0;
535  while (SQLGetDiagRec(handle_type, handle, ++i, state, &nativeerror,
536  diagnostic, sizeof(diagnostic), &diagbytes) == SQL_SUCCESS) {
537  ast_str_append(&errors, 0, "%s%s", ast_str_strlen(errors) ? "," : "", state);
538  ast_log(LOG_WARNING, "%s returned an error: %s: %s\n", operation, state, diagnostic);
539  /* XXX Why is this here? */
540  if (i > 10) {
541  ast_log(LOG_WARNING, "There are more than 10 diagnostic records! Ignore the rest.\n");
542  break;
543  }
544  }
545 
546  return errors;
547 }
#define LOG_WARNING
Definition: logger.h:274
static struct ast_threadstorage errors_buf
Definition: res_odbc.c:113
int ast_str_append(struct ast_str **buf, ssize_t max_len, const char *fmt,...)
Append to a thread local dynamic string.
Definition: strings.h:1091
#define ast_log
Definition: astobj2.c:42
The descriptor of a dynamic string XXX storage will be optimized later if needed We use the ts field ...
Definition: strings.h:584
void ast_str_reset(struct ast_str *buf)
Reset the content of a dynamic string. Useful before a series of ast_str_append.
Definition: strings.h:653
size_t ast_str_strlen(const struct ast_str *buf)
Returns the current length of the string stored within buf.
Definition: strings.h:688
struct ast_str * ast_str_thread_get(struct ast_threadstorage *ts, size_t init_len)
Retrieve a thread locally stored dynamic string.
Definition: strings.h:861

◆ ast_odbc_release_obj()

void ast_odbc_release_obj ( struct odbc_obj obj)

Releases an ODBC object previously allocated by ast_odbc_request_obj()

Parameters
objThe ODBC object

Definition at line 813 of file res_odbc.c.

References ao2_ref, ast_cond_signal, ast_debug, ast_free, AST_LIST_INSERT_HEAD, ast_mutex_lock, ast_mutex_unlock, odbc_class::list, NULL, odbc_obj::parent, and odbc_obj::sql_text.

Referenced by ast_odbc_find_table(), config_odbc(), create_transaction(), destroy_odbc(), dsn_destructor(), free_zone(), get_dsn(), load_config(), odbc_log(), odbc_register_class(), realtime_multi_odbc(), realtime_odbc(), release_obj_or_dsn(), release_transaction(), store_odbc(), update2_odbc(), and update_odbc().

814 {
815  struct odbc_class *class = obj->parent;
816 
817  ast_debug(2, "Releasing ODBC handle %p into pool\n", obj);
818 
819  /* The odbc_obj only holds a reference to the class when it is
820  * actively being used. This guarantees no circular reference
821  * between odbc_class and odbc_obj. Since it is being released
822  * we also release our class reference. If a reload occurred before
823  * the class will go away automatically once all odbc_obj are
824  * released back.
825  */
826  obj->parent = NULL;
827 
828  /* Free the SQL text so that the next user of this connection has
829  * a fresh start.
830  */
831  ast_free(obj->sql_text);
832  obj->sql_text = NULL;
833 
834  ast_mutex_lock(&class->lock);
835  AST_LIST_INSERT_HEAD(&class->connections, obj, list);
836  ast_cond_signal(&class->cond);
837  ast_mutex_unlock(&class->lock);
838 
839  ao2_ref(class, -1);
840 }
#define ast_mutex_lock(a)
Definition: lock.h:187
#define NULL
Definition: resample.c:96
#define ast_cond_signal(cond)
Definition: lock.h:201
#define ast_debug(level,...)
Log a DEBUG message.
Definition: logger.h:444
#define ao2_ref(o, delta)
Definition: astobj2.h:464
struct odbc_class * parent
Definition: res_odbc.h:48
#define AST_LIST_INSERT_HEAD(head, elm, field)
Inserts a list entry at the head of a list.
Definition: linkedlists.h:710
#define ast_free(a)
Definition: astmm.h:182
char * sql_text
Definition: res_odbc.h:54
#define ast_mutex_unlock(a)
Definition: lock.h:188

◆ ast_odbc_sanity_check()

int ast_odbc_sanity_check ( struct odbc_obj obj)

Checks an ODBC object to ensure it is still connected.

Parameters
objThe ODBC object
Return values
0if connected
-1otherwise.

◆ ast_odbc_smart_execute()

int ast_odbc_smart_execute ( struct odbc_obj obj,
SQLHSTMT  stmt 
)

Executes a prepared statement handle.

Parameters
objThe non-NULL result of odbc_request_obj()
stmtThe prepared statement handle
Return values
0on success
-1on failure

This function was originally designed simply to execute a prepared statement handle and to retry if the initial execution failed. Unfortunately, it did this by disconnecting and reconnecting the database handle which on most databases causes the statement handle to become invalid. Therefore, this method has been deprecated in favor of odbc_prepare_and_execute() which allows the statement to be prepared multiple times, if necessary, in case of a loss of connection.

This function really only ever worked with MySQL, where the statement handle is not prepared on the server. If you are not using MySQL, you should avoid it.

Definition at line 489 of file res_odbc.c.

References ast_atomic_fetchadd_int(), ast_odbc_print_errors(), odbc_class::logging, odbc_obj::parent, and odbc_class::queries_executed.

490 {
491  int res = 0;
492 
493  res = SQLExecute(stmt);
494  if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
495  if (res == SQL_ERROR) {
496  ast_odbc_print_errors(SQL_HANDLE_STMT, stmt, "SQL Execute");
497  }
498  }
499 
500  if (obj->parent->logging) {
502  }
503 
504  return res;
505 }
unsigned int logging
Definition: res_odbc.c:92
struct ast_str * ast_odbc_print_errors(SQLSMALLINT handle_type, SQLHANDLE handle, const char *operation)
Shortcut for printing errors to logs after a failed SQL operation.
Definition: res_odbc.c:524
int ast_atomic_fetchadd_int(volatile int *p, int v)
Atomically add v to *p and return the previous value of *p.
Definition: lock.h:755
struct odbc_class * parent
Definition: res_odbc.h:48
int queries_executed
Definition: res_odbc.c:96

◆ ast_odbc_text2isolation()

int ast_odbc_text2isolation ( const char *  txt)

Convert from textual transaction isolation values to their numeric constants.

Definition at line 147 of file res_odbc.c.

Referenced by acf_transaction_write(), and load_odbc_config().

148 {
149  if (strncasecmp(txt, "read_", 5) == 0) {
150  if (strncasecmp(txt + 5, "c", 1) == 0) {
151  return SQL_TXN_READ_COMMITTED;
152  } else if (strncasecmp(txt + 5, "u", 1) == 0) {
153  return SQL_TXN_READ_UNCOMMITTED;
154  } else {
155  return 0;
156  }
157  } else if (strncasecmp(txt, "ser", 3) == 0) {
158  return SQL_TXN_SERIALIZABLE;
159  } else if (strncasecmp(txt, "rep", 3) == 0) {
160  return SQL_TXN_REPEATABLE_READ;
161  } else {
162  return 0;
163  }
164 }