Wed Mar 2 18:58:15 2011

Asterisk developer's documentation


res_odbc.c File Reference

ODBC resource manager. More...

#include "asterisk.h"
#include "asterisk/file.h"
#include "asterisk/channel.h"
#include "asterisk/config.h"
#include "asterisk/pbx.h"
#include "asterisk/module.h"
#include "asterisk/cli.h"
#include "asterisk/lock.h"
#include "asterisk/res_odbc.h"
#include "asterisk/time.h"
#include "asterisk/astobj2.h"
#include "asterisk/app.h"
#include "asterisk/strings.h"
#include "asterisk/threadstorage.h"

Include dependency graph for res_odbc.c:

Go to the source code of this file.

Data Structures

struct  odbc_class
struct  odbc_tables
struct  odbc_txn_frame

Defines

#define EOR_TX   (void *)(long)3
#define NO_TX   (void *)(long)2
#define USE_TX   (void *)(long)1

Functions

static void __init_errors_buf (void)
static void __reg_module (void)
static void __unreg_module (void)
static int acf_transaction_read (struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
static int acf_transaction_write (struct ast_channel *chan, const char *cmd, char *s, const char *value)
static int aoro2_class_cb (void *obj, void *arg, int flags)
static int aoro2_obj_cb (void *vobj, void *arg, int flags)
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.
int ast_odbc_backslash_is_escape (struct odbc_obj *obj)
 Checks if the database natively supports backslash as an escape character.
int ast_odbc_clear_cache (const char *database, const char *tablename)
 Remove a cache entry from memory.
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.
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.
struct odbc_cache_tables * ast_odbc_find_table (const char *database, const char *tablename)
 Find or create an entry describing the table specified.
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.
void ast_odbc_release_obj (struct odbc_obj *obj)
 Releases an ODBC object previously allocated by odbc_request_obj().
struct odbc_obj * ast_odbc_request_obj (const char *name, int check)
struct odbc_obj * ast_odbc_request_obj2 (const char *name, struct ast_flags flags)
 Retrieves a connected ODBC object.
struct odbc_obj * ast_odbc_retrieve_transaction_obj (struct ast_channel *chan, const char *objname)
 Retrieve a stored ODBC object, if a transaction has been started.
int ast_odbc_sanity_check (struct odbc_obj *obj)
 Checks an ODBC object to ensure it is still connected.
int ast_odbc_smart_execute (struct odbc_obj *obj, SQLHSTMT stmt)
 Executes a prepared statement handle.
static int commit_exec (struct ast_channel *chan, void *data)
static void destroy_table_cache (struct odbc_cache_tables *table)
static struct odbc_txn_frame * find_transaction (struct ast_channel *chan, struct odbc_obj *obj, const char *name, int active)
static char * handle_cli_odbc_show (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static const char * isolation2text (int iso)
static int load_module (void)
static int load_odbc_config (void)
static int mark_transaction_active (struct ast_channel *chan, struct odbc_txn_frame *tx)
static int null_hash_fn (const void *obj, const int flags)
static void odbc_class_destructor (void *data)
static odbc_status odbc_obj_connect (struct odbc_obj *obj)
static void odbc_obj_destructor (void *data)
static odbc_status odbc_obj_disconnect (struct odbc_obj *obj)
static int odbc_register_class (struct odbc_class *class, int connect)
static void odbc_release_obj2 (struct odbc_obj *obj, struct odbc_txn_frame *tx)
static void odbc_txn_free (void *data)
static struct odbc_txn_frame * release_transaction (struct odbc_txn_frame *tx)
static int reload (void)
static int rollback_exec (struct ast_channel *chan, void *data)
static int text2isolation (const char *txt)
static int unload_module (void)

Variables

static struct ast_module_info __mod_info = { .name = AST_MODULE, .flags = AST_MODFLAG_GLOBAL_SYMBOLS , .description = "ODBC resource" , .key = "This paragraph is copyright (c) 2006 by Digium, Inc. \In order for your module to load, it must return this \key via a function called \"key\". Any code which \includes this paragraph must be licensed under the GNU \General Public License version 2 or later (at your \option). In addition to Digium's general reservations \of rights, Digium expressly reserves the right to \allow other parties to license this paragraph under \different terms. Any use of Digium, Inc. trademarks or \logos (including \"Asterisk\" or \"Digium\") without \express written permission of Digium, Inc. is prohibited.\n" , .buildopt_sum = AST_BUILDOPT_SUM, .load = load_module, .unload = unload_module, .reload = reload, }
static const char * app_commit = "ODBC_Commit"
static const char * app_rollback = "ODBC_Rollback"
static struct ast_module_info * ast_module_info = &__mod_info
struct ao2_container * class_container
static struct ast_cli_entry cli_odbc []
static struct ast_threadstorage errors_buf = { .once = PTHREAD_ONCE_INIT , .key_init = __init_errors_buf , .custom_init = NULL , }
static struct ast_custom_function odbc_function
static struct ast_datastore_info txn_info


Detailed Description

ODBC resource manager.

Author:
Mark Spencer <markster@digium.com>

Anthony Minessale II <anthmct@yahoo.com>

Tilghman Lesher <tilghman@digium.com>

Definition in file res_odbc.c.


Define Documentation

#define EOR_TX   (void *)(long)3

Definition at line 1139 of file res_odbc.c.

Referenced by aoro2_obj_cb(), and ast_odbc_request_obj2().

#define NO_TX   (void *)(long)2

Definition at line 1138 of file res_odbc.c.

Referenced by aoro2_obj_cb(), and ast_odbc_request_obj2().

#define USE_TX   (void *)(long)1

Definition at line 1137 of file res_odbc.c.

Referenced by aoro2_obj_cb(), and ast_odbc_request_obj2().


Function Documentation

static void __init_errors_buf ( void   )  [static]

Definition at line 146 of file res_odbc.c.

00148 {

static void __reg_module ( void   )  [static]

Definition at line 1703 of file res_odbc.c.

static void __unreg_module ( void   )  [static]

Definition at line 1703 of file res_odbc.c.

static int acf_transaction_read ( struct ast_channel *  chan,
const char *  cmd,
char *  data,
char *  buf,
size_t  len 
) [static]

Definition at line 1465 of file res_odbc.c.

References AST_APP_ARG, ast_copy_string(), AST_DECLARE_APP_ARGS, AST_STANDARD_APP_ARGS, ast_strlen_zero(), find_transaction(), odbc_txn_frame::forcecommit, odbc_txn_frame::isolation, isolation2text(), and odbc_txn_frame::name.

01466 {
01467    AST_DECLARE_APP_ARGS(args,
01468       AST_APP_ARG(property);
01469       AST_APP_ARG(opt);
01470    );
01471    struct odbc_txn_frame *tx;
01472 
01473    AST_STANDARD_APP_ARGS(args, data);
01474    if (strcasecmp(args.property, "transaction") == 0) {
01475       if ((tx = find_transaction(chan, NULL, NULL, 1))) {
01476          ast_copy_string(buf, tx->name, len);
01477          return 0;
01478       }
01479    } else if (strcasecmp(args.property, "isolation") == 0) {
01480       if (!ast_strlen_zero(args.opt)) {
01481          tx = find_transaction(chan, NULL, args.opt, 0);
01482       } else {
01483          tx = find_transaction(chan, NULL, NULL, 1);
01484       }
01485       if (tx) {
01486          ast_copy_string(buf, isolation2text(tx->isolation), len);
01487          return 0;
01488       }
01489    } else if (strcasecmp(args.property, "forcecommit") == 0) {
01490       if (!ast_strlen_zero(args.opt)) {
01491          tx = find_transaction(chan, NULL, args.opt, 0);
01492       } else {
01493          tx = find_transaction(chan, NULL, NULL, 1);
01494       }
01495       if (tx) {
01496          ast_copy_string(buf, tx->forcecommit ? "1" : "0", len);
01497          return 0;
01498       }
01499    }
01500    return -1;
01501 }

static int acf_transaction_write ( struct ast_channel *  chan,
const char *  cmd,
char *  s,
const char *  value 
) [static]

Definition at line 1503 of file res_odbc.c.

References AST_APP_ARG, AST_DECLARE_APP_ARGS, ast_false(), ast_log(), ast_odbc_request_obj2(), AST_STANDARD_APP_ARGS, ast_strlen_zero(), ast_true(), odbc_obj::con, find_transaction(), odbc_txn_frame::forcecommit, odbc_txn_frame::isolation, odbc_class::isolation, LOG_ERROR, LOG_WARNING, mark_transaction_active(), odbc_txn_frame::obj, pbx_builtin_setvar_helper(), RES_ODBC_INDEPENDENT_CONNECTION, S_OR, text2isolation(), and odbc_obj::tx.

01504 {
01505    AST_DECLARE_APP_ARGS(args,
01506       AST_APP_ARG(property);
01507       AST_APP_ARG(opt);
01508    );
01509    struct odbc_txn_frame *tx;
01510    SQLINTEGER nativeerror=0, numfields=0;
01511    SQLSMALLINT diagbytes=0, i;
01512    unsigned char state[10], diagnostic[256];
01513 
01514    AST_STANDARD_APP_ARGS(args, s);
01515    if (strcasecmp(args.property, "transaction") == 0) {
01516       /* Set active transaction */
01517       struct odbc_obj *obj;
01518       if ((tx = find_transaction(chan, NULL, value, 0))) {
01519          mark_transaction_active(chan, tx);
01520       } else {
01521          /* No such transaction, create one */
01522          struct ast_flags flags = { RES_ODBC_INDEPENDENT_CONNECTION };
01523          if (ast_strlen_zero(args.opt) || !(obj = ast_odbc_request_obj2(args.opt, flags))) {
01524             ast_log(LOG_ERROR, "Could not create transaction: invalid database specification '%s'\n", S_OR(args.opt, ""));
01525             pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_DB");
01526             return -1;
01527          }
01528          if (!(tx = find_transaction(chan, obj, value, 0))) {
01529             pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
01530             return -1;
01531          }
01532          obj->tx = 1;
01533       }
01534       pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
01535       return 0;
01536    } else if (strcasecmp(args.property, "forcecommit") == 0) {
01537       /* Set what happens when an uncommitted transaction ends without explicit Commit or Rollback */
01538       if (ast_strlen_zero(args.opt)) {
01539          tx = find_transaction(chan, NULL, NULL, 1);
01540       } else {
01541          tx = find_transaction(chan, NULL, args.opt, 0);
01542       }
01543       if (!tx) {
01544          pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
01545          return -1;
01546       }
01547       if (ast_true(value)) {
01548          tx->forcecommit = 1;
01549       } else if (ast_false(value)) {
01550          tx->forcecommit = 0;
01551       } else {
01552          ast_log(LOG_ERROR, "Invalid value for forcecommit: '%s'\n", S_OR(value, ""));
01553          pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_VALUE");
01554          return -1;
01555       }
01556 
01557       pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
01558       return 0;
01559    } else if (strcasecmp(args.property, "isolation") == 0) {
01560       /* How do uncommitted transactions affect reads? */
01561       int isolation = text2isolation(value);
01562       if (ast_strlen_zero(args.opt)) {
01563          tx = find_transaction(chan, NULL, NULL, 1);
01564       } else {
01565          tx = find_transaction(chan, NULL, args.opt, 0);
01566       }
01567       if (!tx) {
01568          pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "FAILED_TO_CREATE");
01569          return -1;
01570       }
01571       if (isolation == 0) {
01572          pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "INVALID_VALUE");
01573          ast_log(LOG_ERROR, "Invalid isolation specification: '%s'\n", S_OR(value, ""));
01574       } else if (SQLSetConnectAttr(tx->obj->con, SQL_ATTR_TXN_ISOLATION, (void *)(long)isolation, 0) == SQL_ERROR) {
01575          pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "SQL_ERROR");
01576          SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
01577          for (i = 0; i < numfields; i++) {
01578             SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
01579             ast_log(LOG_WARNING, "SetConnectAttr (Txn isolation) returned an error: %s: %s\n", state, diagnostic);
01580             if (i > 10) {
01581                ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
01582                break;
01583             }
01584          }
01585       } else {
01586          pbx_builtin_setvar_helper(chan, "ODBC_RESULT", "OK");
01587          tx->isolation = isolation;
01588       }
01589       return 0;
01590    } else {
01591       ast_log(LOG_ERROR, "Unknown property: '%s'\n", args.property);
01592       return -1;
01593    }
01594 }

static int aoro2_class_cb ( void *  obj,
void *  arg,
int  flags 
) [static]

Definition at line 1127 of file res_odbc.c.

References CMP_MATCH, CMP_STOP, and odbc_class::name.

Referenced by ast_odbc_request_obj2().

01128 {
01129    struct odbc_class *class = obj;
01130    char *name = arg;
01131    if (!strcmp(class->name, name) && !class->delme) {
01132       return CMP_MATCH | CMP_STOP;
01133    }
01134    return 0;
01135 }

static int aoro2_obj_cb ( void *  vobj,
void *  arg,
int  flags 
) [static]

Definition at line 1141 of file res_odbc.c.

References ast_mutex_lock(), ast_mutex_unlock(), CMP_MATCH, CMP_STOP, EOR_TX, odbc_obj::lock, NO_TX, odbc_obj::tx, USE_TX, and odbc_obj::used.

Referenced by ast_odbc_request_obj2().

01142 {
01143    struct odbc_obj *obj = vobj;
01144    ast_mutex_lock(&obj->lock);
01145    if ((arg == NO_TX && !obj->tx) || (arg == EOR_TX && !obj->used) || (arg == USE_TX && obj->tx && !obj->used)) {
01146       obj->used = 1;
01147       ast_mutex_unlock(&obj->lock);
01148       return CMP_MATCH | CMP_STOP;
01149    }
01150    ast_mutex_unlock(&obj->lock);
01151    return 0;
01152 }

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:
buf Address of the pointer to the ast_str structure.
pmaxlen The maximum size of the resulting string, or 0 for no limit.
StatementHandle The statement handle from which to retrieve data.
ColumnNumber Column number (1-based offset) for which to retrieve data.
TargetType The SQL constant indicating what kind of data is to be retrieved (usually SQL_CHAR)
StrLen_or_Ind A pointer to a length indicator, specifying the total length of data.

Definition at line 679 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().

00680 {
00681    SQLRETURN res;
00682 
00683    if (pmaxlen == 0) {
00684       if (SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), 0, StrLen_or_Ind) == SQL_SUCCESS_WITH_INFO) {
00685          ast_str_make_space(buf, *StrLen_or_Ind + 1);
00686       }
00687    } else if (pmaxlen > 0) {
00688       ast_str_make_space(buf, pmaxlen);
00689    }
00690    res = SQLGetData(StatementHandle, ColumnNumber, TargetType, ast_str_buffer(*buf), ast_str_size(*buf), StrLen_or_Ind);
00691    ast_str_update(*buf);
00692 
00693    return res;
00694 }

int ast_odbc_backslash_is_escape ( struct odbc_obj *  obj  ) 

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

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

Definition at line 1048 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().

01049 {
01050    return obj->parent->backslash_is_escape;
01051 }

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

Remove a cache entry from memory.

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

Definition at line 551 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.

00552 {
00553    struct odbc_cache_tables *tableptr;
00554 
00555    AST_RWLIST_WRLOCK(&odbc_tables);
00556    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&odbc_tables, tableptr, list) {
00557       if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
00558          AST_LIST_REMOVE_CURRENT(list);
00559          destroy_table_cache(tableptr);
00560          break;
00561       }
00562    }
00563    AST_RWLIST_TRAVERSE_SAFE_END
00564    AST_RWLIST_UNLOCK(&odbc_tables);
00565    return tableptr ? 0 : -1;
00566 }

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:
obj The ODBC object
exec_cb A function callback, which, when called, should return a statement handle with result columns bound.
data A parameter to be passed to the exec_cb parameter function, indicating which statement handle is to be prepared.
Return values:
a statement handle
NULL on error

Definition at line 568 of file res_odbc.c.

References ast_log(), ast_odbc_sanity_check(), odbc_class::dsn, LOG_WARNING, odbc_class::name, odbc_obj::parent, and odbc_obj::tx.

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

00569 {
00570    int attempt;
00571    SQLHSTMT stmt;
00572 
00573    for (attempt = 0; attempt < 2; attempt++) {
00574       stmt = exec_cb(obj, data);
00575 
00576       if (stmt) {
00577          break;
00578       } else if (obj->tx) {
00579          ast_log(LOG_WARNING, "Failed to execute, but unable to reconnect, as we're transactional.\n");
00580          break;
00581       } else if (attempt == 0) {
00582          ast_log(LOG_WARNING, "SQL Execute error! Verifying connection to %s [%s]...\n", obj->parent->name, obj->parent->dsn);
00583       }
00584       if (!ast_odbc_sanity_check(obj)) {
00585          break;
00586       }
00587    }
00588 
00589    return stmt;
00590 }

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

Find a column entry within a cached table structure.

Parameters:
table Cached table structure, as returned from ast_odbc_find_table()
colname The column name requested
Return values:
A structure describing the column type, or NULL, if the column is not found.
Since:
1.6.1

Definition at line 540 of file res_odbc.c.

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

Referenced by update2_prepare(), and update_odbc().

00541 {
00542    struct odbc_cache_columns *col;
00543    AST_RWLIST_TRAVERSE(&table->columns, col, list) {
00544       if (strcasecmp(col->name, colname) == 0) {
00545          return col;
00546       }
00547    }
00548    return NULL;
00549 }

struct odbc_cache_tables* ast_odbc_find_table ( const char *  database,
const char *  tablename 
) [read]

Find or create an entry describing the table specified.

Parameters:
database Name of an ODBC class on which to query the table
tablename Tablename to describe
Return values:
A structure 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.
Since:
1.6.1

Definition at line 425 of file res_odbc.c.

References ast_calloc, AST_LIST_INSERT_TAIL, ast_log(), ast_odbc_release_obj(), ast_odbc_request_obj(), ast_odbc_sanity_check(), AST_RWLIST_HEAD_INIT, AST_RWLIST_INSERT_TAIL, AST_RWLIST_RDLOCK, AST_RWLIST_TRAVERSE, AST_RWLIST_UNLOCK, ast_verb, odbc_cache_tables::columns, odbc_obj::con, odbc_cache_tables::connection, odbc_cache_columns::decimals, destroy_table_cache(), odbc_class::list, LOG_ERROR, LOG_WARNING, odbc_cache_columns::name, 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_prepare(), and update_odbc().

00426 {
00427    struct odbc_cache_tables *tableptr;
00428    struct odbc_cache_columns *entry;
00429    char columnname[80];
00430    SQLLEN sqlptr;
00431    SQLHSTMT stmt = NULL;
00432    int res = 0, error = 0, try = 0;
00433    struct odbc_obj *obj = ast_odbc_request_obj(database, 0);
00434 
00435    AST_RWLIST_RDLOCK(&odbc_tables);
00436    AST_RWLIST_TRAVERSE(&odbc_tables, tableptr, list) {
00437       if (strcmp(tableptr->connection, database) == 0 && strcmp(tableptr->table, tablename) == 0) {
00438          break;
00439       }
00440    }
00441    if (tableptr) {
00442       AST_RWLIST_RDLOCK(&tableptr->columns);
00443       AST_RWLIST_UNLOCK(&odbc_tables);
00444       if (obj) {
00445          ast_odbc_release_obj(obj);
00446       }
00447       return tableptr;
00448    }
00449 
00450    if (!obj) {
00451       ast_log(LOG_WARNING, "Unable to retrieve database handle for table description '%s@%s'\n", tablename, database);
00452       AST_RWLIST_UNLOCK(&odbc_tables);
00453       return NULL;
00454    }
00455 
00456    /* Table structure not already cached; build it now. */
00457    do {
00458       res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
00459       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
00460          if (try == 0) {
00461             try = 1;
00462             ast_odbc_sanity_check(obj);
00463             continue;
00464          }
00465          ast_log(LOG_WARNING, "SQL Alloc Handle failed on connection '%s'!\n", database);
00466          break;
00467       }
00468 
00469       res = SQLColumns(stmt, NULL, 0, NULL, 0, (unsigned char *)tablename, SQL_NTS, (unsigned char *)"%", SQL_NTS);
00470       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
00471          if (try == 0) {
00472             try = 1;
00473             SQLFreeHandle(SQL_HANDLE_STMT, stmt);
00474             ast_odbc_sanity_check(obj);
00475             continue;
00476          }
00477          ast_log(LOG_ERROR, "Unable to query database columns on connection '%s'.\n", database);
00478          break;
00479       }
00480 
00481       if (!(tableptr = ast_calloc(sizeof(char), sizeof(*tableptr) + strlen(database) + 1 + strlen(tablename) + 1))) {
00482          ast_log(LOG_ERROR, "Out of memory creating entry for table '%s' on connection '%s'\n", tablename, database);
00483          break;
00484       }
00485 
00486       tableptr->connection = (char *)tableptr + sizeof(*tableptr);
00487       tableptr->table = (char *)tableptr + sizeof(*tableptr) + strlen(database) + 1;
00488       strcpy(tableptr->connection, database); /* SAFE */
00489       strcpy(tableptr->table, tablename); /* SAFE */
00490       AST_RWLIST_HEAD_INIT(&(tableptr->columns));
00491 
00492       while ((res = SQLFetch(stmt)) != SQL_NO_DATA && res != SQL_ERROR) {
00493          SQLGetData(stmt,  4, SQL_C_CHAR, columnname, sizeof(columnname), &sqlptr);
00494 
00495          if (!(entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(columnname) + 1))) {
00496             ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s' on connection '%s'\n", columnname, tablename, database);
00497             error = 1;
00498             break;
00499          }
00500          entry->name = (char *)entry + sizeof(*entry);
00501          strcpy(entry->name, columnname);
00502 
00503          SQLGetData(stmt,  5, SQL_C_SHORT, &entry->type, sizeof(entry->type), NULL);
00504          SQLGetData(stmt,  7, SQL_C_LONG, &entry->size, sizeof(entry->size), NULL);
00505          SQLGetData(stmt,  9, SQL_C_SHORT, &entry->decimals, sizeof(entry->decimals), NULL);
00506          SQLGetData(stmt, 10, SQL_C_SHORT, &entry->radix, sizeof(entry->radix), NULL);
00507          SQLGetData(stmt, 11, SQL_C_SHORT, &entry->nullable, sizeof(entry->nullable), NULL);
00508          SQLGetData(stmt, 16, SQL_C_LONG, &entry->octetlen, sizeof(entry->octetlen), NULL);
00509 
00510          /* Specification states that the octenlen should be the maximum number of bytes
00511           * returned in a char or binary column, but it seems that some drivers just set
00512           * it to NULL. (Bad Postgres! No biscuit!) */
00513          if (entry->octetlen == 0) {
00514             entry->octetlen = entry->size;
00515          }
00516 
00517          ast_verb(10, "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);
00518          /* Insert column info into column list */
00519          AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
00520       }
00521       SQLFreeHandle(SQL_HANDLE_STMT, stmt);
00522 
00523       AST_RWLIST_INSERT_TAIL(&odbc_tables, tableptr, list);
00524       AST_RWLIST_RDLOCK(&(tableptr->columns));
00525       break;
00526    } while (1);
00527 
00528    AST_RWLIST_UNLOCK(&odbc_tables);
00529 
00530    if (error) {
00531       destroy_table_cache(tableptr);
00532       tableptr = NULL;
00533    }
00534    if (obj) {
00535       ast_odbc_release_obj(obj);
00536    }
00537    return tableptr;
00538 }

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:
obj The ODBC object
prepare_cb A function callback, which, when called, should return a statement handle prepared, with any necessary parameters or result columns bound.
data A parameter to be passed to the prepare_cb parameter function, indicating which statement handle is to be prepared.
Return values:
a statement handle
NULL on error

Definition at line 592 of file res_odbc.c.

References ast_log(), ast_odbc_sanity_check(), ast_tvnow(), odbc_class::dsn, odbc_obj::last_used, LOG_WARNING, odbc_class::name, odbc_obj::parent, odbc_obj::tx, and odbc_obj::up.

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

00593 {
00594    int res = 0, i, attempt;
00595    SQLINTEGER nativeerror=0, numfields=0;
00596    SQLSMALLINT diagbytes=0;
00597    unsigned char state[10], diagnostic[256];
00598    SQLHSTMT stmt;
00599 
00600    for (attempt = 0; attempt < 2; attempt++) {
00601       /* This prepare callback may do more than just prepare -- it may also
00602        * bind parameters, bind results, etc.  The real key, here, is that
00603        * when we disconnect, all handles become invalid for most databases.
00604        * We must therefore redo everything when we establish a new
00605        * connection. */
00606       stmt = prepare_cb(obj, data);
00607 
00608       if (stmt) {
00609          res = SQLExecute(stmt);
00610          if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
00611             if (res == SQL_ERROR) {
00612                SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
00613                for (i = 0; i < numfields; i++) {
00614                   SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
00615                   ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
00616                   if (i > 10) {
00617                      ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
00618                      break;
00619                   }
00620                }
00621             }
00622 
00623             if (obj->tx) {
00624                ast_log(LOG_WARNING, "SQL Execute error, but unable to reconnect, as we're transactional.\n");
00625                break;
00626             } else {
00627                ast_log(LOG_WARNING, "SQL Execute error %d! Verifying connection to %s [%s]...\n", res, obj->parent->name, obj->parent->dsn);
00628                SQLFreeHandle(SQL_HANDLE_STMT, stmt);
00629                stmt = NULL;
00630 
00631                obj->up = 0;
00632                /*
00633                 * While this isn't the best way to try to correct an error, this won't automatically
00634                 * fail when the statement handle invalidates.
00635                 */
00636                if (!ast_odbc_sanity_check(obj)) {
00637                   break;
00638                }
00639                continue;
00640             }
00641          } else {
00642             obj->last_used = ast_tvnow();
00643          }
00644          break;
00645       } else if (attempt == 0) {
00646          ast_odbc_sanity_check(obj);
00647       }
00648    }
00649 
00650    return stmt;
00651 }

void ast_odbc_release_obj ( struct odbc_obj *  obj  ) 

Releases an ODBC object previously allocated by odbc_request_obj().

Parameters:
obj The ODBC object

Definition at line 1042 of file res_odbc.c.

References find_transaction(), and odbc_release_obj2().

Referenced by acf_odbc_read(), acf_odbc_write(), ast_odbc_find_table(), cli_odbc_read(), cli_odbc_write(), config_odbc(), destroy_odbc(), load_config(), odbc_log(), odbc_register_class(), realtime_multi_odbc(), realtime_odbc(), store_odbc(), update2_odbc(), and update_odbc().

01043 {
01044    struct odbc_txn_frame *tx = find_transaction(NULL, obj, NULL, 0);
01045    odbc_release_obj2(obj, tx);
01046 }

struct odbc_obj* ast_odbc_request_obj ( const char *  name,
int  check 
) [read]

Definition at line 1332 of file res_odbc.c.

References ast_odbc_request_obj2(), and RES_ODBC_SANITY_CHECK.

Referenced by acf_odbc_read(), acf_odbc_write(), ast_odbc_find_table(), cli_odbc_read(), cli_odbc_write(), config_odbc(), destroy_odbc(), load_config(), odbc_log(), odbc_register_class(), realtime_multi_odbc(), realtime_odbc(), store_odbc(), update2_odbc(), and update_odbc().

01334 {
01335    struct ast_flags flags = { check ? RES_ODBC_SANITY_CHECK : 0 };
01336 #ifdef DEBUG_THREADS
01337    return _ast_odbc_request_obj2(name, flags, file, function, lineno);
01338 #else
01339    return ast_odbc_request_obj2(name, flags);
01340 #endif
01341 }

struct odbc_obj* ast_odbc_request_obj2 ( const char *  name,
struct ast_flags  flags 
) [read]

Retrieves a connected ODBC object.

Parameters:
name The name of the ODBC class for which a connection is needed.
flags Set of flags used to control which connection is returned.
Return values:
ODBC object
NULL if there is no connection available with the requested name.
Connection classes may, in fact, contain multiple connection handles. If the connection is pooled, then each connection will be dedicated to the thread which requests it. Note that all connections should be released when the thread is done by calling odbc_release_obj(), below.

Definition at line 1157 of file res_odbc.c.

References ao2_alloc, ao2_callback, ao2_link, ao2_ref, aoro2_class_cb(), aoro2_obj_cb(), ast_assert, ast_atomic_fetchadd_int(), ast_copy_string(), ast_log(), ast_mutex_init(), ast_odbc_sanity_check(), ast_test_flag, ast_tvdiff_sec(), ast_tvnow(), class_container, odbc_obj::con, odbc_class::count, EOR_TX, odbc_class::idlecheck, odbc_class::isolation, odbc_obj::last_used, odbc_obj::lock, LOG_WARNING, NO_TX, odbc_class::obj_container, ODBC_FAIL, odbc_obj_connect(), odbc_obj_destructor(), odbc_obj::parent, RES_ODBC_INDEPENDENT_CONNECTION, RES_ODBC_SANITY_CHECK, USE_TX, and odbc_obj::used.

Referenced by acf_transaction_write(), and ast_odbc_request_obj().

01159 {
01160    struct odbc_obj *obj = NULL;
01161    struct odbc_class *class;
01162    SQLINTEGER nativeerror=0, numfields=0;
01163    SQLSMALLINT diagbytes=0, i;
01164    unsigned char state[10], diagnostic[256];
01165 
01166    if (!(class = ao2_callback(class_container, 0, aoro2_class_cb, (char *) name))) {
01167       return NULL;
01168    }
01169 
01170    ast_assert(ao2_ref(class, 0) > 1);
01171 
01172    if (class->haspool) {
01173       /* Recycle connections before building another */
01174       obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, EOR_TX);
01175 
01176       if (obj) {
01177          ast_assert(ao2_ref(obj, 0) > 1);
01178       }
01179 
01180       if (!obj && (class->count < class->limit)) {
01181          obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
01182          if (!obj) {
01183             ao2_ref(class, -1);
01184             return NULL;
01185          }
01186          ast_assert(ao2_ref(obj, 0) == 1);
01187          ast_mutex_init(&obj->lock);
01188          /* obj inherits the outstanding reference to class */
01189          obj->parent = class;
01190          class = NULL;
01191          if (odbc_obj_connect(obj) == ODBC_FAIL) {
01192             ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
01193             ao2_ref(obj, -1);
01194             ast_assert(ao2_ref(class, 0) > 0);
01195             obj = NULL;
01196          } else {
01197             obj->used = 1;
01198             ao2_link(obj->parent->obj_container, obj);
01199             ast_atomic_fetchadd_int(&obj->parent->count, +1);
01200          }
01201       } else {
01202          /* Object is not constructed, so delete outstanding reference to class. */
01203          ao2_ref(class, -1);
01204          class = NULL;
01205       }
01206 
01207       if (obj && ast_test_flag(&flags, RES_ODBC_INDEPENDENT_CONNECTION)) {
01208          /* Ensure this connection has autocommit turned off. */
01209          if (SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_OFF, 0) == SQL_ERROR) {
01210             SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
01211             for (i = 0; i < numfields; i++) {
01212                SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
01213                ast_log(LOG_WARNING, "SQLSetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
01214                if (i > 10) {
01215                   ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
01216                   break;
01217                }
01218             }
01219          }
01220       }
01221    } else if (ast_test_flag(&flags, RES_ODBC_INDEPENDENT_CONNECTION)) {
01222       /* Non-pooled connections -- but must use a separate connection handle */
01223       if (!(obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, USE_TX))) {
01224          obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor);
01225          if (!obj) {
01226             ao2_ref(class, -1);
01227             return NULL;
01228          }
01229          ast_mutex_init(&obj->lock);
01230          /* obj inherits the outstanding reference to class */
01231          obj->parent = class;
01232          class = NULL;
01233          if (odbc_obj_connect(obj) == ODBC_FAIL) {
01234             ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
01235             ao2_ref(obj, -1);
01236             obj = NULL;
01237          } else {
01238             obj->used = 1;
01239             ao2_link(obj->parent->obj_container, obj);
01240             ast_atomic_fetchadd_int(&obj->parent->count, +1);
01241          }
01242       }
01243 
01244       if (obj && SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_OFF, 0) == SQL_ERROR) {
01245          SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
01246          for (i = 0; i < numfields; i++) {
01247             SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
01248             ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
01249             if (i > 10) {
01250                ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
01251                break;
01252             }
01253          }
01254       }
01255    } else {
01256       /* Non-pooled connection: multiple modules can use the same connection. */
01257       if ((obj = ao2_callback(class->obj_container, 0, aoro2_obj_cb, NO_TX))) {
01258          /* Object is not constructed, so delete outstanding reference to class. */
01259          ast_assert(ao2_ref(class, 0) > 1);
01260          ao2_ref(class, -1);
01261          class = NULL;
01262       } else {
01263          /* No entry: build one */
01264          if (!(obj = ao2_alloc(sizeof(*obj), odbc_obj_destructor))) {
01265             ast_assert(ao2_ref(class, 0) > 1);
01266             ao2_ref(class, -1);
01267             return NULL;
01268          }
01269          ast_mutex_init(&obj->lock);
01270          /* obj inherits the outstanding reference to class */
01271          obj->parent = class;
01272          class = NULL;
01273          if (odbc_obj_connect(obj) == ODBC_FAIL) {
01274             ast_log(LOG_WARNING, "Failed to connect to %s\n", name);
01275             ao2_ref(obj, -1);
01276             obj = NULL;
01277          } else {
01278             ao2_link(obj->parent->obj_container, obj);
01279             ast_assert(ao2_ref(obj, 0) > 1);
01280          }
01281       }
01282 
01283       if (obj && SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_ON, 0) == SQL_ERROR) {
01284          SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
01285          for (i = 0; i < numfields; i++) {
01286             SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
01287             ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
01288             if (i > 10) {
01289                ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
01290                break;
01291             }
01292          }
01293       }
01294    }
01295 
01296    /* Set the isolation property */
01297    if (obj && SQLSetConnectAttr(obj->con, SQL_ATTR_TXN_ISOLATION, (void *)(long)obj->parent->isolation, 0) == SQL_ERROR) {
01298       SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
01299       for (i = 0; i < numfields; i++) {
01300          SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
01301          ast_log(LOG_WARNING, "SetConnectAttr (Txn isolation) returned an error: %s: %s\n", state, diagnostic);
01302          if (i > 10) {
01303             ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
01304             break;
01305          }
01306       }
01307    }
01308 
01309    if (obj && ast_test_flag(&flags, RES_ODBC_SANITY_CHECK)) {
01310       ast_odbc_sanity_check(obj);
01311    } else if (obj && obj->parent->idlecheck > 0 && ast_tvdiff_sec(ast_tvnow(), obj->last_used) > obj->parent->idlecheck)
01312       odbc_obj_connect(obj);
01313 
01314 #ifdef DEBUG_THREADS
01315    if (obj) {
01316       ast_copy_string(obj->file, file, sizeof(obj->file));
01317       ast_copy_string(obj->function, function, sizeof(obj->function));
01318       obj->lineno = lineno;
01319    }
01320 #endif
01321    ast_assert(class == NULL);
01322 
01323    if (obj) {
01324       ast_assert(ao2_ref(obj, 0) > 1);
01325    }
01326    return obj;
01327 }

struct odbc_obj* ast_odbc_retrieve_transaction_obj ( struct ast_channel *  chan,
const char *  objname 
) [read]

Retrieve a stored ODBC object, if a transaction has been started.

Parameters:
chan Channel associated with the transaction.
objname Name of the database handle. This name corresponds to the name passed to
See also:
ast_odbc_request_obj2 (or formerly, to ast_odbc_request_obj). Note that the existence of this parameter name explicitly allows for multiple transactions to be open at once, albeit to different databases.
Return values:
A stored ODBC object, if a transaction was already started.
NULL,if no transaction yet exists.

Definition at line 1343 of file res_odbc.c.

References ast_channel_datastore_find(), ast_channel_lock, ast_channel_unlock, AST_LIST_HEAD, AST_LIST_LOCK, AST_LIST_TRAVERSE, AST_LIST_UNLOCK, ast_datastore::data, odbc_class::list, odbc_class::name, odbc_txn_frame::obj, odbc_obj::parent, and txn_info.

Referenced by acf_odbc_write().

01344 {
01345    struct ast_datastore *txn_store;
01346    AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
01347    struct odbc_txn_frame *txn = NULL;
01348 
01349    if (!chan) {
01350       /* No channel == no transaction */
01351       return NULL;
01352    }
01353 
01354    ast_channel_lock(chan);
01355    if ((txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
01356       oldlist = txn_store->data;
01357    } else {
01358       ast_channel_unlock(chan);
01359       return NULL;
01360    }
01361 
01362    AST_LIST_LOCK(oldlist);
01363    ast_channel_unlock(chan);
01364 
01365    AST_LIST_TRAVERSE(oldlist, txn, list) {
01366       if (txn->obj && txn->obj->parent && !strcmp(txn->obj->parent->name, objname)) {
01367          AST_LIST_UNLOCK(oldlist);
01368          return txn->obj;
01369       }
01370    }
01371    AST_LIST_UNLOCK(oldlist);
01372    return NULL;
01373 }

int ast_odbc_sanity_check ( struct odbc_obj *  obj  ) 

Checks an ODBC object to ensure it is still connected.

Parameters:
obj The ODBC object
Return values:
0 if connected
-1 otherwise.

Definition at line 696 of file res_odbc.c.

References ast_log(), ast_strlen_zero(), odbc_obj::con, LOG_WARNING, odbc_obj_connect(), odbc_obj_disconnect(), odbc_obj::parent, odbc_class::sanitysql, odbc_obj::tx, and odbc_obj::up.

Referenced by ast_odbc_direct_execute(), ast_odbc_find_table(), ast_odbc_prepare_and_execute(), ast_odbc_request_obj2(), and handle_cli_odbc_show().

00697 {
00698    char *test_sql = "select 1";
00699    SQLHSTMT stmt;
00700    int res = 0;
00701 
00702    if (!ast_strlen_zero(obj->parent->sanitysql))
00703       test_sql = obj->parent->sanitysql;
00704 
00705    if (obj->up) {
00706       res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
00707       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
00708          obj->up = 0;
00709       } else {
00710          res = SQLPrepare(stmt, (unsigned char *)test_sql, SQL_NTS);
00711          if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
00712             obj->up = 0;
00713          } else {
00714             res = SQLExecute(stmt);
00715             if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
00716                obj->up = 0;
00717             }
00718          }
00719       }
00720       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
00721    }
00722 
00723    if (!obj->up && !obj->tx) { /* Try to reconnect! */
00724       ast_log(LOG_WARNING, "Connection is down attempting to reconnect...\n");
00725       odbc_obj_disconnect(obj);
00726       odbc_obj_connect(obj);
00727    }
00728    return obj->up;
00729 }

int ast_odbc_smart_execute ( struct odbc_obj *  obj,
SQLHSTMT  stmt 
)

Executes a prepared statement handle.

Parameters:
obj The non-NULL result of odbc_request_obj()
stmt The prepared statement handle
Return values:
0 on success
-1 on 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 653 of file res_odbc.c.

References ast_log(), ast_tvnow(), odbc_obj::last_used, and LOG_WARNING.

00654 {
00655    int res = 0, i;
00656    SQLINTEGER nativeerror=0, numfields=0;
00657    SQLSMALLINT diagbytes=0;
00658    unsigned char state[10], diagnostic[256];
00659 
00660    res = SQLExecute(stmt);
00661    if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO) && (res != SQL_NO_DATA)) {
00662       if (res == SQL_ERROR) {
00663          SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
00664          for (i = 0; i < numfields; i++) {
00665             SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
00666             ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
00667             if (i > 10) {
00668                ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
00669                break;
00670             }
00671          }
00672       }
00673    } else
00674       obj->last_used = ast_tvnow();
00675    
00676    return res;
00677 }

static int commit_exec ( struct ast_channel *  chan,
void *  data 
) [static]

Definition at line 1053 of file res_odbc.c.

References ast_log(), ast_str_append(), ast_str_buffer(), ast_str_reset(), ast_str_strlen(), ast_str_thread_get(), ast_strlen_zero(), odbc_obj::con, errors_buf, find_transaction(), LOG_WARNING, odbc_txn_frame::obj, and pbx_builtin_setvar_helper().

Referenced by load_module().

01054 {
01055    struct odbc_txn_frame *tx;
01056    SQLINTEGER nativeerror=0, numfields=0;
01057    SQLSMALLINT diagbytes=0, i;
01058    unsigned char state[10], diagnostic[256];
01059 
01060    if (ast_strlen_zero(data)) {
01061       tx = find_transaction(chan, NULL, NULL, 1);
01062    } else {
01063       tx = find_transaction(chan, NULL, data, 0);
01064    }
01065 
01066    pbx_builtin_setvar_helper(chan, "COMMIT_RESULT", "OK");
01067 
01068    if (tx) {
01069       if (SQLEndTran(SQL_HANDLE_DBC, tx->obj->con, SQL_COMMIT) == SQL_ERROR) {
01070          struct ast_str *errors = ast_str_thread_get(&errors_buf, 16);
01071          ast_str_reset(errors);
01072 
01073          /* Handle possible transaction commit failure */
01074          SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
01075          for (i = 0; i < numfields; i++) {
01076             SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
01077             ast_str_append(&errors, 0, "%s%s", ast_str_strlen(errors) ? "," : "", state);
01078             ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
01079             if (i > 10) {
01080                ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
01081                break;
01082             }
01083          }
01084          pbx_builtin_setvar_helper(chan, "COMMIT_RESULT", ast_str_buffer(errors));
01085       }
01086    }
01087    return 0;
01088 }

static void destroy_table_cache ( struct odbc_cache_tables *  table  )  [static]

Definition at line 404 of file res_odbc.c.

References ast_debug, ast_free, AST_RWLIST_HEAD_DESTROY, AST_RWLIST_REMOVE_HEAD, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, odbc_cache_tables::columns, odbc_class::list, and odbc_cache_tables::table.

Referenced by ast_odbc_clear_cache(), ast_odbc_find_table(), and reload().

00404                                                                  {
00405    struct odbc_cache_columns *col;
00406    ast_debug(1, "Destroying table cache for %s\n", table->table);
00407    AST_RWLIST_WRLOCK(&table->columns);
00408    while ((col = AST_RWLIST_REMOVE_HEAD(&table->columns, list))) {
00409       ast_free(col);
00410    }
00411    AST_RWLIST_UNLOCK(&table->columns);
00412    AST_RWLIST_HEAD_DESTROY(&table->columns);
00413    ast_free(table);
00414 }

static struct odbc_txn_frame* find_transaction ( struct ast_channel *  chan,
struct odbc_obj *  obj,
const char *  name,
int  active 
) [static, read]

Definition at line 204 of file res_odbc.c.

References odbc_txn_frame::active, ast_calloc, ast_channel_datastore_add(), ast_channel_datastore_find(), ast_channel_lock, ast_channel_unlock, ast_datastore_alloc, ast_datastore_free(), AST_LIST_HEAD, AST_LIST_HEAD_INIT, AST_LIST_INSERT_TAIL, AST_LIST_LOCK, AST_LIST_TRAVERSE, AST_LIST_UNLOCK, ast_log(), ast_datastore::data, odbc_class::forcecommit, odbc_txn_frame::forcecommit, odbc_class::isolation, odbc_txn_frame::isolation, odbc_class::list, LOG_ERROR, odbc_txn_frame::name, odbc_txn_frame::obj, odbc_txn_frame::owner, odbc_obj::parent, odbc_obj::tx, odbc_obj::txf, and txn_info.

Referenced by acf_transaction_read(), acf_transaction_write(), ast_odbc_release_obj(), commit_exec(), and rollback_exec().

00205 {
00206    struct ast_datastore *txn_store;
00207    AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
00208    struct odbc_txn_frame *txn = NULL;
00209 
00210    if (!chan && obj && obj->txf && obj->txf->owner) {
00211       chan = obj->txf->owner;
00212    } else if (!chan) {
00213       /* No channel == no transaction */
00214       return NULL;
00215    }
00216 
00217    ast_channel_lock(chan);
00218    if ((txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
00219       oldlist = txn_store->data;
00220    } else {
00221       /* Need to create a new datastore */
00222       if (!(txn_store = ast_datastore_alloc(&txn_info, NULL))) {
00223          ast_log(LOG_ERROR, "Unable to allocate a new datastore.  Cannot create a new transaction.\n");
00224          ast_channel_unlock(chan);
00225          return NULL;
00226       }
00227 
00228       if (!(oldlist = ast_calloc(1, sizeof(*oldlist)))) {
00229          ast_log(LOG_ERROR, "Unable to allocate datastore list head.  Cannot create a new transaction.\n");
00230          ast_datastore_free(txn_store);
00231          ast_channel_unlock(chan);
00232          return NULL;
00233       }
00234 
00235       txn_store->data = oldlist;
00236       AST_LIST_HEAD_INIT(oldlist);
00237       ast_channel_datastore_add(chan, txn_store);
00238    }
00239 
00240    AST_LIST_LOCK(oldlist);
00241    ast_channel_unlock(chan);
00242 
00243    /* Scanning for an object is *fast*.  Scanning for a name is much slower. */
00244    if (obj != NULL || active == 1) {
00245       AST_LIST_TRAVERSE(oldlist, txn, list) {
00246          if (txn->obj == obj || txn->active) {
00247             AST_LIST_UNLOCK(oldlist);
00248             return txn;
00249          }
00250       }
00251    }
00252 
00253    if (name != NULL) {
00254       AST_LIST_TRAVERSE(oldlist, txn, list) {
00255          if (!strcasecmp(txn->name, name)) {
00256             AST_LIST_UNLOCK(oldlist);
00257             return txn;
00258          }
00259       }
00260    }
00261 
00262    /* Nothing found, create one */
00263    if (name && obj && (txn = ast_calloc(1, sizeof(*txn) + strlen(name) + 1))) {
00264       struct odbc_txn_frame *otxn;
00265 
00266       strcpy(txn->name, name); /* SAFE */
00267       txn->obj = obj;
00268       txn->isolation = obj->parent->isolation;
00269       txn->forcecommit = obj->parent->forcecommit;
00270       txn->owner = chan;
00271       txn->active = 1;
00272 
00273       /* On creation, the txn becomes active, and all others inactive */
00274       AST_LIST_TRAVERSE(oldlist, otxn, list) {
00275          otxn->active = 0;
00276       }
00277       AST_LIST_INSERT_TAIL(oldlist, txn, list);
00278 
00279       obj->txf = txn;
00280       obj->tx = 1;
00281    }
00282    AST_LIST_UNLOCK(oldlist);
00283 
00284    return txn;
00285 }

static char* handle_cli_odbc_show ( struct ast_cli_entry *  e,
int  cmd,
struct ast_cli_args *  a 
) [static]

Definition at line 872 of file res_odbc.c.

References ao2_iterator_destroy(), ao2_iterator_init(), ao2_iterator_next, ao2_ref, ast_cli_args::argc, ast_cli_args::argv, ast_cli(), ast_mutex_lock(), ast_mutex_unlock(), ast_odbc_sanity_check(), ast_strdup, class_container, CLI_GENERATE, CLI_INIT, CLI_SUCCESS, ast_cli_entry::command, odbc_class::count, ast_cli_args::fd, odbc_obj::lock, ast_cli_args::n, ast_cli_args::pos, odbc_obj::up, ast_cli_entry::usage, odbc_obj::used, and ast_cli_args::word.

00873 {
00874    struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
00875    struct odbc_class *class;
00876    struct odbc_obj *current;
00877    int length = 0;
00878    int which = 0;
00879    char *ret = NULL;
00880 
00881    switch (cmd) {
00882    case CLI_INIT:
00883       e->command = "odbc show";
00884       e->usage =
00885             "Usage: odbc show [class]\n"
00886             "       List settings of a particular ODBC class or,\n"
00887             "       if not specified, all classes.\n";
00888       return NULL;
00889    case CLI_GENERATE:
00890       if (a->pos != 2)
00891          return NULL;
00892       length = strlen(a->word);
00893       while ((class = ao2_iterator_next(&aoi))) {
00894          if (!strncasecmp(a->word, class->name, length) && ++which > a->n) {
00895             ret = ast_strdup(class->name);
00896          }
00897          ao2_ref(class, -1);
00898          if (ret) {
00899             break;
00900          }
00901       }
00902       ao2_iterator_destroy(&aoi);
00903       if (!ret && !strncasecmp(a->word, "all", length) && ++which > a->n) {
00904          ret = ast_strdup("all");
00905       }
00906       return ret;
00907    }
00908 
00909    ast_cli(a->fd, "\nODBC DSN Settings\n");
00910    ast_cli(a->fd,   "-----------------\n\n");
00911    aoi = ao2_iterator_init(class_container, 0);
00912    while ((class = ao2_iterator_next(&aoi))) {
00913       if ((a->argc == 2) || (a->argc == 3 && !strcmp(a->argv[2], "all")) || (!strcmp(a->argv[2], class->name))) {
00914          int count = 0;
00915          ast_cli(a->fd, "  Name:   %s\n  DSN:    %s\n", class->name, class->dsn);
00916 
00917          if (class->haspool) {
00918             struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
00919 
00920             ast_cli(a->fd, "  Pooled: Yes\n  Limit:  %d\n  Connections in use: %d\n", class->limit, class->count);
00921 
00922             while ((current = ao2_iterator_next(&aoi2))) {
00923                ast_mutex_lock(&current->lock);
00924 #ifdef DEBUG_THREADS
00925                ast_cli(a->fd, "    - Connection %d: %s (%s:%d %s)\n", ++count,
00926                   current->used ? "in use" :
00927                   current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected",
00928                   current->file, current->lineno, current->function);
00929 #else
00930                ast_cli(a->fd, "    - Connection %d: %s\n", ++count,
00931                   current->used ? "in use" :
00932                   current->up && ast_odbc_sanity_check(current) ? "connected" : "disconnected");
00933 #endif
00934                ast_mutex_unlock(&current->lock);
00935                ao2_ref(current, -1);
00936             }
00937             ao2_iterator_destroy(&aoi2);
00938          } else {
00939             /* Should only ever be one of these (unless there are transactions) */
00940             struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
00941             while ((current = ao2_iterator_next(&aoi2))) {
00942                ast_cli(a->fd, "  Pooled: No\n  Connected: %s\n", current->used ? "In use" :
00943                   current->up && ast_odbc_sanity_check(current) ? "Yes" : "No");
00944                ao2_ref(current, -1);
00945             }
00946             ao2_iterator_destroy(&aoi2);
00947          }
00948          ast_cli(a->fd, "\n");
00949       }
00950       ao2_ref(class, -1);
00951    }
00952    ao2_iterator_destroy(&aoi);
00953 
00954    return CLI_SUCCESS;
00955 }

static const char* isolation2text ( int  iso  )  [static]

Definition at line 170 of file res_odbc.c.

Referenced by acf_transaction_read().

00171 {
00172    if (iso == SQL_TXN_READ_COMMITTED) {
00173       return "read_committed";
00174    } else if (iso == SQL_TXN_READ_UNCOMMITTED) {
00175       return "read_uncommitted";
00176    } else if (iso == SQL_TXN_SERIALIZABLE) {
00177       return "serializable";
00178    } else if (iso == SQL_TXN_REPEATABLE_READ) {
00179       return "repeatable_read";
00180    } else {
00181       return "unknown";
00182    }
00183 }

static int load_module ( void   )  [static]

static int load_odbc_config ( void   )  [static]

Definition at line 731 of file res_odbc.c.

References ao2_alloc, ao2_container_alloc, ao2_match_by_addr, ao2_ref, ast_category_browse(), ast_config_destroy(), ast_config_load, ast_copy_string(), ast_false(), ast_log(), ast_strdup, ast_strlen_zero(), ast_true(), ast_variable_browse(), config, CONFIG_STATUS_FILEINVALID, CONFIG_STATUS_FILEMISSING, odbc_class::dsn, enabled, odbc_class::forcecommit, odbc_class::idlecheck, odbc_class::isolation, odbc_class::limit, LOG_ERROR, LOG_NOTICE, LOG_WARNING, ast_variable::name, ast_variable::next, null_hash_fn(), odbc_class_destructor(), odbc_register_class(), odbc_class::password, odbc_class::sanitysql, setenv(), text2isolation(), odbc_class::username, and ast_variable::value.

Referenced by load_module(), and reload().

00732 {
00733    static char *cfg = "res_odbc.conf";
00734    struct ast_config *config;
00735    struct ast_variable *v;
00736    char *cat;
00737    const char *dsn, *username, *password, *sanitysql;
00738    int enabled, pooling, limit, bse, forcecommit, isolation;
00739    unsigned int idlecheck;
00740    int preconnect = 0, res = 0;
00741    struct ast_flags config_flags = { 0 };
00742 
00743    struct odbc_class *new;
00744 
00745    config = ast_config_load(cfg, config_flags);
00746    if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
00747       ast_log(LOG_WARNING, "Unable to load config file res_odbc.conf\n");
00748       return -1;
00749    }
00750    for (cat = ast_category_browse(config, NULL); cat; cat=ast_category_browse(config, cat)) {
00751       if (!strcasecmp(cat, "ENV")) {
00752          for (v = ast_variable_browse(config, cat); v; v = v->next) {
00753             setenv(v->name, v->value, 1);
00754             ast_log(LOG_NOTICE, "Adding ENV var: %s=%s\n", v->name, v->value);
00755          }
00756       } else {
00757          /* Reset all to defaults for each class of odbc connections */
00758          dsn = username = password = sanitysql = NULL;
00759          enabled = 1;
00760          preconnect = idlecheck = 0;
00761          pooling = 0;
00762          limit = 0;
00763          bse = 1;
00764          forcecommit = 0;
00765          isolation = SQL_TXN_READ_COMMITTED;
00766          for (v = ast_variable_browse(config, cat); v; v = v->next) {
00767             if (!strcasecmp(v->name, "pooling")) {
00768                if (ast_true(v->value))
00769                   pooling = 1;
00770             } else if (!strncasecmp(v->name, "share", 5)) {
00771                /* "shareconnections" is a little clearer in meaning than "pooling" */
00772                if (ast_false(v->value))
00773                   pooling = 1;
00774             } else if (!strcasecmp(v->name, "limit")) {
00775                sscanf(v->value, "%30d", &limit);
00776                if (ast_true(v->value) && !limit) {
00777                   ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'.  Setting limit to 1023 for ODBC class '%s'.\n", v->value, cat);
00778                   limit = 1023;
00779                } else if (ast_false(v->value)) {
00780                   ast_log(LOG_WARNING, "Limit should be a number, not a boolean: '%s'.  Disabling ODBC class '%s'.\n", v->value, cat);
00781                   enabled = 0;
00782                   break;
00783                }
00784             } else if (!strcasecmp(v->name, "idlecheck")) {
00785                sscanf(v->value, "%30u", &idlecheck);
00786             } else if (!strcasecmp(v->name, "enabled")) {
00787                enabled = ast_true(v->value);
00788             } else if (!strcasecmp(v->name, "pre-connect")) {
00789                preconnect = ast_true(v->value);
00790             } else if (!strcasecmp(v->name, "dsn")) {
00791                dsn = v->value;
00792             } else if (!strcasecmp(v->name, "username")) {
00793                username = v->value;
00794             } else if (!strcasecmp(v->name, "password")) {
00795                password = v->value;
00796             } else if (!strcasecmp(v->name, "sanitysql")) {
00797                sanitysql = v->value;
00798             } else if (!strcasecmp(v->name, "backslash_is_escape")) {
00799                bse = ast_true(v->value);
00800             } else if (!strcasecmp(v->name, "forcecommit")) {
00801                forcecommit = ast_true(v->value);
00802             } else if (!strcasecmp(v->name, "isolation")) {
00803                if ((isolation = text2isolation(v->value)) == 0) {
00804                   ast_log(LOG_ERROR, "Unrecognized value for 'isolation': '%s' in section '%s'\n", v->value, cat);
00805                   isolation = SQL_TXN_READ_COMMITTED;
00806                }
00807             }
00808          }
00809 
00810          if (enabled && !ast_strlen_zero(dsn)) {
00811             new = ao2_alloc(sizeof(*new), odbc_class_destructor);
00812 
00813             if (!new) {
00814                res = -1;
00815                break;
00816             }
00817 
00818             SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &new->env);
00819             res = SQLSetEnvAttr(new->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
00820 
00821             if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
00822                ast_log(LOG_WARNING, "res_odbc: Error SetEnv\n");
00823                ao2_ref(new, -1);
00824                return res;
00825             }
00826 
00827             new->obj_container = ao2_container_alloc(1, null_hash_fn, ao2_match_by_addr);
00828 
00829             if (pooling) {
00830                new->haspool = pooling;
00831                if (limit) {
00832                   new->limit = limit;
00833                } else {
00834                   ast_log(LOG_WARNING, "Pooling without also setting a limit is pointless.  Changing limit from 0 to 5.\n");
00835                   new->limit = 5;
00836                }
00837             }
00838 
00839             new->backslash_is_escape = bse ? 1 : 0;
00840             new->forcecommit = forcecommit ? 1 : 0;
00841             new->isolation = isolation;
00842             new->idlecheck = idlecheck;
00843 
00844             if (cat)
00845                ast_copy_string(new->name, cat, sizeof(new->name));
00846             if (dsn)
00847                ast_copy_string(new->dsn, dsn, sizeof(new->dsn));
00848             if (username && !(new->username = ast_strdup(username))) {
00849                ao2_ref(new, -1);
00850                break;
00851             }
00852             if (password && !(new->password = ast_strdup(password))) {
00853                ao2_ref(new, -1);
00854                break;
00855             }
00856             if (sanitysql && !(new->sanitysql = ast_strdup(sanitysql))) {
00857                ao2_ref(new, -1);
00858                break;
00859             }
00860 
00861             odbc_register_class(new, preconnect);
00862             ast_log(LOG_NOTICE, "Registered ODBC class '%s' dsn->[%s]\n", cat, dsn);
00863             ao2_ref(new, -1);
00864             new = NULL;
00865          }
00866       }
00867    }
00868    ast_config_destroy(config);
00869    return res;
00870 }

static int mark_transaction_active ( struct ast_channel *  chan,
struct odbc_txn_frame *  tx 
) [static]

Definition at line 339 of file res_odbc.c.

References odbc_txn_frame::active, ast_channel_datastore_find(), ast_channel_lock, ast_channel_unlock, AST_LIST_HEAD, AST_LIST_LOCK, AST_LIST_TRAVERSE, AST_LIST_UNLOCK, ast_datastore::data, odbc_class::list, odbc_txn_frame::owner, and txn_info.

Referenced by acf_transaction_write().

00340 {
00341    struct ast_datastore *txn_store;
00342    AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
00343    struct odbc_txn_frame *active = NULL, *txn;
00344 
00345    if (!chan && tx && tx->owner) {
00346       chan = tx->owner;
00347    }
00348 
00349    ast_channel_lock(chan);
00350    if (!(txn_store = ast_channel_datastore_find(chan, &txn_info, NULL))) {
00351       ast_channel_unlock(chan);
00352       return -1;
00353    }
00354 
00355    oldlist = txn_store->data;
00356    AST_LIST_LOCK(oldlist);
00357    AST_LIST_TRAVERSE(oldlist, txn, list) {
00358       if (txn == tx) {
00359          txn->active = 1;
00360          active = txn;
00361       } else {
00362          txn->active = 0;
00363       }
00364    }
00365    AST_LIST_UNLOCK(oldlist);
00366    ast_channel_unlock(chan);
00367    return active ? 0 : -1;
00368 }

static int null_hash_fn ( const void *  obj,
const int  flags 
) [static]

Definition at line 389 of file res_odbc.c.

Referenced by load_module(), and load_odbc_config().

00390 {
00391    return 0;
00392 }

static void odbc_class_destructor ( void *  data  )  [static]

Definition at line 370 of file res_odbc.c.

References ao2_ref, and ast_free.

Referenced by load_odbc_config().

00371 {
00372    struct odbc_class *class = data;
00373    /* Due to refcounts, we can safely assume that any objects with a reference
00374     * to us will prevent our destruction, so we don't need to worry about them.
00375     */
00376    if (class->username) {
00377       ast_free(class->username);
00378    }
00379    if (class->password) {
00380       ast_free(class->password);
00381    }
00382    if (class->sanitysql) {
00383       ast_free(class->sanitysql);
00384    }
00385    ao2_ref(class->obj_container, -1);
00386    SQLFreeHandle(SQL_HANDLE_ENV, class->env);
00387 }

static odbc_status odbc_obj_connect ( struct odbc_obj *  obj  )  [static]

Definition at line 1412 of file res_odbc.c.

References ast_log(), ast_mutex_lock(), ast_mutex_unlock(), ast_tvnow(), odbc_obj::con, odbc_class::dsn, odbc_class::env, odbc_obj::last_used, odbc_obj::lock, LOG_NOTICE, LOG_WARNING, msg, odbc_class::name, ODBC_FAIL, odbc_obj_disconnect(), ODBC_SUCCESS, odbc_obj::parent, odbc_class::password, odbc_obj::up, and odbc_class::username.

Referenced by ast_odbc_request_obj2(), and ast_odbc_sanity_check().

01413 {
01414    int res;
01415    SQLINTEGER err;
01416    short int mlen;
01417    unsigned char msg[200], state[10];
01418 #ifdef NEEDTRACE
01419    SQLINTEGER enable = 1;
01420    char *tracefile = "/tmp/odbc.trace";
01421 #endif
01422    ast_mutex_lock(&obj->lock);
01423 
01424    if (obj->up) {
01425       odbc_obj_disconnect(obj);
01426       ast_log(LOG_NOTICE, "Re-connecting %s\n", obj->parent->name);
01427    } else {
01428       ast_log(LOG_NOTICE, "Connecting %s\n", obj->parent->name);
01429    }
01430 
01431    res = SQLAllocHandle(SQL_HANDLE_DBC, obj->parent->env, &obj->con);
01432 
01433    if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
01434       ast_log(LOG_WARNING, "res_odbc: Error AllocHDB %d\n", res);
01435       ast_mutex_unlock(&obj->lock);
01436       return ODBC_FAIL;
01437    }
01438    SQLSetConnectAttr(obj->con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *) 10, 0);
01439    SQLSetConnectAttr(obj->con, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER *) 10, 0);
01440 #ifdef NEEDTRACE
01441    SQLSetConnectAttr(obj->con, SQL_ATTR_TRACE, &enable, SQL_IS_INTEGER);
01442    SQLSetConnectAttr(obj->con, SQL_ATTR_TRACEFILE, tracefile, strlen(tracefile));
01443 #endif
01444 
01445    res = SQLConnect(obj->con,
01446          (SQLCHAR *) obj->parent->dsn, SQL_NTS,
01447          (SQLCHAR *) obj->parent->username, SQL_NTS,
01448          (SQLCHAR *) obj->parent->password, SQL_NTS);
01449 
01450    if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
01451       SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, state, &err, msg, 100, &mlen);
01452       ast_mutex_unlock(&obj->lock);
01453       ast_log(LOG_WARNING, "res_odbc: Error SQLConnect=%d errno=%d %s\n", res, (int)err, msg);
01454       return ODBC_FAIL;
01455    } else {
01456       ast_log(LOG_NOTICE, "res_odbc: Connected to %s [%s]\n", obj->parent->name, obj->parent->dsn);
01457       obj->up = 1;
01458       obj->last_used = ast_tvnow();
01459    }
01460 
01461    ast_mutex_unlock(&obj->lock);
01462    return ODBC_SUCCESS;
01463 }

static void odbc_obj_destructor ( void *  data  )  [static]

Definition at line 394 of file res_odbc.c.

References ao2_ref, ast_mutex_destroy(), odbc_obj::lock, odbc_obj_disconnect(), and odbc_obj::parent.

Referenced by ast_odbc_request_obj2().

00395 {
00396    struct odbc_obj *obj = data;
00397    struct odbc_class *class = obj->parent;
00398    obj->parent = NULL;
00399    odbc_obj_disconnect(obj);
00400    ast_mutex_destroy(&obj->lock);
00401    ao2_ref(class, -1);
00402 }

static odbc_status odbc_obj_disconnect ( struct odbc_obj *  obj  )  [static]

Definition at line 1375 of file res_odbc.c.

References ast_log(), ast_mutex_lock(), ast_mutex_unlock(), odbc_obj::con, odbc_class::dsn, odbc_obj::lock, LOG_DEBUG, LOG_WARNING, msg, odbc_class::name, ODBC_SUCCESS, odbc_obj::parent, and odbc_obj::up.

Referenced by ast_odbc_sanity_check(), odbc_obj_connect(), and odbc_obj_destructor().

01376 {
01377    int res;
01378    SQLINTEGER err;
01379    short int mlen;
01380    unsigned char msg[200], state[10];
01381 
01382    /* Nothing to disconnect */
01383    if (!obj->con) {
01384       return ODBC_SUCCESS;
01385    }
01386 
01387    ast_mutex_lock(&obj->lock);
01388 
01389    res = SQLDisconnect(obj->con);
01390 
01391    if (obj->parent) {
01392       if (res == SQL_SUCCESS || res == SQL_SUCCESS_WITH_INFO) {
01393          ast_log(LOG_DEBUG, "Disconnected %d from %s [%s]\n", res, obj->parent->name, obj->parent->dsn);
01394       } else {
01395          ast_log(LOG_DEBUG, "res_odbc: %s [%s] already disconnected\n", obj->parent->name, obj->parent->dsn);
01396       }
01397    }
01398 
01399    if ((res = SQLFreeHandle(SQL_HANDLE_DBC, obj->con) == SQL_SUCCESS)) {
01400       obj->con = NULL;
01401       ast_log(LOG_DEBUG, "Database handle deallocated\n");
01402    } else {
01403       SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, 1, state, &err, msg, 100, &mlen);
01404       ast_log(LOG_WARNING, "Unable to deallocate database handle? %d errno=%d %s\n", res, (int)err, msg);
01405    }
01406 
01407    obj->up = 0;
01408    ast_mutex_unlock(&obj->lock);
01409    return ODBC_SUCCESS;
01410 }

static int odbc_register_class ( struct odbc_class *  class,
int  connect 
) [static]

Definition at line 961 of file res_odbc.c.

References ao2_link, ast_log(), ast_odbc_release_obj(), ast_odbc_request_obj(), class_container, and LOG_WARNING.

Referenced by load_odbc_config().

00962 {
00963    struct odbc_obj *obj;
00964    if (class) {
00965       ao2_link(class_container, class);
00966       /* I still have a reference in the caller, so a deref is NOT missing here. */
00967 
00968       if (preconnect) {
00969          /* Request and release builds a connection */
00970          obj = ast_odbc_request_obj(class->name, 0);
00971          if (obj) {
00972             ast_odbc_release_obj(obj);
00973          }
00974       }
00975 
00976       return 0;
00977    } else {
00978       ast_log(LOG_WARNING, "Attempted to register a NULL class?\n");
00979       return -1;
00980    }
00981 }

static void odbc_release_obj2 ( struct odbc_obj *  obj,
struct odbc_txn_frame *  tx 
) [static]

Definition at line 983 of file res_odbc.c.

References ao2_ref, ast_debug, ast_log(), odbc_obj::con, odbc_txn_frame::forcecommit, LOG_WARNING, odbc_txn_frame::obj, release_transaction(), odbc_obj::txf, and odbc_obj::used.

Referenced by ast_odbc_release_obj(), and release_transaction().

00984 {
00985    SQLINTEGER nativeerror=0, numfields=0;
00986    SQLSMALLINT diagbytes=0, i;
00987    unsigned char state[10], diagnostic[256];
00988 
00989    ast_debug(2, "odbc_release_obj2(%p) called (obj->txf = %p)\n", obj, obj->txf);
00990    if (tx) {
00991       ast_debug(1, "called on a transactional handle with %s\n", tx->forcecommit ? "COMMIT" : "ROLLBACK");
00992       if (SQLEndTran(SQL_HANDLE_DBC, obj->con, tx->forcecommit ? SQL_COMMIT : SQL_ROLLBACK) == SQL_ERROR) {
00993          /* Handle possible transaction commit failure */
00994          SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
00995          for (i = 0; i < numfields; i++) {
00996             SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
00997             ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
00998             if (!strcmp((char *)state, "25S02") || !strcmp((char *)state, "08007")) {
00999                /* These codes mean that a commit failed and a transaction
01000                 * is still active. We must rollback, or things will get
01001                 * very, very weird for anybody using the handle next. */
01002                SQLEndTran(SQL_HANDLE_DBC, obj->con, SQL_ROLLBACK);
01003             }
01004             if (i > 10) {
01005                ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
01006                break;
01007             }
01008          }
01009       }
01010 
01011       /* Transaction is done, reset autocommit */
01012       if (SQLSetConnectAttr(obj->con, SQL_ATTR_AUTOCOMMIT, (void *)SQL_AUTOCOMMIT_ON, 0) == SQL_ERROR) {
01013          SQLGetDiagField(SQL_HANDLE_DBC, obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
01014          for (i = 0; i < numfields; i++) {
01015             SQLGetDiagRec(SQL_HANDLE_DBC, obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
01016             ast_log(LOG_WARNING, "SetConnectAttr (Autocommit) returned an error: %s: %s\n", state, diagnostic);
01017             if (i > 10) {
01018                ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
01019                break;
01020             }
01021          }
01022       }
01023    }
01024 
01025 #ifdef DEBUG_THREADS
01026    obj->file[0] = '\0';
01027    obj->function[0] = '\0';
01028    obj->lineno = 0;
01029 #endif
01030 
01031    /* For pooled connections, this frees the connection to be
01032     * reused.  For non-pooled connections, it does nothing. */
01033    obj->used = 0;
01034    if (obj->txf) {
01035       /* Prevent recursion -- transaction is already closed out. */
01036       obj->txf->obj = NULL;
01037       obj->txf = release_transaction(obj->txf);
01038    }
01039    ao2_ref(obj, -1);
01040 }

static void odbc_txn_free ( void *  data  )  [static]

Definition at line 323 of file res_odbc.c.

References ast_debug, ast_free, AST_LIST_HEAD, AST_LIST_HEAD_DESTROY, AST_LIST_LOCK, AST_LIST_REMOVE_HEAD, AST_LIST_UNLOCK, odbc_class::list, and release_transaction().

00324 {
00325    struct odbc_txn_frame *tx;
00326    AST_LIST_HEAD(, odbc_txn_frame) *oldlist = vdata;
00327 
00328    ast_debug(2, "odbc_txn_free(%p) called\n", vdata);
00329 
00330    AST_LIST_LOCK(oldlist);
00331    while ((tx = AST_LIST_REMOVE_HEAD(oldlist, list))) {
00332       release_transaction(tx);
00333    }
00334    AST_LIST_UNLOCK(oldlist);
00335    AST_LIST_HEAD_DESTROY(oldlist);
00336    ast_free(oldlist);
00337 }

static struct odbc_txn_frame* release_transaction ( struct odbc_txn_frame *  tx  )  [static, read]

Definition at line 287 of file res_odbc.c.

References ast_channel_datastore_find(), ast_channel_lock, ast_channel_unlock, ast_debug, ast_free, AST_LIST_HEAD, AST_LIST_LOCK, AST_LIST_REMOVE, AST_LIST_UNLOCK, ast_datastore::data, odbc_class::list, odbc_txn_frame::obj, odbc_release_obj2(), odbc_txn_frame::owner, odbc_obj::txf, and txn_info.

Referenced by odbc_release_obj2(), and odbc_txn_free().

00288 {
00289    if (!tx) {
00290       return NULL;
00291    }
00292 
00293    ast_debug(2, "release_transaction(%p) called (tx->obj = %p, tx->obj->txf = %p)\n", tx, tx->obj, tx->obj ? tx->obj->txf : NULL);
00294 
00295    /* If we have an owner, disassociate */
00296    if (tx->owner) {
00297       struct ast_datastore *txn_store;
00298       AST_LIST_HEAD(, odbc_txn_frame) *oldlist;
00299 
00300       ast_channel_lock(tx->owner);
00301       if ((txn_store = ast_channel_datastore_find(tx->owner, &txn_info, NULL))) {
00302          oldlist = txn_store->data;
00303          AST_LIST_LOCK(oldlist);
00304          AST_LIST_REMOVE(oldlist, tx, list);
00305          AST_LIST_UNLOCK(oldlist);
00306       }
00307       ast_channel_unlock(tx->owner);
00308       tx->owner = NULL;
00309    }
00310 
00311    if (tx->obj) {
00312       /* If we have any uncommitted transactions, they are handled when we release the object */
00313       struct odbc_obj *obj = tx->obj;
00314       /* Prevent recursion during destruction */
00315       tx->obj->txf = NULL;
00316       tx->obj = NULL;
00317       odbc_release_obj2(obj, tx);
00318    }
00319    ast_free(tx);
00320    return NULL;
00321 }

static int reload ( void   )  [static]

Definition at line 1605 of file res_odbc.c.

References ao2_iterator_destroy(), ao2_iterator_init(), ao2_iterator_next, ao2_ref, ao2_unlink, AST_RWLIST_REMOVE_HEAD, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, class_container, destroy_table_cache(), odbc_class::list, load_odbc_config(), and table.

01606 {
01607    struct odbc_cache_tables *table;
01608    struct odbc_class *class;
01609    struct odbc_obj *current;
01610    struct ao2_iterator aoi = ao2_iterator_init(class_container, 0);
01611 
01612    /* First, mark all to be purged */
01613    while ((class = ao2_iterator_next(&aoi))) {
01614       class->delme = 1;
01615       ao2_ref(class, -1);
01616    }
01617    ao2_iterator_destroy(&aoi);
01618 
01619    load_odbc_config();
01620 
01621    /* Purge remaining classes */
01622 
01623    /* Note on how this works; this is a case of circular references, so we
01624     * explicitly do NOT want to use a callback here (or we wind up in
01625     * recursive hell).
01626     *
01627     * 1. Iterate through all the classes.  Note that the classes will currently
01628     * contain two classes of the same name, one of which is marked delme and
01629     * will be purged when all remaining objects of the class are released, and
01630     * the other, which was created above when we re-parsed the config file.
01631     * 2. On each class, there is a reference held by the master container and
01632     * a reference held by each connection object.  There are two cases for
01633     * destruction of the class, noted below.  However, in all cases, all O-refs
01634     * (references to objects) will first be freed, which will cause the C-refs
01635     * (references to classes) to be decremented (but never to 0, because the
01636     * class container still has a reference).
01637     *    a) If the class has outstanding objects, the C-ref by the class
01638     *    container will then be freed, which leaves only C-refs by any
01639     *    outstanding objects.  When the final outstanding object is released
01640     *    (O-refs held by applications and dialplan functions), it will in turn
01641     *    free the final C-ref, causing class destruction.
01642     *    b) If the class has no outstanding objects, when the class container
01643     *    removes the final C-ref, the class will be destroyed.
01644     */
01645    aoi = ao2_iterator_init(class_container, 0);
01646    while ((class = ao2_iterator_next(&aoi))) { /* C-ref++ (by iterator) */
01647       if (class->delme) {
01648          struct ao2_iterator aoi2 = ao2_iterator_init(class->obj_container, 0);
01649          while ((current = ao2_iterator_next(&aoi2))) { /* O-ref++ (by iterator) */
01650             ao2_unlink(class->obj_container, current); /* unlink O-ref from class (reference handled implicitly) */
01651             ao2_ref(current, -1); /* O-ref-- (by iterator) */
01652             /* At this point, either
01653              * a) there's an outstanding O-ref, or
01654              * b) the object has already been destroyed.
01655              */
01656          }
01657          ao2_iterator_destroy(&aoi2);
01658          ao2_unlink(class_container, class); /* unlink C-ref from container (reference handled implicitly) */
01659          /* At this point, either
01660           * a) there's an outstanding O-ref, which holds an outstanding C-ref, or
01661           * b) the last remaining C-ref is held by the iterator, which will be
01662           * destroyed in the next step.
01663           */
01664       }
01665       ao2_ref(class, -1); /* C-ref-- (by iterator) */
01666    }
01667    ao2_iterator_destroy(&aoi);
01668 
01669    /* Empty the cache; it will get rebuilt the next time the tables are needed. */
01670    AST_RWLIST_WRLOCK(&odbc_tables);
01671    while ((table = AST_RWLIST_REMOVE_HEAD(&odbc_tables, list))) {
01672       destroy_table_cache(table);
01673    }
01674    AST_RWLIST_UNLOCK(&odbc_tables);
01675 
01676    return 0;
01677 }

static int rollback_exec ( struct ast_channel *  chan,
void *  data 
) [static]

Definition at line 1090 of file res_odbc.c.

References ast_log(), ast_str_append(), ast_str_buffer(), ast_str_reset(), ast_str_strlen(), ast_str_thread_get(), ast_strlen_zero(), odbc_obj::con, errors_buf, find_transaction(), LOG_WARNING, odbc_txn_frame::obj, and pbx_builtin_setvar_helper().

Referenced by load_module().

01091 {
01092    struct odbc_txn_frame *tx;
01093    SQLINTEGER nativeerror=0, numfields=0;
01094    SQLSMALLINT diagbytes=0, i;
01095    unsigned char state[10], diagnostic[256];
01096 
01097    if (ast_strlen_zero(data)) {
01098       tx = find_transaction(chan, NULL, NULL, 1);
01099    } else {
01100       tx = find_transaction(chan, NULL, data, 0);
01101    }
01102 
01103    pbx_builtin_setvar_helper(chan, "ROLLBACK_RESULT", "OK");
01104 
01105    if (tx) {
01106       if (SQLEndTran(SQL_HANDLE_DBC, tx->obj->con, SQL_ROLLBACK) == SQL_ERROR) {
01107          struct ast_str *errors = ast_str_thread_get(&errors_buf, 16);
01108          ast_str_reset(errors);
01109 
01110          /* Handle possible transaction commit failure */
01111          SQLGetDiagField(SQL_HANDLE_DBC, tx->obj->con, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
01112          for (i = 0; i < numfields; i++) {
01113             SQLGetDiagRec(SQL_HANDLE_DBC, tx->obj->con, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
01114             ast_str_append(&errors, 0, "%s%s", ast_str_strlen(errors) ? "," : "", state);
01115             ast_log(LOG_WARNING, "SQLEndTran returned an error: %s: %s\n", state, diagnostic);
01116             if (i > 10) {
01117                ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
01118                break;
01119             }
01120          }
01121          pbx_builtin_setvar_helper(chan, "ROLLBACK_RESULT", ast_str_buffer(errors));
01122       }
01123    }
01124    return 0;
01125 }

static int text2isolation ( const char *  txt  )  [static]

Definition at line 185 of file res_odbc.c.

Referenced by acf_transaction_write(), and load_odbc_config().

00186 {
00187    if (strncasecmp(txt, "read_", 5) == 0) {
00188       if (strncasecmp(txt + 5, "c", 1) == 0) {
00189          return SQL_TXN_READ_COMMITTED;
00190       } else if (strncasecmp(txt + 5, "u", 1) == 0) {
00191          return SQL_TXN_READ_UNCOMMITTED;
00192       } else {
00193          return 0;
00194       }
00195    } else if (strncasecmp(txt, "ser", 3) == 0) {
00196       return SQL_TXN_SERIALIZABLE;
00197    } else if (strncasecmp(txt, "rep", 3) == 0) {
00198       return SQL_TXN_REPEATABLE_READ;
00199    } else {
00200       return 0;
00201    }
00202 }

static int unload_module ( void   )  [static]

Definition at line 1679 of file res_odbc.c.

01680 {
01681    /* Prohibit unloading */
01682    return -1;
01683 }


Variable Documentation

struct ast_module_info __mod_info = { .name = AST_MODULE, .flags = AST_MODFLAG_GLOBAL_SYMBOLS , .description = "ODBC resource" , .key = "This paragraph is copyright (c) 2006 by Digium, Inc. \In order for your module to load, it must return this \key via a function called \"key\". Any code which \includes this paragraph must be licensed under the GNU \General Public License version 2 or later (at your \option). In addition to Digium's general reservations \of rights, Digium expressly reserves the right to \allow other parties to license this paragraph under \different terms. Any use of Digium, Inc. trademarks or \logos (including \"Asterisk\" or \"Digium\") without \express written permission of Digium, Inc. is prohibited.\n" , .buildopt_sum = AST_BUILDOPT_SUM, .load = load_module, .unload = unload_module, .reload = reload, } [static]

Definition at line 1703 of file res_odbc.c.

const char* app_commit = "ODBC_Commit" [static]

Definition at line 1602 of file res_odbc.c.

Referenced by load_module().

const char* app_rollback = "ODBC_Rollback" [static]

Definition at line 1603 of file res_odbc.c.

Referenced by load_module().

Definition at line 1703 of file res_odbc.c.

struct ast_cli_entry cli_odbc[] [static]

Initial value:

 {
   AST_CLI_DEFINE(handle_cli_odbc_show, "List ODBC DSN(s)")
}

Definition at line 957 of file res_odbc.c.

Referenced by load_module().

struct ast_threadstorage errors_buf = { .once = PTHREAD_ONCE_INIT , .key_init = __init_errors_buf , .custom_init = NULL , } [static]

Definition at line 146 of file res_odbc.c.

Referenced by commit_exec(), and rollback_exec().

Initial value:

 {
   .name = "ODBC",
   .read = acf_transaction_read,
   .write = acf_transaction_write,
}

Definition at line 1596 of file res_odbc.c.

Referenced by load_module().

struct ast_datastore_info txn_info [static]

Initial value:

 {
   .type = "ODBC_Transaction",
   .destroy = odbc_txn_free,
}

Definition at line 148 of file res_odbc.c.

Referenced by ast_odbc_retrieve_transaction_obj(), find_transaction(), mark_transaction_active(), and release_transaction().


Generated on Wed Mar 2 18:58:16 2011 for Asterisk - the Open Source PBX by  doxygen 1.5.9