Search code examples
androidmysqldbflow

Get SQL insert statement string from model?


Pretty simple question, assuming I've got the model for a row in a table, I'd like to get the insert statement necessary to create that row.

List<MyModel> updatedRows = new Select()
                .from(MyDatabase.getMyModels().get(table))
                .where(Condition.column(NameAlias.builder("id").build())
                .in(new Select(UpdatedRecord$Table.updated_record_id)
                        .from(UpdatedRecord.class)
                        .where(UpdatedRecord$Table.updated_table.eq(table))))
                .queryList();

StringBuilder updateStatements = new StringBuilder();
for (MyModel tableModel : updatedRows) {
    // this is the insert statement, but there's no way to get it as a string
    tableModel.getModelAdapter().getInsertStatement();
    updateStatements.append(insertSqlStatementString);
}

tableModel.getModelAdapter().getInsertStatement() properly returns the insert statement, however, it is in the form of a DatabaseStatement, and I can't find any documentation for that class. I want the insert statement as a string.

Looking at that line in the debugger shows that underneath it there is a Statement and inside of that, mSQL which holds the string.

Can anyone help me out or point me in the right direction?

Tried this to no avail:

String tableCreateStatement = tableModel.getModelAdapter().getCreationQuery();
DatabaseStatement dbSt = tableModel.getModelAdapter().getCompiledStatement();
tableModel.getModelAdapter().bindToInsertStatement(dbSt, tableModel);
AndroidDatabaseStatement a = (AndroidDatabaseStatement)dbSt;
String p = a.getStatement().toString();

Solution

  • Here's what I ended up using after the main contributor to DBFlow responded to my question here:

    // BaseModel row;
    ContentValues values = new ContentValues();
    row.getModelAdapter().bindToInsertValues(values, row);
    String query = SQLite.insert(row.getClass()).columnValues(values).getQuery();