Esempio n. 1
0
/*
** Set "auto commit" property of the connection.
** If 'true', then rollback current transaction.
** If 'false', then start a new transaction.
*/
static int conn_setautocommit(lua_State *L)
{
	conn_data *conn = getconnection(L);
	if (lua_toboolean(L, 2))
    {
		conn->auto_commit = 1;
        /* undo active transaction - ignore errors */
        sqlite_exec(conn->sql_conn, "ROLLBACK", NULL, NULL, NULL);
	}
	else
    {
        char *errmsg;
        int res;
		conn->auto_commit = 0;
        res = sqlite_exec(conn->sql_conn, "BEGIN", NULL, NULL, &errmsg);
        if (res != SQLITE_OK)
        {
            lua_pushliteral(L, LUASQL_PREFIX);
            lua_pushstring(L, errmsg);
            sqlite_freemem(errmsg);
            lua_concat(L, 2);
            lua_error(L);
        }
	}
	lua_pushboolean(L, 1);
	return 1;
}
Esempio n. 2
0
void sql(const char *fmt, ...)
{
	char *sql;
	va_list ap;
	int rc, busyc = 0;

	va_start(ap, fmt);
	vasprintf(&sql, fmt, ap);
	va_end(ap);

	while (1) {
		rc = sqlite_exec(db, sql, 0, 0, 0);
		if ( rc != SQLITE_BUSY ) break;
		if (busyc++ > 60) {
			fprintf(stderr, "** Database busy for long time [%d secs]: %s\n", busyc, sql);
		}
		sleep(1);
	}

	if ( rc != SQLITE_OK ) {
		fprintf(stderr, "** Database Error %d in '%s'!\n", rc, sql);
		sqlite_exec(db, "COMMIT TRANSACTION", 0, 0, 0);
		exit(1);
	}

	free(sql);
}
Esempio n. 3
0
/*
** Initialize all database files - the main database file, the file
** used to store temporary tables, and any additional database files
** created using ATTACH statements.  Return a success code.  If an
** error occurs, write an error message into *pzErrMsg.
**
** After the database is initialized, the SQLITE_Initialized
** bit is set in the flags field of the sqlite structure.  An
** attempt is made to initialize the database as soon as it
** is opened.  If that fails (perhaps because another process
** has the sqlite_master table locked) than another attempt
** is made the first time the database is accessed.
*/
int sqliteInit(sqlite *db, char **pzErrMsg){
  int i, rc;
  
  if( db->init.busy ) return SQLITE_OK;
  assert( (db->flags & SQLITE_Initialized)==0 );
  rc = SQLITE_OK;
  db->init.busy = 1;
  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
    if( DbHasProperty(db, i, DB_SchemaLoaded) ) continue;
    assert( i!=1 );  /* Should have been initialized together with 0 */
    rc = sqliteInitOne(db, i, pzErrMsg);
    if( rc ){
      sqliteResetInternalSchema(db, i);
    }
  }
  db->init.busy = 0;
  if( rc==SQLITE_OK ){
    db->flags |= SQLITE_Initialized;
    sqliteCommitInternalChanges(db);
  }

  /* If the database is in formats 1 or 2, then upgrade it to
  ** version 3.  This will reconstruct all indices.  If the
  ** upgrade fails for any reason (ex: out of disk space, database
  ** is read only, interrupt received, etc.) then fail the init.
  */
  if( rc==SQLITE_OK && db->file_format<3 ){
    char *zErr = 0;
    InitData initData;
    int meta[SQLITE_N_BTREE_META];

    db->magic = SQLITE_MAGIC_OPEN;
    initData.db = db;
    initData.pzErrMsg = &zErr;
    db->file_format = 3;
    rc = sqlite_exec(db,
      "BEGIN; SELECT name FROM sqlite_master WHERE type='table';",
      upgrade_3_callback,
      &initData,
      &zErr);
    if( rc==SQLITE_OK ){
      sqliteBtreeGetMeta(db->aDb[0].pBt, meta);
      meta[2] = 4;
      sqliteBtreeUpdateMeta(db->aDb[0].pBt, meta);
      sqlite_exec(db, "COMMIT", 0, 0, 0);
    }
    if( rc!=SQLITE_OK ){
      sqliteSetString(pzErrMsg, 
        "unable to upgrade database to the version 2.6 format",
        zErr ? ": " : 0, zErr, (char*)0);
    }
    sqlite_freemem(zErr);
  }

  if( rc!=SQLITE_OK ){
    db->flags &= ~SQLITE_Initialized;
  }
  return rc;
}
Esempio n. 4
0
/*
 * smb_nic_dbcreate
 *
 * Creates the host database based on the defined SQL statement.
 * It also initializes db_info table.
 */
static int
smb_nic_dbcreate(void)
{
	sqlite *db = NULL;
	char *errmsg = NULL;
	int rc, err = SMB_NIC_SUCCESS;

	(void) unlink(SMB_NIC_DB_NAME);

	db = sqlite_open(SMB_NIC_DB_NAME, 0600, &errmsg);
	if (db == NULL) {
		syslog(LOG_ERR, "Failed to create host database (%s).",
		    NULL_MSGCHK(errmsg));
		sqlite_freemem(errmsg);
		return (SMB_NIC_DBOPEN_FAILED);
	}

	sqlite_busy_timeout(db, SMB_NIC_DB_TIMEOUT);
	rc = sqlite_exec(db, "BEGIN TRANSACTION", NULL, NULL, &errmsg);
	if (rc != SQLITE_OK) {
		syslog(LOG_ERR, "Failed to create host database.  Unable to " \
		    "begin database transaction (%s).", NULL_MSGCHK(errmsg));
		sqlite_freemem(errmsg);
		sqlite_close(db);
		return (SMB_NIC_DBEXEC_FAILED);
	}

	if (sqlite_exec(db, SMB_NIC_DB_SQL, NULL, NULL, &errmsg) == SQLITE_OK) {
		rc = sqlite_exec(db, "COMMIT TRANSACTION", NULL, NULL,
		    &errmsg);
		if (rc == SQLITE_OK)
			err = smb_nic_dbsetinfo(db);
		if (err != SMB_NIC_SUCCESS)
			rc = sqlite_exec(db, "ROLLBACK TRANSACTION", NULL, NULL,
			    &errmsg);
	} else {
		syslog(LOG_ERR, "Failed to create host database.  Unable to " \
		    "initialize host database (%s).", NULL_MSGCHK(errmsg));
		sqlite_freemem(errmsg);
		rc = sqlite_exec(db, "ROLLBACK TRANSACTION", NULL, NULL,
		    &errmsg);
	}

	if (rc != SQLITE_OK) {
		/* this is bad - database may be left in a locked state */
		syslog(LOG_ERR, "Failed to create host database.  Unable to " \
		    "close a transaction (%s).", NULL_MSGCHK(errmsg));
		sqlite_freemem(errmsg);
		err = SMB_NIC_DBINIT_FAILED;
	}

	(void) sqlite_close(db);
	return (err);
}
Esempio n. 5
0
int
_ds_set_spamrecord (DSPAM_CTX * CTX, unsigned long long token,
                    struct _ds_spam_stat *stat)
{
  struct _sqlite_drv_storage *s = (struct _sqlite_drv_storage *) CTX->storage;
  char query[1024];
  char *err=NULL;
  int result = 0;

  if (s->dbh == NULL)
  {
    LOGDEBUG ("_ds_set_spamrecord: invalid database handle (NULL)");
    return EINVAL;
  }

  if (CTX->operating_mode == DSM_CLASSIFY)
    return 0;

  /* It's either not on disk or the caller isn't using stat.disk */
  if (!(stat->status & TST_DISK))
  {
    snprintf (query, sizeof (query),
              "insert into dspam_token_data(token, spam_hits, "
              "innocent_hits, last_hit)"
              " values('%" LLU_FMT_SPEC "', %ld, %ld, date('now'))",
              token, 
              stat->spam_hits > 0 ? stat->spam_hits : 0,
              stat->innocent_hits > 0 ? stat->innocent_hits : 0);
    result = sqlite_exec(s->dbh, query, NULL, NULL, &err);
  }

  if ((stat->status & TST_DISK) || result)
  {
    /* insert failed; try updating instead */
    snprintf (query, sizeof (query), "update dspam_token_data "
              "set spam_hits = %ld, "
              "innocent_hits = %ld "
              "where token = %" LLD_FMT_SPEC,
              stat->spam_hits > 0 ? stat->spam_hits : 0,
              stat->innocent_hits > 0 ? stat->innocent_hits : 0,
              token);

    if ((sqlite_exec(s->dbh, query, NULL, NULL, &err))!=SQLITE_OK)
    {
      _sqlite_drv_query_error (err, query);
      return EFAILURE;
    }
  }

  return 0;
}
Esempio n. 6
0
int
_ds_del_spamrecord (DSPAM_CTX * CTX, unsigned long long token)
{
  struct _sqlite_drv_storage *s = (struct _sqlite_drv_storage *) CTX->storage;
  char query[128];
  char *err=NULL;

  if (s->dbh == NULL)
  {
    LOGDEBUG ("_ds_delete_signature: invalid database handle (NULL)");
    return EINVAL;
  }
                                                                                
  snprintf (query, sizeof (query),
            "delete from dspam_token_data where token = \"%" LLU_FMT_SPEC "\"",
            token);
                                                                                
  if ((sqlite_exec(s->dbh, query, NULL, NULL, &err))!=SQLITE_OK)
  {
    _sqlite_drv_query_error (err, query);
    return EFAILURE;
  }

  return 0;
}
Esempio n. 7
0
static void sqlite_client_thread(void *arg)
{
    unsigned long i, succeeded, failed;
    DBPool *pool = arg;
    char *errmsg = 0;

    succeeded = failed = 0;

    info(0,"Client thread started with %ld queries to perform on pool", queries);

    /* perform random queries on the pool */
    for (i = 1; i <= queries; i++) {
        DBPoolConn *pconn;
        int state;

        /* provide us with a connection from the pool */
        pconn = dbpool_conn_consume(pool);
        debug("",0,"Query %ld/%ld: sqlite conn obj at %p",
              i, queries, (void*) pconn->conn);

        state = sqlite_exec(pconn->conn, octstr_get_cstr(sql), callback, 0, &errmsg);
        if (state != SQLITE_OK) {
            error(0, "SQLite: %s", errmsg);
            failed++;
        } else {
            succeeded++;
        }

        /* return the connection to the pool */
        dbpool_conn_produce(pconn);
    }
    info(0, "This thread: %ld succeeded, %ld failed.", succeeded, failed);
}
Esempio n. 8
0
int
_ds_delete_signature (DSPAM_CTX * CTX, const char *signature)
{
  struct _sqlite_drv_storage *s = (struct _sqlite_drv_storage *) CTX->storage;
  char query[128];
  char *err=NULL;

  if (s->dbh == NULL)
  {
    LOGDEBUG ("_ds_delete_signature: invalid database handle (NULL)");
    return EINVAL;
  }

  snprintf (query, sizeof (query),
            "delete from dspam_signature_data where signature = \"%s\"",
             signature);

  if ((sqlite_exec(s->dbh, query, NULL, NULL, &err))!=SQLITE_OK)
  {
    _sqlite_drv_query_error (err, query);
    return EFAILURE;
  }

  return 0;
}
int main(int argc, char **argv){
  int i;
  sqlite *db;
  char *zErr;
  int status;
  int parent = getpid();

  unlink("test.db");
  unlink("test.db-journal");
  db = sqlite_open("test.db", 0, &zErr);
  if( db==0 ){
    printf("Cannot initialize: %s\n", zErr);
    return 1;
  }
  sqlite_exec(db, "CREATE TABLE t1(a,b)", 0, 0, 0);
  sqlite_close(db);
  for(i=0; i<10000; i++){
    int pid = fork();
    if( pid==0 ){
      sched_yield();
      do_some_sql(parent);
      return 0;
    }
    printf("test %d, pid=%d\n", i, pid);
    usleep(rand()%10000 + 1000);
    kill(pid, SIGKILL);
    waitpid(pid, &status, 0);
  }
  return 0;
}
Esempio n. 10
0
static int
smb_nic_dbaddhost(const char *host, const char *cmnt, char *if_list)
{
	sqlite *db;
	char *sql;
	char *errmsg;
	int rc, err = SMB_NIC_SUCCESS;

	sql = sqlite_mprintf("REPLACE INTO hosts (hostname, comment, ifnames)"
	    "VALUES ('%s', '%q', '%s')", host, (cmnt) ? cmnt : "", if_list);
	if (sql == NULL)
		return (SMB_NIC_NO_MEMORY);

	db = smb_nic_dbopen(SMB_NIC_DB_ORW);
	if (db == NULL) {
		sqlite_freemem(sql);
		return (SMB_NIC_DBOPEN_FAILED);
	}

	rc = sqlite_exec(db, sql, NULL, NULL, &errmsg);
	sqlite_freemem(sql);
	smb_nic_dbclose(db);

	if (rc != SQLITE_OK) {
		syslog(LOG_ERR, "Failed to add host %s to host database (%s).",
		    host, NULL_MSGCHK(errmsg));
		sqlite_freemem(errmsg);
		err = SMB_NIC_INSERT_FAILED;
	}

	return (err);
}
Esempio n. 11
0
void SqliteDataset::make_query(StringList &_sql) {
  string query;

  if (autocommit) db->start_transaction();


  if (db == NULL) {
      if (db->in_transaction()) db->rollback_transaction();
      return;
  }


  for (list<string>::iterator i =_sql.begin(); i!=_sql.end(); i++) {
	query = *i;
	char* err=NULL; 
	Dataset::parse_sql(query);
	if (db->setErr(sqlite_exec(this->handle(),query.c_str(),NULL,NULL,&err),query.c_str())!=SQLITE_OK) {
	  if (db->in_transaction()) db->rollback_transaction();
	  return;
    }
  } // end of for


  if (db->in_transaction() && autocommit) db->commit_transaction();

  active = true;
  ds_state = dsSelect;		
  if (autorefresh)
    refresh();
}
Esempio n. 12
0
static int
smb_nic_dbdelhost(const char *host)
{
	sqlite *db;
	char *sql;
	char *errmsg;
	int rc, err = SMB_NIC_SUCCESS;

	sql = sqlite_mprintf("DELETE FROM hosts WHERE hostname = '%s'", host);
	if (sql == NULL)
		return (SMB_NIC_NO_MEMORY);

	db = smb_nic_dbopen(SMB_NIC_DB_ORW);
	if (db == NULL) {
		sqlite_freemem(sql);
		return (SMB_NIC_DBOPEN_FAILED);
	}

	rc = sqlite_exec(db, sql, NULL, NULL, &errmsg);
	sqlite_freemem(sql);
	smb_nic_dbclose(db);

	if (rc != SQLITE_OK) {
		syslog(LOG_ERR, "Failed to delete host %s from host " \
		    "database (%s).", host, NULL_MSGCHK(errmsg));
		sqlite_freemem(errmsg);
		err = SMB_NIC_DELETE_FAILED;
	}

	return (err);
}
Esempio n. 13
0
/*
 * smb_nic_dbsetinfo
 *
 * Initializes the db_info table upon database creation.
 */
static int
smb_nic_dbsetinfo(sqlite *db)
{
	char *errmsg = NULL;
	char *sql;
	int rc, err = SMB_NIC_SUCCESS;

	sql = sqlite_mprintf("INSERT INTO db_info (ver_major, ver_minor,"
	    " magic) VALUES (%d, %d, %d)", SMB_NIC_DB_VERMAJOR,
	    SMB_NIC_DB_VERMINOR, SMB_NIC_DB_MAGIC);

	if (sql == NULL)
		return (SMB_NIC_NO_MEMORY);

	rc = sqlite_exec(db, sql, NULL, NULL, &errmsg);
	sqlite_freemem(sql);
	if (rc != SQLITE_OK) {
		syslog(LOG_ERR, "Failed to add database information to " \
		    "host database (%s).", NULL_MSGCHK(errmsg));
		sqlite_freemem(errmsg);
		err = SMB_NIC_DBINIT_ERROR;
	}

	return (err);
}
Esempio n. 14
0
int
_ds_set_signature (DSPAM_CTX * CTX, struct _ds_spam_signature *SIG,
                   const char *signature)
{
  struct _sqlite_drv_storage *s = (struct _sqlite_drv_storage *) CTX->storage;
  unsigned long length;
  char *mem;
  char scratch[1024];
  buffer *query;
  char *err=NULL;

  if (s->dbh == NULL)
  {
    LOGDEBUG ("_ds_set_signature; invalid database handle (NULL)");
    return EINVAL;
  }

  query = buffer_create (NULL);
  if (query == NULL)
  {
    LOG (LOG_CRIT, ERR_MEM_ALLOC);
    return EUNKNOWN;
  }

  mem = calloc (1, 2 + (257*SIG->length)/254);
  if (mem == NULL)
  {
    LOG (LOG_CRIT, ERR_MEM_ALLOC);
    buffer_destroy(query);
    return EUNKNOWN;
  }

  length = sqlite_encode_binary(SIG->data, SIG->length, (unsigned char *) mem);
  if (length<0) {
   LOG(LOG_ERR, "sqlite_encode_binary() failed on error %d", length);
   buffer_destroy(query);
   return EFAILURE;
  }

  snprintf (scratch, sizeof (scratch),
            "insert into dspam_signature_data(signature, created_on, data) "
            "values(\"%s\", date('now'), '",
            signature);
  buffer_cat (query, scratch);
  buffer_cat (query, mem);
  buffer_cat (query, "')");

  if ((sqlite_exec(s->dbh, query->data, NULL, NULL, &err))!=SQLITE_OK)
  {
    _sqlite_drv_query_error (err, query->data);
    buffer_destroy(query);
    free(mem);
    return EFAILURE;
  }

  free (mem);
  buffer_destroy(query);
  return 0;
}
Esempio n. 15
0
static int load_module(void)
{
	char *zErr;
	char fn[PATH_MAX];
	int res;

	/* is the database there? */
	snprintf(fn, sizeof(fn), "%s/cdr.db", ast_config_AST_LOG_DIR);
	db = sqlite_open(fn, 0660, &zErr);
	if (!db) {
		ast_log(LOG_ERROR, "cdr_sqlite: %s\n", zErr);
		free(zErr);
		return -1;
	}

	/* is the table there? */
	res = sqlite_exec(db, "SELECT COUNT(id) FROM cdr;", NULL, NULL, NULL);
	if (res) {
		res = sqlite_exec(db, sql_create_table, NULL, NULL, &zErr);
		if (res) {
			ast_log(LOG_ERROR, "cdr_sqlite: Unable to create table 'cdr': %s\n", zErr);
			free(zErr);
			goto err;
		}
		/*res = sqlite_exec(db, sql_create_trigger, NULL, NULL, &zErr);
		if (res) {
			ast_log(LOG_ERROR, "cdr_sqlite: Unable to create maxentries trigger: %s\n", zErr);
			free(zErr);
			goto err;
		}*/

		/* TODO: here we should probably create an index */
	}
	
	res = ast_cdr_register(name, ast_module_info->description, sqlite_log);
	if (res) {
		ast_log(LOG_ERROR, "Unable to register SQLite CDR handling\n");
		return -1;
	}
	return 0;

err:
	if (db)
		sqlite_close(db);
	return -1;
}
Esempio n. 16
0
static int sqlite_load_module(void)
{
	char *zErr;
	char fn[PATH_MAX];
	int res;

	/* is the database there? */
	snprintf(fn, sizeof(fn), "%s/astdb.db", ast_config_AST_LOG_DIR);
	db = sqlite_open(fn, 0660, &zErr);
	if (!db) {
		ast_log(LOG_ERROR, "app_dbsqlite: %s\n", zErr);
		free(zErr);
		return -1;
	}

	/* is the table there? */
	res = sqlite_exec(db, "SELECT COUNT(Id) FROM astdb;", NULL, NULL, &zErr);
	if (res) {
		res = sqlite_exec(db, sql_create_table, NULL, NULL, &zErr);
		if (res) {
			ast_log(LOG_ERROR, "app_dbsqlite: Unable to create table 'astdb': %s\n", zErr);
			free(zErr);
			goto err;
		}

		/* TODO: here we should probably create an index */
	}
	res = ast_register_application (g_app, sqliteget_exec, g_synopsis, g_descrip);
	if (!res)
		res = ast_register_application (p_app, sqliteput_exec, p_synopsis, p_descrip);
	if (!res)
		res = ast_register_application (d_app, sqlitedel_exec, d_synopsis, d_descrip);
	if (!res)
		res = ast_register_application (dt_app, sqlitedeltree_exec, dt_synopsis, dt_descrip);

	if (res) {
		ast_log(LOG_ERROR, "Unable to register app_dbsqlite\n");
		return -1;
	}
	return 0;

err:
	if (db)
		sqlite_close(db);
	return -1;
}
Esempio n. 17
0
/*
** Implementation of the x_sqlite_exec() function.  This function takes
** a single argument and attempts to execute that argument as SQL code.
** This is illegal and should set the SQLITE_MISUSE flag on the database.
**
** 2004-Jan-07:  We have changed this to make it legal to call sqlite_exec()
** from within a function call.  
** 
** This routine simulates the effect of having two threads attempt to
** use the same database at the same time.
*/
static void sqliteExecFunc(sqlite_func *context, int argc, const char **argv){
  struct dstr x;
  memset(&x, 0, sizeof(x));
  sqlite_exec((sqlite*)sqlite_user_data(context), argv[0], 
      execFuncCallback, &x, 0);
  sqlite_set_result_string(context, x.z, x.nUsed);
  sqliteFree(x.z);
}
Esempio n. 18
0
int SqliteDataset::exec(const string &sql) {
  if (!handle()) return DB_ERROR;
  int res;
  exec_res.record_header.clear();
  exec_res.records.clear();
  if(res = db->setErr(sqlite_exec(handle(),sql.c_str(),&callback,&exec_res,&errmsg),sql.c_str()) == SQLITE_OK)
    return res;
  else
    return DB_ERROR;
}
Esempio n. 19
0
static int load_module(void)
{
	char *zErr;
	char fn[PATH_MAX];
	int res;

	ast_log(LOG_NOTICE, "This module has been marked deprecated in favor of "
		"using cdr_sqlite3_custom.\n");

	/* is the database there? */
	snprintf(fn, sizeof(fn), "%s/cdr.db", ast_config_AST_LOG_DIR);
	db = sqlite_open(fn, AST_FILE_MODE, &zErr);
	if (!db) {
		ast_log(LOG_ERROR, "cdr_sqlite: %s\n", zErr);
		ast_free(zErr);
		return AST_MODULE_LOAD_DECLINE;
	}

	/* is the table there? */
	res = sqlite_exec(db, "SELECT COUNT(AcctId) FROM cdr;", NULL, NULL, NULL);
	if (res) {
		res = sqlite_exec(db, sql_create_table, NULL, NULL, &zErr);
		if (res) {
			ast_log(LOG_ERROR, "cdr_sqlite: Unable to create table 'cdr': %s\n", zErr);
			ast_free(zErr);
			goto err;
		}

		/* TODO: here we should probably create an index */
	}

	res = ast_cdr_register(name, ast_module_info->description, sqlite_log);
	if (res) {
		ast_log(LOG_ERROR, "Unable to register SQLite CDR handling\n");
		return AST_MODULE_LOAD_DECLINE;
	}
	return AST_MODULE_LOAD_SUCCESS;

err:
	if (db)
		sqlite_close(db);
	return AST_MODULE_LOAD_DECLINE;
}
Esempio n. 20
0
bool DatabaseSqlite::Execute(const char *sql)
{
    char *errmsg;

    if (!mSqlite)
        return false;

    if(sqlite_exec(mSqlite, sql, NULL, NULL, &errmsg) != SQLITE_OK)
        return false;

    return true;
}
Esempio n. 21
0
int SqliteDatabase::connect() {
  disconnect();
  if (conn = sqlite_open(db.c_str(),0,NULL)) {
    //cout << "Connected!\n";
    char* err=NULL;
    if (setErr(sqlite_exec(getHandle(),"PRAGMA empty_result_callbacks=ON",NULL,NULL,&err),"PRAGMA empty_result_callbacks=ON") != SQLITE_OK) {
      return DB_CONNECTION_NONE;
    }
    active = true;
    return DB_CONNECTION_OK;
  }
  return DB_CONNECTION_NONE;
};
Esempio n. 22
0
/*
** Execute an SQL statement.
*/
void db_execute(sqlite *db, const char *zFile, const char *zFormat, ...){
  char *zSql;
  int rc;
  char *zErrMsg = 0;
  va_list ap;
  va_start(ap, zFormat);
  zSql = sqlite_vmprintf(zFormat, ap);
  va_end(ap);
  if( verbose ) printf("EXEC %s: %s\n", zFile, zSql);
  rc = sqlite_exec(db, zSql, 0, 0, &zErrMsg);
  while( rc==SQLITE_SCHEMA ){
    if( zErrMsg ) free(zErrMsg);
    rc = sqlite_exec(db, zSql, 0, 0, &zErrMsg);
  }
  if( verbose ) printf("DONE %s: %s\n", zFile, zSql);
  if( zErrMsg ){
    fprintf(stdout,"%s: command failed: %s - %s\n", zFile, zSql, zErrMsg);
    free(zErrMsg);
    sqlite_freemem(zSql);
    Exit(1);
  }
  sqlite_freemem(zSql);
}
Esempio n. 23
0
long SqliteDatabase::nextid(const char* sname) {
  if (!active) return DB_UNEXPECTED_RESULT;
  int id,nrow,ncol;
  result_set res;
  char sqlcmd[512];
  sprintf(sqlcmd,"select nextid from %s where seq_name = '%s'",sequence_table.c_str(), sname);
  if (last_err = sqlite_exec(getHandle(),sqlcmd,&callback,&res,NULL) != SQLITE_OK) {
    return DB_UNEXPECTED_RESULT;
    }
  if (res.records.size() == 0) {
    id = 1;
    sprintf(sqlcmd,"insert into %s (nextid,seq_name) values (%d,'%s')",sequence_table.c_str(),id,sname);
    if (last_err = sqlite_exec(conn,sqlcmd,NULL,NULL,NULL) != SQLITE_OK) return DB_UNEXPECTED_RESULT;
    return id;
  }
  else {
    id = res.records[0][0].get_asInteger()+1;
    sprintf(sqlcmd,"update %s set nextid=%d where seq_name = '%s'",sequence_table.c_str(),id,sname);
    if (last_err = sqlite_exec(conn,sqlcmd,NULL,NULL,NULL) != SQLITE_OK) return DB_UNEXPECTED_RESULT;
    return id;    
  }
  return DB_UNEXPECTED_RESULT;
}
Esempio n. 24
0
bool QSQLiteDriver::rollbackTransaction()
{
    if (!isOpen() || isOpenError())
        return FALSE;

    char* err;
    int res = sqlite_exec(d->access, "ROLLBACK", 0, this, &err);

    if (res == SQLITE_OK)
        return TRUE;

    setLastError(QSqlError("Unable to rollback Transaction", err, QSqlError::Transaction, res));
    sqlite_freemem(err);
    return FALSE;
}
Esempio n. 25
0
bool QSQLite2Driver::rollbackTransaction()
{
    if (!isOpen() || isOpenError())
        return false;

    char* err;
    int res = sqlite_exec(d->access, "ROLLBACK", 0, this, &err);

    if (res == SQLITE_OK)
        return true;

    setLastError(QSqlError(tr("Unable to rollback transaction"),
                           QString::fromAscii(err), QSqlError::TransactionError, res));
    sqlite_freemem(err);
    return false;
}
Esempio n. 26
0
/* _sqlite2_query */
static int _sqlite2_query(SQLite2 * sqlite, char const * query,
                          DatabaseCallback callback, void * data)
{
    int ret;
    char * error = NULL;

#ifdef DEBUG
    fprintf(stderr, "DEBUG: %s(\"%s\")\n", __func__, query);
#endif
    ret = (sqlite_exec(sqlite->handle, query, callback, data, &error)
           == SQLITE_OK) ? 0 : -error_set_code(1, "%s",
                   (error != NULL) ? error : "Unknown error");
    if(error != NULL)
        free(error);
    return ret;
}
Esempio n. 27
0
bool QSQLite2Driver::commitTransaction()
{
    Q_D(QSQLite2Driver);
    if (!isOpen() || isOpenError())
        return false;

    char* err;
    int res = sqlite_exec(d->access, "COMMIT", 0, this, &err);

    if (res == SQLITE_OK)
        return true;

    setLastError(QSqlError(tr("Unable to commit transaction"),
                QString::fromLatin1(err), QSqlError::TransactionError, res));
    sqlite_freemem(err);
    return false;
}
Esempio n. 28
0
File: IoSQLite.c Progetto: Akiyah/io
IoObject *IoSQLite_execWithCallback(IoSQLite *self,
									IoObject *locals,
									IoMessage *m,
									IoSymbol *s,
									ResultRowCallback *callback)
{
	IoList *results;

	if (!DATA(self)->db)
	{
		IoSQLite_open(self, locals, m);

		if (!DATA(self)->db)
		{
			return IONIL(self);
		}
	}

	DATA(self)->results = IOREF(IoList_new(IOSTATE));

	if (DATA(self)->debugOn)
	{
		IoState_print_(IOSTATE, "*** %s ***\n", CSTRING(s));
	}

	{
		char *zErrMsg;
		int rc = sqlite_exec(DATA(self)->db, CSTRING(s), callback, self, &zErrMsg);

		if (rc != SQLITE_OK)
		{
			IoSQLite_error_(self, zErrMsg);
			IoState_error_(IOSTATE, m, zErrMsg);
		}
		else
		{
			IoSQLite_error_(self, "");
		}
	}

	results = DATA(self)->results;
	DATA(self)->results = NULL;
	return results;
}
Esempio n. 29
0
bool cSQLiteDriver::exec( const QString& query )
{
	char* error;

	if ( sqlite_exec( ( sqlite * ) connection, query.local8Bit(), NULL, NULL, &error ) != SQLITE_OK )
	{
		if ( error )
		{
			QString err( QString( error ) + " (" + query + ")" );
			sqlite_freemem( error );
			throw err;
		}
		else
		{
			throw QString( "Unknown SQLite error while executing: %1" ).arg( query );
		}
	}

	return true;
}
Esempio n. 30
0
bool SqliteDataset::query(const char *query) {
    if (db == NULL)
        return false;
    if(((SqliteDatabase*)db)->getHandle() == NULL)
        return false;
    std::string qry = query;
    int fs = qry.find("select");
    int fS = qry.find("SELECT");
    if (!( fs >= 0 || fS >=0))                                 
         return false;

  close();

  if (  db->setErr(sqlite_exec(handle(),query,&callback,&result,&errmsg),query) == SQLITE_OK) {
        active = true;
	ds_state = dsSelect;
	this->first();
	return true;
   }
   return false;
}