build method
Implementation
JsonQuery build() {
if (_modelName == null) {
throw StateError('Model name is required');
}
if (_action == null) {
throw StateError('Action is required');
}
final arguments = <String, dynamic>{};
if (_where != null) arguments['where'] = _where;
if (_data != null) arguments['data'] = _data;
if (_orderBy != null) arguments['orderBy'] = _orderBy;
if (_take != null) arguments['take'] = _take;
if (_skip != null) arguments['skip'] = _skip;
if (_aggregate != null) arguments['_aggregate'] = _aggregate;
if (_groupBy != null) arguments['by'] = _groupBy;
if (_selectFields != null) arguments['selectFields'] = _selectFields;
if (_computed != null) {
arguments['_computed'] = _computed!.map(
(key, value) => MapEntry(key, value.toJson()),
);
}
// DISTINCT support
if (_distinct) {
arguments['distinct'] = true;
if (_distinctFields != null && _distinctFields!.isNotEmpty) {
arguments['distinctFields'] = _distinctFields;
}
}
// Build selection
JsonSelection? selection;
if (_select != null || _include != null || _includeRequired != null) {
final fields = <String, JsonFieldSelection>{};
if (_select != null) {
for (final entry in _select!.entries) {
if (entry.value == true) {
fields[entry.key] = const JsonFieldSelection();
}
}
}
// Include with LEFT JOIN (default)
if (_include != null) {
for (final entry in _include!.entries) {
if (entry.value == true) {
fields[entry.key] = const JsonFieldSelection(
selection: JsonSelection(scalars: true),
);
} else if (entry.value is Map) {
fields[entry.key] = JsonFieldSelection(
arguments: entry.value as Map<String, dynamic>,
selection: const JsonSelection(scalars: true),
);
}
}
}
// Include with INNER JOIN (required relations)
if (_includeRequired != null) {
for (final entry in _includeRequired!.entries) {
final args = <String, dynamic>{'_joinType': 'inner'};
if (entry.value == true) {
fields[entry.key] = JsonFieldSelection(
arguments: args,
selection: const JsonSelection(scalars: true),
);
} else if (entry.value is Map) {
final existingArgs = entry.value as Map<String, dynamic>;
final finalArgs = Map<String, dynamic>.from(existingArgs);
finalArgs['_joinType'] =
'inner'; // Ensure INNER JOIN takes precedence
fields[entry.key] = JsonFieldSelection(
arguments: finalArgs,
selection: const JsonSelection(scalars: true),
);
}
}
}
selection = JsonSelection(
scalars: _selectScalars,
fields: fields.isNotEmpty ? fields : null,
);
} else {
selection = JsonSelection(scalars: _selectScalars);
}
return JsonQuery(
modelName: _modelName!,
action: _action!,
args: JsonQueryArgs(
arguments: arguments.isNotEmpty ? arguments : null,
selection: selection,
),
);
}