isUniqueSQLField static method
ValidatorEvent
isUniqueSQLField({
- required MySQLConnection db,
- required String table,
- required String field,
- QO operator = QO.EQ,
- Where? where,
Validator to check if a field value is unique in a SQL database table.
The validator checks whether the provided value already exists in the specified table and field.
If the value exists, an error message 'error.field.unique'
is returned.
Parameters:
db
: The MySQLConnection instance to use for the database query. (required)table
: The name of the database table to check. (required)field
: The name of the field/column to check for uniqueness. (required)operator
: The comparison operator to use in the query. Defaults toQO.EQ
.where
: An optional additionalWhere
clause to further filter the query. Returns:ValidatorEvent
: A validator event function that can be used in theFormValidator
.
Implementation
static ValidatorEvent isUniqueSQLField({
required MySQLConnection db,
required String table,
required String field,
QO operator = QO.EQ,
Where? where,
}) {
return (v) async {
Sqler sqler = Sqler();
sqler.from(QField(table));
sqler.addSelect(SQL.count(QField(field, as: 'count_of_field')));
sqler.where(WhereOne(QField(field), operator, QVar(v)));
if (where != null) {
sqler.where(where);
}
var res = await db.execute(sqler.toSQL());
if (res.rows.isNotEmpty) {
var count = res.rows.first.assoc()['count_of_field'] ?? '0';
if (count.toString().toInt(def: 10) == 0) {
return FieldValidateResult(success: true);
}
}
return FieldValidateResult(success: false, error: 'error.field.unique');
};
}