build method
Builds the SQL query string from the SqlBuilder instance.
This method constructs the SQL query string by joining the statements in the _select list.
It also performs various checks to ensure that the SQL query is valid.
The print parameter is optional and defaults to false. If print is true, the final SQL query string is logged using PrintHandler.warningLogger.i().
The method throws an Exception if the SQL query is invalid. For example, if the 'select' statement is not the first one in the _select list, or if the 'select' statement is missing.
The flow of the method is as follows:
- It initializes a
statementsmap with keys as SQL statement names and values asStatementobjects. - If
_selectlist is empty and_rawSqlis not null and valid, it returns_rawSql. - If
_selectlist is not empty, it iterates over the list and performs the following checks:- If the statement name is 'select' and it's not the first statement, it logs an error and throws an
Exception. - It checks the index of the current statement and the count of the same type of statements.
- If the statement name is 'select' and it's not the first statement, it logs an error and throws an
- It joins the
_selectlist into a string to form the final SQL query. - If
printistrue, it logs the final SQL query. - It returns the final SQL query.
- If
_selectlist is empty and_rawSqlis null or invalid, it logs an error and throws anException.
It's important to note that the select method of the DAO uses this method to create the SQL query. Therefore, it's not necessary to make a raw query with this method. The use of this method is primarily for debugging or similar purposes.
Usage:
String sentence = SqlBuilder().addTheStatementsToTheBuilder().build(print: true);
Returns the final SQL query string.
Implementation
String build({bool print = false}) {
var statements = {
'select': Statement('select', 0),
'from': Statement('from', 0),
'join': Statement('join', 0),
'where': Statement('where', 0),
'order': Statement('order', 0),
'limit': Statement('limit', 0),
};
if (_select.isEmpty && _rawSql != null && _checkStatement(_rawSql!)) {
return _rawSql!;
} else if (_select.isNotEmpty) {
for (var index = 0; index < _select.length; index++) {
var statementName = _select[index].split(' ')[0].toLowerCase();
if (statements.containsKey(statementName)) {
var statement = statements[statementName];
if (statementName == 'select' && index != 0) {
_error +=
'The select statement must be the first one in the sentence.';
PrintHandler.warningLogger.e(_error);
throw Exception(_error);
} else {
_checkIndex(index, _select.length, statementName,
isLimit: statementName == 'limit');
_checkIndexCount(statement!.index, statementName);
statement.index++;
}
}
}
var finalSql = _select.join();
if (print) {
PrintHandler.warningLogger.i(finalSql);
}
return finalSql;
} else {
_error += 'The select statement is required.';
PrintHandler.warningLogger.e(_error);
throw Exception(_error);
}
}