generateUniqueSqliteFunction method
Generates the method primaryKeyByUniqueColumns
for the adapter
Implementation
@protected
@mustCallSuper
String generateUniqueSqliteFunction(Map<String, String> uniqueFields) {
final functionDeclaration =
'@override\nFuture<int?> primaryKeyByUniqueColumns(${element.name} instance, DatabaseExecutor executor) async';
final whereStatement = <String>[];
final valuesStatement = <String>[];
final selectStatement = <String>[];
for (final entry in uniqueFields.entries) {
whereStatement.add('${entry.value} = ?');
valuesStatement.add('instance.${entry.key}');
selectStatement.add(entry.value);
}
if (selectStatement.isEmpty && whereStatement.isEmpty) {
return '$functionDeclaration => instance.primaryKey;';
}
return """$functionDeclaration {
final results = await executor.rawQuery('''
SELECT * FROM `$tableName` WHERE ${whereStatement.join(' OR ')} LIMIT 1''',
[${valuesStatement.join(',')}]
);
// SQFlite returns [{}] when no results are found
if (results.isEmpty || (results.length == 1 && results.first.isEmpty)) {
return null;
}
return results.first['${InsertTable.PRIMARY_KEY_COLUMN}'] as int;
}""";
}