toPgSql method

String toPgSql({
  1. required String tableName,
  2. required ColumnDefinition columnDefinition,
})

Implementation

String toPgSql({
  required String tableName,
  required ColumnDefinition columnDefinition,
}) {
  var out = '';
  if (addNullable) {
    out +=
        'ALTER TABLE "$tableName" ALTER COLUMN "$physicalName"'
        ' DROP NOT NULL;\n';
  } else if (removeNullable) {
    out +=
        'ALTER TABLE "$tableName" ALTER COLUMN "$physicalName"'
        ' SET NOT NULL;\n';
  }
  if (changeDefault) {
    if (newDefault == null) {
      out +=
          'ALTER TABLE "$tableName" ALTER COLUMN "$physicalName"'
          ' DROP DEFAULT;\n';
      return out;
    } else if (newDefault == defaultIntSerial) {
      // Adding a serial default requires creating a sequence via the serial
      // pseudo-type on column (re)create. SET DEFAULT cannot express this.
      throw StateError(
        'Cannot SET DEFAULT "$defaultIntSerial" on column "$physicalName" '
        'of table "$tableName". Auto-increment defaults must be applied by '
        'recreating the column with the serial type.',
      );
    } else {
      var newDefaultSql = columnDefinition.columnType.getPgColumnDefault(
        newDefault,
      );
      out +=
          'ALTER TABLE "$tableName" ALTER COLUMN "$physicalName"'
          ' SET DEFAULT $newDefaultSql;\n';
    }
  }

  if (newType != null) {
    var typeName = newType!.name;
    out +=
        'ALTER TABLE "$tableName" ALTER COLUMN "$columnName"'
        ' SET DATA TYPE $typeName USING "$columnName"::$typeName;\n';
  }

  return out;
}