Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL timestamp does not change when UPDATE happens

I use the following SQL command to create a products table on an Android client.

CREATE TABLE IF NOT EXISTS 'products' (
  '_id' INTEGER PRIMARY KEY AUTOINCREMENT,
  'name' TEXT,
  'serverId' INTEGER, 
  'modifiedAt' TIMESTAMP DEFAULT CURRENT_TIMESTAMP, 
  UNIQUE ( 'serverId' ) 
ON CONFLICT REPLACE );

When I load data from a server and insert it into the local database, I use the following commands in the content provider to either update a row or insert new values.

public int bulkInsert(Uri uri, ContentValues[] values) {
    final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    long rowId;
    int rowsAdded = 0;
    for (ContentValues contentValues : values) {
        int affectedRows = db.update("products", contentValues, 
                "serverId = ?", 
                new String[] { contentValues.getAsString("serverId") });
        if (affectedRows == 0) {
            rowId = db.insert("products", null, contentValues);
            if (rowId > 0) {
                rowsAdded++;
            }
        }
    }
    return rowsAdded;
}

All columns are updated when new values are there, except the column modifiedAt.
Note: The bulk commands are wrapped into a transaction. I left out the code to keep the question simple.

Question:

How can I update the timestamp of the modifiedAt column every time an update happens?

like image 387
JJD Avatar asked Mar 28 '26 02:03

JJD


1 Answers

You could let the database handle that by setting up triggers:

Untested...

database.execSQL("CREATE TRIGGER updateLastModifiedDate " +
     "AFTER INSERT ON products FOR EACH ROW BEGIN " +
     "UPDATE products SET modifiedAt = date('now') " +
     "WHERE _id = NEW.id " +
     "END;");

database.execSQL("CREATE TRIGGER updateLastModifiedDate " +
     "AFTER UPDATE ON products FOR EACH ROW BEGIN " +
     "UPDATE products SET modifiedAt = date('now') " +
     "WHERE _id = NEW.id " +
     "END;");
like image 57
jenzz Avatar answered Mar 29 '26 16:03

jenzz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!