Skip to content

Commit

Permalink
Never set integer primary key fields to empty string
Browse files Browse the repository at this point in the history
Don't attempt to set an INTEGER PRIMARY KEY field to an empty string as
it will always result in a 'datatype mismatch' error by SQLite. Instead
set it to '0'.

See issue sqlitebrowser#859.
  • Loading branch information
MKleusberg committed Feb 15, 2017
1 parent 8533433 commit eddeb78
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/sqlitetablemodel.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,19 @@ bool SqliteTableModel::setTypedData(const QModelIndex& index, bool isBlob, const
QByteArray newValue = encode(value.toByteArray());
QByteArray oldValue = m_data.at(index.row()).at(index.column());

// Special handling for integer columns: instead of setting an integer column to an empty string, set it to '0' when it is also
// used in a primary key. Otherwise SQLite will always output an 'datatype mismatch' error.
if(newValue == "" && !newValue.isNull())
{
sqlb::TablePtr table = m_db.getObjectByName(m_sTable).dynamicCast<sqlb::Table>();
if(table)
{
sqlb::FieldPtr field = table->field(table->findField(m_headers.at(index.column())));
if(table->primaryKey().contains(field) && field->isInteger())
newValue = "0";
}
}

// Don't do anything if the data hasn't changed
// To differentiate NULL and empty byte arrays, we also compare the NULL flag
if(oldValue == newValue && oldValue.isNull() == newValue.isNull())
Expand Down

0 comments on commit eddeb78

Please sign in to comment.