5.5. Ограничения #
Типы данных сами по себе ограничивают множество данных, которые можно сохранить в таблице. Однако для многих приложений такие ограничения слишком грубые. Например, столбец, содержащий цену продукта, должен, вероятно, принимать только положительные значения. Но такого стандартного типа данных нет. Возможно, вы также захотите ограничить данные столбца по отношению к другим столбцам или строкам. Например, в таблице с информацией о товаре должна быть только одна строка с определённым кодом товара.
Для решения подобных задач SQL позволяет вам определять ограничения для столбцов и таблиц. Ограничения дают вам возможность управлять данными в таблицах так, как вы захотите. Если пользователь попытается сохранить в столбце значение, нарушающее ограничения, возникнет ошибка. Ограничения будут действовать, даже если это значение по умолчанию.
5.5.1. Ограничения-проверки #
Ограничение-проверка — наиболее общий тип ограничений. В его определении вы можете указать, что значение данного столбца должно удовлетворять логическому выражению (проверке истинности). Например, цену товара можно ограничить положительными значениями так:
CREATE TABLE products (
product_no integer,
name text,
price numeric CHECK (price > 0)
);
Как вы видите, ограничение определяется после типа данных, как и значение по умолчанию. Значения по умолчанию и ограничения могут указываться в любом порядке. Ограничение-проверка состоит из ключевого слова CHECK
, за которым идёт выражение в скобках. Это выражение должно включать столбец, для которого задаётся ограничение, иначе оно не имеет большого смысла.
Вы можете также присвоить ограничению отдельное имя. Это улучшит сообщения об ошибках и позволит вам ссылаться на это ограничение, когда вам понадобится изменить его. Сделать это можно так:
CREATE TABLE products (
product_no integer,
name text,
price numeric CONSTRAINT positive_price CHECK (price > 0)
);
То есть, чтобы создать именованное ограничение, напишите ключевое слово CONSTRAINT
, а за ним идентификатор и собственно определение ограничения. (Если вы не определите имя ограничения таким образом, система выберет для него имя за вас.)
Ограничение-проверка может также ссылаться на несколько столбцов. Например, если вы храните обычную цену и цену со скидкой, так вы можете гарантировать, что цена со скидкой будет всегда меньше обычной:
CREATE TABLE products (
product_no integer,
name text,
price numeric CHECK (price > 0),
discounted_price numeric CHECK (discounted_price > 0),
CHECK (price > discounted_price)
);
Первые два ограничения определяются похожим образом, но для третьего используется новый синтаксис. Оно не связано с определённым столбцом, а представлено отдельным элементом в списке. Определения столбцов и такие определения ограничений можно переставлять в произвольном порядке.
Про первые два ограничения можно сказать, что это ограничения столбцов, тогда как третье является ограничением таблицы, так как оно написано отдельно от определений столбцов. Ограничения столбцов также можно записать в виде ограничений таблицы, тогда как обратное не всегда возможно, так как подразумевается, что ограничение столбца ссылается только на связанный столбец. (Хотя PostgreSQL этого не требует, но для совместимости с другими СУБД лучше следовать это правилу.) Ранее приведённый пример можно переписать и так:
CREATE TABLE products ( product_no integer, name text, price numeric, CHECK (price > 0), discounted_price numeric, CHECK (discounted_price > 0), CHECK (price > discounted_price) );
Или даже так:
CREATE TABLE products ( product_no integer, name text, price numeric CHECK (price > 0), discounted_price numeric, CHECK (discounted_price > 0 AND price > discounted_price) );
Это дело вкуса.
Ограничениям таблицы можно присваивать имена так же, как и ограничениям столбцов:
CREATE TABLE products (
product_no integer,
name text,
price numeric,
CHECK (price > 0),
discounted_price numeric,
CHECK (discounted_price > 0),
CONSTRAINT valid_discount CHECK (price > discounted_price)
);
Следует заметить, что ограничение-проверка удовлетворяется, если выражение принимает значение true или NULL. Так как результатом многих выражений с операндами NULL будет значение NULL, такие ограничения не будут препятствовать записи NULL в ограничиваемые столбцы. Чтобы гарантировать, что столбец не содержит значения NULL, можно использовать ограничение NOT NULL, описанное в следующем разделе.
Примечание
PostgreSQL не поддерживает ограничения CHECK
, которые обращаются к данным, не относящимся к новой или изменённой строке. Хотя ограничение CHECK
, нарушающее это правило, может работать в простых случаях, в общем случае нельзя гарантировать, что база данных не придёт в состояние, когда условие ограничения окажется ложным (вследствие последующих изменений других участвующих в его вычислении строк). В результате восстановление выгруженных данных может оказаться невозможным. Во время восстановления возможен сбой, даже если полное состояние базы данных согласуется с условием ограничения, по причине того, что строки загружаются не в том порядке, в котором это условие будет соблюдаться. Поэтому для определения ограничений, затрагивающих другие строки и другие таблицы, используйте ограничения UNIQUE
, EXCLUDE
или FOREIGN KEY
, если это возможно.
Если вам не нужна постоянно поддерживаемая гарантия целостности, а достаточно разовой проверки добавляемой строки по отношению к другим строкам, вы можете реализовать эту проверку в собственном триггере. (Этот подход исключает вышеописанные проблемы при восстановлении, так как в выгрузке pg_dump триггеры воссоздаются после восстановления данных, и поэтому эта проверка не будет действовать в процессе выгрузки/восстановления.)
Примечание
В PostgreSQL предполагается, что условия ограничений CHECK
являются постоянными, то есть при одинаковых данных в строке они всегда выдают одинаковый результат. Именно этим предположением оправдывается то, что ограничения CHECK
проверяются только при добавлении или изменении строк, а не при каждом обращении к ним. (Приведённое выше предупреждение о недопустимости обращений к другим таблицам является частным следствием этого предположения.)
Однако это предположение может нарушаться, как часто бывает, когда в выражении CHECK
используется пользовательская функция, поведение которой впоследствии меняется. PostgreSQL не запрещает этого, и если строки в таблице перестанут удовлетворять ограничению CHECK
, это останется незамеченным. В итоге при попытке загрузить выгруженные позже данные могут возникнуть проблемы. Поэтому подобные изменения рекомендуется осуществлять следующим образом: удалить ограничение (используя ALTER TABLE
), изменить определение функции, а затем пересоздать ограничение той же командой, которая при этом перепроверит все строки таблицы.
5.5.2. Ограничения NOT NULL #
Ограничение NOT NULL просто указывает, что столбцу нельзя присваивать значение NULL. Пример синтаксиса:
CREATE TABLE products ( product_no integer NOT NULL, name text NOT NULL, price numeric );
Ограничение NOT NULL всегда записывается как ограничение столбца и функционально эквивалентно ограничению CHECK (
, но в PostgreSQL явное ограничение NOT NULL работает более эффективно. Хотя у такой записи есть недостаток — назначить имя таким ограничениям нельзя.имя_столбца
IS NOT NULL)
Естественно, для столбца можно определить больше одного ограничения. Для этого их нужно просто указать одно за другим:
CREATE TABLE products ( product_no integer NOT NULL, name text NOT NULL, price numeric NOT NULL CHECK (price > 0) );
Порядок здесь не имеет значения, он не обязательно соответствует порядку проверки ограничений.
Для ограничения NOT NULL
есть и обратное: ограничение NULL
. Оно не означает, что столбец должен иметь только значение NULL, что конечно было бы бессмысленно. Суть же его в простом указании, что столбец может иметь значение NULL (это поведение по умолчанию). Ограничение NULL
отсутствует в стандарте SQL и использовать его в переносимых приложениях не следует. (Оно было добавлено в PostgreSQL только для совместимости с некоторыми другими СУБД.) Однако некоторые пользователи любят его использовать, так как оно позволяет легко переключать ограничения в скрипте. Например, вы можете начать с:
CREATE TABLE products ( product_no integer NULL, name text NULL, price numeric NULL );
и затем вставить ключевое слово NOT
, где потребуется.
Подсказка
При проектировании баз данных чаще всего большинство столбцов должны быть помечены как NOT NULL.
5.5.3. Ограничения уникальности #
Ограничения уникальности гарантируют, что данные в определённом столбце или группе столбцов уникальны среди всех строк таблицы. Ограничение записывается так:
CREATE TABLE products (
product_no integer UNIQUE,
name text,
price numeric
);
в виде ограничения столбца и так:
CREATE TABLE products (
product_no integer,
name text,
price numeric,
UNIQUE (product_no)
);
в виде ограничения таблицы.
Чтобы определить ограничение уникальности для группы столбцов, запишите его в виде ограничения таблицы, перечислив имена столбцов через запятую:
CREATE TABLE example (
a integer,
b integer,
c integer,
UNIQUE (a, c)
);
Такое ограничение указывает, что сочетание значений перечисленных столбцов должно быть уникально во всей таблице, тогда как значения каждого столбца по отдельности не должны быть (и обычно не будут) уникальными.
Вы можете назначить уникальному ограничению имя обычным образом:
CREATE TABLE products (
product_no integer CONSTRAINT must_be_different UNIQUE,
name text,
price numeric
);
При добавлении ограничения уникальности будет автоматически создан уникальный индекс-B-дерево для столбца или группы столбцов, перечисленных в ограничении. Условие уникальности, распространяющееся только на некоторые строки, нельзя записать в виде ограничения уникальности, однако такое условие можно установить, создав уникальный частичный индекс.
Как правило, ограничение уникальности нарушается, если в таблице оказывается несколько строк, у которых совпадают значения всех столбцов, включённых в ограничение. По умолчанию два значения NULL при таком сравнении не считаются равными. Это означает, что даже при наличии ограничения уникальности в таблице можно сохранить строки с дублирующимися значениями, если они содержат NULL в одном или нескольких ограничиваемых столбцах. Это поведение можно изменить, добавив предложение NULLS NOT DISTINCT
, например
CREATE TABLE products (
product_no integer UNIQUE NULLS NOT DISTINCT,
name text,
price numeric
);
или
CREATE TABLE products (
product_no integer,
name text,
price numeric,
UNIQUE NULLS NOT DISTINCT (product_no)
);
Поведение по умолчанию можно выбрать явно, добавив NULLS DISTINCT
. Согласно стандарту SQL вариант обработки значений NULL по умолчанию определяется реализацией, и в других СУБД встречается другое поведение. Это следует учитывать при разработке переносимых приложений.
5.5.4. Первичные ключи #
Ограничение первичного ключа означает, что образующий его столбец или группа столбцов может быть уникальным идентификатором строк в таблице. Для этого требуется, чтобы значения были одновременно уникальными и отличными от NULL. Таким образом, таблицы со следующими двумя определениями будут принимать одинаковые данные:
CREATE TABLE products ( product_no integer UNIQUE NOT NULL, name text, price numeric );
CREATE TABLE products (
product_no integer PRIMARY KEY,
name text,
price numeric
);
Первичные ключи могут включать несколько столбцов; синтаксис похож на запись ограничений уникальности:
CREATE TABLE example (
a integer,
b integer,
c integer,
PRIMARY KEY (a, c)
);
При добавлении первичного ключа автоматически создаётся уникальный индекс-B-дерево для столбца или группы столбцов, перечисленных в первичном ключе, и данные столбцы помечаются как NOT NULL
.
Таблица может иметь максимум один первичный ключ. (Ограничений уникальности и ограничений NOT NULL, которые функционально почти равнозначны первичным ключам, может быть сколько угодно, но назначить ограничением первичного ключа можно только одно.) Теория реляционных баз данных говорит, что первичный ключ должен быть в каждой таблице. В PostgreSQL такого жёсткого требования нет, но обычно лучше ему следовать.
Первичные ключи полезны и для документирования, и для клиентских приложений. Например, графическому приложению с возможностями редактирования содержимого таблицы, вероятно, потребуется знать первичный ключ таблицы, чтобы однозначно идентифицировать её строки. Первичные ключи находят и другое применение в СУБД; в частности, первичный ключ в таблице определяет целевые столбцы по умолчанию для сторонних ключей, ссылающихся на эту таблицу.
5.5.5. Внешние ключи #
Ограничение внешнего ключа указывает, что значения столбца (или группы столбцов) должны соответствовать значениям в некоторой строке другой таблицы. Это называется ссылочной целостностью двух связанных таблиц.
Пусть у вас уже есть таблица продуктов, которую мы неоднократно использовали ранее:
CREATE TABLE products ( product_no integer PRIMARY KEY, name text, price numeric );
Давайте предположим, что у вас есть таблица с заказами этих продуктов. Мы хотим, чтобы в таблице заказов содержались только заказы действительно существующих продуктов. Поэтому мы определим в ней ограничение внешнего ключа, ссылающееся на таблицу продуктов:
CREATE TABLE orders (
order_id integer PRIMARY KEY,
product_no integer REFERENCES products (product_no),
quantity integer
);
С таким ограничением создать заказ со значением product_no
, отсутствующим в таблице products (и не равным NULL), будет невозможно.
В такой схеме таблицу orders называют подчинённой таблицей, а products — главной. Соответственно, столбцы называют так же подчинённым и главным (или ссылающимся и целевым).
Предыдущую команду можно сократить так:
CREATE TABLE orders (
order_id integer PRIMARY KEY,
product_no integer REFERENCES products,
quantity integer
);
то есть, если опустить список столбцов, внешний ключ будет неявно связан с первичным ключом главной таблицы.
Ограничению внешнего ключа можно назначить имя стандартным способом.
Внешний ключ также может ссылаться на группу столбцов. В этом случае его нужно записать в виде обычного ограничения таблицы. Например:
CREATE TABLE t1 (
a integer PRIMARY KEY,
b integer,
c integer,
FOREIGN KEY (b, c) REFERENCES other_table (c1, c2)
);
Естественно, число и типы столбцов в ограничении должны соответствовать числу и типам целевых столбцов.
Иногда имеет смысл задать в ограничении внешнего ключа в качестве «другой таблицы» ту же таблицу; такой внешний ключ называется ссылающимся на себя. Например, если вы хотите, чтобы строки таблицы представляли узлы древовидной структуры, вы можете написать
CREATE TABLE tree ( node_id integer PRIMARY KEY, parent_id integer REFERENCES tree, name text, ... );
Для узла верхнего уровня parent_id
будет равен NULL, пока записи с отличным от NULL parent_id
будут ссылаться только на существующие строки таблицы.
Таблица может содержать несколько ограничений внешнего ключа. Это полезно для связи таблиц в отношении многие-ко-многим. Скажем, у вас есть таблицы продуктов и заказов, но вы хотите, чтобы один заказ мог содержать несколько продуктов (что невозможно в предыдущей схеме). Для этого вы можете использовать такую схему:
CREATE TABLE products ( product_no integer PRIMARY KEY, name text, price numeric ); CREATE TABLE orders ( order_id integer PRIMARY KEY, shipping_address text, ... ); CREATE TABLE order_items ( product_no integer REFERENCES products, order_id integer REFERENCES orders, quantity integer, PRIMARY KEY (product_no, order_id) );
Заметьте, что в последней таблице первичный ключ покрывает внешние ключи.
Мы знаем, что внешние ключи запрещают создание заказов, не относящихся ни к одному продукту. Но что делать, если после создания заказов с определённым продуктом мы захотим удалить его? SQL справится с этой ситуацией. Интуиция подсказывает следующие варианты поведения:
Запретить удаление продукта
Удалить также связанные заказы
Что-то ещё?
Для иллюстрации давайте реализуем следующее поведение в вышеприведённом примере: при попытке удаления продукта, на который ссылаются заказы (через таблицу order_items
), мы запрещаем эту операцию. Если же кто-то попытается удалить заказ, то удалится и его содержимое:
CREATE TABLE products ( product_no integer PRIMARY KEY, name text, price numeric ); CREATE TABLE orders ( order_id integer PRIMARY KEY, shipping_address text, ... ); CREATE TABLE order_items ( product_no integer REFERENCES products ON DELETE RESTRICT, order_id integer REFERENCES orders ON DELETE CASCADE, quantity integer, PRIMARY KEY (product_no, order_id) );
Ограничивающие и каскадные удаления — два наиболее распространённых варианта. RESTRICT
предотвращает удаление связанной строки. NO ACTION
означает, что если зависимые строки продолжают существовать при проверке ограничения, возникает ошибка (это поведение по умолчанию). (Главным отличием этих двух вариантов является то, что NO ACTION
позволяет отложить проверку в процессе транзакции, а RESTRICT
— нет.) CASCADE
указывает, что при удалении связанных строк зависимые от них будут так же автоматически удалены. Есть ещё два варианта: SET NULL
и SET DEFAULT
. При удалении связанных строк они назначают зависимым столбцам в подчинённой таблице значения NULL или значения по умолчанию, соответственно. Заметьте, что это не будет основанием для нарушения ограничений. Например, если в качестве действия задано SET DEFAULT
, но значение по умолчанию не удовлетворяет ограничению внешнего ключа, операция закончится ошибкой.
Какой вариант действия ON DELETE
выбрать — зависит от того, какие типы объектов представляются в связанных таблицах. Когда в подчинённой таблице представляется объект, который является составной частью сущности, представленной в главной таблице, и не может существовать независимо, уместно выбрать действие CASCADE
. Если две таблицы представляют независимые объекты, более подходящим действием будет RESTRICT
или NO ACTION
; тогда приложению, которому действительно нужно удалить оба объекта, потребуется сделать это явно и выполнить две команды удаления. В приведённом выше примере позиции заказа являются частью заказа, и будет удобно, если они удалятся автоматически при удалении заказа. Но продукты и заказы — разные вещи, поэтому автоматическое удаление некоторых позиций заказов при удалении продуктов может быть неприемлемым. Если же отношение внешнего ключа представляет необязательную информацию, подходящим может быть действие SET NULL
или SET DEFAULT
. Например, если в таблице продуктов содержится ссылка на менеджера продукта, и запись менеджера удаляется, может быть полезным установить в поле менеджера продукта значение NULL или значение по умолчанию.
Действия SET NULL
и SET DEFAULT
могут принимать список столбцов, которые получат соответствующие значения. Обычно значения присваиваются всем столбцам ограничения внешнего ключа; присвоение для подмножества столбцов полезно только в некоторых особых случаях. Рассмотрите следующий пример:
CREATE TABLE tenants (
tenant_id integer PRIMARY KEY
);
CREATE TABLE users (
tenant_id integer REFERENCES tenants ON DELETE CASCADE,
user_id integer NOT NULL,
PRIMARY KEY (tenant_id, user_id)
);
CREATE TABLE posts (
tenant_id integer REFERENCES tenants ON DELETE CASCADE,
post_id integer NOT NULL,
author_id integer,
PRIMARY KEY (tenant_id, post_id),
FOREIGN KEY (tenant_id, author_id) REFERENCES users ON DELETE SET NULL (author_id)
);
Без указания столбца внешний ключ также установил бы значение NULL для столбца tenant_id
, но этот столбец является частью первичного ключа.
Аналогично указанию ON DELETE
существует ON UPDATE
, которое срабатывает при изменении заданного столбца. При этом возможные действия те же, за исключением того, что для SET NULL
и SET DEFAULT
нельзя задать списки столбцов. CASCADE
в данном случае означает, что изменённые значения связанных столбцов будут скопированы в зависимые строки.
Обычно зависимая строка не должна удовлетворять ограничению внешнего ключа, если один из связанных столбцов содержит NULL. Если в объявление внешнего ключа добавлено MATCH FULL
, строка будет удовлетворять ограничению, только если все связанные столбцы равны NULL (то есть при разных значениях (NULL и не NULL) гарантируется невыполнение ограничения MATCH FULL
). Если вы хотите, чтобы зависимые строки не могли избежать и этого ограничения, объявите связанные столбцы как NOT NULL
.
Внешний ключ должен ссылаться на столбцы, либо являющиеся первичным ключом, либо образующие ограничение уникальности, либо являющиеся столбцами из нечастичного уникального индекса. Таким образом, для связанных столбцов всегда будет существовать индекс, а значит проверки наличия соответствия для связанной строки будут выполняться эффективно. Так как команды DELETE
для строк главной таблицы или UPDATE
для зависимых столбцов потребуют просканировать подчинённую таблицу и найти строки, ссылающиеся на старые значения, полезно будет иметь индекс и для подчинённых столбцов. Но это нужно не всегда, и создать соответствующий индекс можно по-разному, поэтому объявление внешнего ключа не создаёт автоматически индекс по связанным столбцам.
Подробнее об изменении и удалении данных рассказывается в Главе 6. Вы также можете подробнее узнать о синтаксисе ограничений внешнего ключа в справке CREATE TABLE.
5.5.6. Ограничения-исключения #
Ограничения-исключения гарантируют, что при сравнении любых двух строк по указанным столбцам или выражениям с помощью заданных операторов, минимум одно из этих сравнений возвратит false или NULL. Записывается это так:
CREATE TABLE circles ( c circle, EXCLUDE USING gist (c WITH &&) );
Подробнее об этом см. CREATE TABLE ... CONSTRAINT ... EXCLUDE
.
При добавлении ограничения-исключения будет автоматически создан индекс того типа, который указан в объявлении ограничения.
PostgreSQL 9.4.1 Documentation | |||
---|---|---|---|
Prev | Up | Chapter 31. libpq - C Library | Next |
31.3. Command Execution Functions
Once a connection to a database server has been successfully established, the functions described here are used to perform SQL queries and commands.
31.3.1. Main Functions
PQexec
Submits a command to the server and waits for the result.
PGresult *PQexec(PGconn *conn, const char *command);
Returns a PGresult pointer or possibly a null pointer. A non-null pointer will generally be returned except in out-of-memory conditions or serious errors such as inability to send the command to the server. The
PQresultStatus
function should be called to check the return value for any errors (including the value of a null pointer, in which case it will return PGRES_FATAL_ERROR). UsePQerrorMessage
to get more information about such errors.
The command string can include multiple SQL commands (separated by semicolons). Multiple queries sent in a single PQexec
call are processed in a single transaction, unless there are explicit BEGIN/COMMIT commands included in the query string to divide it into multiple transactions. Note however that the returned PGresult structure describes only the result of the last command executed from the string. Should one of the commands fail, processing of the string stops with it and the returned PGresult describes the error condition.
PQexecParams
Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.
PGresult *PQexecParams(PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char * const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat);
PQexecParams
is likePQexec
, but offers additional functionality: parameter values can be specified separately from the command string proper, and query results can be requested in either text or binary format.PQexecParams
is supported only in protocol 3.0 and later connections; it will fail when using protocol 2.0.The function arguments are:
- conn
The connection object to send the command through.
- command
The SQL command string to be executed. If parameters are used, they are referred to in the command string as $1, $2, etc.
- nParams
The number of parameters supplied; it is the length of the arrays paramTypes[], paramValues[], paramLengths[], and paramFormats[]. (The array pointers can be NULL when nParams is zero.)
- paramTypes[]
Specifies, by OID, the data types to be assigned to the parameter symbols. If paramTypes is NULL, or any particular element in the array is zero, the server infers a data type for the parameter symbol in the same way it would do for an untyped literal string.
- paramValues[]
Specifies the actual values of the parameters. A null pointer in this array means the corresponding parameter is null; otherwise the pointer points to a zero-terminated text string (for text format) or binary data in the format expected by the server (for binary format).
- paramLengths[]
Specifies the actual data lengths of binary-format parameters. It is ignored for null parameters and text-format parameters. The array pointer can be null when there are no binary parameters.
- paramFormats[]
Specifies whether parameters are text (put a zero in the array entry for the corresponding parameter) or binary (put a one in the array entry for the corresponding parameter). If the array pointer is null then all parameters are presumed to be text strings.
Values passed in binary format require knowledge of the internal representation expected by the backend. For example, integers must be passed in network byte order. Passing numeric values requires knowledge of the server storage format, as implemented in src/backend/utils/adt/numeric.c::numeric_send() and src/backend/utils/adt/numeric.c::numeric_recv().
- resultFormat
Specify zero to obtain results in text format, or one to obtain results in binary format. (There is not currently a provision to obtain different result columns in different formats, although that is possible in the underlying protocol.)
The primary advantage of PQexecParams
over PQexec
is that parameter values can be separated from the command string, thus avoiding the need for tedious and error-prone quoting and escaping.
Unlike PQexec
, PQexecParams
allows at most one SQL command in the given string. (There can be semicolons in it, but not more than one nonempty command.) This is a limitation of the underlying protocol, but has some usefulness as an extra defense against SQL-injection attacks.
Tip: Specifying parameter types via OIDs is tedious, particularly if you prefer not to hard-wire particular OID values into your program. However, you can avoid doing so even in cases where the server by itself cannot determine the type of the parameter, or chooses a different type than you want. In the SQL command text, attach an explicit cast to the parameter symbol to show what data type you will send. For example:
SELECT * FROM mytable WHERE x = $1::bigint;This forces parameter $1 to be treated as bigint, whereas by default it would be assigned the same type as x. Forcing the parameter type decision, either this way or by specifying a numeric type OID, is strongly recommended when sending parameter values in binary format, because binary format has less redundancy than text format and so there is less chance that the server will detect a type mismatch mistake for you.
PQprepare
Submits a request to create a prepared statement with the given parameters, and waits for completion.
PGresult *PQprepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes);
PQprepare
creates a prepared statement for later execution withPQexecPrepared
. This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed.PQprepare
is supported only in protocol 3.0 and later connections; it will fail when using protocol 2.0.The function creates a prepared statement named stmtName from the query string, which must contain a single SQL command. stmtName can be "" to create an unnamed statement, in which case any pre-existing unnamed statement is automatically replaced; otherwise it is an error if the statement name is already defined in the current session. If any parameters are used, they are referred to in the query as $1, $2, etc. nParams is the number of parameters for which types are pre-specified in the array paramTypes[]. (The array pointer can be NULL when nParams is zero.) paramTypes[] specifies, by OID, the data types to be assigned to the parameter symbols. If paramTypes is NULL, or any particular element in the array is zero, the server assigns a data type to the parameter symbol in the same way it would do for an untyped literal string. Also, the query can use parameter symbols with numbers higher than nParams; data types will be inferred for these symbols as well. (See
PQdescribePrepared
for a means to find out what data types were inferred.)As with
PQexec
, the result is normally a PGresult object whose contents indicate server-side success or failure. A null result indicates out-of-memory or inability to send the command at all. UsePQerrorMessage
to get more information about such errors.
Prepared statements for use with PQexecPrepared
can also be created by executing SQL PREPARE statements. Also, although there is no libpq function for deleting a prepared statement, the SQL DEALLOCATE statement can be used for that purpose.
PQexecPrepared
Sends a request to execute a prepared statement with given parameters, and waits for the result.
PGresult *PQexecPrepared(PGconn *conn, const char *stmtName, int nParams, const char * const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat);
PQexecPrepared
is likePQexecParams
, but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. The statement must have been prepared previously in the current session.PQexecPrepared
is supported only in protocol 3.0 and later connections; it will fail when using protocol 2.0.The parameters are identical to
PQexecParams
, except that the name of a prepared statement is given instead of a query string, and the paramTypes[] parameter is not present (it is not needed since the prepared statement's parameter types were determined when it was created).PQdescribePrepared
Submits a request to obtain information about the specified prepared statement, and waits for completion.
PGresult *PQdescribePrepared(PGconn *conn, const char *stmtName);
PQdescribePrepared
allows an application to obtain information about a previously prepared statement.PQdescribePrepared
is supported only in protocol 3.0 and later connections; it will fail when using protocol 2.0.stmtName can be "" or NULL to reference the unnamed statement, otherwise it must be the name of an existing prepared statement. On success, a PGresult with status PGRES_COMMAND_OK is returned. The functions
PQnparams
andPQparamtype
can be applied to this PGresult to obtain information about the parameters of the prepared statement, and the functionsPQnfields
,PQfname
,PQftype
, etc provide information about the result columns (if any) of the statement.PQdescribePortal
Submits a request to obtain information about the specified portal, and waits for completion.
PGresult *PQdescribePortal(PGconn *conn, const char *portalName);
PQdescribePortal
allows an application to obtain information about a previously created portal. (libpq does not provide any direct access to portals, but you can use this function to inspect the properties of a cursor created with a DECLARE CURSOR SQL command.)PQdescribePortal
is supported only in protocol 3.0 and later connections; it will fail when using protocol 2.0.portalName can be "" or NULL to reference the unnamed portal, otherwise it must be the name of an existing portal. On success, a PGresult with status PGRES_COMMAND_OK is returned. The functions
PQnfields
,PQfname
,PQftype
, etc can be applied to the PGresult to obtain information about the result columns (if any) of the portal.
The PGresult structure encapsulates the result returned by the server. libpq application programmers should be careful to maintain the PGresult abstraction. Use the accessor functions below to get at the contents of PGresult. Avoid directly referencing the fields of the PGresult structure because they are subject to change in the future.
PQresultStatus
Returns the result status of the command.
ExecStatusType PQresultStatus(const PGresult *res);
PQresultStatus
can return one of the following values:- PGRES_EMPTY_QUERY
The string sent to the server was empty.
- PGRES_COMMAND_OK
Successful completion of a command returning no data.
- PGRES_TUPLES_OK
Successful completion of a command returning data (such as a SELECT or SHOW).
- PGRES_COPY_OUT
Copy Out (from server) data transfer started.
- PGRES_COPY_IN
Copy In (to server) data transfer started.
- PGRES_BAD_RESPONSE
The server's response was not understood.
- PGRES_NONFATAL_ERROR
A nonfatal error (a notice or warning) occurred.
- PGRES_FATAL_ERROR
A fatal error occurred.
- PGRES_COPY_BOTH
Copy In/Out (to and from server) data transfer started. This feature is currently used only for streaming replication, so this status should not occur in ordinary applications.
- PGRES_SINGLE_TUPLE
The PGresult contains a single result tuple from the current command. This status occurs only when single-row mode has been selected for the query (see Section 31.5).
If the result status is PGRES_TUPLES_OK or PGRES_SINGLE_TUPLE, then the functions described below can be used to retrieve the rows returned by the query. Note that a SELECT command that happens to retrieve zero rows still shows PGRES_TUPLES_OK. PGRES_COMMAND_OK is for commands that can never return rows (INSERT or UPDATE without a RETURNING clause, etc.). A response of PGRES_EMPTY_QUERY might indicate a bug in the client software.
A result of status PGRES_NONFATAL_ERROR will never be returned directly by
PQexec
or other query execution functions; results of this kind are instead passed to the notice processor (see Section 31.12).PQresStatus
Converts the enumerated type returned by
PQresultStatus
into a string constant describing the status code. The caller should not free the result.char *PQresStatus(ExecStatusType status);
PQresultErrorMessage
Returns the error message associated with the command, or an empty string if there was no error.
char *PQresultErrorMessage(const PGresult *res);
If there was an error, the returned string will include a trailing newline. The caller should not free the result directly. It will be freed when the associated PGresult handle is passed to
PQclear
.Immediately following a
PQexec
orPQgetResult
call,PQerrorMessage
(on the connection) will return the same string asPQresultErrorMessage
(on the result). However, a PGresult will retain its error message until destroyed, whereas the connection's error message will change when subsequent operations are done. UsePQresultErrorMessage
when you want to know the status associated with a particular PGresult; usePQerrorMessage
when you want to know the status from the latest operation on the connection.PQresultErrorField
Returns an individual field of an error report.
char *PQresultErrorField(const PGresult *res, int fieldcode);
fieldcode is an error field identifier; see the symbols listed below. NULL is returned if the PGresult is not an error or warning result, or does not include the specified field. Field values will normally not include a trailing newline. The caller should not free the result directly. It will be freed when the associated PGresult handle is passed to
PQclear
.The following field codes are available:
- PG_DIAG_SEVERITY
The severity; the field contents are ERROR, FATAL, or PANIC (in an error message), or WARNING, NOTICE, DEBUG, INFO, or LOG (in a notice message), or a localized translation of one of these. Always present.
- PG_DIAG_SQLSTATE
The SQLSTATE code for the error. The SQLSTATE code identifies the type of error that has occurred; it can be used by front-end applications to perform specific operations (such as error handling) in response to a particular database error. For a list of the possible SQLSTATE codes, see Appendix A. This field is not localizable, and is always present.
- PG_DIAG_MESSAGE_PRIMARY
The primary human-readable error message (typically one line). Always present.
- PG_DIAG_MESSAGE_DETAIL
Detail: an optional secondary error message carrying more detail about the problem. Might run to multiple lines.
- PG_DIAG_MESSAGE_HINT
Hint: an optional suggestion what to do about the problem. This is intended to differ from detail in that it offers advice (potentially inappropriate) rather than hard facts. Might run to multiple lines.
- PG_DIAG_STATEMENT_POSITION
A string containing a decimal integer indicating an error cursor position as an index into the original statement string. The first character has index 1, and positions are measured in characters not bytes.
- PG_DIAG_INTERNAL_POSITION
This is defined the same as the PG_DIAG_STATEMENT_POSITION field, but it is used when the cursor position refers to an internally generated command rather than the one submitted by the client. The PG_DIAG_INTERNAL_QUERY field will always appear when this field appears.
- PG_DIAG_INTERNAL_QUERY
The text of a failed internally-generated command. This could be, for example, a SQL query issued by a PL/pgSQL function.
- PG_DIAG_CONTEXT
An indication of the context in which the error occurred. Presently this includes a call stack traceback of active procedural language functions and internally-generated queries. The trace is one entry per line, most recent first.
- PG_DIAG_SCHEMA_NAME
If the error was associated with a specific database object, the name of the schema containing that object, if any.
- PG_DIAG_TABLE_NAME
If the error was associated with a specific table, the name of the table. (Refer to the schema name field for the name of the table's schema.)
- PG_DIAG_COLUMN_NAME
If the error was associated with a specific table column, the name of the column. (Refer to the schema and table name fields to identify the table.)
- PG_DIAG_DATATYPE_NAME
If the error was associated with a specific data type, the name of the data type. (Refer to the schema name field for the name of the data type's schema.)
- PG_DIAG_CONSTRAINT_NAME
If the error was associated with a specific constraint, the name of the constraint. Refer to fields listed above for the associated table or domain. (For this purpose, indexes are treated as constraints, even if they weren't created with constraint syntax.)
- PG_DIAG_SOURCE_FILE
The file name of the source-code location where the error was reported.
- PG_DIAG_SOURCE_LINE
The line number of the source-code location where the error was reported.
- PG_DIAG_SOURCE_FUNCTION
The name of the source-code function reporting the error.
Note: The fields for schema name, table name, column name, data type name, and constraint name are supplied only for a limited number of error types; see Appendix A. Do not assume that the presence of any of these fields guarantees the presence of another field. Core error sources observe the interrelationships noted above, but user-defined functions may use these fields in other ways. In the same vein, do not assume that these fields denote contemporary objects in the current database.
The client is responsible for formatting displayed information to meet its needs; in particular it should break long lines as needed. Newline characters appearing in the error message fields should be treated as paragraph breaks, not line breaks.
Errors generated internally by libpq will have severity and primary message, but typically no other fields. Errors returned by a pre-3.0-protocol server will include severity and primary message, and sometimes a detail message, but no other fields.
Note that error fields are only available from PGresult objects, not PGconn objects; there is no
PQerrorField
function.PQclear
Frees the storage associated with a PGresult. Every command result should be freed via
PQclear
when it is no longer needed.void PQclear(PGresult *res);
You can keep a PGresult object around for as long as you need it; it does not go away when you issue a new command, nor even if you close the connection. To get rid of it, you must call
PQclear
. Failure to do this will result in memory leaks in your application.
31.3.2. Retrieving Query Result Information
These functions are used to extract information from a PGresult object that represents a successful query result (that is, one that has status PGRES_TUPLES_OK or PGRES_SINGLE_TUPLE). They can also be used to extract information from a successful Describe operation: a Describe's result has all the same column information that actual execution of the query would provide, but it has zero rows. For objects with other status values, these functions will act as though the result has zero rows and zero columns.
PQntuples
Returns the number of rows (tuples) in the query result. Because it returns an integer result, large result sets might overflow the return value on 32-bit operating systems.
int PQntuples(const PGresult *res);
PQnfields
Returns the number of columns (fields) in each row of the query result.
int PQnfields(const PGresult *res);
PQfname
Returns the column name associated with the given column number. Column numbers start at 0. The caller should not free the result directly. It will be freed when the associated PGresult handle is passed to
PQclear
.char *PQfname(const PGresult *res, int column_number);
NULL is returned if the column number is out of range.
PQfnumber
Returns the column number associated with the given column name.
int PQfnumber(const PGresult *res, const char *column_name);
-1 is returned if the given name does not match any column.
The given name is treated like an identifier in an SQL command, that is, it is downcased unless double-quoted. For example, given a query result generated from the SQL command:
SELECT 1 AS FOO, 2 AS "BAR";
we would have the results:
PQfname(res, 0) foo PQfname(res, 1) BAR PQfnumber(res, "FOO") 0 PQfnumber(res, "foo") 0 PQfnumber(res, "BAR") -1 PQfnumber(res, "\"BAR\"") 1
PQftable
Returns the OID of the table from which the given column was fetched. Column numbers start at 0.
Oid PQftable(const PGresult *res, int column_number);
InvalidOid is returned if the column number is out of range, or if the specified column is not a simple reference to a table column, or when using pre-3.0 protocol. You can query the system table pg_class to determine exactly which table is referenced.
The type Oid and the constant InvalidOid will be defined when you include the libpq header file. They will both be some integer type.
PQftablecol
Returns the column number (within its table) of the column making up the specified query result column. Query-result column numbers start at 0, but table columns have nonzero numbers.
int PQftablecol(const PGresult *res, int column_number);
Zero is returned if the column number is out of range, or if the specified column is not a simple reference to a table column, or when using pre-3.0 protocol.
PQfformat
Returns the format code indicating the format of the given column. Column numbers start at 0.
int PQfformat(const PGresult *res, int column_number);
Format code zero indicates textual data representation, while format code one indicates binary representation. (Other codes are reserved for future definition.)
PQftype
Returns the data type associated with the given column number. The integer returned is the internal OID number of the type. Column numbers start at 0.
Oid PQftype(const PGresult *res, int column_number);
You can query the system table pg_type to obtain the names and properties of the various data types. The OIDs of the built-in data types are defined in the file src/include/catalog/pg_type.h in the source tree.
PQfmod
Returns the type modifier of the column associated with the given column number. Column numbers start at 0.
int PQfmod(const PGresult *res, int column_number);
The interpretation of modifier values is type-specific; they typically indicate precision or size limits. The value -1 is used to indicate "no information available". Most data types do not use modifiers, in which case the value is always -1.
PQfsize
Returns the size in bytes of the column associated with the given column number. Column numbers start at 0.
int PQfsize(const PGresult *res, int column_number);
PQfsize
returns the space allocated for this column in a database row, in other words the size of the server's internal representation of the data type. (Accordingly, it is not really very useful to clients.) A negative value indicates the data type is variable-length.PQbinaryTuples
Returns 1 if the PGresult contains binary data and 0 if it contains text data.
int PQbinaryTuples(const PGresult *res);
This function is deprecated (except for its use in connection with COPY), because it is possible for a single PGresult to contain text data in some columns and binary data in others.
PQfformat
is preferred.PQbinaryTuples
returns 1 only if all columns of the result are binary (format 1).PQgetvalue
Returns a single field value of one row of a PGresult. Row and column numbers start at 0. The caller should not free the result directly. It will be freed when the associated PGresult handle is passed to
PQclear
.char *PQgetvalue(const PGresult *res, int row_number, int column_number);
For data in text format, the value returned by
PQgetvalue
is a null-terminated character string representation of the field value. For data in binary format, the value is in the binary representation determined by the data type'stypsend
andtypreceive
functions. (The value is actually followed by a zero byte in this case too, but that is not ordinarily useful, since the value is likely to contain embedded nulls.)An empty string is returned if the field value is null. See
PQgetisnull
to distinguish null values from empty-string values.The pointer returned by
PQgetvalue
points to storage that is part of the PGresult structure. One should not modify the data it points to, and one must explicitly copy the data into other storage if it is to be used past the lifetime of the PGresult structure itself.PQgetisnull
Tests a field for a null value. Row and column numbers start at 0.
int PQgetisnull(const PGresult *res, int row_number, int column_number);
This function returns 1 if the field is null and 0 if it contains a non-null value. (Note that
PQgetvalue
will return an empty string, not a null pointer, for a null field.)PQgetlength
Returns the actual length of a field value in bytes. Row and column numbers start at 0.
int PQgetlength(const PGresult *res, int row_number, int column_number);
This is the actual data length for the particular data value, that is, the size of the object pointed to by
PQgetvalue
. For text data format this is the same asstrlen()
. For binary format this is essential information. Note that one should not rely onPQfsize
to obtain the actual data length.PQnparams
Returns the number of parameters of a prepared statement.
int PQnparams(const PGresult *res);
This function is only useful when inspecting the result of
PQdescribePrepared
. For other types of queries it will return zero.PQparamtype
Returns the data type of the indicated statement parameter. Parameter numbers start at 0.
Oid PQparamtype(const PGresult *res, int param_number);
This function is only useful when inspecting the result of
PQdescribePrepared
. For other types of queries it will return zero.PQprint
Prints out all the rows and, optionally, the column names to the specified output stream.
void PQprint(FILE *fout, /* output stream */ const PGresult *res, const PQprintOpt *po); typedef struct { pqbool header; /* print output field headings and row count */ pqbool align; /* fill align the fields */ pqbool standard; /* old brain dead format */ pqbool html3; /* output HTML tables */ pqbool expanded; /* expand tables */ pqbool pager; /* use pager for output if needed */ char *fieldSep; /* field separator */ char *tableOpt; /* attributes for HTML table element */ char *caption; /* HTML table caption */ char **fieldName; /* null-terminated array of replacement field names */ } PQprintOpt;
This function was formerly used by psql to print query results, but this is no longer the case. Note that it assumes all the data is in text format.
31.3.3. Retrieving Other Result Information
These functions are used to extract other information from PGresult objects.
PQcmdStatus
Returns the command status tag from the SQL command that generated the PGresult.
char *PQcmdStatus(PGresult *res);
Commonly this is just the name of the command, but it might include additional data such as the number of rows processed. The caller should not free the result directly. It will be freed when the associated PGresult handle is passed to
PQclear
.PQcmdTuples
Returns the number of rows affected by the SQL command.
char *PQcmdTuples(PGresult *res);
This function returns a string containing the number of rows affected by the SQL statement that generated the PGresult. This function can only be used following the execution of a SELECT, CREATE TABLE AS, INSERT, UPDATE, DELETE, MOVE, FETCH, or COPY statement, or an EXECUTE of a prepared query that contains an INSERT, UPDATE, or DELETE statement. If the command that generated the PGresult was anything else,
PQcmdTuples
returns an empty string. The caller should not free the return value directly. It will be freed when the associated PGresult handle is passed toPQclear
.PQoidValue
Returns the OID of the inserted row, if the SQL command was an INSERT that inserted exactly one row into a table that has OIDs, or a EXECUTE of a prepared query containing a suitable INSERT statement. Otherwise, this function returns InvalidOid. This function will also return InvalidOid if the table affected by the INSERT statement does not contain OIDs.
Oid PQoidValue(const PGresult *res);
PQoidStatus
This function is deprecated in favor of
PQoidValue
and is not thread-safe. It returns a string with the OID of the inserted row, whilePQoidValue
returns the OID value.char *PQoidStatus(const PGresult *res);
31.3.4. Escaping Strings for Inclusion in SQL Commands
PQescapeLiteral
char *PQescapeLiteral(PGconn *conn, const char *str, size_t length);
PQescapeLiteral
escapes a string for use within an SQL command. This is useful when inserting data values as literal constants in SQL commands. Certain characters (such as quotes and backslashes) must be escaped to prevent them from being interpreted specially by the SQL parser.PQescapeLiteral
performs this operation.PQescapeLiteral
returns an escaped version of the str parameter in memory allocated withmalloc()
. This memory should be freed usingPQfreemem()
when the result is no longer needed. A terminating zero byte is not required, and should not be counted in length. (If a terminating zero byte is found before length bytes are processed,PQescapeLiteral
stops at the zero; the behavior is thus rather likestrncpy
.) The return string has all special characters replaced so that they can be properly processed by the PostgreSQL string literal parser. A terminating zero byte is also added. The single quotes that must surround PostgreSQL string literals are included in the result string.On error,
PQescapeLiteral
returns NULL and a suitable message is stored in the conn object.Tip: It is especially important to do proper escaping when handling strings that were received from an untrustworthy source. Otherwise there is a security risk: you are vulnerable to "SQL injection" attacks wherein unwanted SQL commands are fed to your database.
Note that it is not necessary nor correct to do escaping when a data value is passed as a separate parameter in
PQexecParams
or its sibling routines.PQescapeIdentifier
char *PQescapeIdentifier(PGconn *conn, const char *str, size_t length);
PQescapeIdentifier
escapes a string for use as an SQL identifier, such as a table, column, or function name. This is useful when a user-supplied identifier might contain special characters that would otherwise not be interpreted as part of the identifier by the SQL parser, or when the identifier might contain upper case characters whose case should be preserved.PQescapeIdentifier
returns a version of the str parameter escaped as an SQL identifier in memory allocated withmalloc()
. This memory must be freed usingPQfreemem()
when the result is no longer needed. A terminating zero byte is not required, and should not be counted in length. (If a terminating zero byte is found before length bytes are processed,PQescapeIdentifier
stops at the zero; the behavior is thus rather likestrncpy
.) The return string has all special characters replaced so that it will be properly processed as an SQL identifier. A terminating zero byte is also added. The return string will also be surrounded by double quotes.On error,
PQescapeIdentifier
returns NULL and a suitable message is stored in the conn object.Tip: As with string literals, to prevent SQL injection attacks, SQL identifiers must be escaped when they are received from an untrustworthy source.
PQescapeStringConn
size_t PQescapeStringConn(PGconn *conn, char *to, const char *from, size_t length, int *error);
PQescapeStringConn
escapes string literals, much likePQescapeLiteral
. UnlikePQescapeLiteral
, the caller is responsible for providing an appropriately sized buffer. Furthermore,PQescapeStringConn
does not generate the single quotes that must surround PostgreSQL string literals; they should be provided in the SQL command that the result is inserted into. The parameter from points to the first character of the string that is to be escaped, and the length parameter gives the number of bytes in this string. A terminating zero byte is not required, and should not be counted in length. (If a terminating zero byte is found before length bytes are processed,PQescapeStringConn
stops at the zero; the behavior is thus rather likestrncpy
.) to shall point to a buffer that is able to hold at least one more byte than twice the value of length, otherwise the behavior is undefined. Behavior is likewise undefined if the to and from strings overlap.If the error parameter is not NULL, then *error is set to zero on success, nonzero on error. Presently the only possible error conditions involve invalid multibyte encoding in the source string. The output string is still generated on error, but it can be expected that the server will reject it as malformed. On error, a suitable message is stored in the conn object, whether or not error is NULL.
PQescapeStringConn
returns the number of bytes written to to, not including the terminating zero byte.PQescapeString
PQescapeString
is an older, deprecated version ofPQescapeStringConn
.size_t PQescapeString (char *to, const char *from, size_t length);
The only difference from
PQescapeStringConn
is thatPQescapeString
does not take PGconn or error parameters. Because of this, it cannot adjust its behavior depending on the connection properties (such as character encoding) and therefore it might give the wrong results. Also, it has no way to report error conditions.PQescapeString
can be used safely in client programs that work with only one PostgreSQL connection at a time (in this case it can find out what it needs to know "behind the scenes"). In other contexts it is a security hazard and should be avoided in favor ofPQescapeStringConn
.PQescapeByteaConn
Escapes binary data for use within an SQL command with the type bytea. As with
PQescapeStringConn
, this is only used when inserting data directly into an SQL command string.unsigned char *PQescapeByteaConn(PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length);
Certain byte values must be escaped when used as part of a bytea literal in an SQL statement.
PQescapeByteaConn
escapes bytes using either hex encoding or backslash escaping. See Section 8.4 for more information.The from parameter points to the first byte of the string that is to be escaped, and the from_length parameter gives the number of bytes in this binary string. (A terminating zero byte is neither necessary nor counted.) The to_length parameter points to a variable that will hold the resultant escaped string length. This result string length includes the terminating zero byte of the result.
PQescapeByteaConn
returns an escaped version of the from parameter binary string in memory allocated withmalloc()
. This memory should be freed usingPQfreemem()
when the result is no longer needed. The return string has all special characters replaced so that they can be properly processed by the PostgreSQL string literal parser, and the bytea input function. A terminating zero byte is also added. The single quotes that must surround PostgreSQL string literals are not part of the result string.On error, a null pointer is returned, and a suitable error message is stored in the conn object. Currently, the only possible error is insufficient memory for the result string.
PQescapeBytea
PQescapeBytea
is an older, deprecated version ofPQescapeByteaConn
.unsigned char *PQescapeBytea(const unsigned char *from, size_t from_length, size_t *to_length);
The only difference from
PQescapeByteaConn
is thatPQescapeBytea
does not take a PGconn parameter. Because of this,PQescapeBytea
can only be used safely in client programs that use a single PostgreSQL connection at a time (in this case it can find out what it needs to know "behind the scenes"). It might give the wrong results if used in programs that use multiple database connections (usePQescapeByteaConn
in such cases).PQunescapeBytea
Converts a string representation of binary data into binary data — the reverse of
PQescapeBytea
. This is needed when retrieving bytea data in text format, but not when retrieving it in binary format.unsigned char *PQunescapeBytea(const unsigned char *from, size_t *to_length);
The from parameter points to a string such as might be returned by
PQgetvalue
when applied to a bytea column.PQunescapeBytea
converts this string representation into its binary representation. It returns a pointer to a buffer allocated withmalloc()
, or NULL on error, and puts the size of the buffer in to_length. The result must be freed usingPQfreemem
when it is no longer needed.This conversion is not exactly the inverse of
PQescapeBytea
, because the string is not expected to be "escaped" when received fromPQgetvalue
. In particular this means there is no need for string quoting considerations, and so no need for a PGconn parameter.