# Impossibile inserire null in un record PostgreSQL enterprise con valore di default current\_timestamp non null

**URL:** <https://meta.discourse.org/t/unable-to-insert-null-into-a-not-null-default-current-timestamp-record-of-postgresql-enterprise/354557>\
**Category:** Bug\
**Created:** [26 Febbraio 2025, 6:28am UTC](https://meta.discourse.org/t/unable-to-insert-null-into-a-not-null-default-current-timestamp-record-of-postgresql-enterprise/354557 "2025-02-26T06:28:37Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Hiệp\_Nguyễn\_ngoc](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/hi%E1%BB%87p_nguy%E1%BB%85n_ngoc/32/478398_2.png) [@Hiệp\_Nguyễn\_ngoc](https://meta.discourse.org/u/Hi%E1%BB%87p_Nguy%E1%BB%85n_ngoc)\
**Post date:** [26 Febbraio 2025, 6:28am UTC](https://meta.discourse.org/t/unable-to-insert-null-into-a-not-null-default-current-timestamp-record-of-postgresql-enterprise/354557/1 "2025-02-26T06:28:37Z")

</div>

Discourse higher 3.2.0 (v3.3.3,…).  
Sto usando **PostgreSQL 15.3 (EnterpriseDB Advanced Server 15.3.0) su x86\_64-pc-linux-gnu, compilato da gcc (GCC) 8.5.0 20210514 (Red Hat 8.5.0-16), a 64 bit**.  
Quando eseguo `rake db:migrate`, incontro questo errore:

```plaintext
PG::NotNullViolation: ERRORE: valore null nella colonna "first_unread_at" della relazione "user_stats" viola il vincolo not-null (PG::NotNullViolation)
DETAIL: La riga fallita contiene (130, 0, 0, 0, 0, 0, 0, 2025-02-25 03:27:48.934913, null, null, 0, 0, 0, null, 0, 0, 0, null, 0, null, null, null, 0, 0)

```

Ho investigato e ho scoperto che il motivo è che l’applicazione sta cercando di inserire un valore null in un campo che non è null con un **default current\_timestamp**.  
La mia soluzione:

```plaintext
BEGIN;
ALTER TABLE user_stats 
  ALTER COLUMN first_unread_at SET NOT NULL,
  ALTER COLUMN first_unread_at SET DEFAULT NOW();
COMMIT;

BEGIN;
ALTER TABLE user_stats 
  ALTER COLUMN first_unread_pm_at SET NOT NULL,
  ALTER COLUMN first_unread_pm_at SET DEFAULT NOW();
COMMIT;

BEGIN;
ALTER TABLE group_users 
  ALTER COLUMN first_unread_pm_at SET NOT NULL,
  ALTER COLUMN first_unread_pm_at SET DEFAULT NOW();
COMMIT;

```

Ma ci sono molti altri campi che non possono essere inseriti, non sono riuscito a trovarli e correggerli tutti usando questo metodo.

---

<div class="post-metadata">

**Author:** ![sam](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/sam/32/102149_2.png) [@sam](https://meta.discourse.org/u/sam)\
**Post date:** [27 Febbraio 2025, 12:20am UTC](https://meta.discourse.org/t/unable-to-insert-null-into-a-not-null-default-current-timestamp-record-of-postgresql-enterprise/354557/2 "2025-02-27T00:20:16Z")

</div>

Sono confuso, abbiamo impostato il segfault qui:

> <https://github.com/discourse/discourse/blob/fbe5a9c71096dde8d7d59a0b2bec932b22c38a05/db/migrate/20190402024053_add_first_unread_at_to_user_stats.rb#L8-L14>
