39.6. Библиотека pgtypes #
Библиотека pgtypes сопоставляет типы базы данных Postgres Pro с их эквивалентами в C, которые можно использовать в программах на C. Она также предлагает функции для выполнения простых вычислений с этими типами в C, то есть без помощи сервера Postgres Pro. Рассмотрите следующий пример:
EXEC SQL BEGIN DECLARE SECTION;
date date1;
timestamp ts1, tsout;
interval iv1;
char *out;
EXEC SQL END DECLARE SECTION;
PGTYPESdate_today(&date1);
EXEC SQL SELECT started, duration INTO :ts1, :iv1 FROM datetbl WHERE d=:date1;
PGTYPEStimestamp_add_interval(&ts1, &iv1, &tsout);
out = PGTYPEStimestamp_to_asc(&tsout);
printf("Started + duration: %s\n", out);
PGTYPESchar_free(out);
39.6.1. Символьные строки #
Некоторые функции, в частности PGTYPESnumeric_to_asc, возвращают указатель на строку в выделенной для неё памяти. Их результаты должны освобождаться функцией PGTYPESchar_free, а не free. (Это важно только в Windows, где выделение и освобождение памяти в определённых случаях должно производиться одной библиотекой.)
39.6.2. Тип numeric #
Тип numeric позволяет производить вычисления с произвольной точностью. Эквивалентный ему тип на сервере Postgres Pro описан в Разделе 8.1. Ввиду того, что переменная имеет произвольную точность, она должна расширяться и сжиматься динамически. Поэтому такие переменные можно создавать только в области кучи, используя функции PGTYPESnumeric_new и PGTYPESnumeric_free. Тип decimal подобен numeric, но имеет ограниченную точность, и поэтому может размещаться и в области кучи, и в стеке.
Для работы с типом numeric можно использовать следующие функции:
PGTYPESnumeric_new#Запрашивает указатель на новую переменную, размещённую в памяти.
numeric *PGTYPESnumeric_new(void);
PGTYPESnumeric_free#Освобождает переменную типа numeric, высвобождая всю её память.
void PGTYPESnumeric_free(numeric *var);
PGTYPESnumeric_from_asc#Разбирает числовой тип из строковой записи.
numeric *PGTYPESnumeric_from_asc(char *str, char **endptr);
Допускаются в частности следующие форматы:
-2,.794,+3.44,592.49E07и-32.84e-4. Если значение удаётся разобрать успешно, возвращается действительный указатель, в противном случае указатель NULL. На данный момент ECPG всегда разбирает строку до конца, так что эта функция не может вернуть адрес первого недопустимого символа в*endptr. Поэтому вendptrсвободно можно передать NULL.PGTYPESnumeric_to_asc#Возвращает указатель на строку, выделенную функцией
mallocи содержащую строковое представление значенияnumчислового типа.char *PGTYPESnumeric_to_asc(numeric *num, int dscale);
Числовое значение будет выводиться с заданным в
dscaleколичеством цифр после запятой, округлённое при необходимости. Результат нужно освободить функциейPGTYPESchar_free().PGTYPESnumeric_add#Суммирует две числовые переменные и возвращает результат в третьей.
int PGTYPESnumeric_add(numeric *var1, numeric *var2, numeric *result);
Эта функция суммирует переменные
var1иvar2в результирующую переменнуюresult. Функция возвращает 0 в случае успеха и -1 при ошибке.PGTYPESnumeric_sub#Вычисляет разность двух числовых переменных и возвращает результат в третьей.
int PGTYPESnumeric_sub(numeric *var1, numeric *var2, numeric *result);
Эта функция вычитает переменную
var2изvar1. Результат операции помещается в переменнуюresult. Функция возвращает 0 в случае успеха и -1 при ошибке.PGTYPESnumeric_mul#Перемножает две числовые переменные и возвращает результат в третьей.
int PGTYPESnumeric_mul(numeric *var1, numeric *var2, numeric *result);
Эта функция перемножает переменные
var1иvar2. Результат операции сохраняется в переменнойresult. Функция возвращает 0 в случае успеха и -1 при ошибке.PGTYPESnumeric_div#Вычисляет частное двух числовых переменных и возвращает результат в третьей.
int PGTYPESnumeric_div(numeric *var1, numeric *var2, numeric *result);
Эта функция делит переменную
var1наvar2. Результат операции сохраняется в переменнойresult. Функция возвращает 0 в случае успеха и -1 при ошибке.PGTYPESnumeric_cmp#Сравнивает две числовые переменные.
int PGTYPESnumeric_cmp(numeric *var1, numeric *var2)
Эта функция производит сравнение двух числовых переменных. При ошибке возвращается
INT_MAX. В случае успеха функция возвращает одно из трёх возможных значений:1, если
var1большеvar2-1, если
var1меньшеvar20, если
var1иvar2равны
PGTYPESnumeric_from_int#Преобразует переменную int в переменную numeric.
int PGTYPESnumeric_from_int(signed int int_val, numeric *var);
Эта функция принимает целочисленную переменную со знаком типа signed int и сохраняет её значение в переменной
varтипа numeric. Функция возвращает 0 в случае успеха и -1 при ошибке.PGTYPESnumeric_from_long#Преобразует переменную long int в переменную numeric.
int PGTYPESnumeric_from_long(signed long int long_val, numeric *var);
Эта функция принимает целочисленную переменную со знаком типа signed long int и сохраняет её значение в переменной
varтипа numeric. Функция возвращает 0 в случае успеха и -1 при ошибке.PGTYPESnumeric_copy#Копирует одну числовую переменную в другую.
int PGTYPESnumeric_copy(numeric *src, numeric *dst);
Эта функция копирует значение переменной, на которую указывает
src, в переменную, на которую указываетdst. Она возвращает 0 в случае успеха и -1 при ошибке.PGTYPESnumeric_from_double#Преобразует переменную типа double в переменную numeric.
int PGTYPESnumeric_from_double(double d, numeric *dst);
Эта функция принимает переменную типа double и сохраняет преобразованное значение в переменной, на которую указывает
dst. Она возвращает 0 в случае успеха и -1 при ошибке.PGTYPESnumeric_to_double#Преобразует переменную типа numeric в переменную double.
int PGTYPESnumeric_to_double(numeric *nv, double *dp)
Эта функция преобразует значение типа numeric переменной, на которую указывает
nv, в переменную типа double, на которую указываетdp. Она возвращает 0 в случае успеха и -1 при ошибке, в том числе при переполнении. Если происходит переполнение, в глобальной переменнойerrnoдополнительно устанавливается значениеPGTYPES_NUM_OVERFLOW.PGTYPESnumeric_to_int#Преобразует переменную типа numeric в переменную int.
int PGTYPESnumeric_to_int(numeric *nv, int *ip);
Эта функция преобразует значение типа numeric переменной, на которую указывает
nv, в целочисленную переменную, на которую указываетip. Она возвращает 0 в случае успеха и -1 при ошибке, в том числе при переполнении. Если происходит переполнение, в глобальной переменнойerrnoдополнительно устанавливается значениеPGTYPES_NUM_OVERFLOW.PGTYPESnumeric_to_long#Преобразует переменную типа numeric в переменную long.
int PGTYPESnumeric_to_long(numeric *nv, long *lp);
Эта функция преобразует значение типа numeric переменной, на которую указывает
nv, в целочисленную переменную типа long, на которую указываетlp. Она возвращает 0 в случае успеха и -1 при ошибке, в том числе при переполнении. Если происходит переполнение, в глобальной переменнойerrnoдополнительно устанавливается значениеPGTYPES_NUM_OVERFLOW.PGTYPESnumeric_to_decimal#Преобразует переменную типа numeric в переменную decimal.
int PGTYPESnumeric_to_decimal(numeric *src, decimal *dst);
Эта функция преобразует значение типа numeric переменной, на которую указывает
src, в переменную типа decimal, на которую указываетdst. Она возвращает 0 в случае успеха и -1 при ошибке, в том числе при переполнении. Если происходит переполнение, в глобальной переменнойerrnoдополнительно устанавливается значениеPGTYPES_NUM_OVERFLOW.PGTYPESnumeric_from_decimal#Преобразует переменную типа decimal в переменную numeric.
int PGTYPESnumeric_from_decimal(decimal *src, numeric *dst);
Эта функция преобразует значение типа decimal переменной, на которую указывает
src, в переменную типа numeric, на которую указываетdst. Она возвращает 0 в случае успеха и -1 при ошибке. Так как тип decimal реализован как ограниченная версия типа numeric, при таком преобразовании переполнение невозможно.
39.6.3. Тип date #
Тип date, реализованный в C, позволяет программам работать с данными типа date в SQL. Соответствующий тип сервера Postgres Pro описан в Разделе 8.5.
Для работы с типом date можно использовать следующие функции:
PGTYPESdate_from_timestamp#Извлекает часть даты из значения типа timestamp.
date PGTYPESdate_from_timestamp(timestamp dt);
Эта функция получает в единственном аргументе значение времени типа timestamp и возвращает извлечённую из него дату.
PGTYPESdate_from_asc#Разбирает дату из её текстового представления.
date PGTYPESdate_from_asc(char *str, char **endptr);
Эта функция получает строку C char*
strи указатель на строку C char*endptr. На данный момент ECPG всегда разбирает строку до конца, так что эта функция не может вернуть адрес первого недопустимого символа в*endptr. Поэтому вendptrсвободно можно передать NULL.Заметьте, что эта функция всегда подразумевает формат дат MDY (месяц-день-год) и никакой переменной для изменения этого формата в ECPG нет.
Все допустимые форматы ввода перечислены в Таблице 39.2.
Таблица 39.2. Допустимые форматы ввода для
PGTYPESdate_from_ascВвод Результат January 8, 1999January 8, 19991999-01-08January 8, 19991/8/1999January 8, 19991/18/1999January 18, 199901/02/03February 1, 20031999-Jan-08January 8, 1999Jan-08-1999January 8, 199908-Jan-1999January 8, 199999-Jan-08January 8, 199908-Jan-99January 8, 199908-Jan-06January 8, 2006Jan-08-99January 8, 199919990108ISO 8601; January 8, 1999990108ISO 8601; January 8, 19991999.008год и день годаJ2451187Юлианский деньJanuary 8, 99 BC99 год до нашей эрыPGTYPESdate_to_asc#Возвращает текстовое представление переменной типа date.
char *PGTYPESdate_to_asc(date dDate);
Эта функция получает в качестве единственного параметра дату
dDateи выводит её в виде1999-01-18, то есть в форматеYYYY-MM-DD. Результат необходимо освободить функциейPGTYPESchar_free().PGTYPESdate_julmdy#Извлекает значения дня, месяца и года из переменной типа date.
void PGTYPESdate_julmdy(date d, int *mdy);
Эта функция получает дату
dи указатель на 3 целочисленных значенияmdy. Имя переменной указывает на порядок значений: вmdy[0]записывается номер месяца, вmdy[1]— номер дня, а вmdy[2]— год.PGTYPESdate_mdyjul#Образует значение даты из массива 3 целых чисел, задающих день, месяц и год даты.
void PGTYPESdate_mdyjul(int *mdy, date *jdate);
Эта функция получает в первом аргументе массив из 3 целых чисел (
mdy), а во втором указатель на переменную типа date, в которую будет помещён результат операции.PGTYPESdate_dayofweek#Возвращает число, представляющее день недели для заданной даты.
int PGTYPESdate_dayofweek(date d);
Эта функция принимает в единственном аргументе переменную
dтипа date и возвращает целое число, выражающее день недели для этой даты.0 — Воскресенье
1 — Понедельник
2 — Вторник
3 — Среда
4 — Четверг
5 — Пятница
6 — Суббота
PGTYPESdate_today#Выдаёт текущую дату.
void PGTYPESdate_today(date *d);
Эта функция получает указатель на переменную (
d) типа date, в которую будет записана текущая дата.PGTYPESdate_fmt_asc#Преобразует переменную типа date в текстовое представление по маске формата.
int PGTYPESdate_fmt_asc(date dDate, char *fmtstring, char *outbuf);
Эта функция принимает дату для преобразования (
dDate), маску формата (fmtstring) и строку, в которую будет помещено текстовое представление даты (outbuf).В случае успеха возвращается 0, а в случае ошибки — отрицательное значение.
В строке формата можно использовать следующие коды полей:
dd— Номер дня в месяце.mm— Номер месяца в году.yy— Номер года в виде двух цифр.yyyy— Номер года в виде четырёх цифр.ddd— Название дня недели (сокращённое).mmm— Название месяца (сокращённое).
Все другие символы копируются в выводимую строку 1:1.
В Таблице 39.3 перечислены несколько возможных форматов. Это даёт представление, как можно использовать эту функцию. Все строки вывода даны для одной даты: 23 ноября 1959 г.
Таблица 39.3. Допустимые форматы ввода для
PGTYPESdate_fmt_ascФормат Результат mmddyy112359ddmmyy231159yymmdd591123yy/mm/dd59/11/23yy mm dd59 11 23yy.mm.dd59.11.23.mm.yyyy.dd..11.1959.23.mmm. dd, yyyyNov. 23, 1959mmm dd yyyyNov 23 1959yyyy dd mm1959 23 11ddd, mmm. dd, yyyyMon, Nov. 23, 1959(ddd) mmm. dd, yyyy(Mon) Nov. 23, 1959PGTYPESdate_defmt_asc#Преобразует строку C
char*в значение типа date по маске формата.int PGTYPESdate_defmt_asc(date *d, char *fmt, char *str);
Эта функция принимает указатель на переменную типа date (
d), в которую будет помещён результат операции, маску формата для разбора даты (fmt) и строку C char*, содержащую текстовое представление даты (str). Ожидается, что текстовое представление будет соответствовать маске формата. Однако это соответствие не обязательно должно быть точным. Данная функция анализирует только порядок элементов и ищет в нём подстрокиyyилиyyyy, обозначающие позицию года, подстрокуmm, обозначающую позицию месяца, иdd, обозначающую позицию дня.В Таблица 39.4 перечислены несколько возможных форматов. Это даёт представление, как можно использовать эту функцию.
Таблица 39.4. Допустимые форматы ввода для
rdefmtdateФормат Строка Результат ddmmyy21-2-541954-02-21ddmmyy2-12-541954-12-02ddmmyy201119541954-11-20ddmmyy1304641964-04-13mmm.dd.yyyyMAR-12-19671967-03-12yy/mm/dd1954, February 3rd1954-02-03mmm.dd.yyyy0412691969-04-12yy/mm/ddIn the year 2525, in the month of July, mankind will be alive on the 28th day2525-07-28dd-mm-yyI said on the 28th of July in the year 25252525-07-28mmm.dd.yyyy9/14/581958-09-14yy/mm/dd47/03/291947-03-29mmm.dd.yyyyoct 28 19751975-10-28mmddyyNov 14th, 19851985-11-14
39.6.4. Тип timestamp #
Тип timestamp, реализованный в C, позволяет программам работать с данными типа timestamp в SQL. Соответствующий тип сервера Postgres Pro описан в Разделе 8.5.
Для работы с типом timestamp можно использовать следующие функции:
PGTYPEStimestamp_from_asc#Разбирает значение даты/времени из текстового представления в переменную типа timestamp.
timestamp PGTYPEStimestamp_from_asc(char *str, char **endptr);
Эта функция получает строку (
str), которую нужно разобрать, и указатель на строку C char* (endptr). На данный момент ECPG всегда разбирает строку до конца, так что эта функция не может вернуть адрес первого недопустимого символа в*endptr. Поэтому вendptrсвободно можно передать NULL.В случае успеха эта функция возвращает разобранное время, а в случае ошибки возвращается
PGTYPESInvalidTimestampи вerrnoустанавливается значениеPGTYPES_TS_BAD_TIMESTAMP. См. замечание относительноPGTYPESInvalidTimestamp.Вообще вводимая строка может содержать допустимое указание даты, пробельные символы и допустимое указание времени в любом сочетании. Заметьте, что часовые пояса ECPG не поддерживает. Эта функция может разобрать их, но не задействует их в вычислениях как это делает, например, сервер Postgres Pro. Указания часового пояса во вводимой строке просто игнорируются.
В Таблица 39.5 приведены несколько примеров вводимых строк.
Таблица 39.5. Допустимые форматы ввода для
PGTYPEStimestamp_from_ascВвод Результат 1999-01-08 04:05:061999-01-08 04:05:06January 8 04:05:06 1999 PST1999-01-08 04:05:061999-Jan-08 04:05:06.789-81999-01-08 04:05:06.789 (указание часового пояса игнорируется)J2451187 04:05-08:001999-01-08 04:05:00 (указание часового пояса игнорируется)PGTYPEStimestamp_to_asc#Преобразует значение даты в строку C char*.
char *PGTYPEStimestamp_to_asc(timestamp tstamp);
Эта функция принимает в качестве единственного аргумента
tstampзначение типа timestamp и возвращает размещённую в памяти строку, содержащую текстовое представление даты/времени. Результат необходимо освободить функциейPGTYPESchar_free().PGTYPEStimestamp_current#Получает текущее время.
void PGTYPEStimestamp_current(timestamp *ts);
Эта функция получает текущее время и сохраняет его в переменной типа timestamp, на которую указывает
ts.PGTYPEStimestamp_fmt_asc#Преобразует переменную типа timestamp в строку C char* по маске формата.
int PGTYPEStimestamp_fmt_asc(timestamp *ts, char *output, int str_len, char *fmtstr);
Эта функция получает в первом аргументе (
ts) указатель на переменную типа timestamp, а в последующих указатель на буфер вывода (output), максимальную длину строки, которую может принять буфер (str_len), и маску формата, с которой будет выполняться преобразование (fmtstr).В случае успеха возвращается 0, а в случае ошибки — отрицательное значение.
В маске формата можно использовать коды формата, перечисленные ниже. Эти же коды принимает функция
strftimeиз библиотеки libc. Любые символы, не относящиеся к кодам формата, будут просто скопированы в буфер вывода.%A— заменяется локализованным представлением полного названия дня недели.%a— заменяется локализованным представлением сокращённого названия дня недели.%B— заменяется локализованным представлением полного названия месяца.%b— заменяется локализованным представлением сокращённого названия месяца.%C— заменяется столетием (год / 100) в виде десятичного числа; одиночная цифра предваряется нулём.%c— заменяется локализованным представлением даты и времени.%D— равнозначно%m/%d/%y.%d— заменяется днём месяца в виде десятичного числа (01–31).%E*%O*— расширения локали POSIX. Последовательности%Ec%EC%Ex%EX%Ey%EY%Od%Oe%OH%OI%Om%OM%OS%Ou%OU%OV%Ow%OW%Oyдолжны выводить альтернативные представления.Кроме того, альтернативные названия месяцев представляет код формата
%OB(используется отдельно, без упоминания дня).%e— заменяется днём в виде десятичного числа (1–31); одиночная цифра предваряется пробелом.%F— равнозначно%Y-%m-%d.%G— заменяется годом в виде десятичного числа (со столетием). При этом годом считается тот, что содержит наибольшую часть недели (дни недели начинаются с понедельника).%g— заменяется тем же годом, что и%G, но в виде десятичного числа без столетия (00–99).%H— заменяется часами (в 24-часовом формате) в виде десятичного числа (00–23).%h— равнозначно%b.%I— заменяется часами (в 12-часовом формате) в виде десятичного числа (01–12).%j— заменяется днём года в виде десятичного числа (001–366).%k— заменяется часами (в 24-часовом формате) в виде десятичного числа (0–23); одиночная цифра предваряется пробелом.%l— заменяется часами (в 12-часовом формате) в виде десятичного числа (1–12); одиночная цифра предваряется пробелом.%M— заменяется минутами в виде десятичного числа (00–59).%m— заменяется номером месяца в виде десятичного числа (01–12).%n— заменяется символом новой строки.%O*— равнозначно%E*.%p— заменяется локализованным представлением «до полудня» или «после полудня» в зависимости от времени.%R— равнозначно%H:%M.%r— равнозначно%I:%M:%S %p.%S— заменяется секундами в виде десятичного числа (00–60).%s— заменяется числом секунд с начала эпохи, по мировому времени (UTC).%T— равнозначно%H:%M:%S%t— заменяется символом табуляции.%U— заменяется номером недели в году (первым днём недели считается воскресенье) в виде десятичного числа (00–53).%u— заменяется номером дня недели (первым днём недели считается понедельник) в виде десятичного числа (1–7).%V— заменяется номером недели в году (первым днём недели считается понедельник) в виде десятичного числа (01–53). Если к недели, включающей 1 января, относятся 4 или больше дней нового года, она считается неделей с номером 1; в противном случае это последняя неделя предыдущего года, а неделей под номером 1 будет следующая.%v— равнозначно%e-%b-%Y.%W— заменяется номером недели в году (первым днём недели считается понедельник) в виде десятичного числа (00–53).%w— заменяется номером дня недели (первым днём недели считается воскресенье) в виде десятичного числа (0–6).%X— заменяется локализованным представлением времени.%x— заменяется локализованным представлением даты.%Y— заменяется годом со столетием в виде десятичного числа.%y— заменяется годом без столетия в виде десятичного числа (00–99).%Z— заменяется названием часового пояса.%z— заменяется смещением часового пояса от UTC; ведущий знак плюс обозначает смещение к востоку от UTC, а знак минус — к западу, часы и минуты задаются парами цифр без разделителя между ними (эта форма установлена для даты в RFC 822).%+— заменяется локализованным представлением даты и времени.%-*— расширение GNU libc. Отключает дополнение чисел по ширине при выводе.$_* — расширение GNU libc. Явно включает дополнение пробелами.
%0*— расширение GNU libc. Явно включает дополнение нулями.%%— заменяется символом%.
PGTYPEStimestamp_sub#Вычитает одно значение времени из другого и сохраняет результат в переменной типа interval.
int PGTYPEStimestamp_sub(timestamp *ts1, timestamp *ts2, interval *iv);
Эта функция вычитает значение типа timestamp, на которое указывает
ts2, из значения timestamp, на которое указываетts1, и сохраняет результат в переменной типа interval, на которую указываетiv.В случае успеха возвращается 0, а в случае ошибки — отрицательное значение.
PGTYPEStimestamp_defmt_asc#Разбирает значение типа timestamp из текстового представления с заданной маской формата.
int PGTYPEStimestamp_defmt_asc(char *str, char *fmt, timestamp *d);
Эта функция получает текстовое представление даты/времени в переменной
str, а также маску формата для разбора в переменнойfmt. Результат будет сохранён в переменной, на которую указываетd.Если вместо маски формата
fmtпередаётся NULL, эта функция переходит к стандартной маске форматирования, а именно:%Y-%m-%d %H:%M:%S.Данная функция является обратной к функции
PGTYPEStimestamp_fmt_asc. Обратитесь к её документации, чтобы узнать о возможных вариантах маски формата.PGTYPEStimestamp_add_interval#Добавляет переменную типа interval к переменной типа timestamp.
int PGTYPEStimestamp_add_interval(timestamp *tin, interval *span, timestamp *tout);
Эта функция получает указатель на переменную
tinтипа timestamp и указатель на переменнуюspanтипа interval. Она добавляет временной интервал к значению даты/времени и сохраняет полученную дату и время в переменной типа timestamp, на которую указываетtout.В случае успеха возвращается 0, а в случае ошибки — отрицательное значение.
PGTYPEStimestamp_sub_interval#Вычитает переменную типа interval из переменной типа timestamp.
int PGTYPEStimestamp_sub_interval(timestamp *tin, interval *span, timestamp *tout);
Эта функция вычитает значение типа interval, на которое указывает
span, из значения типа timestamp, на которое указываетtin, и сохраняет результат в переменной, на которую указываетtout.В случае успеха возвращается 0, а в случае ошибки — отрицательное значение.
39.6.5. Тип interval #
Тип interval, реализованный в C, позволяет программам работать с данными типа interval в SQL. Соответствующий тип сервера Postgres Pro описан в Разделе 8.5.
Для работы с типом interval можно использовать следующие функции:
PGTYPESinterval_new#Возвращает указатель на новую переменную interval, размещённую в памяти.
interval *PGTYPESinterval_new(void);
PGTYPESinterval_free#Освобождает место, занимаемое ранее размещённой в памяти переменной типа interval.
void PGTYPESinterval_free(interval *intvl);
PGTYPESinterval_from_asc#Разбирает значение типа interval из его текстового представления.
interval *PGTYPESinterval_from_asc(char *str, char **endptr);
Эта функция разбирает входную строку
strи возвращает указатель на размещённую в памяти переменную типа interval. На данный момент ECPG всегда разбирает строку до конца, так что эта функция не может вернуть адрес первого недопустимого символа в*endptr. Поэтому вendptrсвободно можно передать NULL.PGTYPESinterval_to_asc#Преобразует переменную типа interval в текстовое представление.
char *PGTYPESinterval_to_asc(interval *span);
Эта функция преобразует переменную типа interval, на которую указывает
span, в строку C char*. Её вывод выглядит примерно так:@ 1 day 12 hours 59 mins 10 secs. Результат необходимо освободить функциейPGTYPESchar_free().PGTYPESinterval_copy#Копирует переменную типа interval.
int PGTYPESinterval_copy(interval *intvlsrc, interval *intvldest);
Эта функция копирует переменную типа interval, на которую указывает
intvlsrc, в переменную, на которую указываетintvldest. Заметьте, что для целевой переменной необходимо предварительно выделить память.
39.6.6. Тип decimal #
Тип decimal похож на тип numeric, однако его максимальная точность ограничена 30 значащими цифрами. В отличие от типа numeric, который можно создать только в области кучи, тип decimal можно создать и в стеке, и в области кучи (посредством функций PGTYPESdecimal_new и PGTYPESdecimal_free). Для работы с типом decimal есть много других функций, подключаемых в режиме совместимости с Informix, описанном в Разделе 39.15.
Для работы с типом decimal можно использовать следующие функции (содержащиеся не в библиотеке libcompat).
39.6.7. Значения errno, которые устанавливает pgtypeslib #
PGTYPES_NUM_BAD_NUMERIC#Аргумент должен содержать переменную типа numeric (либо указывать на переменную типа numeric), но представление этого типа в памяти оказалось некорректным.
PGTYPES_NUM_OVERFLOW#Произошло переполнение. Так как тип numeric может принимать значения практически любой точности, при преобразовании этого типа в другие типы возможно переполнение.
PGTYPES_NUM_UNDERFLOW#Произошло антипереполнение. Так как тип numeric может принимать значения практически любой точности, при преобразовании переменной этого типа в другие типы возможно антипереполнение.
PGTYPES_NUM_DIVIDE_ZERO#Имела место попытка деления на ноль.
PGTYPES_DATE_BAD_DATE#Функции
PGTYPESdate_from_ascпередана некорректная строка даты.PGTYPES_DATE_ERR_EARGS#Функции
PGTYPESdate_defmt_ascпереданы некорректные аргументы.PGTYPES_DATE_ERR_ENOSHORTDATE#В строке, переданной функции
PGTYPESdate_defmt_asc, оказался неправильный компонент даты.PGTYPES_INTVL_BAD_INTERVAL#Функции
PGTYPESinterval_from_ascпередана некорректная строка, задающая интервал, либо функцииPGTYPESinterval_to_ascпередано некорректное значение интервала.PGTYPES_DATE_ERR_ENOTDMY#Обнаружено несоответствие при выводе компонентов день/месяц/год в функции
PGTYPESdate_defmt_asc.PGTYPES_DATE_BAD_DAY#Функция
PGTYPESdate_defmt_ascобнаружила некорректное значение дня месяца.PGTYPES_DATE_BAD_MONTH#Функция
PGTYPESdate_defmt_ascобнаружила некорректное значение месяца.PGTYPES_TS_BAD_TIMESTAMP#Функции
PGTYPEStimestamp_from_ascпередана некорректная строка даты/времени, либо функцииPGTYPEStimestamp_to_ascпередано некорректное значение типа timestamp.PGTYPES_TS_ERR_EINFTIME#Значение типа timestamp, представляющее бесконечность, получено в недопустимом контексте.
39.6.8. Специальные константы pgtypeslib #
PGTYPESInvalidTimestamp#Значение типа timestamp, представляющее недопустимое время. Это значение возвращает функция
PGTYPEStimestamp_from_ascпри ошибке разбора. Заметьте, что вследствие особенности внутреннего представления типаtimestamp, значениеPGTYPESInvalidTimestampв то же время представляет корректное время (1899-12-31 23:59:59). Поэтому для выявления ошибок необходимо, чтобы приложение не только сравнивало результат функции сPGTYPESInvalidTimestamp, но и проверяло условиеerrno != 0после каждого вызоваPGTYPEStimestamp_from_asc.
39.6. pgtypes Library #
The pgtypes library maps Postgres Pro database types to C equivalents that can be used in C programs. It also offers functions to do basic calculations with those types within C, i.e., without the help of the Postgres Pro server. See the following example:
EXEC SQL BEGIN DECLARE SECTION;
date date1;
timestamp ts1, tsout;
interval iv1;
char *out;
EXEC SQL END DECLARE SECTION;
PGTYPESdate_today(&date1);
EXEC SQL SELECT started, duration INTO :ts1, :iv1 FROM datetbl WHERE d=:date1;
PGTYPEStimestamp_add_interval(&ts1, &iv1, &tsout);
out = PGTYPEStimestamp_to_asc(&tsout);
printf("Started + duration: %s\n", out);
PGTYPESchar_free(out);
39.6.1. Character Strings #
Some functions such as PGTYPESnumeric_to_asc return a pointer to a freshly allocated character string. These results should be freed with PGTYPESchar_free instead of free. (This is important only on Windows, where memory allocation and release sometimes need to be done by the same library.)
39.6.2. The numeric Type #
The numeric type offers to do calculations with arbitrary precision. See Section 8.1 for the equivalent type in the Postgres Pro server. Because of the arbitrary precision this variable needs to be able to expand and shrink dynamically. That's why you can only create numeric variables on the heap, by means of the PGTYPESnumeric_new and PGTYPESnumeric_free functions. The decimal type, which is similar but limited in precision, can be created on the stack as well as on the heap.
The following functions can be used to work with the numeric type:
PGTYPESnumeric_new#Request a pointer to a newly allocated numeric variable.
numeric *PGTYPESnumeric_new(void);
PGTYPESnumeric_free#Free a numeric type, release all of its memory.
void PGTYPESnumeric_free(numeric *var);
PGTYPESnumeric_from_asc#Parse a numeric type from its string notation.
numeric *PGTYPESnumeric_from_asc(char *str, char **endptr);
Valid formats are for example:
-2,.794,+3.44,592.49E07or-32.84e-4. If the value could be parsed successfully, a valid pointer is returned, else the NULL pointer. At the moment ECPG always parses the complete string and so it currently does not support to store the address of the first invalid character in*endptr. You can safely setendptrto NULL.PGTYPESnumeric_to_asc#Returns a pointer to a string allocated by
mallocthat contains the string representation of the numeric typenum.char *PGTYPESnumeric_to_asc(numeric *num, int dscale);
The numeric value will be printed with
dscaledecimal digits, with rounding applied if necessary. The result must be freed withPGTYPESchar_free().PGTYPESnumeric_add#Add two numeric variables into a third one.
int PGTYPESnumeric_add(numeric *var1, numeric *var2, numeric *result);
The function adds the variables
var1andvar2into the result variableresult. The function returns 0 on success and -1 in case of error.PGTYPESnumeric_sub#Subtract two numeric variables and return the result in a third one.
int PGTYPESnumeric_sub(numeric *var1, numeric *var2, numeric *result);
The function subtracts the variable
var2from the variablevar1. The result of the operation is stored in the variableresult. The function returns 0 on success and -1 in case of error.PGTYPESnumeric_mul#Multiply two numeric variables and return the result in a third one.
int PGTYPESnumeric_mul(numeric *var1, numeric *var2, numeric *result);
The function multiplies the variables
var1andvar2. The result of the operation is stored in the variableresult. The function returns 0 on success and -1 in case of error.PGTYPESnumeric_div#Divide two numeric variables and return the result in a third one.
int PGTYPESnumeric_div(numeric *var1, numeric *var2, numeric *result);
The function divides the variables
var1byvar2. The result of the operation is stored in the variableresult. The function returns 0 on success and -1 in case of error.PGTYPESnumeric_cmp#Compare two numeric variables.
int PGTYPESnumeric_cmp(numeric *var1, numeric *var2)
This function compares two numeric variables. In case of error,
INT_MAXis returned. On success, the function returns one of three possible results:1, if
var1is bigger thanvar2-1, if
var1is smaller thanvar20, if
var1andvar2are equal
PGTYPESnumeric_from_int#Convert an int variable to a numeric variable.
int PGTYPESnumeric_from_int(signed int int_val, numeric *var);
This function accepts a variable of type signed int and stores it in the numeric variable
var. Upon success, 0 is returned and -1 in case of a failure.PGTYPESnumeric_from_long#Convert a long int variable to a numeric variable.
int PGTYPESnumeric_from_long(signed long int long_val, numeric *var);
This function accepts a variable of type signed long int and stores it in the numeric variable
var. Upon success, 0 is returned and -1 in case of a failure.PGTYPESnumeric_copy#Copy over one numeric variable into another one.
int PGTYPESnumeric_copy(numeric *src, numeric *dst);
This function copies over the value of the variable that
srcpoints to into the variable thatdstpoints to. It returns 0 on success and -1 if an error occurs.PGTYPESnumeric_from_double#Convert a variable of type double to a numeric.
int PGTYPESnumeric_from_double(double d, numeric *dst);
This function accepts a variable of type double and stores the result in the variable that
dstpoints to. It returns 0 on success and -1 if an error occurs.PGTYPESnumeric_to_double#Convert a variable of type numeric to double.
int PGTYPESnumeric_to_double(numeric *nv, double *dp)
The function converts the numeric value from the variable that
nvpoints to into the double variable thatdppoints to. It returns 0 on success and -1 if an error occurs, including overflow. On overflow, the global variableerrnowill be set toPGTYPES_NUM_OVERFLOWadditionally.PGTYPESnumeric_to_int#Convert a variable of type numeric to int.
int PGTYPESnumeric_to_int(numeric *nv, int *ip);
The function converts the numeric value from the variable that
nvpoints to into the integer variable thatippoints to. It returns 0 on success and -1 if an error occurs, including overflow. On overflow, the global variableerrnowill be set toPGTYPES_NUM_OVERFLOWadditionally.PGTYPESnumeric_to_long#Convert a variable of type numeric to long.
int PGTYPESnumeric_to_long(numeric *nv, long *lp);
The function converts the numeric value from the variable that
nvpoints to into the long integer variable thatlppoints to. It returns 0 on success and -1 if an error occurs, including overflow. On overflow, the global variableerrnowill be set toPGTYPES_NUM_OVERFLOWadditionally.PGTYPESnumeric_to_decimal#Convert a variable of type numeric to decimal.
int PGTYPESnumeric_to_decimal(numeric *src, decimal *dst);
The function converts the numeric value from the variable that
srcpoints to into the decimal variable thatdstpoints to. It returns 0 on success and -1 if an error occurs, including overflow. On overflow, the global variableerrnowill be set toPGTYPES_NUM_OVERFLOWadditionally.PGTYPESnumeric_from_decimal#Convert a variable of type decimal to numeric.
int PGTYPESnumeric_from_decimal(decimal *src, numeric *dst);
The function converts the decimal value from the variable that
srcpoints to into the numeric variable thatdstpoints to. It returns 0 on success and -1 if an error occurs. Since the decimal type is implemented as a limited version of the numeric type, overflow cannot occur with this conversion.
39.6.3. The date Type #
The date type in C enables your programs to deal with data of the SQL type date. See Section 8.5 for the equivalent type in the Postgres Pro server.
The following functions can be used to work with the date type:
PGTYPESdate_from_timestamp#Extract the date part from a timestamp.
date PGTYPESdate_from_timestamp(timestamp dt);
The function receives a timestamp as its only argument and returns the extracted date part from this timestamp.
PGTYPESdate_from_asc#Parse a date from its textual representation.
date PGTYPESdate_from_asc(char *str, char **endptr);
The function receives a C char* string
strand a pointer to a C char* stringendptr. At the moment ECPG always parses the complete string and so it currently does not support to store the address of the first invalid character in*endptr. You can safely setendptrto NULL.Note that the function always assumes MDY-formatted dates and there is currently no variable to change that within ECPG.
Table 39.2 shows the allowed input formats.
Table 39.2. Valid Input Formats for
PGTYPESdate_from_ascInput Result January 8, 1999January 8, 19991999-01-08January 8, 19991/8/1999January 8, 19991/18/1999January 18, 199901/02/03February 1, 20031999-Jan-08January 8, 1999Jan-08-1999January 8, 199908-Jan-1999January 8, 199999-Jan-08January 8, 199908-Jan-99January 8, 199908-Jan-06January 8, 2006Jan-08-99January 8, 199919990108ISO 8601; January 8, 1999990108ISO 8601; January 8, 19991999.008year and day of yearJ2451187Julian dayJanuary 8, 99 BCyear 99 before the Common EraPGTYPESdate_to_asc#Return the textual representation of a date variable.
char *PGTYPESdate_to_asc(date dDate);
The function receives the date
dDateas its only parameter. It will output the date in the form1999-01-18, i.e., in theYYYY-MM-DDformat. The result must be freed withPGTYPESchar_free().PGTYPESdate_julmdy#Extract the values for the day, the month and the year from a variable of type date.
void PGTYPESdate_julmdy(date d, int *mdy);
The function receives the date
dand a pointer to an array of 3 integer valuesmdy. The variable name indicates the sequential order:mdy[0]will be set to contain the number of the month,mdy[1]will be set to the value of the day andmdy[2]will contain the year.PGTYPESdate_mdyjul#Create a date value from an array of 3 integers that specify the day, the month and the year of the date.
void PGTYPESdate_mdyjul(int *mdy, date *jdate);
The function receives the array of the 3 integers (
mdy) as its first argument and as its second argument a pointer to a variable of type date that should hold the result of the operation.PGTYPESdate_dayofweek#Return a number representing the day of the week for a date value.
int PGTYPESdate_dayofweek(date d);
The function receives the date variable
das its only argument and returns an integer that indicates the day of the week for this date.0 - Sunday
1 - Monday
2 - Tuesday
3 - Wednesday
4 - Thursday
5 - Friday
6 - Saturday
PGTYPESdate_today#Get the current date.
void PGTYPESdate_today(date *d);
The function receives a pointer to a date variable (
d) that it sets to the current date.PGTYPESdate_fmt_asc#Convert a variable of type date to its textual representation using a format mask.
int PGTYPESdate_fmt_asc(date dDate, char *fmtstring, char *outbuf);
The function receives the date to convert (
dDate), the format mask (fmtstring) and the string that will hold the textual representation of the date (outbuf).On success, 0 is returned and a negative value if an error occurred.
The following literals are the field specifiers you can use:
dd- The number of the day of the month.mm- The number of the month of the year.yy- The number of the year as a two digit number.yyyy- The number of the year as a four digit number.ddd- The name of the day (abbreviated).mmm- The name of the month (abbreviated).
All other characters are copied 1:1 to the output string.
Table 39.3 indicates a few possible formats. This will give you an idea of how to use this function. All output lines are based on the same date: November 23, 1959.
Table 39.3. Valid Input Formats for
PGTYPESdate_fmt_ascFormat Result mmddyy112359ddmmyy231159yymmdd591123yy/mm/dd59/11/23yy mm dd59 11 23yy.mm.dd59.11.23.mm.yyyy.dd..11.1959.23.mmm. dd, yyyyNov. 23, 1959mmm dd yyyyNov 23 1959yyyy dd mm1959 23 11ddd, mmm. dd, yyyyMon, Nov. 23, 1959(ddd) mmm. dd, yyyy(Mon) Nov. 23, 1959PGTYPESdate_defmt_asc#Use a format mask to convert a C
char*string to a value of type date.int PGTYPESdate_defmt_asc(date *d, char *fmt, char *str);
The function receives a pointer to the date value that should hold the result of the operation (
d), the format mask to use for parsing the date (fmt) and the C char* string containing the textual representation of the date (str). The textual representation is expected to match the format mask. However you do not need to have a 1:1 mapping of the string to the format mask. The function only analyzes the sequential order and looks for the literalsyyoryyyythat indicate the position of the year,mmto indicate the position of the month andddto indicate the position of the day.Table 39.4 indicates a few possible formats. This will give you an idea of how to use this function.
Table 39.4. Valid Input Formats for
rdefmtdateFormat String Result ddmmyy21-2-541954-02-21ddmmyy2-12-541954-12-02ddmmyy201119541954-11-20ddmmyy1304641964-04-13mmm.dd.yyyyMAR-12-19671967-03-12yy/mm/dd1954, February 3rd1954-02-03mmm.dd.yyyy0412691969-04-12yy/mm/ddIn the year 2525, in the month of July, mankind will be alive on the 28th day2525-07-28dd-mm-yyI said on the 28th of July in the year 25252525-07-28mmm.dd.yyyy9/14/581958-09-14yy/mm/dd47/03/291947-03-29mmm.dd.yyyyoct 28 19751975-10-28mmddyyNov 14th, 19851985-11-14
39.6.4. The timestamp Type #
The timestamp type in C enables your programs to deal with data of the SQL type timestamp. See Section 8.5 for the equivalent type in the Postgres Pro server.
The following functions can be used to work with the timestamp type:
PGTYPEStimestamp_from_asc#Parse a timestamp from its textual representation into a timestamp variable.
timestamp PGTYPEStimestamp_from_asc(char *str, char **endptr);
The function receives the string to parse (
str) and a pointer to a C char* (endptr). At the moment ECPG always parses the complete string and so it currently does not support to store the address of the first invalid character in*endptr. You can safely setendptrto NULL.The function returns the parsed timestamp on success. On error,
PGTYPESInvalidTimestampis returned anderrnois set toPGTYPES_TS_BAD_TIMESTAMP. SeePGTYPESInvalidTimestampfor important notes on this value.In general, the input string can contain any combination of an allowed date specification, a whitespace character and an allowed time specification. Note that time zones are not supported by ECPG. It can parse them but does not apply any calculation as the Postgres Pro server does for example. Timezone specifiers are silently discarded.
Table 39.5 contains a few examples for input strings.
Table 39.5. Valid Input Formats for
PGTYPEStimestamp_from_ascInput Result 1999-01-08 04:05:061999-01-08 04:05:06January 8 04:05:06 1999 PST1999-01-08 04:05:061999-Jan-08 04:05:06.789-81999-01-08 04:05:06.789 (time zone specifier ignored)J2451187 04:05-08:001999-01-08 04:05:00 (time zone specifier ignored)PGTYPEStimestamp_to_asc#Converts a date to a C char* string.
char *PGTYPEStimestamp_to_asc(timestamp tstamp);
The function receives the timestamp
tstampas its only argument and returns an allocated string that contains the textual representation of the timestamp. The result must be freed withPGTYPESchar_free().PGTYPEStimestamp_current#Retrieve the current timestamp.
void PGTYPEStimestamp_current(timestamp *ts);
The function retrieves the current timestamp and saves it into the timestamp variable that
tspoints to.PGTYPEStimestamp_fmt_asc#Convert a timestamp variable to a C char* using a format mask.
int PGTYPEStimestamp_fmt_asc(timestamp *ts, char *output, int str_len, char *fmtstr);
The function receives a pointer to the timestamp to convert as its first argument (
ts), a pointer to the output buffer (output), the maximal length that has been allocated for the output buffer (str_len) and the format mask to use for the conversion (fmtstr).Upon success, the function returns 0 and a negative value if an error occurred.
You can use the following format specifiers for the format mask. The format specifiers are the same ones that are used in the
strftimefunction in libc. Any non-format specifier will be copied into the output buffer.%A- is replaced by national representation of the full weekday name.%a- is replaced by national representation of the abbreviated weekday name.%B- is replaced by national representation of the full month name.%b- is replaced by national representation of the abbreviated month name.%C- is replaced by (year / 100) as decimal number; single digits are preceded by a zero.%c- is replaced by national representation of time and date.%D- is equivalent to%m/%d/%y.%d- is replaced by the day of the month as a decimal number (01–31).%E*%O*- POSIX locale extensions. The sequences%Ec%EC%Ex%EX%Ey%EY%Od%Oe%OH%OI%Om%OM%OS%Ou%OU%OV%Ow%OW%Oyare supposed to provide alternative representations.Additionally
%OBimplemented to represent alternative months names (used standalone, without day mentioned).%e- is replaced by the day of month as a decimal number (1–31); single digits are preceded by a blank.%F- is equivalent to%Y-%m-%d.%G- is replaced by a year as a decimal number with century. This year is the one that contains the greater part of the week (Monday as the first day of the week).%g- is replaced by the same year as in%G, but as a decimal number without century (00–99).%H- is replaced by the hour (24-hour clock) as a decimal number (00–23).%h- the same as%b.%I- is replaced by the hour (12-hour clock) as a decimal number (01–12).%j- is replaced by the day of the year as a decimal number (001–366).%k- is replaced by the hour (24-hour clock) as a decimal number (0–23); single digits are preceded by a blank.%l- is replaced by the hour (12-hour clock) as a decimal number (1–12); single digits are preceded by a blank.%M- is replaced by the minute as a decimal number (00–59).%m- is replaced by the month as a decimal number (01–12).%n- is replaced by a newline.%O*- the same as%E*.%p- is replaced by national representation of either “ante meridiem” or “post meridiem” as appropriate.%R- is equivalent to%H:%M.%r- is equivalent to%I:%M:%S %p.%S- is replaced by the second as a decimal number (00–60).%s- is replaced by the number of seconds since the Epoch, UTC.%T- is equivalent to%H:%M:%S%t- is replaced by a tab.%U- is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number (00–53).%u- is replaced by the weekday (Monday as the first day of the week) as a decimal number (1–7).%V- is replaced by the week number of the year (Monday as the first day of the week) as a decimal number (01–53). If the week containing January 1 has four or more days in the new year, then it is week 1; otherwise it is the last week of the previous year, and the next week is week 1.%v- is equivalent to%e-%b-%Y.%W- is replaced by the week number of the year (Monday as the first day of the week) as a decimal number (00–53).%w- is replaced by the weekday (Sunday as the first day of the week) as a decimal number (0–6).%X- is replaced by national representation of the time.%x- is replaced by national representation of the date.%Y- is replaced by the year with century as a decimal number.%y- is replaced by the year without century as a decimal number (00–99).%Z- is replaced by the time zone name.%z- is replaced by the time zone offset from UTC; a leading plus sign stands for east of UTC, a minus sign for west of UTC, hours and minutes follow with two digits each and no delimiter between them (common form for RFC 822 date headers).%+- is replaced by national representation of the date and time.%-*- GNU libc extension. Do not do any padding when performing numerical outputs.$_* - GNU libc extension. Explicitly specify space for padding.
%0*- GNU libc extension. Explicitly specify zero for padding.%%- is replaced by%.
PGTYPEStimestamp_sub#Subtract one timestamp from another one and save the result in a variable of type interval.
int PGTYPEStimestamp_sub(timestamp *ts1, timestamp *ts2, interval *iv);
The function will subtract the timestamp variable that
ts2points to from the timestamp variable thatts1points to and will store the result in the interval variable thativpoints to.Upon success, the function returns 0 and a negative value if an error occurred.
PGTYPEStimestamp_defmt_asc#Parse a timestamp value from its textual representation using a formatting mask.
int PGTYPEStimestamp_defmt_asc(char *str, char *fmt, timestamp *d);
The function receives the textual representation of a timestamp in the variable
stras well as the formatting mask to use in the variablefmt. The result will be stored in the variable thatdpoints to.If the formatting mask
fmtis NULL, the function will fall back to the default formatting mask which is%Y-%m-%d %H:%M:%S.This is the reverse function to
PGTYPEStimestamp_fmt_asc. See the documentation there in order to find out about the possible formatting mask entries.PGTYPEStimestamp_add_interval#Add an interval variable to a timestamp variable.
int PGTYPEStimestamp_add_interval(timestamp *tin, interval *span, timestamp *tout);
The function receives a pointer to a timestamp variable
tinand a pointer to an interval variablespan. It adds the interval to the timestamp and saves the resulting timestamp in the variable thattoutpoints to.Upon success, the function returns 0 and a negative value if an error occurred.
PGTYPEStimestamp_sub_interval#Subtract an interval variable from a timestamp variable.
int PGTYPEStimestamp_sub_interval(timestamp *tin, interval *span, timestamp *tout);
The function subtracts the interval variable that
spanpoints to from the timestamp variable thattinpoints to and saves the result into the variable thattoutpoints to.Upon success, the function returns 0 and a negative value if an error occurred.
39.6.5. The interval Type #
The interval type in C enables your programs to deal with data of the SQL type interval. See Section 8.5 for the equivalent type in the Postgres Pro server.
The following functions can be used to work with the interval type:
PGTYPESinterval_new#Return a pointer to a newly allocated interval variable.
interval *PGTYPESinterval_new(void);
PGTYPESinterval_free#Release the memory of a previously allocated interval variable.
void PGTYPESinterval_free(interval *intvl);
PGTYPESinterval_from_asc#Parse an interval from its textual representation.
interval *PGTYPESinterval_from_asc(char *str, char **endptr);
The function parses the input string
strand returns a pointer to an allocated interval variable. At the moment ECPG always parses the complete string and so it currently does not support to store the address of the first invalid character in*endptr. You can safely setendptrto NULL.PGTYPESinterval_to_asc#Convert a variable of type interval to its textual representation.
char *PGTYPESinterval_to_asc(interval *span);
The function converts the interval variable that
spanpoints to into a C char*. The output looks like this example:@ 1 day 12 hours 59 mins 10 secs. The result must be freed withPGTYPESchar_free().PGTYPESinterval_copy#Copy a variable of type interval.
int PGTYPESinterval_copy(interval *intvlsrc, interval *intvldest);
The function copies the interval variable that
intvlsrcpoints to into the variable thatintvldestpoints to. Note that you need to allocate the memory for the destination variable before.
39.6.6. The decimal Type #
The decimal type is similar to the numeric type. However it is limited to a maximum precision of 30 significant digits. In contrast to the numeric type which can be created on the heap only, the decimal type can be created either on the stack or on the heap (by means of the functions PGTYPESdecimal_new and PGTYPESdecimal_free). There are a lot of other functions that deal with the decimal type in the Informix compatibility mode described in Section 39.15.
The following functions can be used to work with the decimal type and are not only contained in the libcompat library.
39.6.7. errno Values of pgtypeslib #
PGTYPES_NUM_BAD_NUMERIC#An argument should contain a numeric variable (or point to a numeric variable) but in fact its in-memory representation was invalid.
PGTYPES_NUM_OVERFLOW#An overflow occurred. Since the numeric type can deal with almost arbitrary precision, converting a numeric variable into other types might cause overflow.
PGTYPES_NUM_UNDERFLOW#An underflow occurred. Since the numeric type can deal with almost arbitrary precision, converting a numeric variable into other types might cause underflow.
PGTYPES_NUM_DIVIDE_ZERO#A division by zero has been attempted.
PGTYPES_DATE_BAD_DATE#An invalid date string was passed to the
PGTYPESdate_from_ascfunction.PGTYPES_DATE_ERR_EARGS#Invalid arguments were passed to the
PGTYPESdate_defmt_ascfunction.PGTYPES_DATE_ERR_ENOSHORTDATE#An invalid token in the input string was found by the
PGTYPESdate_defmt_ascfunction.PGTYPES_INTVL_BAD_INTERVAL#An invalid interval string was passed to the
PGTYPESinterval_from_ascfunction, or an invalid interval value was passed to thePGTYPESinterval_to_ascfunction.PGTYPES_DATE_ERR_ENOTDMY#There was a mismatch in the day/month/year assignment in the
PGTYPESdate_defmt_ascfunction.PGTYPES_DATE_BAD_DAY#An invalid day of the month value was found by the
PGTYPESdate_defmt_ascfunction.PGTYPES_DATE_BAD_MONTH#An invalid month value was found by the
PGTYPESdate_defmt_ascfunction.PGTYPES_TS_BAD_TIMESTAMP#An invalid timestamp string pass passed to the
PGTYPEStimestamp_from_ascfunction, or an invalid timestamp value was passed to thePGTYPEStimestamp_to_ascfunction.PGTYPES_TS_ERR_EINFTIME#An infinite timestamp value was encountered in a context that cannot handle it.
39.6.8. Special Constants of pgtypeslib #
PGTYPESInvalidTimestamp#A value of type timestamp representing an invalid time stamp. This is returned by the function
PGTYPEStimestamp_from_ascon parse error. Note that due to the internal representation of thetimestampdata type,PGTYPESInvalidTimestampis also a valid timestamp at the same time. It is set to1899-12-31 23:59:59. In order to detect errors, make sure that your application does not only test forPGTYPESInvalidTimestampbut also forerrno != 0after each call toPGTYPEStimestamp_from_asc.