38.15. Режим совместимости с Informix #

Препроцессор ecpg может работать в так называемом режиме совместимости с Informix. Если этот режим включён, ecpg старается работать как предкомпилятор Informix для кода Informix E/SQL. Вообще говоря, это позволяет записывать встраиваемые команды SQL, используя знак доллара вместо слов EXEC SQL:

$int j = 3;
$CONNECT TO :dbname;
$CREATE TABLE test(i INT PRIMARY KEY, j INT);
$INSERT INTO test(i, j) VALUES (7, :j);
$COMMIT;

Примечание

Между $ и последующей директивой препроцессора (в частности, include, define, ifdef и т. п.) не должно быть пробельных символов. В противном случае препроцессор воспримет следующее слово как имя переменной среды.

Поддерживаются два режима совместимости: INFORMIX и INFORMIX_SE

При компоновке программ, использующих этот режим совместимости, обязательно подключите библиотеку libcompat, поставляемую с ECPG.

Помимо ранее упомянутого синтаксического сахара, режим совместимости с Informix приносит из E/SQL в ECPG набор функций для ввода, вывода и преобразования данных, а также встраиваемые операторы SQL.

Режим совместимости с Informix тесно связан с библиотекой pgtypeslib из ECPG. Библиотека pgtypeslib сопоставляет типы данных SQL с типами данных в ведущей программе на C, а большинство дополнительных функций режима совместимости с Informix позволяют работать с этими типами C. Заметьте, однако, что степень совместимости ограничена. ECPG не пытается копировать поведение Informix; вы можете выполнять примерно те же операции и пользоваться функции с теми же именами и с тем же поведением, но если вы используете Informix, просто заменить одно средство другим на данный момент нельзя. Более того, есть различия и в типах данных. В частности, типы даты и интервала в Postgres Pro не воспринимают диапазоны, например YEAR TO MINUTE, так что и в ECPG это не будет поддерживаться.

38.15.1. Дополнительные типы #

Теперь в режиме Informix без указания typedef поддерживается специальный псевдотип Informix "string" для хранения символьной строки, обрезаемой справа. На самом деле, в режиме Informix ECPG откажется обрабатывать исходные файлы, содержащие определение типа typedef некоторый_тип string;

EXEC SQL BEGIN DECLARE SECTION;
string userid; /* эта переменная будет содержать обрезанные данные */
EXEC SQL END DECLARE SECTION;

EXEC SQL FETCH MYCUR INTO :userid;

38.15.2. Дополнительные/недостающие операторы встраиваемого SQL #

CLOSE DATABASE #

Этот оператор закрывает текущее подключение. Фактически это синоним команды DISCONNECT CURRENT в ECPG:

$CLOSE DATABASE;                /* закрыть текущее подключение */
EXEC SQL CLOSE DATABASE;
FREE имя_курсора #

Из-за различий в подходах ECPG и ESQL/C Informix (а именно другого разделения на чисто грамматические преобразования и вызовы нижележащей библиотеки времени выполнения) в ECPG нет оператора FREE имя_курсора. Это связано с тем, что в ECPG команда DECLARE CURSOR не сводится к вызову функции в библиотеке времени выполнения, которая бы принимала имя курсора. Это значит, что курсоры SQL в библиотеке ECPG не требуют обслуживания, оно требуется только на уровне сервера Postgres Pro.

FREE имя_оператора #

Команда FREE имя_оператора является синонимом команды DEALLOCATE PREPARE имя_оператора.

38.15.3. Области дескрипторов SQLDA, совместимые с Informix #

Режим совместимости с Informix поддерживает структуру, отличную от описанной в Подразделе 38.7.2. См. ниже:

struct sqlvar_compat
{
    short   sqltype;
    int     sqllen;
    char   *sqldata;
    short  *sqlind;
    char   *sqlname;
    char   *sqlformat;
    short   sqlitype;
    short   sqlilen;
    char   *sqlidata;
    int     sqlxid;
    char   *sqltypename;
    short   sqltypelen;
    short   sqlownerlen;
    short   sqlsourcetype;
    char   *sqlownername;
    int     sqlsourceid;
    char   *sqlilongdata;
    int     sqlflags;
    void   *sqlreserved;
};

struct sqlda_compat
{
    short  sqld;
    struct sqlvar_compat *sqlvar;
    char   desc_name[19];
    short  desc_occ;
    struct sqlda_compat *desc_next;
    void  *reserved;
};

typedef struct sqlvar_compat    sqlvar_t;
typedef struct sqlda_compat     sqlda_t;

Глобальные свойства:

sqld #

Число полей в дескрипторе SQLDA.

sqlvar #

Указатель на свойства по полям.

desc_name #

Не используется, заполняется нулями.

desc_occ #

Размер структуры в памяти.

desc_next #

Указатель на следующую структуру SQLDA, если набор результатов содержит больше одной записи.

reserved #

Неиспользуемый указатель, содержит NULL. Сохраняется для совместимости с Informix.

Свойства, относящиеся к полям, описаны ниже, они хранятся в массиве sqlvar:

sqltype #

Тип поля. Соответствующие константы представлены в sqltypes.h

sqllen #

Длина данных поля.

sqldata #

Указатель на данные поля. Этот указатель имеет тип char *, но он указывает на данные в двоичном формате. Например:

int intval;

switch (sqldata->sqlvar[i].sqltype)
{
    case SQLINTEGER:
        intval = *(int *)sqldata->sqlvar[i].sqldata;
        break;
  ...
}
sqlind #

Указатель на индикатор NULL. Если возвращается командами DESCRIBE или FETCH, это всегда действительный указатель. Если передаётся на вход команде EXECUTE ... USING sqlda;, NULL вместо указателя означает, что значение этого поля отлично от NULL. Чтобы обозначить NULL в поле, необходимо корректно установить этот указатель и sqlitype. Например:

if (*(int2 *)sqldata->sqlvar[i].sqlind != 0)
    printf("value is NULL\n");
sqlname #

Имя поля, в виде строки с завершающим 0.

sqlformat #

Зарезервировано в Informix, значение PQfformat для данного поля.

sqlitype #

Тип данных индикатора NULL. При получении данных с сервера это всегда SQLSMINT. Когда SQLDA используется в параметризованном запросе, данные индикатора обрабатываются в соответствии с указанным здесь типом.

sqlilen #

Длина данных индикатора NULL.

sqlxid #

Расширенный тип поля, результат функции PQftype.

sqltypename
sqltypelen
sqlownerlen
sqlsourcetype
sqlownername
sqlsourceid
sqlflags
sqlreserved #

Не используются.

sqlilongdata #

Совпадает с sqldata, если sqllen превышает 32 Кбайта.

Например:

EXEC SQL INCLUDE sqlda.h;

    sqlda_t        *sqlda; /* Это объявление не обязательно должно быть внутри DECLARE SECTION */

    EXEC SQL BEGIN DECLARE SECTION;
    char *prep_stmt = "select * from table1";
    int i;
    EXEC SQL END DECLARE SECTION;

    ...

    EXEC SQL PREPARE mystmt FROM :prep_stmt;

    EXEC SQL DESCRIBE mystmt INTO sqlda;

    printf("# of fields: %d\n", sqlda->sqld);
    for (i = 0; i < sqlda->sqld; i++)
      printf("field %d: \"%s\"\n", sqlda->sqlvar[i]->sqlname);

    EXEC SQL DECLARE mycursor CURSOR FOR mystmt;
    EXEC SQL OPEN mycursor;
    EXEC SQL WHENEVER NOT FOUND GOTO out;

    while (1)
    {
      EXEC SQL FETCH mycursor USING sqlda;
    }

    EXEC SQL CLOSE mycursor;

    free(sqlda); /* Освобождать нужно только основную структуру,
                  * sqlda и sqlda->sqlvar находятся в одной выделенной области. */

38.15.4. Дополнительные функции #

decadd #

Складывает два значения типа decimal.

int decadd(decimal *arg1, decimal *arg2, decimal *sum);

Эта функция получает указатель на первый операнд типа decimal (arg1), указатель на второй операнд типа decimal (arg2) и указатель на переменную типа decimal, в которую будет записана сумма (sum). В случае успеха эта функция возвращает 0. ECPG_INFORMIX_NUM_OVERFLOW возвращается в случае переполнения, а ECPG_INFORMIX_NUM_UNDERFLOW в случае антипереполнения. При любых других ошибках возвращается -1, а в errno устанавливается код errno из pgtypeslib.

deccmp #

Сравнивает два значения типа decimal.

int deccmp(decimal *arg1, decimal *arg2);

Эта функция получает указатель на первое значение типа decimal (arg1), указатель на второе значение типа decimal (arg2) и возвращает целое, отражающее результат сравнения этих чисел.

  • 1, если значение, на которое указывает arg1, больше значения, на которое указывает var2

  • -1, если значение, на которое указывает arg1, меньше значения, на которое указывает arg2

  • 0, если значение, на которое указывает arg1, равно значению, на которое указывает arg2

deccopy #

Копирует значение типа decimal.

void deccopy(decimal *src, decimal *target);

Функция принимает в первом аргументе (src) указатель на значение decimal, которое должно быть скопировано, а во втором аргументе (target) принимает указатель на структуру типа decimal для скопированного значения.

deccvasc #

Преобразует значение из представления ASCII в тип decimal.

int deccvasc(char *cp, int len, decimal *np);

Эта функция получает указатель на строку, содержащую строковое представление числа, которое нужно преобразовать, (cp), а также его длину len. В np передаётся указатель на переменную типа decimal, в которую будет помещён результат преобразования.

Допустимыми являются, например следующие форматы: -2, .794, +3.44, 592.49E07 или -32.84e-4.

В случае успеха эта функция возвращает 0. При переполнении или антипереполнении возвращается ECPG_INFORMIX_NUM_OVERFLOW или ECPG_INFORMIX_NUM_UNDERFLOW, соответственно. Если разобрать ASCII-представление не удаётся, возвращается ECPG_INFORMIX_BAD_NUMERIC или ECPG_INFORMIX_BAD_EXPONENT, если не удаётся разобрать компонент экспоненты.

deccvdbl #

Преобразует значение double в значение типа decimal.

int deccvdbl(double dbl, decimal *np);

Данная функция принимает в первом аргументе (dbl) переменную типа double, которая должна быть преобразована. Во втором аргументе (np) она принимает указатель на переменную decimal, в которую будет помещён результат операции.

Эта функция возвращает 0 в случае успеха, либо отрицательное значение, если выполнить преобразование не удалось.

deccvint #

Преобразует значение int в значение типа decimal.

int deccvint(int in, decimal *np);

Данная функция принимает в первом аргументе (in) переменную типа int, которая должна быть преобразована. Во втором аргументе (np) она принимает указатель на переменную decimal, в которую будет помещён результат операции.

Эта функция возвращает 0 в случае успеха, либо отрицательное значение, если выполнить преобразование не удалось.

deccvlong #

Преобразует значение long в значение типа decimal.

int deccvlong(long lng, decimal *np);

Данная функция принимает в первом аргументе (lng) переменную типа long, которая должна быть преобразована. Во втором аргументе (np) она принимает указатель на переменную decimal, в которую будет помещён результат операции.

Эта функция возвращает 0 в случае успеха, либо отрицательное значение, если выполнить преобразование не удалось.

decdiv #

Делит одну переменную типа decimal на другую.

int decdiv(decimal *n1, decimal *n2, decimal *result);

Эта функция получает указатели на переменные (n1 и n2) и вычисляет частное n1/n2. В result передаётся указатель на переменную, в которую будет помещён результат операции.

В случае успеха возвращается 0, а при ошибке — отрицательное значение. В случае переполнения или антипереполнения данная функция возвращает ECPG_INFORMIX_NUM_OVERFLOW или ECPG_INFORMIX_NUM_UNDERFLOW, соответственно. При попытке деления на ноль возвращается ECPG_INFORMIX_DIVIDE_ZERO.

decmul #

Перемножает два значения типа decimal.

int decmul(decimal *n1, decimal *n2, decimal *result);

Эта функция получает указатели на переменные (n1 и n2) и вычисляет произведение n1*n2. В result передаётся указатель на переменную, в которую будет помещён результат операции.

В случае успеха возвращается 0, а при ошибке — отрицательное значение. В случае переполнения или антипереполнения данная функция возвращает ECPG_INFORMIX_NUM_OVERFLOW или ECPG_INFORMIX_NUM_UNDERFLOW, соответственно.

decsub #

Вычитает одно значение типа decimal из другого.

int decsub(decimal *n1, decimal *n2, decimal *result);

Эта функция получает указатели на переменные (n1 и n2) и вычисляет разность n1-n2. В result передаётся указатель на переменную, в которую будет помещён результат операции.

В случае успеха возвращается 0, а при ошибке — отрицательное значение. В случае переполнения или антипереполнения данная функция возвращает ECPG_INFORMIX_NUM_OVERFLOW или ECPG_INFORMIX_NUM_UNDERFLOW, соответственно.

dectoasc #

Преобразует переменную типа decimal в представление ASCII (в строку C char*).

int dectoasc(decimal *np, char *cp, int len, int right)

Эта функция получает указатель на переменную типа decimal (np), которая будет преобразована в текстовое представление. Аргумент cp указывает на буфер, в который будет помещён результат операции. Аргумент right определяет, сколько должно выводиться цифр правее десятичной точки. Результат будет округлён до этого числа десятичных цифр. Значение right, равное -1, указывает, что выводиться должны все имеющиеся десятичные цифры. Если длина выходного буфера, которую задаёт len, недостаточна для помещения в него текстового представления, включая завершающий нулевой байт, в буфере сохраняется один знак * и возвращается -1.

Эта функция возвращает -1, если буфер cp слишком мал, либо ECPG_INFORMIX_OUT_OF_MEMORY при нехватке памяти.

dectodbl #

Преобразует переменную типа decimal в тип double.

int dectodbl(decimal *np, double *dblp);

Эта функция получает указатель (np) на значение decimal, которое нужно преобразовать, и указатель (dblp) на переменную double, в которую будет помещён результат операции.

В случае успеха возвращается 0, или отрицательное значение, если выполнить преобразование не удалось.

dectoint #

Преобразует переменную типа decimal в тип integer.

int dectoint(decimal *np, int *ip);

Эта функция получает указатель (np) на значение decimal, которое нужно преобразовать, и указатель (ip) на целочисленную переменную, в которую будет помещён результат операции.

В случае успеха возвращается 0, или отрицательное значение, если выполнить преобразование не удалось. В случае переполнения возвращается ECPG_INFORMIX_NUM_OVERFLOW.

Заметьте, что реализация ECPG отличается от реализации Informix. В Informix целое ограничивается диапазоном -32767 .. 32767, тогда как в ECPG ограничение зависит от архитектуры (INT_MIN .. INT_MAX).

dectolong #

Преобразует переменную типа decimal в тип long.

int dectolong(decimal *np, long *lngp);

Эта функция получает указатель (np) на значение decimal, которое нужно преобразовать, и указатель (lngp) на переменную типа long, в которую будет помещён результат операции.

В случае успеха возвращается 0, или отрицательное значение, если выполнить преобразование не удалось. В случае переполнения возвращается ECPG_INFORMIX_NUM_OVERFLOW.

Заметьте, что реализация ECPG отличается от реализации Informix. В Informix длинное целое ограничено диапазоном -2 147 483 647 .. 2 147 483 647, тогда как в ECPG ограничение зависит от архитектуры (-LONG_MAX .. LONG_MAX).

rdatestr #

Преобразует дату в строку C char*.

int rdatestr(date d, char *str);

Эта функция принимает два аргумента. В первом (d) передаётся дата, которую нужно преобразовать, а во втором указатель на целевую строку. Результат всегда выводится в формате yyyy-mm-dd, так что для этой строки нужно выделить минимум 11 байт (включая завершающий нулевой байт).

Эта функция возвращает 0 в случае успеха, а в случае ошибки — отрицательное значение.

Заметьте, что реализация ECPG отличается от реализации Informix. В Informix формат вывода можно изменить переменными окружения, а в ECPG он фиксирован.

rstrdate #

Разбирает текстовое представление даты.

int rstrdate(char *str, date *d);

Эта функция получает текстовое представление (str) даты, которую нужно преобразовать, и указатель на переменную типа date (d). Для данной функции нельзя задать маску формата. Она использует стандартную маску формата Informix, а именно: mm/dd/yyyy. Внутри эта функция вызывает rdefmtdate. Таким образом, rstrdate не будет быстрее, и если у вас есть выбор, используйте функцию rdefmtdate, которая позволяет явно задать маску формата.

Эта функция возвращает те же значения, что и rdefmtdate.

rtoday #

Выдаёт текущую дату.

void rtoday(date *d);

Эта функция получает указатель на переменную (d) типа date, в которую будет записана текущая дата.

Внутри эта функция вызывает PGTYPESdate_today.

rjulmdy #

Извлекает значения дня, месяца и года из переменной типа date.

int rjulmdy(date d, short mdy[3]);

Эта функция получает дату d и указатель на 3 коротких целочисленных значения mdy. Имя переменной указывает на порядок значений: в mdy[0] записывается номер месяца, в mdy[1] — номер дня, а в mdy[2] — год.

В текущем состоянии эта функция всегда возвращает 0.

Внутри эта функция вызывает PGTYPESdate_julmdy.

rdefmtdate #

Преобразует символьную строку в значение типа date по маске формата.

int rdefmtdate(date *d, char *fmt, char *str);

Эта функция принимает указатель на переменную типа date (d), в которую будет помещён результат операции, маску формата для разбора даты (fmt) и строку C char*, содержащую текстовое представление даты (str). Ожидается, что текстовое представление будет соответствовать маске формата. Однако это соответствие не обязательно должно быть точным. Данная функция анализирует только порядок элементов и ищет в нём подстроки yy или yyyy, обозначающие позицию года, подстроку mm, обозначающую позицию месяца, и dd, обозначающую позицию дня.

Эта функция возвращает следующие значения:

  • 0 — Функция выполнена успешно.

  • ECPG_INFORMIX_ENOSHORTDATE — Дата не содержит разделителей между днём, месяцем и годом. С таким форматом входная строка должна быть длиной ровно 6 или 8 байт, но это не так.

  • ECPG_INFORMIX_ENOTDMY — Строка формата не определяет корректно последовательный порядок года, месяца и дня.

  • ECPG_INFORMIX_BAD_DAY — Во входной строке отсутствует корректное указание дня.

  • ECPG_INFORMIX_BAD_MONTH — Во входной строке отсутствует корректное указание месяца.

  • ECPG_INFORMIX_BAD_YEAR — Во входной строке отсутствует корректное указание года.

В реализации этой функции вызывается PGTYPESdate_defmt_asc. Примеры вводимых строк приведены в таблице в её описании.

rfmtdate #

Преобразует переменную типа date в текстовое представление по маске формата.

int rfmtdate(date d, char *fmt, char *str);

Эта функция принимает дату для преобразования (d), маску формата (fmt) и строку, в которую будет помещено текстовое представление даты (str).

В случае успеха возвращается 0, а в случае ошибки — отрицательное значение.

Внутри эта функция вызывает PGTYPESdate_fmt_asc, примеры форматов можно найти в её описании.

rmdyjul #

Образует значение даты из массива 3 коротких целых, задающих день, месяц и год даты.

int rmdyjul(short mdy[3], date *d);

Эта функция получает в первом аргументе массив из 3 коротких целых (mdy), а во втором указатель на переменную типа date, в которую будет помещён результат операции.

В настоящее время эта функция всегда возвращает 0.

В реализации этой функции вызывается PGTYPESdate_mdyjul.

rdayofweek #

Возвращает число, представляющее день недели для заданной даты.

int rdayofweek(date d);

Эта функция принимает в единственном аргументе переменную d типа date и возвращает целое число, выражающее день недели для этой даты.

  • 0 — Воскресенье

  • 1 — Понедельник

  • 2 — Вторник

  • 3 — Среда

  • 4 — Четверг

  • 5 — Пятница

  • 6 — Суббота

В реализации этой функции вызывается PGTYPESdate_dayofweek.

dtcurrent #

Получает текущее время.

void dtcurrent(timestamp *ts);

Эта функция получает текущее время и сохраняет его в переменной типа timestamp, на которую указывает ts.

dtcvasc #

Разбирает время из текстового представления в переменную типа timestamp.

int dtcvasc(char *str, timestamp *ts);

Эта функция получает строку (str), которую нужно разобрать, и указатель на переменную типа timestamp, в которую будет помещён результат операции (ts).

Эта функция возвращает 0 в случае успеха, а в случае ошибки — отрицательное значение.

Внутри эта функция вызывает PGTYPEStimestamp_from_asc. Примеры вводимых строк приведены в таблице в её описании.

dtcvfmtasc #

Разбирает время из текстового представления в переменную типа timestamp по маске формата.

dtcvfmtasc(char *inbuf, char *fmtstr, timestamp *dtvalue)

Эта функция получает строку (inbuf), которую нужно разобрать, маску формата (fmtstr) и указатель на переменную timestamp, в которой будет содержаться результат операции (dtvalue).

В реализации этой функции используется PGTYPEStimestamp_defmt_asc. Список допустимых кодов формата приведён в её описании.

Эта функция возвращает 0 в случае успеха, а в случае ошибки — отрицательное значение.

dtsub #

Вычитает одно значение времени из другого и возвращает переменную типа interval.

int dtsub(timestamp *ts1, timestamp *ts2, interval *iv);

Эта функция вычитает значение timestamp, на которое указывает ts2, из значения timestamp, на которое указывает ts1, и сохраняет результат в переменной типа interval, на которую указывает iv.

В случае успеха возвращается 0, а в случае ошибки — отрицательное значение.

dttoasc #

Преобразует переменную типа timestamp в строку C char*.

int dttoasc(timestamp *ts, char *output);

Эта функция получает указатель (ts) на переменную типа timestamp, которую нужно преобразовать, и строку (output) для сохранения результата операции. Она преобразует ts в текстовое представление согласно стандарту SQL, то есть по маске YYYY-MM-DD HH:MM:SS.

В случае успеха возвращается 0, а в случае ошибки — отрицательное значение.

dttofmtasc #

Преобразует переменную типа timestamp в строку C char* по маске формата.

int dttofmtasc(timestamp *ts, char *output, int str_len, char *fmtstr);

Эта функция получает в первом аргументе (ts) указатель на переменную типа timestamp, а в последующих указатель на буфер вывода (output), максимальную длину строки, которую может принять буфер (str_len), и маску формата, с которой будет выполняться преобразование (fmtstr).

В случае успеха возвращается 0, а в случае ошибки — отрицательное значение.

Внутри эта функция использует PGTYPEStimestamp_fmt_asc. Примеры допустимых масок формата можно найти в её описании.

intoasc #

Преобразует переменную типа interval в строку C char*.

int intoasc(interval *i, char *str);

Эта функция получает указатель (i) на переменную типа interval, которую нужно преобразовать, и строку (str) для сохранения результата операции. Она преобразует i в текстовое представление согласно стандарту SQL, то есть по маске YYYY-MM-DD HH:MM:SS.

В случае успеха возвращается 0, а в случае ошибки — отрицательное значение.

rfmtlong #

Преобразует длинное целое в текстовое представление по маске формата.

int rfmtlong(long lng_val, char *fmt, char *outbuf);

Эта функция принимает значение типа long (lng_val), маску формата (fmt) и указатель на выходной буфер (outbuf). Она преобразует длинное целое в его текстовое представление согласно заданной маске формата.

Маску формата можно составить из следующих символов, определяющих формат:

  • * (звёздочка) — если в данной позиции будет пусто, заполнить её звёздочкой.

  • & (амперсанд) — если в данной позиции будет пусто, заполнить её нулём.

  • # — заменить ведущие нули пробелами.

  • < — выровнять число в строке по левой стороне.

  • , (запятая) — сгруппировать числа, содержащие четыре и более цифр, в группы по три цифры через запятую.

  • . (точка) — этот символ отделяет целую часть числа от дробной.

  • - (минус) — с отрицательным числом должен выводиться знак минус.

  • + (плюс) — с положительным числом должен выводиться знак плюс.

  • ( — это символ заменяет знак минус перед отрицательным числом. Сам знак минус выводиться не будет.

  • ) — этот символ заменяет минус и выводится после отрицательного числа.

  • $ — символ денежной суммы.

rupshift #

Приводит строку к верхнему регистру.

void rupshift(char *str);

Эта функция получает указатель на строку и приводит в ней каждый символ в нижнем регистре к верхнему регистру.

byleng #

Возвращает число символов в строке, не считая завершающих пробелов.

int byleng(char *str, int len);

Эта функция принимает в первом аргументе (str) строку фиксированной длины, а во втором (len) её длину. Она возвращает число значимых символов, то есть длину строки без завершающих пробелов.

ldchar #

Копирует строку фиксированной длины в строку с завершающим нулём.

void ldchar(char *src, int len, char *dest);

Эта функция принимает строку фиксированной длины (src), которую нужно скопировать, её длину (len) и указатель на целевой буфер в памяти (dest). Учтите, что для буфера, на который указывает dest, необходимо выделить как минимум len+1 байт. Данная функция копирует в новую область не больше len байт (меньше, если в исходной строке есть завершающие пробелы) и добавляет завершающий 0.

rgetmsg #
int rgetmsg(int msgnum, char *s, int maxsize);

Эта функция определена, но не реализована на данный момент!

rtypalign #
int rtypalign(int offset, int type);

Эта функция определена, но не реализована на данный момент!

rtypmsize #
int rtypmsize(int type, int len);

Эта функция определена, но не реализована на данный момент!

rtypwidth #
int rtypwidth(int sqltype, int sqllen);

Эта функция определена, но не реализована на данный момент!

rsetnull #

Присваивает переменной NULL.

int rsetnull(int t, char *ptr);

Эта функция получает целое, определяющее тип переменной, и указатель на саму переменную, приведённый к указателю C char*.

Определены следующие типы:

  • CCHARTYPE — для переменной типа char или char*

  • CSHORTTYPE — для переменной типа short int

  • CINTTYPE — для переменной типа int

  • CBOOLTYPE — для переменной типа boolean

  • CFLOATTYPE — для переменной типа float

  • CLONGTYPE — для переменной типа long

  • CDOUBLETYPE — для переменной типа double

  • CDECIMALTYPE — для переменной типа decimal

  • CDATETYPE — для переменной типа date

  • CDTIMETYPE — для переменной типа timestamp

Примеры вызова этой функции:

$char c[] = "abc       ";
$short s = 17;
$int i = -74874;

rsetnull(CCHARTYPE, (char *) c);
rsetnull(CSHORTTYPE, (char *) &s);
rsetnull(CINTTYPE, (char *) &i);

risnull #

Проверяет содержимое переменной на NULL.

int risnull(int t, char *ptr);

Эта функция получает тип проверяемой переменной (t), а также указатель на неё (ptr). Заметьте, что этот указатель нужно привести к char*. Список возможных типов переменных приведён в описании функции rsetnull.

Примеры использования этой функции:

$char c[] = "abc       ";
$short s = 17;
$int i = -74874;

risnull(CCHARTYPE, (char *) c);
risnull(CSHORTTYPE, (char *) &s);
risnull(CINTTYPE, (char *) &i);

38.15.5. Дополнительные константы #

Заметьте, что все эти константы относятся к ошибкам и все они представлены отрицательными значениями. Из описаний различных констант вы также можете узнать, какими именно числами они представлены в текущей реализации. Однако полагаться на эти числа не следует. Тем не менее вы можете рассчитывать на то, что все эти значения будут отрицательными.

ECPG_INFORMIX_NUM_OVERFLOW #

Функции возвращают это значение, если при вычислении происходит переполнение. Внутри оно представляется числом -1200 (определение Informix).

ECPG_INFORMIX_NUM_UNDERFLOW #

Функции возвращают это значение, если при вычислении происходит антипереполнение. Внутри оно представляется числом -1201 (определение Informix).

ECPG_INFORMIX_DIVIDE_ZERO #

Функции возвращают это значение при попытке деления на ноль. Внутри оно представляется числом -1202 (определение Informix).

ECPG_INFORMIX_BAD_YEAR #

Функции возвращают это значение, если при разборе даты встретилось некорректное указание года. Внутри оно представляется числом -1204 (определение Informix).

ECPG_INFORMIX_BAD_MONTH #

Функции возвращают это значение, если при разборе даты встретилось некорректное указание месяца. Внутри оно представляется числом -1205 (определение Informix).

ECPG_INFORMIX_BAD_DAY #

Функции возвращают это значение, если при разборе даты встретилось некорректное указание дня. Внутри оно представляется числом -1206 (определение Informix).

ECPG_INFORMIX_ENOSHORTDATE #

Функции возвращают это значение, если процедуре разбора даты требуется короткая запись даты, но строка даты имеет неподходящую длину. Внутри оно представляется числом -1209 (определение Informix).

ECPG_INFORMIX_DATE_CONVERT #

Функции возвращают это значение, если при форматировании даты происходит ошибка. Внутри оно представляется числом -1210 (определение Informix).

ECPG_INFORMIX_OUT_OF_MEMORY #

Функции возвращают это значение, если им не хватает памяти для выполнения операций. Внутри оно представляется числом -1211 (определение Informix).

ECPG_INFORMIX_ENOTDMY #

Функции возвращают это значение, если процедура разбора должна была получить маску формата (например, mmddyy), но не все поля были записаны правильно. Внутри оно представляется числом -1212 (определение Informix).

ECPG_INFORMIX_BAD_NUMERIC #

Функции возвращают это значение, если процедура разбора не может получить числовое значение из текстового представления, потому что оно некорректно, либо если процедура вычисления не может произвести операцию с числовыми переменными из-за недопустимого значения минимум одной из этих переменных. Внутри оно представляется числом -1213 (определение Informix).

ECPG_INFORMIX_BAD_EXPONENT #

Функции возвращают это значение, если процедура разбора не может воспринять экспоненту в числе. Внутри оно представляется числом -1216 (определение Informix).

ECPG_INFORMIX_BAD_DATE #

Функции возвращают это значение, если процедура разбора не может разобрать дату. Внутри оно представляется числом -1218 (определение Informix).

ECPG_INFORMIX_EXTRA_CHARS #

Функции возвращают это значение, если процедуре разбора передаются посторонние символы, которая она не может разобрать. Внутри оно представляется числом -1264 (определение Informix).

38.15. Informix Compatibility Mode #

ecpg can be run in a so-called Informix compatibility mode. If this mode is active, it tries to behave as if it were the Informix precompiler for Informix E/SQL. Generally spoken this will allow you to use the dollar sign instead of the EXEC SQL primitive to introduce embedded SQL commands:

$int j = 3;
$CONNECT TO :dbname;
$CREATE TABLE test(i INT PRIMARY KEY, j INT);
$INSERT INTO test(i, j) VALUES (7, :j);
$COMMIT;

Note

There must not be any white space between the $ and a following preprocessor directive, that is, include, define, ifdef, etc. Otherwise, the preprocessor will parse the token as a host variable.

There are two compatibility modes: INFORMIX, INFORMIX_SE

When linking programs that use this compatibility mode, remember to link against libcompat that is shipped with ECPG.

Besides the previously explained syntactic sugar, the Informix compatibility mode ports some functions for input, output and transformation of data as well as embedded SQL statements known from E/SQL to ECPG.

Informix compatibility mode is closely connected to the pgtypeslib library of ECPG. pgtypeslib maps SQL data types to data types within the C host program and most of the additional functions of the Informix compatibility mode allow you to operate on those C host program types. Note however that the extent of the compatibility is limited. It does not try to copy Informix behavior; it allows you to do more or less the same operations and gives you functions that have the same name and the same basic behavior but it is no drop-in replacement if you are using Informix at the moment. Moreover, some of the data types are different. For example, Postgres Pro's datetime and interval types do not know about ranges like for example YEAR TO MINUTE so you won't find support in ECPG for that either.

38.15.1. Additional Types #

The Informix-special "string" pseudo-type for storing right-trimmed character string data is now supported in Informix-mode without using typedef. In fact, in Informix-mode, ECPG refuses to process source files that contain typedef sometype string;

EXEC SQL BEGIN DECLARE SECTION;
string userid; /* this variable will contain trimmed data */
EXEC SQL END DECLARE SECTION;

EXEC SQL FETCH MYCUR INTO :userid;

38.15.2. Additional/Missing Embedded SQL Statements #

CLOSE DATABASE #

This statement closes the current connection. In fact, this is a synonym for ECPG's DISCONNECT CURRENT:

$CLOSE DATABASE;                /* close the current connection */
EXEC SQL CLOSE DATABASE;

FREE cursor_name #

Due to differences in how ECPG works compared to Informix's ESQL/C (namely, which steps are purely grammar transformations and which steps rely on the underlying run-time library) there is no FREE cursor_name statement in ECPG. This is because in ECPG, DECLARE CURSOR doesn't translate to a function call into the run-time library that uses to the cursor name. This means that there's no run-time bookkeeping of SQL cursors in the ECPG run-time library, only in the Postgres Pro server.

FREE statement_name #

FREE statement_name is a synonym for DEALLOCATE PREPARE statement_name.

38.15.3. Informix-compatible SQLDA Descriptor Areas #

Informix-compatible mode supports a different structure than the one described in Section 38.7.2. See below:

struct sqlvar_compat
{
    short   sqltype;
    int     sqllen;
    char   *sqldata;
    short  *sqlind;
    char   *sqlname;
    char   *sqlformat;
    short   sqlitype;
    short   sqlilen;
    char   *sqlidata;
    int     sqlxid;
    char   *sqltypename;
    short   sqltypelen;
    short   sqlownerlen;
    short   sqlsourcetype;
    char   *sqlownername;
    int     sqlsourceid;
    char   *sqlilongdata;
    int     sqlflags;
    void   *sqlreserved;
};

struct sqlda_compat
{
    short  sqld;
    struct sqlvar_compat *sqlvar;
    char   desc_name[19];
    short  desc_occ;
    struct sqlda_compat *desc_next;
    void  *reserved;
};

typedef struct sqlvar_compat    sqlvar_t;
typedef struct sqlda_compat     sqlda_t;

The global properties are:

sqld #

The number of fields in the SQLDA descriptor.

sqlvar #

Pointer to the per-field properties.

desc_name #

Unused, filled with zero-bytes.

desc_occ #

Size of the allocated structure.

desc_next #

Pointer to the next SQLDA structure if the result set contains more than one record.

reserved #

Unused pointer, contains NULL. Kept for Informix-compatibility.

The per-field properties are below, they are stored in the sqlvar array:

sqltype #

Type of the field. Constants are in sqltypes.h

sqllen #

Length of the field data.

sqldata #

Pointer to the field data. The pointer is of char * type, the data pointed by it is in a binary format. Example:

int intval;

switch (sqldata->sqlvar[i].sqltype)
{
    case SQLINTEGER:
        intval = *(int *)sqldata->sqlvar[i].sqldata;
        break;
  ...
}

sqlind #

Pointer to the NULL indicator. If returned by DESCRIBE or FETCH then it's always a valid pointer. If used as input for EXECUTE ... USING sqlda; then NULL-pointer value means that the value for this field is non-NULL. Otherwise a valid pointer and sqlitype has to be properly set. Example:

if (*(int2 *)sqldata->sqlvar[i].sqlind != 0)
    printf("value is NULL\n");

sqlname #

Name of the field. 0-terminated string.

sqlformat #

Reserved in Informix, value of PQfformat for the field.

sqlitype #

Type of the NULL indicator data. It's always SQLSMINT when returning data from the server. When the SQLDA is used for a parameterized query, the data is treated according to the set type.

sqlilen #

Length of the NULL indicator data.

sqlxid #

Extended type of the field, result of PQftype.

sqltypename
sqltypelen
sqlownerlen
sqlsourcetype
sqlownername
sqlsourceid
sqlflags
sqlreserved #

Unused.

sqlilongdata #

It equals to sqldata if sqllen is larger than 32kB.

Example:

EXEC SQL INCLUDE sqlda.h;

    sqlda_t        *sqlda; /* This doesn't need to be under embedded DECLARE SECTION */

    EXEC SQL BEGIN DECLARE SECTION;
    char *prep_stmt = "select * from table1";
    int i;
    EXEC SQL END DECLARE SECTION;

    ...

    EXEC SQL PREPARE mystmt FROM :prep_stmt;

    EXEC SQL DESCRIBE mystmt INTO sqlda;

    printf("# of fields: %d\n", sqlda->sqld);
    for (i = 0; i < sqlda->sqld; i++)
      printf("field %d: \"%s\"\n", sqlda->sqlvar[i]->sqlname);

    EXEC SQL DECLARE mycursor CURSOR FOR mystmt;
    EXEC SQL OPEN mycursor;
    EXEC SQL WHENEVER NOT FOUND GOTO out;

    while (1)
    {
      EXEC SQL FETCH mycursor USING sqlda;
    }

    EXEC SQL CLOSE mycursor;

    free(sqlda); /* The main structure is all to be free(),
                  * sqlda and sqlda->sqlvar is in one allocated area */

38.15.4. Additional Functions #

decadd #

Add two decimal type values.

int decadd(decimal *arg1, decimal *arg2, decimal *sum);

The function receives a pointer to the first operand of type decimal (arg1), a pointer to the second operand of type decimal (arg2) and a pointer to a value of type decimal that will contain the sum (sum). On success, the function returns 0. ECPG_INFORMIX_NUM_OVERFLOW is returned in case of overflow and ECPG_INFORMIX_NUM_UNDERFLOW in case of underflow. -1 is returned for other failures and errno is set to the respective errno number of the pgtypeslib.

deccmp #

Compare two variables of type decimal.

int deccmp(decimal *arg1, decimal *arg2);

The function receives a pointer to the first decimal value (arg1), a pointer to the second decimal value (arg2) and returns an integer value that indicates which is the bigger value.

  • 1, if the value that arg1 points to is bigger than the value that var2 points to

  • -1, if the value that arg1 points to is smaller than the value that arg2 points to

  • 0, if the value that arg1 points to and the value that arg2 points to are equal

deccopy #

Copy a decimal value.

void deccopy(decimal *src, decimal *target);

The function receives a pointer to the decimal value that should be copied as the first argument (src) and a pointer to the target structure of type decimal (target) as the second argument.

deccvasc #

Convert a value from its ASCII representation into a decimal type.

int deccvasc(char *cp, int len, decimal *np);

The function receives a pointer to string that contains the string representation of the number to be converted (cp) as well as its length len. np is a pointer to the decimal value that saves the result of the operation.

Valid formats are for example: -2, .794, +3.44, 592.49E07 or -32.84e-4.

The function returns 0 on success. If overflow or underflow occurred, ECPG_INFORMIX_NUM_OVERFLOW or ECPG_INFORMIX_NUM_UNDERFLOW is returned. If the ASCII representation could not be parsed, ECPG_INFORMIX_BAD_NUMERIC is returned or ECPG_INFORMIX_BAD_EXPONENT if this problem occurred while parsing the exponent.

deccvdbl #

Convert a value of type double to a value of type decimal.

int deccvdbl(double dbl, decimal *np);

The function receives the variable of type double that should be converted as its first argument (dbl). As the second argument (np), the function receives a pointer to the decimal variable that should hold the result of the operation.

The function returns 0 on success and a negative value if the conversion failed.

deccvint #

Convert a value of type int to a value of type decimal.

int deccvint(int in, decimal *np);

The function receives the variable of type int that should be converted as its first argument (in). As the second argument (np), the function receives a pointer to the decimal variable that should hold the result of the operation.

The function returns 0 on success and a negative value if the conversion failed.

deccvlong #

Convert a value of type long to a value of type decimal.

int deccvlong(long lng, decimal *np);

The function receives the variable of type long that should be converted as its first argument (lng). As the second argument (np), the function receives a pointer to the decimal variable that should hold the result of the operation.

The function returns 0 on success and a negative value if the conversion failed.

decdiv #

Divide two variables of type decimal.

int decdiv(decimal *n1, decimal *n2, decimal *result);

The function receives pointers to the variables that are the first (n1) and the second (n2) operands and calculates n1/n2. result is a pointer to the variable that should hold the result of the operation.

On success, 0 is returned and a negative value if the division fails. If overflow or underflow occurred, the function returns ECPG_INFORMIX_NUM_OVERFLOW or ECPG_INFORMIX_NUM_UNDERFLOW respectively. If an attempt to divide by zero is observed, the function returns ECPG_INFORMIX_DIVIDE_ZERO.

decmul #

Multiply two decimal values.

int decmul(decimal *n1, decimal *n2, decimal *result);

The function receives pointers to the variables that are the first (n1) and the second (n2) operands and calculates n1*n2. result is a pointer to the variable that should hold the result of the operation.

On success, 0 is returned and a negative value if the multiplication fails. If overflow or underflow occurred, the function returns ECPG_INFORMIX_NUM_OVERFLOW or ECPG_INFORMIX_NUM_UNDERFLOW respectively.

decsub #

Subtract one decimal value from another.

int decsub(decimal *n1, decimal *n2, decimal *result);

The function receives pointers to the variables that are the first (n1) and the second (n2) operands and calculates n1-n2. result is a pointer to the variable that should hold the result of the operation.

On success, 0 is returned and a negative value if the subtraction fails. If overflow or underflow occurred, the function returns ECPG_INFORMIX_NUM_OVERFLOW or ECPG_INFORMIX_NUM_UNDERFLOW respectively.

dectoasc #

Convert a variable of type decimal to its ASCII representation in a C char* string.

int dectoasc(decimal *np, char *cp, int len, int right)

The function receives a pointer to a variable of type decimal (np) that it converts to its textual representation. cp is the buffer that should hold the result of the operation. The parameter right specifies, how many digits right of the decimal point should be included in the output. The result will be rounded to this number of decimal digits. Setting right to -1 indicates that all available decimal digits should be included in the output. If the length of the output buffer, which is indicated by len is not sufficient to hold the textual representation including the trailing zero byte, only a single * character is stored in the result and -1 is returned.

The function returns either -1 if the buffer cp was too small or ECPG_INFORMIX_OUT_OF_MEMORY if memory was exhausted.

dectodbl #

Convert a variable of type decimal to a double.

int dectodbl(decimal *np, double *dblp);

The function receives a pointer to the decimal value to convert (np) and a pointer to the double variable that should hold the result of the operation (dblp).

On success, 0 is returned and a negative value if the conversion failed.

dectoint #

Convert a variable of type decimal to an integer.

int dectoint(decimal *np, int *ip);

The function receives a pointer to the decimal value to convert (np) and a pointer to the integer variable that should hold the result of the operation (ip).

On success, 0 is returned and a negative value if the conversion failed. If an overflow occurred, ECPG_INFORMIX_NUM_OVERFLOW is returned.

Note that the ECPG implementation differs from the Informix implementation. Informix limits an integer to the range from -32767 to 32767, while the limits in the ECPG implementation depend on the architecture (INT_MIN .. INT_MAX).

dectolong #

Convert a variable of type decimal to a long integer.

int dectolong(decimal *np, long *lngp);

The function receives a pointer to the decimal value to convert (np) and a pointer to the long variable that should hold the result of the operation (lngp).

On success, 0 is returned and a negative value if the conversion failed. If an overflow occurred, ECPG_INFORMIX_NUM_OVERFLOW is returned.

Note that the ECPG implementation differs from the Informix implementation. Informix limits a long integer to the range from -2,147,483,647 to 2,147,483,647, while the limits in the ECPG implementation depend on the architecture (-LONG_MAX .. LONG_MAX).

rdatestr #

Converts a date to a C char* string.

int rdatestr(date d, char *str);

The function receives two arguments, the first one is the date to convert (d) and the second one is a pointer to the target string. The output format is always yyyy-mm-dd, so you need to allocate at least 11 bytes (including the zero-byte terminator) for the string.

The function returns 0 on success and a negative value in case of error.

Note that ECPG's implementation differs from the Informix implementation. In Informix the format can be influenced by setting environment variables. In ECPG however, you cannot change the output format.

rstrdate #

Parse the textual representation of a date.

int rstrdate(char *str, date *d);

The function receives the textual representation of the date to convert (str) and a pointer to a variable of type date (d). This function does not allow you to specify a format mask. It uses the default format mask of Informix which is mm/dd/yyyy. Internally, this function is implemented by means of rdefmtdate. Therefore, rstrdate is not faster and if you have the choice you should opt for rdefmtdate which allows you to specify the format mask explicitly.

The function returns the same values as rdefmtdate.

rtoday #

Get the current date.

void rtoday(date *d);

The function receives a pointer to a date variable (d) that it sets to the current date.

Internally this function uses the PGTYPESdate_today function.

rjulmdy #

Extract the values for the day, the month and the year from a variable of type date.

int rjulmdy(date d, short mdy[3]);

The function receives the date d and a pointer to an array of 3 short integer values mdy. 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 and mdy[2] will contain the year.

The function always returns 0 at the moment.

Internally the function uses the PGTYPESdate_julmdy function.

rdefmtdate #

Use a format mask to convert a character string to a value of type date.

int rdefmtdate(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 literals yy or yyyy that indicate the position of the year, mm to indicate the position of the month and dd to indicate the position of the day.

The function returns the following values:

  • 0 - The function terminated successfully.

  • ECPG_INFORMIX_ENOSHORTDATE - The date does not contain delimiters between day, month and year. In this case the input string must be exactly 6 or 8 bytes long but isn't.

  • ECPG_INFORMIX_ENOTDMY - The format string did not correctly indicate the sequential order of year, month and day.

  • ECPG_INFORMIX_BAD_DAY - The input string does not contain a valid day.

  • ECPG_INFORMIX_BAD_MONTH - The input string does not contain a valid month.

  • ECPG_INFORMIX_BAD_YEAR - The input string does not contain a valid year.

Internally this function is implemented to use the PGTYPESdate_defmt_asc function. See the reference there for a table of example input.

rfmtdate #

Convert a variable of type date to its textual representation using a format mask.

int rfmtdate(date d, char *fmt, char *str);

The function receives the date to convert (d), the format mask (fmt) and the string that will hold the textual representation of the date (str).

On success, 0 is returned and a negative value if an error occurred.

Internally this function uses the PGTYPESdate_fmt_asc function, see the reference there for examples.

rmdyjul #

Create a date value from an array of 3 short integers that specify the day, the month and the year of the date.

int rmdyjul(short mdy[3], date *d);

The function receives the array of the 3 short integers (mdy) and a pointer to a variable of type date that should hold the result of the operation.

Currently the function returns always 0.

Internally the function is implemented to use the function PGTYPESdate_mdyjul.

rdayofweek #

Return a number representing the day of the week for a date value.

int rdayofweek(date d);

The function receives the date variable d as 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

Internally the function is implemented to use the function PGTYPESdate_dayofweek.

dtcurrent #

Retrieve the current timestamp.

void dtcurrent(timestamp *ts);

The function retrieves the current timestamp and saves it into the timestamp variable that ts points to.

dtcvasc #

Parses a timestamp from its textual representation into a timestamp variable.

int dtcvasc(char *str, timestamp *ts);

The function receives the string to parse (str) and a pointer to the timestamp variable that should hold the result of the operation (ts).

The function returns 0 on success and a negative value in case of error.

Internally this function uses the PGTYPEStimestamp_from_asc function. See the reference there for a table with example inputs.

dtcvfmtasc #

Parses a timestamp from its textual representation using a format mask into a timestamp variable.

dtcvfmtasc(char *inbuf, char *fmtstr, timestamp *dtvalue)

The function receives the string to parse (inbuf), the format mask to use (fmtstr) and a pointer to the timestamp variable that should hold the result of the operation (dtvalue).

This function is implemented by means of the PGTYPEStimestamp_defmt_asc function. See the documentation there for a list of format specifiers that can be used.

The function returns 0 on success and a negative value in case of error.

dtsub #

Subtract one timestamp from another and return a variable of type interval.

int dtsub(timestamp *ts1, timestamp *ts2, interval *iv);

The function will subtract the timestamp variable that ts2 points to from the timestamp variable that ts1 points to and will store the result in the interval variable that iv points to.

Upon success, the function returns 0 and a negative value if an error occurred.

dttoasc #

Convert a timestamp variable to a C char* string.

int dttoasc(timestamp *ts, char *output);

The function receives a pointer to the timestamp variable to convert (ts) and the string that should hold the result of the operation (output). It converts ts to its textual representation according to the SQL standard, which is be YYYY-MM-DD HH:MM:SS.

Upon success, the function returns 0 and a negative value if an error occurred.

dttofmtasc #

Convert a timestamp variable to a C char* using a format mask.

int dttofmtasc(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.

Internally, this function uses the PGTYPEStimestamp_fmt_asc function. See the reference there for information on what format mask specifiers can be used.

intoasc #

Convert an interval variable to a C char* string.

int intoasc(interval *i, char *str);

The function receives a pointer to the interval variable to convert (i) and the string that should hold the result of the operation (str). It converts i to its textual representation according to the SQL standard, which is be YYYY-MM-DD HH:MM:SS.

Upon success, the function returns 0 and a negative value if an error occurred.

rfmtlong #

Convert a long integer value to its textual representation using a format mask.

int rfmtlong(long lng_val, char *fmt, char *outbuf);

The function receives the long value lng_val, the format mask fmt and a pointer to the output buffer outbuf. It converts the long value according to the format mask to its textual representation.

The format mask can be composed of the following format specifying characters:

  • * (asterisk) - if this position would be blank otherwise, fill it with an asterisk.

  • & (ampersand) - if this position would be blank otherwise, fill it with a zero.

  • # - turn leading zeroes into blanks.

  • < - left-justify the number in the string.

  • , (comma) - group numbers of four or more digits into groups of three digits separated by a comma.

  • . (period) - this character separates the whole-number part of the number from the fractional part.

  • - (minus) - the minus sign appears if the number is a negative value.

  • + (plus) - the plus sign appears if the number is a positive value.

  • ( - this replaces the minus sign in front of the negative number. The minus sign will not appear.

  • ) - this character replaces the minus and is printed behind the negative value.

  • $ - the currency symbol.

rupshift #

Convert a string to upper case.

void rupshift(char *str);

The function receives a pointer to the string and transforms every lower case character to upper case.

byleng #

Return the number of characters in a string without counting trailing blanks.

int byleng(char *str, int len);

The function expects a fixed-length string as its first argument (str) and its length as its second argument (len). It returns the number of significant characters, that is the length of the string without trailing blanks.

ldchar #

Copy a fixed-length string into a null-terminated string.

void ldchar(char *src, int len, char *dest);

The function receives the fixed-length string to copy (src), its length (len) and a pointer to the destination memory (dest). Note that you need to reserve at least len+1 bytes for the string that dest points to. The function copies at most len bytes to the new location (less if the source string has trailing blanks) and adds the null-terminator.

rgetmsg #

int rgetmsg(int msgnum, char *s, int maxsize);

This function exists but is not implemented at the moment!

rtypalign #

int rtypalign(int offset, int type);

This function exists but is not implemented at the moment!

rtypmsize #

int rtypmsize(int type, int len);

This function exists but is not implemented at the moment!

rtypwidth #

int rtypwidth(int sqltype, int sqllen);

This function exists but is not implemented at the moment!

rsetnull #

Set a variable to NULL.

int rsetnull(int t, char *ptr);

The function receives an integer that indicates the type of the variable and a pointer to the variable itself that is cast to a C char* pointer.

The following types exist:

  • CCHARTYPE - For a variable of type char or char*

  • CSHORTTYPE - For a variable of type short int

  • CINTTYPE - For a variable of type int

  • CBOOLTYPE - For a variable of type boolean

  • CFLOATTYPE - For a variable of type float

  • CLONGTYPE - For a variable of type long

  • CDOUBLETYPE - For a variable of type double

  • CDECIMALTYPE - For a variable of type decimal

  • CDATETYPE - For a variable of type date

  • CDTIMETYPE - For a variable of type timestamp

Here is an example of a call to this function:

$char c[] = "abc       ";
$short s = 17;
$int i = -74874;

rsetnull(CCHARTYPE, (char *) c);
rsetnull(CSHORTTYPE, (char *) &s);
rsetnull(CINTTYPE, (char *) &i);

risnull #

Test if a variable is NULL.

int risnull(int t, char *ptr);

The function receives the type of the variable to test (t) as well a pointer to this variable (ptr). Note that the latter needs to be cast to a char*. See the function rsetnull for a list of possible variable types.

Here is an example of how to use this function:

$char c[] = "abc       ";
$short s = 17;
$int i = -74874;

risnull(CCHARTYPE, (char *) c);
risnull(CSHORTTYPE, (char *) &s);
risnull(CINTTYPE, (char *) &i);

38.15.5. Additional Constants #

Note that all constants here describe errors and all of them are defined to represent negative values. In the descriptions of the different constants you can also find the value that the constants represent in the current implementation. However you should not rely on this number. You can however rely on the fact all of them are defined to represent negative values.

ECPG_INFORMIX_NUM_OVERFLOW #

Functions return this value if an overflow occurred in a calculation. Internally it is defined as -1200 (the Informix definition).

ECPG_INFORMIX_NUM_UNDERFLOW #

Functions return this value if an underflow occurred in a calculation. Internally it is defined as -1201 (the Informix definition).

ECPG_INFORMIX_DIVIDE_ZERO #

Functions return this value if an attempt to divide by zero is observed. Internally it is defined as -1202 (the Informix definition).

ECPG_INFORMIX_BAD_YEAR #

Functions return this value if a bad value for a year was found while parsing a date. Internally it is defined as -1204 (the Informix definition).

ECPG_INFORMIX_BAD_MONTH #

Functions return this value if a bad value for a month was found while parsing a date. Internally it is defined as -1205 (the Informix definition).

ECPG_INFORMIX_BAD_DAY #

Functions return this value if a bad value for a day was found while parsing a date. Internally it is defined as -1206 (the Informix definition).

ECPG_INFORMIX_ENOSHORTDATE #

Functions return this value if a parsing routine needs a short date representation but did not get the date string in the right length. Internally it is defined as -1209 (the Informix definition).

ECPG_INFORMIX_DATE_CONVERT #

Functions return this value if an error occurred during date formatting. Internally it is defined as -1210 (the Informix definition).

ECPG_INFORMIX_OUT_OF_MEMORY #

Functions return this value if memory was exhausted during their operation. Internally it is defined as -1211 (the Informix definition).

ECPG_INFORMIX_ENOTDMY #

Functions return this value if a parsing routine was supposed to get a format mask (like mmddyy) but not all fields were listed correctly. Internally it is defined as -1212 (the Informix definition).

ECPG_INFORMIX_BAD_NUMERIC #

Functions return this value either if a parsing routine cannot parse the textual representation for a numeric value because it contains errors or if a routine cannot complete a calculation involving numeric variables because at least one of the numeric variables is invalid. Internally it is defined as -1213 (the Informix definition).

ECPG_INFORMIX_BAD_EXPONENT #

Functions return this value if a parsing routine cannot parse an exponent. Internally it is defined as -1216 (the Informix definition).

ECPG_INFORMIX_BAD_DATE #

Functions return this value if a parsing routine cannot parse a date. Internally it is defined as -1218 (the Informix definition).

ECPG_INFORMIX_EXTRA_CHARS #

Functions return this value if a parsing routine is passed extra characters it cannot parse. Internally it is defined as -1264 (the Informix definition).

FAQ