com.j256.ormlite.support.ConnectionSource Java Examples
The following examples show how to use
com.j256.ormlite.support.ConnectionSource.
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: DaoManager.java From ormlite-core with ISC License | 6 votes |
/** * Helper method to lookup a DAO if it has already been associated with the table-config. Otherwise this returns * null. */ public synchronized static <D extends Dao<T, ?>, T> D lookupDao(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig) { if (connectionSource == null) { throw new IllegalArgumentException("connectionSource argument cannot be null"); } TableConfigConnectionSource key = new TableConfigConnectionSource(connectionSource, tableConfig); Dao<?, ?> dao = lookupDao(key); if (dao == null) { return null; } else { @SuppressWarnings("unchecked") D castDao = (D) dao; return castDao; } }
Example #2
Source File: SelectIteratorTest.java From ormlite-core with ISC License | 6 votes |
@Test(expected = IllegalStateException.class) public void testHasNextThrow() throws Exception { ConnectionSource cs = createMock(ConnectionSource.class); cs.releaseConnection(null); CompiledStatement stmt = createMock(CompiledStatement.class); DatabaseResults results = createMock(DatabaseResults.class); expect(stmt.runQuery(null)).andReturn(results); expect(results.first()).andThrow(new SQLException("some database problem")); stmt.close(); replay(stmt, results, cs); SelectIterator<Foo, Integer> iterator = new SelectIterator<Foo, Integer>(Foo.class, null, null, cs, null, stmt, "statement", null); try { iterator.hasNext(); } finally { iterator.close(); } }
Example #3
Source File: DatabaseHelper.java From ormlite-android-gradle-plugin with Apache License 2.0 | 6 votes |
/** * This is called when the database is first created. Usually you should call createTable statements here to create * the tables that will store your data. */ @Override public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) { try { Log.i(DatabaseHelper.class.getName(), "onCreate"); TableUtils.createTable(connectionSource, SimpleData.class); } catch (SQLException e) { Log.e(DatabaseHelper.class.getName(), "Can't create database", e); throw new RuntimeException(e); } // here we try inserting data in the on-create as a test RuntimeExceptionDao<SimpleData, Integer> dao = getSimpleDataDao(); long millis = System.currentTimeMillis(); // create some entries in the onCreate SimpleData simple = new SimpleData(millis); dao.create(simple); simple = new SimpleData(millis + 1); dao.create(simple); Log.i(DatabaseHelper.class.getName(), "created new entries in onCreate: " + millis); }
Example #4
Source File: TableUtils.java From ormlite-core with ISC License | 6 votes |
private static <T, ID> int doCreateTable(ConnectionSource connectionSource, TableInfo<T, ID> tableInfo, boolean ifNotExists) throws SQLException { DatabaseType databaseType = connectionSource.getDatabaseType(); List<String> statements = new ArrayList<String>(); List<String> queriesAfter = new ArrayList<String>(); addCreateTableStatements(databaseType, tableInfo, statements, queriesAfter, ifNotExists, true); DatabaseConnection connection = connectionSource.getReadWriteConnection(tableInfo.getTableName()); try { int stmtC = doStatements(connection, "create", statements, false, databaseType.isCreateTableReturnsNegative(), databaseType.isCreateTableReturnsZero()); stmtC += doCreateTestQueries(connection, databaseType, queriesAfter); return stmtC; } finally { connectionSource.releaseConnection(connection); } }
Example #5
Source File: DataBaseHelper.java From privacy-friendly-shopping-list with Apache License 2.0 | 6 votes |
@Override public void onCreate(SQLiteDatabase database, final ConnectionSource connectionSource) { try { setupClasses(); PFALogger.debug(getClass().getName(), ON_CREATE, START); for ( Class aClass : entityClasses ) { TableUtils.createTable(connectionSource, aClass); } } catch ( Exception e ) { PFALogger.error(getClass().getName(), ON_CREATE, e); } }
Example #6
Source File: OrmLiteSqlStorage.java From mxisd with GNU Affero General Public License v3.0 | 6 votes |
public OrmLiteSqlStorage(String backend, String path) { if (StringUtils.isBlank(backend)) { throw new ConfigurationException("storage.backend"); } if (StringUtils.isBlank(path)) { throw new ConfigurationException("Storage destination cannot be empty"); } withCatcher(() -> { ConnectionSource connPool = new JdbcConnectionSource("jdbc:" + backend + ":" + path); invDao = createDaoAndTable(connPool, ThreePidInviteIO.class); expInvDao = createDaoAndTable(connPool, HistoricalThreePidInviteIO.class); sessionDao = createDaoAndTable(connPool, ThreePidSessionDao.class); asTxnDao = createDaoAndTable(connPool, ASTransactionDao.class); }); }
Example #7
Source File: SchemaUtils.java From ormlite-core with ISC License | 6 votes |
private static <T, ID> int doCreateSchema(ConnectionSource connectionSource, String schemaName, boolean ifNotExists) throws SQLException { DatabaseType databaseType = connectionSource.getDatabaseType(); List<String> statements = new ArrayList<String>(); List<String> queriesAfter = new ArrayList<String>(); addCreateSchemaStatements(databaseType, schemaName, statements, queriesAfter, ifNotExists, true); DatabaseConnection connection = connectionSource.getReadWriteConnection(schemaName); try { int stmtC = doStatements(connection, "create", statements, false, databaseType.isCreateSchemaReturnsNegative(), databaseType.isCreateSchemaReturnsZero()); stmtC += doCreateTestQueries(connection, databaseType, queriesAfter); return stmtC; } finally { connectionSource.releaseConnection(connection); } }
Example #8
Source File: DatabaseHelper.java From Notification-Analyser with MIT License | 6 votes |
@Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVersion, int newVersion) { if (oldVersion < 2) { // Do changes from version 1 to 2 try { NotificationItemDao dao = getNotificationDao(); dao.executeRawNoArgs("ALTER TABLE " + NotificationItem.FIELD_TABLE_NAME + " ADD COLUMN " + NotificationItem.FIELD_MESSAGE + " TEXT"); } catch (SQLException e) { e.printStackTrace(); } } if (oldVersion < 3) { // Do changes from version 2 to 3 } }
Example #9
Source File: ApsTableUtils.java From entando-core with GNU Lesser General Public License v3.0 | 6 votes |
private static <T, ID> int doCreateTable(ConnectionSource connectionSource, TableInfo<T, ID> tableInfo, boolean ifNotExists) throws SQLException { DatabaseType databaseType = connectionSource.getDatabaseType(); logger.debug("creating table '{}'", tableInfo.getTableName()); List<String> statements = new ArrayList<String>(); List<String> queriesAfter = new ArrayList<String>(); addCreateTableStatements(databaseType, tableInfo, statements, queriesAfter, ifNotExists); DatabaseConnection connection = connectionSource.getReadWriteConnection(); try { int stmtC = doStatements(connection, "create", statements, false, databaseType.isCreateTableReturnsNegative(), databaseType.isCreateTableReturnsZero()); stmtC += doCreateTestQueries(connection, databaseType, queriesAfter); return stmtC; } finally { connectionSource.releaseConnection(connection); } }
Example #10
Source File: DatabaseHelper.java From moVirt with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") private void migrate(ConnectionSource connectionSource, int oldVersion, int newVersion) { boolean updateTriggers = true; // change for new migration rules if (45 <= oldVersion && newVersion < Integer.MAX_VALUE) { updateTriggers = false; } try { Set<Class<?>> classes = new HashSet<>(getUriMatcher().getClasses()); for (Class clazz : classes) { if (!updateTriggers && Trigger.class.isAssignableFrom(clazz)) { continue; } TableUtils.dropTable(connectionSource, clazz, true); TableUtils.createTable(connectionSource, clazz); } } catch (SQLException e) { Log.e(TAG, "Cannot upgrade database", e); } }
Example #11
Source File: DatabaseTableConfigUtil.java From ormlite-android with ISC License | 6 votes |
/** * Build our list table config from a class using some annotation fu around. */ public static <T> DatabaseTableConfig<T> fromClass(ConnectionSource connectionSource, Class<T> clazz) throws SQLException { DatabaseType databaseType = connectionSource.getDatabaseType(); String tableName = DatabaseTableConfig.extractTableName(databaseType, clazz); List<DatabaseFieldConfig> fieldConfigs = new ArrayList<DatabaseFieldConfig>(); for (Class<?> classWalk = clazz; classWalk != null; classWalk = classWalk.getSuperclass()) { for (Field field : classWalk.getDeclaredFields()) { DatabaseFieldConfig config = configFromField(databaseType, tableName, field); if (config != null && config.isPersisted()) { fieldConfigs.add(config); } } } if (fieldConfigs.size() == 0) { return null; } else { return new DatabaseTableConfig<T>(clazz, tableName, fieldConfigs); } }
Example #12
Source File: OrmLiteDatabaseHelper.java From AndroidBase with Apache License 2.0 | 6 votes |
/** * 数据库降级 */ @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { ConnectionSource cs = getConnectionSource(); DatabaseConnection conn = cs.getSpecialConnection(null); boolean clearSpecial = false; if (conn == null) { conn = new AndroidDatabaseConnection(db, true, this.cancelQueriesEnabled); try { cs.saveSpecialConnection(conn); clearSpecial = true; } catch (SQLException var11) { throw new IllegalStateException("Could not save special connection", var11); } } try { this.onDowngrade(cs, oldVersion, newVersion); } finally { if (clearSpecial) { cs.clearSpecialConnection(conn); } } }
Example #13
Source File: SelectIterator.java From ormlite-core with ISC License | 6 votes |
/** * If the statement parameter is null then this won't log information */ public SelectIterator(Class<?> dataClass, Dao<T, ID> classDao, GenericRowMapper<T> rowMapper, ConnectionSource connectionSource, DatabaseConnection connection, CompiledStatement compiledStmt, String statement, ObjectCache objectCache) throws SQLException { this.dataClass = dataClass; this.classDao = classDao; this.rowMapper = rowMapper; this.connectionSource = connectionSource; this.connection = connection; this.compiledStmt = compiledStmt; this.results = compiledStmt.runQuery(objectCache); this.statement = statement; if (statement != null) { logger.debug("starting iterator @{} for '{}'", hashCode(), statement); } }
Example #14
Source File: DatabaseHandler.java From AndroidBase with Apache License 2.0 | 6 votes |
/** * 处理表有变化的情况 */ private void dealColumnChange(SQLiteDatabase db, ConnectionSource cs, List<ColumnStruct> oldStruct, List<ColumnStruct> newStruct) throws SQLException { if (DatabaseUtil.hasChangeColumnLimit(oldStruct, newStruct)) { LogUtils.d("数据表已有字段的描述改变"); // 已有字段描述改变了,删除旧表,重建新表 reset(cs); } else { // 数据表已有字段的描述没有改变 // 判断列是否有增减 List<String> oldColumns = DatabaseUtil.getColumnNames(oldStruct); List<String> newColumns = DatabaseUtil.getColumnNames(newStruct); if (!oldColumns.equals(newColumns)) { LogUtils.d("表发生了变化"); // 判断列的变化情况:增加、减少、增减 List<String> deleteList = DatabaseUtil.getDeleteColumns(oldColumns, newColumns); upgradeByCopy(db, cs, getCopyColumns(oldColumns, deleteList)); } else { LogUtils.i("表没有发生变化,不需要更新数据表"); } } }
Example #15
Source File: TableFactory.java From entando-core with GNU Lesser General Public License v3.0 | 6 votes |
public void dropTables(List<String> tableClassNames) throws ApsSystemException { ConnectionSource connectionSource = null; try { connectionSource = this.createConnectionSource(); this.dropTables(tableClassNames, connectionSource); } catch (Throwable t) { _logger.error("Error dropping tables to db {}", this.getDatabaseName(), t); throw new ApsSystemException("Error dropping tables to db " + this.getDatabaseName(), t); } finally { if (connectionSource != null) { try { connectionSource.close(); } catch (SQLException ex) {} } } }
Example #16
Source File: MappedDeleteTest.java From ormlite-core with ISC License | 5 votes |
@Test(expected = SQLException.class) public void testDeleteNoId() throws Exception { StatementExecutor<NoId, Void> se = new StatementExecutor<NoId, Void>(databaseType, new TableInfo<NoId, Void>(databaseType, NoId.class), null); NoId noId = new NoId(); noId.stuff = "1"; ConnectionSource connectionSource = createMock(ConnectionSource.class); expect(connectionSource.getReadOnlyConnection(NOID_TABLE_NAME)).andReturn(null); replay(connectionSource); se.delete(connectionSource.getReadOnlyConnection(NOID_TABLE_NAME), noId, null); }
Example #17
Source File: FieldType.java From ormlite-core with ISC License | 5 votes |
/** * Create a shell object and assign its id field. */ private <FT, FID> FT createForeignShell(ConnectionSource connectionSource, Object val, ObjectCache objectCache) throws SQLException { @SuppressWarnings("unchecked") Dao<FT, FID> castDao = (Dao<FT, FID>) foreignDao; FT foreignObject = castDao.createObjectInstance(); foreignIdField.assignField(connectionSource, foreignObject, val, false, objectCache); return foreignObject; }
Example #18
Source File: ForeignCollectionMain.java From ormlite-jdbc with ISC License | 5 votes |
/** * Setup our database and DAOs */ private void setupDatabase(ConnectionSource connectionSource) throws Exception { accountDao = DaoManager.createDao(connectionSource, Account.class); orderDao = DaoManager.createDao(connectionSource, Order.class); // if you need to create the table TableUtils.createTable(connectionSource, Account.class); TableUtils.createTable(connectionSource, Order.class); }
Example #19
Source File: DatabaseHelper.java From moVirt with Apache License 2.0 | 5 votes |
@Override public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) { ViewHelper.dropViews(database); // call instead of super.onUpgrade() migrate(connectionSource, oldVersion, newVersion); ViewHelper.replaceTablesWithViews(database); }
Example #20
Source File: TransactionManagerTest.java From ormlite-core with ISC License | 5 votes |
@Test public void testTransactionManagerAutoCommitOn() throws Exception { ConnectionSource connectionSource = createMock(ConnectionSource.class); DatabaseConnection conn = createMock(DatabaseConnection.class); expect(conn.isAutoCommitSupported()).andReturn(true); expect(conn.isAutoCommit()).andReturn(true); conn.setAutoCommit(false); Savepoint savePoint = createMock(Savepoint.class); expect(savePoint.getSavepointName()).andReturn("name").anyTimes(); expect(conn.setSavePoint(isA(String.class))).andReturn(savePoint); conn.commit(savePoint); conn.setAutoCommit(true); expect(connectionSource.getDatabaseType()).andReturn(databaseType); expect(connectionSource.getReadWriteConnection(null)).andReturn(conn); expect(connectionSource.saveSpecialConnection(conn)).andReturn(true); connectionSource.clearSpecialConnection(conn); connectionSource.releaseConnection(conn); replay(connectionSource, conn, savePoint); TransactionManager tm = new TransactionManager(connectionSource); tm.callInTransaction(new Callable<Void>() { @Override public Void call() { return null; } }); verify(connectionSource, conn, savePoint); }
Example #21
Source File: GeoPackageDaoManager.java From geopackage-core-java with MIT License | 5 votes |
/** * Unregister the provided * * @param connectionSource * connection source * @param clazz * DAO class type */ public static void unregisterDao(ConnectionSource connectionSource, Class<?> clazz) { Dao<?, ?> dao = DaoManager.lookupDao(connectionSource, clazz); if (dao != null) { DaoManager.unregisterDao(connectionSource, dao); } }
Example #22
Source File: Manager.java From passopolis-server with GNU General Public License v3.0 | 5 votes |
@Override public void close() { final String txnId = transactionId; sourcePool.removeManager(this); if (this.connectionSource != this.auditConnectionSource) { this.auditConnectionSource.closeQuietly(); } this.connectionSource.closeQuietly(); // HACK: Unregister Daos from OrmLite's stupid internal cache to avoid a memory leak // We need to unregister ALL tables; creating a Dao creates Daos for any related objects. // TODO: the docs suggest reusing a single JdbcPooledConnectionSource, which might work // (reusing a plain JdbcConnectionSource will not because it is a single connection) ConnectionSource[] sources = {connectionSource, auditConnectionSource}; for (ConnectionSource source : sources) { // Get all the daos for all data types ArrayList<Dao<?, ?>> daos = new ArrayList<Dao<?, ?>>(DATA_CLASSES.length); for (Class<?> clazz : DATA_CLASSES) { // Get the cached Dao from the DaoManager, then remove it try { daos.add(DaoManager.createDao(source, clazz)); } catch (SQLException e) { throw new RuntimeException("Unexpected SQLException", e); } } // Unregister them all to avoid leaks due to related tables for (Dao<?, ?> dao : daos) { DaoManager.unregisterDao(source, dao); } } // do NOT remove this writeAuditLogs check. Otherwise, we will go in an endless loop // (the manager used by the transaction processor will trigger another txn complete) if (shouldWriteAuditLogs()) { ManagerFactory.getInstance().transactionComplete(txnId); } }
Example #23
Source File: FieldType.java From ormlite-core with ISC License | 5 votes |
/** * Assign an ID value to this field. */ public Object assignIdValue(ConnectionSource connectionSource, Object data, Number val, ObjectCache objectCache) throws SQLException { Object idVal = dataPersister.convertIdNumber(val); if (idVal == null) { throw new SQLException("Invalid class " + dataPersister + " for sequence-id " + this); } else { assignField(connectionSource, data, idVal, false, objectCache); return idVal; } }
Example #24
Source File: TableUtils.java From ormlite-core with ISC License | 5 votes |
/** * Clear all data out of the table. For certain database types and with large sized tables, which may take a long * time. In some configurations, it may be faster to drop and re-create the table. * * <p> * <b>WARNING:</b> This is [obviously] very destructive and is unrecoverable. * </p> */ public static <T> int clearTable(ConnectionSource connectionSource, Class<T> dataClass) throws SQLException { DatabaseType databaseType = connectionSource.getDatabaseType(); String tableName = DatabaseTableConfig.extractTableName(databaseType, dataClass); String schemaName = DatabaseTableConfig.extractSchemaName(dataClass); if (databaseType.isEntityNamesMustBeUpCase()) { tableName = databaseType.upCaseEntityName(tableName); } return clearTable(connectionSource, schemaName, tableName); }
Example #25
Source File: OrmLiteSqliteOpenHelper.java From ormlite-android with ISC License | 5 votes |
/** * Satisfies the {@link SQLiteOpenHelper#onCreate(SQLiteDatabase)} interface method. */ @Override public final void onCreate(SQLiteDatabase db) { ConnectionSource cs = getConnectionSource(); /* * The method is called by Android database helper's get-database calls when Android detects that we need to * create or update the database. So we have to use the database argument and save a connection to it on the * AndroidConnectionSource, otherwise it will go recursive if the subclass calls getConnectionSource(). */ DatabaseConnection conn = cs.getSpecialConnection(null); boolean clearSpecial = false; if (conn == null) { conn = new AndroidDatabaseConnection(db, true, cancelQueriesEnabled); try { cs.saveSpecialConnection(conn); clearSpecial = true; } catch (SQLException e) { throw new IllegalStateException("Could not save special connection", e); } } try { onCreate(db, cs); } finally { if (clearSpecial) { cs.clearSpecialConnection(conn); } } }
Example #26
Source File: LocalSqliteDriverImpl.java From mae-annotation with GNU General Public License v3.0 | 5 votes |
@Override public void setupDatabase(ConnectionSource source) throws MaeDBException { try { taskDao = DaoManager.createDao(source, Task.class); charIndexDao = DaoManager.createDao(source, CharIndex.class); tagTypeDao = DaoManager.createDao(source, TagType.class); eTagDao = DaoManager.createDao(source, ExtentTag.class); lTagDao = DaoManager.createDao(source, LinkTag.class); attTypeDao = DaoManager.createDao(source, AttributeType.class); attDao = DaoManager.createDao(source, Attribute.class); argTypeDao = DaoManager.createDao(source, ArgumentType.class); argDao = DaoManager.createDao(source, Argument.class); } catch (SQLException e) { throw catchSQLException(e); } charIndexQuery = charIndexDao.queryBuilder(); tagTypeQuery = tagTypeDao.queryBuilder(); eTagQuery = eTagDao.queryBuilder(); lTagQuery = lTagDao.queryBuilder(); attTypeQuery = attTypeDao.queryBuilder(); attQuery = attDao.queryBuilder(); argTypeQuery = argTypeDao.queryBuilder(); argQuery = argDao.queryBuilder(); allDaos = new Dao[]{ taskDao, charIndexDao, tagTypeDao, eTagDao, lTagDao, attTypeDao, attDao, argTypeDao, argDao}; allQueryBuilders = new QueryBuilder[]{ charIndexQuery, tagTypeQuery, eTagQuery, lTagQuery, attTypeQuery, attQuery, argTypeQuery, argQuery}; dropAllTables(source); createAllTables(source); }
Example #27
Source File: DatabaseHelper.java From renrenpay-android with Apache License 2.0 | 5 votes |
@Override public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) { try { TableUtils.createTable(connectionSource, User.class); TableUtils.createTable(connectionSource, Logs.class); } catch (SQLException e) { e.printStackTrace(); } }
Example #28
Source File: DBHelper.java From Maying with Apache License 2.0 | 5 votes |
@Override public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) { try { TableUtils.createTable(connectionSource, Profile.class); TableUtils.createTable(connectionSource, SSRSub.class); } catch (SQLException e) { VayLog.e(TAG, "onCreate", e); } }
Example #29
Source File: BaseDaoImpl.java From ormlite-core with ISC License | 5 votes |
private BaseDaoImpl(ConnectionSource connectionSource, Class<T> dataClass, DatabaseTableConfig<T> tableConfig) throws SQLException { this.dataClass = dataClass; this.tableConfig = tableConfig; this.constructor = findNoArgConstructor(dataClass); if (connectionSource != null) { this.connectionSource = connectionSource; initialize(); } }
Example #30
Source File: ForeignMain.java From ormlite-jdbc with ISC License | 5 votes |
/** * Setup our database and DAOs */ private void setupDatabase(ConnectionSource connectionSource) throws Exception { accountDao = DaoManager.createDao(connectionSource, Account.class); orderDao = DaoManager.createDao(connectionSource, Order.class); // if you need to create the table TableUtils.createTable(connectionSource, Account.class); TableUtils.createTable(connectionSource, Order.class); }