org.sqlite.SQLiteConfig Java Examples

The following examples show how to use org.sqlite.SQLiteConfig. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AccessAccessionMappingDatabase.java    From megan-ce with GNU General Public License v3.0 6 votes vote down vote up
/**
 * constructor, opens and maintains connection to database
 *
 * @param dbFile
 * @throws IOException
 * @throws SQLException
 */
public AccessAccessionMappingDatabase(String dbFile) throws IOException, SQLException {
    if (!Basic.fileExistsAndIsNonEmpty(dbFile))
        throw new IOException("File not found or unreadable: " + dbFile);

    // setting database configurations, as suggested by suggested by takrl at
    // https://stackoverflow.com/questions/784173/what-are-the-performance-characteristics-of-sqlite-with-very-large-database-files
    final SQLiteConfig config = new SQLiteConfig();
    config.setCacheSize(10000);
    config.setReadOnly(true);

    connection = config.createConnection("jdbc:sqlite:" + dbFile);

    if (!fileFilter.apply(executeQueryString("SELECT info_string FROM info WHERE id = 'general';", 1).get(0)))
        throw new IOException("Mapping file " + Basic.getFileNameWithoutPath(dbFile) + " is intended for use with MEGAN Ultimate Edition, it is not compatible with MEGAN Community Edition");
}
 
Example #2
Source File: UdgerParser.java    From udger-java with MIT License 6 votes vote down vote up
private void connect() throws SQLException {
    if (connection == null) {
        SQLiteConfig config = new SQLiteConfig();
        config.setReadOnly(true);
        if (inMemoryEnabled) {
            // we cannot use read only for in memory DB since we need to populate this DB from the file.
            connection = DriverManager.getConnection("jdbc:sqlite::memory:");
            File dbfile = new File(parserDbData.dbFileName);
            try (Statement statement = connection.createStatement()) {
                statement.executeUpdate("restore from " + dbfile.getPath());
            } catch (Exception e) {
                LOG.warning("Error re-constructing in memory data base from Db file " + dbfile);
            }
        } else {
            connection = DriverManager.getConnection("jdbc:sqlite:" + parserDbData.dbFileName, config.toProperties());
        }
    }
}
 
Example #3
Source File: Database.java    From burp-hash with MIT License 6 votes vote down vote up
/**
 * open and return database connections
 */
private Connection getConnection() 
{
	Connection connection;
	SQLiteConfig sc = new SQLiteConfig();
	sc.setEncoding(SQLiteConfig.Encoding.UTF_8);
	try 
	{
		connection = DriverManager.getConnection(connPrefix
				+ config.databaseFilename, sc.toProperties());
		stdOut.println(moduleName + ": Opened database file: " + config.databaseFilename);
	} 
	catch (SQLException e) 
	{
		stdErr.println(e.getMessage());
		return null;
	}
	return connection;
}
 
Example #4
Source File: TMDatabaseImpl.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void start() throws SQLException, ClassNotFoundException {
	File file = new File(metaData.getDataPath()+File.separator+metaData.getDatabaseName());
	if(!file.exists()){
		throw new SQLException("File not found");
	}
	
	SQLiteConfig conf = new SQLiteConfig();
	conf.setSynchronous(SynchronousMode.OFF);

	String url = Utils.replaceParams(dbConfig.getDbURL(), metaData);

	url = url.replace("__FILE_SEPARATOR__", File.separator);
	String driver = dbConfig.getDriver();
	Class.forName(driver);
	Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), metaData);
	SQLiteConfig config = new SQLiteConfig(prop);
	config.setSynchronous(SynchronousMode.OFF);
	conn = DriverManager.getConnection(url, config.toProperties());
	// conn.setAutoCommit(false);
}
 
Example #5
Source File: DBQueries.java    From cqengine with Apache License 2.0 6 votes vote down vote up
public static void setSyncAndJournaling(final Connection connection, final SQLiteConfig.SynchronousMode pragmaSynchronous, final SQLiteConfig.JournalMode pragmaJournalMode){
    Statement statement = null;
    try {
        final boolean autoCommit = DBUtils.setAutoCommit(connection, true);
        statement = connection.createStatement();
        statement.execute("PRAGMA synchronous = " + pragmaSynchronous.getValue());

        // This little transaction will also cause a wanted fsync on the OS to flush the data still in the OS cache to disc.
        statement.execute("PRAGMA journal_mode = " + pragmaJournalMode.getValue());

        DBUtils.setAutoCommit(connection, autoCommit);
    }catch (SQLException e){
        throw new IllegalStateException("Unable to set the 'synchronous' and 'journal_mode' pragmas", e);
    }finally{
        DBUtils.closeQuietly(statement);
    }
}
 
Example #6
Source File: DBQueries.java    From cqengine with Apache License 2.0 6 votes vote down vote up
public static SQLiteConfig.SynchronousMode getPragmaSynchronousOrNull(final Connection connection){
    Statement statement = null;
    try {
        statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery("PRAGMA synchronous;");
        if (resultSet.next()){
            final int syncPragmaId = resultSet.getInt(1);
            if (!resultSet.wasNull()) {
                switch (syncPragmaId){
                    case 0: return SQLiteConfig.SynchronousMode.OFF;
                    case 1: return SQLiteConfig.SynchronousMode.NORMAL;
                    case 2: return SQLiteConfig.SynchronousMode.FULL;
                    default: return null;
                }
            }
        }
        return null;
    }catch (Exception e){
        return null;
    }finally{
        DBUtils.closeQuietly(statement);
    }
}
 
Example #7
Source File: DBQueries.java    From cqengine with Apache License 2.0 6 votes vote down vote up
public static SQLiteConfig.JournalMode getPragmaJournalModeOrNull(final Connection connection){
    Statement statement = null;
    try {
        statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery("PRAGMA journal_mode;");
        if (resultSet.next()){
            final String journalMode = resultSet.getString(1);
            return journalMode != null ? SQLiteConfig.JournalMode.valueOf(journalMode.toUpperCase()) : null;
        }
        return null;
    }catch (Exception e){
        return null;
    }finally{
        DBUtils.closeQuietly(statement);
    }
}
 
Example #8
Source File: DiskPersistenceTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Test
public void testEqualsAndHashCode() {
    SQLiteDataSource ds1 = new SQLiteDataSource(new SQLiteConfig());
    ds1.setUrl("foo");
    SQLiteDataSource ds2 = new SQLiteDataSource(new SQLiteConfig());
    ds2.setUrl("bar");
    EqualsVerifier.forClass(DiskPersistence.class)
            .withIgnoredFields("sqLiteDataSource", "persistentConnection", "closed", "useReadWriteLock", "readWriteLock")
            .suppress(Warning.NULL_FIELDS, Warning.STRICT_INHERITANCE)
            .withPrefabValues(SQLiteDataSource.class, ds1, ds2)
            .verify();
}
 
Example #9
Source File: TMDatabaseImpl.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void start() throws SQLException, ClassNotFoundException {
	SQLiteConfig conf = new SQLiteConfig();
	conf.setSynchronous(SynchronousMode.OFF);

	String url = Utils.replaceParams(dbConfig.getDbURL(), metaData);
	url = url.replace("__FILE_SEPARATOR__", File.separator);
	String driver = dbConfig.getDriver();
	Class.forName(driver);
	Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), metaData);
	SQLiteConfig config = new SQLiteConfig(prop);
	config.setSynchronous(SynchronousMode.OFF);
	conn = DriverManager.getConnection(url, config.toProperties());
	// conn.setAutoCommit(false);
}
 
Example #10
Source File: OperateSystemDBImpl.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * (non-Javadoc)
 * @see net.heartsome.cat.database.SystemDBOperator#getConnection(java.lang.String, java.lang.String,
 *      java.util.Properties)
 */
protected synchronized Connection getConnection(String driver, String url, Properties p)
		throws ClassNotFoundException, SQLException {
	if (conn != null && !conn.isClosed()) {
		if (!conn.getAutoCommit()) {
			conn.commit();
		}
		conn.close();
	}
	Class.forName(driver);
	SQLiteConfig config = new SQLiteConfig(p);
	return config.createConnection(url);
}
 
Example #11
Source File: SqliteDb.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public boolean open( String dbPath ) throws Exception {
    this.mDbPath = dbPath;

    connectionData = new ConnectionData();
    connectionData.connectionLabel = dbPath;
    connectionData.connectionUrl = new String(dbPath);
    connectionData.user = user;
    connectionData.password = password;
    connectionData.dbType = getType().getCode();

    boolean dbExists = false;
    if (dbPath != null) {
        File dbFile = new File(dbPath);
        if (dbFile.exists()) {
            if (mPrintInfos)
                Logger.INSTANCE.insertInfo(null, "Database exists");
            dbExists = true;
        }
    } else {
        dbPath = "file:inmemory?mode=memory";
        dbExists = true;
    }
    // enabling dynamic extension loading
    // absolutely required by SpatiaLite
    SQLiteConfig config = new SQLiteConfig();
    config.enableLoadExtension(true);
    Properties properties = config.toProperties();
    if (user != null && password != null) {
        properties.setProperty("user", user);
        properties.setProperty("password", password);
    }
    jdbcConn = DriverManager.getConnection(EDb.SQLITE.getJdbcPrefix() + dbPath, properties);
    mConn = new HMConnection(jdbcConn, false);
    if (mPrintInfos) {
        String[] dbInfo = getDbInfo();
        Logger.INSTANCE.insertInfo(null, "SQLite Version: " + dbInfo[0]);
    }
    return dbExists;
}
 
Example #12
Source File: SqliteConnectionThreadPool.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
@SneakyThrows
private static Connection getConnection(String database) {
    Class.forName("org.sqlite.JDBC");

    SQLiteConfig config = new SQLiteConfig();
    config.setOpenMode(SQLiteOpenMode.READWRITE);
    config.setOpenMode(SQLiteOpenMode.CREATE);
    config.setOpenMode(SQLiteOpenMode.NOMUTEX);

    return DriverManager.getConnection("jdbc:sqlite:" + database, config.toProperties());
}
 
Example #13
Source File: SqliteConnectionThreadPool.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
@SneakyThrows
private static Connection getConnection(String database) {
    Class.forName("org.sqlite.JDBC");

    SQLiteConfig config = new SQLiteConfig();
    config.setOpenMode(SQLiteOpenMode.READWRITE);
    config.setOpenMode(SQLiteOpenMode.CREATE);
    config.setOpenMode(SQLiteOpenMode.NOMUTEX);

    return DriverManager.getConnection("jdbc:sqlite:" + database, config.toProperties());
}
 
Example #14
Source File: OperateSystemDBImpl.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * (non-Javadoc)
 * @see net.heartsome.cat.database.SystemDBOperator#getConnection(java.lang.String, java.lang.String,
 *      java.util.Properties)
 */
protected synchronized Connection getConnection(String driver, String url, Properties p)
		throws ClassNotFoundException, SQLException {
	if (conn != null && !conn.isClosed()) {
		if (!conn.getAutoCommit()) {
			conn.commit();
		}
		conn.close();
	}
	Class.forName(driver);
	SQLiteConfig config = new SQLiteConfig(p);
	return config.createConnection(url);
}
 
Example #15
Source File: DBQueriesTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Test
public void suspendSyncAndJournaling() throws Exception {
    Connection connection = null;
    try {

        ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
        connection = connectionManager.getConnection(null, noQueryOptions());

        final SQLiteConfig.JournalMode journalMode = DBQueries.getPragmaJournalModeOrNull(connection);
        final SQLiteConfig.SynchronousMode synchronousMode = DBQueries.getPragmaSynchronousOrNull(connection);

        DBQueries.suspendSyncAndJournaling(connection);

        final SQLiteConfig.JournalMode journalModeDisabled = DBQueries.getPragmaJournalModeOrNull(connection);
        final SQLiteConfig.SynchronousMode synchronousModeDisabled = DBQueries.getPragmaSynchronousOrNull(connection);

        Assert.assertEquals(journalModeDisabled, SQLiteConfig.JournalMode.OFF);
        Assert.assertEquals(synchronousModeDisabled, SQLiteConfig.SynchronousMode.OFF);

        DBQueries.setSyncAndJournaling(connection, SQLiteConfig.SynchronousMode.FULL, SQLiteConfig.JournalMode.DELETE);

        final SQLiteConfig.JournalMode journalModeReset = DBQueries.getPragmaJournalModeOrNull(connection);
        final SQLiteConfig.SynchronousMode synchronousModeReset = DBQueries.getPragmaSynchronousOrNull(connection);

        Assert.assertEquals(journalModeReset, journalMode);
        Assert.assertEquals(synchronousModeReset, synchronousMode);

    }finally {
        DBUtils.closeQuietly(connection);
    }
}
 
Example #16
Source File: ModifyAccessionMappingDatabase.java    From megan-ce with GNU General Public License v3.0 5 votes vote down vote up
/**
 * constructor
 *
 * @param databaseFile
 */
public ModifyAccessionMappingDatabase(String databaseFile) throws IOException, SQLException {
    this.databaseFile = databaseFile;

    System.err.println("Database '" + databaseFile + "', current contents: ");
    try (AccessAccessionMappingDatabase accessAccessionMappingDatabase = new AccessAccessionMappingDatabase(databaseFile)) {
        System.err.println(accessAccessionMappingDatabase.getInfo());
    }

    config = new SQLiteConfig();
    config.setCacheSize(10000);
    config.setLockingMode(SQLiteConfig.LockingMode.EXCLUSIVE);
    config.setSynchronous(SQLiteConfig.SynchronousMode.NORMAL);
    config.setJournalMode(SQLiteConfig.JournalMode.WAL);
}
 
Example #17
Source File: OffHeapPersistenceTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Test
public void testEqualsAndHashCode() {
    SQLiteDataSource ds1 = new SQLiteDataSource(new SQLiteConfig());
    ds1.setUrl("foo");
    SQLiteDataSource ds2 = new SQLiteDataSource(new SQLiteConfig());
    ds2.setUrl("bar");
    EqualsVerifier.forClass(OffHeapPersistence.class)
            .withIgnoredFields("sqLiteDataSource", "persistentConnection", "closed", "readWriteLock")
            .suppress(Warning.NULL_FIELDS, Warning.STRICT_INHERITANCE)
            .withPrefabValues(SQLiteDataSource.class, ds1, ds2)
            .verify();
}
 
Example #18
Source File: DiskPersistence.java    From cqengine with Apache License 2.0 5 votes vote down vote up
protected DiskPersistence(SimpleAttribute<O, A> primaryKeyAttribute, File file, Properties overrideProperties) {
    Properties effectiveProperties = new Properties();
    effectiveProperties.putAll(DEFAULT_PROPERTIES);
    effectiveProperties.putAll(overrideProperties);
    SQLiteConfig sqLiteConfig = new SQLiteConfig(effectiveProperties);
    SQLiteDataSource sqLiteDataSource = new SQLiteDataSource(sqLiteConfig);
    sqLiteDataSource.setUrl("jdbc:sqlite:file:" + file);

    this.primaryKeyAttribute = primaryKeyAttribute;
    this.file = file.getAbsoluteFile();
    this.sqLiteDataSource = sqLiteDataSource;

    boolean openPersistentConnection = "true".equals(effectiveProperties.getProperty("persistent_connection")); //default false
    boolean useSharedCache = "true".equals(effectiveProperties.getProperty("shared_cache")); // default false
    boolean useReadWriteLock = !"false".equals(effectiveProperties.getProperty("use_read_write_lock")); // default true
    if (useSharedCache) {
        // If shared_cache mode is enabled, by default we also use a read-write lock,
        // unless using the read-write lock has been explicitly disabled...
        sqLiteDataSource.setUrl("jdbc:sqlite:file:" + file + "?cache=shared");
        this.useReadWriteLock = useReadWriteLock;
    }
    else {
        // If we are not using shared_cache mode, we never use a read-write lock...
        sqLiteDataSource.setUrl("jdbc:sqlite:file:" + file);
        this.useReadWriteLock = false;
    }
    if (useSharedCache || openPersistentConnection) {
        // If shared_cache is enabled, we always open a persistent connection regardless...
        this.persistentConnection = getConnectionWithoutRWLock(null, noQueryOptions());
    }
}
 
Example #19
Source File: OffHeapPersistence.java    From cqengine with Apache License 2.0 5 votes vote down vote up
protected OffHeapPersistence(SimpleAttribute<O, A> primaryKeyAttribute, Properties overrideProperties) {
    Properties effectiveProperties = new Properties(DEFAULT_PROPERTIES);
    effectiveProperties.putAll(overrideProperties);
    SQLiteConfig sqLiteConfig = new SQLiteConfig(effectiveProperties);
    SQLiteDataSource sqLiteDataSource = new SQLiteDataSource(sqLiteConfig);
    String instanceName = "cqengine_" + INSTANCE_ID_GENERATOR.incrementAndGet();
    sqLiteDataSource.setUrl("jdbc:sqlite:file:" + instanceName + "?mode=memory&cache=shared");

    this.primaryKeyAttribute = primaryKeyAttribute;
    this.instanceName = instanceName;
    this.sqLiteDataSource = sqLiteDataSource;
    this.persistentConnection = getConnectionInternal(null, noQueryOptions());
}
 
Example #20
Source File: ScoreLogDatabaseAccessor.java    From beatoraja with GNU General Public License v3.0 5 votes vote down vote up
public ScoreLogDatabaseAccessor(String path) throws ClassNotFoundException {
	Class.forName("org.sqlite.JDBC");
	SQLiteConfig conf = new SQLiteConfig();
	conf.setSharedCache(true);
	conf.setSynchronous(SynchronousMode.OFF);
	// conf.setJournalMode(JournalMode.MEMORY);
	ds = new SQLiteDataSource(conf);
	ds.setUrl("jdbc:sqlite:" + path);
	qr = new QueryRunner(ds);
	createTable();		
}
 
Example #21
Source File: SQLiteSongDatabaseAccessor.java    From beatoraja with GNU General Public License v3.0 5 votes vote down vote up
public SQLiteSongDatabaseAccessor(String filepath, String[] bmsroot) throws ClassNotFoundException {
	Class.forName("org.sqlite.JDBC");
	SQLiteConfig conf = new SQLiteConfig();
	conf.setSharedCache(true);
	conf.setSynchronous(SynchronousMode.OFF);
	// conf.setJournalMode(JournalMode.MEMORY);
	ds = new SQLiteDataSource(conf);
	ds.setUrl("jdbc:sqlite:" + filepath);
	qr = new QueryRunner(ds);
	root = Paths.get(".");
	createTable();
}
 
Example #22
Source File: SongInformationAccessor.java    From beatoraja with GNU General Public License v3.0 5 votes vote down vote up
public SongInformationAccessor(String filepath) throws ClassNotFoundException {
	Class.forName("org.sqlite.JDBC");
	SQLiteConfig conf = new SQLiteConfig();
	conf.setSharedCache(true);
	conf.setSynchronous(SynchronousMode.OFF);
	// conf.setJournalMode(JournalMode.MEMORY);
	ds = new SQLiteDataSource(conf);
	ds.setUrl("jdbc:sqlite:" + filepath);
	qr = new QueryRunner(ds);
	createTable();
}
 
Example #23
Source File: ScoreDatabaseAccessor.java    From beatoraja with GNU General Public License v3.0 5 votes vote down vote up
public ScoreDatabaseAccessor(String path) throws ClassNotFoundException {
	Class.forName("org.sqlite.JDBC");
	SQLiteConfig conf = new SQLiteConfig();
	conf.setSharedCache(true);
	conf.setSynchronous(SynchronousMode.OFF);
	// conf.setJournalMode(JournalMode.MEMORY);
	SQLiteDataSource ds = new SQLiteDataSource(conf);
	ds.setUrl("jdbc:sqlite:" + path);
	qr = new QueryRunner(ds);
}
 
Example #24
Source File: TemporaryDatabase.java    From cqengine with Apache License 2.0 4 votes vote down vote up
public TemporaryFileDatabase() {
    this.config = new SQLiteConfig();
}
 
Example #25
Source File: TemporaryDatabase.java    From cqengine with Apache License 2.0 4 votes vote down vote up
public TemporaryFileDatabase(SQLiteConfig config) {
    this.config = config;
}
 
Example #26
Source File: TemporaryDatabase.java    From cqengine with Apache License 2.0 4 votes vote down vote up
public TemporaryInMemoryDatabase(final SQLiteConfig config){
    this.config = config;
}
 
Example #27
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 4 votes vote down vote up
/**
 * Verifies that if connectionManager.isApplyUpdateForIndexEnabled() returns false,
 * init() will do nothing.
 */
@Test
public void testInit_ApplyUpdateForIndexIsFalse() throws Exception{
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connection = mock(Connection.class);
    when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
    // Simulate isApplyUpdateForIndexEnabled == false...
    when(connectionManager.isApplyUpdateForIndexEnabled(any(SQLiteIndex.class))).thenReturn(false);

    Statement statement = mock(Statement.class);
    when(connection.createStatement()).thenReturn(statement);

    java.sql.ResultSet journalModeRs = mock(java.sql.ResultSet.class);
    java.sql.ResultSet synchronousRs = mock(java.sql.ResultSet.class);
    when(journalModeRs.next()).thenReturn(true).thenReturn(false);
    when(synchronousRs.next()).thenReturn(true).thenReturn(false);

    when(journalModeRs.getString(1)).thenReturn("DELETE");
    when(synchronousRs.getInt(1)).thenReturn(2);

    when(statement.executeQuery("PRAGMA journal_mode;")).thenReturn(journalModeRs);
    when(statement.executeQuery("PRAGMA synchronous;")).thenReturn(synchronousRs);

    SQLiteIndex<String, Car, Integer> carFeaturesOffHeapIndex = new SQLiteIndex<String, Car, Integer>(
            Car.FEATURES,
            OBJECT_TO_ID,
            ID_TO_OBJECT,
            ""
    );

    carFeaturesOffHeapIndex.init(emptyObjectStore(), createQueryOptions(connectionManager));

    verify(statement, times(1)).executeQuery("PRAGMA journal_mode;");
    verify(statement, times(1)).executeQuery("PRAGMA synchronous;");
    verify(statement, times(2)).close();

    Assert.assertEquals(carFeaturesOffHeapIndex.pragmaSynchronous, SQLiteConfig.SynchronousMode.FULL);
    Assert.assertEquals(carFeaturesOffHeapIndex.pragmaJournalMode, SQLiteConfig.JournalMode.DELETE);
    Assert.assertTrue(carFeaturesOffHeapIndex.canModifySyncAndJournaling);

}
 
Example #28
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 4 votes vote down vote up
/**
 * Verifies that if connectionManager.isApplyUpdateForIndexEnabled() returns true,
 * and the index table does not exist, init() will create and populate the index table.
 */
@Test
public void testInit_IndexTableDoesNotExist() throws Exception{
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connection = mock(Connection.class);
    Statement statement = mock(Statement.class);
    PreparedStatement preparedStatement = mock(PreparedStatement.class);

    java.sql.ResultSet tableCheckRs = mock(java.sql.ResultSet.class);
    java.sql.ResultSet journalModeRs = mock(java.sql.ResultSet.class);
    java.sql.ResultSet synchronousRs = mock(java.sql.ResultSet.class);
    when(tableCheckRs.next()).thenReturn(false); // <- simulates table does not already exist
    when(journalModeRs.next()).thenReturn(true).thenReturn(false);
    when(synchronousRs.next()).thenReturn(true).thenReturn(false);

    when(journalModeRs.getString(1)).thenReturn("DELETE");
    when(synchronousRs.getInt(1)).thenReturn(2);

    when(statement.executeQuery("SELECT 1 FROM sqlite_master WHERE type='table' AND name='cqtbl_features';")).thenReturn(tableCheckRs);
    when(statement.executeQuery("PRAGMA journal_mode;")).thenReturn(journalModeRs);
    when(statement.executeQuery("PRAGMA synchronous;")).thenReturn(synchronousRs);

    when(connection.prepareStatement("INSERT OR IGNORE INTO " + TABLE_NAME + " values(?, ?);")).thenReturn(preparedStatement);
    when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
    when(connectionManager.isApplyUpdateForIndexEnabled(any(SQLiteIndex.class))).thenReturn(true);
    when(connection.createStatement()).thenReturn(statement);
    when(preparedStatement.executeBatch()).thenReturn(new int[] {2});

    // The objects to add
    Set<Car> initWithObjects = new HashSet<Car>(2);
    initWithObjects.add(new Car(1, "Ford", "Focus", Car.Color.BLUE, 5, 9000.50, Arrays.asList("abs", "gps"), Collections.emptyList()));
    initWithObjects.add(new Car(2, "Honda", "Civic", Car.Color.RED, 5, 5000.00, Arrays.asList("airbags"), Collections.emptyList()));

    SQLiteIndex<String, Car, Integer> carFeaturesOffHeapIndex = new SQLiteIndex<String, Car, Integer>(
            Car.FEATURES,
            OBJECT_TO_ID,
            ID_TO_OBJECT,
            ""
    );

    carFeaturesOffHeapIndex.init(wrappingObjectStore(initWithObjects), createQueryOptions(connectionManager));

    // Verify
    verify(statement, times(1)).executeQuery("PRAGMA journal_mode;");
    verify(statement, times(1)).executeQuery("PRAGMA synchronous;");
    verify(statement, times(1)).executeUpdate("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (objectKey INTEGER, value TEXT, PRIMARY KEY (objectKey, value)) WITHOUT ROWID;");
    verify(statement, times(1)).executeUpdate("CREATE INDEX IF NOT EXISTS " + INDEX_NAME + " ON " + TABLE_NAME + " (value);");
    verify(statement, times(6)).close();

    verify(preparedStatement, times(2)).setObject(1, 1);
    verify(preparedStatement, times(1)).setObject(1, 2);
    verify(preparedStatement, times(1)).setObject(2, "abs");
    verify(preparedStatement, times(1)).setObject(2, "gps");
    verify(preparedStatement, times(1)).setObject(2, "airbags");
    verify(preparedStatement, times(3)).addBatch();
    verify(preparedStatement, times(1)).executeBatch();
    verify(preparedStatement, times(1)).close();

    verify(connection, times(0)).close();

    Assert.assertEquals(carFeaturesOffHeapIndex.pragmaSynchronous, SQLiteConfig.SynchronousMode.FULL);
    Assert.assertEquals(carFeaturesOffHeapIndex.pragmaJournalMode, SQLiteConfig.JournalMode.DELETE);
    Assert.assertTrue(carFeaturesOffHeapIndex.canModifySyncAndJournaling);
}
 
Example #29
Source File: DBQueries.java    From cqengine with Apache License 2.0 4 votes vote down vote up
public static void suspendSyncAndJournaling(final Connection connection){
    setSyncAndJournaling(connection, SQLiteConfig.SynchronousMode.OFF, SQLiteConfig.JournalMode.OFF);
}
 
Example #30
Source File: SQLiteDataSource.java    From ofexport2 with Apache License 2.0 4 votes vote down vote up
@Override
public Connection getConnection() throws SQLException {
    final SQLiteConfig config = new SQLiteConfig();
    config.setReadOnly(this.readOnly);
    return DriverManager.getConnection(getDriverURL(), config.toProperties());
}