Ejemplo n.º 1
0
static JSVAL sqlite_extended_result_codes(JSARGS args) {
    HandleScope scope;
    Local<External>wrap = Local<External>::Cast(args[0]);
    sqlite3 *db = (sqlite3 *)wrap->Value();
    int onoff = args[1]->IntegerValue()	;
    return scope.Close(Integer::New(sqlite3_extended_result_codes(db, onoff)));
}
Ejemplo n.º 2
0
/** 
 * Opens a SQLite database.
 * @param strFileName - The name of the file to open.
 * @param bReadOnly - true if the file is to be opened read only, else false. (Defaults to false.)
 */
void SQLiteDatabase::open(const std::string& strFileName, bool bReadOnly)
{
        int iReturnCode = SQLITE_OK;
        m_dbName = strFileName;
        std::string tmp_unc_path=Fs::convertToUncPath(m_dbName);
        for(int iIndex=0; iIndex < 10; iIndex++)
        {    
	    iReturnCode = sqlite3_open(tmp_unc_path.c_str(), &m_pdb);
            sqlite3_extended_result_codes(m_pdb, 1);
           
            if (iReturnCode == SQLITE_BUSY)
            {
                Verbose::out(4, "SQLiteDatabase::open failed on attempt " + ::ToStr(iIndex));
                #ifndef WIN32 
                  struct timespec tWait, tRet;
                  tWait.tv_sec = 1;
                  tWait.tv_nsec = 0;
                  nanosleep(&tWait, &tRet);
               #endif 
            }
            else
            {
                break;
            }
        }
        if(iReturnCode != SQLITE_OK)
        {
                Verbose::out(4, "SQLiteDatabase::open failed to open SQLite file  " + FS_QUOTE_PATH(tmp_unc_path) + " with error code " + ::ToStr(iReturnCode));
                error(iReturnCode, "Failed to open SQLite file: "+FS_QUOTE_PATH(tmp_unc_path));
        }
        m_bOpen = true;
}
Ejemplo n.º 3
0
/**
 * Creates a new registry object. To start using a registry, one must first be
 * attached with `reg_attach`.
 *
 * @param [out] regPtr address of the allocated registry
 * @param [out] errPtr on error, a description of the error that occurred
 * @return             true if success; false if failure
 */
int reg_open(reg_registry** regPtr, reg_error* errPtr) {
    reg_registry* reg = malloc(sizeof(reg_registry));
    if (!reg) {
        return 0;
    }
    if (sqlite3_open(NULL, &reg->db) == SQLITE_OK) {
        /* Enable extended result codes, requires SQLite >= 3.3.8
         * Check added for compatibility with Tiger. */
#if SQLITE_VERSION_NUMBER >= 3003008
        sqlite3_extended_result_codes(reg->db, 1);
#endif

        sqlite3_busy_timeout(reg->db, 25);

        if (init_db(reg->db, errPtr)) {
            reg->status = reg_none;
            *regPtr = reg;
            return 1;
        }
    } else {
        reg_sqlite_error(reg->db, errPtr, NULL);
    }
    sqlite3_close(reg->db);
    free(reg);
    return 0;
}
Ejemplo n.º 4
0
bool SQLiteDatabase::open(const String& filename)
{
    close();

    m_openError = SQLiteFileSystem::openDatabase(filename, &m_db);
    if (m_openError != SQLITE_OK) {
        m_openErrorMessage = m_db ? sqlite3_errmsg(m_db) : "sqlite_open returned null";
        WTF_LOG_ERROR("SQLite database failed to load from %s\nCause - %s", filename.ascii().data(),
            m_openErrorMessage.data());
        sqlite3_close(m_db);
        m_db = 0;
        return false;
    }

    m_openError = sqlite3_extended_result_codes(m_db, 1);
    if (m_openError != SQLITE_OK) {
        m_openErrorMessage = sqlite3_errmsg(m_db);
        WTF_LOG_ERROR("SQLite database error when enabling extended errors - %s", m_openErrorMessage.data());
        sqlite3_close(m_db);
        m_db = 0;
        return false;
    }

    if (isOpen())
        m_openingThread = currentThread();
    else
        m_openErrorMessage = "sqlite_open returned null";

    if (!SQLiteStatement(*this, "PRAGMA temp_store = MEMORY;").executeCommand())
        WTF_LOG_ERROR("SQLite database could not set temp_store to memory");

    return isOpen();
}
Ejemplo n.º 5
0
/**
 * Returns a database connexion or NULL.
 * @param database_name is the filename of the file that contains the
 *        database
 * @result returns a db_t * filled with the database connexion or NULL
 *         in case of an error.
 */
db_t *open_database(gchar *database_name)
{
    db_t *database = NULL;
    sqlite3 *db = NULL;
    int result = 0;

    database = (db_t *) g_malloc0(sizeof(db_t));

    result = sqlite3_open(database_name, &db);

    if (result != SQLITE_OK)
        {
            print_db_error(db, _("(%d) Error while trying to open %s database: %s\n"), result, database_name, sqlite3_errmsg(db));
            free_variable(database);
            sqlite3_close(db);

            return NULL;
        }
    else
        {
            database->db = db;
            sqlite3_extended_result_codes(db, 1);
            verify_if_tables_exists(database);

            return database;
        }
}
QgsScopedSqlite::QgsScopedSqlite( const QString& path, bool withExtension )
{
  if ( withExtension )
  {
    // register a statically-linked function as extension
    // for all future database connection
    sqlite3_auto_extension( reinterpret_cast < void( * )() > ( qgsvlayerModuleInit ) );
  }
  int r;
  r = sqlite3_open( path.toLocal8Bit().constData(), &db_ );
  if ( withExtension )
  {
    // reset the automatic extensions
    sqlite3_reset_auto_extension();
  }

  if ( r )
  {
    QString err = QString( "%1 [%2]" ).arg( sqlite3_errmsg( db_ ), path );
    QgsDebugMsg( err );
    throw std::runtime_error( err.toLocal8Bit().constData() );
  }
  // enable extended result codes
  sqlite3_extended_result_codes( db_, 1 );
}
Ejemplo n.º 7
0
bool SQLiteDatabase::open(const String& filename, bool forWebSQLDatabase)
{
    close();

    if (SQLiteFileSystem::openDatabase(filename, &m_db, forWebSQLDatabase) != SQLITE_OK) {
        LOG_ERROR("SQLite database failed to load from %s\nCause - %s", filename.ascii().data(),
            sqlite3_errmsg(m_db));
        sqlite3_close(m_db);
        m_db = 0;
        return false;
    }
    if (sqlite3_extended_result_codes(m_db, 1) != SQLITE_OK) {
        LOG_ERROR("SQLite database error when enabling extended errors - %s", sqlite3_errmsg(m_db));
        sqlite3_close(m_db);
        m_db = 0;
        return false;
    }

    if (isOpen())
        m_openingThread = currentThread();

    if (!SQLiteStatement(*this, "PRAGMA temp_store = MEMORY;").executeCommand())
        LOG_ERROR("SQLite database could not set temp_store to memory");

    return isOpen();
}
Ejemplo n.º 8
0
// open the database, read-only or read/write as specified by the flag. if the
// database is missing: create in write mode, return 0 in read mode.
static _Bool db_open(_Bool write) {
    char *name;
    int err, flags;

    name = dbfilename(NULL);

    if (write)
        flags = SQLITE_OPEN_READWRITE;
    else
        flags = SQLITE_OPEN_READONLY;

    err = sqlite3_open_v2(name, &db, flags, 0);

    if (err != SQLITE_OK && errno == ENOENT) {
        if (!write) return 0;
        flags |= SQLITE_OPEN_CREATE;
        err = sqlite3_open_v2(name, &db, flags, 0);
        if (err == SQLITE_OK)
            db_init();
    }

    if (err != SQLITE_OK) {
        fatal4("cannot open database `", name, "': ", sqlite3_errmsg(db));
        sqlite3_close(db);
    }

    sqlite3_extended_result_codes(db, 1);

    db_check_version();
    return 1;
}
Ejemplo n.º 9
0
 Connection::Connection(const std::string & filename)
 {
     int status = sqlite3_open(filename.c_str(), &_db);
     if(status != SQLITE_OK)
     {
         sqlite3_close(_db);
         throw Runtime_error("Error connecting to db (" +
             filename + "): " + sqlite3_errmsg(_db), "", status, nullptr);
     }
     sqlite3_extended_result_codes(_db, true);
 }
Ejemplo n.º 10
0
ikptr
ik_sqlite3_extended_result_codes (ikptr s_conn, ikptr s_boolean, ikpcb * pcb)
{
#ifdef HAVE_SQLITE3_EXTENDED_RESULT_CODES
  sqlite3 *	conn = IK_SQLITE_CONNECTION(s_conn);
  int		rv;
  rv = sqlite3_extended_result_codes(conn, (IK_FALSE_OBJECT == s_boolean)? 0 : 1);
  return ika_integer_from_sqlite_errcode(pcb,rv);
#else
  feature_failure(__func__);
#endif
}
Ejemplo n.º 11
0
RmSwapTable *rm_swap_table_open(gboolean in_memory, GError **error) {
    RmSwapTable *self = NULL;

    char *path = NULL;

    if(in_memory) {
        path = g_strdup(":memory:");
    } else {
        char pid[20] = {0};
        memset(pid, 0, sizeof(pid));

        g_snprintf(pid, sizeof(pid), "%d", getpid());
        path = g_build_filename(g_get_user_cache_dir(), "rmlint", pid, NULL);

        /* Make sure that path actually exists */
        rm_swap_table_create_cachedir(error);
    }

    /* Might happen if no tmp file could be created */
    if(error && *error) {
        goto cleanup;
    }

    /* We do locking ourselves */
    sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);

    sqlite3 *handle = NULL;
    if(sqlite3_open(path, &handle) != SQLITE_OK) {
        SET_ERROR("Cannot open swap table db");
        goto cleanup;
    }

    /* Finetune sqlite (quite slow without these) */
    sqlite3_extended_result_codes(handle, TRUE);
    sqlite3_exec(handle, "PRAGMA cache_size = 8000;", 0, 0, 0);
    sqlite3_exec(handle, "PRAGMA synchronous = OFF;", 0, 0, 0);
    sqlite3_exec(handle, "PRAGMA journal_mode = MEMORY;", 0, 0, 0);
    sqlite3_enable_shared_cache(TRUE);

    size_t path_len = strlen(path) + 1;
    self = g_malloc(sizeof(RmSwapTable) + path_len);
    self->cache = handle;
    self->attrs = g_ptr_array_new();
    self->transaction_running = FALSE;
    strncpy(self->path, path, path_len);
    g_mutex_init(&self->mtx);

cleanup:
    g_free(path);
    return self;
}
Ejemplo n.º 12
0
Sqlite_connection_t::Sqlite_connection_t(const char * a_file_name)
    : file_name(a_file_name)
{
    Logger * log = Logger::get_instance();

    log->debug(boost::format("Opening connection to SQLite3 database %1%")
               % a_file_name);
    int result = sqlite3_open_v2(a_file_name, &conn, SQLITE_OPEN_READONLY, NULL);
    if(result != SQLITE_OK) {
        signalSqlite3ErrorAndThrow(a_file_name, conn);
    }

    sqlite3_extended_result_codes(conn, 1);
}
SWIGEXPORT jint JNICALL Java_com_almworks_sqlite4java__1SQLiteSwiggedJNI_sqlite3_1extended_1result_1codes(JNIEnv *jenv, jclass jcls, jlong jarg1, jint jarg2) {
  jint jresult = 0 ;
  sqlite3 *arg1 = (sqlite3 *) 0 ;
  int arg2 ;
  int result;
  
  (void)jenv;
  (void)jcls;
  arg1 = *(sqlite3 **)&jarg1; 
  arg2 = (int)jarg2; 
  result = (int)sqlite3_extended_result_codes(arg1,arg2);
  jresult = (jint)result; 
  return jresult;
}
Ejemplo n.º 14
0
bool SQLiteDatabase::open(const String& filename, bool forWebSQLDatabase)
{
    close();

    m_openError = SQLiteFileSystem::openDatabase(filename, &m_db, forWebSQLDatabase);
    if (m_openError != SQLITE_OK) {
        m_openErrorMessage = m_db ? sqlite3_errmsg(m_db) : "sqlite_open returned null";
        LOG_ERROR("SQLite database failed to load from %s\nCause - %s", filename.ascii().data(),
            m_openErrorMessage.data());
        sqlite3_close(m_db);
        m_db = 0;
        return false;
    }

    overrideUnauthorizedFunctions();

    m_openError = sqlite3_extended_result_codes(m_db, 1);
    if (m_openError != SQLITE_OK) {
        m_openErrorMessage = sqlite3_errmsg(m_db);
        LOG_ERROR("SQLite database error when enabling extended errors - %s", m_openErrorMessage.data());
        sqlite3_close(m_db);
        m_db = 0;
        return false;
    }

    if (isOpen())
        m_openingThread = currentThread();
    else
        m_openErrorMessage = "sqlite_open returned null";

    if (!SQLiteStatement(*this, ASCIILiteral("PRAGMA temp_store = MEMORY;")).executeCommand())
        LOG_ERROR("SQLite database could not set temp_store to memory");

    SQLiteStatement walStatement(*this, ASCIILiteral("PRAGMA journal_mode=WAL;"));
    int result = walStatement.step();
    if (result != SQLITE_OK && result != SQLITE_ROW)
        LOG_ERROR("SQLite database failed to set journal_mode to WAL, error: %s",  lastErrorMsg());

#ifndef NDEBUG
    if (result == SQLITE_ROW) {
        String mode = walStatement.getColumnText(0);
        if (!equalIgnoringCase(mode, "wal"))
            LOG_ERROR("journal_mode of database should be 'wal', but is '%s'", mode.utf8().data());
    }
#endif

    return isOpen();
}
Ejemplo n.º 15
0
/**
 * Returns a database connexion or NULL.
 * @param dirname is the name of the directory where the database is
 *        located.
 * @param filename is the filename of the file that contains the
 *        database
 * @result returns a db_t * filled with the database connexion or NULL
 *         in case of an error.
 */
db_t *open_database(gchar *dirname, gchar *filename)
{
    gchar *database_name = NULL;
    db_t *database = NULL;
    sqlite3 *db = NULL;
    int result = 0;

    if (dirname != NULL && filename != NULL)
        {
            create_directory(dirname);
            database_name = g_build_filename(dirname, filename, NULL);
            result = sqlite3_open(database_name, &db);

            if (result != SQLITE_OK)
                {
                    print_db_error(_("(%d) Error while trying to open %s database: %s\n"), result, database_name, sqlite3_errmsg(db));
                    sqlite3_close(db);
                    free_variable(database_name);

                    return NULL;
                }
            else
                {
                    database = (db_t *) g_malloc0(sizeof(db_t));
                    g_assert_nonnull(database);

                    database->version_filename = g_strdup_printf("%s.version", database_name);
                    database->db = db;
                    sqlite3_extended_result_codes(db, 1);

                    verify_if_tables_exists(database);
                    database->stmts = new_stmts(db);
                    database->version = get_database_version(database->version_filename, KN_CLIENT_DATABASE);
                    migrate_schema_if_needed(database);

                    free_variable(database_name);

                    return database;
                }
        }
    else
        {
            return NULL;
        }
}
Ejemplo n.º 16
0
void cduck_db_open ()
{
	FILE* fp = NULL;
	mkdir("/var/cduck", 0700);
	lockFD = open("/var/cduck/cduck.db.lock", O_RDWR | O_CREAT | O_EXLOCK);
	if (fp = fopen("/var/cduck/cduck.db", "r"))
	{
		fclose(fp);
	}
	sqlite3_open("/var/cduck/cduck.db", &db);
	assert(db);
	sqlite3_extended_result_codes(db, 1);
	if (fp == NULL) // this means we didn't open it earlier
	{
		initdb();
	}
	initgroups();
}
Ejemplo n.º 17
0
static void
db_open (void)
{
	gchar	*filename;
	gint	res;

	filename = common_create_data_filename ("liferea.db");
	debug1 (DEBUG_DB, "Opening DB file %s...", filename);
	res = sqlite3_open_v2 (filename, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
	if (SQLITE_OK != res)
		g_error ("Data base file %s could not be opened (error code %d: %s)...", filename, res, sqlite3_errmsg (db));
	g_free (filename);

	sqlite3_extended_result_codes (db, TRUE);

	db_exec("PRAGMA journal_mode=WAL");
	db_exec("PRAGMA page_size=32768");
	db_exec("PRAGMA synchronous=NORMAL");
}
Ejemplo n.º 18
0
int
duf_sqlite_open( const char *dbpath )
{
  int r3 = 0;

/*										*/ DEBUG_START(  );
  if ( !pDb )
  {
    r3 = sqlite3_initialize(  );
    DUF_TRACE( action, 0, "DB Initialize %s (%d)", r3 == SQLITE_OK ? "OK" : "FAIL", r3 );
    if ( r3 == SQLITE_OK )
    {
      /* r3 = sqlite3_open( dbpath, &pDb ); */
      r3 = sqlite3_open_v2( dbpath, &pDb, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL );
      sqlite3_extended_result_codes( pDb, 1 );
      DUF_TRACE( action, 0, "DB Open %s %s (%d)", dbpath, r3 == SQLITE_OK ? "OK" : "FAIL", r3 );
    }
  }
  /*          */ DEBUG_END(  );
  return ( r3 );
}
Ejemplo n.º 19
0
int run_sql_query_buffer(const char* dbpath, 
			 int open_mode, 
			 const char *sqldump, size_t dump_size )
{
    int rc =0;
    sqlite3* db = NULL;

    fprintf( stderr, "open db '%s'\n", dbpath);
    rc = open_db(dbpath, open_mode, &db); 

    /*if error ocured while opening DB*/
    if( rc ){
        fprintf( stderr, 
		 "error opening database, "
		 "errtext %s, errcode=%d\n", 
		 sqlite3_errmsg(db), rc);
    }
    /*if no errors related to opening DB, try to run SQL query */
    else{
	/*enable extended sqlite error code*/
	rc = sqlite3_extended_result_codes(db, 1);
	fprintf(stderr, "sql extended result code enable, err code=%d \n", rc);

	rc = exec_query_print_results(db, sqldump );
	fprintf(stderr, "sql query complete, err code=%d \n", rc);
    }
    
    /*one way to close DB for case with or without errors*/
    sqlite3_close(db);
    fprintf( stderr, "closed db\n");
    fflush(0);

#ifdef READ_ONLY_SQL
    /*just get fd for already opened file*/
    int db_fd = open(dbpath, O_RDONLY);
    close(db_fd); /*release file descriptor for file opened explicitly*/
#endif

    return rc;
}
Ejemplo n.º 20
0
static void init(void) {
	if(sHandle)
		return;

	// todo: error handling
	sqlite3_open("build/db.bin", &sHandle);
	sqlite3_extended_result_codes(sHandle, 1);
	CREATE("'HU.ECCO' (C1 CHAR(2))");
	CREATE("STAFF (EMPNUM CHAR(3) NOT NULL UNIQUE,"
		"EMPNAME  CHAR(20),"
		"GRADE    DECIMAL(4),"
		"CITY     CHAR(15))");
	CREATE("PROJ   (PNUM     CHAR(3) NOT NULL UNIQUE,"
		"PNAME    CHAR(20),"
		"PTYPE    CHAR(6),"
		"BUDGET   DECIMAL(9),"
		"CITY     CHAR(15))");
	CREATE("WORKS (EMPNUM   CHAR(3) NOT NULL,"
		"PNUM     CHAR(3) NOT NULL,"
		"HOURS    DECIMAL(5),"
		"UNIQUE(EMPNUM,PNUM))");
}
Ejemplo n.º 21
0
bool SQLiteDatabase::open(const String& filename)
{
    close();

    m_openError = SQLiteFileSystem::openDatabase(filename, &m_db);
    if (m_openError != SQLITE_OK) {
        m_openErrorMessage = m_db ? sqlite3_errmsg(m_db) : "sqlite_open returned null";
        DLOG(ERROR) << "SQLite database failed to load from " << filename << "\nCause - " << m_openErrorMessage.data();
        sqlite3_close(m_db);
        m_db = 0;
        return false;
    }

    m_openError = sqlite3_extended_result_codes(m_db, 1);
    if (m_openError != SQLITE_OK) {
        m_openErrorMessage = sqlite3_errmsg(m_db);
        DLOG(ERROR) << "SQLite database error when enabling extended errors - " <<  m_openErrorMessage.data();
        sqlite3_close(m_db);
        m_db = 0;
        return false;
    }

    if (isOpen())
        m_openingThread = currentThread();
    else
        m_openErrorMessage = "sqlite_open returned null";

    if (!SQLiteStatement(*this, "PRAGMA temp_store = MEMORY;").executeCommand())
        DLOG(ERROR) << "SQLite database could not set temp_store to memory";

    // Foreign keys are not supported by WebDatabase.  Make sure foreign key support is consistent
    // if SQLite has SQLITE_DEFAULT_FOREIGN_KEYS.
    if (!SQLiteStatement(*this, "PRAGMA foreign_keys = OFF;").executeCommand())
        DLOG(ERROR) << "SQLite database could not turn off foreign_keys";

    return isOpen();
}
Ejemplo n.º 22
0
sqlite3 *
init_db()
{
	sqlite3 *db;
	int rc = 0;

	sqlite3_initialize();
	rc = sqlite3_open_v2(DBPATH, &db,
		SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
	
	if (rc != SQLITE_OK) {
		warnx("%s", sqlite3_errmsg(db));
		sqlite3_shutdown();
		exit(EXIT_FAILURE);
	}
	sqlite3_extended_result_codes(db, 1);


	/* Register the zip and unzip functions for FTS compression */
	rc = sqlite3_create_function(db, "zip", 1, SQLITE_ANY, NULL, 
                             zip, NULL, NULL);
	if (rc != SQLITE_OK) {
		sqlite3_close(db);
		sqlite3_shutdown();
		errx(EXIT_FAILURE, "Unable to register function: compress");
	}

	rc = sqlite3_create_function(db, "unzip", 1, SQLITE_ANY, NULL, 
		                         unzip, NULL, NULL);
	if (rc != SQLITE_OK) {
		sqlite3_close(db);
		sqlite3_shutdown();
		errx(EXIT_FAILURE, "Unable to register function: uncompress");
	}
	return db;

}
Ejemplo n.º 23
0
  Database::Database (const std::string& name, int openFlags) :
      _connection (nullptr)
  {

    if (openFlags == 0)
      {
        openFlags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
      }

    sqlite3* db = nullptr;
    auto sl3rc = sqlite3_open_v2 (name.c_str (), &db, openFlags, 0);

    if (sl3rc != SQLITE_OK)
      {
        SQLite3Error sl3error (sl3rc, sqlite3_errmsg (db));
        sqlite3_close (db);
        throw sl3error;
      }

    _connection.reset (new internal::Connection (db));

    sqlite3_extended_result_codes (_connection->db (), true);

  }
Ejemplo n.º 24
0
 int database::enable_extended_result_codes(bool enable)
 {
   return sqlite3_extended_result_codes(db_, enable ? 1 : 0);
 }
/* init_db --
 *   Prepare the database. Register the compress/uncompress functions and the
 *   stopword tokenizer.
 *	 db_flag specifies the mode in which to open the database. 3 options are 
 *   available:
 *   	1. DB_READONLY: Open in READONLY mode. An error if db does not exist.
 *  	2. DB_READWRITE: Open in read-write mode. An error if db does not exist.
 *  	3. DB_CREATE: Open in read-write mode. It will try to create the db if
 *			it does not exist already.
 *  RETURN VALUES:
 *		The function will return NULL in case the db does not exist and DB_CREATE 
 *  	was not specified. And in case DB_CREATE was specified and yet NULL is 
 *  	returned, then there was some other error.
 *  	In normal cases the function should return a handle to the db.
 */
sqlite3 *
init_db(int db_flag, const char *manconf)
{
	sqlite3 *db = NULL;
	sqlite3_stmt *stmt;
	struct stat sb;
	int rc;
	int create_db_flag = 0;

	char *dbpath = get_dbpath(manconf);
	if (dbpath == NULL)
		errx(EXIT_FAILURE, "_mandb entry not found in man.conf");
	/* Check if the database exists or not */
	if (!(stat(dbpath, &sb) == 0 && S_ISREG(sb.st_mode))) {
		/* Database does not exist, check if DB_CREATE was specified, and set
		 * flag to create the database schema
		 */
		if (db_flag != (MANDB_CREATE)) {
			warnx("Missing apropos database. "
			      "Please run makemandb to create it.");
			return NULL;
		}
		create_db_flag = 1;
	}

	/* Now initialize the database connection */
	sqlite3_initialize();
	rc = sqlite3_open_v2(dbpath, &db, db_flag, NULL);
	
	if (rc != SQLITE_OK) {
		warnx("%s", sqlite3_errmsg(db));
		sqlite3_shutdown();
		return NULL;
	}

	if (create_db_flag && create_db(db) < 0) {
		warnx("%s", "Unable to create database schema");
		goto error;
	}

	rc = sqlite3_prepare_v2(db, "PRAGMA user_version", -1, &stmt, NULL);
	if (rc != SQLITE_OK) {
		warnx("Unable to query schema version: %s",
		    sqlite3_errmsg(db));
		goto error;
	}
	if (sqlite3_step(stmt) != SQLITE_ROW) {
		sqlite3_finalize(stmt);
		warnx("Unable to query schema version: %s",
		    sqlite3_errmsg(db));
		goto error;
	}
	if (sqlite3_column_int(stmt, 0) != APROPOS_SCHEMA_VERSION) {
		sqlite3_finalize(stmt);
		warnx("Incorrect schema version found. "
		      "Please run makemandb -f.");
		goto error;
	}
	sqlite3_finalize(stmt);

	sqlite3_extended_result_codes(db, 1);
	
	/* Register the zip and unzip functions for FTS compression */
	rc = sqlite3_create_function(db, "zip", 1, SQLITE_ANY, NULL, zip, NULL, NULL);
	if (rc != SQLITE_OK) {
		warnx("Unable to register function: compress: %s",
		    sqlite3_errmsg(db));
		goto error;
	}

	rc = sqlite3_create_function(db, "unzip", 1, SQLITE_ANY, NULL, 
                                 unzip, NULL, NULL);
	if (rc != SQLITE_OK) {
		warnx("Unable to register function: uncompress: %s",
		    sqlite3_errmsg(db));
		goto error;
	}
	return db;

error:
	sqlite3_close(db);
	sqlite3_shutdown();
	return NULL;
}
Ejemplo n.º 26
0
DLL_FUNCTION(int32_t) BU_SQLite_Extended_Result_Codes(sqlite3* db, int32_t onoff) {
#pragma comment(linker, "/EXPORT:BU_SQLite_Extended_Result_Codes=_BU_SQLite_Extended_Result_Codes@8")
	return sqlite3_extended_result_codes(db, onoff);
}
Ejemplo n.º 27
0
/* init_db --
 *   Prepare the database. Register the compress/uncompress functions and the
 *   stopword tokenizer.
 *	 db_flag specifies the mode in which to open the database. 3 options are
 *   available:
 *   	1. DB_READONLY: Open in READONLY mode. An error if db does not exist.
 *  	2. DB_READWRITE: Open in read-write mode. An error if db does not exist.
 *  	3. DB_CREATE: Open in read-write mode. It will try to create the db if
 *			it does not exist already.
 *  RETURN VALUES:
 *		The function will return NULL in case the db does not exist
 *		and DB_CREATE
 *  	was not specified. And in case DB_CREATE was specified and yet NULL is
 *  	returned, then there was some other error.
 *  	In normal cases the function should return a handle to the db.
 */
sqlite3 *
init_db(mandb_access_mode db_flag, const char *manconf)
{
	sqlite3 *db = NULL;
	sqlite3_stmt *stmt;
	struct stat sb;
	int rc;
	int create_db_flag = 0;

	char *dbpath = get_dbpath(manconf);
	if (dbpath == NULL)
		errx(EXIT_FAILURE, "_mandb entry not found in man.conf");

	if (!(stat(dbpath, &sb) == 0 && S_ISREG(sb.st_mode))) {
		/* Database does not exist, check if DB_CREATE was specified,
		 * and set flag to create the database schema
		 */
		if (db_flag != (MANDB_CREATE)) {
			warnx("Missing apropos database. "
			      "Please run makemandb to create it.");
			return NULL;
		}
		create_db_flag = 1;
	} else {
		/*
		 * Database exists. Check if we have the permissions
		 * to read/write the files
		 */
		int access_mode = R_OK;
		switch (db_flag) {
		case MANDB_CREATE:
		case MANDB_WRITE:
			access_mode |= W_OK;
			break;
		default:
			break;
		}
		if ((access(dbpath, access_mode)) != 0) {
			warnx("Unable to access the database, please check"
			    " permissions for `%s'", dbpath);
			return NULL;
		}
	}

	sqlite3_initialize();
	rc = sqlite3_open_v2(dbpath, &db, db_flag, NULL);

	if (rc != SQLITE_OK) {
		warnx("%s", sqlite3_errmsg(db));
		goto error;
	}

	if (create_db_flag && create_db(db) < 0) {
		warnx("%s", "Unable to create database schema");
		goto error;
	}

	rc = sqlite3_prepare_v2(db, "PRAGMA user_version", -1, &stmt, NULL);
	if (rc != SQLITE_OK) {
		warnx("Unable to query schema version: %s",
		    sqlite3_errmsg(db));
		goto error;
	}
	if (sqlite3_step(stmt) != SQLITE_ROW) {
		sqlite3_finalize(stmt);
		warnx("Unable to query schema version: %s",
		    sqlite3_errmsg(db));
		goto error;
	}
	if (sqlite3_column_int(stmt, 0) != APROPOS_SCHEMA_VERSION) {
		sqlite3_finalize(stmt);
		warnx("Incorrect schema version found. "
		      "Please run makemandb -f.");
		goto error;
	}
	sqlite3_finalize(stmt);

	sqlite3_extended_result_codes(db, 1);

	/* Register the zip and unzip functions for FTS compression */
	rc = sqlite3_create_function(db, "zip", 1, SQLITE_ANY, NULL, zip,
	    NULL, NULL);
	if (rc != SQLITE_OK) {
		warnx("Unable to register function: compress: %s",
		    sqlite3_errmsg(db));
		goto error;
	}

	rc = sqlite3_create_function(db, "unzip", 1, SQLITE_ANY, NULL,
                                 unzip, NULL, NULL);
	if (rc != SQLITE_OK) {
		warnx("Unable to register function: uncompress: %s",
		    sqlite3_errmsg(db));
		goto error;
	}
	return db;

error:
	close_db(db);
	return NULL;
}
Ejemplo n.º 28
0
 connection::connection(std::string const & db)
     : handle(0){
         open(db);
         sqlite3_extended_result_codes(handle, 1);
 }
Ejemplo n.º 29
0
int open_db(const char* path, int open_mode, sqlite3** db)
{
    int rc=0;

    /*check provided path*/
    struct stat st;
    rc=stat(path, &st);

#ifdef READ_ONLY_SQL
    /*if READ_ONLY  character device or block device specified
     *trying to open channel described by manifest*/
    if ( rc == 0 &&
	 open_mode == EDbReadOnly &&
	 ((st.st_mode&S_IFMT) == S_IFCHR || (st.st_mode&S_IFMT) == S_IFBLK) &&
	 (st.st_mode&S_IRWXU) == S_IRUSR ){
	/*open db filename that will be used by sqlite VFS*/
	int database_fd = open( path, O_RDONLY );
	assert( database_fd >= 0 );
	/*setup mode that forcing opening DB in special READ-ONLY mode
	  with using VFS feature that natively supported by SQLITE but
	  VFS implementation is part of libsqlite3 provided among ZRT library*/
	int regerr = register_fs_channel( database_fd );
	assert( SQLITE_OK == regerr );
	/*Open sqlite db, hosted on our registered VFS, it's used "fake" name
	  that will not be used because sqlite was tuned to use database_fd 
	  descriptor of already opened file*/
	fprintf( stderr, "open db in read only mode\n");
	rc = sqlite3_open_v2( "fake",      /* fake DB name will not be used */
			      db,         /* OUT: SQLite db handle */
			      SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_READONLY,    /* Flags */
			      FS_VFS_NAME  /* Name of VFS module to use */
			      );
    }
    else
#endif
	{
	    fprintf( stderr, "open db in read/write mode\n");
	    rc = sqlite3_open( path,  /* Database filename (UTF-8) */
			       db    /* OUT: SQLite db handle */
			       );
	    
	    /*enable extended sqlite error code*/
	    rc = sqlite3_extended_result_codes(*db, 1);
	    fprintf(stderr, "sql extended result code enable, err code=%d \n", rc);

	    /*disable journaling*/
	    if (!rc){
	    	rc = sqlite_pragma(*db, "PRAGMA journal_mode=MEMORY;" );
	    	fprintf( stderr, "set journal_mode pragma errcode=%d\n", rc);
	    }
	    /*disable using of synchronisation, because it's not supported by ZRT FS*/
	    if (!rc){
	    	rc = sqlite_pragma(*db, "PRAGMA synchronous=OFF;" );
	    	fprintf( stderr, "set syncronous pragma errcode=%d\n", rc);
	    }
	    /*exclusive access to DB by single process*/
	    if (!rc){
	    	rc = sqlite_pragma(*db, "PRAGMA locking_mode=EXCLUSIVE;" );
	    	fprintf( stderr, "set locking_mode pragma errcode=%d\n", rc);
	    }
	}
    return rc;
}