com.j256.ormlite.table.TableUtils Java Examples

The following examples show how to use com.j256.ormlite.table.TableUtils. 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: DataBaseHelper.java    From privacy-friendly-shopping-list with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: JdbcPooledConnectionSourceTest.java    From ormlite-jdbc with ISC License 6 votes vote down vote up
@Test
public void testConnectionRollback() throws Exception {
	JdbcPooledConnectionSource pooled = new JdbcPooledConnectionSource(DEFAULT_DATABASE_URL);
	Dao<Foo, Integer> dao = null;
	DatabaseConnection conn = null;
	try {
		TableUtils.createTable(pooled, Foo.class);
		dao = DaoManager.createDao(pooled, Foo.class);
		conn = dao.startThreadConnection();
		dao.setAutoCommit(conn, false);
		Foo foo = new Foo();
		assertEquals(1, dao.create(foo));
		assertNotNull(dao.queryForId(foo.id));
		dao.endThreadConnection(conn);
		assertNull(dao.queryForId(foo.id));
	} finally {
		TableUtils.dropTable(pooled, Foo.class, true);
		if (dao != null) {
			dao.endThreadConnection(conn);
		}
		pooled.close();
	}
}
 
Example #3
Source File: DatabaseHelper.java    From zulip-android with Apache License 2.0 6 votes vote down vote up
/**
 * 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");
        // Create the databases we're using
        TableUtils.createTable(connectionSource, Person.class);
        TableUtils.createTable(connectionSource, Stream.class);
        TableUtils.createTable(connectionSource, Message.class);
        TableUtils.createTable(connectionSource, MessageRange.class);
        TableUtils.createTable(connectionSource, Emoji.class);
        TableUtils.createTable(connectionSource, Reaction.class);
        TableUtils.createTable(connectionSource, UserReaction.class);
    } catch (SQLException e) {
        Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
        throw new RuntimeException(e);
    }
}
 
Example #4
Source File: ManyToManyMain.java    From ormlite-jdbc with ISC License 6 votes vote down vote up
/**
 * Setup our database and DAOs
 */
private void setupDatabase(ConnectionSource connectionSource) throws Exception {

	/**
	 * Create our DAOs. One for each class and associated table.
	 */
	userDao = DaoManager.createDao(connectionSource, User.class);
	postDao = DaoManager.createDao(connectionSource, Post.class);
	userPostDao = DaoManager.createDao(connectionSource, UserPost.class);

	/**
	 * Create the tables for our example. This would not be necessary if the tables already existed.
	 */
	TableUtils.createTable(connectionSource, User.class);
	TableUtils.createTable(connectionSource, Post.class);
	TableUtils.createTable(connectionSource, UserPost.class);
}
 
Example #5
Source File: DatabaseHelper.java    From android-overlay-protection with Apache License 2.0 6 votes vote down vote up
/**
 * This is called when your application is upgraded and it has a higher version number. This allows you to adjust
 * the various data to match the new version number.
 */
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
    try {
        Log.i(TAG, "onUpgrade");
        TableUtils.dropTable(connectionSource, SuspectedApp.class, true);
        Log.d(TAG, String.format("Dropped suspected app table!"));
        Dao<WhiteEntry, Integer> whiteListDao = getWhiteListDao();
        DeleteBuilder<WhiteEntry, Integer> deleteBuilder = whiteListDao.deleteBuilder();
        deleteBuilder.where().eq("systemEntry", Boolean.TRUE);
        int deleted = deleteBuilder.delete();
        Log.d(TAG, String.format("Delete %d old system whitelist entries", deleted));
        onCreate(db, connectionSource);
    } catch (SQLException e) {
        Log.e(TAG, "Can't drop databases", e);
        throw new RuntimeException(e);
    }
}
 
Example #6
Source File: DatabaseHelper.java    From AndroidAPS with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
    try {
        if (L.isEnabled(L.DATABASE))
            log.info("onCreate");
        TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
        TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
        TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class);
        TableUtils.createTableIfNotExists(connectionSource, DbRequest.class);
        TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
        TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
        TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
        TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
        TableUtils.createTableIfNotExists(connectionSource, TDD.class);
        TableUtils.createTableIfNotExists(connectionSource, InsightHistoryOffset.class);
        TableUtils.createTableIfNotExists(connectionSource, InsightBolusID.class);
        TableUtils.createTableIfNotExists(connectionSource, InsightPumpID.class);
        database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DATABASE_INSIGHT_BOLUS_IDS + "\", " + System.currentTimeMillis() + " " +
                "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DATABASE_INSIGHT_BOLUS_IDS + "\")");
        database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DATABASE_INSIGHT_PUMP_IDS + "\", " + System.currentTimeMillis() + " " +
                "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DATABASE_INSIGHT_PUMP_IDS + "\")");
    } catch (SQLException e) {
        log.error("Can't create database", e);
        throw new RuntimeException(e);
    }
}
 
Example #7
Source File: TableCreatorTest.java    From ormlite-jdbc with ISC License 6 votes vote down vote up
@Test
public void testDestroyDoesntExist() throws Exception {
	Dao<Foo, Object> fooDao = createDao(Foo.class, false);
	List<Dao<?, ?>> daoList = new ArrayList<Dao<?, ?>>();
	daoList.add(fooDao);
	TableCreator tableCreator = new TableCreator(connectionSource, daoList);
	try {
		System.setProperty(TableCreator.AUTO_CREATE_TABLES, Boolean.TRUE.toString());
		System.setProperty(TableCreator.AUTO_DROP_TABLES, Boolean.TRUE.toString());
		tableCreator.maybeCreateTables();
		TableUtils.dropTable(connectionSource, Foo.class, true);
		tableCreator.maybeDropTables();
	} finally {
		System.clearProperty(TableCreator.AUTO_CREATE_TABLES);
		System.clearProperty(TableCreator.AUTO_DROP_TABLES);
	}
}
 
Example #8
Source File: DBEmailQueueTest.java    From passopolis-server with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testTimeZone() throws SQLException {
  // create a temporary H2 connection
  JdbcConnectionSource connection = new JdbcConnectionSource("jdbc:h2:mem:");
  TableUtils.createTable(connection, DBEmailQueue.class);
  Dao<DBEmailQueue, Integer> dao = DaoManager.createDao(connection, DBEmailQueue.class);

  DBEmailQueue email = DBEmailQueue.makeInvitation("[email protected]", "[email protected]", "pw");
  dao.create(email);

  // Force a daylight savings time string in the DB
  setRawDate(connection, email.getId(), "2013-05-17T14:47:59.864022");
  Date t = dao.queryForId(email.getId()).getAttemptedTime();
  assertEquals("2013-05-17T14:47:59.864Z", DBEmailQueue.getUtcIsoFormat().format(t));
  assertEquals(1368802079864L, t.getTime());

  // Set a date/time in standard time, not daylight time
  setRawDate(connection, email.getId(), "2013-11-04T15:38:11.997012");
  t = dao.queryForId(email.getId()).getAttemptedTime();
  assertEquals("2013-11-04T15:38:11.997Z", DBEmailQueue.getUtcIsoFormat().format(t));
  assertEquals(1383579491997L, t.getTime());
}
 
Example #9
Source File: DatabaseHelper.java    From ormlite-android-gradle-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #10
Source File: DatabaseHelper.java    From AndroidDatabaseLibraryComparison with MIT License 6 votes vote down vote up
/**
 * This is called when your application is upgraded and it has a higher version number. This allows you to adjust
 * the various data to match the new version number.
 */
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
    try {
        Log.i(DatabaseHelper.class.getName(), "onUpgrade");
        TableUtils.dropTable(connectionSource, AddressBook.class, true);
        TableUtils.dropTable(connectionSource, AddressItem.class, true);
        TableUtils.dropTable(connectionSource, Contact.class, true);
        TableUtils.dropTable(connectionSource, SimpleAddressItem.class, true);
        // after we drop the old databases, we create the new ones
        onCreate(db, connectionSource);
    } catch (SQLException e) {
        Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
        throw new RuntimeException(e);
    }
}
 
Example #11
Source File: DatabaseHelper.java    From SightRemote with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
    try {
        TableUtils.createTableIfNotExists(connectionSource, BolusDelivered.class);
        TableUtils.createTableIfNotExists(connectionSource, BolusProgrammed.class);
        TableUtils.createTableIfNotExists(connectionSource, EndOfTBR.class);
        TableUtils.createTableIfNotExists(connectionSource, Offset.class);
        TableUtils.createTableIfNotExists(connectionSource, PumpStatusChanged.class);
        TableUtils.createTableIfNotExists(connectionSource, TimeChanged.class);
        TableUtils.createTableIfNotExists(connectionSource, CannulaFilled.class);
        TableUtils.createTableIfNotExists(connectionSource, DailyTotal.class);
        TableUtils.createTableIfNotExists(connectionSource, CartridgeInserted.class);
        TableUtils.createTableIfNotExists(connectionSource, BatteryInserted.class);
        TableUtils.createTableIfNotExists(connectionSource, TubeFilled.class);
        TableUtils.createTableIfNotExists(connectionSource, OccurenceOfAlert.class);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
 
Example #12
Source File: DatabaseHelper.java    From poetry with Apache License 2.0 6 votes vote down vote up
public <T> void dropTable(Class<T> classObject)
{
    try
    {
        TableUtils.dropTable(getConnectionSource(), classObject, true);

        if (sCachedDaos.containsKey(classObject))
        {
            sCachedDaos.remove(classObject);
        }
    }
    catch (SQLException e)
    {
        sLogger.error("can't drop table", e);
    }
}
 
Example #13
Source File: DataBaseHelper.java    From privacy-friendly-shopping-list with Apache License 2.0 6 votes vote down vote up
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion)
{
    try
    {
        setupClasses();
        for ( Class aClass : entityClasses )
        {
            TableUtils.dropTable(connectionSource, aClass, true);
        }
        onCreate(database, connectionSource);
    }
    catch ( SQLException e )
    {
        PFALogger.error(getClass().getName(), ON_UPGRADE, e);
    }
}
 
Example #14
Source File: LocalDbCacheHelper.java    From android-project-wo2b with Apache License 2.0 6 votes vote down vote up
/**
 * 创建数据库时会回调的接口,在这个方法里面完成对数据库表的创建
 */
@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource)
{
	try
	{
		Log.I(TAG, "--------------------- onCreate ---------------------");
		
		TableUtils.createTable(connectionSource, Like.class);
		
		// 数据初始化
		initDatabase(db, connectionSource);
	}
	catch (SQLException e)
	{
		Log.E(TAG, "Can't create database.", e);
		throw new RuntimeException(e);
	}
	
}
 
Example #15
Source File: FlowDatabaseHelper.java    From flow-android with MIT License 6 votes vote down vote up
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVer, int newVer) {
    try {
        TableUtils.dropTable(connectionSource, User.class, true);
        TableUtils.dropTable(connectionSource, Course.class, true);
        TableUtils.dropTable(connectionSource, ScheduleCourse.class, true);
        TableUtils.dropTable(connectionSource, Exam.class, true);
        TableUtils.dropTable(connectionSource, UserCourse.class, true);
        TableUtils.dropTable(connectionSource, ScheduleImage.class, true);
        onCreate(sqLiteDatabase, connectionSource);
    } catch (SQLException e) {
        Log.e(TAG, "Unable to upgrade database from version " + oldVer + " to new "
                + newVer, e);
        Crashlytics.logException(e);
    }
}
 
Example #16
Source File: DbOpenHelper.java    From FamilyChat with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource)
{
    try
    {
        TableUtils.createTable(connectionSource, UserBean.class);
        TableUtils.createTable(connectionSource, InviteBean.class);
        TableUtils.createTable(connectionSource, ShortVideoBean.class);
    } catch (SQLException e)
    {
        KLog.e("DbOpenHelper.onCreate() fail : " + e.toString());
    }
}
 
Example #17
Source File: DbHelperUtils.java    From q-municate-android with Apache License 2.0 5 votes vote down vote up
public static void clearTable(ConnectionSource connectionSource, Class clazz) {
    try {
        TableUtils.clearTable(connectionSource, clazz);
    } catch (SQLException e) {
        ErrorUtils.logError(e);
    }
}
 
Example #18
Source File: DbHelperUtils.java    From q-municate-android with Apache License 2.0 5 votes vote down vote up
public static void clearTable(ConnectionSource connectionSource, Class clazz) {
    try {
        TableUtils.clearTable(connectionSource, clazz);
    } catch (SQLException e) {
        ErrorUtils.logError(e);
    }
}
 
Example #19
Source File: DbHelperUtils.java    From q-municate-android with Apache License 2.0 5 votes vote down vote up
public static void onCreate(ConnectionSource connectionSource, Class<?>[] tables) {
    try {
        for (Class clazz : tables) {
            TableUtils.createTable(connectionSource, clazz);
        }
    } catch (SQLException e) {
        ErrorUtils.logError(e);
    }
}
 
Example #20
Source File: DbHelperUtils.java    From q-municate-android with Apache License 2.0 5 votes vote down vote up
public static void onCreate(ConnectionSource connectionSource, Class<?>[] tables) {
    try {
        for (Class clazz : tables) {
            TableUtils.createTable(connectionSource, clazz);
        }
    } catch (SQLException e) {
        ErrorUtils.logError(e);
    }
}
 
Example #21
Source File: BaseCoreTest.java    From ormlite-core with ISC License 5 votes vote down vote up
protected <T> void createTable(DatabaseTableConfig<T> tableConfig, boolean dropAtEnd) throws SQLException {
	try {
		// first we drop it in case it existed before
		dropTable(tableConfig, true);
	} catch (SQLException ignored) {
		// ignore any errors about missing tables
	}
	TableUtils.createTable(connectionSource, tableConfig);
}
 
Example #22
Source File: InviteDao.java    From FamilyChat with Apache License 2.0 5 votes vote down vote up
/**
 * 清楚表中所有数据
 */
public void clear()
{
    try
    {
        TableUtils.clearTable(getDao().getConnectionSource(), InviteBean.class);
    } catch (SQLException e)
    {
        KLog.e(TAG + "InviteDao.clear fail:" + e.toString());
    }
}
 
Example #23
Source File: DBHelper.java    From A-week-to-develop-android-app-plan with Apache License 2.0 5 votes vote down vote up
/**
 * 创建表
 * @param database
 * @param connectionSource
 */
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
    // 创建表
    try {
        // 示例
        TableUtils.createTable(connectionSource, User.class);
    } catch (SQLException e) {
        e.printStackTrace();
    }


}
 
Example #24
Source File: DatabaseHelper.java    From Quiz with GNU General Public License v2.0 5 votes vote down vote up
private void createDataBase(ConnectionSource cs) throws java.sql.SQLException {
	TableUtils.createTable(cs, Level.class);
	TableUtils.createTable(cs, Exercise.class);
	TableUtils.createTable(cs, Question.class);
	TableUtils.createTable(cs, Answer.class);
	TableUtils.createTable(cs, Scoring.class);
}
 
Example #25
Source File: DatabaseHelper.java    From Presentation with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
    try {
        TableUtils.createTable(connectionSource, Pin.class);
    } catch (SQLException e) {
        Logger.e(e.getMessage());
    }
}
 
Example #26
Source File: ORMLiteExecutor.java    From android-orm-benchmark-updated with Apache License 2.0 5 votes vote down vote up
@Override
public long createDbStructure() throws SQLException {
    long start = System.nanoTime();
    ConnectionSource connectionSource = mHelper.getConnectionSource();
    TableUtils.createTable(connectionSource, User.class);
    TableUtils.createTable(connectionSource, Message.class);
    return System.nanoTime() - start;
}
 
Example #27
Source File: TableCreator.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
/**
 * If you are using the Spring type wiring, this should be called after all of the set methods.
 */
public void initialize() throws SQLException {
	if (!Boolean.parseBoolean(System.getProperty(AUTO_CREATE_TABLES))) {
		return;
	}

	if (configuredDaos == null) {
		throw new SQLException("configuredDaos was not set in " + getClass().getSimpleName());
	}

	// find all of the daos and create the tables
	for (Dao<?, ?> dao : configuredDaos) {
		Class<?> clazz = dao.getDataClass();
		try {
			DatabaseTableConfig<?> tableConfig = null;
			if (dao instanceof BaseDaoImpl) {
				tableConfig = ((BaseDaoImpl<?, ?>) dao).getTableConfig();
			}
			if (tableConfig == null) {
				tableConfig = DatabaseTableConfig.fromClass(connectionSource.getDatabaseType(), clazz);
			}
			TableUtils.createTable(connectionSource, tableConfig);
			createdClasses.add(tableConfig);
		} catch (Exception e) {
			// we don't stop because the table might already exist
			System.err.println("Was unable to auto-create table for " + clazz);
			e.printStackTrace();
		}
	}
}
 
Example #28
Source File: PersistManager.java    From Man-Man with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
    try {
        TableUtils.createTable(connectionSource, ManSectionItem.class);
        TableUtils.createTable(connectionSource, ManSectionIndex.class);
        TableUtils.createTable(connectionSource, ManPage.class);
    } catch (SQLException e) {
        Log.e(TAG, "error creating DB " + DATABASE_NAME);
        throw new RuntimeException(e);
    }
}
 
Example #29
Source File: DatabaseHelper.java    From AndroidDatabaseLibraryComparison with MIT License 5 votes vote down vote up
/**
 * 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, AddressBook.class);
        TableUtils.createTable(connectionSource, AddressItem.class);
        TableUtils.createTable(connectionSource, Contact.class);
        TableUtils.createTable(connectionSource, SimpleAddressItem.class);
    } catch (SQLException e) {
        Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
        throw new RuntimeException(e);
    }
}
 
Example #30
Source File: DatabaseHelper.java    From android-project-wo2b with Apache License 2.0 5 votes vote down vote up
/**
 * 处理数据库版本升级
 */
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion)
{
	Log.I(TAG, "--------------------- onUpgrade ---------------------");
	int version = oldVersion;
	if (version < 4)
	{
		upgradeFor2(db);
		version = 3;
	}
	
	if (version != DATABASE_VERSION)
	{
		Log.W(TAG, "Destroying all old data.");
		try
		{
			Log.I(TAG, "--------------------- onUpgrade ---------------------");
			
			TableUtils.dropTable(connectionSource, AlbumInfo.class, true);
			TableUtils.dropTable(connectionSource, PhotoInfo.class, true);
			
			onCreate(db, connectionSource);
		}
		catch (SQLException e)
		{
			Log.E(TAG, "Can't drop databases", e);
			throw new RuntimeException(e);
		}
	}
	
}