writeMappingMethod method

void writeMappingMethod(
  1. Scope scope
)

Implementation

void writeMappingMethod(Scope scope) {
  if (!scope.generationOptions.writeDataClasses) {
    final nullableString = scope.nullableType('String');
    buffer.writeln('''
      @override
      Never map(Map<String, dynamic> data, {$nullableString tablePrefix}) {
        throw UnsupportedError('TableInfo.map in schema verification code');
      }
    ''');
    return;
  }

  final dataClassName = tableOrView.dartTypeCode(scope.generationOptions);

  buffer.write('@override\n$dataClassName map(Map<String, dynamic> data, '
      '{${scope.nullableType('String')} tablePrefix}) {\n');

  if (tableOrView.hasExistingRowClass) {
    buffer.write('final effectivePrefix = '
        "tablePrefix != null ? '\$tablePrefix.' : '';");

    final info = tableOrView.existingRowClass!;
    final positionalToIndex = <MoorColumn, int>{};
    final named = <MoorColumn, String>{};

    final parameters = info.constructor.parameters;
    info.mapping.forEach((column, parameter) {
      if (parameter.isNamed) {
        named[column] = parameter.name;
      } else {
        positionalToIndex[column] = parameters.indexOf(parameter);
      }
    });

    // Sort positional columns by the position of their respective parameter
    // in the constructor.
    final positional = positionalToIndex.keys.toList()
      ..sort(
          (a, b) => positionalToIndex[a]!.compareTo(positionalToIndex[b]!));

    final writer = RowMappingWriter(
      positional,
      named,
      tableOrView,
      scope.generationOptions,
      scope.options,
    );

    final classElement = info.targetClass;
    final ctor = info.constructor;
    buffer
      ..write('return ')
      ..write(classElement.name);
    if (ctor.name.isNotEmpty) {
      buffer
        ..write('.')
        ..write(ctor.name);
    }

    writer.writeArguments(buffer);
    buffer.write(';\n');
  } else {
    // Use default .fromData constructor in the moor-generated data class
    final hasDbParameter = scope.generationOptions.writeForMoorPackage &&
        tableOrView is MoorTable;
    if (hasDbParameter) {
      buffer.write('return $dataClassName.fromData(data, attachedDatabase, '
          "prefix: tablePrefix != null ? '\$tablePrefix.' : null);\n");
    } else {
      buffer.write('return $dataClassName.fromData(data, '
          "prefix: tablePrefix != null ? '\$tablePrefix.' : null);\n");
    }
  }

  buffer.write('}\n');
}