Exemplo n.º 1
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);
}
Exemplo n.º 2
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);
}
Exemplo n.º 3
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);
}
Exemplo 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);
}
Exemplo n.º 5
0
/*
** Execute an SQL statement.
** Return a Cursor object if the statement is a query, otherwise
** return the number of tuples affected by the statement.
*/
static int conn_execute(lua_State *L)
{
	conn_data *conn = getconnection(L);
	const char *statement = luaL_checkstring(L, 2);
    int res;
    sqlite_vm *vm;
    char *errmsg;
    int numcols;
    const char **col_info;

    res = sqlite_compile(conn->sql_conn, statement, NULL, &vm, &errmsg);
    if (res != SQLITE_OK)
    {
        lua_pushnil(L);
        lua_pushliteral(L, LUASQL_PREFIX);
        lua_pushstring(L, errmsg);
        sqlite_freemem(errmsg);
        lua_concat(L, 2);
        return 2;
    }

    /* process first result to retrive query information and type */
    res = sqlite_step(vm, &numcols, NULL, &col_info);

    /* real query? if empty, must have numcols!=0 */
	if ((res == SQLITE_ROW) || ((res == SQLITE_DONE) && numcols))
	{
		sqlite_reset(vm, NULL);
		return create_cursor(L, 1, conn, vm, numcols, col_info);
	}

    if (res == SQLITE_DONE) /* and numcols==0, INSERT,UPDATE,DELETE statement */
    {
        sqlite_finalize(vm, NULL);
        /* return number of columns changed */
        lua_pushnumber(L, sqlite_changes(conn->sql_conn));
        return 1;
    }

    /* error */
    sqlite_finalize(vm, &errmsg);
    lua_pushnil(L);
    lua_pushliteral(L, LUASQL_PREFIX);
    lua_pushstring(L, errmsg);
    sqlite_freemem(errmsg);
    lua_concat(L, 2);
    return 2;
}
Exemplo n.º 6
0
bool cSQLiteDriver::open( int )
{
	char* error = NULL;

	close();

	connection = sqlite_open( _dbname.latin1(), 0, &error );

	if ( !connection )
	{
		if ( error )
		{
			QString err( error );
			sqlite_freemem( error );
			throw err;
		}
		else
		{
			throw QString( "Unknown SQLite error while opening database." );
		}
	}

	exec( "PRAGMA synchronous = OFF;" );
	exec( "PRAGMA default_synchronous = OFF;" );
	exec( "PRAGMA full_column_names = OFF;" );
	exec( "PRAGMA show_datatypes = OFF;" );
	exec( "PRAGMA parser_trace = OFF;" );

	return true;
}
Exemplo n.º 7
0
/*
   SQLite dbs have no user name, passwords, hosts or ports.
   just file names.
*/
bool QSQLite2Driver::open(const QString & db, const QString &, const QString &, const QString &, int, const QString &)
{
    if (isOpen())
        close();

    if (db.isEmpty())
        return false;

    char* err = 0;
    d->access = sqlite_open(QFile::encodeName(db), 0, &err);
    if (err) {
        setLastError(QSqlError(tr("Error opening database"), QString::fromAscii(err),
                     QSqlError::ConnectionError));
        sqlite_freemem(err);
        err = 0;
    }

    if (d->access) {
        setOpen(true);
        setOpenError(false);
        return true;
    }
    setOpenError(true);
    return false;
}
Exemplo n.º 8
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;
}
Exemplo n.º 9
0
/*
** Usage:  sqlite_reset   VM 
**
** Reset a virtual machine and prepare it to be run again.
*/
static int test_reset(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  sqlite_vm *vm;
  int rc;
  char *zErrMsg = 0;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
       " VM\"", 0);
    return TCL_ERROR;
  }
  if( getVmPointer(interp, argv[1], &vm) ) return TCL_ERROR;
  rc = sqlite_reset(vm, &zErrMsg);
  if( rc ){
    char zBuf[50];
    sprintf(zBuf, "(%d) ", rc);
    Tcl_AppendResult(interp, zBuf, zErrMsg, 0);
    sqlite_freemem(zErrMsg);
    return TCL_ERROR;
  }
  return TCL_OK;
}
Exemplo n.º 10
0
// Call this to free the query
void cDBResult::free()
{
	if ( mysql_type )
	{
#ifdef MYSQL_DRIVER
		mysql_free_result( ( st_mysql_res * ) _result );
#endif
	}
	else
	{
		char* error;
		if ( sqlite_finalize( ( sqlite_vm * ) _result, &error ) != SQLITE_OK )
		{
			if ( error )
			{
				QString err( error );
				sqlite_freemem( error );
				throw err;
			}
			else
			{
				throw QString( "Unknown SQLite error while finalizing query." );
			}
		}
	}

	_result = 0;
	_row = 0;
	_connection = 0;
}
Exemplo n.º 11
0
/*
** Free the results of a db_query() call.
*/
void db_query_free(char **az){
  int i;
  for(i=0; az[i]; i++){
    sqlite_freemem(az[i]);
  }
  free(az);
}
Exemplo n.º 12
0
/*
** Usage:  sqlite_compile  DB  SQL  ?TAILVAR?
**
** Attempt to compile an SQL statement.  Return a pointer to the virtual
** machine used to execute that statement.  Unprocessed SQL is written
** into TAILVAR.
*/
static int test_compile(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  sqlite *db;
  sqlite_vm *vm;
  int rc;
  char *zErr = 0;
  const char *zTail;
  char zBuf[50];
  if( argc!=3 && argc!=4 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], 
       " DB SQL TAILVAR", 0);
    return TCL_ERROR;
  }
  if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
  rc = sqlite_compile(db, argv[2], argc==4 ? &zTail : 0, &vm, &zErr);
  if( argc==4 ) Tcl_SetVar(interp, argv[3], zTail, 0);
  if( rc ){
    assert( vm==0 );
    sprintf(zBuf, "(%d) ", rc);
    Tcl_AppendResult(interp, zBuf, zErr, 0);
    sqlite_freemem(zErr);
    return TCL_ERROR;
  }
  if( vm ){
    if( makePointerStr(interp, zBuf, vm) ) return TCL_ERROR;
    Tcl_AppendResult(interp, zBuf, 0);
  }
  return TCL_OK;
}
Exemplo n.º 13
0
QueryResult* DatabaseSqlite::Query(const char *sql)
{
    char *errmsg;

    if (!mSqlite)
        return 0;

    char **tableData;
    int rowCount;
    int fieldCount;

    sqlite_get_table(mSqlite, sql, &tableData, &rowCount, &fieldCount, &errmsg);

    if (!rowCount)
        return 0;

    if (!tableData)
    {

        if (errmsg)
            sqlite_freemem(errmsg);
        return 0;
    }

    QueryResultSqlite *queryResult = new QueryResultSqlite(tableData, rowCount, fieldCount);
    if(!queryResult)
    {

        return 0;
    }

    queryResult->NextRow();

    return queryResult;
}
Exemplo n.º 14
0
void kr_dbError (KR_API *db) {
	memset (db->err, 0, 1024);
	if ( db->dberr != NULL )
		sprintf (db->err, "%s (Table: %s)", db->dberr, db->table);
		//strcpy (db->err, db->dberr);
	sqlite_freemem (db->dberr);
}
Exemplo n.º 15
0
void CMusikPlayer::_ChooseRandomAlbumSongs(int nAlbumsToAdd,CMusikSongArray &arrAlbumSongs)
{
	if(nAlbumsToAdd <= 0)
		return;
	int nMaxRepeatCount = 30;
	int hours = wxGetApp().Prefs.nAutoDjDoNotPlaySongPlayedTheLastNHours;
	char * count_query = sqlite_mprintf("select count(*) from autodj_albums where most_lastplayed = '' or most_lastplayed < julianday('now','-%d hours');",hours);
	int albums_count = wxGetApp().Library.QueryCount(count_query);
	sqlite_freemem( count_query );
	wxArrayString arrAlbums;
	while ( (nMaxRepeatCount > 0) && ( arrAlbums.GetCount() < (size_t)nAlbumsToAdd ))
	{
		int r = (size_t) (albums_count * (GetRandomNumber() / (RandomMax + 1.0)));  // random range  [0 , albums_count-1] 
		wxString sQueryRandomAlbum = wxString::Format(wxT("select album||'|'||artist from autodj_albums where most_lastplayed = '' or most_lastplayed < julianday('now','-%d hours') limit 1 offset %d;") 
											,nMaxRepeatCount < 5 ? 1 : (int)wxGetApp().Prefs.nAutoDjDoNotPlaySongPlayedTheLastNHours,r);

		wxArrayString newAlbums;
		wxGetApp().Library.Query(sQueryRandomAlbum,newAlbums,false);
		bool repeat = false;
		if(newAlbums.GetCount() > 0)
		{
			//--- check for repeats ---//
			for ( size_t j = 0;  j < arrAlbums.GetCount(); j++ )
			{
				if ( newAlbums[0] == arrAlbums[j] )
				{
					repeat = true; 
					break;
				}
			}
		}
		else
			repeat = true;

		if(!repeat)
			arrAlbums.Add(newAlbums[0]);
		else
			nMaxRepeatCount--;

	} 

	
	
	for(size_t i = 0;i < arrAlbums.GetCount();i++)
	{
		wxString sQuery;
		sQuery.Alloc( 80);
		arrAlbums[i].Replace( wxT( "'" ), wxT( "''" ));
		wxArrayString album_artist;
		DelimitStr(arrAlbums[i],wxT("|"),album_artist);
		sQuery+=wxT("album='");
		sQuery+=album_artist[0];
		sQuery+=wxT("' and artist='");
		sQuery+=album_artist[1];
		sQuery+=wxT("' order by tracknum");
		wxGetApp().Library.QuerySongsWhere(sQuery ,arrAlbumSongs,false,false);	
	}
	

}
Exemplo n.º 16
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;
}
Exemplo n.º 17
0
void QSQLiteResultPrivate::finalize()
{
    if (!currentMachine)
        return;

    char* err = 0;
    int res = sqlite_finalize(currentMachine, &err);
    if (err) {
        q->setLastError(QSqlError("Unable to fetch results", err, QSqlError::Statement, res));
        sqlite_freemem(err);
    }
    currentMachine = 0;
}
Exemplo n.º 18
0
Arquivo: IoSQLite.c Projeto: Akiyah/io
IoObject *IoSQLite_escapeString(IoSQLite *self, IoObject *locals, IoMessage *m)
{
	/*doc SQLite escapeString(aString)
	Returns a translated version of aString by making two 
	copies of every single-quote (') character. This has the effect 
	of escaping the end-of-string meaning of single-quote within a string literal.
	*/

	IoSymbol *s = IoMessage_locals_seqArgAt_(m, locals, 0);
	char *newString = sqlite_mprintf("%q", CSTRING(s));
	UArray *ba = UArray_newWithCString_(newString);
	sqlite_freemem(newString);
	return IoState_symbolWithUArray_copy_(IOSTATE, ba, 0);
}
Exemplo n.º 19
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);
}
Exemplo n.º 20
0
/*
 * smb_nic_dbopen
 *
 * Opens host database with the given mode.
 */
static sqlite *
smb_nic_dbopen(int mode)
{
	sqlite *db;
	char *errmsg = NULL;

	db = sqlite_open(SMB_NIC_DB_NAME, mode, &errmsg);
	if (db == NULL) {
		syslog(LOG_ERR, "Failed to open host database: %s (%s).",
		    SMB_NIC_DB_NAME, NULL_MSGCHK(errmsg));
		sqlite_freemem(errmsg);
	}

	return (db);
}
Exemplo n.º 21
0
void QSQLite2ResultPrivate::finalize()
{
    if (!currentMachine)
        return;

    char* err = 0;
    int res = sqlite_finalize(currentMachine, &err);
    if (err) {
        q->setLastError(QSqlError(QCoreApplication::translate("QSQLite2Result",
                                  "Unable to fetch results"), QString::fromAscii(err),
                                  QSqlError::StatementError, res));
        sqlite_freemem(err);
    }
    currentMachine = 0;
}
Exemplo n.º 22
0
static int conn_escape(lua_State *L)
{
    const char *from = luaL_checklstring (L, 2, 0);
    char *escaped = sqlite_mprintf("%q", from);
    if (escaped == NULL) 
    {
        lua_pushnil(L);
    } 
    else
    {
        lua_pushstring(L, escaped);        
        sqlite_freemem(escaped);
    }
    return 1;
}
Exemplo n.º 23
0
/*
** Finalizes the vm
** Return nil + errmsg or nil in case of sucess
*/
static int finalize(lua_State *L, cur_data *cur) {
    char *errmsg;
    if (sqlite_finalize(cur->sql_vm, &errmsg) != SQLITE_OK)
    {
        cur->sql_vm = NULL;
        lua_pushnil(L);
        lua_pushliteral(L, LUASQL_PREFIX);
        lua_pushstring(L, errmsg);
        sqlite_freemem(errmsg);
        lua_concat(L, 2);
        return 2;
    }
	lua_pushnil(L);
    return 1;
}
Exemplo 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;
}
Exemplo 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;
}
Exemplo n.º 26
0
bool DatabaseSqlite::Initialize(const char *infoString)
{
    char *errmsg;

    mSqlite = sqlite_open(infoString, 0, &errmsg);

    if (!mSqlite)
    {

        if (errmsg)
            sqlite_freemem(errmsg);
        return false;
    }

    return true;
}
Exemplo 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;
}
Exemplo n.º 28
0
/*
** Connects to a data source.
*/
static int env_connect(lua_State *L)
{
    const char *sourcename;
	sqlite *conn;
    char *errmsg;
	getenvironment(L);  /* validate environment */
    sourcename = luaL_checkstring(L, 2);
    conn = sqlite_open(sourcename, 0, &errmsg);
    if (conn == NULL)
    {
        lua_pushnil(L);
        lua_pushliteral(L, LUASQL_PREFIX);
        lua_pushstring(L, errmsg);
        sqlite_freemem(errmsg);
        lua_concat(L, 2);
        return 2;
    }
    return create_connection(L, 1, conn);
}
Exemplo n.º 29
0
/*
** Called for each row of the result.
**
** This version is used when either of the following is true:
**
**    (1) This version of TCL uses UTF-8 and the data in the
**        SQLite database is already in the UTF-8 format.
**
**    (2) This version of TCL uses ISO8859 and the data in the
**        SQLite database is already in the ISO8859 format.
*/
static int DbEvalCallback(
  void *clientData,      /* An instance of CallbackData */
  int nCol,              /* Number of columns in the result */
  char ** azCol,         /* Data for each column */
  char ** azN            /* Name for each column */
){
  CallbackData *cbData = (CallbackData*)clientData;
  int i, rc;
  if( azCol==0 || (cbData->once && cbData->zArray[0]) ){
    Tcl_SetVar2(cbData->interp, cbData->zArray, "*", "", 0);
    for(i=0; i<nCol; i++){
      Tcl_SetVar2(cbData->interp, cbData->zArray, "*", azN[i],
         TCL_LIST_ELEMENT|TCL_APPEND_VALUE);
      if( azN[nCol] ){
        char *z = sqlite_mprintf("typeof:%s", azN[i]);
        Tcl_SetVar2(cbData->interp, cbData->zArray, z, azN[i+nCol],
           TCL_LIST_ELEMENT|TCL_APPEND_VALUE);
        sqlite_freemem(z);
      }
    }
    cbData->once = 0;
  }
  if( azCol!=0 ){
    if( cbData->zArray[0] ){
      for(i=0; i<nCol; i++){
        char *z = azCol[i];
        if( z==0 ) z = "";
        Tcl_SetVar2(cbData->interp, cbData->zArray, azN[i], z, 0);
      }
    }else{
      for(i=0; i<nCol; i++){
        char *z = azCol[i];
        if( z==0 ) z = "";
        Tcl_SetVar(cbData->interp, azN[i], z, 0);
      }
    }
  }
  rc = Tcl_EvalObj(cbData->interp, cbData->pCode);
  if( rc==TCL_CONTINUE ) rc = TCL_OK;
  cbData->tcl_rc = rc;
  return rc!=TCL_OK;
}
Exemplo n.º 30
0
/*
   Execute \a query.
*/
bool QSQLite2Result::reset (const QString& query)
{
    // this is where we build a query.
    if (!driver())
        return false;
    if (!driver()-> isOpen() || driver()->isOpenError())
        return false;

    d->cleanup();

    // Um, ok.  callback based so.... pass private static function for this.
    setSelect(false);
    char *err = 0;
    int res = sqlite_compile(d->access,
                                d->utf8 ? query.toUtf8().constData()
                                        : query.toAscii().constData(),
                                &(d->currentTail),
                                &(d->currentMachine),
                                &err);
    if (res != SQLITE_OK || err) {
        setLastError(QSqlError(QCoreApplication::translate("QSQLite2Result",
                     "Unable to execute statement"), QString::fromAscii(err),
                     QSqlError::StatementError, res));
        sqlite_freemem(err);
    }
    //if (*d->currentTail != '\000' then there is more sql to eval
    if (!d->currentMachine) {
        setActive(false);
        return false;
    }
    // we have to fetch one row to find out about
    // the structure of the result set
    d->skippedStatus = d->fetchNext(d->firstRow, 0, true);
    if (lastError().isValid()) {
        setSelect(false);
        setActive(false);
        return false;
    }
    setSelect(!d->rInf.isEmpty());
    setActive(true);
    return true;
}