writeColumnDefinition method

void writeColumnDefinition(
  1. GenerationContext into
)

Writes the definition of this column, as defined here, into the given buffer.

Implementation

void writeColumnDefinition(GenerationContext into) {
  final isSerial = into.dialect == SqlDialect.postgres && hasAutoIncrement;
  final escapedName = escapedNameFor(into.dialect);

  if (isSerial) {
    into.buffer.write('$escapedName bigserial PRIMARY KEY NOT NULL');
  } else {
    into.buffer.write('$escapedName ${type.sqlTypeName(into)}');
  }

  if ($customConstraints == null) {
    if (!isSerial) {
      into.buffer.write($nullable ? ' NULL' : ' NOT NULL');
    }

    final defaultValue = this.defaultValue;
    if (defaultValue != null) {
      into.buffer.write(' DEFAULT ');

      // we need to write brackets if the default value is not a literal.
      // see https://www.sqlite.org/syntax/column-constraint.html
      final writeBrackets = !defaultValue.isLiteral;

      if (writeBrackets) into.buffer.write('(');
      defaultValue.writeInto(into);
      if (writeBrackets) into.buffer.write(')');
    }

    final generated = generatedAs;
    if (generated != null) {
      into.buffer.write(' GENERATED ALWAYS AS (');
      generated.generatedAs.writeInto(into);
      into.buffer
        ..write(') ')
        ..write(generated.stored ? 'STORED' : 'VIRTUAL');
    }

    final checkExpr = check?.call();
    if (checkExpr != null) {
      into.buffer.write(' CHECK(');
      checkExpr.writeInto(into);
      into.buffer.write(')');
    }

    // these custom constraints refer to builtin constraints from drift
    if (!isSerial && _defaultConstraints != null) {
      _defaultConstraints(into);
    }
  } else if ($customConstraints?.isNotEmpty == true) {
    into.buffer
      ..write(' ')
      ..write($customConstraints);
  }
}