m261009_000002_allow_empty_declaration_payer.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. use yii\db\Migration;
  3. class m261009_000002_allow_empty_declaration_payer extends Migration
  4. {
  5. public function safeUp()
  6. {
  7. $this->setPayerNullability(false);
  8. }
  9. public function safeDown()
  10. {
  11. $table = '{{%APPROACH_DEC_ORDER}}';
  12. $nullCount = (int) (new \yii\db\Query())
  13. ->from($table)
  14. ->where(['USER_ID' => null])
  15. ->count('*', $this->db);
  16. if ($nullCount > 0) {
  17. throw new \RuntimeException('Cannot restore APPROACH_DEC_ORDER.USER_ID NOT NULL while guest declaration rows exist.');
  18. }
  19. $this->setPayerNullability(true);
  20. }
  21. private function setPayerNullability(bool $notNull): void
  22. {
  23. $table = '{{%APPROACH_DEC_ORDER}}';
  24. $schema = $this->db->getTableSchema($table, true);
  25. if (!$schema || !isset($schema->columns['USER_ID'])) {
  26. throw new \RuntimeException('APPROACH_DEC_ORDER.USER_ID column was not found.');
  27. }
  28. $column = $schema->columns['USER_ID'];
  29. if ((bool) $column->allowNull === !$notNull) {
  30. return;
  31. }
  32. $definition = $this->db->getSchema()->createColumnSchemaBuilder($column->type, $column->size);
  33. $definition->notNull($notNull);
  34. $this->alterColumn($table, 'USER_ID', $definition);
  35. }
  36. }