public boolean tableIsExist(Class<?> entityType) throws DbException { Table table = Table.get(this, entityType); if (table.isCheckedDatabase()) { return true; } Cursor cursor = execQuery( "SELECT COUNT(*) AS c FROM sqlite_master WHERE type='table' AND name='" + table.tableName + "'"); if (cursor != null) { try { if (cursor.moveToNext()) { int count = cursor.getInt(0); if (count > 0) { table.setCheckedDatabase(true); return true; } } } catch (Throwable e) { throw new DbException(e); } finally { IOUtils.closeQuietly(cursor); } } return false; }
@SuppressWarnings("unchecked") public <T> T findById(Class<T> entityType, Object idValue) throws DbException { if (!tableIsExist(entityType)) return null; Table table = Table.get(this, entityType); Selector selector = Selector.from(entityType).where(table.id.getColumnName(), "=", idValue); String sql = selector.limit(1).toString(); long seq = CursorUtils.FindCacheSequence.getSeq(); findTempCache.setSeq(seq); Object obj = findTempCache.get(sql); if (obj != null) { return (T) obj; } Cursor cursor = execQuery(sql); if (cursor != null) { try { if (cursor.moveToNext()) { T entity = (T) CursorUtils.getEntity(this, cursor, entityType, seq); findTempCache.put(sql, entity); return entity; } } catch (Throwable e) { throw new DbException(e); } finally { IOUtils.closeQuietly(cursor); } } return null; }
public long count(Selector selector) throws DbException { Class<?> entityType = selector.getEntityType(); if (!tableIsExist(entityType)) return 0; Table table = Table.get(this, entityType); DbModelSelector dmSelector = selector.select("count(" + table.id.getColumnName() + ") as count"); return findDbModelFirst(dmSelector).getLong("count"); }
// ***************************** private operations with out transaction // ***************************** private void saveOrUpdateWithoutTransaction(Object entity) throws DbException { Table table = Table.get(this, entity.getClass()); Id id = table.id; if (id.isAutoIncrement()) { if (id.getColumnValue(entity) != null) { execNonQuery(SqlInfoBuilder.buildUpdateSqlInfo(this, entity)); } else { saveBindingIdWithoutTransaction(entity); } } else { execNonQuery(SqlInfoBuilder.buildReplaceSqlInfo(this, entity)); } }
private boolean saveBindingIdWithoutTransaction(Object entity) throws DbException { Class<?> entityType = entity.getClass(); Table table = Table.get(this, entityType); Id idColumn = table.id; if (idColumn.isAutoIncrement()) { execNonQuery(SqlInfoBuilder.buildInsertSqlInfo(this, entity)); long id = getLastAutoIncrementId(table.tableName); if (id == -1) { return false; } idColumn.setAutoIncrementId(entity, id); return true; } else { execNonQuery(SqlInfoBuilder.buildInsertSqlInfo(this, entity)); return true; } }