Postgresql ошибка ошибочный литерал массива

Human beings are born to make mistakes. Eventually, when you do some code, you also make mistakes that lead you to some errors, i.e., logical, syntax, and technical. Just like any language, a database also comes up with many errors. PostgreSQL database is full of such errors that we get daily. One of those errors is “Malformed Array Literal”. The causes of this error in the PostgreSQL database can be many. We just need to find out all those causes and remove the error. Today, we have decided to cover this article for our users who are unknown to the postgresql database error: malformed array literal. Let’s see how we can encounter and solve it within the PostgreSQL pgAmdin graphical user interface.

Let’s start with the launch of your installed PostgreSQL database by searching it through the search bar of the Windows 10 desktop front screen. On the search bar of your Windows 10 desktop( from the left bottom corner), write “pgAdmin”. The pop-up for application “pgAdmin 4” of the PostgreSQL database will be shown. You have to click on it to open it on your system. It will use 20 to 30 seconds to open itself. On opening, it will show you the dialog box to enter your password for the database server. You have to write the password that you have entered when installing the PostgreSQL database. After adding the database server password, the server is ready for our use. Within the Servers option at the left area of PostgreSQL, expand the databases. Choose the database of your choice to start working on it. We have chosen the database “aqsayasin” from our database server. Now, open the chosen database “query tool” by clicking on the icon of “query tool” from the top taskbar. It will open up the query area to do some tasks through commands in the database.

Example 01:

The very first and most-occurred cause of an error: malformed array literal in PostgreSQL database is to copy the contents of JSON-type column to some array type. Let’s make the situation something like this and resolve it after that. We need a table with a JSON type column to use JSON data. Thus, we have created a new table named “Malformed” in the database “aqsayasin” using the CREATE TABLE command. This table has been created with three different columns. Its first column, “ID” is a simple integer type, and the second column “name” is of text array type. The last column, “info” has been initialized as a “jsonb” data type to store the JSON data in it. Tap on the postgreSQL database “run” button from its taskbar. You will see that the empty table “Malformed” will be created as per the success query output beneath.

Let’s insert some records in the ID and info column of table “Malformed” casting off the INSERT INTO instruction on the query tool. We are not inserting records in the array type column “name”, because we will copy the records of jsonb column “info” to it later. Thus, we have added the JSON data into the “info” column and integer value into the “ID” column. It was quite easy to use the “VALUES” keyword and was successful as per the below output.

To get the malformed array literal error, we must use the wrong query format in the query tool. Thus, we have been using the UPDATE instruction to modify the records of the table “Malformed”. We are using the “SET” keyword to cast the array record “name” as text from the info column to the “name” column, which is empty right now. On running this instruction, we have found that this way of copying JSON data to an array-type column is throwing an error “malformed array literal”. We have to change the format of copying the data so far.

To copy the JSONB column data to some array-type column, we need to utilize the concat function within our UPDATE command. Therefore, we used the UPDATE command to modify the table “Malformed”. The SET keyword assigns the record to column “name” of array type. While assigning, it uses concat and translates function. The translate function will convert the JSON data to array type for the column “info”. After that, the concat function will add up the translated data to one in the form of an array so that it can be saved to the column “name”. The error has been removed on execution, and data has been copied properly.

Let’s display the table “Malformed” data on our pgAdmin GUI screen using the “SELECT” instruction shown below. You can see that the JSON data from column “info” is successfully copied to the array column “name”.

Example 02:

Another way to get this error on your database is using the wrong way to merge two arrays. Thus, we will be using the SELECT ARRAY query to merge the array values 11 and 25 within square brackets to a value in single inverted commas, i.e., 78 separated by the “||” sign beneath the column “Array”. The execution of this query leads to the same errors.

To resolve this error, you need to add the value after “||” into curly brackets within the single inverted commas as ’{78}’. On execution, you will see that the array will be formed as “{11,25,78}” beneath the column “Array”.

Let’s take another illustration to get the error: malformed array literal. Thus, we have been merging the array in a square bracket with the none, i.e., empty value in single commas. On running this instruction, we have found the same malformed array literal error on the output.

To recover our system from this error, we will be replacing the empty inverted commas with the “NULL” keyword in the below-shown image. On execution of this instruction, we have got the array {11,25}’ beneath the column “Array” in the output area.

Example 03:

Let’s take the last example to get the error: malformed array literal and solve it through. Assume you have a table named “Ftest” in your database with some records in it. Fetch all its records with the SELECT instruction shown below. It is fine when you are fetching all its records without any condition as per the instruction below used within the query tool.

Let’s fetch all the records of this table from ID 1 to 4 using the WHERE clause condition. The IDs have been mentioned in the simple brackets within single inverted commas. But, it leads us to a malformed array literal error.

To resolve this error, we need to combine two conditions through AND operator within the WHERE clause of the SELECT instruction. This time, our query worked greatly and displayed the records from ID 3 to 5.

Conclusion:

Finally! We have completed the explanation of solving the PostgreSQL error “malformed array literal”. We have discussed three of the different scenarios that may cause this error in the PostgreSQL database. We have also covered the solutions to all those scenarios that may cause this error to happen. Therefore, we know that you will find all these examples easy to understand and learn a new thing in the PostgreSQL database.

About the author

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.

Люди рождены, чтобы совершать ошибки. В конце концов, когда вы делаете какой-то код, вы также делаете ошибки, которые приводят к некоторым ошибкам, то есть логическим, синтаксическим и техническим. Как и в любом языке, в базе данных возникает множество ошибок. База данных PostgreSQL полна таких ошибок, которые мы получаем ежедневно. Одной из таких ошибок является «Искаженный литерал массива». Причин этой ошибки в базе данных PostgreSQL может быть много. Нам просто нужно выяснить все эти причины и устранить ошибку. Сегодня мы решили рассказать об этой статье нашим пользователям, которым неизвестна ошибка базы данных postgresql: искаженный литерал массива. Давайте посмотрим, как мы можем найти и решить эту проблему в графическом пользовательском интерфейсе PostgreSQL pgAmdin.

Давайте начнем с запуска вашей установленной базы данных PostgreSQL, выполнив поиск в строке поиска на переднем экране рабочего стола Windows 10. В строке поиска на рабочем столе Windows 10 (в левом нижнем углу) напишите «pgAdmin». Появится всплывающее окно для приложения «pgAdmin 4» базы данных PostgreSQL. Вы должны нажать на него, чтобы открыть его в вашей системе. Он будет использовать от 20 до 30 секунд, чтобы открыть себя. При открытии появится диалоговое окно для ввода пароля для сервера базы данных. Вы должны написать пароль, который вы ввели при установке базы данных PostgreSQL. После добавления пароля сервера базы данных сервер готов к использованию. В опции «Серверы» в левой части PostgreSQL разверните базы данных. Выберите базу данных по вашему выбору, чтобы начать работу над ней. Мы выбрали базу данных «aqsayasin» с нашего сервера базы данных. Теперь откройте выбранную базу данных «инструмент запроса», щелкнув значок «инструмент запроса» на верхней панели задач. Это откроет область запросов для выполнения некоторых задач с помощью команд в базе данных.

Пример 01:

Самая первая и наиболее часто встречающаяся причина ошибки: искаженный литерал массива в базе данных PostgreSQL заключается в копировании содержимого столбца типа JSON в какой-либо тип массива. Давайте сделаем ситуацию примерно такой и разрешим ее после этого. Нам нужна таблица со столбцом типа JSON для использования данных JSON. Таким образом, мы создали новую таблицу с именем «Malformed» в базе данных «aqsayasin» с помощью команды CREATE TABLE. Эта таблица была создана с тремя разными столбцами. Его первый столбец «ID» представляет собой простой целочисленный тип, а второй столбец «name» имеет тип текстового массива. Последний столбец «info» был инициализирован как тип данных «jsonb» для хранения в нем данных JSON. Нажмите кнопку запуска базы данных postgreSQL на панели задач. Вы увидите, что пустая таблица «Malformed» будет создана в соответствии с выходными данными успешного запроса ниже.

Давайте вставим несколько записей в столбец ID и информации таблицы «Malformed», отбросив инструкцию INSERT INTO в инструменте запросов. Мы не вставляем записи в столбец типа массива «имя», потому что позже мы скопируем в него записи столбца jsonb «информация». Таким образом, мы добавили данные JSON в столбец «info» и целочисленное значение в столбец «ID». Было довольно легко использовать ключевое слово «VALUES», и результат был успешным, как показано ниже.

Чтобы получить литеральную ошибку искаженного массива, мы должны использовать неправильный формат запроса в инструменте запросов. Таким образом, мы использовали инструкцию UPDATE для изменения записей таблицы «Malformed». Мы используем ключевое слово «SET», чтобы преобразовать запись массива «имя» в виде текста из информационного столбца в столбец «имя», который сейчас пуст. При выполнении этой инструкции мы обнаружили, что этот способ копирования данных JSON в столбец типа массива выдает ошибку «неверный формат литерала массива». Нам пока приходится менять формат копирования данных.

Чтобы скопировать данные столбца JSONB в какой-либо столбец типа массива, нам нужно использовать функцию concat в нашей команде UPDATE. Поэтому мы использовали команду UPDATE для изменения таблицы «Malformed». Ключевое слово SET присваивает запись столбцу «имя» типа массива. При назначении он использует concat и функцию перевода. Функция перевода преобразует данные JSON в тип массива для столбца «информация». После этого функция concat сложит переведенные данные в единицу в виде массива, чтобы их можно было сохранить в столбец «имя». Ошибка была устранена при выполнении, и данные были скопированы правильно.

Давайте отобразим данные таблицы «Искаженные» на нашем экране графического интерфейса pgAdmin, используя инструкцию «SELECT», показанную ниже. Вы можете видеть, что данные JSON из столбца «информация» успешно скопированы в столбец массива «имя».

Пример 02:

Другой способ получить эту ошибку в вашей базе данных — использовать неправильный способ объединения двух массивов. Таким образом, мы будем использовать запрос SELECT ARRAY для объединения значений массива 11 и 25 в пределах квадрата. скобки до значения в одинарных кавычках, т. е. 78, разделенных «||» подпись под колонкой «Множество». Выполнение этого запроса приводит к тем же ошибкам.

Чтобы устранить эту ошибку, вам нужно добавить значение после «||» в фигурные скобки в одинарных кавычках как ‘{78}’. При выполнении вы увидите, что массив будет сформирован как «{11,25,78}» под столбцом «Массив».

Давайте возьмем другую иллюстрацию, чтобы получить ошибку: искаженный литерал массива. Таким образом, мы объединили массив в квадратной скобке с пустым значением в одинарных запятых. При выполнении этой инструкции мы обнаружили на выходе ту же ошибку литерала искаженного массива.

Чтобы восстановить нашу систему от этой ошибки, мы заменим пустые кавычки ключевым словом «NULL» на изображении ниже. При выполнении этой инструкции мы получили массив {11,25}’ под столбцом «Массив» в области вывода.

Пример 03:

Давайте возьмем последний пример, чтобы получить ошибку: искаженный литерал массива и решить ее. Предположим, у вас есть таблица с именем «Ftest» в вашей базе данных с некоторыми записями в ней. Извлеките все его записи с помощью инструкции SELECT, показанной ниже. Это нормально, когда вы извлекаете все его записи без каких-либо условий в соответствии с приведенной ниже инструкцией, используемой в инструменте запросов.

Давайте выберем все записи этой таблицы с идентификаторами от 1 до 4, используя условие предложения WHERE. Идентификаторы указаны в простых скобках в одинарных кавычках. Но это приводит нас к неправильно сформированной литеральной ошибке массива.

Чтобы устранить эту ошибку, нам нужно объединить два условия с помощью оператора AND в предложении WHERE инструкции SELECT. На этот раз наш запрос работал отлично и отображал записи с ID 3 по 5.

Заключение:

Ну наконец то! Мы завершили объяснение решения ошибки PostgreSQL «неверный формат массива». Мы обсудили три различных сценария, которые могут вызвать эту ошибку в базе данных PostgreSQL. Мы также рассмотрели решения для всех тех сценариев, которые могут вызвать эту ошибку. Поэтому мы знаем, что вы найдете все эти примеры простыми для понимания и узнаете что-то новое в базе данных PostgreSQL.

I want to copy an array from jsonb field to a PostgreSQL array column:

CREATE TABLE survey_results (
    id integer NOT NULL,
    areas text[],  
    raw jsonb DEFAULT '{}'::jsonb
);

INSERT INTO survey_results (id, raw)
    VALUES (1, '{"areas": ["test", "test2"]}');

UPDATE survey_results SET areas = CAST(raw#>>'{areas}' AS text[]);

This returns me?

ERROR: malformed array literal: "["test", "test2"]" Detail: "[" must introduce explicitly-specified array dimensions.

How can I fix that?

http://sqlfiddle.com/#!17/d8122/2

asked Feb 19, 2018 at 12:52

Mateusz Urbański's user avatar

Mateusz UrbańskiMateusz Urbański

7,35215 gold badges68 silver badges133 bronze badges

1

http://sqlfiddle.com/#!17/d8122/33

json array is not self castable to postgres array. You need to either properly parse and cast it (json_array_elements, unnest, array_agg), or use some monkey hack, like:

UPDATE survey_results 
SET areas = concat('{',translate(raw#>>'{areas}','"',$$'$$),'}')::text[];

above I «prepare» json array, by changing quotes, so they would be literal, not identifier ones and prepare it to postgres array text representation '{}'

as alternative smth like:

with a as (
  select jsonb_array_elements_text(raw#>'{areas}') e from survey_results 
)
, b as (
select array_agg(e) ag from a
)
UPDATE survey_results 
SET areas = ag::text[]
FROM b;
select * from survey_results
  ;

can be used — for safer «casting»

answered Feb 19, 2018 at 13:03

Vao Tsun's user avatar

2

For Node.JS, this task could be solved approximately as follows:

// const { Client } = require('discord.js');
let user_input = 123; // for example
let fetchedInvite = await client.fetchInvite(user_input);
const features = fetchedInvite.guild.features;
// ['BANNER', /*.../* 'PREVIEW_ENABLED'];
const featuresPreparedToQuery = JSON.stringify(features)
    .replace('[', '{')
    .replace(']', '}');
console.log("featuresPreparedToQuery:", featuresPreparedToQuery);
// {'BANNER', /*.../* 'PREVIEW_ENABLED'}

answered May 16, 2022 at 7:53

Gesugao-san's user avatar

Just a slight variation to Chris’s answer:

SELECT a, translate(b, '[]', '{}')::text[] AS b, d
FROM json_to_record('{"a": 1, "b": ["hello", "There"], "c": "bar"}')
AS x(a int, b text, d text);

The idea is the same: massage the JSON array into an array — in this case, through an array literal. In addition to a bit cleaner looking code (though I love it, regex usually does not help much in this regard :), it seems slighly faster, too:

CREATE TABLE jsonb_test (
    id serial,
    data jsonb
);

INSERT INTO jsonb_test (id, data)
SELECT i, format('{"a": %s, "b": ["foo", "bar"], "c": "baz"}', i::text)::jsonb 
FROM generate_series(1,10000) t(i);

SELECT a, string_to_array(regexp_replace(b, '\[*\"*\s*\]*','','g'),',') AS b, d
FROM jsonb_test AS j, 
LATERAL json_to_record(j.data::json) AS r(a int, b text, d text);

-- versus 

SELECT a, translate(b, '[]', '{}')::text[] AS b, d
FROM jsonb_test AS j, 
LATERAL json_to_record(j.data::json) AS r(a int, b text, d text);

On this dataset and on my test box, the regex version shows and average execution time of 300 ms, while my version shows 210 ms.

I’m using a postgres function that loops another function which uses dblink to commit updates to my db.

Here is a part from the «inner» function:

    selectedIds := array(select id from items where id2 is null and id > latestItemId order by id asc  limit _limit);
highestItemId := (select max(x) from unnest(selectedIds) x);
updatedItemCount := array_length(selectedIds, 1);
raise notice 'updatedItemCount %', updatedItemCount;
raise notice 'SelectedItemiDs %', selectedIds;

PERFORM dblink_connect('dblink_trans','dbname=notified-local port=5432 user=postgres');
PERFORM dblink('dblink_trans','update items set id2 = id where id = any(' || selectedIds || ')');
PERFORM dblink('dblink_trans','COMMIT;');
PERFORM dblink_disconnect('dblink_trans'); 

My raise notice on selectedIds looks like this: {23,60,65,66,588,968,1049,1198,1236,1356,1358,1359,1360,1364,1365,1366}

and then i get the error in the title when i’m trying to do the dblink update.

The error says that i should have { as a start of my array and from what i can see in the raise notice that is exactly what i have?

Понравилась статья? Поделить с друзьями:
  • Postgresql ошибка нехватка памяти
  • Postgresql ошибка не удалось открыть файл
  • Postgres ошибка создания временной директории
  • Postgres ошибка роль не существует
  • Postgres ошибка 28000