com.yahoo.squidb.sql.Table Java Examples

The following examples show how to use com.yahoo.squidb.sql.Table. 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: TableModel.java    From squidb with Apache License 2.0 6 votes vote down vote up
void bindValuesForInsert(Table table, ISQLitePreparedStatement preparedInsert) {
    LongProperty rowidProperty = getRowIdProperty();
    Property<?>[] allProperties = table.getProperties();

    ModelAndIndex modelAndIndex = new ModelAndIndex(this);
    for (Property<?> property : allProperties) {
        if (property == rowidProperty) {
            long rowid = getRowId();
            if (rowid == TableModel.NO_ID) {
                preparedInsert.bindNull(modelAndIndex.index);
            } else {
                preparedInsert.bindLong(modelAndIndex.index, rowid);
            }
        } else {
            property.accept(valueBindingVisitor, preparedInsert, modelAndIndex);
        }
        modelAndIndex.index++;
    }
}
 
Example #2
Source File: PreparedInsertCache.java    From squidb with Apache License 2.0 6 votes vote down vote up
ISQLitePreparedStatement getPreparedInsert(SquidDatabase db, Table table,
        TableStatement.ConflictAlgorithm conflictAlgorithm) {

    Class<? extends TableModel> modelClass = table.getModelClass();
    ISQLitePreparedStatement[] preparedStatements = preparedStatementCache.get(modelClass);

    if (preparedStatements == null) {
        preparedStatements = new ISQLitePreparedStatement[TableStatement.ConflictAlgorithm.values().length];
        preparedStatementCache.put(modelClass, preparedStatements);
    }

    if (conflictAlgorithm == null) {
        conflictAlgorithm = TableStatement.ConflictAlgorithm.NONE;
    }

    ISQLitePreparedStatement toReturn = preparedStatements[conflictAlgorithm.ordinal()];
    if (toReturn == null) {
        toReturn = prepareInsert(db, table, conflictAlgorithm);
        preparedStatements[conflictAlgorithm.ordinal()] = toReturn;
    }
    return toReturn;
}
 
Example #3
Source File: SquidDatabase.java    From squidb with Apache License 2.0 6 votes vote down vote up
/**
 * Same as {@link #updateRow(TableModel)} with the ability to specify a ConflictAlgorithm for handling constraint
 * violations
 *
 * @param item the model to save
 * @param conflictAlgorithm the conflict algorithm to use
 * @return true if success, false otherwise
 */
protected final boolean updateRow(TableModel item, TableStatement.ConflictAlgorithm conflictAlgorithm) {
    if (!item.isModified()) { // nothing changed
        return true;
    }
    if (!item.isSaved()) {
        return false;
    }

    Class<? extends TableModel> modelClass = item.getClass();
    Table table = getTable(modelClass);
    Update update = Update.table(table).fromTemplate(item).where(table.getRowIdProperty().eq(item.getRowId()));
    if (conflictAlgorithm != null) {
        update.onConflict(conflictAlgorithm);
    }
    boolean result = updateInternal(update) > 0;
    if (result) {
        notifyForTable(DataChangedNotifier.DBOperation.UPDATE, item, table, item.getRowId());
        item.markSaved();
    }
    return result;
}
 
Example #4
Source File: SquidDatabase.java    From squidb with Apache License 2.0 6 votes vote down vote up
/**
 * Update all rows matching the given {@link Criterion}, setting values based on the provided template model. Any
 * constraint violations will be resolved using the specified
 * {@link com.yahoo.squidb.sql.TableStatement.ConflictAlgorithm ConflictAlgorithm}.
 *
 * @param where the criterion to match. Note: passing null will update all rows!
 * @param template a model containing new values for the properties (columns) that should be updated
 * @param conflictAlgorithm the conflict algorithm to use
 * @return the number of updated rows
 * @see #update(Criterion, TableModel)
 */
public int updateWithOnConflict(Criterion where, TableModel template,
        TableStatement.ConflictAlgorithm conflictAlgorithm) {
    Class<? extends TableModel> modelClass = template.getClass();
    Table table = getTable(modelClass);
    Update update = Update.table(table).fromTemplate(template);
    if (where != null) {
        update.where(where);
    }
    if (conflictAlgorithm != null) {
        update.onConflict(conflictAlgorithm);
    }

    int rowsUpdated = updateInternal(update);
    if (rowsUpdated > 0) {
        notifyForTable(DataChangedNotifier.DBOperation.UPDATE, template, table, TableModel.NO_ID);
    }
    return rowsUpdated;
}
 
Example #5
Source File: SquidDatabase.java    From squidb with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new {@link Index} in the database
 *
 * @param indexName name for the Index
 * @param table the table to create the index on
 * @param unique true if the index is a unique index on the specified columns
 * @param properties the columns to create the index on
 * @return true if the statement executed without error, false otherwise
 */
protected boolean tryCreateIndex(String indexName, Table table, boolean unique, Property<?>... properties) {
    if (properties == null || properties.length == 0) {
        onError(String.format("Cannot create index %s: no properties specified", indexName), null);
        return false;
    }
    StringBuilder sql = new StringBuilder(STRING_BUILDER_INITIAL_CAPACITY);
    sql.append("CREATE ");
    if (unique) {
        sql.append("UNIQUE ");
    }
    sql.append("INDEX IF NOT EXISTS ").append(indexName).append(" ON ").append(table.getExpression())
            .append("(");
    for (Property<?> p : properties) {
        sql.append(p.getName()).append(",");
    }
    sql.deleteCharAt(sql.length() - 1);
    sql.append(")");
    return tryExecSql(sql.toString());
}
 
Example #6
Source File: TasksDatabase.java    From squidb with Apache License 2.0 5 votes vote down vote up
@Override
protected Table[] getTables() {
    return new Table[]{
            Task.TABLE,
            Tag.TABLE
    };
}
 
Example #7
Source File: MyDatabase.java    From android-orm-benchmark-updated with Apache License 2.0 5 votes vote down vote up
@Override
protected Table[] getTables()
{
    return new Table[]{
        Message.TABLE, User.TABLE
    };
}
 
Example #8
Source File: PreparedInsertCache.java    From squidb with Apache License 2.0 5 votes vote down vote up
private ISQLitePreparedStatement prepareInsert(SquidDatabase db, Table table,
        TableStatement.ConflictAlgorithm conflictAlgorithm) {
    Object[] placeholders = new Object[table.getProperties().length];
    Arrays.fill(placeholders, new Object());

    Insert insert = Insert.into(table).columns(table.getProperties())
            .values(placeholders).onConflict(conflictAlgorithm);
    CompiledStatement compiled = insert.compile(db.getCompileContext());

    ISQLitePreparedStatement statement = db.prepareStatement(compiled.sql);
    dbStatementTracking.add(statement);
    return statement;
}
 
Example #9
Source File: SquidDatabase.java    From squidb with Apache License 2.0 5 votes vote down vote up
private long insertRowLegacy(TableModel item, Table table, TableStatement.ConflictAlgorithm conflictAlgorithm) {
    ValuesStorage mergedValues = item.getMergedValues();
    if (mergedValues.size() == 0) {
        return -1;
    }
    Insert insert = Insert.into(table).fromValues(mergedValues);
    if (conflictAlgorithm != null) {
        insert.onConflict(conflictAlgorithm);
    }
    return insertInternal(insert);
}
 
Example #10
Source File: SquidDatabase.java    From squidb with Apache License 2.0 5 votes vote down vote up
/**
 * Same as {@link #insertRow(TableModel)} with the ability to specify a ConflictAlgorithm for handling constraint
 * violations
 *
 * @param item the model to insert
 * @param conflictAlgorithm the conflict algorithm to use
 * @return true if success, false otherwise
 */
protected final boolean insertRow(TableModel item, TableStatement.ConflictAlgorithm conflictAlgorithm) {
    Class<? extends TableModel> modelClass = item.getClass();
    Table table = getTable(modelClass);

    long newRow;
    if (preparedInsertCacheEnabled) {
        acquireNonExclusiveLock();
        try {
            PreparedInsertCache insertCache = preparedInsertCache.get();
            ISQLitePreparedStatement preparedStatement =
                    insertCache.getPreparedInsert(this, table, conflictAlgorithm);
            item.bindValuesForInsert(table, preparedStatement);
            newRow = preparedStatement.executeInsert();
        } finally {
            releaseNonExclusiveLock();
        }
    } else {
        newRow = insertRowLegacy(item, table, conflictAlgorithm);
    }

    boolean result = newRow > 0;
    if (result) {
        notifyForTable(DataChangedNotifier.DBOperation.INSERT, item, table, newRow);
        item.setRowId(newRow);
        item.markSaved();
    }
    return result;
}
 
Example #11
Source File: SquidDatabase.java    From squidb with Apache License 2.0 5 votes vote down vote up
/**
 * Delete all rows matching the given {@link Criterion}
 *
 * @param modelClass model class for the table to delete from
 * @param where the Criterion to match. Note: passing null will delete all rows!
 * @return the number of deleted rows
 */
public int deleteWhere(Class<? extends TableModel> modelClass, Criterion where) {
    Table table = getTable(modelClass);
    Delete delete = Delete.from(table);
    if (where != null) {
        delete.where(where);
    }
    int rowsUpdated = deleteInternal(delete);
    if (rowsUpdated > 0) {
        notifyForTable(DataChangedNotifier.DBOperation.DELETE, null, table, TableModel.NO_ID);
    }
    return rowsUpdated;
}
 
Example #12
Source File: SquidDatabase.java    From squidb with Apache License 2.0 5 votes vote down vote up
/**
 * Delete the row with the given row ID
 *
 * @param modelClass the model class corresponding to the table to delete from
 * @param id the row ID of the record
 * @return true if delete was successful
 */
public boolean delete(Class<? extends TableModel> modelClass, long id) {
    Table table = getTable(modelClass);
    int rowsUpdated = deleteInternal(Delete.from(table).where(table.getRowIdProperty().eq(id)));
    if (rowsUpdated > 0) {
        notifyForTable(DataChangedNotifier.DBOperation.DELETE, null, table, id);
    }
    return rowsUpdated > 0;
}
 
Example #13
Source File: SquidDatabase.java    From squidb with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link Table} or {@link VirtualTable} in the database
 *
 * @param table the Table or VirtualTable to create
 * @return true if the statement executed without error, false otherwise
 */
protected boolean tryCreateTable(Table table) {
    SqlConstructorVisitor sqlVisitor = new SqlConstructorVisitor();
    StringBuilder sql = new StringBuilder(STRING_BUILDER_INITIAL_CAPACITY);
    table.appendCreateTableSql(getCompileContext(), sql, sqlVisitor);
    return tryExecSql(sql.toString());
}
 
Example #14
Source File: SquidDatabase.java    From squidb with Apache License 2.0 5 votes vote down vote up
/**
 * Called to create the database tables
 */
public void onCreate(ISQLiteDatabase db) {
    setDatabase(db);
    StringBuilder sql = new StringBuilder(STRING_BUILDER_INITIAL_CAPACITY);
    SqlConstructorVisitor sqlVisitor = new SqlConstructorVisitor();

    // create tables
    Table[] tables = getTables();
    if (tables != null) {
        for (Table table : tables) {
            table.appendCreateTableSql(getCompileContext(), sql, sqlVisitor);
            db.execSQL(sql.toString());
            sql.setLength(0);
        }
    }

    View[] views = getViews();
    if (views != null) {
        for (View view : views) {
            view.createViewSql(getCompileContext(), sql);
            db.execSQL(sql.toString());
            sql.setLength(0);
        }
    }

    Index[] indexes = getIndexes();
    if (indexes != null) {
        for (Index idx : indexes) {
            tryCreateIndex(idx);
        }
    }

    // post-table-creation
    SquidDatabase.this.onTablesCreated(db);
}
 
Example #15
Source File: TestDatabase.java    From squidb with Apache License 2.0 5 votes vote down vote up
@Override
protected Table[] getTables() {
    return new Table[]{
            TestModel.TABLE,
            Thing.TABLE,
            Employee.TABLE,
            TriggerTester.TABLE,
            BasicData.TABLE,
            TestVirtualModel.TABLE,
            TestMultiColumnKey.TABLE,
            TestNonIntegerPrimaryKey.TABLE
    };
}
 
Example #16
Source File: ReactiveSquidDatabaseTest.java    From squidb with Apache License 2.0 5 votes vote down vote up
private void testMultipleStatements(boolean useTransaction, boolean successfulTransaction) {
    final AtomicInteger callCount = new AtomicInteger();
    Observable<Table> observable = database.observeTable(TestModel.TABLE);
    observable.subscribe(new Action1<Table>() {
        @Override
        public void call(Table table) {
            callCount.incrementAndGet();
        }
    });
    assertEquals(0, callCount.get());
    if (useTransaction) {
        database.beginTransaction();
    }
    try {
        database.persist(new TestModel().setFirstName("A").setLastName("B")
                .setBirthday(System.currentTimeMillis() - 2));
        database.persist(new TestModel().setFirstName("C").setLastName("D")
                .setBirthday(System.currentTimeMillis() - 1));
        if (useTransaction && successfulTransaction) {
            database.setTransactionSuccessful();
        }
    } finally {
        if (useTransaction) {
            database.endTransaction();
        }
    }
    int expectedCount;
    if (useTransaction) {
        expectedCount = successfulTransaction ? 1 : 0;
    } else {
        expectedCount = 2;
    }
    assertEquals(expectedCount, callCount.get());
}
 
Example #17
Source File: ReactiveSquidDatabaseTest.java    From squidb with Apache License 2.0 5 votes vote down vote up
public void testSimpleObservableEmitsTable() {
    final AtomicBoolean tablesMatch = new AtomicBoolean(false);
    Observable<Table> observable = database.observeTable(TestModel.TABLE, true);
    observable.subscribe(new Action1<Table>() {
        @Override
        public void call(Table table) {
            tablesMatch.set(TestModel.TABLE.equals(table));
        }
    });
    assertTrue(tablesMatch.get());
}
 
Example #18
Source File: ReactiveSquidDatabaseTest.java    From squidb with Apache License 2.0 5 votes vote down vote up
public void testObservableWithInitialSubscribeFlagEmitsOnFirstSubscribe() {
    final AtomicBoolean called = new AtomicBoolean(false);
    Observable<Table> observable = database.observeTable(TestModel.TABLE, true);
    observable.subscribe(new Action1<Table>() {
        @Override
        public void call(Table table) {
            called.set(true);
        }
    });
    assertTrue(called.get());
}
 
Example #19
Source File: TestReactiveDatabase.java    From squidb with Apache License 2.0 5 votes vote down vote up
@Override
protected Table[] getTables() {
    return new Table[]{
            TestModel.TABLE,
            Thing.TABLE,
            Employee.TABLE,
            TriggerTester.TABLE,
            BasicData.TABLE,
            TestVirtualModel.TABLE
    };
}
 
Example #20
Source File: SquidDatabase.java    From squidb with Apache License 2.0 4 votes vote down vote up
protected <TYPE extends TableModel> SquidCursor<TYPE> fetchItemById(Class<TYPE> modelClass, long id,
        Property<?>... properties) {
    Table table = getTable(modelClass);
    return fetchFirstItem(modelClass, table.getRowIdProperty().eq(id), properties);
}
 
Example #21
Source File: MySquidDatabase.java    From android-database-performance with Apache License 2.0 4 votes vote down vote up
@Override
protected Table[] getTables() {
    return new Table[] { SimpleEntityNotNull.TABLE, IndexedStringEntity.TABLE };
}
 
Example #22
Source File: SquidDatabase.java    From squidb with Apache License 2.0 2 votes vote down vote up
/**
 * Drop a {@link Table} or {@link VirtualTable} in the database if it exists
 *
 * @param table the Table or VirtualTable to drop
 * @return true if the statement executed without error, false otherwise
 */
protected boolean tryDropTable(Table table) {
    return tryExecSql("DROP TABLE IF EXISTS " + table.getExpression());
}
 
Example #23
Source File: SquidDatabase.java    From squidb with Apache License 2.0 2 votes vote down vote up
/**
 * Return the {@link Table} corresponding to the specified TableModel class
 *
 * @param modelClass the model class
 * @return the corresponding table for the model
 * @throws UnsupportedOperationException if the model class is unknown to this database
 */
protected final Table getTable(Class<? extends TableModel> modelClass) {
    return (Table) getSqlTable(modelClass);
}
 
Example #24
Source File: SquidDatabase.java    From squidb with Apache License 2.0 2 votes vote down vote up
/**
 * @return all {@link Table Tables} and {@link VirtualTable VirtualTables} and that should be created when the
 * database is created
 */
protected abstract Table[] getTables();