From 08d3ebba69520f2e800323709201d85c9c80527c Mon Sep 17 00:00:00 2001
From: Alex Pott <alex.a.pott@googlemail.com>
Date: Wed, 12 Nov 2014 23:24:17 -0800
Subject: [PATCH] Issue #2232477 by tstoeckler, a 'fliptable' mateescu, plach:
 Fixed Fatal when adding new fields with NOT NULL constraints in a base table
 that contains existing entities.

---
 .../Core/Entity/Sql/SqlContentEntityStorageSchema.php    | 9 +++++++++
 .../Entity/Sql/SqlContentEntityStorageSchemaTest.php     | 2 ++
 2 files changed, 11 insertions(+)

diff --git a/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorageSchema.php b/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorageSchema.php
index dac658484c82..f48bf3d6926c 100644
--- a/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorageSchema.php
+++ b/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorageSchema.php
@@ -1415,10 +1415,19 @@ protected function getSharedTableFieldSchema(FieldStorageDefinitionInterface $st
       // table. For this reason the revision ID field cannot be marked as NOT
       // NULL.
       unset($keys['label'], $keys['revision']);
+
       // Key fields may not be NULL.
       if (in_array($field_name, $keys)) {
         $schema['fields'][$schema_field_name]['not null'] = TRUE;
       }
+      // All the other columns have to be able to be NULL regardless of the
+      // actual field storage schema in order to support adding a base field
+      // definition to an entity type with non-empty base table(s).
+      // @todo Revisit the strict 'not null' => FALSE requirement for all
+      // non-key columns in https://www.drupal.org/node/2346019.
+      elseif (isset($schema['fields'][$schema_field_name]['not null'])) {
+        $schema['fields'][$schema_field_name]['not null'] = FALSE;
+      }
     }
 
     if (!empty($field_schema['indexes'])) {
diff --git a/core/tests/Drupal/Tests/Core/Entity/Sql/SqlContentEntityStorageSchemaTest.php b/core/tests/Drupal/Tests/Core/Entity/Sql/SqlContentEntityStorageSchemaTest.php
index 222dd133768c..f2c83a37a2fe 100644
--- a/core/tests/Drupal/Tests/Core/Entity/Sql/SqlContentEntityStorageSchemaTest.php
+++ b/core/tests/Drupal/Tests/Core/Entity/Sql/SqlContentEntityStorageSchemaTest.php
@@ -220,6 +220,7 @@ public function testGetSchemaBase() {
       'columns' => array(
         'target_id' => array(
           'type' => 'int',
+          'not null' => TRUE,
         ),
         'target_revision_id' => array(
           'type' => 'int',
@@ -315,6 +316,7 @@ public function testGetSchemaBase() {
           'editor_revision__target_id' => array(
             'description' => 'The editor_revision field.',
             'type' => 'int',
+            'not null' => FALSE,
           ),
           'editor_revision__target_revision_id' => array(
             'description' => 'The editor_revision field.',
-- 
GitLab