Score:0

Creating user programmatically fails with Postgres

cn flag

Anyone know what's wrong here? After the D8->D9 upgrade, a stupidly simple piece of code is not working, has there been a change? It worked before.

$params = [
  'name' => $username,
  'pass' => $password,
  'mail' => $email,
  'init' => $email,
];

$user = $this->users->create($params);

$user->enforceIsNew();
$user->save();

In D8 this was fine, in D9 I'm getting:

Drupal\Core\Entity\EntityStorageException: SQLSTATE[23502]: Not null violation: 7 ERROR:  null value in column "uid" of relation "drupal_users" violates not-null constraint
DETAIL:  Failing row contains (null, 740f7084-de66-4572-8ec7-049376cf5a33, en).: INSERT INTO "drupal_users" ("uuid", "langcode") VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1);

Research tells me that there was a change from D8 to D9.5 where the UID field is now a serial field instead of an integer using the sequence API.

In Postgres, you either omit the serial field, or use "DEFAULT".

The UID field is not being omitted but it's set to NULL. If I try to force it to be DEFAULT it gets type-cast to 0 (zero) and we get the UID already exists error.

How on earth can I create this user programmatically?

id flag
Can you compare the users table schema against that of a fresh install to be sure this isn’t just a missed update?
id flag
You are referring to https://www.drupal.org/node/838992. It would be good to include that research link in the question.
id flag
What object is `$this->users`?
apaderno avatar
us flag
There is no need to call `enforceIsNew()` as that is already done from the entity storage. I hope `$this->users` contains an entity storage instance for the User entity.
cn flag
$this->users is the user entity storage - looks like it might be a missed update on the test site. But must be okay on production because that's not generating any issues, (Ha, I'd soon hear about it if it was.)
Score:0
cn flag

It turned out that there was a database update that hadn't been run on the test site, the one that switched the users.UID column to being serial, instead of int.

Score:-1
mu flag

Instead of explicitly setting the "uid" value in your code, you can let the database handle it by omitting it from the $params array.

id flag
They are not specifying the uid.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.