LogicException: The database connection is not serializable.

Created on 23 July 2018, almost 7 years ago
Updated 18 June 2022, about 3 years ago

Hi,

Im not sure if anyone else has got this error or not, but when I try to perform a validation $form_state->setErrorI am getting an error 

LogicException: The database connection is not serializable. This probably means you are serializing an object that has an indirect reference to the database connection. Adjust your code so that is not necessary. Alternatively, look at DependencySerializationTrait as a temporary solution. in Drupal\Core\Database\Connection->__sleep()

I will explain a bit more. In my form I have a form element which has an "Add more" functionality. That is, I can add another instance of that field with an incremented index in its name which is working all fine. Now I have added a form validation and want to validate against all the instances of this field. Its a straight forward validation logic

if (empty($field)) {
  $form_state->setError($form['content_bag_container']['bag_wrapper'][$key]['content_bag'], t('Please enter a content bag name.'));
}

Weirdly enough, this validation works for the first instance of the form element which pre-loads with the page itself. But whenever, I create a new instance via ajax, this validation fails and throws this error message in the log.

Can anyone check if this is some problem from my end or a bug in the core, cause I am not sure if an ajax populated field should be validated separately.

Thanks in advance...

๐Ÿ› Bug report
Status

Postponed: needs info

Version

9.5

Component
Formย  โ†’

Last updated 2 days ago

Created by

๐Ÿ‡ฎ๐Ÿ‡ณIndia pratip.ghosh

Live updates comments and jobs are added and updated live.
  • Needs tests

    The change is currently missing an automated test that fails when run with the original code, and succeeds when the bug has been fixed.

Sign in to follow issues

Merge Requests

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • last update about 2 years ago
    30,322 pass
  • Got the same problem on a Drupal 9.5.9 / 9.5.10, migrated from a 8.x, when tring to add a file in a file field in a node.
    No custom code in this content type.

    Patch #15 work for me.
    Thanks.

  • ๐Ÿ‡ซ๐Ÿ‡ฎFinland aleksip Finland

    Five years later I come across this again, on Drupal 10.1.4. This time it happens if I set a translated error message in my form validation code. And does not happen with an untranslated error message. And the fix in #15 does seem to work.

    Considering the nature of the exception and reading all the comments it seems likely that there are different causes for the exception, probably requiring different fixes.

    I also wonder about the fix in #15, since the exception message states that DependencySerializationTrait should be looked as a temporary solution.

  • ๐Ÿ‡บ๐Ÿ‡ธUnited States SamLerner

    I'm seeing a similar issue on a Drupal 10.1.4 site, and I've narrowed it down to the Agreement module. Based on the comments that refer to the problem being with translating form errors, I think this code is the problem:

      public function validateForm(array &$form, FormStateInterface $form_state) {
        $storage = $form_state->getStorage();
        $agreement = $storage['agreement'];
        if (!$agreement->allowsRejecting() && !$form_state->getValue('agree') && !$storage['agreed']) {
          $settings = $agreement->getSettings();
          $form_state->setErrorByName('agree', $this->t('@agree_error', ['@agree_error' => $settings['failure']]));
        }
      }
    

    If the form is getting serialized, and the error message is using t(), then it's possible this is where the database connection is getting serialized as well. I can't reproduce the issue locally, so I'm applying the patch in #15 and will verify when the change gets to production.

    I am also curious about what should be done long-term if indeed DependencySerializationTrait is meant to be temporary.

  • ๐Ÿ‡ณ๐Ÿ‡ฑNetherlands johnv

    Relating to a meta issue.

  • ๐Ÿ‡บ๐Ÿ‡ธUnited States SamLerner

    Adding the DependencySerializationTrait didn't seem to solve my issue, I either didn't put it in the right place, or it's not the same cause of the error. I'll keep looking and see if I can figure out where it's coming from.

  • ๐Ÿ‡ณ๐Ÿ‡ฑNetherlands johnv

    Indeed, the problem is in an apparently unrelated class/object.

    In #35, if you replace $this->t('@agree_error' with global t('@agree_error', I expect the problem to be gone.

  • Status changed to Needs review over 1 year ago
  • ๐Ÿ‡ณ๐Ÿ‡ฑNetherlands johnv

    Let me re-open this issue and post a proposal patch.
    In the OP, I added some comments that makes the problem reproducable.
    Please check ๐Ÿ› LogicException: The database connection is not serializable (for string translations in Ajax callback) [META] Active , which I created with many references to other reported issues of (apparently) the same problem.
    IMO, adding DependencySerializationTrait to so many other, unrelated core/contrib classes is not the way to go. (Therefore, it is euphemistically a 'temporary' solution.)

    Attached patch interferes in the serialization of the TranslationManager, which contains a list of Translators (TranslatorInterface).
    By NOT serializing the listed Translators, the problem disappears.
    Unlike other objects, those Translators are re-created after the unserialization of the form.

    In my test case, 2 Translators were listed:
    - Drupal\Core\StringTranslation\Translator\CustomStrings (serializable)
    - Drupal\locale\LocaleTranslation (NOT serializable)
    As per comments in other topics, the second is not serializable due to an open DatabaseConnection. The object contains DependencySerializationTrait itself, but apparently that does not work.

    Hence, proposed solution is in TranslationManager, not in TranslatorInterface instances.
    My test case: #3399054-23: Ajax error on [Add exception] button if "seasons" is activated โ†’

    Let me first upload this patch, to check the tests.
    Then, let me add another patch, removing DependencySerializationTrait from some core classes.

  • Open in Jenkins โ†’ Open on Drupal.org โ†’
    Environment: PHP 8.1 & MariaDB 10.3.22
    last update over 1 year ago
    Patch Failed to Apply
  • last update over 1 year ago
    Patch Failed to Apply
  • last update over 1 year ago
    Patch Failed to Apply
  • Open in Jenkins โ†’ Open on Drupal.org โ†’
    Environment: PHP 8.1 & MySQL 5.7 updated deps
    last update over 1 year ago
    Patch Failed to Apply
  • Status changed to Needs work over 1 year ago
  • The Needs Review Queue Bot โ†’ tested this issue.

    While you are making the above changes, we recommend that you convert this patch to a merge request โ†’ . Merge requests are preferred over patches. Be sure to hide the old patch files as well. (Converting an issue to a merge request without other contributions to the issue will not receive credit.)

  • ๐Ÿ‡บ๐Ÿ‡ฆUkraine artem_kondra

    I have the same issue in Drupal core 10.1.6 with nl translation node, confirm that #15 solves problems, it will be great to see that in core

  • ๐Ÿ‡ฌ๐Ÿ‡งUnited Kingdom alexpott ๐Ÿ‡ช๐Ÿ‡บ๐ŸŒ

    @johnv I' ve tried the steps to reproduce and it does not happen for me with the address module. I've got a some questions about the steps to reproduce:

    • Is it with the Standard install profile?
    • What is the contrib field module you are using?
    • Are there any other contrib modules installed?
  • ๐Ÿ‡ณ๐Ÿ‡ฑNetherlands johnv

    @alexpott, please check attached patch for some test instructions.

    Test by:
    - Install with normal install profile.
    - Enable locale module 'User interface translation' with +1 languages.
    - Enable office_hours module and add field to a Content type.
    - In Field settings, Allow both Exceptions and Seasons.
    - Select widget type 'Office Hours (week) with exceptions and seasons'.
    - Edit with non-English page, e.g., /nl/node/8/edit .
    - Enable both Exceptions and Season in widget settings.
    - Create/Edit node with non-English page, e.g., /nl/node/8/edit .
    - Click 'Add Exception' button. (You may need to click twice.)
    - Check if an empty exception is added, or error occurs.
    Set breakpoint at OfficeHoursSeason~label() and OfficeHoursSeasonHeader~process().
    @see https://www.drupal.org/project/office_hours/issues/3399054 ๐Ÿ› Ajax error on [Add exception] button if "seasons" is activated Active

    You can provoke the error by switching between the following return values in OfficeHoursSeason~label():
    - return $this->t($this->name);
    - return t($this->name);
    - return $this->name;
    The first one will generate the error.

    (IMO in previous Drupal versions, bootstrap::t() and $this->t() return different classes. I might be mistaken, because in my current D10.2 dev version, both return TranslatableMarkup, only created with different parameters. I never understood why there was/is a difference. )

  • ๐Ÿ‡ณ๐Ÿ‡ฑNetherlands johnv

    @alexpott, please ignore the file in #43. It is too long. See newly attached file.

  • ๐Ÿ‡น๐Ÿ‡ญThailand AlfTheCat

    Having the same issue on 10.3.9, on image fields in my case.

    I tried the patch from #39 but it doesn't apply:

    sudo -u www-data patch -p1 < core_2987548-39_serialize.patch
    patch unexpectedly ends in middle of line
    patch: **** Only garbage was found in the patch input.
  • Tested.
    Interestingly enough, the 3-year patch (#15) worked for Drupal11 (v 11.1.5)
    #39 and #44 didn't apply.

    This error is now gone and after patch #15 I can delete referenced entities without errors

    LogicException: The database connection is not serializable. This probably means you are serializing an object that has an indirect reference to the database connection. Adjust your code so that is not necessary. Alternatively, look at DependencySerializationTrait as a temporary solution. in Drupal\Core\Database\Connection->__sleep() (line 1297 of /home/pearls/public_html/d11site/web/core/lib/Drupal/Core/Database/Connection.php)
    
  • ๐Ÿ‡จ๐Ÿ‡ฆCanada hommesreponse

    @samlerner Did you ever get this figured out? I have the Agreement module installed also and have tried #15 with no success. #39 also gave me this when trying to apply:

    sudo -u www-data patch -p1 < core_2987548-39_serialize.patch
    patch unexpectedly ends in middle of line
    patch: **** Only garbage was found in the patch input. 
  • ๐Ÿ‡บ๐Ÿ‡ธUnited States SamLerner

    @hommesreponse I'm not entirely sure how, but the problem seems to be gone. I can't find those errors in our logs for the last 3 months, and I applied the patch in #15 back in 2023. We're on Drupal 10.4.6, maybe the problem was fixed elsewhere?

  • ๐Ÿ‡ฌ๐Ÿ‡งUnited Kingdom rakesh.gectcr Manchester

    I'm still encountering the following error on the 11.x branch:

    LogicException: The database connection is not serializable. This probably means you are serializing an object that has an indirect reference to the database connection. Adjust your code so that is not necessary. Alternatively, look at DependencySerializationTrait as a temporary solution. in Drupal\Core\Database\Connection->__sleep() (line 1309 of /var/www/html/core/lib/Drupal/Core/Database/Connection.php).
    

    I've also re-rolled the patch from #15 to apply cleanly against the 11.x branch.

  • ๐Ÿ‡ซ๐Ÿ‡ทFrance lazzyvn paris

    @rakesh.gectcr thanks you save my day.
    I confirm patch #49 fixed this issue

  • ๐Ÿ‡น๐Ÿ‡ทTurkey orkut murat yฤฑlmaz Istanbul

    @rakesh.gectcr, thanks for the patch. I can confirm that, patch #49 can fix this issue too.

  • ๐Ÿ‡ต๐Ÿ‡นPortugal jrochate

    I'm having the same problem on Drupal 11.2 and #49 solved it.

    Anyway, the solution doesn't look definitive.

  • ๐Ÿ‡ฌ๐Ÿ‡งUnited Kingdom alexpott ๐Ÿ‡ช๐Ÿ‡บ๐ŸŒ

    I've managed to reproduce this issue reliably with Drupal 11.2.0.

    1. Install standard Drupal in French
    2. Edit the admin/content view
    3. Change a field name for example the actions field

    You will get an ajax error and if you check the logs you will see:

     46   21/Jun 20:34   php      Erreur        LogicException: The database connection is not serializable. This probably means you are serializing an object that has an indirect reference to the database
                                                 connection. Adjust your code s
    
  • Merge request !12440Fix serialization issue โ†’ (Closed) created by alexpott
  • ๐Ÿ‡ฌ๐Ÿ‡งUnited Kingdom alexpott ๐Ÿ‡ช๐Ÿ‡บ๐ŸŒ

    Now that core itself can trigger this bug it is a critical.

    We just need a test of serializing \Drupal\locale\LocaleTranslation ... will work on adding that.

  • ๐Ÿ‡ฌ๐Ÿ‡งUnited Kingdom alexpott ๐Ÿ‡ช๐Ÿ‡บ๐ŸŒ

    Tagging because this now covers a regression in 11.2.0

  • Pipeline finished with Success
    20 days ago
    #528170
  • Pipeline finished with Canceled
    20 days ago
    Total: 346s
    #528191
  • ๐Ÿ‡ฌ๐Ÿ‡งUnited Kingdom alexpott ๐Ÿ‡ช๐Ÿ‡บ๐ŸŒ

    I've added a test - well updated the existing \Drupal\Tests\locale\Kernel\LocaleTranslationTest::testSerializable() to test this problem. We're unlucky #3128389: LocaleTranslation is not serializable โ†’ did not catch this.

  • ๐Ÿ‡ฌ๐Ÿ‡งUnited Kingdom alexpott ๐Ÿ‡ช๐Ÿ‡บ๐ŸŒ
  • Pipeline finished with Success
    20 days ago
    #528195
  • ๐Ÿ‡บ๐Ÿ‡ธUnited States xjm

    Test-only pipeline indeed throws the exception folks have been reporting all this time:

    There was 1 error:
    1) Drupal\Tests\locale\Kernel\LocaleTranslationTest::testSerializable
    LogicException: The database connection is not serializable. This probably means you are serializing an object that has an indirect reference to the database connection. Adjust your code so that is not necessary. Alternatively, look at DependencySerializationTrait as a temporary solution.
    /builds/issue/drupal-2987548/core/lib/Drupal/Core/Database/Connection.php:1309
    /builds/issue/drupal-2987548/core/modules/locale/tests/src/Kernel/LocaleTranslationTest.php:49
    ERRORS!
  • ๐Ÿ‡ฌ๐Ÿ‡งUnited Kingdom alexpott ๐Ÿ‡ช๐Ÿ‡บ๐ŸŒ

    Crediting @alezu for ๐Ÿ› "The database connection is not serializable" error on views configuration save Active as this duplicate help find a way to reproduce this issue.

  • Pipeline finished with Success
    20 days ago
    Total: 1207s
    #528214
  • ๐Ÿ‡บ๐Ÿ‡ธUnited States xjm

    It's really great to have identified the actual root cause of this after so much time -- thanks @alexpott!

    Could some of the folks encountering the latest version of this in production on 11.2.0 manually test and confirm that the above fixes the issue? If it's helpful, here's a patch version of the merge request:
    https://git.drupalcode.org/project/drupal/-/merge_requests/12440.diff

  • ๐Ÿ‡บ๐Ÿ‡ธUnited States xjm

    Hiding outdated patch files for clarity.

  • ๐Ÿ‡ต๐Ÿ‡นPortugal jrochate

    Hi @xjm.

    Like reported above, I had this error appearing and needed to patch with #49.

    But now I have removed the patch and applied the MR!12440 and it works as expected.
    I'm not having the error on the operations I was having before.

    Thanks you @all for the effort is solving this.

  • ๐Ÿ‡บ๐Ÿ‡ธUnited States xjm

    OK great, thanks @jrochate for testing!

  • ๐Ÿ‡บ๐Ÿ‡ธUnited States nicxvan

    Ran test only to confirm and it fails with a relevant error.

  • ๐Ÿ‡ง๐Ÿ‡ชBelgium gillesbailleux La Roche-en-Ardenne

    Do core maintainers plan a D11.2.1 release in a near future?

  • ๐Ÿ‡ฌ๐Ÿ‡งUnited Kingdom alexpott ๐Ÿ‡ช๐Ÿ‡บ๐ŸŒ

    @gillesbailleux yes we are planning to do a release once this makes it to 11.2.x and a couple of other critical regressions we've found.

    • larowlan โ†’ committed 72642535 on 11.2.x
      Issue #2987548 by alexpott, johnv, euphoric_mv, HbtTundar, cilefen, xjm...
    • larowlan โ†’ committed 743f5aa2 on 11.x
      Issue #2987548 by alexpott, johnv, euphoric_mv, HbtTundar, cilefen, xjm...
  • ๐Ÿ‡ฆ๐Ÿ‡บAustralia larowlan ๐Ÿ‡ฆ๐Ÿ‡บ๐Ÿ.au GMT+10

    Committed to 11.x and backported to 11.2.x

    Thanks folks.

  • ๐Ÿ‡ฌ๐Ÿ‡งUnited Kingdom alexpott ๐Ÿ‡ช๐Ÿ‡บ๐ŸŒ

    Given this is an old bug and can easily affect contrib and is not that often tested for (ie. test coverage of module not in the default language is probably pretty thing on the ground) - I think we should backport this fix to 10.5.x and 10.6.x

  • ๐Ÿ‡ฌ๐Ÿ‡งUnited Kingdom alexpott ๐Ÿ‡ช๐Ÿ‡บ๐ŸŒ

    The cherry pick to 10.5.x is clean and the test passes.

  • ๐Ÿ‡ฌ๐Ÿ‡งUnited Kingdom catch

    Yeah makes sense to backport this one to 10.5.x too. Cherry-picked to both 10.x branches.

  • ๐Ÿ‡ฎ๐Ÿ‡นItaly arturopanetta Grotteria (RC)

    After upgrading to Drupal 11.2.0 Views returns the following error in the browser console:

    "\nSi รจ verificato un errore HTTP in AJAX.\nCodice HTTP di risposta: 500\nDebugging information follows.\nPercorso: /admin/structure/views/ajax/display/tassonomia_ambito/block_1/title\nStatusText: error\nResponseText: The website encountered an unexpected error. Try again later."

    Also, in the php logs I see this error:

    LogicException: The database connection is not serializable. This probably means you are serializing an object that has an indirect reference to the database connection. Adjust your code so that is not necessary. Alternatively, look at DependencySerializationTrait as a temporary solution. in Drupal\Core\Database\Connection->__sleep() (line 1309 of /opt/drupal/web/core/lib/Drupal/Core/Database/Connection.php).

    I have tested several patches, the #72 (https://git.drupalcode.org/project/drupal/-/merge_requests/12440.patch) works, views does not return any more error.

  • ๐Ÿ‡ฌ๐Ÿ‡งUnited Kingdom alexpott ๐Ÿ‡ช๐Ÿ‡บ๐ŸŒ

    For some reason #78 made changes to the issue summary so I reverted it back to the state before that comment.

  • Automatically closed - issue fixed for 2 weeks with no activity.

Production build 0.71.5 2024