Text not null default ошибка

I cannot create a table with the SQL instructions below

I’ve tried to modify some de fault values but I have the same error.

DROP TABLE IF EXISTS CountryLanguage;
CREATE TABLE CountryLanguage (
  CountryCode TEXT NOT NULL DEFAULT '',
  Lang TEXT NOT NULL DEFAULT '',
  IsOfficial INTEGER NOT NULL DEFAULT '0',
  Percentage NUMBER NOT NULL default '0.0',
  PRIMARY KEY  (CountryCode,Lang)
);

Table is not created and I have the message below:

Static analysis:

1 errors found during the scan.

Data type not recognized. (near "NUMBER" in position 164)

SQL request: CREATE TABLE CountryLanguage ( CountryCode TEXT NOT NULL DEFAULT '', Lang TEXT NOT NULL DEFAULT '', IsOfficial INTEGER NOT NULL DEFAULT '0', Percentage NUMBER NOT NULL default '0.0', PRIMARY KEY (CountryCode,Lang) )

MySQL replied: Documentation
# 1064 - Syntax error near 'NUMBER NOT NULL default' 0.0 ',
   PRIMARY KEY (CountryCode, Lang)
) 'at line 5

Problem Description:

I have migration:

lass ChangeDefaultValueBodyForBlogPosts < ActiveRecord::Migration
  def up
    change_column :blog_posts, :body, :text, :null => false
    change_column :comments, :text, :text, :null => false
  end

  def down
    change_column :comments, :text, :text, :default => nil
    change_column :blog_posts, :body, :text, :default => nil
  end
end

rake db:migrate display error:

Mysql2::Error: BLOB, TEXT, GEOMETRY or JSON column ‘body’ can’t have a default value: ALTER TABLE blog_posts CHANGE body body text DEFAULT ” NOT NULL/home/user/projects/projectname/db/migrate/20120508203410_change_default_value_body_for_blog_posts.rb:3:in `up’

I use ubuntu 16.04,

mysql server 5.7(Version: 5.7.12-0ubuntu1.1
Version: 5.7.12-0ubuntu1
Version: 5.7.11-0ubuntu6
)

I looked in google, solving this issue need change

sql-mode=”STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION”

to

sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

But my.conf file is empty.

#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
# 
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

#
# * IMPORTANT: Additional settings that can override those from this file!
#   The files must end with '.cnf', otherwise they'll be ignored.
#

!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/

How solve this issue, please help. Thank you.

Solution – 1

I found solution:
Need add in my.cnf

[mysqld]
sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Solution – 2

You need to find the correct my.cnf:

sudo find / -name "*.cnf"

/etc/mysql/mysql.conf.d/mysqld.cnf
/etc/mysql/my.cnf
/etc/mysql/mysql.cnf
/etc/mysql/conf.d/mysqldump.cnf
/etc/mysql/conf.d/mysql.cnf

I edited /etc/mysql/mysql.conf.d/mysqld.cnf based on

strace mysql ";" 2>&1  | grep cnf

stat("/etc/my.cnf", 0x7ffda9472660)     = -1 ENOENT (No such file or directory)
stat("/etc/mysql/my.cnf", {st_mode=S_IFREG|0644, st_size=683, ...}) = 0
open("/etc/mysql/my.cnf", O_RDONLY)     = 3
stat("/etc/mysql/conf.d/mysql.cnf", {st_mode=S_IFREG|0644, st_size=8, ...}) = 0
open("/etc/mysql/conf.d/mysql.cnf", O_RDONLY) = 4
stat("/etc/mysql/conf.d/mysqldump.cnf", {st_mode=S_IFREG|0644, st_size=55, ...}) = 0
open("/etc/mysql/conf.d/mysqldump.cnf", O_RDONLY) = 4
stat("/etc/mysql/mysql.conf.d/mysqld.cnf", {st_mode=S_IFREG|0644, st_size=3034, ...}) = 0
open("/etc/mysql/mysql.conf.d/mysqld.cnf", O_RDONLY) = 4
stat("/etc/mysql/mysql.conf.d/mysqld_safe_syslog.cnf", {st_mode=S_IFREG|0644, st_size=21, ...}) = 0
open("/etc/mysql/mysql.conf.d/mysqld_safe_syslog.cnf", O_RDONLY) = 4
stat("/root/.my.cnf", 0x7ffda9472660)   = -1 ENOENT (No such file or directory)
stat("/root/.mylogin.cnf", 0x7ffda9472660) = -1 ENOENT (No such file or directory)

Once you find the correct file add sql-mode=”NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION” below [mysqld] statement

Solution – 3

I had no problems with migrating on my local machine using mysql from xampp. Only on the production server it started failing. I figured out that xampp runs mariadb instead of plain mysql. So using mariaDB on the server fixed my problems.

Solution – 4

Check your sql code again error clearly said above ‘body’ not a default value

Example :

 `completed` text NOT NULL  DEFAULT 'false',

After remove Default value

`completed` text NOT NULL,

Now hopefully your error is gone.
and sorry for my english.

Solution – 5

I solved this problem this way: I once wanted to export my mySql database on a server and import it in another server (CPanel host). phpMyAdmin kept giving this error on one of the fields of one of database tables each time I tried. I then went to my source host; opened phpMyAdmin and opened that table structure and removed default value for that field. Then I exported again and this time it worked.

Solution – 6

Starting from MySQL 8.0.13, it is now possible to have a default value for TEXT/BLOB field. However, literal default needs to be specified as an expression.

For example, this is valid:

`title` text COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT ('Title')

But this will produce an error:

`title` text COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'Title'


Ошибки базы данных -поля отличаются

Ошибки базы данных -поля отличаются

28.12.2016

На одном действующем Битрикс сайте выдает ошибки БД — поля отличаются подробности в журнале.
Журнал:
———————————————
В таблице b_ticket поле TITLE «text NOT NULL » не соответствует описанию на диске «varchar(255) NOT NULL »
В таблице b_ticket поле OWNER_SID «text NULL DEFAULT NULL » не соответствует описанию на диске «varchar(255) NULL DEFAULT NULL »
В таблице b_ticket поле LAST_MESSAGE_SID «text NULL DEFAULT NULL » не соответствует описанию на диске «varchar(255) NULL DEFAULT NULL »
В таблице b_ticket поле SUPPORT_COMMENTS «text NULL DEFAULT NULL » не соответствует описанию на диске «varchar(255) NULL DEFAULT NULL »
В таблице b_search_content_stem поле STEM «varchar(50) NOT NULL » не соответствует описанию на диске «int(11) NOT NULL »
В таблице b_search_content_freq поле STEM «varchar(50) NOT NULL DEFAULT «» » не соответствует описанию на диске «int(11) NOT NULL DEFAULT «0» »
ALT ER TABLE `b_ticket` MODIFY `TITLE` varchar(255) NOT NULL ;
ALT ER TABLE `b_ticket` MODIFY `OWNER_SID` varchar(255) NULL DEFAULT NULL ;
ALT ER TABLE `b_ticket` MODIFY `LAST_MESSAGE_SID` varchar(255) NULL DEFAULT NULL ;
ALT ER TABLE `b_ticket` MODIFY `SUPPORT_COMMENTS` varchar(255) NULL DEFAULT NULL ;
ALT ER TABLE `b_search_content_stem` MODIFY `STEM` int(11) NOT NULL ;
ALT ER TABLE `b_search_content_freq` MODIFY `STEM` int(11) NOT NULL DEFAULT «0» ;

Способы решения

Автоматическое исправление не решает проблемы.  Нужно перейти в sql-строку (Настройки > Инструменты > SQL запрос) и там выполнить запрос:
ALTER TABLE `b_ticket` MODIFY `TITLE` varchar(255) NOT NULL ;
ALTER TABLE `b_ticket` MODIFY `OWNER_SID` varchar(255) NULL DEFAULT NULL ;
ALTER TABLE `b_ticket` MODIFY `LAST_MESSAGE_SID` varchar(255) NULL DEFAULT NULL ;
ALTER TABLE `b_ticket` MODIFY `SUPPORT_COMMENTS` varchar(255) NULL DEFAULT NULL ;

После этого нужно переустановить (удалить и снова установить) модуль поиска без сохранения таблиц (Настройки-Настройки продукта-Модули).

Затем нужно выполнить полную переиндексацию. Для этого в административной части сайта перейти в «Настройки > Поиск > Переиндексация». Снять галочку «Переиндексировать только измененные», установить шаг, например, 10 секунд и нажать кнопку «Переиндексировать».

Ещё статьи:

12.05.2023
Битрикс убрал тип поля «Привязка к карте Яндекс»
В новых обновлениях Битрикс убрал тип поля «Привязка к карте Яндекс».
ID: 455

18.01.2023
Нюансы перехода битрикс на РНР 8.0
С февраля битрикс прекращает поддерживать РНР 7.4 и в битрикс сегменте сайтов начался переход на РНР 8 для получения обновлений.
Но без нюансов и ошибок…
ID: 431

10.01.2023
БУС окончательно всё?
Появилась информация от битрикс, что грубо говоря поддержка по отраслевому медицинскому решению от битрикс будет до 1 февраля 2024 года, а что потом б…
ID: 426

Новые статьи в блоге:

Возврат к списку

  1. Offline

    Georgios

    Недавно здесь

    Регистрация:
    05.02.2011
    Сообщения:
    5
    Симпатии:
    0
    Пол:
    Мужской

    Доброго времени суток!

    При переносе базы на сервер столкнулся в такой ошибкой:

    хотя в моем SQL-запросе вот так:Заранее спасибо!

  2. woojin

    Offline

    woojin

    Местный
    Команда форума
    => Cпециалист <=

    Регистрация:
    31.05.2009
    Сообщения:
    3 206
    Симпатии:
    334
    Пол:
    Мужской

    а почему ссылка идёт на третью строку твоего запроса:

    найди свой SQL файл с таблицами и сравни с оригинальной таблицей banners

    1. CREATE TABLE `#__banner` (
    2.   `bid` int(11) NOT NULL auto_increment,
    3.   `cid` int(11) NOT NULL default ‘0’,
    4.   `type` varchar(30) NOT NULL default ‘banner’,
    5.   `name` varchar(255) NOT NULL default »,
    6.   `alias` varchar(255) NOT NULL default »,
    7.   `imptotal` int(11) NOT NULL default ‘0’,
    8.   `impmade` int(11) NOT NULL default ‘0’,
    9.   `clicks` int(11) NOT NULL default ‘0’,
    10.   `imageurl` varchar(100) NOT NULL default »,
    11.   `clickurl` varchar(200) NOT NULL default »,
    12.   `date` datetime default NULL,
    13.   `showBanner` tinyint(1) NOT NULL default ‘0’,
    14.   `checked_out` tinyint(1) NOT NULL default ‘0’,
    15.   `checked_out_time` datetime NOT NULL default ‘0000-00-00 00:00:00’,
    16.   `editor` varchar(50) default NULL,
    17.   `catid` INTEGER UNSIGNED NOT NULL DEFAULT 0,
    18.   `description` TEXT NOT NULL DEFAULT »,
    19.   `sticky` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
    20.   `ordering` INTEGER NOT NULL DEFAULT 0,
    21.   `publish_up` datetime NOT NULL default ‘0000-00-00 00:00:00’,
    22.   `publish_down` datetime NOT NULL default ‘0000-00-00 00:00:00’,
    23.   `tags` TEXT NOT NULL DEFAULT »,
    24.   `params` TEXT NOT NULL DEFAULT »,
    25.   KEY `viewbanner` (`showBanner`),
    26.   INDEX `idx_banner_catid`(`catid`)
    27. ) TYPE=MyISAM CHARACTER SET `utf8`;
  3. Offline

    Georgios

    Недавно здесь

    Регистрация:
    05.02.2011
    Сообщения:
    5
    Симпатии:
    0
    Пол:
    Мужской

    а что там можно сравнить? посмотрел вроде, ничего подозрительного…

    меня смущают те слэши которые добавляются в запрос

    1. `type` varchar(30) NOT NULL default ‘banner’,

    становится

    1. `type` varchar(30) NOT NULL default ‘banner’,

    P.S. Еще пишет вот такое:

    Последнее редактирование: 06.02.2011

  4. woojin

    Offline

    woojin

    Местный
    Команда форума
    => Cпециалист <=

    Регистрация:
    31.05.2009
    Сообщения:
    3 206
    Симпатии:
    334
    Пол:
    Мужской

    это экранирование, сделай любой запрос в phpMyAdmin а потом нажми на «PHP код запроса» и увидишь сколько там слешей будет
    к томуже у тебя ошибка то не в той сроке ule у тебя слеши прописаны, а в этой

  5. Offline

    Georgios

    Недавно здесь

    Регистрация:
    05.02.2011
    Сообщения:
    5
    Симпатии:
    0
    Пол:
    Мужской

    а попробывал удалить строку «name», он стал ругаться на следующую :(

  6. woojin

    Offline

    woojin

    Местный
    Команда форума
    => Cпециалист <=

    Регистрация:
    31.05.2009
    Сообщения:
    3 206
    Симпатии:
    334
    Пол:
    Мужской

    кинь вложением свой SQL файл

  7. Offline

    Georgios

    Недавно здесь

    Регистрация:
    05.02.2011
    Сообщения:
    5
    Симпатии:
    0
    Пол:
    Мужской

    вот файл, но я пробовал даже путем вставки запроса одной таблицы…

    Вложения:

  8. woojin

    Offline

    woojin

    Местный
    Команда форума
    => Cпециалист <=

    Регистрация:
    31.05.2009
    Сообщения:
    3 206
    Симпатии:
    334
    Пол:
    Мужской

    в phpMyAdmin вставил твой дамп
    вот ответ: SQL-запрос был успешно выполнен ( запрос занял 0.1529 сек. )

    и вообще как ты этот дамп в БД вносишь?

  9. Offline

    Georgios

    Недавно здесь

    Регистрация:
    05.02.2011
    Сообщения:
    5
    Симпатии:
    0
    Пол:
    Мужской

    вставкой самого кода…

    Сейчас при помощи импорта файла сделал… ВСЕ ПОЛУЧИЛОСЬ!!!
    СПАСИБО, woojin

  10. woojin

    Offline

    woojin

    Местный
    Команда форума
    => Cпециалист <=

    Регистрация:
    31.05.2009
    Сообщения:
    3 206
    Симпатии:
    334
    Пол:
    Мужской

    было бы за что :spiteful:

Поделиться этой страницей


Форумы Joomla! CMS

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Open

karibertils opened this issue

May 8, 2019

· 14 comments

Comments

@karibertils

I like to avoid nullable fields so i don’t also need to check for the null case every time in type safe languages.

But i often need to add new (non nullable) text field to existing table with data. I want the field to be initialized as empty string for the existing rows.

I have been doing this by adding any text string as the default value and then changing it to empty string. But would be better if you could specify empty string as the default value.

@elitan

Same issue here. I added the column via SQL instead.

ALTER TABLE "users" ADD COLUMN "name" text NOT NULL DEFAULT '';

@rikinsk-zz
rikinsk-zz

added

c/console

Related to console

e/easy

can be wrapped up in a couple of days

p/medium

non-urgent issues/features that are candidates for being included in one of the upcoming sprints

and removed

c/server

Related to server

labels

Aug 22, 2019

@rikinsk-zz

This can be fixed by changing the way console accepts default string values. The following options seem possible:

  • we can make string values need to be explicitly surrounded by 's to avoid confusion and allow same flexibility as SQL
    • issue: unintuitive
    • issue: if quotes are missed, the error msg by PG is very unhelpful
  • we treat '' as a special input for empty string
    • issue: how to set default value to the string ''
    • issue: how does user know '' means empty string without just trying it out

Any other suggestions would be welcome as well

Also, extending this issue to also allow setting a default value with 's in them which currently is not possible

@rikinsk-zz
rikinsk-zz

added

p/high

candidate for being included in the upcoming sprint

and removed

p/medium

non-urgent issues/features that are candidates for being included in one of the upcoming sprints

labels

Aug 22, 2019

@elitan

What is the problem to do the following?

  • if default value text box is empty, the default value will be empty (i.e '').

@rikinsk-zz

@elitan in that case it would not be possible to not set a default value. We’ll then need to add a checkbox to mark that a default has to be set (that’s what adminer does).

It is definitely another valid option for sure.

@elitan

Here is some inspiration from how phpmyadmin handles it:

image


image


image

Very intuitive I think.

@aerskine

Use trim('') or format('') as the default value in the UI — either are easily recognizable as string functions.

@franciscolourenco

@aerskine this is not currently support right?

@fpieper

Similiar to @elitan’s workaround, it is also possible to modify an already existing column:

ALTER TABLE persons ALTER COLUMN first_name SET DEFAULT '';

It is correctly detected in the Hasura Console afterwards.

@aerskine

@franciscolourenco No not supported directly from UI, only via SQL — but @fpieper or @elitan have a better approach, I didn’t realize when I posted that '' would be correctly displayed in Console

@namesphill

Why not simply: if the default value is surrounded by either » or ‘, remove them and take whatever’s between, which could be an empty string.
Anyone who tries to set an empty string default value will certainly first try «» or ».

@serudda

Screen Shot 2020-06-04 at 9 13 19 AM

it would be a beautiful and very useful approach.

@binaryme

it would be a beautiful and very useful approach.

For if someone is as noob as I was when applied @fpieper workaround.

Here is the documentation for sending post values to hasura:
https://hasura.io/docs/1.0/graphql/manual/api-reference/schema-metadata-api/run-sql.html

Ran my post with postman and it worked perfectly, had to send headers
Content-Type: application/json
x-hasura-admin-secret: **** (my admin secret)

and body raw:

{
    "type": "run_sql",
    "args": {
        "sql": "ALTER TABLE properties ALTER COLUMN colonia SET DEFAULT '';"
    }
}

@fpieper

@binaryme I am not sure if you needed to run the query from a client or programmatically, but you can easily run the query from the Hasura Console (under Data / SQL (last point in the left sidebar)).

That’s the way I applied my query :)

atb00ker

added a commit
to atb00ker/graphql-engine
that referenced
this issue

Aug 24, 2021

@atb00ker

atb00ker

added a commit
to atb00ker/graphql-engine
that referenced
this issue

Aug 24, 2021

@atb00ker

atb00ker

added a commit
to atb00ker/graphql-engine
that referenced
this issue

Aug 24, 2021

@atb00ker

atb00ker

added a commit
to atb00ker/graphql-engine
that referenced
this issue

Aug 24, 2021

@atb00ker

@atb00ker

Hi folks,

I got the ball rolling for this one at #7452

fhas

Implemented the solution suggested by @elitan and @sruda, what do you think about this solution @rikinsk ?

P.S: Another hack for now, if you are using PostgreSQL, just typing value ''::text will get the same thing done! 😄

atb00ker

added a commit
to atb00ker/graphql-engine
that referenced
this issue

Aug 24, 2021

@atb00ker

atb00ker

added a commit
to atb00ker/graphql-engine
that referenced
this issue

Aug 29, 2021

@atb00ker

atb00ker

added a commit
to atb00ker/graphql-engine
that referenced
this issue

Aug 29, 2021

@atb00ker

atb00ker

added a commit
to atb00ker/graphql-engine
that referenced
this issue

Aug 29, 2021

@atb00ker

atb00ker

added a commit
to atb00ker/graphql-engine
that referenced
this issue

Aug 29, 2021

@atb00ker

atb00ker

added a commit
to atb00ker/graphql-engine
that referenced
this issue

Aug 29, 2021

@atb00ker

Понравилась статья? Поделить с друзьями:
  • Text file busy linux ошибка
  • Terraria error ошибка при запуске что делать
  • Terrain response range rover ошибка
  • Terrain response freelander 2 ошибка
  • Termokraft pk 24bt ошибка е7