addColumn method

  1. @override
void addColumn(
  1. String name,
  2. String type, {
  3. bool nullable = false,
  4. dynamic length,
  5. bool unsigned = false,
  6. bool zeroFill = false,
  7. dynamic defaultValue,
  8. String? comment,
  9. String? collation,
  10. String? expression,
  11. String? virtuality,
  12. bool increment = false,
  13. bool unique = false,
})

Implementation

@override
void addColumn(
  String name,
  String type, {
  bool nullable = false,
  dynamic length,
  bool unsigned = false,
  bool zeroFill = false,
  dynamic defaultValue,
  String? comment,
  String? collation,
  String? expression,
  String? virtuality,
  bool increment = false,
  bool unique = false,
}) {
  final columnDefinition = StringBuffer('  `$name` $type');

  if (length != null) {
    columnDefinition.write('($length)');
  }

  if (unsigned) {
    columnDefinition.write(' UNSIGNED');
  }

  if (zeroFill) {
    columnDefinition.write(' ZEROFILL');
  }

  String nullableStr = nullable ? 'NULL' : 'NOT NULL';
  columnDefinition
      .write(' ' * (20 - columnDefinition.length % 20) + nullableStr);

  if (unique) {
    columnDefinition.write(' UNIQUE');
  }

  if (defaultValue != null) {
    RegExp funcRegex = RegExp(
        r'^(CURRENT_TIMESTAMP|NOW\(\)|UUID\(\)|RAND\(\))$',
        caseSensitive: false);
    if (funcRegex.hasMatch(defaultValue.toString())) {
      columnDefinition.write(" DEFAULT $defaultValue");

      if (name == 'updated_at' &&
          defaultValue.toString().toUpperCase() == 'CURRENT_TIMESTAMP') {
        columnDefinition.write(" ON UPDATE CURRENT_TIMESTAMP");
      }
    } else {
      if (defaultValue is int || defaultValue is bool) {
        columnDefinition.write(" DEFAULT $defaultValue");
      } else {
        columnDefinition.write(" DEFAULT '$defaultValue'");
      }
    }
  }

  if (comment != null) {
    columnDefinition.write(" COMMENT '$comment'");
  }

  if (collation != null) {
    columnDefinition.write(" COLLATE $collation");
  }

  if (expression != null) {
    columnDefinition.write(' GENERATED ALWAYS AS ($expression)');
  }

  if (virtuality != null) {
    columnDefinition.write(' $virtuality');
  }

  if (increment) {
    columnDefinition.write(' AUTO_INCREMENT');
  }

  _queries.add(columnDefinition.toString());
}