lundi 14 mars 2016

sqlite "upsertOrThrow" when there's a primary key and another unique column

I am trying to write an upsert function that can insert new rows or update existing rows. The catch is that I have a PRIMARY KEY and another UNIQUE column.

test table:

CREATE TABLE test (
     _id INTEGER PRIMARY KEY,
     name TEXT,
     uniq_field TEXT UNIQUE ON_CONFLICT FAIL)

test data:

_id | name   | uniq_field
  1 | first  | foo
  2 | second | bar

Now I want to be able to do the following operations:

Inserting new (non-conflicting) row should insert row with _id=3:

upsert(null, 'third','moo');

Inserting row that conflicts in the UNIQUE field should fail:

upsert(null, 'third','foo'); // foo exists

Updating existing row with no conflict:

upsert(1, 'FIRST','mew');

Updating existing row with conflict in the uniq field:

upsert(1, 'FIRST','bar'); // bar exists

This is my current code from MyDbHelper (extends SQLiteOpenHelper):

public long upsert(final Long _id, final String name, final String uniqField) {
    final ContentValues values = new ContentValues();
    if (_id != null && _id != -1) {
        values.put(ItemColumns._ID, _id);
    }
    values.put(ItemColumns.NAME, name);
    values.put(ItemColumns.UNIQ_FIELD, uniqField);

    SQLiteDatabase db = getWritableDatabase();
    // Insert the new row, returning the primary key value of the new row

    // TRIED THIS:
    final long newRowId = db.replaceOrThrow(
            getTableName(),
            null,
            values);

    // AND THIS AS WELL:
    final long newRowId = db.insertWithOnConflict(
            getTableName(),
            null,
            values,
            SQLiteDatabase.CONFLICT_REPLACE);

    return newRowId;
}

Aucun commentaire:

Enregistrer un commentaire