From a6f392e4c83dd7a8856b1dc430790fdc8f6194db Mon Sep 17 00:00:00 2001 From: Ayberk Date: Thu, 14 Dec 2017 15:09:05 +0300 Subject: [PATCH] add create index if not exist method. need unit test! --- .../com/j256/ormlite/table/TableUtils.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/main/java/com/j256/ormlite/table/TableUtils.java b/src/main/java/com/j256/ormlite/table/TableUtils.java index 7eda880b9..6d4392b35 100644 --- a/src/main/java/com/j256/ormlite/table/TableUtils.java +++ b/src/main/java/com/j256/ormlite/table/TableUtils.java @@ -243,6 +243,27 @@ public static int clearTable(ConnectionSource connectionSource, DatabaseTabl return clearTable(connectionSource, tableConfig.getTableName()); } + + /** + * Create table indexes if they do not already exist. This is not supported by all databases. + */ + public static void createIndexIfNotExists(ConnectionSource connectionSource, Class dataClass) + throws SQLException { + Dao dao = DaoManager.createDao(connectionSource, dataClass); + doCreateIndex(dao, true); + } + + private static void doCreateIndex(Dao dao, boolean ifNotExists) throws SQLException { + if (dao instanceof BaseDaoImpl) { + addCreateIndexStatements(dao.getConnectionSource().getDatabaseType(), ((BaseDaoImpl) dao).getTableInfo(), new ArrayList(), ifNotExists, false); + addCreateIndexStatements(dao.getConnectionSource().getDatabaseType(), ((BaseDaoImpl) dao).getTableInfo(), new ArrayList(), ifNotExists, true); + } else { + TableInfo tableInfo = new TableInfo(dao.getConnectionSource(), null, dao.getDataClass()); + addCreateIndexStatements(dao.getConnectionSource().getDatabaseType(), tableInfo, new ArrayList(), ifNotExists, false); + addCreateIndexStatements(dao.getConnectionSource().getDatabaseType(), tableInfo, new ArrayList(), ifNotExists, true); + } + } + private static int clearTable(ConnectionSource connectionSource, String tableName) throws SQLException { DatabaseType databaseType = connectionSource.getDatabaseType(); StringBuilder sb = new StringBuilder(48);