Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add create index if not exist method. #127

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/main/java/com/j256/ormlite/table/TableUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,27 @@ public static <T> 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 <T> void createIndexIfNotExists(ConnectionSource connectionSource, Class<T> dataClass)
throws SQLException {
Dao<T, ?> dao = DaoManager.createDao(connectionSource, dataClass);
doCreateIndex(dao, true);
}

private static <T, ID> void doCreateIndex(Dao<T, ID> dao, boolean ifNotExists) throws SQLException {
if (dao instanceof BaseDaoImpl<?, ?>) {
addCreateIndexStatements(dao.getConnectionSource().getDatabaseType(), ((BaseDaoImpl<?, ?>) dao).getTableInfo(), new ArrayList<String>(), ifNotExists, false);
addCreateIndexStatements(dao.getConnectionSource().getDatabaseType(), ((BaseDaoImpl<?, ?>) dao).getTableInfo(), new ArrayList<String>(), ifNotExists, true);
} else {
TableInfo<T, ID> tableInfo = new TableInfo<T, ID>(dao.getConnectionSource(), null, dao.getDataClass());
addCreateIndexStatements(dao.getConnectionSource().getDatabaseType(), tableInfo, new ArrayList<String>(), ifNotExists, false);
addCreateIndexStatements(dao.getConnectionSource().getDatabaseType(), tableInfo, new ArrayList<String>(), ifNotExists, true);
}
}

private static <T> int clearTable(ConnectionSource connectionSource, String tableName) throws SQLException {
DatabaseType databaseType = connectionSource.getDatabaseType();
StringBuilder sb = new StringBuilder(48);
Expand Down