Error 23502 null value in column

Your Question Gorm v1.21.13 Apologies if something basic, but I'm stumped. A simple query like this stopping working for me recently: INSERT INTO "example" ("uid","name...

Comments

@ivanakimov

Your Question

Gorm v1.21.13

Apologies if something basic, but I’m stumped. A simple query like this stopping working for me recently:

INSERT INTO "example" ("uid","name","slug","website","updated_at","created_at") VALUES ('c4fenn594816lfvs44t0','t1629416412','t1629416412','',1629416412,1629416412) RETURNING "example_id"

I get the following error now:

ERROR: null value in column "website" of relation "example" violates not-null constraint (SQLSTATE 23502)

It’s an empty string, not a null.

The table looks like this:

create table if not exists example (
  example_id bigserial primary key,
  uid varchar(20) default '' not null,
  name varchar(255) default '' not null,
  slug varchar(500) default '' not null,
  website varchar(1000) default '' not null,
  updated_at bigint default 0 not null,
  created_at bigint default 0 not null,
  unique (uid),
  unique (name),
  unique (slug)
);

The struct does not have any gorm tag on the Website column.

The document you expected this should be explained

Expected answer

The weird thing is if I copy and paste that query manually into Postgres, the query executes just fine.

Am I missing some gorm tag on the struct? Seems like this was working fine without any tags at the beginning of the project.

@ivanakimov

After a bit of poking around, it seems that if I remove PreferSimpleProtocol: true then it starts working.

Any insight as to how to fix without removing this setting would be great.

@ivanakimov
ivanakimov

changed the title
ERROR: null value in column «X» of relation «Y» violates not-null constraint (SQLSTATE 23502)

ERROR: null value violates not-null constraint (SQLSTATE 23502) when using PreferSimpleProtocol: true

Aug 20, 2021

@ivanakimov
ivanakimov

changed the title
ERROR: null value violates not-null constraint (SQLSTATE 23502) when using PreferSimpleProtocol: true

ERROR (SQLSTATE 23502): null value violates not-null constraint when using PreferSimpleProtocol: true

Aug 20, 2021

@Akaame

This is surely super weird.

Struct I have

type Schema struct {
	gorm.Model
	Name    string `gorm:"column:name;uniqueIndex;type:varchar(45);NOT NULL"`
	Memo    string `gorm:"column:memo;type:text;NOT NULL"`
	Website string
}

I added not null constraint on the db and here it goes:

image

The field having a gorm tag did not matter for me. It is working with an empty string

I added a large char field with default value to replicate your column but still it works:

image

Quoting PreferSimpleProtocol from pgx

// PreferSimpleProtocol disables implicit prepared statement usage. By default pgx automatically uses the extended
// protocol. This can improve performance due to being able to use the binary format. It also does not rely on client
// side parameter sanitization. However, it does incur two round-trips per query (unless using a prepared statement)
// and may be incompatible proxies such as PGBouncer. Setting PreferSimpleProtocol causes the simple protocol to be
// used by default. The same functionality can be controlled on a per query basis by setting
// QueryExOptions.SimpleProtocol.

gorm version: v1.21.13
psql version: 13.4

@ivanakimov

@Akaame Thank you for the taking the time to try and reproduce + the screenshots. From my understanding, it looks like it’s hard to reproduce the issue, so let me try to give a more concrete example:

The Postgres table:

create table if not exists examples (
  example_id bigserial primary key,
  test varchar(2038) default '' not null,
  categories integer[],
  updated_at bigint default 0 not null,
  created_at bigint default 0 not null
);

Code to insert one row:

package main

import (
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"strings"
)

func main() {
	db, err := gorm.Open(postgres.New(postgres.Config{
		DSN: strings.Join([]string{
			"host=localhost",
			"dbname=app",        // @TODO
			"user=postgres",     // @TODO
			"password=password", // @TODO
			"port=5432",
			"sslmode=disable",
		}, " "),
		PreferSimpleProtocol: true,
	}), &gorm.Config{
		SkipDefaultTransaction: true,
		PrepareStmt:            false,
		Logger:                 logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		log.Fatal(err)
	}

	type Example struct {
		ExampleID int64   `json:"exampleId" gorm:"primaryKey"`
		Test      *string `json:"test"`
		UpdatedAt int64   `json:"updatedAt" gorm:"autoUpdateTime"`
		CreatedAt int64   `json:"createdAt" gorm:"autoCreateTime"`
	}

	test := ""
	example := Example{
		Test: &test,
	}

	if err := db.Create(&example).Error; err != nil {
		log.Fatal(err)
	}

	log.Println("Done.")
}

My personal go.mod:

module pgtest

go 1.17

require (
	github.com/lib/pq v1.10.2
	gorm.io/driver/postgres v1.1.0
	gorm.io/gorm v1.21.13
)

require (
	github.com/jackc/chunkreader/v2 v2.0.1 // indirect
	github.com/jackc/pgconn v1.10.0 // indirect
	github.com/jackc/pgio v1.0.0 // indirect
	github.com/jackc/pgpassfile v1.0.0 // indirect
	github.com/jackc/pgproto3/v2 v2.1.1 // indirect
	github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
	github.com/jackc/pgtype v1.8.1 // indirect
	github.com/jackc/pgx/v4 v4.13.0 // indirect
	github.com/jinzhu/inflection v1.0.0 // indirect
	github.com/jinzhu/now v1.1.2 // indirect
	golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97 // indirect
	golang.org/x/text v0.3.6 // indirect
)

This is what I get when I try to run the program:

sn

The interesting thing is that if I try to copy and paste the generated SQL manually into Postgres CLI, it works! And if I comment out the line PreferSimpleProtocol: true, then the code also works.

I’m not sure whether the issues is with PreferSimpleProtocol or something else. Maybe someone else can see something else I don’t?


PS: You might’ve noticed that my gorm.Open config settings are somewhat non-standard. I’m simply trying not to use prepared statements so that I can edit Postgres tables manually without having to restart the Golang server in the real project.

@ivanakimov

@jinzhu This started out as a question, but we managed to create a consistent reproducible example (above), which seems like this could be a bug (not sure if in gorm or somewhere down the line). Any chance you could take a look and advise on something?

@Akaame

Hello,

Sorry I was busy with work. I will try to take a look at it sometime today.

Cheers.

Edit: Sorry I thought you were referring to me.

I thought you had problem with PSQL Extended Protocol. But you explicitly want to use the simple protocol to shut down prepared statements completely (Correct me if my reasoning here is false). I think the reason PSQL client is able to execute your query is probably it defaults to Extended Protocol.

I will try and replicate your setup but this hits me more like a driver issue. This territory is quite uncharted for me.

Second edit I replicated you issue on my local.

image

When I change it to test := «a». It works perfectly.

@ivanakimov

@Akaame,

Second edit I replicated you issue on my local … When I change it to test := «a». It works perfectly.

Yep, exactly :(

But you explicitly want to use the simple protocol to shut down prepared statements completely (Correct me if my reasoning here is false).

That’s correct. And to elaborate a bit: I’m not entirely sure what protocol I want/need(?). I tried to disable prepared statements simply because I kept getting an error that the SQL schema has changed and I had to restart the Go server every time (I didn’t want the same issue in production). I’d just like to manually adjust SQL schemas in CLI without having to restart the Go server/connections — and the simplest way to do that seems to be to disable prepared statements(?).

tl&dr: Having a hard time inserting empty strings when prepared statements are disabled.

@ivanakimov

@Akaame, did you get a chance to check it out?

P.S: Are you one of the maintainers or this repo or just helping out? I’m curious cause would be nice to put a «bug» label on the issue, since it seems like one, but I’m not able to apply one.

@Akaame

@Akaame Hello I had some personal matters to attend to. And no I am not a maintainer. I will update here with investigarions if/when I have time.

@github-actions

This issue has been automatically marked as stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 30 days

#database #laravel #postgresql #laravel-8 #rest

Вопрос:

Ниже приведен API для загрузки файлов. это показывает ошибку —

SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "Userid" of relation "files" violates not-null constraintnDETAIL: Failing row contains (7, null, Distance Learning Promo.mp4, null, null, null, 2021-07-07 13:38:07, 2021-07-07 13:38:07). (SQL: insert into "files" ("FileName", "updated_at", "created_at") values (Distance Learning Promo.mp4, 2021-07-07 13:38:07, 2021-07-07 13:38:07) returning "id") .

И Почтальон показывает статус 500 internal status error .

Я не думаю, что моя Userid колонка здесь пуста . Пожалуйста, помогите мне с некоторыми предложениями

Контроллер

 <?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppModelsUploads;
use IlluminateSupportFacadesAuth;

class UploadController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api');
    }
    public function upload(Request $request)
    {
        $file=$request->file('file_name');
        $fileName=$file->getClientOriginalName();

        $folder = uniqid().'-'.now()->timestamp;
        $file->storeAs('public/other-document/'.$folder, $fileName);
       
       $filePath = $folder.'/'.$fileName;
       $dataToInsert = array();
       $dataToInsert['FileName'] = $fileName;
       $dataToInsert['FilePath'] = $filePath;
       if($request->has('uploadType'))
       {
           $dataToInsert['FileType'] = $request->uploadType;
       }
       $dataToInsert['uploadedBy'] = Auth::user()->id;
       $dataToInsert['Userid'] = $request->bearerToken();
       Uploads::create($dataToInsert); 
    }

}
 

Файл миграции

 Schema::create('files', function (Blueprint $table) {
            $table->id();
            $table->string('Userid');
            $table->string('FileName');
            $table->string('FilePath');
            $table->string('FileType');
            $table->integer('uploadedBy');
            $table->timestamps();
        });
 

Комментарии:

1. пожалуйста, проверьте $dataToInsert['Userid'] = $request->bearerToken(); , удерживает ли какое-либо значение

2. @JEJ это имеет значение. даже если Userid в столбец вставлено фиктивное значение ,подобное этому — $dataToInsert['Userid'] =1 , оно показывает ту же ошибку.

Ответ №1:

  $dataToInsert['Userid'] = $request->bearerToken(); // error is here

if(!$dataToInsert['Userid']){
 return "Null value in userID";
}
 

Проверьте $dataToInsert['Userid'] , удерживает ли какое-либо значение.

Также убедитесь, что Вы передаете bearerToken в заголовке

Комментарии:

1. это имеет значение. даже если в столбец Userid также вставлено фиктивное значение- $dataToInsert[‘Идентификатор пользователя’] =1 ,оно показывает ту же ошибку.

2. @MG проверьте свои заполняемые файлы в модели

SergeyIvankov

0 / 0 / 1

Регистрация: 03.04.2016

Сообщений: 71

1

15.10.2017, 16:59. Показов 3401. Ответов 6

Метки нет (Все метки)


Добрый день, подключаю к C# базу Postgresql делаю добавление полей выводит ошибку: «23502: null value in column «IdDepartment» violates not-null constraint»

Мой код:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Npgsql;
 
namespace Kyrsss
{
    public partial class Form1 : Form
    {
        NpgsqlConnection con = new NpgsqlConnection ("Server=localhost;Port=5432;" +
        "User Id=postgres;Password=1qaz;Database=Dean's Office;");
        NpgsqlCommand cmd;
        NpgsqlDataAdapter adapt;
        int iddepartment = 0;
        public Form1()
        {
            InitializeComponent();
            DisplayData();
        }
 
        private void DisplayData()
        {
            con.Open();
            DataTable dt = new DataTable();
            adapt = new NpgsqlDataAdapter("select * from Departments", con);
            adapt.Fill(dt);
            dataGridView1.DataSource = dt;
            con.Close();
        }
        //Clear Data  
        private void ClearData()
        {
            textBox1.Text = "";
            textBox2.Text = "";
            iddepartment = 0;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text != "" && textBox2.Text != "")
            {
                cmd = new NpgsqlCommand("insert into Departments(titledepartment,phonedepartment) values(@title,@phone)", con);
                con.Open();
                cmd.Parameters.AddWithValue("@title", textBox1.Text);
                cmd.Parameters.AddWithValue("@phone", textBox2.Text);
                cmd.ExecuteNonQuery();
                con.Close();
                MessageBox.Show("Record Inserted Successfully");
                DisplayData();
                ClearData();
            }
            else
            {
                MessageBox.Show("Please Provide Details!");
            }
        }
 
        private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
 
            iddepartment = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
            textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
            textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
        }
    }
}

Скриншот прикрепил, подскажите пожалуйста в чем собственно проблема.

Миниатюры

Ошибка: null value in column
 

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

15.10.2017, 16:59

6

359 / 286 / 76

Регистрация: 21.06.2016

Сообщений: 1,115

15.10.2017, 17:05

2

Ну правильно оно всё выводит. Нечего налы сунуть туда где их быть не должно, разбирайтесь с таблицей своей в БД, налы в поле запрещены, а Вы ничего туда не передаёте.



0



0 / 0 / 1

Регистрация: 03.04.2016

Сообщений: 71

15.10.2017, 17:07

 [ТС]

3

Цитата
Сообщение от hoolygan
Посмотреть сообщение

Ну правильно оно всё выводит. Нечего налы сунуть туда где их быть не должно, разбирайтесь с таблицей своей в БД, налы в поле запрещены, а Вы ничего туда не передаёте.

Глянь пожалуйста, вот описание таблицы в БД.

Миниатюры

Ошибка: null value in column
 



0



0 / 0 / 1

Регистрация: 03.04.2016

Сообщений: 71

15.10.2017, 17:39

 [ТС]

4

Так, что нужно сделать, подскажите пожалуйста. Поменять каждому ID тип serial ?



0



1274 / 979 / 137

Регистрация: 01.10.2009

Сообщений: 3,100

Записей в блоге: 1

15.10.2017, 19:56

5

SergeyIvankov, iddepartment null, хотя стоит как not null, и вообще по мне так оно должно быть автоинкрементное, что у Вас скорее всего не сделано



0



0 / 0 / 1

Регистрация: 03.04.2016

Сообщений: 71

15.10.2017, 20:06

 [ТС]

6

Цитата
Сообщение от XIST
Посмотреть сообщение

SergeyIvankov, iddepartment null, хотя стоит как not null, и вообще по мне так оно должно быть автоинкрементное, что у Вас скорее всего не сделано

Сори за глупые вопросы, автоинкрементов нет, тип для первичных ключей брал интеджер. А not null бд выставляло автоматически после того как указывал, что это первичных ключ.
Решением будет изменить всем Idшникам тип данных ?



0



359 / 286 / 76

Регистрация: 21.06.2016

Сообщений: 1,115

15.10.2017, 21:20

7

Ааааа. Это аут.
SergeyIvankov, а ну ка вспоминаем, что такое primary key? И когда вспомним (или хоть раз откроем учебник по БД) попробуем понять, могут ли быть там наловые значения?
Естественно, что программа ругается, ей больше ничего не остается.
В общем, если не хотите отдавать поддержку этой колонки на субд, то будьте добры, указывать значение собственноручно в шарпе ( что не рекомендую для интового поля). Уж лучше тогда guid вписывайте, чтобы не ошибиться с уникальностью.



0



Last updated

9 months ago.

has it been defined as an auto-increment?

You mean, in the laravel project or in the database?
I didn’t define anything beacause the database was already created.

Here is my Registrar class:

class Registrar implements RegistrarContract {

/**
 * Get a validator for an incoming registration request.
 *
 * @param  array  $data
 * @return IlluminateContractsValidationValidator
 */
public function validator(array $data)
{
	return Validator::make($data, [
		'name' => 'required|max:255',
		'password' => 'required|confirmed|min:6',
	]);
}

/**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return User
 */
public function create(array $data)
{
	return User::create([
		'login' => $data['name'],
		'pass' => bcrypt($data['password']),
	]);
}

}

Thank you!

I am feeling so dumb.

This error appeared because i just filled some fields instead of filling all of them in database.

Sorry, and thanks jacksoncharles. :)

Sign in to participate in this thread!

We’d like to thank these
amazing companies

for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.


© 2023 Laravel.io — All rights reserved.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error 235 oem check failed from bios service acer v5 571
  • Error 2336 емиас
  • Error 2330 error getting file attributes
  • Error 233 only secured capsule is allowed on a secureflash system g580
  • Error 279 roblox что это

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии