aboutsummaryrefslogtreecommitdiff
path: root/src/backend/utils
diff options
context:
space:
mode:
Diffstat (limited to 'src/backend/utils')
-rw-r--r--src/backend/utils/adt/acl.c6
-rw-r--r--src/backend/utils/adt/cash.c3
-rw-r--r--src/backend/utils/adt/date.c66
-rw-r--r--src/backend/utils/adt/datetime.c112
-rw-r--r--src/backend/utils/adt/float.c50
-rw-r--r--src/backend/utils/adt/formatting.c4745
-rw-r--r--src/backend/utils/adt/geo_ops.c4
-rw-r--r--src/backend/utils/adt/geo_selfuncs.c4
-rw-r--r--src/backend/utils/adt/int.c17
-rw-r--r--src/backend/utils/adt/int8.c10
-rw-r--r--src/backend/utils/adt/like.c38
-rw-r--r--src/backend/utils/adt/lztext.c108
-rw-r--r--src/backend/utils/adt/nabstime.c22
-rw-r--r--src/backend/utils/adt/name.c5
-rw-r--r--src/backend/utils/adt/network.c6
-rw-r--r--src/backend/utils/adt/numeric.c126
-rw-r--r--src/backend/utils/adt/numutils.c4
-rw-r--r--src/backend/utils/adt/oid.c13
-rw-r--r--src/backend/utils/adt/oracle_compat.c41
-rw-r--r--src/backend/utils/adt/pg_locale.c110
-rw-r--r--src/backend/utils/adt/pg_lzcompress.c262
-rw-r--r--src/backend/utils/adt/regproc.c4
-rw-r--r--src/backend/utils/adt/ri_triggers.c1613
-rw-r--r--src/backend/utils/adt/ruleutils.c124
-rw-r--r--src/backend/utils/adt/selfuncs.c443
-rw-r--r--src/backend/utils/adt/tid.c45
-rw-r--r--src/backend/utils/adt/timestamp.c50
-rw-r--r--src/backend/utils/adt/varbit.c1382
-rw-r--r--src/backend/utils/adt/varchar.c3
-rw-r--r--src/backend/utils/adt/varlena.c10
-rw-r--r--src/backend/utils/cache/catcache.c99
-rw-r--r--src/backend/utils/cache/fcache.c7
-rw-r--r--src/backend/utils/cache/inval.c99
-rw-r--r--src/backend/utils/cache/lsyscache.c39
-rw-r--r--src/backend/utils/cache/relcache.c194
-rw-r--r--src/backend/utils/cache/syscache.c55
-rw-r--r--src/backend/utils/cache/temprel.c8
-rw-r--r--src/backend/utils/error/elog.c104
-rw-r--r--src/backend/utils/fmgr/dfmgr.c13
-rw-r--r--src/backend/utils/hash/dynahash.c15
-rw-r--r--src/backend/utils/init/globals.c5
-rw-r--r--src/backend/utils/init/miscinit.c134
-rw-r--r--src/backend/utils/init/postinit.c159
-rw-r--r--src/backend/utils/mb/conv.c1770
-rw-r--r--src/backend/utils/mb/wchar.c4
-rw-r--r--src/backend/utils/misc/database.c73
-rw-r--r--src/backend/utils/misc/trace.c22
-rw-r--r--src/backend/utils/mmgr/aset.c24
-rw-r--r--src/backend/utils/mmgr/oset.c3
-rw-r--r--src/backend/utils/mmgr/portalmem.c6
-rw-r--r--src/backend/utils/sort/logtape.c252
-rw-r--r--src/backend/utils/sort/tuplesort.c647
52 files changed, 7388 insertions, 5770 deletions
diff --git a/src/backend/utils/adt/acl.c b/src/backend/utils/adt/acl.c
index 1533b5f18df..6c27fbe03fa 100644
--- a/src/backend/utils/adt/acl.c
+++ b/src/backend/utils/adt/acl.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/acl.c,v 1.44 2000/01/26 05:57:12 momjian Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/acl.c,v 1.45 2000/04/12 17:15:47 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -681,8 +681,8 @@ ChangeACLStmt *
makeAclStmt(char *privileges, List *rel_list, char *grantee,
char grant_or_revoke)
{
- ChangeACLStmt *n = makeNode(ChangeACLStmt);
- StringInfoData str;
+ ChangeACLStmt *n = makeNode(ChangeACLStmt);
+ StringInfoData str;
initStringInfo(&str);
diff --git a/src/backend/utils/adt/cash.c b/src/backend/utils/adt/cash.c
index a255e2a3d0e..d19749ab014 100644
--- a/src/backend/utils/adt/cash.c
+++ b/src/backend/utils/adt/cash.c
@@ -9,7 +9,7 @@
* workings can be found in the book "Software Solutions in C" by
* Dale Schumacher, Academic Press, ISBN: 0-12-632360-7.
*
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/cash.c,v 1.34 2000/03/19 22:10:52 tgl Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/cash.c,v 1.35 2000/04/12 17:15:48 momjian Exp $
*/
#include <limits.h>
@@ -32,6 +32,7 @@ static const char *num_word(Cash value);
#ifdef USE_LOCALE
static struct lconv *lconvert = NULL;
+
#endif
/* cash_in()
diff --git a/src/backend/utils/adt/date.c b/src/backend/utils/adt/date.c
index 378289373b8..e0d361152fa 100644
--- a/src/backend/utils/adt/date.c
+++ b/src/backend/utils/adt/date.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/date.c,v 1.43 2000/03/14 23:06:35 thomas Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/date.c,v 1.44 2000/04/12 17:15:48 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -22,7 +22,7 @@
#include "utils/builtins.h"
static int
-date2tm(DateADT dateVal, int *tzp, struct tm * tm, double *fsec, char **tzn);
+ date2tm(DateADT dateVal, int *tzp, struct tm * tm, double *fsec, char **tzn);
/*****************************************************************************
@@ -188,10 +188,10 @@ date_mii(DateADT dateVal, int4 days)
/* date_timestamp()
* Convert date to timestamp data type.
*/
-Timestamp *
+Timestamp *
date_timestamp(DateADT dateVal)
{
- Timestamp *result;
+ Timestamp *result;
struct tm tt,
*tm = &tt;
int tz;
@@ -392,7 +392,7 @@ time_in(char *str)
elog(ERROR, "Bad (null) time external representation");
if ((ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf) != 0)
- || (DecodeTimeOnly(field, ftype, nf, &dtype, tm, &fsec, NULL) != 0))
+ || (DecodeTimeOnly(field, ftype, nf, &dtype, tm, &fsec, NULL) != 0))
elog(ERROR, "Bad time external representation '%s'", str);
time = palloc(sizeof(*time));
@@ -492,16 +492,16 @@ time_cmp(TimeADT *time1, TimeADT *time2)
return (*time1 < *time2) ? -1 : (((*time1 > *time2) ? 1 : 0));
} /* time_cmp() */
-TimeADT *
+TimeADT *
time_larger(TimeADT *time1, TimeADT *time2)
{
- return time_gt(time1, time2)? time1: time2;
+ return time_gt(time1, time2) ? time1 : time2;
} /* time_larger() */
-TimeADT *
+TimeADT *
time_smaller(TimeADT *time1, TimeADT *time2)
{
- return time_lt(time1, time2)? time1: time2;
+ return time_lt(time1, time2) ? time1 : time2;
} /* time_smaller() */
/* overlaps_time()
@@ -514,19 +514,21 @@ overlaps_time(TimeADT *ts1, TimeADT *te1, TimeADT *ts2, TimeADT *te2)
/* Make sure we have ordered pairs... */
if (time_gt(ts1, te1))
{
- TimeADT *tt = ts1;
+ TimeADT *tt = ts1;
+
ts1 = te1;
te1 = tt;
}
if (time_gt(ts2, te2))
{
- TimeADT *tt = ts2;
+ TimeADT *tt = ts2;
+
ts2 = te2;
te2 = tt;
}
return ((time_gt(ts1, ts2) && (time_lt(ts1, te2) || time_lt(te1, te2)))
- || (time_gt(ts2, ts1) && (time_lt(ts2, te1) || time_lt(te2, te1)))
+ || (time_gt(ts2, ts1) && (time_lt(ts2, te1) || time_lt(te2, te1)))
|| time_eq(ts1, ts2));
}
@@ -550,13 +552,9 @@ timestamp_time(Timestamp *timestamp)
elog(ERROR, "Unable to convert timestamp to date");
if (TIMESTAMP_IS_EPOCH(*timestamp))
- {
timestamp2tm(SetTimestamp(*timestamp), NULL, tm, &fsec, NULL);
- }
else if (TIMESTAMP_IS_CURRENT(*timestamp))
- {
timestamp2tm(SetTimestamp(*timestamp), &tz, tm, &fsec, &tzn);
- }
else
{
if (timestamp2tm(*timestamp, &tz, tm, &fsec, &tzn) != 0)
@@ -574,10 +572,10 @@ timestamp_time(Timestamp *timestamp)
/* datetime_timestamp()
* Convert date and time to timestamp data type.
*/
-Timestamp *
+Timestamp *
datetime_timestamp(DateADT date, TimeADT *time)
{
- Timestamp *result;
+ Timestamp *result;
if (!PointerIsValid(time))
{
@@ -618,7 +616,7 @@ time_interval(TimeADT *time)
*****************************************************************************/
-TimeTzADT *
+TimeTzADT *
timetz_in(char *str)
{
TimeTzADT *time;
@@ -638,7 +636,7 @@ timetz_in(char *str)
elog(ERROR, "Bad (null) time external representation");
if ((ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf) != 0)
- || (DecodeTimeOnly(field, ftype, nf, &dtype, tm, &fsec, &tz) != 0))
+ || (DecodeTimeOnly(field, ftype, nf, &dtype, tm, &fsec, &tz) != 0))
elog(ERROR, "Bad time external representation '%s'", str);
time = palloc(sizeof(*time));
@@ -738,19 +736,19 @@ timetz_ge(TimeTzADT *time1, TimeTzADT *time2)
int
timetz_cmp(TimeTzADT *time1, TimeTzADT *time2)
{
- return (timetz_lt(time1, time2) ? -1 : (timetz_gt(time1, time2)? 1: 0));
+ return (timetz_lt(time1, time2) ? -1 : (timetz_gt(time1, time2) ? 1 : 0));
} /* timetz_cmp() */
-TimeTzADT *
+TimeTzADT *
timetz_larger(TimeTzADT *time1, TimeTzADT *time2)
{
- return timetz_gt(time1, time2)? time1: time2;
+ return timetz_gt(time1, time2) ? time1 : time2;
} /* timetz_larger() */
-TimeTzADT *
+TimeTzADT *
timetz_smaller(TimeTzADT *time1, TimeTzADT *time2)
{
- return timetz_lt(time1, time2)? time1: time2;
+ return timetz_lt(time1, time2) ? time1 : time2;
} /* timetz_smaller() */
/* overlaps_timetz()
@@ -763,13 +761,15 @@ overlaps_timetz(TimeTzADT *ts1, TimeTzADT *te1, TimeTzADT *ts2, TimeTzADT *te2)
/* Make sure we have ordered pairs... */
if (timetz_gt(ts1, te1))
{
- TimeTzADT *tt = ts1;
+ TimeTzADT *tt = ts1;
+
ts1 = te1;
te1 = tt;
}
if (timetz_gt(ts2, te2))
{
- TimeTzADT *tt = ts2;
+ TimeTzADT *tt = ts2;
+
ts2 = te2;
te2 = tt;
}
@@ -782,10 +782,10 @@ overlaps_timetz(TimeTzADT *ts1, TimeTzADT *te1, TimeTzADT *ts2, TimeTzADT *te2)
/* timestamp_timetz()
* Convert timestamp to timetz data type.
*/
-TimeTzADT *
+TimeTzADT *
timestamp_timetz(Timestamp *timestamp)
{
- TimeTzADT *result;
+ TimeTzADT *result;
struct tm tt,
*tm = &tt;
int tz;
@@ -804,9 +804,7 @@ timestamp_timetz(Timestamp *timestamp)
tz = 0;
}
else if (TIMESTAMP_IS_CURRENT(*timestamp))
- {
timestamp2tm(SetTimestamp(*timestamp), &tz, tm, &fsec, &tzn);
- }
else
{
if (timestamp2tm(*timestamp, &tz, tm, &fsec, &tzn) != 0)
@@ -828,7 +826,7 @@ timestamp_timetz(Timestamp *timestamp)
* stored with the timetz to the result.
* - thomas 2000-03-10
*/
-Timestamp *
+Timestamp *
datetimetz_timestamp(DateADT date, TimeTzADT *time)
{
Timestamp *result;
@@ -841,9 +839,7 @@ datetimetz_timestamp(DateADT date, TimeTzADT *time)
result = palloc(sizeof(*result));
if (!PointerIsValid(date) || !PointerIsValid(time))
- {
TIMESTAMP_INVALID(*result);
- }
else
{
if (date2tm(date, &tz, tm, &fsec, &tzn) != 0)
@@ -857,5 +853,3 @@ datetimetz_timestamp(DateADT date, TimeTzADT *time)
return result;
} /* datetimetz_timestamp() */
-
-
diff --git a/src/backend/utils/adt/datetime.c b/src/backend/utils/adt/datetime.c
index 6d52d2f2817..2f899d21e93 100644
--- a/src/backend/utils/adt/datetime.c
+++ b/src/backend/utils/adt/datetime.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/datetime.c,v 1.45 2000/03/29 03:57:18 thomas Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/datetime.c,v 1.46 2000/04/12 17:15:49 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -35,7 +35,7 @@
#define USE_DATE_CACHE 1
#define ROUND_ALL 0
-static int DecodePosixTimezone(char *str, int *val);
+static int DecodePosixTimezone(char *str, int *val);
int day_tab[2][13] = {
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0},
@@ -457,23 +457,24 @@ ParseDateTime(char *timestr, char *lowstr,
while (isalpha(*cp))
*lp++ = tolower(*cp++);
- /* Full date string with leading text month?
- * Could also be a POSIX time zone...
+ /*
+ * Full date string with leading text month? Could also be a
+ * POSIX time zone...
*/
if ((*cp == '-') || (*cp == '/') || (*cp == '.'))
{
#if 0
+
/*
- * special case of Posix timezone "GMT-0800"
- * Note that other sign (e.g. "GMT+0800"
- * is recognized as two separate fields and handled later.
- * XXX There is no room for a delimiter between
- * the "GMT" and the "-0800", so we are going to just swallow the "GMT".
- * But this leads to other troubles with the definition of signs,
- * so we have to flip
- * - thomas 2000-02-06
+ * special case of Posix timezone "GMT-0800" Note that
+ * other sign (e.g. "GMT+0800" is recognized as two
+ * separate fields and handled later. XXX There is no room
+ * for a delimiter between the "GMT" and the "-0800", so
+ * we are going to just swallow the "GMT". But this leads
+ * to other troubles with the definition of signs, so we
+ * have to flip - thomas 2000-02-06
*/
- if ((*cp == '-') && isdigit(*(cp+1))
+ if ((*cp == '-') && isdigit(*(cp + 1))
&& (strncmp(field[nf], "gmt", 3) == 0))
{
*cp = '+';
@@ -586,7 +587,8 @@ DecodeDateTime(char **field, int *ftype, int nf,
tm->tm_min = 0;
tm->tm_sec = 0;
*fsec = 0;
- tm->tm_isdst = -1; /* don't know daylight savings time status apriori */
+ tm->tm_isdst = -1; /* don't know daylight savings time status
+ * apriori */
if (tzp != NULL)
*tzp = 0;
@@ -595,10 +597,11 @@ DecodeDateTime(char **field, int *ftype, int nf,
switch (ftype[i])
{
case DTK_DATE:
- /* Already have a date?
- * Then this might be a POSIX time zone
- * with an embedded dash (e.g. "PST-3" == "EST")
- * - thomas 2000-03-15
+
+ /*
+ * Already have a date? Then this might be a POSIX time
+ * zone with an embedded dash (e.g. "PST-3" == "EST") -
+ * thomas 2000-03-15
*/
if ((fmask & DTK_DATE_M) == DTK_DATE_M)
{
@@ -630,17 +633,18 @@ DecodeDateTime(char **field, int *ftype, int nf,
return -1;
{
- int tz;
+ int tz;
if (DecodeTimezone(field[i], &tz) != 0)
return -1;
- /* Already have a time zone?
- * Then maybe this is the second field of a POSIX time:
- * EST+3 (equivalent to PST)
+ /*
+ * Already have a time zone? Then maybe this is the
+ * second field of a POSIX time: EST+3 (equivalent to
+ * PST)
*/
if ((i > 0) && ((fmask & DTK_M(TZ)) != 0)
- && (ftype[i-1] == DTK_TZ) && (isalpha(*field[i-1])))
+ && (ftype[i - 1] == DTK_TZ) && (isalpha(*field[i - 1])))
{
*tzp -= tz;
tmask = 0;
@@ -742,6 +746,7 @@ DecodeDateTime(char **field, int *ftype, int nf,
break;
case MONTH:
+
/*
* already have a (numeric) month? then see if we
* can substitute...
@@ -881,7 +886,8 @@ DecodeDateTime(char **field, int *ftype, int nf,
tm->tm_mon += 1;
#if defined(HAVE_TM_ZONE)
- *tzp = -(tm->tm_gmtoff); /* tm_gmtoff is Sun/DEC-ism */
+ *tzp = -(tm->tm_gmtoff); /* tm_gmtoff is
+ * Sun/DEC-ism */
#elif defined(HAVE_INT_TIMEZONE)
#ifdef __CYGWIN__
*tzp = ((tm->tm_isdst > 0) ? (_timezone - 3600) : _timezone);
@@ -937,7 +943,8 @@ DecodeTimeOnly(char **field, int *ftype, int nf,
tm->tm_min = 0;
tm->tm_sec = 0;
*fsec = 0;
- tm->tm_isdst = -1; /* don't know daylight savings time status apriori */
+ tm->tm_isdst = -1; /* don't know daylight savings time status
+ * apriori */
if (tzp != NULL)
*tzp = 0;
@@ -948,9 +955,10 @@ DecodeTimeOnly(char **field, int *ftype, int nf,
switch (ftype[i])
{
case DTK_DATE:
- /* This might be a POSIX time zone
- * with an embedded dash (e.g. "PST-3" == "EST")
- * - thomas 2000-03-15
+
+ /*
+ * This might be a POSIX time zone with an embedded dash
+ * (e.g. "PST-3" == "EST") - thomas 2000-03-15
*/
if ((tzp == NULL)
|| (DecodePosixTimezone(field[i], tzp) != 0))
@@ -970,17 +978,18 @@ DecodeTimeOnly(char **field, int *ftype, int nf,
return -1;
{
- int tz;
+ int tz;
if (DecodeTimezone(field[i], &tz) != 0)
return -1;
- /* Already have a time zone?
- * Then maybe this is the second field of a POSIX time:
- * EST+3 (equivalent to PST)
+ /*
+ * Already have a time zone? Then maybe this is the
+ * second field of a POSIX time: EST+3 (equivalent to
+ * PST)
*/
if ((i > 0) && ((fmask & DTK_M(TZ)) != 0)
- && (ftype[i-1] == DTK_TZ) && (isalpha(*field[i-1])))
+ && (ftype[i - 1] == DTK_TZ) && (isalpha(*field[i - 1])))
{
*tzp -= tz;
tmask = 0;
@@ -1107,11 +1116,12 @@ DecodeTimeOnly(char **field, int *ftype, int nf,
/* timezone not specified? then find local timezone if possible */
if ((tzp != NULL) && (!(fmask & DTK_M(TZ))))
{
- struct tm tt, *tmp = &tt;
+ struct tm tt,
+ *tmp = &tt;
/*
- * daylight savings time modifier but no standard timezone?
- * then error
+ * daylight savings time modifier but no standard timezone? then
+ * error
*/
if (fmask & DTK_M(DTZMOD))
return -1;
@@ -1127,7 +1137,7 @@ DecodeTimeOnly(char **field, int *ftype, int nf,
tm->tm_isdst = tmp->tm_isdst;
#if defined(HAVE_TM_ZONE)
- *tzp = -(tmp->tm_gmtoff); /* tm_gmtoff is Sun/DEC-ism */
+ *tzp = -(tmp->tm_gmtoff); /* tm_gmtoff is Sun/DEC-ism */
#elif defined(HAVE_INT_TIMEZONE)
#ifdef __CYGWIN__
*tzp = ((tmp->tm_isdst > 0) ? (_timezone - 3600) : _timezone);
@@ -1366,10 +1376,8 @@ DecodeNumber(int flen, char *str, int fmask,
* Enough digits to be unequivocal year? Used to test for 4 digits or
* more, but we now test first for a three-digit doy so anything
* bigger than two digits had better be an explicit year. - thomas
- * 1999-01-09
- * Back to requiring a 4 digit year.
- * We accept a two digit year farther down.
- * - thomas 2000-03-28
+ * 1999-01-09 Back to requiring a 4 digit year. We accept a two digit
+ * year farther down. - thomas 2000-03-28
*/
else if (flen >= 4)
{
@@ -1414,8 +1422,10 @@ DecodeNumber(int flen, char *str, int fmask,
*tmask = DTK_M(DAY);
tm->tm_mday = val;
}
- /* Check for 2 or 4 or more digits, but currently we reach here
- * only if two digits. - thomas 2000-03-28
+
+ /*
+ * Check for 2 or 4 or more digits, but currently we reach here only
+ * if two digits. - thomas 2000-03-28
*/
else if (!(fmask & DTK_M(YEAR))
&& ((flen >= 4) || (flen == 2)))
@@ -1550,14 +1560,15 @@ DecodeTimezone(char *str, int *tzp)
/* DecodePosixTimezone()
* Interpret string as a POSIX-compatible timezone:
- * PST-hh:mm
- * PST+h
+ * PST-hh:mm
+ * PST+h
* - thomas 2000-03-15
*/
static int
DecodePosixTimezone(char *str, int *tzp)
{
- int val, tz;
+ int val,
+ tz;
int type;
char *cp;
char delim;
@@ -1571,10 +1582,10 @@ DecodePosixTimezone(char *str, int *tzp)
delim = *cp;
*cp = '\0';
- type = DecodeSpecial(MAXDATEFIELDS-1, str, &val);
+ type = DecodeSpecial(MAXDATEFIELDS - 1, str, &val);
*cp = delim;
- switch(type)
+ switch (type)
{
case DTZ:
case TZ:
@@ -1898,7 +1909,7 @@ DecodeUnits(int field, char *lowtoken, int *val)
* Binary search -- from Knuth (6.2.1) Algorithm B. Special case like this
* is WAY faster than the generic bsearch().
*/
-datetkn *
+datetkn *
datebsearch(char *key, datetkn *base, unsigned int nel)
{
datetkn *last = base + nel - 1,
@@ -2002,7 +2013,8 @@ EncodeTimeOnly(struct tm * tm, double fsec, int *tzp, int style, char *str)
if (tzp != NULL)
{
- int hour, min;
+ int hour,
+ min;
hour = -(*tzp / 3600);
min = ((abs(*tzp) / 60) % 60);
diff --git a/src/backend/utils/adt/float.c b/src/backend/utils/adt/float.c
index 82c7e191d53..354ee0110b7 100644
--- a/src/backend/utils/adt/float.c
+++ b/src/backend/utils/adt/float.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/float.c,v 1.56 2000/04/07 13:39:40 thomas Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/float.c,v 1.57 2000/04/12 17:15:49 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -1159,8 +1159,9 @@ dpow(float64 arg1, float64 arg2)
tmp1 = *arg1;
tmp2 = *arg2;
- /* We must check both for errno getting set and for a NaN result,
- * in order to deal with the vagaries of different platforms...
+ /*
+ * We must check both for errno getting set and for a NaN result, in
+ * order to deal with the vagaries of different platforms...
*/
errno = 0;
*result = (float64data) pow(tmp1, tmp2);
@@ -1192,9 +1193,10 @@ dexp(float64 arg1)
tmp = *arg1;
- /* We must check both for errno getting set and for a NaN result,
- * in order to deal with the vagaries of different platforms.
- * Also, a zero result implies unreported underflow.
+ /*
+ * We must check both for errno getting set and for a NaN result, in
+ * order to deal with the vagaries of different platforms. Also, a
+ * zero result implies unreported underflow.
*/
errno = 0;
*result = (float64data) exp(tmp);
@@ -1234,7 +1236,7 @@ dlog1(float64 arg1)
CheckFloat8Val(*result);
return result;
-} /* dlog1() */
+} /* dlog1() */
/*
@@ -1260,7 +1262,7 @@ dlog10(float64 arg1)
CheckFloat8Val(*result);
return result;
-} /* dlog10() */
+} /* dlog10() */
/*
@@ -1289,7 +1291,7 @@ dacos(float64 arg1)
CheckFloat8Val(*result);
return result;
-} /* dacos() */
+} /* dacos() */
/*
@@ -1318,7 +1320,7 @@ dasin(float64 arg1)
CheckFloat8Val(*result);
return result;
-} /* dasin() */
+} /* dasin() */
/*
@@ -1347,7 +1349,7 @@ datan(float64 arg1)
CheckFloat8Val(*result);
return result;
-} /* datan() */
+} /* datan() */
/*
@@ -1374,7 +1376,7 @@ datan2(float64 arg1, float64 arg2)
CheckFloat8Val(*result);
return result;
-} /* datan2() */
+} /* datan2() */
/*
@@ -1403,7 +1405,7 @@ dcos(float64 arg1)
CheckFloat8Val(*result);
return result;
-} /* dcos() */
+} /* dcos() */
/*
@@ -1430,10 +1432,10 @@ dcot(float64 arg1)
)
elog(ERROR, "dcot(%f) input is out of range", *arg1);
- *result = 1.0/(*result);
+ *result = 1.0 / (*result);
CheckFloat8Val(*result);
return result;
-} /* dcot() */
+} /* dcot() */
/*
@@ -1462,7 +1464,7 @@ dsin(float64 arg1)
CheckFloat8Val(*result);
return result;
-} /* dsin() */
+} /* dsin() */
/*
@@ -1491,7 +1493,7 @@ dtan(float64 arg1)
CheckFloat8Val(*result);
return result;
-} /* dtan() */
+} /* dtan() */
#ifndef M_PI
@@ -1517,7 +1519,7 @@ degrees(float64 arg1)
CheckFloat8Val(*result);
return result;
-} /* degrees() */
+} /* degrees() */
/*
@@ -1533,7 +1535,7 @@ dpi(void)
*result = (M_PI);
return result;
-} /* dpi() */
+} /* dpi() */
/*
@@ -1553,11 +1555,11 @@ radians(float64 arg1)
CheckFloat8Val(*result);
return result;
-} /* radians() */
+} /* radians() */
/*
- * drandom - returns a random number
+ * drandom - returns a random number
*/
float64
drandom(void)
@@ -1571,7 +1573,7 @@ drandom(void)
CheckFloat8Val(*result);
return result;
-} /* drandom() */
+} /* drandom() */
/*
@@ -1580,12 +1582,12 @@ drandom(void)
int32
setseed(float64 seed)
{
- int iseed = ((*seed) * RAND_MAX);
+ int iseed = ((*seed) * RAND_MAX);
srandom((unsigned int) ((*seed) * RAND_MAX));
return iseed;
-} /* setseed() */
+} /* setseed() */
/*
diff --git a/src/backend/utils/adt/formatting.c b/src/backend/utils/adt/formatting.c
index bc60ca65471..8d204a15957 100644
--- a/src/backend/utils/adt/formatting.c
+++ b/src/backend/utils/adt/formatting.c
@@ -1,58 +1,58 @@
/* -----------------------------------------------------------------------
* formatting.c
*
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/formatting.c,v 1.7 2000/04/07 19:17:31 momjian Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/formatting.c,v 1.8 2000/04/12 17:15:49 momjian Exp $
*
*
- * Portions Copyright (c) 1999-2000, PostgreSQL, Inc
+ * Portions Copyright (c) 1999-2000, PostgreSQL, Inc
*
*
- * TO_CHAR(); TO_TIMESTAMP(); TO_DATE(); TO_NUMBER();
+ * TO_CHAR(); TO_TIMESTAMP(); TO_DATE(); TO_NUMBER();
*
- * The PostgreSQL routines for a timestamp/int/float/numeric formatting,
- * inspire with Oracle TO_CHAR() / TO_DATE() / TO_NUMBER() routines.
+ * The PostgreSQL routines for a timestamp/int/float/numeric formatting,
+ * inspire with Oracle TO_CHAR() / TO_DATE() / TO_NUMBER() routines.
*
*
- * Cache & Memory:
- * Routines use (itself) internal cache for format pictures.
- *
+ * Cache & Memory:
+ * Routines use (itself) internal cache for format pictures.
+ *
* The cache uses a static buffers and is persistent across transactions.
- * If format-picture is bigger than cache buffer, parser is called always.
+ * If format-picture is bigger than cache buffer, parser is called always.
*
- * NOTE for Number version:
+ * NOTE for Number version:
* All in this version is implemented as keywords ( => not used
- * suffixes), because a format picture is for *one* item (number)
- * only. It not is as a timestamp version, where each keyword (can)
- * has suffix.
+ * suffixes), because a format picture is for *one* item (number)
+ * only. It not is as a timestamp version, where each keyword (can)
+ * has suffix.
*
- * NOTE for Timestamp routines:
+ * NOTE for Timestamp routines:
* In this module the POSIX 'struct tm' type is *not* used, but rather
* PgSQL type, which has tm_mon based on one (*non* zero) and
- * year *not* based on 1900, but is used full year number.
+ * year *not* based on 1900, but is used full year number.
* Module supports AD / BC / AM / PM.
*
- * Supported types for to_char():
- *
+ * Supported types for to_char():
+ *
* Timestamp, Numeric, int4, int8, float4, float8
*
- * Supported types for reverse conversion:
+ * Supported types for reverse conversion:
*
* Timestamp - to_timestamp()
* Date - to_date()
- * Numeric - to_number()
- *
- *
- * Karel Zak - Zakkr
+ * Numeric - to_number()
+ *
+ *
+ * Karel Zak - Zakkr
*
* -----------------------------------------------------------------------
*/
-
+
/* ----------
* UnComment me for DEBUG
* ----------
*/
/***
-#define DEBUG_TO_FROM_CHAR
+#define DEBUG_TO_FROM_CHAR
#define DEBUG_elog_output NOTICE
***/
@@ -74,8 +74,8 @@
* Routines type
* ----------
*/
-#define DCH_TYPE 1 /* DATE-TIME version */
-#define NUM_TYPE 2 /* NUMBER version */
+#define DCH_TYPE 1 /* DATE-TIME version */
+#define NUM_TYPE 2 /* NUMBER version */
/* ----------
* KeyWord Index (ascii from position 32 (' ') to 126 (~))
@@ -85,54 +85,57 @@
#define KeyWord_INDEX_FILTER(_c) ((_c) <= ' ' || (_c) >= '~' ? 0 : 1)
/* ----------
- * Maximal length of one node
+ * Maximal length of one node
* ----------
*/
-#define DCH_MAX_ITEM_SIZ 9 /* max julian day */
-#define NUM_MAX_ITEM_SIZ 8 /* roman number (RN has 15 chars) */
+#define DCH_MAX_ITEM_SIZ 9 /* max julian day */
+#define NUM_MAX_ITEM_SIZ 8 /* roman number (RN has 15 chars) */
/* ----------
* More is in float.c
* ----------
*/
-#define MAXFLOATWIDTH 64
-#define MAXDOUBLEWIDTH 128
+#define MAXFLOATWIDTH 64
+#define MAXDOUBLEWIDTH 128
/* ----------
- * External (defined in PgSQL dt.c (timestamp utils))
+ * External (defined in PgSQL dt.c (timestamp utils))
* ----------
*/
-extern char *months[], /* month abbreviation */
- *days[]; /* full days */
+extern char *months[], /* month abbreviation */
+ *days[]; /* full days */
/* ----------
- * Format parser structs
+ * Format parser structs
* ----------
*/
-typedef struct {
- char *name; /* suffix string */
- int len, /* suffix length */
- id, /* used in node->suffix */
- type; /* prefix / postfix */
+typedef struct
+{
+ char *name; /* suffix string */
+ int len, /* suffix length */
+ id, /* used in node->suffix */
+ type; /* prefix / postfix */
} KeySuffix;
-typedef struct {
- char *name; /* keyword */
- /* action for keyword */
- int len, /* keyword length */
- (*action)(),
- id; /* keyword id */
+typedef struct
+{
+ char *name; /* keyword */
+ /* action for keyword */
+ int len, /* keyword length */
+ (*action) (),
+ id; /* keyword id */
} KeyWord;
-typedef struct {
- int type; /* node type */
- KeyWord *key; /* if node type is KEYWORD */
- int character, /* if node type is CHAR */
- suffix; /* keyword suffix */
+typedef struct
+{
+ int type; /* node type */
+ KeyWord *key; /* if node type is KEYWORD */
+ int character, /* if node type is CHAR */
+ suffix; /* keyword suffix */
} FormatNode;
#define NODE_TYPE_END 1
-#define NODE_TYPE_ACTION 2
+#define NODE_TYPE_ACTION 2
#define NODE_TYPE_CHAR 3
#define SUFFTYPE_PREFIX 1
@@ -143,9 +146,9 @@ typedef struct {
* Full months
* ----------
*/
-static char *months_full[] = {
- "January", "February", "March", "April", "May", "June", "July",
- "August", "September", "October", "November", "December", NULL
+static char *months_full[] = {
+ "January", "February", "March", "April", "May", "June", "July",
+ "August", "September", "October", "November", "December", NULL
};
/* ----------
@@ -153,7 +156,7 @@ static char *months_full[] = {
* ----------
*/
#define YEAR_ABS(_y) (_y < 0 ? -(_y -1) : _y)
-#define BC_STR_ORIG " BC"
+#define BC_STR_ORIG " BC"
#define A_D_STR "A.D."
#define a_d_STR "a.d."
@@ -181,47 +184,47 @@ static char *months_full[] = {
#define pm_STR "pm"
-/* ----------
- * Months in roman-numeral
- * (Must be conversely for seq_search (in FROM_CHAR), because
- * 'VIII' must be over 'V')
+/* ----------
+ * Months in roman-numeral
+ * (Must be conversely for seq_search (in FROM_CHAR), because
+ * 'VIII' must be over 'V')
* ----------
*/
-static char *rm_months_upper[] =
-{ "XII", "XI", "X", "IX", "VIII", "VII", "VI", "V", "IV", "III", "II", "I", NULL };
+static char *rm_months_upper[] =
+{"XII", "XI", "X", "IX", "VIII", "VII", "VI", "V", "IV", "III", "II", "I", NULL};
-static char *rm_months_lower[] =
-{ "xii", "xi", "x", "ix", "viii", "vii", "vi", "v", "iv", "iii", "ii", "i", NULL };
+static char *rm_months_lower[] =
+{"xii", "xi", "x", "ix", "viii", "vii", "vi", "v", "iv", "iii", "ii", "i", NULL};
/* ----------
* Roman numbers
* ----------
*/
-static char *rm1[] = { "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", NULL };
-static char *rm10[] = { "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", NULL };
-static char *rm100[] = { "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", NULL };
+static char *rm1[] = {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", NULL};
+static char *rm10[] = {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", NULL};
+static char *rm100[] = {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", NULL};
-/* ----------
- * Ordinal postfixes
+/* ----------
+ * Ordinal postfixes
* ----------
*/
-static char *numTH[] = { "ST", "ND", "RD", "TH", NULL };
-static char *numth[] = { "st", "nd", "rd", "th", NULL };
+static char *numTH[] = {"ST", "ND", "RD", "TH", NULL};
+static char *numth[] = {"st", "nd", "rd", "th", NULL};
-/* ----------
- * Flags & Options:
+/* ----------
+ * Flags & Options:
* ----------
*/
#define TO_CHAR 1
-#define FROM_CHAR 2
+#define FROM_CHAR 2
-#define ONE_UPPER 1 /* Name */
-#define ALL_UPPER 2 /* NAME */
-#define ALL_LOWER 3 /* name */
+#define ONE_UPPER 1 /* Name */
+#define ALL_UPPER 2 /* NAME */
+#define ALL_LOWER 3 /* name */
#define FULL_SIZ 0
-#define MAX_MON_LEN 3
+#define MAX_MON_LEN 3
#define MAX_DY_LEN 3
#define TH_UPPER 1
@@ -229,21 +232,21 @@ static char *numth[] = { "st", "nd", "rd", "th", NULL };
#ifdef DEBUG_TO_FROM_CHAR
- #define NOTICE_TM {\
+#define NOTICE_TM {\
elog(DEBUG_elog_output, "TM:\nsec %d\nyear %d\nmin %d\nwday %d\nhour %d\nyday %d\nmday %d\nnisdst %d\nmon %d\n",\
tm->tm_sec, tm->tm_year,\
tm->tm_min, tm->tm_wday, tm->tm_hour, tm->tm_yday,\
tm->tm_mday, tm->tm_isdst,tm->tm_mon);\
- }
+ }
#endif
/* ----------
* Flags for DCH version
* ----------
*/
-static int DCH_global_flag = 0;
-
-#define DCH_F_FX 0x01
+static int DCH_global_flag = 0;
+
+#define DCH_F_FX 0x01
#define IS_FX (DCH_global_flag & DCH_F_FX)
@@ -252,33 +255,34 @@ static int DCH_global_flag = 0;
* Number description struct
* ----------
*/
-typedef struct {
- int pre, /* (count) numbers before decimal */
- post, /* (count) numbers after decimal */
- lsign, /* want locales sign */
- flag, /* number parametrs */
- pre_lsign_num, /* tmp value for lsign */
- multi, /* multiplier for 'V' */
- zero_start, /* position of first zero */
- zero_end, /* position of last zero */
- need_locale; /* needs it locale */
+typedef struct
+{
+ int pre, /* (count) numbers before decimal */
+ post, /* (count) numbers after decimal */
+ lsign, /* want locales sign */
+ flag, /* number parametrs */
+ pre_lsign_num, /* tmp value for lsign */
+ multi, /* multiplier for 'V' */
+ zero_start, /* position of first zero */
+ zero_end, /* position of last zero */
+ need_locale; /* needs it locale */
} NUMDesc;
/* ----------
- * Flags for NUMBER version
+ * Flags for NUMBER version
* ----------
*/
-#define NUM_F_DECIMAL 0x01
-#define NUM_F_LDECIMAL 0x02
+#define NUM_F_DECIMAL 0x01
+#define NUM_F_LDECIMAL 0x02
#define NUM_F_ZERO 0x04
-#define NUM_F_BLANK 0x08
+#define NUM_F_BLANK 0x08
#define NUM_F_FILLMODE 0x10
-#define NUM_F_LSIGN 0x20
+#define NUM_F_LSIGN 0x20
#define NUM_F_BRACKET 0x40
-#define NUM_F_MINUS 0x80
+#define NUM_F_MINUS 0x80
#define NUM_F_PLUS 0x100
-#define NUM_F_ROMAN 0x200
-#define NUM_F_MULTI 0x400
+#define NUM_F_ROMAN 0x200
+#define NUM_F_MULTI 0x400
#define NUM_LSIGN_PRE -1
#define NUM_LSIGN_POST 1
@@ -288,59 +292,64 @@ typedef struct {
* Tests
* ----------
*/
-#define IS_DECIMAL(_f) ((_f)->flag & NUM_F_DECIMAL)
-#define IS_LDECIMAL(_f) ((_f)->flag & NUM_F_LDECIMAL)
-#define IS_ZERO(_f) ((_f)->flag & NUM_F_ZERO)
-#define IS_BLANK(_f) ((_f)->flag & NUM_F_BLANK)
-#define IS_FILLMODE(_f) ((_f)->flag & NUM_F_FILLMODE)
-#define IS_BRACKET(_f) ((_f)->flag & NUM_F_BRACKET)
+#define IS_DECIMAL(_f) ((_f)->flag & NUM_F_DECIMAL)
+#define IS_LDECIMAL(_f) ((_f)->flag & NUM_F_LDECIMAL)
+#define IS_ZERO(_f) ((_f)->flag & NUM_F_ZERO)
+#define IS_BLANK(_f) ((_f)->flag & NUM_F_BLANK)
+#define IS_FILLMODE(_f) ((_f)->flag & NUM_F_FILLMODE)
+#define IS_BRACKET(_f) ((_f)->flag & NUM_F_BRACKET)
#define IS_MINUS(_f) ((_f)->flag & NUM_F_MINUS)
#define IS_LSIGN(_f) ((_f)->flag & NUM_F_LSIGN)
-#define IS_PLUS(_f) ((_f)->flag & NUM_F_PLUS)
+#define IS_PLUS(_f) ((_f)->flag & NUM_F_PLUS)
#define IS_ROMAN(_f) ((_f)->flag & NUM_F_ROMAN)
#define IS_MULTI(_f) ((_f)->flag & NUM_F_MULTI)
/* ----------
- * Format picture cache
- * (cache size:
- * Number part = NUM_CACHE_SIZE * NUM_CACHE_FIELDS
+ * Format picture cache
+ * (cache size:
+ * Number part = NUM_CACHE_SIZE * NUM_CACHE_FIELDS
* Date-time part = DCH_CACHE_SIZE * DCH_CACHE_FIELDS
* )
* ----------
*/
-#define NUM_CACHE_SIZE 64
+#define NUM_CACHE_SIZE 64
#define NUM_CACHE_FIELDS 16
#define DCH_CACHE_SIZE 128
#define DCH_CACHE_FIELDS 16
-typedef struct {
- FormatNode format [ DCH_CACHE_SIZE +1];
- char str [ DCH_CACHE_SIZE +1];
- int age;
+typedef struct
+{
+ FormatNode format[DCH_CACHE_SIZE + 1];
+ char str[DCH_CACHE_SIZE + 1];
+ int age;
} DCHCacheEntry;
-typedef struct {
- FormatNode format [ NUM_CACHE_SIZE +1];
- char str [ NUM_CACHE_SIZE +1];
- int age;
- NUMDesc Num;
+typedef struct
+{
+ FormatNode format[NUM_CACHE_SIZE + 1];
+ char str[NUM_CACHE_SIZE + 1];
+ int age;
+ NUMDesc Num;
} NUMCacheEntry;
-static DCHCacheEntry DCHCache [ DCH_CACHE_FIELDS +1]; /* global cache for date/time part */
-static int n_DCHCache = 0; /* number of entries */
-static int DCHCounter = 0;
+static DCHCacheEntry DCHCache[DCH_CACHE_FIELDS + 1]; /* global cache for
+ * date/time part */
+static int n_DCHCache = 0; /* number of entries */
+static int DCHCounter = 0;
-static NUMCacheEntry NUMCache [ NUM_CACHE_FIELDS +1]; /* global cache for number part */
-static int n_NUMCache = 0; /* number of entries */
-static int NUMCounter = 0;
+static NUMCacheEntry NUMCache[NUM_CACHE_FIELDS + 1]; /* global cache for
+ * number part */
+static int n_NUMCache = 0; /* number of entries */
+static int NUMCounter = 0;
#define MAX_INT32 (2147483640)
/* ----------
- * Private global-modul definitions
+ * Private global-modul definitions
* ----------
*/
-static struct tm _tm, *tm = &_tm;
+static struct tm _tm,
+ *tm = &_tm;
/* ----------
* Utils
@@ -354,24 +363,24 @@ static struct tm _tm, *tm = &_tm;
#endif
/*****************************************************************************
- * KeyWords definition & action
+ * KeyWords definition & action
*****************************************************************************/
-static int dch_global(int arg, char *inout, int suf, int flag, FormatNode *node);
-static int dch_time(int arg, char *inout, int suf, int flag, FormatNode *node);
-static int dch_date(int arg, char *inout, int suf, int flag, FormatNode *node);
+static int dch_global(int arg, char *inout, int suf, int flag, FormatNode *node);
+static int dch_time(int arg, char *inout, int suf, int flag, FormatNode *node);
+static int dch_date(int arg, char *inout, int suf, int flag, FormatNode *node);
-/* ----------
- * Suffixes:
+/* ----------
+ * Suffixes:
* ----------
*/
-#define DCH_S_FM 0x01
-#define DCH_S_TH 0x02
-#define DCH_S_th 0x04
-#define DCH_S_SP 0x08
+#define DCH_S_FM 0x01
+#define DCH_S_TH 0x02
+#define DCH_S_th 0x04
+#define DCH_S_SP 0x08
-/* ----------
- * Suffix tests
+/* ----------
+ * Suffix tests
* ----------
*/
#define S_THth(_s) (((_s & DCH_S_TH) || (_s & DCH_S_th)) ? 1 : 0)
@@ -387,47 +396,48 @@ static int dch_date(int arg, char *inout, int suf, int flag, FormatNode *node);
* ----------
*/
static KeySuffix DCH_suff[] = {
- { "FM", 2, DCH_S_FM, SUFFTYPE_PREFIX },
- { "fm", 2, DCH_S_FM, SUFFTYPE_PREFIX },
- { "TH", 2, DCH_S_TH, SUFFTYPE_POSTFIX },
- { "th", 2, DCH_S_th, SUFFTYPE_POSTFIX },
- { "SP", 2, DCH_S_SP, SUFFTYPE_POSTFIX },
+ {"FM", 2, DCH_S_FM, SUFFTYPE_PREFIX},
+ {"fm", 2, DCH_S_FM, SUFFTYPE_PREFIX},
+ {"TH", 2, DCH_S_TH, SUFFTYPE_POSTFIX},
+ {"th", 2, DCH_S_th, SUFFTYPE_POSTFIX},
+ {"SP", 2, DCH_S_SP, SUFFTYPE_POSTFIX},
/* last */
- { NULL, 0, 0, 0 }
+ {NULL, 0, 0, 0}
};
/* ----------
* Format-pictures (KeyWord).
- *
+ *
* The KeyWord field; alphabetic sorted, *BUT* strings alike is sorted
- * complicated -to-> easy:
+ * complicated -to-> easy:
*
- * (example: "DDD","DD","Day","D" )
+ * (example: "DDD","DD","Day","D" )
*
* (this specific sort needs the algorithm for sequential search for strings,
- * which not has exact end; -> How keyword is in "HH12blabla" ? - "HH"
- * or "HH12"? You must first try "HH12", because "HH" is in string, but
- * it is not good.
+ * which not has exact end; -> How keyword is in "HH12blabla" ? - "HH"
+ * or "HH12"? You must first try "HH12", because "HH" is in string, but
+ * it is not good.
*
- * (!)
- * Position for the keyword is simular as position in the enum DCH/NUM_poz
+ * (!)
+ * Position for the keyword is simular as position in the enum DCH/NUM_poz
* (!)
*
- * For fast search is used the 'int index[]', index is ascii table from position
- * 32 (' ') to 126 (~), in this index is DCH_ / NUM_ enums for each ASCII
- * position or -1 if char is not used in the KeyWord. Search example for
+ * For fast search is used the 'int index[]', index is ascii table from position
+ * 32 (' ') to 126 (~), in this index is DCH_ / NUM_ enums for each ASCII
+ * position or -1 if char is not used in the KeyWord. Search example for
* string "MM":
- * 1) see in index to index['M' - 32],
+ * 1) see in index to index['M' - 32],
* 2) take keywords position (enum DCH_MM) from index
- * 3) run sequential search in keywords[] from this position
+ * 3) run sequential search in keywords[] from this position
*
* ----------
*/
-typedef enum {
+typedef enum
+{
DCH_A_D,
DCH_A_M,
- DCH_AD,
+ DCH_AD,
DCH_AM,
DCH_B_C,
DCH_BC,
@@ -439,7 +449,7 @@ typedef enum {
DCH_Day,
DCH_Dy,
DCH_D,
- DCH_FX, /* global suffix */
+ DCH_FX, /* global suffix */
DCH_HH24,
DCH_HH12,
DCH_HH,
@@ -463,14 +473,14 @@ typedef enum {
DCH_YYY,
DCH_YY,
DCH_Y,
- DCH_a_d,
+ DCH_a_d,
DCH_a_m,
DCH_ad,
- DCH_am,
+ DCH_am,
DCH_b_c,
DCH_bc,
DCH_cc,
- DCH_day,
+ DCH_day,
DCH_ddd,
DCH_dd,
DCH_dy,
@@ -478,7 +488,7 @@ typedef enum {
DCH_fx,
DCH_hh24,
DCH_hh12,
- DCH_hh,
+ DCH_hh,
DCH_j,
DCH_mi,
DCH_mm,
@@ -496,13 +506,14 @@ typedef enum {
DCH_yyyy,
DCH_yyy,
DCH_yy,
- DCH_y,
+ DCH_y,
/* last */
_DCH_last_
} DCH_poz;
-typedef enum {
+typedef enum
+{
NUM_COMMA,
NUM_DEC,
NUM_0,
@@ -538,8 +549,8 @@ typedef enum {
NUM_sp,
NUM_s,
NUM_th,
- NUM_v,
-
+ NUM_v,
+
/* last */
_NUM_last_
} NUM_poz;
@@ -548,174 +559,174 @@ typedef enum {
* KeyWords for DATE-TIME version
* ----------
*/
-static KeyWord DCH_keywords[] = {
-/* keyword, len, func. type is in Index */
-{ "A.D.", 4, dch_date, DCH_A_D }, /*A*/
-{ "A.M.", 4, dch_time, DCH_A_M },
-{ "AD", 2, dch_date, DCH_AD },
-{ "AM", 2, dch_time, DCH_AM },
-{ "B.C.", 4, dch_date, DCH_B_C }, /*B*/
-{ "BC", 2, dch_date, DCH_BC },
-{ "CC", 2, dch_date, DCH_CC }, /*C*/
-{ "DAY", 3, dch_date, DCH_DAY }, /*D*/
-{ "DDD", 3, dch_date, DCH_DDD },
-{ "DD", 2, dch_date, DCH_DD },
-{ "DY", 2, dch_date, DCH_DY },
-{ "Day", 3, dch_date, DCH_Day },
-{ "Dy", 2, dch_date, DCH_Dy },
-{ "D", 1, dch_date, DCH_D },
-{ "FX", 2, dch_global, DCH_FX }, /*F*/
-{ "HH24", 4, dch_time, DCH_HH24 }, /*H*/
-{ "HH12", 4, dch_time, DCH_HH12 },
-{ "HH", 2, dch_time, DCH_HH },
-{ "J", 1, dch_date, DCH_J }, /*J*/
-{ "MI", 2, dch_time, DCH_MI },
-{ "MM", 2, dch_date, DCH_MM },
-{ "MONTH", 5, dch_date, DCH_MONTH },
-{ "MON", 3, dch_date, DCH_MON },
-{ "Month", 5, dch_date, DCH_Month },
-{ "Mon", 3, dch_date, DCH_Mon },
-{ "P.M.", 4, dch_time, DCH_P_M }, /*P*/
-{ "PM", 2, dch_time, DCH_PM },
-{ "Q", 1, dch_date, DCH_Q }, /*Q*/
-{ "RM", 2, dch_date, DCH_RM }, /*R*/
-{ "SSSS", 4, dch_time, DCH_SSSS }, /*S*/
-{ "SS", 2, dch_time, DCH_SS },
-{ "WW", 2, dch_date, DCH_WW }, /*W*/
-{ "W", 1, dch_date, DCH_W },
-{ "Y,YYY", 5, dch_date, DCH_Y_YYY }, /*Y*/
-{ "YYYY", 4, dch_date, DCH_YYYY },
-{ "YYY", 3, dch_date, DCH_YYY },
-{ "YY", 2, dch_date, DCH_YY },
-{ "Y", 1, dch_date, DCH_Y },
-{ "a.d.", 4, dch_date, DCH_a_d }, /*a*/
-{ "a.m.", 4, dch_time, DCH_a_m },
-{ "ad", 2, dch_date, DCH_ad },
-{ "am", 2, dch_time, DCH_am },
-{ "b.c.", 4, dch_date, DCH_b_c }, /*b*/
-{ "bc", 2, dch_date, DCH_bc },
-{ "cc", 2, dch_date, DCH_CC }, /*c*/
-{ "day", 3, dch_date, DCH_day }, /*d*/
-{ "ddd", 3, dch_date, DCH_DDD },
-{ "dd", 2, dch_date, DCH_DD },
-{ "dy", 2, dch_date, DCH_dy },
-{ "d", 1, dch_date, DCH_D },
-{ "fx", 2, dch_global, DCH_FX }, /*f*/
-{ "hh24", 4, dch_time, DCH_HH24 }, /*h*/
-{ "hh12", 4, dch_time, DCH_HH12 },
-{ "hh", 2, dch_time, DCH_HH },
-{ "j", 1, dch_time, DCH_J }, /*j*/
-{ "mi", 2, dch_time, DCH_MI }, /*m*/
-{ "mm", 2, dch_date, DCH_MM },
-{ "month", 5, dch_date, DCH_month },
-{ "mon", 3, dch_date, DCH_mon },
-{ "p.m.", 4, dch_time, DCH_p_m }, /*p*/
-{ "pm", 2, dch_time, DCH_pm },
-{ "q", 1, dch_date, DCH_Q }, /*q*/
-{ "rm", 2, dch_date, DCH_rm }, /*r*/
-{ "ssss", 4, dch_time, DCH_SSSS }, /*s*/
-{ "ss", 2, dch_time, DCH_SS },
-{ "ww", 2, dch_date, DCH_WW }, /*w*/
-{ "w", 1, dch_date, DCH_W },
-{ "y,yyy", 5, dch_date, DCH_Y_YYY }, /*y*/
-{ "yyyy", 4, dch_date, DCH_YYYY },
-{ "yyy", 3, dch_date, DCH_YYY },
-{ "yy", 2, dch_date, DCH_YY },
-{ "y", 1, dch_date, DCH_Y },
+static KeyWord DCH_keywords[] = {
+/* keyword, len, func. type is in Index */
+ {"A.D.", 4, dch_date, DCH_A_D}, /* A */
+ {"A.M.", 4, dch_time, DCH_A_M},
+ {"AD", 2, dch_date, DCH_AD},
+ {"AM", 2, dch_time, DCH_AM},
+ {"B.C.", 4, dch_date, DCH_B_C}, /* B */
+ {"BC", 2, dch_date, DCH_BC},
+ {"CC", 2, dch_date, DCH_CC},/* C */
+ {"DAY", 3, dch_date, DCH_DAY}, /* D */
+ {"DDD", 3, dch_date, DCH_DDD},
+ {"DD", 2, dch_date, DCH_DD},
+ {"DY", 2, dch_date, DCH_DY},
+ {"Day", 3, dch_date, DCH_Day},
+ {"Dy", 2, dch_date, DCH_Dy},
+ {"D", 1, dch_date, DCH_D},
+ {"FX", 2, dch_global, DCH_FX}, /* F */
+ {"HH24", 4, dch_time, DCH_HH24}, /* H */
+ {"HH12", 4, dch_time, DCH_HH12},
+ {"HH", 2, dch_time, DCH_HH},
+ {"J", 1, dch_date, DCH_J}, /* J */
+ {"MI", 2, dch_time, DCH_MI},
+ {"MM", 2, dch_date, DCH_MM},
+ {"MONTH", 5, dch_date, DCH_MONTH},
+ {"MON", 3, dch_date, DCH_MON},
+ {"Month", 5, dch_date, DCH_Month},
+ {"Mon", 3, dch_date, DCH_Mon},
+ {"P.M.", 4, dch_time, DCH_P_M}, /* P */
+ {"PM", 2, dch_time, DCH_PM},
+ {"Q", 1, dch_date, DCH_Q}, /* Q */
+ {"RM", 2, dch_date, DCH_RM},/* R */
+ {"SSSS", 4, dch_time, DCH_SSSS}, /* S */
+ {"SS", 2, dch_time, DCH_SS},
+ {"WW", 2, dch_date, DCH_WW},/* W */
+ {"W", 1, dch_date, DCH_W},
+ {"Y,YYY", 5, dch_date, DCH_Y_YYY}, /* Y */
+ {"YYYY", 4, dch_date, DCH_YYYY},
+ {"YYY", 3, dch_date, DCH_YYY},
+ {"YY", 2, dch_date, DCH_YY},
+ {"Y", 1, dch_date, DCH_Y},
+ {"a.d.", 4, dch_date, DCH_a_d}, /* a */
+ {"a.m.", 4, dch_time, DCH_a_m},
+ {"ad", 2, dch_date, DCH_ad},
+ {"am", 2, dch_time, DCH_am},
+ {"b.c.", 4, dch_date, DCH_b_c}, /* b */
+ {"bc", 2, dch_date, DCH_bc},
+ {"cc", 2, dch_date, DCH_CC},/* c */
+ {"day", 3, dch_date, DCH_day}, /* d */
+ {"ddd", 3, dch_date, DCH_DDD},
+ {"dd", 2, dch_date, DCH_DD},
+ {"dy", 2, dch_date, DCH_dy},
+ {"d", 1, dch_date, DCH_D},
+ {"fx", 2, dch_global, DCH_FX}, /* f */
+ {"hh24", 4, dch_time, DCH_HH24}, /* h */
+ {"hh12", 4, dch_time, DCH_HH12},
+ {"hh", 2, dch_time, DCH_HH},
+ {"j", 1, dch_time, DCH_J}, /* j */
+ {"mi", 2, dch_time, DCH_MI},/* m */
+ {"mm", 2, dch_date, DCH_MM},
+ {"month", 5, dch_date, DCH_month},
+ {"mon", 3, dch_date, DCH_mon},
+ {"p.m.", 4, dch_time, DCH_p_m}, /* p */
+ {"pm", 2, dch_time, DCH_pm},
+ {"q", 1, dch_date, DCH_Q}, /* q */
+ {"rm", 2, dch_date, DCH_rm},/* r */
+ {"ssss", 4, dch_time, DCH_SSSS}, /* s */
+ {"ss", 2, dch_time, DCH_SS},
+ {"ww", 2, dch_date, DCH_WW},/* w */
+ {"w", 1, dch_date, DCH_W},
+ {"y,yyy", 5, dch_date, DCH_Y_YYY}, /* y */
+ {"yyyy", 4, dch_date, DCH_YYYY},
+ {"yyy", 3, dch_date, DCH_YYY},
+ {"yy", 2, dch_date, DCH_YY},
+ {"y", 1, dch_date, DCH_Y},
/* last */
-{ NULL, 0, NULL, 0 }};
+{NULL, 0, NULL, 0}};
/* ----------
* KeyWords for NUMBER version
* ----------
*/
-static KeyWord NUM_keywords[] = {
-/* keyword, len, func. type is in Index */
-{ ",", 1, NULL, NUM_COMMA }, /*,*/
-{ ".", 1, NULL, NUM_DEC }, /*.*/
-{ "0", 1, NULL, NUM_0 }, /*0*/
-{ "9", 1, NULL, NUM_9 }, /*9*/
-{ "B", 1, NULL, NUM_B }, /*B*/
-{ "C", 1, NULL, NUM_C }, /*C*/
-{ "D", 1, NULL, NUM_D }, /*D*/
-{ "E", 1, NULL, NUM_E }, /*E*/
-{ "FM", 2, NULL, NUM_FM }, /*F*/
-{ "G", 1, NULL, NUM_G }, /*G*/
-{ "L", 1, NULL, NUM_L }, /*L*/
-{ "MI", 2, NULL, NUM_MI }, /*M*/
-{ "PL", 2, NULL, NUM_PL }, /*P*/
-{ "PR", 2, NULL, NUM_PR },
-{ "RN", 2, NULL, NUM_RN }, /*R*/
-{ "SG", 2, NULL, NUM_SG }, /*S*/
-{ "SP", 2, NULL, NUM_SP },
-{ "S", 1, NULL, NUM_S },
-{ "TH", 2, NULL, NUM_TH }, /*T*/
-{ "V", 1, NULL, NUM_V }, /*V*/
-{ "b", 1, NULL, NUM_B }, /*b*/
-{ "c", 1, NULL, NUM_C }, /*c*/
-{ "d", 1, NULL, NUM_D }, /*d*/
-{ "e", 1, NULL, NUM_E }, /*e*/
-{ "fm", 2, NULL, NUM_FM }, /*f*/
-{ "g", 1, NULL, NUM_G }, /*g*/
-{ "l", 1, NULL, NUM_L }, /*l*/
-{ "mi", 2, NULL, NUM_MI }, /*m*/
-{ "pl", 2, NULL, NUM_PL }, /*p*/
-{ "pr", 2, NULL, NUM_PR },
-{ "rn", 2, NULL, NUM_rn }, /*r*/
-{ "sg", 2, NULL, NUM_SG }, /*s*/
-{ "sp", 2, NULL, NUM_SP },
-{ "s", 1, NULL, NUM_S },
-{ "th", 2, NULL, NUM_th }, /*t*/
-{ "v", 1, NULL, NUM_V }, /*v*/
-
-/* last */
-{ NULL, 0, NULL, 0 }};
+static KeyWord NUM_keywords[] = {
+/* keyword, len, func. type is in Index */
+ {",", 1, NULL, NUM_COMMA}, /* , */
+ {".", 1, NULL, NUM_DEC}, /* . */
+ {"0", 1, NULL, NUM_0}, /* 0 */
+ {"9", 1, NULL, NUM_9}, /* 9 */
+ {"B", 1, NULL, NUM_B}, /* B */
+ {"C", 1, NULL, NUM_C}, /* C */
+ {"D", 1, NULL, NUM_D}, /* D */
+ {"E", 1, NULL, NUM_E}, /* E */
+ {"FM", 2, NULL, NUM_FM}, /* F */
+ {"G", 1, NULL, NUM_G}, /* G */
+ {"L", 1, NULL, NUM_L}, /* L */
+ {"MI", 2, NULL, NUM_MI}, /* M */
+ {"PL", 2, NULL, NUM_PL}, /* P */
+ {"PR", 2, NULL, NUM_PR},
+ {"RN", 2, NULL, NUM_RN}, /* R */
+ {"SG", 2, NULL, NUM_SG}, /* S */
+ {"SP", 2, NULL, NUM_SP},
+ {"S", 1, NULL, NUM_S},
+ {"TH", 2, NULL, NUM_TH}, /* T */
+ {"V", 1, NULL, NUM_V}, /* V */
+ {"b", 1, NULL, NUM_B}, /* b */
+ {"c", 1, NULL, NUM_C}, /* c */
+ {"d", 1, NULL, NUM_D}, /* d */
+ {"e", 1, NULL, NUM_E}, /* e */
+ {"fm", 2, NULL, NUM_FM}, /* f */
+ {"g", 1, NULL, NUM_G}, /* g */
+ {"l", 1, NULL, NUM_L}, /* l */
+ {"mi", 2, NULL, NUM_MI}, /* m */
+ {"pl", 2, NULL, NUM_PL}, /* p */
+ {"pr", 2, NULL, NUM_PR},
+ {"rn", 2, NULL, NUM_rn}, /* r */
+ {"sg", 2, NULL, NUM_SG}, /* s */
+ {"sp", 2, NULL, NUM_SP},
+ {"s", 1, NULL, NUM_S},
+ {"th", 2, NULL, NUM_th}, /* t */
+ {"v", 1, NULL, NUM_V}, /* v */
+
+/* last */
+{NULL, 0, NULL, 0}};
/* ----------
* KeyWords index for DATE-TIME version
* ----------
*/
-static int DCH_index[ KeyWord_INDEX_SIZE ] = {
+static int DCH_index[KeyWord_INDEX_SIZE] = {
/*
0 1 2 3 4 5 6 7 8 9
*/
/*---- first 0..31 chars are skiped ----*/
- -1, -1, -1, -1, -1, -1, -1, -1,
--1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
--1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
--1, -1, -1, -1, -1, DCH_A_D,DCH_B_C,DCH_CC, DCH_DAY,-1,
-DCH_FX, -1, DCH_HH24,-1, DCH_J, -1, -1, DCH_MI, -1, -1,
-DCH_P_M, DCH_Q, DCH_RM, DCH_SSSS,-1, -1, -1, DCH_WW, -1, DCH_Y_YYY,
--1, -1, -1, -1, -1, -1, -1, DCH_a_d,DCH_b_c,DCH_cc,
-DCH_day,-1, DCH_fx, -1, DCH_hh24,-1, DCH_j, -1, -1, DCH_mi,
--1, -1, DCH_p_m, DCH_q, DCH_rm, DCH_ssss,-1, -1, -1, DCH_ww,
--1, DCH_y_yyy,-1, -1, -1, -1
+ -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, DCH_A_D, DCH_B_C, DCH_CC, DCH_DAY, -1,
+ DCH_FX, -1, DCH_HH24, -1, DCH_J, -1, -1, DCH_MI, -1, -1,
+ DCH_P_M, DCH_Q, DCH_RM, DCH_SSSS, -1, -1, -1, DCH_WW, -1, DCH_Y_YYY,
+ -1, -1, -1, -1, -1, -1, -1, DCH_a_d, DCH_b_c, DCH_cc,
+ DCH_day, -1, DCH_fx, -1, DCH_hh24, -1, DCH_j, -1, -1, DCH_mi,
+ -1, -1, DCH_p_m, DCH_q, DCH_rm, DCH_ssss, -1, -1, -1, DCH_ww,
+ -1, DCH_y_yyy, -1, -1, -1, -1
/*---- chars over 126 are skiped ----*/
-};
+};
/* ----------
* KeyWords index for NUMBER version
* ----------
*/
-static int NUM_index[ KeyWord_INDEX_SIZE ] = {
+static int NUM_index[KeyWord_INDEX_SIZE] = {
/*
0 1 2 3 4 5 6 7 8 9
*/
/*---- first 0..31 chars are skiped ----*/
- -1, -1, -1, -1, -1, -1, -1, -1,
--1, -1, -1, -1, NUM_COMMA,-1, NUM_DEC,-1, NUM_0, -1,
--1, -1, -1, -1, -1, -1, -1, NUM_9, -1, -1,
--1, -1, -1, -1, -1, -1, NUM_B, NUM_C, NUM_D, NUM_E,
-NUM_FM, NUM_G, -1, -1, -1, -1, NUM_L, NUM_MI, -1, -1,
-NUM_PL,-1, NUM_RN, NUM_SG, NUM_TH, -1, NUM_V, -1, -1, -1,
--1, -1, -1, -1, -1, -1, -1, -1, NUM_b, NUM_c,
-NUM_d, NUM_e, NUM_fm, NUM_g, -1, -1, -1, -1, NUM_l, NUM_mi,
--1, -1, NUM_pl, -1, NUM_rn, NUM_sg, NUM_th, -1, NUM_v, -1,
--1, -1, -1, -1, -1, -1
+ -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, NUM_COMMA, -1, NUM_DEC, -1, NUM_0, -1,
+ -1, -1, -1, -1, -1, -1, -1, NUM_9, -1, -1,
+ -1, -1, -1, -1, -1, -1, NUM_B, NUM_C, NUM_D, NUM_E,
+ NUM_FM, NUM_G, -1, -1, -1, -1, NUM_L, NUM_MI, -1, -1,
+ NUM_PL, -1, NUM_RN, NUM_SG, NUM_TH, -1, NUM_V, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, NUM_b, NUM_c,
+ NUM_d, NUM_e, NUM_fm, NUM_g, -1, -1, -1, -1, NUM_l, NUM_mi,
+ -1, -1, NUM_pl, -1, NUM_rn, NUM_sg, NUM_th, -1, NUM_v, -1,
+ -1, -1, -1, -1, -1, -1
/*---- chars over 126 are skiped ----*/
};
@@ -726,32 +737,33 @@ NUM_d, NUM_e, NUM_fm, NUM_g, -1, -1, -1, -1, NUM_l, NUM_mi,
*/
typedef struct NUMProc
{
- int type; /* FROM_CHAR (TO_NUMBER) or TO_CHAR */
-
- NUMDesc *Num; /* number description */
-
- int sign, /* '-' or '+' */
- sign_wrote, /* was sign write */
- sign_pos, /* pre number sign position */
- num_count, /* number of write digits */
- num_in, /* is inside number */
- num_curr, /* current position in number */
- num_pre, /* space before first number */
-
- read_dec, /* to_number - was read dec. point */
- read_post; /* to_number - number of dec. digit */
-
- char *number, /* string with number */
- *number_p, /* pointer to current number pozition */
- *inout, /* in / out buffer */
- *inout_p, /* pointer to current inout pozition */
- *last_relevant, /* last relevant number after decimal point */
-
- *L_negative_sign, /* Locale */
- *L_positive_sign,
- *decimal,
- *L_thousands_sep,
- *L_currency_symbol;
+ int type; /* FROM_CHAR (TO_NUMBER) or TO_CHAR */
+
+ NUMDesc *Num; /* number description */
+
+ int sign, /* '-' or '+' */
+ sign_wrote, /* was sign write */
+ sign_pos, /* pre number sign position */
+ num_count, /* number of write digits */
+ num_in, /* is inside number */
+ num_curr, /* current position in number */
+ num_pre, /* space before first number */
+
+ read_dec, /* to_number - was read dec. point */
+ read_post; /* to_number - number of dec. digit */
+
+ char *number, /* string with number */
+ *number_p, /* pointer to current number pozition */
+ *inout, /* in / out buffer */
+ *inout_p, /* pointer to current inout pozition */
+ *last_relevant, /* last relevant number after decimal
+ * point */
+
+ *L_negative_sign,/* Locale */
+ *L_positive_sign,
+ *decimal,
+ *L_thousands_sep,
+ *L_currency_symbol;
} NUMProc;
@@ -762,38 +774,40 @@ typedef struct NUMProc
static KeyWord *index_seq_search(char *str, KeyWord *kw, int *index);
static KeySuffix *suff_search(char *str, KeySuffix *suf, int type);
static void NUMDesc_prepare(NUMDesc *num, FormatNode *n);
-static void parse_format(FormatNode *node, char *str, KeyWord *kw,
- KeySuffix *suf, int *index, int ver, NUMDesc *Num);
+static void parse_format(FormatNode *node, char *str, KeyWord *kw,
+ KeySuffix *suf, int *index, int ver, NUMDesc *Num);
static char *DCH_processor(FormatNode *node, char *inout, int flag);
#ifdef DEBUG_TO_FROM_CHAR
- static void dump_index(KeyWord *k, int *index);
- static void dump_node(FormatNode *node, int max);
+static void dump_index(KeyWord *k, int *index);
+static void dump_node(FormatNode *node, int max);
+
#endif
static char *get_th(char *num, int type);
static char *str_numth(char *dest, char *num, int type);
-static int int4len(int4 num);
+static int int4len(int4 num);
static char *str_toupper(char *buff);
static char *str_tolower(char *buff);
+
/* static int is_acdc(char *str, int *len); */
-static int seq_search(char *name, char **array, int type, int max, int *len);
-static int dch_global(int arg, char *inout, int suf, int flag, FormatNode *node);
-static int dch_time(int arg, char *inout, int suf, int flag, FormatNode *node);
-static int dch_date(int arg, char *inout, int suf, int flag, FormatNode *node);
+static int seq_search(char *name, char **array, int type, int max, int *len);
+static int dch_global(int arg, char *inout, int suf, int flag, FormatNode *node);
+static int dch_time(int arg, char *inout, int suf, int flag, FormatNode *node);
+static int dch_date(int arg, char *inout, int suf, int flag, FormatNode *node);
static char *fill_str(char *str, int c, int max);
-static FormatNode *NUM_cache( int len, NUMDesc *Num, char *pars_str, int *flag);
+static FormatNode *NUM_cache(int len, NUMDesc *Num, char *pars_str, int *flag);
static char *int_to_roman(int number);
static void NUM_prepare_locale(NUMProc *Np);
static char *get_last_relevant_decnum(char *num);
-static void NUM_numpart_from_char(NUMProc *Np, int id, int plen);
-static void NUM_numpart_to_char(NUMProc *Np, int id);
-static char *NUM_processor (FormatNode *node, NUMDesc *Num, char *inout, char *number,
- int plen, int sign, int type);
-static DCHCacheEntry *DCH_cache_search( char *str );
-static DCHCacheEntry *DCH_cache_getnew( char *str );
-static NUMCacheEntry *NUM_cache_search( char *str );
-static NUMCacheEntry *NUM_cache_getnew( char *str );
+static void NUM_numpart_from_char(NUMProc *Np, int id, int plen);
+static void NUM_numpart_to_char(NUMProc *Np, int id);
+static char *NUM_processor(FormatNode *node, NUMDesc *Num, char *inout, char *number,
+ int plen, int sign, int type);
+static DCHCacheEntry *DCH_cache_search(char *str);
+static DCHCacheEntry *DCH_cache_getnew(char *str);
+static NUMCacheEntry *NUM_cache_search(char *str);
+static NUMCacheEntry *NUM_cache_getnew(char *str);
/* ----------
@@ -803,24 +817,26 @@ static NUMCacheEntry *NUM_cache_getnew( char *str );
* ----------
*/
static KeyWord *
-index_seq_search(char *str, KeyWord *kw, int *index)
+index_seq_search(char *str, KeyWord *kw, int *index)
{
- int poz;
+ int poz;
- if (! KeyWord_INDEX_FILTER(*str))
+ if (!KeyWord_INDEX_FILTER(*str))
return (KeyWord *) NULL;
- if ( (poz = *(index + (*str - ' '))) > -1) {
-
- KeyWord *k = kw+poz;
-
- do {
- if (! strncmp(str, k->name, k->len))
+ if ((poz = *(index + (*str - ' '))) > -1)
+ {
+
+ KeyWord *k = kw + poz;
+
+ do
+ {
+ if (!strncmp(str, k->name, k->len))
return k;
k++;
if (!k->name)
- return (KeyWord *) NULL;
- } while(*str == *k->name);
+ return (KeyWord *) NULL;
+ } while (*str == *k->name);
}
return (KeyWord *) NULL;
}
@@ -828,12 +844,13 @@ index_seq_search(char *str, KeyWord *kw, int *index)
static KeySuffix *
suff_search(char *str, KeySuffix *suf, int type)
{
- KeySuffix *s;
-
- for(s=suf; s->name != NULL; s++) {
+ KeySuffix *s;
+
+ for (s = suf; s->name != NULL; s++)
+ {
if (s->type != type)
continue;
-
+
if (!strncmp(str, s->name, s->len))
return s;
}
@@ -844,152 +861,158 @@ suff_search(char *str, KeySuffix *suf, int type)
* Prepare NUMDesc (number description struct) via FormatNode struct
* ----------
*/
-static void
+static void
NUMDesc_prepare(NUMDesc *num, FormatNode *n)
{
if (n->type != NODE_TYPE_ACTION)
return;
-
- switch(n->key->id) {
-
+
+ switch (n->key->id)
+ {
+
case NUM_9:
if (IS_BRACKET(num))
- elog(ERROR, "to_char/to_number(): '9' must be ahead of 'PR'.");
-
- if (IS_MULTI(num)) {
+ elog(ERROR, "to_char/to_number(): '9' must be ahead of 'PR'.");
+
+ if (IS_MULTI(num))
+ {
++num->multi;
break;
}
if (IS_DECIMAL(num))
++num->post;
- else
+ else
++num->pre;
break;
-
+
case NUM_0:
if (IS_BRACKET(num))
- elog(ERROR, "to_char/to_number(): '0' must be ahead of 'PR'.");
+ elog(ERROR, "to_char/to_number(): '0' must be ahead of 'PR'.");
- if (!IS_ZERO(num) && !IS_DECIMAL(num)) {
- num->flag |= NUM_F_ZERO;
+ if (!IS_ZERO(num) && !IS_DECIMAL(num))
+ {
+ num->flag |= NUM_F_ZERO;
num->zero_start = num->pre + 1;
}
- if (! IS_DECIMAL(num))
+ if (!IS_DECIMAL(num))
++num->pre;
- else
+ else
++num->post;
-
+
num->zero_end = num->pre + num->post;
- break;
-
+ break;
+
case NUM_B:
- if (num->pre == 0 && num->post == 0 && (! IS_ZERO(num)))
- num->flag |= NUM_F_BLANK;
- break;
-
+ if (num->pre == 0 && num->post == 0 && (!IS_ZERO(num)))
+ num->flag |= NUM_F_BLANK;
+ break;
+
case NUM_D:
num->flag |= NUM_F_LDECIMAL;
num->need_locale = TRUE;
case NUM_DEC:
if (IS_DECIMAL(num))
- elog(ERROR, "to_char/to_number(): not unique decimal poit.");
+ elog(ERROR, "to_char/to_number(): not unique decimal poit.");
if (IS_MULTI(num))
- elog(ERROR, "to_char/to_number(): can't use 'V' and decimal poin together.");
+ elog(ERROR, "to_char/to_number(): can't use 'V' and decimal poin together.");
num->flag |= NUM_F_DECIMAL;
break;
-
+
case NUM_FM:
num->flag |= NUM_F_FILLMODE;
break;
-
+
case NUM_S:
if (IS_LSIGN(num))
- elog(ERROR, "to_char/to_number(): not unique 'S'.");
-
+ elog(ERROR, "to_char/to_number(): not unique 'S'.");
+
if (IS_PLUS(num) || IS_MINUS(num) || IS_BRACKET(num))
- elog(ERROR, "to_char/to_number(): can't use 'S' and 'PL'/'MI'/'SG'/'PR' together.");
-
- if (! IS_DECIMAL(num)) {
+ elog(ERROR, "to_char/to_number(): can't use 'S' and 'PL'/'MI'/'SG'/'PR' together.");
+
+ if (!IS_DECIMAL(num))
+ {
num->lsign = NUM_LSIGN_PRE;
num->pre_lsign_num = num->pre;
num->need_locale = TRUE;
num->flag |= NUM_F_LSIGN;
-
- } else if (num->lsign == NUM_LSIGN_NONE) {
- num->lsign = NUM_LSIGN_POST;
+
+ }
+ else if (num->lsign == NUM_LSIGN_NONE)
+ {
+ num->lsign = NUM_LSIGN_POST;
num->need_locale = TRUE;
num->flag |= NUM_F_LSIGN;
- }
+ }
break;
-
+
case NUM_MI:
if (IS_LSIGN(num))
- elog(ERROR, "to_char/to_number(): can't use 'S' and 'MI' together.");
-
+ elog(ERROR, "to_char/to_number(): can't use 'S' and 'MI' together.");
+
num->flag |= NUM_F_MINUS;
break;
-
+
case NUM_PL:
if (IS_LSIGN(num))
- elog(ERROR, "to_char/to_number(): can't use 'S' and 'PL' together.");
-
+ elog(ERROR, "to_char/to_number(): can't use 'S' and 'PL' together.");
+
num->flag |= NUM_F_PLUS;
- break;
-
+ break;
+
case NUM_SG:
if (IS_LSIGN(num))
- elog(ERROR, "to_char/to_number(): can't use 'S' and 'SG' together.");
-
+ elog(ERROR, "to_char/to_number(): can't use 'S' and 'SG' together.");
+
num->flag |= NUM_F_MINUS;
num->flag |= NUM_F_PLUS;
break;
-
+
case NUM_PR:
if (IS_LSIGN(num) || IS_PLUS(num) || IS_MINUS(num))
- elog(ERROR, "to_char/to_number(): can't use 'PR' and 'S'/'PL'/'MI'/'SG' together.");
+ elog(ERROR, "to_char/to_number(): can't use 'PR' and 'S'/'PL'/'MI'/'SG' together.");
num->flag |= NUM_F_BRACKET;
- break;
-
+ break;
+
case NUM_rn:
case NUM_RN:
num->flag |= NUM_F_ROMAN;
break;
-
+
case NUM_L:
case NUM_G:
- num->need_locale = TRUE;
+ num->need_locale = TRUE;
break;
-
+
case NUM_V:
if (IS_DECIMAL(num))
- elog(ERROR, "to_char/to_number(): can't use 'V' and decimal poin together.");
+ elog(ERROR, "to_char/to_number(): can't use 'V' and decimal poin together.");
num->flag |= NUM_F_MULTI;
- break;
-
+ break;
+
case NUM_E:
- elog(ERROR, "to_char/to_number(): 'E' is not supported.");
+ elog(ERROR, "to_char/to_number(): 'E' is not supported.");
}
-
+
return;
}
/* ----------
- * Format parser, search small keywords and keyword's suffixes, and make
+ * Format parser, search small keywords and keyword's suffixes, and make
* format-node tree.
*
- * for DATE-TIME & NUMBER version
+ * for DATE-TIME & NUMBER version
* ----------
*/
-static void
-parse_format(FormatNode *node, char *str, KeyWord *kw,
- KeySuffix *suf, int *index, int ver, NUMDesc *Num)
+static void
+parse_format(FormatNode *node, char *str, KeyWord *kw,
+ KeySuffix *suf, int *index, int ver, NUMDesc *Num)
{
- KeySuffix *s;
- FormatNode *n;
- int node_set=0,
- suffix,
- last=0;
+ KeySuffix *s;
+ FormatNode *n;
+ int node_set = 0,
+ suffix,
+ last = 0;
#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, "to_char/number(): run parser.");
@@ -997,63 +1020,74 @@ parse_format(FormatNode *node, char *str, KeyWord *kw,
n = node;
- while(*str) {
- suffix=0;
-
- /* ----------
- * Prefix
+ while (*str)
+ {
+ suffix = 0;
+
+ /* ----------
+ * Prefix
* ----------
*/
- if (ver==DCH_TYPE && (s = suff_search(str, suf, SUFFTYPE_PREFIX)) != NULL) {
+ if (ver == DCH_TYPE && (s = suff_search(str, suf, SUFFTYPE_PREFIX)) != NULL)
+ {
suffix |= s->id;
if (s->len)
str += s->len;
}
-
+
/* ----------
- * Keyword
+ * Keyword
* ----------
*/
- if (*str && (n->key = index_seq_search(str, kw, index)) != NULL) {
-
+ if (*str && (n->key = index_seq_search(str, kw, index)) != NULL)
+ {
+
n->type = NODE_TYPE_ACTION;
n->suffix = 0;
- node_set= 1;
+ node_set = 1;
if (n->key->len)
str += n->key->len;
-
+
/* ----------
- * NUM version: Prepare global NUMDesc struct
+ * NUM version: Prepare global NUMDesc struct
* ----------
*/
- if (ver==NUM_TYPE)
+ if (ver == NUM_TYPE)
NUMDesc_prepare(Num, n);
-
+
/* ----------
* Postfix
* ----------
*/
- if (ver==DCH_TYPE && *str && (s = suff_search(str, suf, SUFFTYPE_POSTFIX)) != NULL) {
+ if (ver == DCH_TYPE && *str && (s = suff_search(str, suf, SUFFTYPE_POSTFIX)) != NULL)
+ {
suffix |= s->id;
if (s->len)
str += s->len;
}
-
- } else if (*str) {
-
- /* ----------
- * Special characters '\' and '"'
+
+ }
+ else if (*str)
+ {
+
+ /* ----------
+ * Special characters '\' and '"'
* ----------
*/
- if (*str == '"' && last != '\\') {
-
- int x = 0;
-
- while(*(++str)) {
- if (*str == '"' && x != '\\') {
+ if (*str == '"' && last != '\\')
+ {
+
+ int x = 0;
+
+ while (*(++str))
+ {
+ if (*str == '"' && x != '\\')
+ {
str++;
break;
- } else if (*str == '\\' && x != '\\') {
+ }
+ else if (*str == '\\' && x != '\\')
+ {
x = '\\';
continue;
}
@@ -1062,17 +1096,21 @@ parse_format(FormatNode *node, char *str, KeyWord *kw,
n->key = (KeyWord *) NULL;
n->suffix = 0;
++n;
- x = *str;
+ x = *str;
}
node_set = 0;
suffix = 0;
last = 0;
-
- } else if (*str && *str == '\\' && last!='\\' && *(str+1) =='"') {
+
+ }
+ else if (*str && *str == '\\' && last != '\\' && *(str + 1) == '"')
+ {
last = *str;
str++;
-
- } else if (*str) {
+
+ }
+ else if (*str)
+ {
n->type = NODE_TYPE_CHAR;
n->character = *str;
n->key = (KeyWord *) NULL;
@@ -1080,19 +1118,20 @@ parse_format(FormatNode *node, char *str, KeyWord *kw,
last = 0;
str++;
}
-
+
}
-
- /* end */
- if (node_set) {
- if (n->type == NODE_TYPE_ACTION)
- n->suffix = suffix;
+
+ /* end */
+ if (node_set)
+ {
+ if (n->type == NODE_TYPE_ACTION)
+ n->suffix = suffix;
++n;
n->suffix = 0;
node_set = 0;
}
-
+
}
n->type = NODE_TYPE_END;
@@ -1101,62 +1140,68 @@ parse_format(FormatNode *node, char *str, KeyWord *kw,
}
/* ----------
- * Call keyword's function for each of (action) node in format-node tree
+ * Call keyword's function for each of (action) node in format-node tree
* ----------
*/
static char *
DCH_processor(FormatNode *node, char *inout, int flag)
{
- FormatNode *n;
- char *s;
-
-
+ FormatNode *n;
+ char *s;
+
+
/* ----------
* Zeroing global flags
* ----------
*/
DCH_global_flag = 0;
-
- for(n=node, s=inout; n->type != NODE_TYPE_END; n++) {
- if (n->type == NODE_TYPE_ACTION) {
-
- int len;
-
+
+ for (n = node, s = inout; n->type != NODE_TYPE_END; n++)
+ {
+ if (n->type == NODE_TYPE_ACTION)
+ {
+
+ int len;
+
/* ----------
- * Call node action function
+ * Call node action function
* ----------
*/
- len = n->key->action(n->key->id, s, n->suffix, flag, n);
- if (len > 0)
+ len = n->key->action(n->key->id, s, n->suffix, flag, n);
+ if (len > 0)
s += len;
else if (len == -1)
- continue;
-
- } else {
-
+ continue;
+
+ }
+ else
+ {
+
/* ----------
* Remove to output char from input in TO_CHAR
* ----------
*/
- if (flag == TO_CHAR)
+ if (flag == TO_CHAR)
*s = n->character;
-
- else {
+
+ else
+ {
/* ----------
- * Skip blank space in FROM_CHAR's input
+ * Skip blank space in FROM_CHAR's input
* ----------
*/
- if (isspace(n->character) && IS_FX == 0) {
- while(*s != '\0' && isspace(*(s+1)))
- ++s;
+ if (isspace(n->character) && IS_FX == 0)
+ {
+ while (*s != '\0' && isspace(*(s + 1)))
+ ++s;
}
}
}
-
- ++s; /* ! */
-
+
+ ++s; /* ! */
+
}
-
+
if (flag == TO_CHAR)
*s = '\0';
return inout;
@@ -1172,91 +1217,101 @@ DCH_processor(FormatNode *node, char *inout, int flag)
#define DUMP_THth(_suf) (S_TH(_suf) ? "TH" : (S_th(_suf) ? "th" : " "))
#define DUMP_FM(_suf) (S_FM(_suf) ? "FM" : " ")
-static void
+static void
dump_node(FormatNode *node, int max)
{
- FormatNode *n;
- int a;
-
+ FormatNode *n;
+ int a;
+
elog(DEBUG_elog_output, "to_from-char(): DUMP FORMAT");
-
- for(a=0, n=node; a<=max; n++, a++) {
- if (n->type == NODE_TYPE_ACTION)
- elog(DEBUG_elog_output, "%d:\t NODE_TYPE_ACTION '%s'\t(%s,%s)",
- a, n->key->name, DUMP_THth(n->suffix), DUMP_FM(n->suffix));
- else if (n->type == NODE_TYPE_CHAR)
- elog(DEBUG_elog_output, "%d:\t NODE_TYPE_CHAR '%c'", a, n->character);
- else if (n->type == NODE_TYPE_END) {
- elog(DEBUG_elog_output, "%d:\t NODE_TYPE_END", a);
+
+ for (a = 0, n = node; a <= max; n++, a++)
+ {
+ if (n->type == NODE_TYPE_ACTION)
+ elog(DEBUG_elog_output, "%d:\t NODE_TYPE_ACTION '%s'\t(%s,%s)",
+ a, n->key->name, DUMP_THth(n->suffix), DUMP_FM(n->suffix));
+ else if (n->type == NODE_TYPE_CHAR)
+ elog(DEBUG_elog_output, "%d:\t NODE_TYPE_CHAR '%c'", a, n->character);
+ else if (n->type == NODE_TYPE_END)
+ {
+ elog(DEBUG_elog_output, "%d:\t NODE_TYPE_END", a);
return;
- } else
- elog(DEBUG_elog_output, "%d:\t UnKnown NODE !!!", a);
-
+ }
+ else
+ elog(DEBUG_elog_output, "%d:\t UnKnown NODE !!!", a);
+
}
}
+
#endif
/*****************************************************************************
- * Private utils
+ * Private utils
*****************************************************************************/
/* ----------
- * Return ST/ND/RD/TH for simple (1..9) numbers
+ * Return ST/ND/RD/TH for simple (1..9) numbers
* type --> 0 upper, 1 lower
- * ----------
- */
+ * ----------
+ */
static char *
get_th(char *num, int type)
{
- int len = strlen(num),
- last;
-
- last = *(num + (len-1));
+ int len = strlen(num),
+ last;
+
+ last = *(num + (len - 1));
if (!isdigit((unsigned char) last))
elog(ERROR, "get_th: '%s' is not number.", num);
-
+
/* 11 || 12 */
- if (len == 2 && (last=='1' || last=='2') && *num == '1')
- last=0;
+ if (len == 2 && (last == '1' || last == '2') && *num == '1')
+ last = 0;
- switch(last) {
+ switch (last)
+ {
case '1':
- if (type==TH_UPPER) return numTH[0];
+ if (type == TH_UPPER)
+ return numTH[0];
return numth[0];
case '2':
- if (type==TH_UPPER) return numTH[1];
+ if (type == TH_UPPER)
+ return numTH[1];
return numth[1];
case '3':
- if (type==TH_UPPER) return numTH[2];
- return numth[2];
+ if (type == TH_UPPER)
+ return numTH[2];
+ return numth[2];
default:
- if (type==TH_UPPER) return numTH[3];
+ if (type == TH_UPPER)
+ return numTH[3];
return numth[3];
}
return NULL;
}
/* ----------
- * Convert string-number to ordinal string-number
- * type --> 0 upper, 1 lower
+ * Convert string-number to ordinal string-number
+ * type --> 0 upper, 1 lower
* ----------
*/
static char *
str_numth(char *dest, char *num, int type)
{
sprintf(dest, "%s%s", num, get_th(num, type));
- return dest;
+ return dest;
}
/* ----------
- * Return length of integer writed in string
+ * Return length of integer writed in string
* ----------
*/
-static int
+static int
int4len(int4 num)
{
- char b[16];
- return sprintf(b, "%d", num);
+ char b[16];
+
+ return sprintf(b, "%d", num);
}
/* ----------
@@ -1265,10 +1320,11 @@ int4len(int4 num)
*/
static char *
str_toupper(char *buff)
-{
- char *p_buff=buff;
+{
+ char *p_buff = buff;
- while (*p_buff) {
+ while (*p_buff)
+ {
*p_buff = toupper((unsigned char) *p_buff);
++p_buff;
}
@@ -1281,10 +1337,11 @@ str_toupper(char *buff)
*/
static char *
str_tolower(char *buff)
-{
- char *p_buff=buff;
+{
+ char *p_buff = buff;
- while (*p_buff) {
+ while (*p_buff)
+ {
*p_buff = tolower((unsigned char) *p_buff);
++p_buff;
}
@@ -1292,132 +1349,151 @@ str_tolower(char *buff)
}
/* ----------
- * Check if in string is AC or BC (return: 0==none; -1==BC; 1==AC)
+ * Check if in string is AC or BC (return: 0==none; -1==BC; 1==AC)
* ----------
*/
/************* not used - use AD/BC format pictures instead **********
-static int
+static int
is_acdc(char *str, int *len)
{
char *p;
-
+
for(p=str; *p != '\0'; p++) {
if (isspace(*p))
continue;
-
- if (*(p+1)) {
+
+ if (*(p+1)) {
if (toupper(*p)=='B' && toupper(*(++p))=='C') {
- *len += (p - str) +1;
- return -1;
+ *len += (p - str) +1;
+ return -1;
} else if (toupper(*p)=='A' && toupper(*(++p))=='C') {
- *len += (p - str) +1;
- return 1;
- }
- }
- return 0;
+ *len += (p - str) +1;
+ return 1;
+ }
+ }
+ return 0;
}
return 0;
-}
+}
******************************/
-
+
/* ----------
* Sequential search with to upper/lower conversion
* ----------
*/
-static int
+static int
seq_search(char *name, char **array, int type, int max, int *len)
{
- char *p, *n, **a;
- int last, i;
-
+ char *p,
+ *n,
+ **a;
+ int last,
+ i;
+
*len = 0;
-
- if (!*name)
+
+ if (!*name)
return -1;
-
- /* set first char */
- if (type == ONE_UPPER || ALL_UPPER)
+
+ /* set first char */
+ if (type == ONE_UPPER || ALL_UPPER)
*name = toupper((unsigned char) *name);
else if (type == ALL_LOWER)
*name = tolower((unsigned char) *name);
-
- for(last=0, a=array; *a != NULL; a++) {
-
+
+ for (last = 0, a = array; *a != NULL; a++)
+ {
+
/* comperate first chars */
if (*name != **a)
continue;
-
- for(i=1, p=*a+1, n=name+1; ; n++, p++, i++) {
-
+
+ for (i = 1, p = *a + 1, n = name + 1;; n++, p++, i++)
+ {
+
/* search fragment (max) only */
- if (max && i == max) {
+ if (max && i == max)
+ {
*len = i;
return a - array;
- }
+ }
/* full size */
- if (*p=='\0') {
+ if (*p == '\0')
+ {
*len = i;
return a - array;
}
/* Not found in array 'a' */
- if (*n=='\0')
+ if (*n == '\0')
break;
-
- /*
+
+ /*
* Convert (but convert new chars only)
*/
- if (i > last) {
- if (type == ONE_UPPER || type == ALL_LOWER)
+ if (i > last)
+ {
+ if (type == ONE_UPPER || type == ALL_LOWER)
*n = tolower((unsigned char) *n);
- else if (type == ALL_UPPER)
+ else if (type == ALL_UPPER)
*n = toupper((unsigned char) *n);
- last=i;
+ last = i;
}
-#ifdef DEBUG_TO_FROM_CHAR
- /* elog(DEBUG_elog_output, "N: %c, P: %c, A: %s (%s)", *n, *p, *a, name);*/
-#endif
+#ifdef DEBUG_TO_FROM_CHAR
+
+ /*
+ * elog(DEBUG_elog_output, "N: %c, P: %c, A: %s (%s)", *n, *p,
+ * *a, name);
+ */
+#endif
if (*n != *p)
- break;
- }
+ break;
+ }
}
-
- return -1;
+
+ return -1;
}
#ifdef DEBUG_TO_FROM_CHAR
/* -----------
- * DEBUG: Call for debug and for index checking; (Show ASCII char
- * and defined keyword for each used position
+ * DEBUG: Call for debug and for index checking; (Show ASCII char
+ * and defined keyword for each used position
* ----------
- */
-static void
+ */
+static void
dump_index(KeyWord *k, int *index)
{
- int i, count=0, free_i=0;
-
+ int i,
+ count = 0,
+ free_i = 0;
+
elog(DEBUG_elog_output, "TO-FROM_CHAR: Dump KeyWord Index:");
-
- for(i=0; i < KeyWord_INDEX_SIZE; i++) {
- if (index[i] != -1) {
- elog(DEBUG_elog_output, "\t%c: %s, ", i+32, k[ index[i] ].name);
+
+ for (i = 0; i < KeyWord_INDEX_SIZE; i++)
+ {
+ if (index[i] != -1)
+ {
+ elog(DEBUG_elog_output, "\t%c: %s, ", i + 32, k[index[i]].name);
count++;
- } else {
- free_i++;
- elog(DEBUG_elog_output, "\t(%d) %c %d", i, i+32, index[i]);
}
- }
+ else
+ {
+ free_i++;
+ elog(DEBUG_elog_output, "\t(%d) %c %d", i, i + 32, index[i]);
+ }
+ }
elog(DEBUG_elog_output, "\n\t\tUsed positions: %d,\n\t\tFree positions: %d",
- count, free_i);
+ count, free_i);
}
+
#endif
/* ----------
* Skip TM / th in FROM_CHAR
* ----------
*/
-#define SKIP_THth(_suf) (S_THth(_suf) ? 2 : 0)
+#define SKIP_THth(_suf) (S_THth(_suf) ? 2 : 0)
/* ----------
@@ -1425,725 +1501,865 @@ dump_index(KeyWord *k, int *index)
* ----------
*/
static int
-dch_global(int arg, char *inout, int suf, int flag, FormatNode *node)
+dch_global(int arg, char *inout, int suf, int flag, FormatNode *node)
{
- switch(arg) {
-
- case DCH_FX:
- DCH_global_flag |= DCH_F_FX;
- break;
+ switch (arg)
+ {
+
+ case DCH_FX:
+ DCH_global_flag |= DCH_F_FX;
+ break;
}
return -1;
}
/* ----------
- * Master function of TIME for:
- * TO_CHAR - write (inout) formated string
- * FROM_CHAR - scan (inout) string by course of FormatNode
+ * Master function of TIME for:
+ * TO_CHAR - write (inout) formated string
+ * FROM_CHAR - scan (inout) string by course of FormatNode
* ----------
*/
-static int
-dch_time(int arg, char *inout, int suf, int flag, FormatNode *node)
+static int
+dch_time(int arg, char *inout, int suf, int flag, FormatNode *node)
{
- char *p_inout = inout;
-
- switch(arg) {
-
- case DCH_A_M:
- case DCH_P_M:
- if (flag == TO_CHAR) {
- strcpy(inout, (tm->tm_hour > 13 ? P_M_STR : A_M_STR ));
- return 3;
-
- } else if (flag == FROM_CHAR) {
- if (strncmp(inout, P_M_STR, 4)==0 && tm->tm_hour < 13)
- tm->tm_hour += 12;
- return 3;
- }
-
- case DCH_AM:
- case DCH_PM:
- if (flag == TO_CHAR) {
- strcpy(inout, (tm->tm_hour > 13 ? PM_STR : AM_STR ));
- return 1;
-
- } else if (flag == FROM_CHAR) {
- if (strncmp(inout, PM_STR, 2)==0 && tm->tm_hour < 13)
- tm->tm_hour += 12;
- return 1;
- }
-
- case DCH_a_m:
- case DCH_p_m:
- if (flag == TO_CHAR) {
- strcpy(inout, (tm->tm_hour > 13 ? p_m_STR : a_m_STR ));
- return 3;
-
- } else if (flag == FROM_CHAR) {
- if (strncmp(inout, p_m_STR, 4)==0 && tm->tm_hour < 13)
- tm->tm_hour += 12;
- return 3;
- }
-
- case DCH_am:
- case DCH_pm:
- if (flag == TO_CHAR) {
- strcpy(inout, (tm->tm_hour > 13 ? pm_STR : am_STR ));
- return 1;
-
- } else if (flag == FROM_CHAR) {
- if (strncmp(inout, pm_STR, 2)==0 && tm->tm_hour < 13)
- tm->tm_hour += 12;
- return 1;
- }
-
- case DCH_HH:
- case DCH_HH12:
- if (flag == TO_CHAR) {
- sprintf(inout, "%0*d", S_FM(suf) ? 0 : 2,
- tm->tm_hour==0 ? 12 :
- tm->tm_hour <13 ? tm->tm_hour : tm->tm_hour-12);
- if (S_THth(suf))
- str_numth(p_inout, inout, 0);
- if (S_FM(suf) || S_THth(suf))
- return strlen(p_inout)-1;
- else
- return 1;
-
- } else if (flag == FROM_CHAR) {
- if (S_FM(suf)) {
- sscanf(inout, "%d", &tm->tm_hour);
- return int4len((int4) tm->tm_hour)-1 + SKIP_THth(suf);
- } else {
- sscanf(inout, "%02d", &tm->tm_hour);
- return 1 + SKIP_THth(suf);
+ char *p_inout = inout;
+
+ switch (arg)
+ {
+
+ case DCH_A_M:
+ case DCH_P_M:
+ if (flag == TO_CHAR)
+ {
+ strcpy(inout, (tm->tm_hour > 13 ? P_M_STR : A_M_STR));
+ return 3;
+
+ }
+ else if (flag == FROM_CHAR)
+ {
+ if (strncmp(inout, P_M_STR, 4) == 0 && tm->tm_hour < 13)
+ tm->tm_hour += 12;
+ return 3;
}
- }
- case DCH_HH24:
- if (flag == TO_CHAR) {
- sprintf(inout, "%0*d", S_FM(suf) ? 0 : 2, tm->tm_hour);
- if (S_THth(suf))
- str_numth(p_inout, inout, S_TH_TYPE(suf));
- if (S_FM(suf) || S_THth(suf))
- return strlen(p_inout) -1;
- else
+ case DCH_AM:
+ case DCH_PM:
+ if (flag == TO_CHAR)
+ {
+ strcpy(inout, (tm->tm_hour > 13 ? PM_STR : AM_STR));
return 1;
-
- } else if (flag == FROM_CHAR) {
- if (S_FM(suf)) {
- sscanf(inout, "%d", &tm->tm_hour);
- return int4len((int4) tm->tm_hour)-1 + SKIP_THth(suf);
- } else {
- sscanf(inout, "%02d", &tm->tm_hour);
- return 1 + SKIP_THth(suf);
+
}
- }
-
- case DCH_MI:
- if (flag == TO_CHAR) {
- sprintf(inout, "%0*d", S_FM(suf) ? 0 : 2, tm->tm_min);
- if (S_THth(suf))
- str_numth(p_inout, inout, S_TH_TYPE(suf));
- if (S_FM(suf) || S_THth(suf))
- return strlen(p_inout)-1;
- else
+ else if (flag == FROM_CHAR)
+ {
+ if (strncmp(inout, PM_STR, 2) == 0 && tm->tm_hour < 13)
+ tm->tm_hour += 12;
return 1;
-
- } else if (flag == FROM_CHAR) {
- if (S_FM(suf)) {
- sscanf(inout, "%d", &tm->tm_min);
- return int4len((int4) tm->tm_min)-1 + SKIP_THth(suf);
- } else {
- sscanf(inout, "%02d", &tm->tm_min);
- return 1 + SKIP_THth(suf);
}
- }
- case DCH_SS:
- if (flag == TO_CHAR) {
- sprintf(inout, "%0*d", S_FM(suf) ? 0 : 2, tm->tm_sec);
- if (S_THth(suf))
- str_numth(p_inout, inout, S_TH_TYPE(suf));
- if (S_FM(suf) || S_THth(suf))
- return strlen(p_inout) -1;
- else
+
+ case DCH_a_m:
+ case DCH_p_m:
+ if (flag == TO_CHAR)
+ {
+ strcpy(inout, (tm->tm_hour > 13 ? p_m_STR : a_m_STR));
+ return 3;
+
+ }
+ else if (flag == FROM_CHAR)
+ {
+ if (strncmp(inout, p_m_STR, 4) == 0 && tm->tm_hour < 13)
+ tm->tm_hour += 12;
+ return 3;
+ }
+
+ case DCH_am:
+ case DCH_pm:
+ if (flag == TO_CHAR)
+ {
+ strcpy(inout, (tm->tm_hour > 13 ? pm_STR : am_STR));
return 1;
-
- } else if (flag == FROM_CHAR) {
- if (S_FM(suf)) {
- sscanf(inout, "%d", &tm->tm_sec);
- return int4len((int4) tm->tm_sec)-1 + SKIP_THth(suf);
- } else {
- sscanf(inout, "%02d", &tm->tm_sec);
- return 1 + SKIP_THth(suf);
+
}
- }
- case DCH_SSSS:
- if (flag == TO_CHAR) {
- sprintf(inout, "%d", tm->tm_hour * 3600 +
- tm->tm_min * 60 +
- tm->tm_sec);
- if (S_THth(suf))
- str_numth(p_inout, inout, S_TH_TYPE(suf));
- return strlen(p_inout)-1;
- } else if (flag == FROM_CHAR)
- elog(ERROR, "to_timestamp(): SSSS is not supported");
- }
- return -1;
+ else if (flag == FROM_CHAR)
+ {
+ if (strncmp(inout, pm_STR, 2) == 0 && tm->tm_hour < 13)
+ tm->tm_hour += 12;
+ return 1;
+ }
+
+ case DCH_HH:
+ case DCH_HH12:
+ if (flag == TO_CHAR)
+ {
+ sprintf(inout, "%0*d", S_FM(suf) ? 0 : 2,
+ tm->tm_hour == 0 ? 12 :
+ tm->tm_hour < 13 ? tm->tm_hour : tm->tm_hour - 12);
+ if (S_THth(suf))
+ str_numth(p_inout, inout, 0);
+ if (S_FM(suf) || S_THth(suf))
+ return strlen(p_inout) - 1;
+ else
+ return 1;
+
+ }
+ else if (flag == FROM_CHAR)
+ {
+ if (S_FM(suf))
+ {
+ sscanf(inout, "%d", &tm->tm_hour);
+ return int4len((int4) tm->tm_hour) - 1 + SKIP_THth(suf);
+ }
+ else
+ {
+ sscanf(inout, "%02d", &tm->tm_hour);
+ return 1 + SKIP_THth(suf);
+ }
+ }
+
+ case DCH_HH24:
+ if (flag == TO_CHAR)
+ {
+ sprintf(inout, "%0*d", S_FM(suf) ? 0 : 2, tm->tm_hour);
+ if (S_THth(suf))
+ str_numth(p_inout, inout, S_TH_TYPE(suf));
+ if (S_FM(suf) || S_THth(suf))
+ return strlen(p_inout) - 1;
+ else
+ return 1;
+
+ }
+ else if (flag == FROM_CHAR)
+ {
+ if (S_FM(suf))
+ {
+ sscanf(inout, "%d", &tm->tm_hour);
+ return int4len((int4) tm->tm_hour) - 1 + SKIP_THth(suf);
+ }
+ else
+ {
+ sscanf(inout, "%02d", &tm->tm_hour);
+ return 1 + SKIP_THth(suf);
+ }
+ }
+
+ case DCH_MI:
+ if (flag == TO_CHAR)
+ {
+ sprintf(inout, "%0*d", S_FM(suf) ? 0 : 2, tm->tm_min);
+ if (S_THth(suf))
+ str_numth(p_inout, inout, S_TH_TYPE(suf));
+ if (S_FM(suf) || S_THth(suf))
+ return strlen(p_inout) - 1;
+ else
+ return 1;
+
+ }
+ else if (flag == FROM_CHAR)
+ {
+ if (S_FM(suf))
+ {
+ sscanf(inout, "%d", &tm->tm_min);
+ return int4len((int4) tm->tm_min) - 1 + SKIP_THth(suf);
+ }
+ else
+ {
+ sscanf(inout, "%02d", &tm->tm_min);
+ return 1 + SKIP_THth(suf);
+ }
+ }
+ case DCH_SS:
+ if (flag == TO_CHAR)
+ {
+ sprintf(inout, "%0*d", S_FM(suf) ? 0 : 2, tm->tm_sec);
+ if (S_THth(suf))
+ str_numth(p_inout, inout, S_TH_TYPE(suf));
+ if (S_FM(suf) || S_THth(suf))
+ return strlen(p_inout) - 1;
+ else
+ return 1;
+
+ }
+ else if (flag == FROM_CHAR)
+ {
+ if (S_FM(suf))
+ {
+ sscanf(inout, "%d", &tm->tm_sec);
+ return int4len((int4) tm->tm_sec) - 1 + SKIP_THth(suf);
+ }
+ else
+ {
+ sscanf(inout, "%02d", &tm->tm_sec);
+ return 1 + SKIP_THth(suf);
+ }
+ }
+ case DCH_SSSS:
+ if (flag == TO_CHAR)
+ {
+ sprintf(inout, "%d", tm->tm_hour * 3600 +
+ tm->tm_min * 60 +
+ tm->tm_sec);
+ if (S_THth(suf))
+ str_numth(p_inout, inout, S_TH_TYPE(suf));
+ return strlen(p_inout) - 1;
+ }
+ else if (flag == FROM_CHAR)
+ elog(ERROR, "to_timestamp(): SSSS is not supported");
+ }
+ return -1;
}
#define CHECK_SEQ_SEARCH(_l, _s) { \
- if (_l <= 0) { \
+ if (_l <= 0) { \
elog(ERROR, "to_timestamp(): bad value for %s", _s); \
} \
}
/* ----------
* Master of DATE for:
- * TO_CHAR - write (inout) formated string
- * FROM_CHAR - scan (inout) string by course of FormatNode
+ * TO_CHAR - write (inout) formated string
+ * FROM_CHAR - scan (inout) string by course of FormatNode
* ----------
*/
-static int
+static int
dch_date(int arg, char *inout, int suf, int flag, FormatNode *node)
{
- char buff[ DCH_CACHE_SIZE ],
- *p_inout;
- int i, len;
+ char buff[DCH_CACHE_SIZE],
+ *p_inout;
+ int i,
+ len;
p_inout = inout;
/* ----------
- * In the FROM-char is not difference between "January" or "JANUARY"
- * or "january", all is before search convert to "first-upper".
+ * In the FROM-char is not difference between "January" or "JANUARY"
+ * or "january", all is before search convert to "first-upper".
* This convention is used for MONTH, MON, DAY, DY
* ----------
*/
- if (flag == FROM_CHAR) {
- if (arg == DCH_MONTH || arg == DCH_Month || arg == DCH_month) {
-
+ if (flag == FROM_CHAR)
+ {
+ if (arg == DCH_MONTH || arg == DCH_Month || arg == DCH_month)
+ {
+
tm->tm_mon = seq_search(inout, months_full, ONE_UPPER, FULL_SIZ, &len);
CHECK_SEQ_SEARCH(len, "MONTH/Month/month");
++tm->tm_mon;
- if (S_FM(suf)) return len-1;
- else return 8;
+ if (S_FM(suf))
+ return len - 1;
+ else
+ return 8;
+
+ }
+ else if (arg == DCH_MON || arg == DCH_Mon || arg == DCH_mon)
+ {
- } else if (arg == DCH_MON || arg == DCH_Mon || arg == DCH_mon) {
-
tm->tm_mon = seq_search(inout, months, ONE_UPPER, MAX_MON_LEN, &len);
CHECK_SEQ_SEARCH(len, "MON/Mon/mon");
++tm->tm_mon;
return 2;
-
- } else if (arg == DCH_DAY || arg == DCH_Day || arg == DCH_day) {
-
- tm->tm_wday = seq_search(inout, days, ONE_UPPER, FULL_SIZ, &len);
+
+ }
+ else if (arg == DCH_DAY || arg == DCH_Day || arg == DCH_day)
+ {
+
+ tm->tm_wday = seq_search(inout, days, ONE_UPPER, FULL_SIZ, &len);
CHECK_SEQ_SEARCH(len, "DAY/Day/day");
- if (S_FM(suf)) return len-1;
- else return 8;
-
- } else if (arg == DCH_DY || arg == DCH_Dy || arg == DCH_dy) {
-
- tm->tm_wday = seq_search(inout, days, ONE_UPPER, MAX_DY_LEN, &len);
+ if (S_FM(suf))
+ return len - 1;
+ else
+ return 8;
+
+ }
+ else if (arg == DCH_DY || arg == DCH_Dy || arg == DCH_dy)
+ {
+
+ tm->tm_wday = seq_search(inout, days, ONE_UPPER, MAX_DY_LEN, &len);
CHECK_SEQ_SEARCH(len, "DY/Dy/dy");
return 2;
-
- }
- }
-
- switch(arg) {
-
- case DCH_A_D:
- case DCH_B_C:
- if (flag == TO_CHAR) {
- strcpy(inout, (tm->tm_year < 0 ? B_C_STR : A_D_STR ));
- return 3;
-
- } else if (flag == FROM_CHAR) {
- if (strncmp(inout, B_C_STR, 4)==0 && tm->tm_year > 0)
- tm->tm_year = -(tm->tm_year);
- if (tm->tm_year < 0)
- tm->tm_year = tm->tm_year+1;
- return 3;
- }
-
- case DCH_AD:
- case DCH_BC:
- if (flag == TO_CHAR) {
- strcpy(inout, (tm->tm_year < 0 ? BC_STR : AD_STR ));
- return 1;
-
- } else if (flag == FROM_CHAR) {
- if (strncmp(inout, BC_STR, 2)==0 && tm->tm_year > 0)
- tm->tm_year = -(tm->tm_year);
- if (tm->tm_year < 0)
- tm->tm_year = tm->tm_year+1;
- return 1;
- }
-
- case DCH_a_d:
- case DCH_b_c:
- if (flag == TO_CHAR) {
- strcpy(inout, (tm->tm_year < 0 ? b_c_STR : a_d_STR ));
- return 3;
-
- } else if (flag == FROM_CHAR) {
- if (strncmp(inout, b_c_STR, 4)==0 && tm->tm_year > 0)
- tm->tm_year = -(tm->tm_year);
- if (tm->tm_year < 0)
- tm->tm_year = tm->tm_year+1;
- return 3;
- }
-
- case DCH_ad:
- case DCH_bc:
- if (flag == TO_CHAR) {
- strcpy(inout, (tm->tm_year < 0 ? bc_STR : ad_STR ));
- return 1;
-
- } else if (flag == FROM_CHAR) {
- if (strncmp(inout, bc_STR, 2)==0 && tm->tm_year > 0)
- tm->tm_year = -(tm->tm_year);
- if (tm->tm_year < 0)
- tm->tm_year = tm->tm_year+1;
- return 1;
- }
-
- case DCH_MONTH:
- strcpy(inout, months_full[ tm->tm_mon - 1]);
- sprintf(inout, "%*s", S_FM(suf) ? 0 : -9, str_toupper(inout));
- if (S_FM(suf))
- return strlen(p_inout)-1;
- else
- return 8;
-
- case DCH_Month:
- sprintf(inout, "%*s", S_FM(suf) ? 0 : -9, months_full[ tm->tm_mon -1 ]);
- if (S_FM(suf))
- return strlen(p_inout)-1;
- else
- return 8;
-
- case DCH_month:
- sprintf(inout, "%*s", S_FM(suf) ? 0 : -9, months_full[ tm->tm_mon -1 ]);
- *inout = tolower(*inout);
- if (S_FM(suf))
- return strlen(p_inout)-1;
- else
- return 8;
-
- case DCH_MON:
- strcpy(inout, months[ tm->tm_mon -1 ]);
- inout = str_toupper(inout);
- return 2;
-
- case DCH_Mon:
- strcpy(inout, months[ tm->tm_mon -1 ]);
- return 2;
-
- case DCH_mon:
- strcpy(inout, months[ tm->tm_mon -1 ]);
- *inout = tolower(*inout);
- return 2;
-
- case DCH_MM:
- if (flag == TO_CHAR) {
- sprintf(inout, "%0*d", S_FM(suf) ? 0 : 2, tm->tm_mon );
- if (S_THth(suf))
- str_numth(p_inout, inout, S_TH_TYPE(suf));
- if (S_FM(suf) || S_THth(suf))
- return strlen(p_inout)-1;
- else
+
+ }
+ }
+
+ switch (arg)
+ {
+
+ case DCH_A_D:
+ case DCH_B_C:
+ if (flag == TO_CHAR)
+ {
+ strcpy(inout, (tm->tm_year < 0 ? B_C_STR : A_D_STR));
+ return 3;
+
+ }
+ else if (flag == FROM_CHAR)
+ {
+ if (strncmp(inout, B_C_STR, 4) == 0 && tm->tm_year > 0)
+ tm->tm_year = -(tm->tm_year);
+ if (tm->tm_year < 0)
+ tm->tm_year = tm->tm_year + 1;
+ return 3;
+ }
+
+ case DCH_AD:
+ case DCH_BC:
+ if (flag == TO_CHAR)
+ {
+ strcpy(inout, (tm->tm_year < 0 ? BC_STR : AD_STR));
return 1;
-
- } else if (flag == FROM_CHAR) {
- if (S_FM(suf)) {
- sscanf(inout, "%d", &tm->tm_mon);
- return int4len((int4) tm->tm_mon)-1 + SKIP_THth(suf);
- } else {
- sscanf(inout, "%02d", &tm->tm_mon);
- return 1 + SKIP_THth(suf);
- }
- }
-
- case DCH_DAY:
- strcpy(inout, days[ tm->tm_wday ]);
- sprintf(inout, "%*s", S_FM(suf) ? 0 : -9, str_toupper(inout));
- if (S_FM(suf))
- return strlen(p_inout)-1;
- else
- return 8;
-
- case DCH_Day:
- sprintf(inout, "%*s", S_FM(suf) ? 0 : -9, days[ tm->tm_wday]);
- if (S_FM(suf))
- return strlen(p_inout)-1;
- else
- return 8;
-
- case DCH_day:
- sprintf(inout, "%*s", S_FM(suf) ? 0 : -9, days[ tm->tm_wday]);
- *inout = tolower(*inout);
- if (S_FM(suf))
- return strlen(p_inout)-1;
- else
- return 8;
-
- case DCH_DY:
- strcpy(inout, days[ tm->tm_wday]);
- inout = str_toupper(inout);
- return 2;
-
- case DCH_Dy:
- strcpy(inout, days[ tm->tm_wday]);
- return 2;
-
- case DCH_dy:
- strcpy(inout, days[ tm->tm_wday]);
- *inout = tolower(*inout);
- return 2;
-
- case DCH_DDD:
- if (flag == TO_CHAR) {
- sprintf(inout, "%0*d", S_FM(suf) ? 0 : 3, tm->tm_yday);
- if (S_THth(suf))
- str_numth(p_inout, inout, S_TH_TYPE(suf));
- if (S_FM(suf) || S_THth(suf))
- return strlen(p_inout)-1;
- else return 2;
-
- } else if (flag == FROM_CHAR) {
- if (S_FM(suf)) {
- sscanf(inout, "%d", &tm->tm_yday);
- return int4len((int4) tm->tm_yday)-1 + SKIP_THth(suf);
- } else {
- sscanf(inout, "%03d", &tm->tm_yday);
- return 2 + SKIP_THth(suf);
- }
- }
-
- case DCH_DD:
- if (flag == TO_CHAR) {
- sprintf(inout, "%0*d", S_FM(suf) ? 0 : 2, tm->tm_mday);
- if (S_THth(suf))
- str_numth(p_inout, inout, S_TH_TYPE(suf));
- if (S_FM(suf) || S_THth(suf))
- return strlen(p_inout)-1;
- else
+
+ }
+ else if (flag == FROM_CHAR)
+ {
+ if (strncmp(inout, BC_STR, 2) == 0 && tm->tm_year > 0)
+ tm->tm_year = -(tm->tm_year);
+ if (tm->tm_year < 0)
+ tm->tm_year = tm->tm_year + 1;
return 1;
-
- } else if (flag == FROM_CHAR) {
- if (S_FM(suf)) {
- sscanf(inout, "%d", &tm->tm_mday);
- return int4len((int4) tm->tm_mday)-1 + SKIP_THth(suf);
- } else {
- sscanf(inout, "%02d", &tm->tm_mday);
- return 1 + SKIP_THth(suf);
- }
- }
- case DCH_D:
- if (flag == TO_CHAR) {
- sprintf(inout, "%d", tm->tm_wday+1);
- if (S_THth(suf)) {
- str_numth(p_inout, inout, S_TH_TYPE(suf));
- return 2;
- }
- return 0;
- } else if (flag == FROM_CHAR) {
- sscanf(inout, "%1d", &tm->tm_wday);
- if(tm->tm_wday) --tm->tm_wday;
- return 0 + SKIP_THth(suf);
- }
-
- case DCH_WW:
- if (flag == TO_CHAR) {
- sprintf(inout, "%0*d", S_FM(suf) ? 0 : 2,
- (tm->tm_yday - tm->tm_wday + 7) / 7);
- if (S_THth(suf))
- str_numth(p_inout, inout, S_TH_TYPE(suf));
- if (S_FM(suf) || S_THth(suf))
- return strlen(p_inout)-1;
- else
+ }
+
+ case DCH_a_d:
+ case DCH_b_c:
+ if (flag == TO_CHAR)
+ {
+ strcpy(inout, (tm->tm_year < 0 ? b_c_STR : a_d_STR));
+ return 3;
+
+ }
+ else if (flag == FROM_CHAR)
+ {
+ if (strncmp(inout, b_c_STR, 4) == 0 && tm->tm_year > 0)
+ tm->tm_year = -(tm->tm_year);
+ if (tm->tm_year < 0)
+ tm->tm_year = tm->tm_year + 1;
+ return 3;
+ }
+
+ case DCH_ad:
+ case DCH_bc:
+ if (flag == TO_CHAR)
+ {
+ strcpy(inout, (tm->tm_year < 0 ? bc_STR : ad_STR));
return 1;
-
- } else if (flag == FROM_CHAR)
- elog(ERROR, "to_datatime(): WW is not supported");
- case DCH_Q:
- if (flag == TO_CHAR) {
- sprintf(inout, "%d", (tm->tm_mon-1)/3+1);
- if (S_THth(suf)) {
- str_numth(p_inout, inout, S_TH_TYPE(suf));
- return 2;
- }
- return 0;
-
- } else if (flag == FROM_CHAR)
- elog(ERROR, "to_datatime(): Q is not supported");
-
- case DCH_CC:
- if (flag == TO_CHAR) {
- i = tm->tm_year/100 +1;
- if (i <= 99 && i >= -99)
- sprintf(inout, "%0*d", S_FM(suf) ? 0 : 2, i);
+
+ }
+ else if (flag == FROM_CHAR)
+ {
+ if (strncmp(inout, bc_STR, 2) == 0 && tm->tm_year > 0)
+ tm->tm_year = -(tm->tm_year);
+ if (tm->tm_year < 0)
+ tm->tm_year = tm->tm_year + 1;
+ return 1;
+ }
+
+ case DCH_MONTH:
+ strcpy(inout, months_full[tm->tm_mon - 1]);
+ sprintf(inout, "%*s", S_FM(suf) ? 0 : -9, str_toupper(inout));
+ if (S_FM(suf))
+ return strlen(p_inout) - 1;
+ else
+ return 8;
+
+ case DCH_Month:
+ sprintf(inout, "%*s", S_FM(suf) ? 0 : -9, months_full[tm->tm_mon - 1]);
+ if (S_FM(suf))
+ return strlen(p_inout) - 1;
else
- sprintf(inout, "%d", i);
- if (S_THth(suf))
- str_numth(p_inout, inout, S_TH_TYPE(suf));
- return strlen(p_inout)-1;
-
- } else if (flag == FROM_CHAR)
- elog(ERROR, "to_datatime(): CC is not supported");
- case DCH_Y_YYY:
- if (flag == TO_CHAR) {
- i= YEAR_ABS(tm->tm_year) / 1000;
- sprintf(inout, "%d,%03d", i, YEAR_ABS(tm->tm_year) -(i*1000));
- if (S_THth(suf))
- str_numth(p_inout, inout, S_TH_TYPE(suf));
- /*
- if (tm->tm_year < 0)
- strcat(inout, BC_STR_ORIG);
- */
- return strlen(p_inout)-1;
-
- } else if (flag == FROM_CHAR) {
- int cc, yy;
- sscanf(inout, "%d,%03d", &cc, &yy);
- tm->tm_year = (cc * 1000) + yy;
-
- if (!S_FM(suf) && tm->tm_year <= 9999 && tm->tm_year >= -9999)
- len = 5;
- else
- len = int4len((int4) tm->tm_year)+1;
- len += SKIP_THth(suf);
- /* AC/BC
- if (is_acdc(inout+len, &len) < 0 && tm->tm_year > 0)
- tm->tm_year = -(tm->tm_year);
- if (tm->tm_year < 0)
- tm->tm_year = tm->tm_year+1;
- */
- return len-1;
- }
-
- case DCH_YYYY :
- if (flag == TO_CHAR) {
- if (tm->tm_year <= 9999 && tm->tm_year >= -9998)
- sprintf(inout, "%0*d", S_FM(suf) ? 0 : 4, YEAR_ABS(tm->tm_year));
+ return 8;
+
+ case DCH_month:
+ sprintf(inout, "%*s", S_FM(suf) ? 0 : -9, months_full[tm->tm_mon - 1]);
+ *inout = tolower(*inout);
+ if (S_FM(suf))
+ return strlen(p_inout) - 1;
else
- sprintf(inout, "%d", YEAR_ABS(tm->tm_year));
- if (S_THth(suf))
- str_numth(p_inout, inout, S_TH_TYPE(suf));
- /*
- if (tm->tm_year < 0)
- strcat(inout, BC_STR_ORIG);
- */
- return strlen(p_inout)-1;
-
- } else if (flag == FROM_CHAR) {
- sscanf(inout, "%d", &tm->tm_year);
- if (!S_FM(suf) && tm->tm_year <= 9999 && tm->tm_year >= -9999)
- len = 4;
- else
- len = int4len((int4) tm->tm_year);
- len += SKIP_THth(suf);
- /* AC/BC
- if (is_acdc(inout+len, &len) < 0 && tm->tm_year > 0)
- tm->tm_year = -(tm->tm_year);
- if (tm->tm_year < 0)
- tm->tm_year = tm->tm_year+1;
- */
- return len-1;
- }
-
- case DCH_YYY:
- if (flag == TO_CHAR) {
- sprintf(buff, "%03d", YEAR_ABS(tm->tm_year));
- i=strlen(buff);
- strcpy(inout, buff+(i-3));
- if (S_THth(suf)) {
- str_numth(p_inout, inout, S_TH_TYPE(suf));
- return 4;
+ return 8;
+
+ case DCH_MON:
+ strcpy(inout, months[tm->tm_mon - 1]);
+ inout = str_toupper(inout);
+ return 2;
+
+ case DCH_Mon:
+ strcpy(inout, months[tm->tm_mon - 1]);
+ return 2;
+
+ case DCH_mon:
+ strcpy(inout, months[tm->tm_mon - 1]);
+ *inout = tolower(*inout);
+ return 2;
+
+ case DCH_MM:
+ if (flag == TO_CHAR)
+ {
+ sprintf(inout, "%0*d", S_FM(suf) ? 0 : 2, tm->tm_mon);
+ if (S_THth(suf))
+ str_numth(p_inout, inout, S_TH_TYPE(suf));
+ if (S_FM(suf) || S_THth(suf))
+ return strlen(p_inout) - 1;
+ else
+ return 1;
+
}
+ else if (flag == FROM_CHAR)
+ {
+ if (S_FM(suf))
+ {
+ sscanf(inout, "%d", &tm->tm_mon);
+ return int4len((int4) tm->tm_mon) - 1 + SKIP_THth(suf);
+ }
+ else
+ {
+ sscanf(inout, "%02d", &tm->tm_mon);
+ return 1 + SKIP_THth(suf);
+ }
+ }
+
+ case DCH_DAY:
+ strcpy(inout, days[tm->tm_wday]);
+ sprintf(inout, "%*s", S_FM(suf) ? 0 : -9, str_toupper(inout));
+ if (S_FM(suf))
+ return strlen(p_inout) - 1;
+ else
+ return 8;
+
+ case DCH_Day:
+ sprintf(inout, "%*s", S_FM(suf) ? 0 : -9, days[tm->tm_wday]);
+ if (S_FM(suf))
+ return strlen(p_inout) - 1;
+ else
+ return 8;
+
+ case DCH_day:
+ sprintf(inout, "%*s", S_FM(suf) ? 0 : -9, days[tm->tm_wday]);
+ *inout = tolower(*inout);
+ if (S_FM(suf))
+ return strlen(p_inout) - 1;
+ else
+ return 8;
+
+ case DCH_DY:
+ strcpy(inout, days[tm->tm_wday]);
+ inout = str_toupper(inout);
return 2;
-
- } else if (flag == FROM_CHAR) {
- int yy;
- sscanf(inout, "%03d", &yy);
- tm->tm_year = (tm->tm_year/1000)*1000 +yy;
- return 2 + SKIP_THth(suf);
- }
-
- case DCH_YY:
- if (flag == TO_CHAR) {
- sprintf(buff, "%02d", YEAR_ABS(tm->tm_year));
- i=strlen(buff);
- strcpy(inout, buff+(i-2));
- if (S_THth(suf)) {
- str_numth(p_inout, inout, S_TH_TYPE(suf));
- return 3;
- }
- return 1;
-
- } else if (flag == FROM_CHAR) {
- int yy;
- sscanf(inout, "%02d", &yy);
- tm->tm_year = (tm->tm_year/100)*100 +yy;
- return 1 + SKIP_THth(suf);
- }
-
- case DCH_Y:
- if (flag == TO_CHAR) {
- sprintf(buff, "%1d", YEAR_ABS(tm->tm_year));
- i=strlen(buff);
- strcpy(inout, buff+(i-1));
- if (S_THth(suf)) {
- str_numth(p_inout, inout, S_TH_TYPE(suf));
- return 2;
- }
- return 0;
-
- } else if (flag == FROM_CHAR) {
- int yy;
- sscanf(inout, "%1d", &yy);
- tm->tm_year = (tm->tm_year/10)*10 +yy;
- return 0 + SKIP_THth(suf);
- }
-
- case DCH_RM:
- if (flag == TO_CHAR) {
- sprintf(inout, "%*s", S_FM(suf) ? 0 : -4,
- rm_months_upper[ 12 - tm->tm_mon ]);
- if (S_FM(suf))
- return strlen(p_inout)-1;
- else
- return 3;
-
- } else if (flag == FROM_CHAR) {
- tm->tm_mon = 11-seq_search(inout, rm_months_upper, ALL_UPPER, FULL_SIZ, &len);
- CHECK_SEQ_SEARCH(len, "RM");
- ++tm->tm_mon;
- if (S_FM(suf))
- return len-1;
- else
- return 3;
- }
-
- case DCH_rm:
- if (flag == TO_CHAR) {
- sprintf(inout, "%*s", S_FM(suf) ? 0 : -4,
- rm_months_lower[ 12 - tm->tm_mon ]);
- if (S_FM(suf))
- return strlen(p_inout)-1;
- else
- return 3;
-
- } else if (flag == FROM_CHAR) {
- tm->tm_mon = 11-seq_search(inout, rm_months_lower, ALL_UPPER, FULL_SIZ, &len);
- CHECK_SEQ_SEARCH(len, "rm");
- ++tm->tm_mon;
- if (S_FM(suf))
- return len-1;
- else
- return 3;
- }
-
- case DCH_W:
- if (flag == TO_CHAR) {
- sprintf(inout, "%d", (tm->tm_mday - tm->tm_wday +7) / 7 );
- if (S_THth(suf)) {
- str_numth(p_inout, inout, S_TH_TYPE(suf));
+
+ case DCH_Dy:
+ strcpy(inout, days[tm->tm_wday]);
+ return 2;
+
+ case DCH_dy:
+ strcpy(inout, days[tm->tm_wday]);
+ *inout = tolower(*inout);
+ return 2;
+
+ case DCH_DDD:
+ if (flag == TO_CHAR)
+ {
+ sprintf(inout, "%0*d", S_FM(suf) ? 0 : 3, tm->tm_yday);
+ if (S_THth(suf))
+ str_numth(p_inout, inout, S_TH_TYPE(suf));
+ if (S_FM(suf) || S_THth(suf))
+ return strlen(p_inout) - 1;
+ else
+ return 2;
+
+ }
+ else if (flag == FROM_CHAR)
+ {
+ if (S_FM(suf))
+ {
+ sscanf(inout, "%d", &tm->tm_yday);
+ return int4len((int4) tm->tm_yday) - 1 + SKIP_THth(suf);
+ }
+ else
+ {
+ sscanf(inout, "%03d", &tm->tm_yday);
+ return 2 + SKIP_THth(suf);
+ }
+ }
+
+ case DCH_DD:
+ if (flag == TO_CHAR)
+ {
+ sprintf(inout, "%0*d", S_FM(suf) ? 0 : 2, tm->tm_mday);
+ if (S_THth(suf))
+ str_numth(p_inout, inout, S_TH_TYPE(suf));
+ if (S_FM(suf) || S_THth(suf))
+ return strlen(p_inout) - 1;
+ else
+ return 1;
+
+ }
+ else if (flag == FROM_CHAR)
+ {
+ if (S_FM(suf))
+ {
+ sscanf(inout, "%d", &tm->tm_mday);
+ return int4len((int4) tm->tm_mday) - 1 + SKIP_THth(suf);
+ }
+ else
+ {
+ sscanf(inout, "%02d", &tm->tm_mday);
+ return 1 + SKIP_THth(suf);
+ }
+ }
+ case DCH_D:
+ if (flag == TO_CHAR)
+ {
+ sprintf(inout, "%d", tm->tm_wday + 1);
+ if (S_THth(suf))
+ {
+ str_numth(p_inout, inout, S_TH_TYPE(suf));
+ return 2;
+ }
+ return 0;
+ }
+ else if (flag == FROM_CHAR)
+ {
+ sscanf(inout, "%1d", &tm->tm_wday);
+ if (tm->tm_wday)
+ --tm->tm_wday;
+ return 0 + SKIP_THth(suf);
+ }
+
+ case DCH_WW:
+ if (flag == TO_CHAR)
+ {
+ sprintf(inout, "%0*d", S_FM(suf) ? 0 : 2,
+ (tm->tm_yday - tm->tm_wday + 7) / 7);
+ if (S_THth(suf))
+ str_numth(p_inout, inout, S_TH_TYPE(suf));
+ if (S_FM(suf) || S_THth(suf))
+ return strlen(p_inout) - 1;
+ else
+ return 1;
+
+ }
+ else if (flag == FROM_CHAR)
+ elog(ERROR, "to_datatime(): WW is not supported");
+ case DCH_Q:
+ if (flag == TO_CHAR)
+ {
+ sprintf(inout, "%d", (tm->tm_mon - 1) / 3 + 1);
+ if (S_THth(suf))
+ {
+ str_numth(p_inout, inout, S_TH_TYPE(suf));
+ return 2;
+ }
+ return 0;
+
+ }
+ else if (flag == FROM_CHAR)
+ elog(ERROR, "to_datatime(): Q is not supported");
+
+ case DCH_CC:
+ if (flag == TO_CHAR)
+ {
+ i = tm->tm_year / 100 + 1;
+ if (i <= 99 && i >= -99)
+ sprintf(inout, "%0*d", S_FM(suf) ? 0 : 2, i);
+ else
+ sprintf(inout, "%d", i);
+ if (S_THth(suf))
+ str_numth(p_inout, inout, S_TH_TYPE(suf));
+ return strlen(p_inout) - 1;
+
+ }
+ else if (flag == FROM_CHAR)
+ elog(ERROR, "to_datatime(): CC is not supported");
+ case DCH_Y_YYY:
+ if (flag == TO_CHAR)
+ {
+ i = YEAR_ABS(tm->tm_year) / 1000;
+ sprintf(inout, "%d,%03d", i, YEAR_ABS(tm->tm_year) - (i * 1000));
+ if (S_THth(suf))
+ str_numth(p_inout, inout, S_TH_TYPE(suf));
+
+ /*
+ * if (tm->tm_year < 0) strcat(inout, BC_STR_ORIG);
+ */
+ return strlen(p_inout) - 1;
+
+ }
+ else if (flag == FROM_CHAR)
+ {
+ int cc,
+ yy;
+
+ sscanf(inout, "%d,%03d", &cc, &yy);
+ tm->tm_year = (cc * 1000) + yy;
+
+ if (!S_FM(suf) && tm->tm_year <= 9999 && tm->tm_year >= -9999)
+ len = 5;
+ else
+ len = int4len((int4) tm->tm_year) + 1;
+ len += SKIP_THth(suf);
+
+ /*
+ * AC/BC if (is_acdc(inout+len, &len) < 0 && tm->tm_year >
+ * 0) tm->tm_year = -(tm->tm_year); if (tm->tm_year < 0)
+ * tm->tm_year = tm->tm_year+1;
+ */
+ return len - 1;
+ }
+
+ case DCH_YYYY:
+ if (flag == TO_CHAR)
+ {
+ if (tm->tm_year <= 9999 && tm->tm_year >= -9998)
+ sprintf(inout, "%0*d", S_FM(suf) ? 0 : 4, YEAR_ABS(tm->tm_year));
+ else
+ sprintf(inout, "%d", YEAR_ABS(tm->tm_year));
+ if (S_THth(suf))
+ str_numth(p_inout, inout, S_TH_TYPE(suf));
+
+ /*
+ * if (tm->tm_year < 0) strcat(inout, BC_STR_ORIG);
+ */
+ return strlen(p_inout) - 1;
+
+ }
+ else if (flag == FROM_CHAR)
+ {
+ sscanf(inout, "%d", &tm->tm_year);
+ if (!S_FM(suf) && tm->tm_year <= 9999 && tm->tm_year >= -9999)
+ len = 4;
+ else
+ len = int4len((int4) tm->tm_year);
+ len += SKIP_THth(suf);
+
+ /*
+ * AC/BC if (is_acdc(inout+len, &len) < 0 && tm->tm_year >
+ * 0) tm->tm_year = -(tm->tm_year); if (tm->tm_year < 0)
+ * tm->tm_year = tm->tm_year+1;
+ */
+ return len - 1;
+ }
+
+ case DCH_YYY:
+ if (flag == TO_CHAR)
+ {
+ sprintf(buff, "%03d", YEAR_ABS(tm->tm_year));
+ i = strlen(buff);
+ strcpy(inout, buff + (i - 3));
+ if (S_THth(suf))
+ {
+ str_numth(p_inout, inout, S_TH_TYPE(suf));
+ return 4;
+ }
return 2;
+
+ }
+ else if (flag == FROM_CHAR)
+ {
+ int yy;
+
+ sscanf(inout, "%03d", &yy);
+ tm->tm_year = (tm->tm_year / 1000) * 1000 + yy;
+ return 2 + SKIP_THth(suf);
+ }
+
+ case DCH_YY:
+ if (flag == TO_CHAR)
+ {
+ sprintf(buff, "%02d", YEAR_ABS(tm->tm_year));
+ i = strlen(buff);
+ strcpy(inout, buff + (i - 2));
+ if (S_THth(suf))
+ {
+ str_numth(p_inout, inout, S_TH_TYPE(suf));
+ return 3;
+ }
+ return 1;
+
+ }
+ else if (flag == FROM_CHAR)
+ {
+ int yy;
+
+ sscanf(inout, "%02d", &yy);
+ tm->tm_year = (tm->tm_year / 100) * 100 + yy;
+ return 1 + SKIP_THth(suf);
+ }
+
+ case DCH_Y:
+ if (flag == TO_CHAR)
+ {
+ sprintf(buff, "%1d", YEAR_ABS(tm->tm_year));
+ i = strlen(buff);
+ strcpy(inout, buff + (i - 1));
+ if (S_THth(suf))
+ {
+ str_numth(p_inout, inout, S_TH_TYPE(suf));
+ return 2;
+ }
+ return 0;
+
+ }
+ else if (flag == FROM_CHAR)
+ {
+ int yy;
+
+ sscanf(inout, "%1d", &yy);
+ tm->tm_year = (tm->tm_year / 10) * 10 + yy;
+ return 0 + SKIP_THth(suf);
}
- return 0;
-
- } else if (flag == FROM_CHAR)
- elog(ERROR, "to_datatime(): W is not supported");
-
- case DCH_J:
- if (flag == TO_CHAR) {
- sprintf(inout, "%d", date2j(tm->tm_year, tm->tm_mon, tm->tm_mday));
- if (S_THth(suf))
- str_numth(p_inout, inout, S_TH_TYPE(suf));
- return strlen(p_inout)-1;
- } else if (flag == FROM_CHAR)
- elog(ERROR, "to_datatime(): J is not supported");
- }
- return -1;
+
+ case DCH_RM:
+ if (flag == TO_CHAR)
+ {
+ sprintf(inout, "%*s", S_FM(suf) ? 0 : -4,
+ rm_months_upper[12 - tm->tm_mon]);
+ if (S_FM(suf))
+ return strlen(p_inout) - 1;
+ else
+ return 3;
+
+ }
+ else if (flag == FROM_CHAR)
+ {
+ tm->tm_mon = 11 - seq_search(inout, rm_months_upper, ALL_UPPER, FULL_SIZ, &len);
+ CHECK_SEQ_SEARCH(len, "RM");
+ ++tm->tm_mon;
+ if (S_FM(suf))
+ return len - 1;
+ else
+ return 3;
+ }
+
+ case DCH_rm:
+ if (flag == TO_CHAR)
+ {
+ sprintf(inout, "%*s", S_FM(suf) ? 0 : -4,
+ rm_months_lower[12 - tm->tm_mon]);
+ if (S_FM(suf))
+ return strlen(p_inout) - 1;
+ else
+ return 3;
+
+ }
+ else if (flag == FROM_CHAR)
+ {
+ tm->tm_mon = 11 - seq_search(inout, rm_months_lower, ALL_UPPER, FULL_SIZ, &len);
+ CHECK_SEQ_SEARCH(len, "rm");
+ ++tm->tm_mon;
+ if (S_FM(suf))
+ return len - 1;
+ else
+ return 3;
+ }
+
+ case DCH_W:
+ if (flag == TO_CHAR)
+ {
+ sprintf(inout, "%d", (tm->tm_mday - tm->tm_wday + 7) / 7);
+ if (S_THth(suf))
+ {
+ str_numth(p_inout, inout, S_TH_TYPE(suf));
+ return 2;
+ }
+ return 0;
+
+ }
+ else if (flag == FROM_CHAR)
+ elog(ERROR, "to_datatime(): W is not supported");
+
+ case DCH_J:
+ if (flag == TO_CHAR)
+ {
+ sprintf(inout, "%d", date2j(tm->tm_year, tm->tm_mon, tm->tm_mday));
+ if (S_THth(suf))
+ str_numth(p_inout, inout, S_TH_TYPE(suf));
+ return strlen(p_inout) - 1;
+ }
+ else if (flag == FROM_CHAR)
+ elog(ERROR, "to_datatime(): J is not supported");
+ }
+ return -1;
}
static DCHCacheEntry *
-DCH_cache_getnew( char *str )
+DCH_cache_getnew(char *str)
{
- DCHCacheEntry *ent = NULL;
-
+ DCHCacheEntry *ent = NULL;
+
/* counter overload check - paranoa? */
- if (DCHCounter + DCH_CACHE_FIELDS >= MAX_INT32) {
+ if (DCHCounter + DCH_CACHE_FIELDS >= MAX_INT32)
+ {
DCHCounter = 0;
- for(ent = DCHCache; ent <= (DCHCache + DCH_CACHE_FIELDS); ent++)
- ent->age = (++DCHCounter);
+ for (ent = DCHCache; ent <= (DCHCache + DCH_CACHE_FIELDS); ent++)
+ ent->age = (++DCHCounter);
}
-
+
/* ----------
* Cache is full - needs remove any older entry
* ----------
*/
- if (n_DCHCache > DCH_CACHE_FIELDS) {
+ if (n_DCHCache > DCH_CACHE_FIELDS)
+ {
+
+ DCHCacheEntry *old = DCHCache + 0;
- DCHCacheEntry *old = DCHCache+0;
#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, "Cache is full (%d)", n_DCHCache);
-#endif
- for(ent = DCHCache; ent <= (DCHCache + DCH_CACHE_FIELDS); ent++) {
+#endif
+ for (ent = DCHCache; ent <= (DCHCache + DCH_CACHE_FIELDS); ent++)
+ {
if (ent->age < old->age)
old = ent;
- }
+ }
#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, "OLD: '%s' AGE: %d", old->str, old->age);
-#endif
- strcpy(old->str, str); /* check str size before this func. */
+#endif
+ strcpy(old->str, str); /* check str size before this func. */
/* old->format fill parser */
old->age = (++DCHCounter);
return old;
-
- } else {
-#ifdef DEBUG_TO_FROM_CHAR
+
+ }
+ else
+ {
+#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, "NEW (%d)", n_DCHCache);
-#endif
+#endif
ent = DCHCache + n_DCHCache;
- strcpy(ent->str, str); /* check str size before this func. */
+ strcpy(ent->str, str); /* check str size before this func. */
/* ent->format fill parser */
ent->age = (++DCHCounter);
++n_DCHCache;
return ent;
}
-
+
return (DCHCacheEntry *) NULL; /* never */
}
static DCHCacheEntry *
-DCH_cache_search( char *str )
+DCH_cache_search(char *str)
{
- int i = 0;
- DCHCacheEntry *ent;
+ int i = 0;
+ DCHCacheEntry *ent;
/* counter overload check - paranoa? */
- if (DCHCounter + DCH_CACHE_FIELDS >= MAX_INT32) {
+ if (DCHCounter + DCH_CACHE_FIELDS >= MAX_INT32)
+ {
DCHCounter = 0;
- for(ent = DCHCache; ent <= (DCHCache + DCH_CACHE_FIELDS); ent++)
- ent->age = (++DCHCounter);
+ for (ent = DCHCache; ent <= (DCHCache + DCH_CACHE_FIELDS); ent++)
+ ent->age = (++DCHCounter);
}
- for(ent = DCHCache; ent <= (DCHCache + DCH_CACHE_FIELDS); ent++) {
+ for (ent = DCHCache; ent <= (DCHCache + DCH_CACHE_FIELDS); ent++)
+ {
if (i == n_DCHCache)
break;
- if (strcmp(ent->str, str) == 0) {
+ if (strcmp(ent->str, str) == 0)
+ {
ent->age = (++DCHCounter);
return ent;
- }
- i++;
+ }
+ i++;
}
-
+
return (DCHCacheEntry *) NULL;
}
@@ -2159,103 +2375,119 @@ DCH_cache_search( char *str )
text *
timestamp_to_char(Timestamp *dt, text *fmt)
{
- text *result, *result_tmp;
- FormatNode *format;
- char *str;
- double fsec;
- char *tzn;
- int len=0, tz, flag = 0, x=0;
+ text *result,
+ *result_tmp;
+ FormatNode *format;
+ char *str;
+ double fsec;
+ char *tzn;
+ int len = 0,
+ tz,
+ flag = 0,
+ x = 0;
if ((!PointerIsValid(dt)) || (!PointerIsValid(fmt)))
return NULL;
-
- len = VARSIZE(fmt) - VARHDRSZ;
-
+
+ len = VARSIZE(fmt) - VARHDRSZ;
+
if ((!len) || (TIMESTAMP_NOT_FINITE(*dt)))
return textin("");
- tm->tm_sec =0; tm->tm_year =0;
- tm->tm_min =0; tm->tm_wday =0;
- tm->tm_hour =0; tm->tm_yday =0;
- tm->tm_mday =1; tm->tm_isdst =0;
- tm->tm_mon =1;
-
- if (TIMESTAMP_IS_EPOCH(*dt)) {
- x = timestamp2tm(SetTimestamp(*dt), NULL, tm, &fsec, NULL);
-
- } else if (TIMESTAMP_IS_CURRENT(*dt)) {
- x = timestamp2tm(SetTimestamp(*dt), &tz, tm, &fsec, &tzn);
-
- } else {
- x = timestamp2tm(*dt, &tz, tm, &fsec, &tzn);
- }
-
- if (x!=0)
- elog(ERROR, "to_char(): Unable to convert timestamp to tm");
-
- tm->tm_wday = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) + 1) % 7;
- tm->tm_yday = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - date2j(tm->tm_year, 1,1) +1;
+ tm->tm_sec = 0;
+ tm->tm_year = 0;
+ tm->tm_min = 0;
+ tm->tm_wday = 0;
+ tm->tm_hour = 0;
+ tm->tm_yday = 0;
+ tm->tm_mday = 1;
+ tm->tm_isdst = 0;
+ tm->tm_mon = 1;
+
+ if (TIMESTAMP_IS_EPOCH(*dt))
+ {
+ x = timestamp2tm(SetTimestamp(*dt), NULL, tm, &fsec, NULL);
+
+ }
+ else if (TIMESTAMP_IS_CURRENT(*dt))
+ {
+ x = timestamp2tm(SetTimestamp(*dt), &tz, tm, &fsec, &tzn);
+
+ }
+ else
+ x = timestamp2tm(*dt, &tz, tm, &fsec, &tzn);
+
+ if (x != 0)
+ elog(ERROR, "to_char(): Unable to convert timestamp to tm");
+
+ tm->tm_wday = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) + 1) % 7;
+ tm->tm_yday = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - date2j(tm->tm_year, 1, 1) + 1;
/* ----------
* Convert VARDATA() to string
* ----------
*/
- str = (char *) palloc(len + 1);
+ str = (char *) palloc(len + 1);
memcpy(str, VARDATA(fmt), len);
- *(str + len) = '\0';
+ *(str + len) = '\0';
/* ----------
* Allocate result
* ----------
*/
- result = (text *) palloc( (len * DCH_MAX_ITEM_SIZ) + 1 + VARHDRSZ);
+ result = (text *) palloc((len * DCH_MAX_ITEM_SIZ) + 1 + VARHDRSZ);
/* ----------
- * Allocate new memory if format picture is bigger than static cache
+ * Allocate new memory if format picture is bigger than static cache
* and not use cache (call parser always) - flag=1 show this variant
* ----------
- */
- if ( len > DCH_CACHE_SIZE ) {
-
+ */
+ if (len > DCH_CACHE_SIZE)
+ {
+
format = (FormatNode *) palloc((len + 1) * sizeof(FormatNode));
- flag = 1;
+ flag = 1;
- parse_format(format, str, DCH_keywords,
- DCH_suff, DCH_index, DCH_TYPE, NULL);
-
- (format + len)->type = NODE_TYPE_END; /* Paranoa? */
-
- } else {
+ parse_format(format, str, DCH_keywords,
+ DCH_suff, DCH_index, DCH_TYPE, NULL);
+
+ (format + len)->type = NODE_TYPE_END; /* Paranoa? */
+
+ }
+ else
+ {
/* ----------
* Use cache buffers
* ----------
*/
- DCHCacheEntry *ent;
+ DCHCacheEntry *ent;
+
flag = 0;
- if ((ent = DCH_cache_search(str)) == NULL) {
-
+ if ((ent = DCH_cache_search(str)) == NULL)
+ {
+
ent = DCH_cache_getnew(str);
-
+
/* ----------
* Not in the cache, must run parser and save a new
- * format-picture to the cache.
+ * format-picture to the cache.
* ----------
- */
- parse_format(ent->format, str, DCH_keywords,
- DCH_suff, DCH_index, DCH_TYPE, NULL);
-
- (ent->format + len)->type = NODE_TYPE_END; /* Paranoa? */
-
-#ifdef DEBUG_TO_FROM_CHAR
+ */
+ parse_format(ent->format, str, DCH_keywords,
+ DCH_suff, DCH_index, DCH_TYPE, NULL);
+
+ (ent->format + len)->type = NODE_TYPE_END; /* Paranoa? */
+
+#ifdef DEBUG_TO_FROM_CHAR
/* dump_node(ent->format, len); */
/* dump_index(DCH_keywords, DCH_index); */
-#endif
- }
- format = ent->format;
+#endif
+ }
+ format = ent->format;
}
-
+
DCH_processor(format, VARDATA(result), TO_CHAR);
if (flag)
@@ -2267,13 +2499,13 @@ timestamp_to_char(Timestamp *dt, text *fmt)
* for result is allocated max memory, which current format-picture
* needs, now it must be re-allocate to result real size
* ----------
- */
- len = strlen(VARDATA(result));
- result_tmp = result;
- result = (text *) palloc( len + 1 + VARHDRSZ);
-
- strcpy( VARDATA(result), VARDATA(result_tmp));
- VARSIZE(result) = len + VARHDRSZ;
+ */
+ len = strlen(VARDATA(result));
+ result_tmp = result;
+ result = (text *) palloc(len + 1 + VARHDRSZ);
+
+ strcpy(VARDATA(result), VARDATA(result_tmp));
+ VARSIZE(result) = len + VARHDRSZ;
pfree(result_tmp);
return result;
@@ -2283,113 +2515,124 @@ timestamp_to_char(Timestamp *dt, text *fmt)
/* ---------------------
* TO_TIMESTAMP()
*
- * Make Timestamp from date_str which is formated at argument 'fmt'
+ * Make Timestamp from date_str which is formated at argument 'fmt'
* ( to_timestamp is reverse to_char() )
* ---------------------
*/
-Timestamp *
+Timestamp *
to_timestamp(text *date_str, text *fmt)
{
- FormatNode *format;
- int flag=0;
- Timestamp *result;
- char *str;
- int len=0,
- fsec=0,
- tz=0;
+ FormatNode *format;
+ int flag = 0;
+ Timestamp *result;
+ char *str;
+ int len = 0,
+ fsec = 0,
+ tz = 0;
if ((!PointerIsValid(date_str)) || (!PointerIsValid(fmt)))
return NULL;
-
- tm->tm_sec =0; tm->tm_year =0;
- tm->tm_min =0; tm->tm_wday =0;
- tm->tm_hour =0; tm->tm_yday =0;
- tm->tm_mday =1; tm->tm_isdst =0;
- tm->tm_mon =1;
-
+
+ tm->tm_sec = 0;
+ tm->tm_year = 0;
+ tm->tm_min = 0;
+ tm->tm_wday = 0;
+ tm->tm_hour = 0;
+ tm->tm_yday = 0;
+ tm->tm_mday = 1;
+ tm->tm_isdst = 0;
+ tm->tm_mon = 1;
+
result = palloc(sizeof(Timestamp));
-
- len = VARSIZE(fmt) - VARHDRSZ;
-
- if (len) {
-
+
+ len = VARSIZE(fmt) - VARHDRSZ;
+
+ if (len)
+ {
+
/* ----------
* Convert VARDATA() to string
* ----------
*/
- str = (char *) palloc(len + 1);
+ str = (char *) palloc(len + 1);
memcpy(str, VARDATA(fmt), len);
- *(str + len) = '\0';
+ *(str + len) = '\0';
/* ----------
- * Allocate new memory if format picture is bigger than static cache
+ * Allocate new memory if format picture is bigger than static cache
* and not use cache (call parser always) - flag=1 show this variant
* ----------
- */
- if ( len > DCH_CACHE_SIZE ) {
+ */
+ if (len > DCH_CACHE_SIZE)
+ {
format = (FormatNode *) palloc((len + 1) * sizeof(FormatNode));
- flag = 1;
+ flag = 1;
- parse_format(format, str, DCH_keywords,
- DCH_suff, DCH_index, DCH_TYPE, NULL);
-
- (format + len)->type = NODE_TYPE_END; /* Paranoa? */
- } else {
+ parse_format(format, str, DCH_keywords,
+ DCH_suff, DCH_index, DCH_TYPE, NULL);
+
+ (format + len)->type = NODE_TYPE_END; /* Paranoa? */
+ }
+ else
+ {
/* ----------
* Use cache buffers
* ----------
*/
- DCHCacheEntry *ent;
+ DCHCacheEntry *ent;
+
flag = 0;
- if ((ent = DCH_cache_search(str)) == NULL) {
-
+ if ((ent = DCH_cache_search(str)) == NULL)
+ {
+
ent = DCH_cache_getnew(str);
-
+
/* ----------
* Not in the cache, must run parser and save a new
- * format-picture to the cache.
+ * format-picture to the cache.
* ----------
- */
- parse_format(ent->format, str, DCH_keywords,
- DCH_suff, DCH_index, DCH_TYPE, NULL);
-
- (ent->format + len)->type = NODE_TYPE_END; /* Paranoa? */
-#ifdef DEBUG_TO_FROM_CHAR
+ */
+ parse_format(ent->format, str, DCH_keywords,
+ DCH_suff, DCH_index, DCH_TYPE, NULL);
+
+ (ent->format + len)->type = NODE_TYPE_END; /* Paranoa? */
+#ifdef DEBUG_TO_FROM_CHAR
/* dump_node(ent->format, len); */
/* dump_index(DCH_keywords, DCH_index); */
-#endif
- }
- format = ent->format;
- }
-
+#endif
+ }
+ format = ent->format;
+ }
+
/* ----------
- * Call action for each node in FormatNode tree
+ * Call action for each node in FormatNode tree
* ----------
- */
-#ifdef DEBUG_TO_FROM_CHAR
+ */
+#ifdef DEBUG_TO_FROM_CHAR
/* dump_node(format, len); */
#endif
- VARDATA(date_str)[ VARSIZE(date_str) - VARHDRSZ ] = '\0';
- DCH_processor(format, VARDATA(date_str), FROM_CHAR);
+ VARDATA(date_str)[VARSIZE(date_str) - VARHDRSZ] = '\0';
+ DCH_processor(format, VARDATA(date_str), FROM_CHAR);
pfree(str);
-
+
if (flag)
pfree(format);
}
#ifdef DEBUG_TO_FROM_CHAR
- NOTICE_TM;
+ NOTICE_TM;
#endif
- if (IS_VALID_UTIME(tm->tm_year, tm->tm_mon, tm->tm_mday)) {
+ if (IS_VALID_UTIME(tm->tm_year, tm->tm_mon, tm->tm_mday))
+ {
#ifdef USE_POSIX_TIME
tm->tm_isdst = -1;
tm->tm_year -= 1900;
- tm->tm_mon -= 1;
+ tm->tm_mon -= 1;
#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, "TO-FROM_CHAR: Call mktime()");
@@ -2413,35 +2656,37 @@ to_timestamp(text *date_str, text *fmt)
#error USE_POSIX_TIME is defined but neither HAVE_TM_ZONE or HAVE_INT_TIMEZONE are defined
#endif
-#else /* !USE_POSIX_TIME */
+#else /* !USE_POSIX_TIME */
tz = CTimeZone;
#endif
- } else {
+ }
+ else
+ {
tm->tm_isdst = 0;
tz = 0;
}
#ifdef DEBUG_TO_FROM_CHAR
- NOTICE_TM;
+ NOTICE_TM;
#endif
if (tm2timestamp(tm, fsec, &tz, result) != 0)
- elog(ERROR, "to_datatime(): can't convert 'tm' to timestamp.");
-
+ elog(ERROR, "to_datatime(): can't convert 'tm' to timestamp.");
+
return result;
}
/* ----------
* TO_DATE
- * Make Date from date_str which is formated at argument 'fmt'
+ * Make Date from date_str which is formated at argument 'fmt'
* ----------
*/
-DateADT
+DateADT
to_date(text *date_str, text *fmt)
{
- return timestamp_date( to_timestamp(date_str, fmt) );
+ return timestamp_date(to_timestamp(date_str, fmt));
}
/**********************************************************************
- * the NUMBER version part
+ * the NUMBER version part
*********************************************************************/
@@ -2449,16 +2694,16 @@ static char *
fill_str(char *str, int c, int max)
{
memset(str, c, max);
- *(str+max+1) = '\0';
- return str;
+ *(str + max + 1) = '\0';
+ return str;
}
#define zeroize_NUM(_n) { \
- (_n)->flag = 0; \
+ (_n)->flag = 0; \
(_n)->lsign = 0; \
(_n)->pre = 0; \
(_n)->post = 0; \
- (_n)->pre_lsign_num = 0; \
+ (_n)->pre_lsign_num = 0; \
(_n)->need_locale = 0; \
(_n)->multi = 0; \
(_n)->zero_start = 0; \
@@ -2466,83 +2711,91 @@ fill_str(char *str, int c, int max)
}
static NUMCacheEntry *
-NUM_cache_getnew( char *str )
+NUM_cache_getnew(char *str)
{
- NUMCacheEntry *ent = NULL;
-
+ NUMCacheEntry *ent = NULL;
+
/* counter overload check - paranoa? */
- if (NUMCounter + NUM_CACHE_FIELDS >= MAX_INT32) {
+ if (NUMCounter + NUM_CACHE_FIELDS >= MAX_INT32)
+ {
NUMCounter = 0;
- for(ent = NUMCache; ent <= (NUMCache + NUM_CACHE_FIELDS); ent++)
- ent->age = (++NUMCounter);
+ for (ent = NUMCache; ent <= (NUMCache + NUM_CACHE_FIELDS); ent++)
+ ent->age = (++NUMCounter);
}
-
+
/* ----------
* Cache is full - needs remove any older entry
* ----------
*/
- if (n_NUMCache > NUM_CACHE_FIELDS) {
+ if (n_NUMCache > NUM_CACHE_FIELDS)
+ {
+
+ NUMCacheEntry *old = NUMCache + 0;
- NUMCacheEntry *old = NUMCache+0;
-
#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, "Cache is full (%d)", n_NUMCache);
#endif
-
- for(ent = NUMCache; ent <= (NUMCache + NUM_CACHE_FIELDS); ent++) {
+
+ for (ent = NUMCache; ent <= (NUMCache + NUM_CACHE_FIELDS); ent++)
+ {
if (ent->age < old->age)
old = ent;
- }
-#ifdef DEBUG_TO_FROM_CHAR
+ }
+#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, "OLD: '%s' AGE: %d", old->str, old->age);
-#endif
- strcpy(old->str, str); /* check str size before this func. */
+#endif
+ strcpy(old->str, str); /* check str size before this func. */
/* old->format fill parser */
old->age = (++NUMCounter);
-
+
ent = old;
-
- } else {
-#ifdef DEBUG_TO_FROM_CHAR
+
+ }
+ else
+ {
+#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, "NEW (%d)", n_NUMCache);
-#endif
+#endif
ent = NUMCache + n_NUMCache;
- strcpy(ent->str, str); /* check str size before this func. */
+ strcpy(ent->str, str); /* check str size before this func. */
/* ent->format fill parser */
ent->age = (++NUMCounter);
++n_NUMCache;
}
-
+
zeroize_NUM(&ent->Num);
-
- return ent; /* never */
+
+ return ent; /* never */
}
static NUMCacheEntry *
-NUM_cache_search( char *str )
+NUM_cache_search(char *str)
{
- int i = 0;
- NUMCacheEntry *ent;
+ int i = 0;
+ NUMCacheEntry *ent;
/* counter overload check - paranoa? */
- if (NUMCounter + NUM_CACHE_FIELDS >= MAX_INT32) {
+ if (NUMCounter + NUM_CACHE_FIELDS >= MAX_INT32)
+ {
NUMCounter = 0;
- for(ent = NUMCache; ent <= (NUMCache + NUM_CACHE_FIELDS); ent++)
- ent->age = (++NUMCounter);
+ for (ent = NUMCache; ent <= (NUMCache + NUM_CACHE_FIELDS); ent++)
+ ent->age = (++NUMCounter);
}
- for(ent = NUMCache; ent <= (NUMCache + NUM_CACHE_FIELDS); ent++) {
+ for (ent = NUMCache; ent <= (NUMCache + NUM_CACHE_FIELDS); ent++)
+ {
if (i == n_NUMCache)
break;
- if (strcmp(ent->str, str) == 0) {
+ if (strcmp(ent->str, str) == 0)
+ {
ent->age = (++NUMCounter);
return ent;
- }
- i++;
+ }
+ i++;
}
-
+
return (NUMCacheEntry *) NULL;
}
@@ -2551,82 +2804,87 @@ NUM_cache_search( char *str )
* ----------
*/
static FormatNode *
-NUM_cache( int len, NUMDesc *Num, char *pars_str, int *flag)
-{
- FormatNode *format = NULL;
- char *str;
+NUM_cache(int len, NUMDesc *Num, char *pars_str, int *flag)
+{
+ FormatNode *format = NULL;
+ char *str;
/* ----------
* Convert VARDATA() to string
* ----------
*/
- str = (char *) palloc(len + 1);
+ str = (char *) palloc(len + 1);
memcpy(str, pars_str, len);
- *(str + len) = '\0';
+ *(str + len) = '\0';
/* ----------
- * Allocate new memory if format picture is bigger than static cache
+ * Allocate new memory if format picture is bigger than static cache
* and not use cache (call parser always) - flag=1 show this variant
* ----------
- */
- if ( len > NUM_CACHE_SIZE ) {
+ */
+ if (len > NUM_CACHE_SIZE)
+ {
format = (FormatNode *) palloc((len + 1) * sizeof(FormatNode));
- *flag = 1;
-
- zeroize_NUM(Num);
-
- parse_format(format, str, NUM_keywords,
- NULL, NUM_index, NUM_TYPE, Num);
-
- (format + len)->type = NODE_TYPE_END; /* Paranoa? */
-
- } else {
-
+ *flag = 1;
+
+ zeroize_NUM(Num);
+
+ parse_format(format, str, NUM_keywords,
+ NULL, NUM_index, NUM_TYPE, Num);
+
+ (format + len)->type = NODE_TYPE_END; /* Paranoa? */
+
+ }
+ else
+ {
+
/* ----------
* Use cache buffers
* ----------
*/
- NUMCacheEntry *ent;
+ NUMCacheEntry *ent;
+
flag = 0;
- if ((ent = NUM_cache_search(str)) == NULL) {
-
+ if ((ent = NUM_cache_search(str)) == NULL)
+ {
+
ent = NUM_cache_getnew(str);
-
+
/* ----------
* Not in the cache, must run parser and save a new
- * format-picture to the cache.
+ * format-picture to the cache.
* ----------
- */
- parse_format(ent->format, str, NUM_keywords,
- NULL, NUM_index, NUM_TYPE, &ent->Num);
-
- (ent->format + len)->type = NODE_TYPE_END; /* Paranoa? */
-
- }
-
- format = ent->format;
-
+ */
+ parse_format(ent->format, str, NUM_keywords,
+ NULL, NUM_index, NUM_TYPE, &ent->Num);
+
+ (ent->format + len)->type = NODE_TYPE_END; /* Paranoa? */
+
+ }
+
+ format = ent->format;
+
/* ----------
* Copy cache to used struct
* ----------
*/
- Num->flag = ent->Num.flag;
- Num->lsign = ent->Num.lsign;
- Num->pre = ent->Num.pre;
- Num->post = ent->Num.post;
- Num->pre_lsign_num = ent->Num.pre_lsign_num;
- Num->need_locale = ent->Num.need_locale;
- Num->multi = ent->Num.multi;
- Num->zero_start = ent->Num.zero_start;
- Num->zero_end = ent->Num.zero_end;
- }
-
-#ifdef DEBUG_TO_FROM_CHAR
+ Num->flag = ent->Num.flag;
+ Num->lsign = ent->Num.lsign;
+ Num->pre = ent->Num.pre;
+ Num->post = ent->Num.post;
+ Num->pre_lsign_num = ent->Num.pre_lsign_num;
+ Num->need_locale = ent->Num.need_locale;
+ Num->multi = ent->Num.multi;
+ Num->zero_start = ent->Num.zero_start;
+ Num->zero_end = ent->Num.zero_end;
+ }
+
+#ifdef DEBUG_TO_FROM_CHAR
/* dump_node(format, len); */
- dump_index(NUM_keywords, NUM_index);
-#endif
+ dump_index(NUM_keywords, NUM_index);
+#endif
pfree(str);
return format;
@@ -2636,39 +2894,44 @@ NUM_cache( int len, NUMDesc *Num, char *pars_str, int *flag)
static char *
int_to_roman(int number)
{
- int len = 0,
- num = 0,
- set = 0;
- char *p = NULL,
- *result,
- numstr[5];
-
- result = (char *) palloc( 16 );
+ int len = 0,
+ num = 0,
+ set = 0;
+ char *p = NULL,
+ *result,
+ numstr[5];
+
+ result = (char *) palloc(16);
*result = '\0';
-
- if (number > 3999 || number < 1) {
+
+ if (number > 3999 || number < 1)
+ {
fill_str(result, '#', 15);
return result;
}
len = sprintf(numstr, "%d", number);
-
- for(p=numstr; *p!='\0'; p++, --len) {
- num = *p - 49; /* 48 ascii + 1 */
+
+ for (p = numstr; *p != '\0'; p++, --len)
+ {
+ num = *p - 49; /* 48 ascii + 1 */
if (num < 0)
continue;
- if (num == -1 && set==0)
+ if (num == -1 && set == 0)
continue;
set = 1;
-
- if (len > 3) {
- while(num-- != -1)
+
+ if (len > 3)
+ {
+ while (num-- != -1)
strcat(result, "M");
- } else {
- if (len==3)
- strcat(result, rm100[num]);
- else if (len==2)
+ }
+ else
+ {
+ if (len == 3)
+ strcat(result, rm100[num]);
+ else if (len == 2)
strcat(result, rm10[num]);
- else if (len==1)
+ else if (len == 1)
strcat(result, rm1[num]);
}
}
@@ -2687,17 +2950,18 @@ NUM_prepare_locale(NUMProc *Np)
#ifdef USE_LOCALE
- if (Np->Num->need_locale) {
+ if (Np->Num->need_locale)
+ {
- struct lconv *lconv;
+ struct lconv *lconv;
/* ----------
* Get locales
* ----------
*/
lconv = PGLC_localeconv();
-
- /* ----------
+
+ /* ----------
* Positive / Negative number sign
* ----------
*/
@@ -2705,54 +2969,56 @@ NUM_prepare_locale(NUMProc *Np)
Np->L_negative_sign = lconv->negative_sign;
else
Np->L_negative_sign = "-";
-
+
if (lconv->positive_sign && *lconv->positive_sign)
Np->L_positive_sign = lconv->positive_sign;
- else
- Np->L_positive_sign = "+";
-
+ else
+ Np->L_positive_sign = "+";
+
/* ----------
* Number thousands separator
* ----------
- */
+ */
if (lconv->thousands_sep && *lconv->thousands_sep)
Np->L_thousands_sep = lconv->thousands_sep;
- else
+ else
Np->L_thousands_sep = ",";
-
+
/* ----------
* Number decimal point
* ----------
*/
if (lconv->decimal_point && *lconv->decimal_point)
Np->decimal = lconv->decimal_point;
- else
+ else
Np->decimal = ".";
-
+
/* ----------
* Currency symbol
* ----------
*/
- if (lconv->currency_symbol && *lconv->currency_symbol)
+ if (lconv->currency_symbol && *lconv->currency_symbol)
Np->L_currency_symbol = lconv->currency_symbol;
- else
- Np->L_currency_symbol = " ";
+ else
+ Np->L_currency_symbol = " ";
+
-
if (!IS_LDECIMAL(Np->Num))
- Np->decimal = ".";
- } else {
+ Np->decimal = ".";
+ }
+ else
+ {
#endif
/* ----------
* Default values
* ----------
*/
- Np->L_negative_sign = "-";
- Np->L_positive_sign = "+";
- Np->decimal = ".";
- Np->L_thousands_sep = ",";
- Np->L_currency_symbol = " ";
+ Np->L_negative_sign = "-";
+ Np->L_positive_sign = "+";
+ Np->decimal = ".";
+ Np->L_thousands_sep = ",";
+ Np->L_currency_symbol = " ";
#ifdef USE_LOCALE
}
@@ -2761,28 +3027,29 @@ NUM_prepare_locale(NUMProc *Np)
/* ----------
* Return pointer of last relevant number after decimal point
- * 12.0500 --> last relevant is '5'
+ * 12.0500 --> last relevant is '5'
* ----------
- */
+ */
static char *
get_last_relevant_decnum(char *num)
{
- char *result,
- *p = strchr(num, '.');
-
-#ifdef DEBUG_TO_FROM_CHAR
+ char *result,
+ *p = strchr(num, '.');
+
+#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, "CALL: get_last_relevant_decnum()");
#endif
-
- if (!p)
+
+ if (!p)
p = num;
result = p;
-
- while(*(++p)) {
- if (*p!='0')
+
+ while (*(++p))
+ {
+ if (*p != '0')
result = p;
}
-
+
return result;
}
@@ -2791,53 +3058,57 @@ get_last_relevant_decnum(char *num)
* ----------
*/
static void
-NUM_numpart_from_char(NUMProc *Np, int id, int plen)
+NUM_numpart_from_char(NUMProc *Np, int id, int plen)
{
-
+
#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, " --- scan start --- ");
#endif
- if (*Np->inout_p == ' ')
- Np->inout_p++;
+ if (*Np->inout_p == ' ')
+ Np->inout_p++;
#define OVERLOAD_TEST (Np->inout_p >= Np->inout + plen)
- if (*Np->inout_p == ' ')
- Np->inout_p++;
-
+ if (*Np->inout_p == ' ')
+ Np->inout_p++;
+
if (OVERLOAD_TEST)
return;
-
+
/* ----------
* read sign
* ----------
*/
- if (*Np->number == ' ' && (id == NUM_0 || id == NUM_9 || NUM_S)) {
+ if (*Np->number == ' ' && (id == NUM_0 || id == NUM_9 || NUM_S))
+ {
#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, "Try read sign (%c).", *Np->inout_p);
-#endif
+#endif
/* ----------
* locale sign
* ----------
*/
- if (IS_LSIGN(Np->Num)) {
-
- int x = strlen(Np->L_negative_sign);
-
+ if (IS_LSIGN(Np->Num))
+ {
+
+ int x = strlen(Np->L_negative_sign);
+
#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, "Try read locale sign (%c).", *Np->inout_p);
-#endif
- if (!strncmp(Np->inout_p, Np->L_negative_sign, x)) {
- Np->inout_p += x-1;
+#endif
+ if (!strncmp(Np->inout_p, Np->L_negative_sign, x))
+ {
+ Np->inout_p += x - 1;
*Np->number = '-';
return;
}
-
+
x = strlen(Np->L_positive_sign);
- if (!strncmp(Np->inout_p, Np->L_positive_sign, x)) {
- Np->inout_p += x-1;
+ if (!strncmp(Np->inout_p, Np->L_positive_sign, x))
+ {
+ Np->inout_p += x - 1;
*Np->number = '+';
return;
}
@@ -2845,76 +3116,86 @@ NUM_numpart_from_char(NUMProc *Np, int id, int plen)
#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, "Try read sipmle sign (%c).", *Np->inout_p);
-#endif
+#endif
/* ----------
* simple + - < >
* ----------
*/
- if (*Np->inout_p == '-' || (IS_BRACKET(Np->Num) &&
- *Np->inout_p == '<' )) {
-
- *Np->number = '-'; /* set - */
+ if (*Np->inout_p == '-' || (IS_BRACKET(Np->Num) &&
+ *Np->inout_p == '<'))
+ {
+
+ *Np->number = '-'; /* set - */
Np->inout_p++;
-
- } else if (*Np->inout_p == '+') {
-
- *Np->number = '+'; /* set + */
+
+ }
+ else if (*Np->inout_p == '+')
+ {
+
+ *Np->number = '+'; /* set + */
Np->inout_p++;
- }
+ }
}
if (OVERLOAD_TEST)
return;
-
+
/* ----------
* read digit
* ----------
*/
- if (isdigit((unsigned char) *Np->inout_p)) {
-
+ if (isdigit((unsigned char) *Np->inout_p))
+ {
+
if (Np->read_dec && Np->read_post == Np->Num->post)
return;
-
+
*Np->number_p = *Np->inout_p;
Np->number_p++;
-
+
if (Np->read_dec)
Np->read_post++;
-#ifdef DEBUG_TO_FROM_CHAR
+#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, "Read digit (%c).", *Np->inout_p);
-#endif
-
- /* ----------
- * read decimal point
- * ----------
- */
- } else if (IS_DECIMAL(Np->Num)) {
+#endif
+
+ /* ----------
+ * read decimal point
+ * ----------
+ */
+ }
+ else if (IS_DECIMAL(Np->Num))
+ {
#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, "Try read decimal point (%c).", *Np->inout_p);
-#endif
- if (*Np->inout_p == '.') {
-
+#endif
+ if (*Np->inout_p == '.')
+ {
+
*Np->number_p = '.';
Np->number_p++;
Np->read_dec = TRUE;
-
- } else {
-
- int x = strlen(Np->decimal);
-
+
+ }
+ else
+ {
+
+ int x = strlen(Np->decimal);
+
#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, "Try read locale point (%c).", *Np->inout_p);
-#endif
- if (!strncmp(Np->inout_p, Np->decimal, x)) {
- Np->inout_p += x-1;
+#endif
+ if (!strncmp(Np->inout_p, Np->decimal, x))
+ {
+ Np->inout_p += x - 1;
*Np->number_p = '.';
Np->number_p++;
Np->read_dec = TRUE;
}
}
- }
+ }
}
/* ----------
@@ -2922,334 +3203,379 @@ NUM_numpart_from_char(NUMProc *Np, int id, int plen)
* ----------
*/
static void
-NUM_numpart_to_char(NUMProc *Np, int id)
-{
+NUM_numpart_to_char(NUMProc *Np, int id)
+{
if (IS_ROMAN(Np->Num))
return;
-
+
/* Note: in this elog() output not set '\0' in 'inout' */
-#ifdef DEBUG_TO_FROM_CHAR
+#ifdef DEBUG_TO_FROM_CHAR
+
/*
- * Np->num_curr is number of current item in format-picture, it is not
- * current position in inout!
- */
- elog(DEBUG_elog_output,
-
- "SIGN_WROTE: %d, CURRENT: %d, NUMBER_P: '%s', INOUT: '%s'",
- Np->sign_wrote,
- Np->num_curr,
- Np->number_p,
- Np->inout);
-#endif
+ * Np->num_curr is number of current item in format-picture, it is not
+ * current position in inout!
+ */
+ elog(DEBUG_elog_output,
+
+ "SIGN_WROTE: %d, CURRENT: %d, NUMBER_P: '%s', INOUT: '%s'",
+ Np->sign_wrote,
+ Np->num_curr,
+ Np->number_p,
+ Np->inout);
+#endif
Np->num_in = FALSE;
-
+
/* ----------
* Write sign
* ----------
*/
- if (Np->num_curr == Np->sign_pos && Np->sign_wrote==FALSE) {
+ if (Np->num_curr == Np->sign_pos && Np->sign_wrote == FALSE)
+ {
-#ifdef DEBUG_TO_FROM_CHAR
+#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, "Writing sign to position: %d", Np->num_curr);
-#endif
- if (IS_LSIGN(Np->Num)) {
-
+#endif
+ if (IS_LSIGN(Np->Num))
+ {
+
/* ----------
- * Write locale SIGN
+ * Write locale SIGN
* ----------
*/
- if (Np->sign=='-')
- strcpy(Np->inout_p, Np->L_negative_sign);
- else
- strcpy(Np->inout_p, Np->L_positive_sign);
- Np->inout_p += strlen(Np->inout_p);
-
- } else if (IS_BRACKET(Np->Num)) {
- *Np->inout_p = '<'; /* Write < */
- ++Np->inout_p;
-
- } else if (Np->sign=='+') {
- *Np->inout_p = ' '; /* Write + */
+ if (Np->sign == '-')
+ strcpy(Np->inout_p, Np->L_negative_sign);
+ else
+ strcpy(Np->inout_p, Np->L_positive_sign);
+ Np->inout_p += strlen(Np->inout_p);
+
+ }
+ else if (IS_BRACKET(Np->Num))
+ {
+ *Np->inout_p = '<'; /* Write < */
+ ++Np->inout_p;
+
+ }
+ else if (Np->sign == '+')
+ {
+ *Np->inout_p = ' '; /* Write + */
++Np->inout_p;
-
- } else if (Np->sign=='-') { /* Write - */
+
+ }
+ else if (Np->sign == '-')
+ { /* Write - */
*Np->inout_p = '-';
- ++Np->inout_p;
- }
+ ++Np->inout_p;
+ }
Np->sign_wrote = TRUE;
- } else if (Np->sign_wrote && IS_BRACKET(Np->Num) &&
- (Np->num_curr == Np->num_count + (Np->num_pre ? 1 : 0)
- + (IS_DECIMAL(Np->Num) ? 1 : 0))) {
+ }
+ else if (Np->sign_wrote && IS_BRACKET(Np->Num) &&
+ (Np->num_curr == Np->num_count + (Np->num_pre ? 1 : 0)
+ + (IS_DECIMAL(Np->Num) ? 1 : 0)))
+ {
/* ----------
* Write close BRACKET
* ----------
- */
+ */
#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, "Writing bracket to position %d", Np->num_curr);
-#endif
- *Np->inout_p = '>'; /* Write '>' */
- ++Np->inout_p;
+#endif
+ *Np->inout_p = '>'; /* Write '>' */
+ ++Np->inout_p;
}
-
+
/* ----------
* digits / FM / Zero / Dec. point
* ----------
*/
- if (id == NUM_9 || id == NUM_0 || id == NUM_D || id == NUM_DEC ||
- (id == NUM_S && Np->num_curr < Np->num_pre)) {
-
- if (Np->num_curr < Np->num_pre &&
- (Np->Num->zero_start > Np->num_curr || !IS_ZERO(Np->Num))) {
-
- /* ----------
- * Write blank space
- * ----------
- */
- if (!IS_FILLMODE(Np->Num)) {
- #ifdef DEBUG_TO_FROM_CHAR
- elog(DEBUG_elog_output, "Writing blank space to position %d", Np->num_curr);
- #endif
- *Np->inout_p = ' '; /* Write ' ' */
+ if (id == NUM_9 || id == NUM_0 || id == NUM_D || id == NUM_DEC ||
+ (id == NUM_S && Np->num_curr < Np->num_pre))
+ {
+
+ if (Np->num_curr < Np->num_pre &&
+ (Np->Num->zero_start > Np->num_curr || !IS_ZERO(Np->Num)))
+ {
+
+ /* ----------
+ * Write blank space
+ * ----------
+ */
+ if (!IS_FILLMODE(Np->Num))
+ {
+#ifdef DEBUG_TO_FROM_CHAR
+ elog(DEBUG_elog_output, "Writing blank space to position %d", Np->num_curr);
+#endif
+ *Np->inout_p = ' '; /* Write ' ' */
++Np->inout_p;
}
- } else if (IS_ZERO(Np->Num) &&
- Np->num_curr < Np->num_pre &&
- Np->Num->zero_start <= Np->num_curr) {
-
+ }
+ else if (IS_ZERO(Np->Num) &&
+ Np->num_curr < Np->num_pre &&
+ Np->Num->zero_start <= Np->num_curr)
+ {
+
/* ----------
* Write ZERO
* ----------
*/
-#ifdef DEBUG_TO_FROM_CHAR
+#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, "Writing zero to position %d", Np->num_curr);
-#endif
- *Np->inout_p = '0'; /* Write '0' */
+#endif
+ *Np->inout_p = '0'; /* Write '0' */
++Np->inout_p;
Np->num_in = TRUE;
-
- } else {
+
+ }
+ else
+ {
/* ----------
- * Write Decinal point
+ * Write Decinal point
* ----------
- */
- if (*Np->number_p=='.') {
-
- if (!Np->last_relevant || *Np->last_relevant!='.' ) {
-#ifdef DEBUG_TO_FROM_CHAR
+ */
+ if (*Np->number_p == '.')
+ {
+
+ if (!Np->last_relevant || *Np->last_relevant != '.')
+ {
+#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, "Writing decimal point to position %d", Np->num_curr);
-#endif
+#endif
strcpy(Np->inout_p, Np->decimal); /* Write DEC/D */
Np->inout_p += strlen(Np->inout_p);
-
- /* terrible Ora
- * '0' -- 9.9 --> '0.'
- */
- } else if (IS_FILLMODE(Np->Num) && *Np->number == '0' &&
- Np->last_relevant && *Np->last_relevant=='.' ) {
-
+
+ /*
+ * terrible Ora '0' -- 9.9 --> '0.'
+ */
+ }
+ else if (IS_FILLMODE(Np->Num) && *Np->number == '0' &&
+ Np->last_relevant && *Np->last_relevant == '.')
+ {
+
strcpy(Np->inout_p, Np->decimal); /* Write DEC/D */
Np->inout_p += strlen(Np->inout_p);
}
-
- } else {
+
+ }
+ else
+ {
/* ----------
* Write Digits
* ----------
*/
if (Np->last_relevant && Np->number_p > Np->last_relevant &&
- id != NUM_0)
+ id != NUM_0)
;
-
- /* terrible Ora format:
- * '0.1' -- 9.9 --> ' .1'
+
+ /*
+ * terrible Ora format: '0.1' -- 9.9 --> ' .1'
*/
- else if (!IS_ZERO(Np->Num) && *Np->number == '0' &&
- Np->number == Np->number_p && Np->Num->post !=0) {
-
- if (!IS_FILLMODE(Np->Num)) {
+ else if (!IS_ZERO(Np->Num) && *Np->number == '0' &&
+ Np->number == Np->number_p && Np->Num->post != 0)
+ {
+
+ if (!IS_FILLMODE(Np->Num))
+ {
*Np->inout_p = ' ';
++Np->inout_p;
-
- /* total terible Ora:
- * '0' -- FM9.9 --> '0.'
- */
- } else if (Np->last_relevant && *Np->last_relevant=='.') {
+
+ /*
+ * total terible Ora: '0' -- FM9.9 --> '0.'
+ */
+ }
+ else if (Np->last_relevant && *Np->last_relevant == '.')
+ {
*Np->inout_p = '0';
++Np->inout_p;
}
-
- } else {
+
+ }
+ else
+ {
#ifdef DEBUG_TO_FROM_CHAR
elog(DEBUG_elog_output, "Writing digit '%c' to position %d", *Np->number_p, Np->num_curr);
-#endif
- *Np->inout_p = *Np->number_p; /* Write DIGIT */
+#endif
+ *Np->inout_p = *Np->number_p; /* Write DIGIT */
++Np->inout_p;
Np->num_in = TRUE;
- }
+ }
}
++Np->number_p;
- }
+ }
}
-
+
++Np->num_curr;
}
-
+
static char *
-NUM_processor (FormatNode *node, NUMDesc *Num, char *inout, char *number,
- int plen, int sign, int type)
+NUM_processor(FormatNode *node, NUMDesc *Num, char *inout, char *number,
+ int plen, int sign, int type)
{
- FormatNode *n;
- NUMProc _Np, *Np = &_Np;
-
- Np->Num = Num;
- Np->type = type;
- Np->number = number;
- Np->inout = inout;
+ FormatNode *n;
+ NUMProc _Np,
+ *Np = &_Np;
+
+ Np->Num = Num;
+ Np->type = type;
+ Np->number = number;
+ Np->inout = inout;
Np->last_relevant = NULL;
- Np->read_post = 0;
- Np->read_dec = FALSE;
+ Np->read_post = 0;
+ Np->read_dec = FALSE;
if (Np->Num->zero_start)
--Np->Num->zero_start;
- /* ----------
- * Roman correction
+ /* ----------
+ * Roman correction
* ----------
*/
- if (IS_ROMAN(Np->Num)) {
- if (Np->type==FROM_CHAR)
- elog(ERROR, "to_number(): RN is not supported");
-
- Np->Num->lsign = Np->Num->pre_lsign_num = Np->Num->post =
- Np->Num->pre = Np->num_pre = Np->sign = 0;
-
- if (IS_FILLMODE(Np->Num)){
+ if (IS_ROMAN(Np->Num))
+ {
+ if (Np->type == FROM_CHAR)
+ elog(ERROR, "to_number(): RN is not supported");
+
+ Np->Num->lsign = Np->Num->pre_lsign_num = Np->Num->post =
+ Np->Num->pre = Np->num_pre = Np->sign = 0;
+
+ if (IS_FILLMODE(Np->Num))
+ {
Np->Num->flag = 0;
Np->Num->flag |= NUM_F_FILLMODE;
- } else {
+ }
+ else
Np->Num->flag = 0;
- }
- Np->Num->flag |= NUM_F_ROMAN;
+ Np->Num->flag |= NUM_F_ROMAN;
}
-
+
/* ----------
* Sign
* ----------
*/
- if (type == FROM_CHAR) {
- Np->sign = FALSE;
- Np->sign_pos = -1;
- } else {
- Np->sign = sign;
-
- if (Np->sign != '-') {
+ if (type == FROM_CHAR)
+ {
+ Np->sign = FALSE;
+ Np->sign_pos = -1;
+ }
+ else
+ {
+ Np->sign = sign;
+
+ if (Np->sign != '-')
+ {
Np->Num->flag &= ~NUM_F_BRACKET;
Np->Num->flag &= ~NUM_F_MINUS;
- } else if (Np->sign != '+') {
- Np->Num->flag &= ~NUM_F_PLUS;
}
-
- if (Np->sign=='+' && IS_FILLMODE(Np->Num) && !IS_LSIGN(Np->Num))
- Np->sign_wrote = TRUE; /* needn't sign */
+ else if (Np->sign != '+')
+ Np->Num->flag &= ~NUM_F_PLUS;
+
+ if (Np->sign == '+' && IS_FILLMODE(Np->Num) && !IS_LSIGN(Np->Num))
+ Np->sign_wrote = TRUE; /* needn't sign */
else
- Np->sign_wrote = FALSE; /* need sign */
+ Np->sign_wrote = FALSE; /* need sign */
Np->sign_pos = -1;
-
+
if (Np->Num->lsign == NUM_LSIGN_PRE && Np->Num->pre == Np->Num->pre_lsign_num)
Np->Num->lsign = NUM_LSIGN_POST;
-
+
/* MI/PL/SG - write sign itself and not in number */
if (IS_PLUS(Np->Num) || IS_MINUS(Np->Num))
- Np->sign_wrote = TRUE; /* needn't sign */
+ Np->sign_wrote = TRUE; /* needn't sign */
}
/* ----------
* Count
* ----------
*/
- Np->num_count = Np->Num->post + Np->Num->pre -1;
+ Np->num_count = Np->Num->post + Np->Num->pre - 1;
- if (type == TO_CHAR) {
+ if (type == TO_CHAR)
+ {
Np->num_pre = plen;
- if (IS_FILLMODE(Np->Num)) {
+ if (IS_FILLMODE(Np->Num))
+ {
if (IS_DECIMAL(Np->Num))
Np->last_relevant = get_last_relevant_decnum(
- Np->number +
- ((Np->Num->zero_end - Np->num_pre > 0) ?
- Np->Num->zero_end - Np->num_pre : 0));
- }
-
- if (!Np->sign_wrote && Np->num_pre==0)
+ Np->number +
+ ((Np->Num->zero_end - Np->num_pre > 0) ?
+ Np->Num->zero_end - Np->num_pre : 0));
+ }
+
+ if (!Np->sign_wrote && Np->num_pre == 0)
++Np->num_count;
-
- if (!Np->sign_wrote) {
-
- /* ----------
- * Set SING position
- * ----------
- */
- if (Np->Num->lsign == NUM_LSIGN_POST) {
- Np->sign_pos = Np->num_count + (Np->num_pre ? 1 : 0);
-
- if (IS_DECIMAL(Np->Num)) /* decimal point correctio */
- ++Np->sign_pos;
- }
- else if (IS_ZERO(Np->Num) && Np->num_pre > Np->Num->zero_start)
- Np->sign_pos = Np->Num->zero_start ? Np->Num->zero_start : 0;
-
- else
- Np->sign_pos = Np->num_pre && !IS_FILLMODE(Np->Num) ? Np->num_pre : 0;
-
- /* ----------
- * terrible Ora format
- * ----------
- */
- if (!IS_ZERO(Np->Num) && *Np->number == '0' &&
- !IS_FILLMODE(Np->Num) && Np->Num->post!=0) {
-
- ++Np->sign_pos;
-
- if (IS_LSIGN(Np->Num)) {
- if (Np->Num->lsign == NUM_LSIGN_PRE)
- ++Np->sign_pos;
- else
- --Np->sign_pos;
- }
- }
- }
-
- } else {
+
+ if (!Np->sign_wrote)
+ {
+
+ /* ----------
+ * Set SING position
+ * ----------
+ */
+ if (Np->Num->lsign == NUM_LSIGN_POST)
+ {
+ Np->sign_pos = Np->num_count + (Np->num_pre ? 1 : 0);
+
+ if (IS_DECIMAL(Np->Num)) /* decimal point correctio */
+ ++Np->sign_pos;
+ }
+ else if (IS_ZERO(Np->Num) && Np->num_pre > Np->Num->zero_start)
+ Np->sign_pos = Np->Num->zero_start ? Np->Num->zero_start : 0;
+
+ else
+ Np->sign_pos = Np->num_pre && !IS_FILLMODE(Np->Num) ? Np->num_pre : 0;
+
+ /* ----------
+ * terrible Ora format
+ * ----------
+ */
+ if (!IS_ZERO(Np->Num) && *Np->number == '0' &&
+ !IS_FILLMODE(Np->Num) && Np->Num->post != 0)
+ {
+
+ ++Np->sign_pos;
+
+ if (IS_LSIGN(Np->Num))
+ {
+ if (Np->Num->lsign == NUM_LSIGN_PRE)
+ ++Np->sign_pos;
+ else
+ --Np->sign_pos;
+ }
+ }
+ }
+
+ }
+ else
+ {
Np->num_pre = 0;
- *Np->number = ' '; /* sign space */
- *(Np->number+1) = '\0';
- }
-
- Np->num_in = 0;
- Np->num_curr = 0;
-
-#ifdef DEBUG_TO_FROM_CHAR
- elog(DEBUG_elog_output,
-
- "\n\tNUM: '%s'\n\tPRE: %d\n\tPOST: %d\n\tNUM_COUNT: %d\n\tNUM_PRE: %d\n\tSIGN_POS: %d\n\tSIGN_WROTE: %s\n\tZERO: %s\n\tZERO_START: %d\n\tZERO_END: %d\n\tLAST_RELEVANT: %s",
- Np->number,
- Np->Num->pre,
- Np->Num->post,
- Np->num_count,
- Np->num_pre,
- Np->sign_pos,
- Np->sign_wrote ? "Yes" : "No",
- IS_ZERO(Np->Num) ? "Yes" : "No",
- Np->Num->zero_start,
- Np->Num->zero_end,
- Np->last_relevant ? Np->last_relevant : "<not set>"
- );
+ *Np->number = ' '; /* sign space */
+ *(Np->number + 1) = '\0';
+ }
+
+ Np->num_in = 0;
+ Np->num_curr = 0;
+
+#ifdef DEBUG_TO_FROM_CHAR
+ elog(DEBUG_elog_output,
+
+ "\n\tNUM: '%s'\n\tPRE: %d\n\tPOST: %d\n\tNUM_COUNT: %d\n\tNUM_PRE: %d\n\tSIGN_POS: %d\n\tSIGN_WROTE: %s\n\tZERO: %s\n\tZERO_START: %d\n\tZERO_END: %d\n\tLAST_RELEVANT: %s",
+ Np->number,
+ Np->Num->pre,
+ Np->Num->post,
+ Np->num_count,
+ Np->num_pre,
+ Np->sign_pos,
+ Np->sign_wrote ? "Yes" : "No",
+ IS_ZERO(Np->Num) ? "Yes" : "No",
+ Np->Num->zero_start,
+ Np->Num->zero_end,
+ Np->last_relevant ? Np->last_relevant : "<not set>"
+ );
#endif
/* ----------
@@ -3262,181 +3588,217 @@ NUM_processor (FormatNode *node, NUMDesc *Num, char *inout, char *number,
* Processor direct cycle
* ----------
*/
- if (Np->type == FROM_CHAR)
- Np->number_p=Np->number+1; /* first char is space for sign */
+ if (Np->type == FROM_CHAR)
+ Np->number_p = Np->number + 1; /* first char is space for sign */
else if (Np->type == TO_CHAR)
- Np->number_p=Np->number;
+ Np->number_p = Np->number;
+
+ for (n = node, Np->inout_p = Np->inout; n->type != NODE_TYPE_END; n++)
+ {
- for(n=node, Np->inout_p=Np->inout; n->type != NODE_TYPE_END; n++) {
-
- if (Np->type == FROM_CHAR) {
+ if (Np->type == FROM_CHAR)
+ {
/* ----------
* Check non-string inout end
* ----------
*/
- if (Np->inout_p >= Np->inout + plen)
+ if (Np->inout_p >= Np->inout + plen)
break;
}
-
+
/* ----------
* Format pictures actions
* ----------
*/
- if (n->type == NODE_TYPE_ACTION) {
-
+ if (n->type == NODE_TYPE_ACTION)
+ {
+
/* ----------
- * Create/reading digit/zero/blank/sing
+ * Create/reading digit/zero/blank/sing
* ----------
*/
- switch( n->key->id ) {
-
- case NUM_9:
- case NUM_0:
- case NUM_DEC:
- case NUM_D:
- case NUM_S:
- case NUM_PR:
- if (Np->type == TO_CHAR) {
- NUM_numpart_to_char(Np, n->key->id);
- continue; /* for() */
- } else {
- NUM_numpart_from_char(Np, n->key->id, plen);
- break; /* switch() case: */
- }
-
- case NUM_COMMA:
- if (Np->type == TO_CHAR) {
- if (!Np->num_in) {
- if (IS_FILLMODE(Np->Num))
- continue;
+ switch (n->key->id)
+ {
+
+ case NUM_9:
+ case NUM_0:
+ case NUM_DEC:
+ case NUM_D:
+ case NUM_S:
+ case NUM_PR:
+ if (Np->type == TO_CHAR)
+ {
+ NUM_numpart_to_char(Np, n->key->id);
+ continue; /* for() */
+ }
+ else
+ {
+ NUM_numpart_from_char(Np, n->key->id, plen);
+ break; /* switch() case: */
+ }
+
+ case NUM_COMMA:
+ if (Np->type == TO_CHAR)
+ {
+ if (!Np->num_in)
+ {
+ if (IS_FILLMODE(Np->Num))
+ continue;
+ else
+ *Np->inout_p = ' ';
+ }
else
- *Np->inout_p= ' ';
- } else
- *Np->inout_p = ',';
-
- } else if (Np->type == FROM_CHAR) {
- if (!Np->num_in) {
- if (IS_FILLMODE(Np->Num))
- continue;
+ *Np->inout_p = ',';
+
}
- }
- break;
-
- case NUM_G:
- if (Np->type == TO_CHAR) {
- if (!Np->num_in) {
- if (IS_FILLMODE(Np->Num))
- continue;
- else {
- int x = strlen(Np->L_thousands_sep);
- memset(Np->inout_p, ' ', x);
- Np->inout_p += x-1;
+ else if (Np->type == FROM_CHAR)
+ {
+ if (!Np->num_in)
+ {
+ if (IS_FILLMODE(Np->Num))
+ continue;
+ }
+ }
+ break;
+
+ case NUM_G:
+ if (Np->type == TO_CHAR)
+ {
+ if (!Np->num_in)
+ {
+ if (IS_FILLMODE(Np->Num))
+ continue;
+ else
+ {
+ int x = strlen(Np->L_thousands_sep);
+
+ memset(Np->inout_p, ' ', x);
+ Np->inout_p += x - 1;
+ }
+ }
+ else
+ {
+ strcpy(Np->inout_p, Np->L_thousands_sep);
+ Np->inout_p += strlen(Np->inout_p) - 1;
}
- } else {
- strcpy(Np->inout_p, Np->L_thousands_sep);
- Np->inout_p += strlen(Np->inout_p)-1;
+
}
-
- } else if (Np->type == FROM_CHAR) {
- if (!Np->num_in) {
- if (IS_FILLMODE(Np->Num))
- continue;
+ else if (Np->type == FROM_CHAR)
+ {
+ if (!Np->num_in)
+ {
+ if (IS_FILLMODE(Np->Num))
+ continue;
+ }
+ Np->inout_p += strlen(Np->L_thousands_sep) - 1;
+ }
+ break;
+
+ case NUM_L:
+ if (Np->type == TO_CHAR)
+ {
+ strcpy(Np->inout_p, Np->L_currency_symbol);
+ Np->inout_p += strlen(Np->inout_p) - 1;
+
+ }
+ else if (Np->type == FROM_CHAR)
+ Np->inout_p += strlen(Np->L_currency_symbol) - 1;
+ break;
+
+ case NUM_RN:
+ if (IS_FILLMODE(Np->Num))
+ {
+ strcpy(Np->inout_p, Np->number_p);
+ Np->inout_p += strlen(Np->inout_p) - 1;
}
- Np->inout_p += strlen(Np->L_thousands_sep)-1;
- }
- break;
-
- case NUM_L:
- if (Np->type == TO_CHAR) {
- strcpy(Np->inout_p, Np->L_currency_symbol);
- Np->inout_p += strlen(Np->inout_p)-1;
-
- } else if (Np->type == FROM_CHAR) {
- Np->inout_p += strlen(Np->L_currency_symbol)-1;
- }
- break;
-
- case NUM_RN:
- if (IS_FILLMODE(Np->Num)) {
- strcpy(Np->inout_p, Np->number_p);
- Np->inout_p += strlen(Np->inout_p) - 1;
- } else
- Np->inout_p += sprintf(Np->inout_p, "%15s", Np->number_p) -1;
- break;
-
- case NUM_rn:
- if (IS_FILLMODE(Np->Num)) {
- strcpy(Np->inout_p, str_tolower(Np->number_p));
- Np->inout_p += strlen(Np->inout_p) - 1;
- } else
- Np->inout_p += sprintf(Np->inout_p, "%15s", str_tolower(Np->number_p)) -1;
- break;
-
- case NUM_th:
- if (IS_ROMAN(Np->Num) || *Np->number=='#' ||
- Np->sign=='-' || IS_DECIMAL(Np->Num))
- continue;
-
- if (Np->type == TO_CHAR)
- strcpy(Np->inout_p, get_th(Np->number, TH_LOWER));
- Np->inout_p += 1;
- break;
-
- case NUM_TH:
- if (IS_ROMAN(Np->Num) || *Np->number=='#' ||
- Np->sign=='-' || IS_DECIMAL(Np->Num))
- continue;
-
- if (Np->type == TO_CHAR)
- strcpy(Np->inout_p, get_th(Np->number, TH_UPPER));
- Np->inout_p += 1;
- break;
-
- case NUM_MI:
- if (Np->type == TO_CHAR) {
- if (Np->sign=='-')
- *Np->inout_p = '-';
- else
- *Np->inout_p = ' ';
-
- } else if (Np->type == FROM_CHAR) {
- if (*Np->inout_p == '-')
- *Np->number = '-';
- }
- break;
-
- case NUM_PL:
- if (Np->type == TO_CHAR) {
- if (Np->sign=='+')
- *Np->inout_p = '+';
else
- *Np->inout_p = ' ';
-
- } else if (Np->type == FROM_CHAR) {
- if (*Np->inout_p == '+')
- *Np->number = '+';
- }
- break;
-
- case NUM_SG:
- if (Np->type == TO_CHAR)
- *Np->inout_p = Np->sign;
-
- else if (Np->type == FROM_CHAR) {
- if (*Np->inout_p == '-')
- *Np->number = '-';
- else if (*Np->inout_p == '+')
- *Np->number = '+';
- }
- break;
-
-
- default:
- continue;
- break;
+ Np->inout_p += sprintf(Np->inout_p, "%15s", Np->number_p) - 1;
+ break;
+
+ case NUM_rn:
+ if (IS_FILLMODE(Np->Num))
+ {
+ strcpy(Np->inout_p, str_tolower(Np->number_p));
+ Np->inout_p += strlen(Np->inout_p) - 1;
+ }
+ else
+ Np->inout_p += sprintf(Np->inout_p, "%15s", str_tolower(Np->number_p)) - 1;
+ break;
+
+ case NUM_th:
+ if (IS_ROMAN(Np->Num) || *Np->number == '#' ||
+ Np->sign == '-' || IS_DECIMAL(Np->Num))
+ continue;
+
+ if (Np->type == TO_CHAR)
+ strcpy(Np->inout_p, get_th(Np->number, TH_LOWER));
+ Np->inout_p += 1;
+ break;
+
+ case NUM_TH:
+ if (IS_ROMAN(Np->Num) || *Np->number == '#' ||
+ Np->sign == '-' || IS_DECIMAL(Np->Num))
+ continue;
+
+ if (Np->type == TO_CHAR)
+ strcpy(Np->inout_p, get_th(Np->number, TH_UPPER));
+ Np->inout_p += 1;
+ break;
+
+ case NUM_MI:
+ if (Np->type == TO_CHAR)
+ {
+ if (Np->sign == '-')
+ *Np->inout_p = '-';
+ else
+ *Np->inout_p = ' ';
+
+ }
+ else if (Np->type == FROM_CHAR)
+ {
+ if (*Np->inout_p == '-')
+ *Np->number = '-';
+ }
+ break;
+
+ case NUM_PL:
+ if (Np->type == TO_CHAR)
+ {
+ if (Np->sign == '+')
+ *Np->inout_p = '+';
+ else
+ *Np->inout_p = ' ';
+
+ }
+ else if (Np->type == FROM_CHAR)
+ {
+ if (*Np->inout_p == '+')
+ *Np->number = '+';
+ }
+ break;
+
+ case NUM_SG:
+ if (Np->type == TO_CHAR)
+ *Np->inout_p = Np->sign;
+
+ else if (Np->type == FROM_CHAR)
+ {
+ if (*Np->inout_p == '-')
+ *Np->number = '-';
+ else if (*Np->inout_p == '+')
+ *Np->number = '+';
+ }
+ break;
+
+
+ default:
+ continue;
+ break;
}
- } else {
+ }
+ else
+ {
/* ----------
* Remove to output char from input in TO_CHAR
* ----------
@@ -3444,34 +3806,38 @@ NUM_processor (FormatNode *node, NUMDesc *Num, char *inout, char *number,
if (Np->type == TO_CHAR)
*Np->inout_p = n->character;
}
- Np->inout_p++;
+ Np->inout_p++;
}
-
- if (Np->type == TO_CHAR) {
+
+ if (Np->type == TO_CHAR)
+ {
*Np->inout_p = '\0';
- return Np->inout;
-
- } else if (Np->type == FROM_CHAR) {
-
- if (*(Np->number_p-1) == '.')
- *(Np->number_p-1) = '\0';
+ return Np->inout;
+
+ }
+ else if (Np->type == FROM_CHAR)
+ {
+
+ if (*(Np->number_p - 1) == '.')
+ *(Np->number_p - 1) = '\0';
else
*Np->number_p = '\0';
-
+
/* ----------
* Correction - precision of dec. number
* ----------
*/
- Np->Num->post = Np->read_post;
+ Np->Num->post = Np->read_post;
#ifdef DEBUG_TO_FROM_CHAR
- elog(DEBUG_elog_output, "TO_NUMBER (number): '%s'", Np->number);
+ elog(DEBUG_elog_output, "TO_NUMBER (number): '%s'", Np->number);
#endif
return Np->number;
- } else
- return NULL;
-
- return NULL;
+ }
+ else
+ return NULL;
+
+ return NULL;
}
/* ----------
@@ -3483,13 +3849,13 @@ NUM_processor (FormatNode *node, NUMDesc *Num, char *inout, char *number,
if (!PointerIsValid(fmt)) \
return NULL; \
\
- len = VARSIZE(fmt) - VARHDRSZ; \
+ len = VARSIZE(fmt) - VARHDRSZ; \
\
- if (!len) \
+ if (!len) \
return textin(""); \
\
result = (text *) palloc( (len * NUM_MAX_ITEM_SIZ) + 1 + VARHDRSZ); \
- format = NUM_cache(len, &Num, VARDATA(fmt), &flag); \
+ format = NUM_cache(len, &Num, VARDATA(fmt), &flag); \
}
/* ----------
@@ -3498,65 +3864,66 @@ NUM_processor (FormatNode *node, NUMDesc *Num, char *inout, char *number,
*/
#define NUM_TOCHAR_finish { \
\
- NUM_processor(format, &Num, VARDATA(result), \
+ NUM_processor(format, &Num, VARDATA(result), \
numstr, plen, sign, TO_CHAR); \
pfree(orgnum); \
\
if (flag) \
pfree(format); \
\
- /* ---------- \
+ /* ---------- \
* for result is allocated max memory, which current format-picture\
* needs, now it must be re-allocate to result real size \
* ---------- \
*/ \
- len = strlen(VARDATA(result)); \
- result_tmp = result; \
- result = (text *) palloc( len + 1 + VARHDRSZ); \
+ len = strlen(VARDATA(result)); \
+ result_tmp = result; \
+ result = (text *) palloc( len + 1 + VARHDRSZ); \
\
- strcpy( VARDATA(result), VARDATA(result_tmp)); \
- VARSIZE(result) = len + VARHDRSZ; \
+ strcpy( VARDATA(result), VARDATA(result_tmp)); \
+ VARSIZE(result) = len + VARHDRSZ; \
pfree(result_tmp); \
}
/* -------------------
- * NUMERIC to_number() (convert string to numeric)
+ * NUMERIC to_number() (convert string to numeric)
* -------------------
*/
-Numeric
+Numeric
numeric_to_number(text *value, text *fmt)
{
- NUMDesc Num;
- Numeric result;
- FormatNode *format;
- char *numstr;
- int flag=0;
- int len=0;
-
- int scale, precision;
-
+ NUMDesc Num;
+ Numeric result;
+ FormatNode *format;
+ char *numstr;
+ int flag = 0;
+ int len = 0;
+
+ int scale,
+ precision;
+
if ((!PointerIsValid(value)) || (!PointerIsValid(fmt)))
- return NULL;
+ return NULL;
+
+ len = VARSIZE(fmt) - VARHDRSZ;
+
+ if (!len)
+ return numeric_in(NULL, 0, 0);
- len = VARSIZE(fmt) - VARHDRSZ;
-
- if (!len)
- return numeric_in(NULL, 0, 0);
-
format = NUM_cache(len, &Num, VARDATA(fmt), &flag);
-
- numstr = (char *) palloc( (len * NUM_MAX_ITEM_SIZ) + 1);
-
- NUM_processor(format, &Num, VARDATA(value), numstr,
- VARSIZE(value) - VARHDRSZ, 0, FROM_CHAR);
-
+
+ numstr = (char *) palloc((len * NUM_MAX_ITEM_SIZ) + 1);
+
+ NUM_processor(format, &Num, VARDATA(value), numstr,
+ VARSIZE(value) - VARHDRSZ, 0, FROM_CHAR);
+
scale = Num.post;
precision = MAX(0, Num.pre) + scale;
if (flag)
pfree(format);
-
- result = numeric_in(numstr, 0, ((precision << 16) | scale) + VARHDRSZ);
+
+ result = numeric_in(numstr, 0, ((precision << 16) | scale) + VARHDRSZ);
pfree(numstr);
return result;
}
@@ -3564,17 +3931,22 @@ numeric_to_number(text *value, text *fmt)
/* ------------------
* NUMERIC to_char()
* ------------------
- */
+ */
text *
numeric_to_char(Numeric value, text *fmt)
{
- NUMDesc Num;
- FormatNode *format;
- text *result, *result_tmp;
- int flag=0;
- int len=0, plen=0, sign=0;
- char *numstr, *orgnum, *p;
- Numeric x = NULL;
+ NUMDesc Num;
+ FormatNode *format;
+ text *result,
+ *result_tmp;
+ int flag = 0;
+ int len = 0,
+ plen = 0,
+ sign = 0;
+ char *numstr,
+ *orgnum,
+ *p;
+ Numeric x = NULL;
NUM_TOCHAR_prepare;
@@ -3582,54 +3954,62 @@ numeric_to_char(Numeric value, text *fmt)
* On DateType depend part (numeric)
* ----------
*/
- if (IS_ROMAN(&Num)) {
+ if (IS_ROMAN(&Num))
+ {
x = numeric_round(value, 0);
- numstr = orgnum = int_to_roman( numeric_int4( x ));
- pfree(x);
-
- } else {
- Numeric val = value;
-
- if (IS_MULTI(&Num)) {
- Numeric a = int4_numeric(10);
- Numeric b = int4_numeric(Num.multi);
-
+ numstr = orgnum = int_to_roman(numeric_int4(x));
+ pfree(x);
+
+ }
+ else
+ {
+ Numeric val = value;
+
+ if (IS_MULTI(&Num))
+ {
+ Numeric a = int4_numeric(10);
+ Numeric b = int4_numeric(Num.multi);
+
x = numeric_power(a, b);
- val = numeric_mul(value, x);
+ val = numeric_mul(value, x);
pfree(x);
pfree(a);
pfree(b);
Num.pre += Num.multi;
}
-
+
x = numeric_round(val, Num.post);
- orgnum = numeric_out( x );
+ orgnum = numeric_out(x);
pfree(x);
-
- if (*orgnum == '-') { /* < 0 */
+
+ if (*orgnum == '-')
+ { /* < 0 */
sign = '-';
- numstr = orgnum+1;
- } else {
+ numstr = orgnum + 1;
+ }
+ else
+ {
sign = '+';
numstr = orgnum;
}
if ((p = strchr(numstr, '.')))
- len = p - numstr;
+ len = p - numstr;
else
len = strlen(numstr);
-
- if (Num.pre > len)
+
+ if (Num.pre > len)
plen = Num.pre - len;
-
- else if (len > Num.pre) {
+
+ else if (len > Num.pre)
+ {
fill_str(numstr, '#', Num.pre);
*(numstr + Num.pre) = '.';
fill_str(numstr + 1 + Num.pre, '#', Num.post);
}
-
+
if (IS_MULTI(&Num))
- pfree(val);
- }
+ pfree(val);
+ }
NUM_TOCHAR_finish;
return result;
@@ -3638,16 +4018,20 @@ numeric_to_char(Numeric value, text *fmt)
/* ---------------
* INT4 to_char()
* ---------------
- */
+ */
text *
int4_to_char(int32 value, text *fmt)
{
- NUMDesc Num;
- FormatNode *format;
- text *result, *result_tmp;
- int flag=0;
- int len=0, plen=0, sign=0;
- char *numstr, *orgnum;
+ NUMDesc Num;
+ FormatNode *format;
+ text *result,
+ *result_tmp;
+ int flag = 0;
+ int len = 0,
+ plen = 0,
+ sign = 0;
+ char *numstr,
+ *orgnum;
NUM_TOCHAR_prepare;
@@ -3655,41 +4039,51 @@ int4_to_char(int32 value, text *fmt)
* On DateType depend part (int32)
* ----------
*/
- if (IS_ROMAN(&Num)) {
- numstr = orgnum = int_to_roman( value );
-
- } else {
- if (IS_MULTI(&Num)) {
- orgnum = int4out(int4mul(value, (int32) pow( (double)10, (double) Num.multi)));
+ if (IS_ROMAN(&Num))
+ {
+ numstr = orgnum = int_to_roman(value);
+
+ }
+ else
+ {
+ if (IS_MULTI(&Num))
+ {
+ orgnum = int4out(int4mul(value, (int32) pow((double) 10, (double) Num.multi)));
Num.pre += Num.multi;
- } else
+ }
+ else
orgnum = int4out(value);
- len = strlen(orgnum);
-
- if (*orgnum == '-') { /* < 0 */
+ len = strlen(orgnum);
+
+ if (*orgnum == '-')
+ { /* < 0 */
sign = '-';
- --len;
- } else
+ --len;
+ }
+ else
sign = '+';
-
- if (Num.post) {
- int i;
-
- numstr = palloc( len + 1 + Num.post );
+
+ if (Num.post)
+ {
+ int i;
+
+ numstr = palloc(len + 1 + Num.post);
strcpy(numstr, orgnum + (*orgnum == '-' ? 1 : 0));
- *(numstr + len) = '.';
-
- for(i=len+1; i<=Num.post+len+1; i++)
- *(numstr+i) = '0';
- *(numstr + Num.post + len + 1) = '\0';
+ *(numstr + len) = '.';
+
+ for (i = len + 1; i <= Num.post + len + 1; i++)
+ *(numstr + i) = '0';
+ *(numstr + Num.post + len + 1) = '\0';
pfree(orgnum);
- orgnum = numstr;
- } else
+ orgnum = numstr;
+ }
+ else
numstr = orgnum + (*orgnum == '-' ? 1 : 0);
-
- if (Num.pre > len)
- plen = Num.pre - len;
- else if (len > Num.pre) {
+
+ if (Num.pre > len)
+ plen = Num.pre - len;
+ else if (len > Num.pre)
+ {
fill_str(numstr, '#', Num.pre);
*(numstr + Num.pre) = '.';
fill_str(numstr + 1 + Num.pre, '#', Num.post);
@@ -3703,16 +4097,20 @@ int4_to_char(int32 value, text *fmt)
/* ---------------
* INT8 to_char()
* ---------------
- */
+ */
text *
int8_to_char(int64 *value, text *fmt)
{
- NUMDesc Num;
- FormatNode *format;
- text *result, *result_tmp;
- int flag=0;
- int len=0, plen=0, sign=0;
- char *numstr, *orgnum;
+ NUMDesc Num;
+ FormatNode *format;
+ text *result,
+ *result_tmp;
+ int flag = 0;
+ int len = 0,
+ plen = 0,
+ sign = 0;
+ char *numstr,
+ *orgnum;
NUM_TOCHAR_prepare;
@@ -3720,48 +4118,59 @@ int8_to_char(int64 *value, text *fmt)
* On DateType depend part (int32)
* ----------
*/
- if (IS_ROMAN(&Num)) {
- numstr = orgnum = int_to_roman( int84( value ));
-
- } else {
- if (IS_MULTI(&Num)) {
- double multi = pow( (double)10, (double) Num.multi);
- orgnum = int8out( int8mul(value, dtoi8( (float64) &multi )));
+ if (IS_ROMAN(&Num))
+ {
+ numstr = orgnum = int_to_roman(int84(value));
+
+ }
+ else
+ {
+ if (IS_MULTI(&Num))
+ {
+ double multi = pow((double) 10, (double) Num.multi);
+
+ orgnum = int8out(int8mul(value, dtoi8((float64) &multi)));
Num.pre += Num.multi;
- } else
+ }
+ else
orgnum = int8out(value);
- len = strlen(orgnum);
-
- if (*orgnum == '-') { /* < 0 */
+ len = strlen(orgnum);
+
+ if (*orgnum == '-')
+ { /* < 0 */
sign = '-';
- --len;
- } else
+ --len;
+ }
+ else
sign = '+';
-
- if (Num.post) {
- int i;
-
- numstr = palloc( len + 1 + Num.post );
+
+ if (Num.post)
+ {
+ int i;
+
+ numstr = palloc(len + 1 + Num.post);
strcpy(numstr, orgnum + (*orgnum == '-' ? 1 : 0));
- *(numstr + len) = '.';
-
- for(i=len+1; i<=Num.post+len+1; i++)
- *(numstr+i) = '0';
- *(numstr + Num.post + len + 1) = '\0';
+ *(numstr + len) = '.';
+
+ for (i = len + 1; i <= Num.post + len + 1; i++)
+ *(numstr + i) = '0';
+ *(numstr + Num.post + len + 1) = '\0';
pfree(orgnum);
- orgnum = numstr;
- } else
+ orgnum = numstr;
+ }
+ else
numstr = orgnum + (*orgnum == '-' ? 1 : 0);
-
- if (Num.pre > len)
- plen = Num.pre - len;
- else if (len > Num.pre) {
+
+ if (Num.pre > len)
+ plen = Num.pre - len;
+ else if (len > Num.pre)
+ {
fill_str(numstr, '#', Num.pre);
*(numstr + Num.pre) = '.';
fill_str(numstr + 1 + Num.pre, '#', Num.post);
- }
+ }
}
-
+
NUM_TOCHAR_finish;
return result;
}
@@ -3769,63 +4178,77 @@ int8_to_char(int64 *value, text *fmt)
/* -----------------
* FLOAT4 to_char()
* -----------------
- */
+ */
text *
float4_to_char(float32 value, text *fmt)
{
- NUMDesc Num;
- FormatNode *format;
- text *result, *result_tmp;
- int flag=0;
- int len=0, plen=0, sign=0;
- char *numstr, *orgnum, *p;
+ NUMDesc Num;
+ FormatNode *format;
+ text *result,
+ *result_tmp;
+ int flag = 0;
+ int len = 0,
+ plen = 0,
+ sign = 0;
+ char *numstr,
+ *orgnum,
+ *p;
NUM_TOCHAR_prepare;
- if (IS_ROMAN(&Num)) {
- numstr = orgnum = int_to_roman( (int) rint( *value ));
-
- } else {
- float32 val = value;
-
- if (IS_MULTI(&Num)) {
- float multi = pow( (double) 10, (double) Num.multi);
+ if (IS_ROMAN(&Num))
+ {
+ numstr = orgnum = int_to_roman((int) rint(*value));
+
+ }
+ else
+ {
+ float32 val = value;
+
+ if (IS_MULTI(&Num))
+ {
+ float multi = pow((double) 10, (double) Num.multi);
+
val = float4mul(value, (float32) &multi);
Num.pre += Num.multi;
- }
-
+ }
+
orgnum = (char *) palloc(MAXFLOATWIDTH + 1);
- len = sprintf(orgnum, "%.0f", fabs(*val));
+ len = sprintf(orgnum, "%.0f", fabs(*val));
if (Num.pre > len)
plen = Num.pre - len;
if (len >= FLT_DIG)
- Num.post = 0;
+ Num.post = 0;
else if (Num.post + len > FLT_DIG)
- Num.post = FLT_DIG - len;
+ Num.post = FLT_DIG - len;
sprintf(orgnum, "%.*f", Num.post, *val);
-
- if (*orgnum == '-') { /* < 0 */
+
+ if (*orgnum == '-')
+ { /* < 0 */
sign = '-';
- numstr = orgnum+1;
- } else {
+ numstr = orgnum + 1;
+ }
+ else
+ {
sign = '+';
numstr = orgnum;
}
if ((p = strchr(numstr, '.')))
- len = p - numstr;
- else
+ len = p - numstr;
+ else
len = strlen(numstr);
-
- if (Num.pre > len)
+
+ if (Num.pre > len)
plen = Num.pre - len;
-
- else if (len > Num.pre) {
+
+ else if (len > Num.pre)
+ {
fill_str(numstr, '#', Num.pre);
*(numstr + Num.pre) = '.';
fill_str(numstr + 1 + Num.pre, '#', Num.post);
- }
+ }
}
-
+
NUM_TOCHAR_finish;
return result;
}
@@ -3833,62 +4256,76 @@ float4_to_char(float32 value, text *fmt)
/* -----------------
* FLOAT8 to_char()
* -----------------
- */
+ */
text *
float8_to_char(float64 value, text *fmt)
{
- NUMDesc Num;
- FormatNode *format;
- text *result, *result_tmp;
- int flag=0;
- int len=0, plen=0, sign=0;
- char *numstr, *orgnum, *p;
+ NUMDesc Num;
+ FormatNode *format;
+ text *result,
+ *result_tmp;
+ int flag = 0;
+ int len = 0,
+ plen = 0,
+ sign = 0;
+ char *numstr,
+ *orgnum,
+ *p;
NUM_TOCHAR_prepare;
- if (IS_ROMAN(&Num)) {
- numstr = orgnum = int_to_roman( (int) rint( *value ));
-
- } else {
- float64 val = value;
-
- if (IS_MULTI(&Num)) {
- double multi = pow( (double) 10, (double) Num.multi);
+ if (IS_ROMAN(&Num))
+ {
+ numstr = orgnum = int_to_roman((int) rint(*value));
+
+ }
+ else
+ {
+ float64 val = value;
+
+ if (IS_MULTI(&Num))
+ {
+ double multi = pow((double) 10, (double) Num.multi);
+
val = float8mul(value, (float64) &multi);
Num.pre += Num.multi;
- }
+ }
orgnum = (char *) palloc(MAXDOUBLEWIDTH + 1);
- len = sprintf(orgnum, "%.0f", fabs(*val));
+ len = sprintf(orgnum, "%.0f", fabs(*val));
if (Num.pre > len)
plen = Num.pre - len;
if (len >= DBL_DIG)
- Num.post = 0;
+ Num.post = 0;
else if (Num.post + len > DBL_DIG)
- Num.post = DBL_DIG - len;
+ Num.post = DBL_DIG - len;
sprintf(orgnum, "%.*f", Num.post, *val);
-
- if (*orgnum == '-') { /* < 0 */
+
+ if (*orgnum == '-')
+ { /* < 0 */
sign = '-';
- numstr = orgnum+1;
- } else {
+ numstr = orgnum + 1;
+ }
+ else
+ {
sign = '+';
numstr = orgnum;
}
if ((p = strchr(numstr, '.')))
- len = p - numstr;
+ len = p - numstr;
else
len = strlen(numstr);
-
- if (Num.pre > len)
+
+ if (Num.pre > len)
plen = Num.pre - len;
-
- else if (len > Num.pre) {
+
+ else if (len > Num.pre)
+ {
fill_str(numstr, '#', Num.pre);
*(numstr + Num.pre) = '.';
fill_str(numstr + 1 + Num.pre, '#', Num.post);
- }
+ }
}
-
+
NUM_TOCHAR_finish;
return result;
}
diff --git a/src/backend/utils/adt/geo_ops.c b/src/backend/utils/adt/geo_ops.c
index 9561f9e875d..0e8bb4405b2 100644
--- a/src/backend/utils/adt/geo_ops.c
+++ b/src/backend/utils/adt/geo_ops.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/geo_ops.c,v 1.49 2000/03/14 23:06:36 thomas Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/geo_ops.c,v 1.50 2000/04/12 17:15:50 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -877,7 +877,7 @@ line_construct_pm(Point *pt, double m)
/* use "mx - y + yinter = 0" */
result->A = m;
result->B = -1.0;
- if (m==DBL_MAX)
+ if (m == DBL_MAX)
result->C = pt->y;
else
result->C = pt->y - m * pt->x;
diff --git a/src/backend/utils/adt/geo_selfuncs.c b/src/backend/utils/adt/geo_selfuncs.c
index 95e594ea0ef..b2a281f638d 100644
--- a/src/backend/utils/adt/geo_selfuncs.c
+++ b/src/backend/utils/adt/geo_selfuncs.c
@@ -9,7 +9,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/geo_selfuncs.c,v 1.13 2000/02/17 03:39:42 tgl Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/geo_selfuncs.c,v 1.14 2000/04/12 17:15:50 momjian Exp $
*
* XXX These are totally bogus. Perhaps someone will make them do
* something reasonable, someday.
@@ -34,7 +34,7 @@
* In general, rtrees need to search multiple subtrees in order to guarantee
* that all occurrences of the same key have been found. Because of this,
* the estimated cost for scanning the index ought to be higher than the
- * output selectivity would indicate. rtcostestimate(), over in selfuncs.c,
+ * output selectivity would indicate. rtcostestimate(), over in selfuncs.c,
* ought to be adjusted accordingly --- but until we can generate somewhat
* realistic numbers here, it hardly matters...
*/
diff --git a/src/backend/utils/adt/int.c b/src/backend/utils/adt/int.c
index 7eb7783274c..242e9c54011 100644
--- a/src/backend/utils/adt/int.c
+++ b/src/backend/utils/adt/int.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/int.c,v 1.35 2000/03/14 23:06:36 thomas Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/int.c,v 1.36 2000/04/12 17:15:50 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -88,7 +88,7 @@ int2vectorin(char *intString)
result = (int16 *) palloc(sizeof(int16[INDEX_MAX_KEYS]));
- for (slot=0; *intString && slot < INDEX_MAX_KEYS; slot++)
+ for (slot = 0; *intString && slot < INDEX_MAX_KEYS; slot++)
{
if (sscanf(intString, "%hd", &result[slot]) != 1)
break;
@@ -100,7 +100,7 @@ int2vectorin(char *intString)
while (*intString && isspace(*intString))
intString++;
if (*intString)
- elog(ERROR,"int2vector value has too many values");
+ elog(ERROR, "int2vector value has too many values");
while (slot < INDEX_MAX_KEYS)
result[slot++] = 0;
@@ -113,7 +113,8 @@ int2vectorin(char *intString)
char *
int2vectorout(int16 *int2Array)
{
- int num, maxnum;
+ int num,
+ maxnum;
char *rp;
char *result;
@@ -126,12 +127,12 @@ int2vectorout(int16 *int2Array)
}
/* find last non-zero value in vector */
- for (maxnum = INDEX_MAX_KEYS-1; maxnum >= 0; maxnum--)
+ for (maxnum = INDEX_MAX_KEYS - 1; maxnum >= 0; maxnum--)
if (int2Array[maxnum] != 0)
break;
/* assumes sign, 5 digits, ' ' */
- rp = result = (char *) palloc((maxnum+1) * 7 + 1);
+ rp = result = (char *) palloc((maxnum + 1) * 7 + 1);
for (num = 0; num <= maxnum; num++)
{
if (num != 0)
@@ -694,13 +695,13 @@ int2fac(int16 arg1)
int32
int4abs(int32 arg1)
{
- return ((arg1 < 0)? -arg1: arg1);
+ return ((arg1 < 0) ? -arg1 : arg1);
}
int16
int2abs(int16 arg1)
{
- return ((arg1 < 0)? -arg1: arg1);
+ return ((arg1 < 0) ? -arg1 : arg1);
}
int16
diff --git a/src/backend/utils/adt/int8.c b/src/backend/utils/adt/int8.c
index 27b0f42c97f..018352df1ad 100644
--- a/src/backend/utils/adt/int8.c
+++ b/src/backend/utils/adt/int8.c
@@ -71,10 +71,10 @@ int8in(char *str)
elog(ERROR, "Bad int8 external representation \"%s\"", str);
while (*ptr && isdigit(*ptr)) /* process digits */
{
- int64 newtmp = tmp * 10 + (*ptr++ - '0');
+ int64 newtmp = tmp * 10 + (*ptr++ - '0');
if ((newtmp / 10) != tmp) /* overflow? */
- elog(ERROR,"int8 value out of range: \"%s\"", str);
+ elog(ERROR, "int8 value out of range: \"%s\"", str);
tmp = newtmp;
}
if (*ptr) /* trailing junk? */
@@ -372,7 +372,7 @@ int8abs(int64 *arg1)
result = palloc(sizeof(*result));
- *result = ((*arg1 < 0)? -*arg1: *arg1);
+ *result = ((*arg1 < 0) ? -*arg1 : *arg1);
return result;
}
@@ -400,7 +400,7 @@ int64 *
int8fac(int64 *arg1)
{
int64 *result;
- int64 i;
+ int64 i;
if (!PointerIsValid(arg1))
return NULL;
@@ -581,7 +581,7 @@ int84(int64 *val)
#if NOT_USED
int64 *
-int2vector (int16 val)
+int2vector (int16 val)
{
int64 *result;
diff --git a/src/backend/utils/adt/like.c b/src/backend/utils/adt/like.c
index 2522a7471b4..3ec148bacb4 100644
--- a/src/backend/utils/adt/like.c
+++ b/src/backend/utils/adt/like.c
@@ -11,7 +11,7 @@
* Portions Copyright (c) 1994, Regents of the University of California
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/like.c,v 1.33 2000/01/26 05:57:14 momjian Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/like.c,v 1.34 2000/04/12 17:15:50 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -149,7 +149,7 @@ textnlike(struct varlena * s, struct varlena * p)
static int
DoMatch(pg_wchar * text, pg_wchar * p)
{
- for (; *p && *text; text++, p++)
+ for (; *p && *text; text ++, p++)
{
switch (*p)
{
@@ -158,7 +158,7 @@ DoMatch(pg_wchar * text, pg_wchar * p)
p++;
/* FALLTHROUGH */
default:
- if (*text != *p)
+ if (*text !=*p)
return LIKE_FALSE;
break;
case '_':
@@ -172,29 +172,37 @@ DoMatch(pg_wchar * text, pg_wchar * p)
/* Trailing percent matches everything. */
if (*p == '\0')
return LIKE_TRUE;
- /* Otherwise, scan for a text position at which we
- * can match the rest of the pattern.
+
+ /*
+ * Otherwise, scan for a text position at which we can
+ * match the rest of the pattern.
*/
- for (; *text; text++)
+ for (; *text; text ++)
{
- /* Optimization to prevent most recursion: don't recurse
- * unless first pattern char might match this text char.
+
+ /*
+ * Optimization to prevent most recursion: don't
+ * recurse unless first pattern char might match this
+ * text char.
*/
if (*text == *p || *p == '\\' || *p == '_')
{
- int matched = DoMatch(text, p);
+ int matched = DoMatch(text, p);
+
if (matched != LIKE_FALSE)
- return matched; /* TRUE or ABORT */
+ return matched; /* TRUE or ABORT */
}
}
- /* End of text with no match, so no point in trying later
+
+ /*
+ * End of text with no match, so no point in trying later
* places to start matching this pattern.
*/
return LIKE_ABORT;
}
}
- if (*text != '\0')
+ if (*text !='\0')
return LIKE_FALSE; /* end of pattern, but not of text */
/* End of input string. Do we have matching pattern remaining? */
@@ -202,8 +210,10 @@ DoMatch(pg_wchar * text, pg_wchar * p)
p++;
if (*p == '\0')
return LIKE_TRUE;
- /* End of text with no match, so no point in trying later
- * places to start matching this pattern.
+
+ /*
+ * End of text with no match, so no point in trying later places to
+ * start matching this pattern.
*/
return LIKE_ABORT;
}
diff --git a/src/backend/utils/adt/lztext.c b/src/backend/utils/adt/lztext.c
index 4cc6667e305..a5d72ba9f26 100644
--- a/src/backend/utils/adt/lztext.c
+++ b/src/backend/utils/adt/lztext.c
@@ -1,7 +1,7 @@
/* ----------
* lztext.c -
*
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/Attic/lztext.c,v 1.5 1999/12/28 13:40:48 wieck Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/Attic/lztext.c,v 1.6 2000/04/12 17:15:50 momjian Exp $
*
* Text type with internal LZ compressed representation. Uses the
* standard PostgreSQL compression method.
@@ -34,10 +34,10 @@
lztext *
lztextin(char *str)
{
- lztext *result;
- int32 rawsize;
- lztext *tmp;
- int tmp_size;
+ lztext *result;
+ int32 rawsize;
+ lztext *tmp;
+ int tmp_size;
/* ----------
* Handle NULL
@@ -66,11 +66,11 @@ lztextin(char *str)
* sequence.
* ----------
*/
- if (tmp_size - tmp->varsize < 256 ||
- tmp_size - tmp->varsize < tmp_size / 4)
- {
+ if (tmp_size - tmp->varsize < 256 ||
+ tmp_size - tmp->varsize < tmp_size / 4)
result = tmp;
- } else {
+ else
+ {
result = (lztext *) palloc(tmp->varsize);
memcpy(result, tmp, tmp->varsize);
pfree(tmp);
@@ -89,7 +89,7 @@ lztextin(char *str)
char *
lztextout(lztext *lz)
{
- char *result;
+ char *result;
/* ----------
* Handle NULL
@@ -137,10 +137,12 @@ int32
lztextlen(lztext *lz)
{
#ifdef MULTIBYTE
- unsigned char *s1,*s2;
- int len;
- int l;
- int wl;
+ unsigned char *s1,
+ *s2;
+ int len;
+ int l;
+ int wl;
+
#endif
/* ----------
* Handle NULL
@@ -151,7 +153,7 @@ lztextlen(lztext *lz)
#ifdef MULTIBYTE
len = 0;
- s1 = s2 = (unsigned char *)lztextout(lz);
+ s1 = s2 = (unsigned char *) lztextout(lz);
l = PGLZ_RAW_SIZE(lz);
while (l > 0)
{
@@ -160,7 +162,7 @@ lztextlen(lztext *lz)
s1 += wl;
len++;
}
- pfree((char *)s2);
+ pfree((char *) s2);
return (len);
#else
/* ----------
@@ -206,11 +208,11 @@ lztextoctetlen(lztext *lz)
lztext *
text_lztext(text *txt)
{
- lztext *result;
- int32 rawsize;
- lztext *tmp;
- int tmp_size;
- char *str;
+ lztext *result;
+ int32 rawsize;
+ lztext *tmp;
+ int tmp_size;
+ char *str;
/* ----------
* Handle NULL
@@ -223,8 +225,8 @@ text_lztext(text *txt)
* Determine input size and eventually tuple size
* ----------
*/
- rawsize = VARSIZE(txt) - VARHDRSZ;
- str = VARDATA(txt);
+ rawsize = VARSIZE(txt) - VARHDRSZ;
+ str = VARDATA(txt);
tmp_size = PGLZ_MAX_OUTPUT(rawsize);
/* ----------
@@ -240,11 +242,11 @@ text_lztext(text *txt)
* sequence.
* ----------
*/
- if (tmp_size - tmp->varsize < 256 ||
- tmp_size - tmp->varsize < tmp_size / 4)
- {
+ if (tmp_size - tmp->varsize < 256 ||
+ tmp_size - tmp->varsize < tmp_size / 4)
result = tmp;
- } else {
+ else
+ {
result = (lztext *) palloc(tmp->varsize);
memcpy(result, tmp, tmp->varsize);
pfree(tmp);
@@ -303,12 +305,12 @@ lztext_cmp(lztext *lz1, lztext *lz2)
{
#ifdef USE_LOCALE
- char *cp1;
- char *cp2;
- int result;
+ char *cp1;
+ char *cp2;
+ int result;
if (lz1 == NULL || lz2 == NULL)
- return (int32)0;
+ return (int32) 0;
cp1 = lztextout(lz1);
cp2 = lztextout(lz2);
@@ -320,21 +322,21 @@ lztext_cmp(lztext *lz1, lztext *lz2)
return result;
-#else /* !USE_LOCALE */
+#else /* !USE_LOCALE */
- PGLZ_DecompState ds1;
- PGLZ_DecompState ds2;
- int c1;
- int c2;
- int32 result = (int32)0;
+ PGLZ_DecompState ds1;
+ PGLZ_DecompState ds2;
+ int c1;
+ int c2;
+ int32 result = (int32) 0;
if (lz1 == NULL || lz2 == NULL)
- return (int32)0;
+ return (int32) 0;
pglz_decomp_init(&ds1, lz1);
pglz_decomp_init(&ds2, lz2);
- for(;;)
+ for (;;)
{
c1 = pglz_decomp_getchar(&ds1);
c2 = pglz_decomp_getchar(&ds2);
@@ -342,17 +344,17 @@ lztext_cmp(lztext *lz1, lztext *lz2)
if (c1 == EOF)
{
if (c2 != EOF)
- result = (int32)-1;
+ result = (int32) -1;
break;
- } else {
+ }
+ else
+ {
if (c2 == EOF)
- {
- result = (int32)1;
- }
+ result = (int32) 1;
}
if (c1 != c2)
{
- result = (int32)(c1 - c2);
+ result = (int32) (c1 - c2);
break;
}
}
@@ -362,7 +364,7 @@ lztext_cmp(lztext *lz1, lztext *lz2)
return result;
-#endif /* USE_LOCALE */
+#endif /* USE_LOCALE */
}
@@ -379,7 +381,7 @@ lztext_eq(lztext *lz1, lztext *lz2)
if (lz1 == NULL || lz2 == NULL)
return false;
- return (bool)(lztext_cmp(lz1, lz2) == 0);
+ return (bool) (lztext_cmp(lz1, lz2) == 0);
}
@@ -389,7 +391,7 @@ lztext_ne(lztext *lz1, lztext *lz2)
if (lz1 == NULL || lz2 == NULL)
return false;
- return (bool)(lztext_cmp(lz1, lz2) != 0);
+ return (bool) (lztext_cmp(lz1, lz2) != 0);
}
@@ -399,7 +401,7 @@ lztext_gt(lztext *lz1, lztext *lz2)
if (lz1 == NULL || lz2 == NULL)
return false;
- return (bool)(lztext_cmp(lz1, lz2) > 0);
+ return (bool) (lztext_cmp(lz1, lz2) > 0);
}
@@ -409,7 +411,7 @@ lztext_ge(lztext *lz1, lztext *lz2)
if (lz1 == NULL || lz2 == NULL)
return false;
- return (bool)(lztext_cmp(lz1, lz2) >= 0);
+ return (bool) (lztext_cmp(lz1, lz2) >= 0);
}
@@ -419,7 +421,7 @@ lztext_lt(lztext *lz1, lztext *lz2)
if (lz1 == NULL || lz2 == NULL)
return false;
- return (bool)(lztext_cmp(lz1, lz2) < 0);
+ return (bool) (lztext_cmp(lz1, lz2) < 0);
}
@@ -429,7 +431,5 @@ lztext_le(lztext *lz1, lztext *lz2)
if (lz1 == NULL || lz2 == NULL)
return false;
- return (bool)(lztext_cmp(lz1, lz2) <= 0);
+ return (bool) (lztext_cmp(lz1, lz2) <= 0);
}
-
-
diff --git a/src/backend/utils/adt/nabstime.c b/src/backend/utils/adt/nabstime.c
index 28a94f5e168..ef18ad02793 100644
--- a/src/backend/utils/adt/nabstime.c
+++ b/src/backend/utils/adt/nabstime.c
@@ -9,7 +9,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/nabstime.c,v 1.66 2000/02/16 17:24:48 thomas Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/nabstime.c,v 1.67 2000/04/12 17:15:50 momjian Exp $
*
* NOTES
*
@@ -47,6 +47,7 @@
#if 0
static AbsoluteTime tm2abstime(struct tm * tm, int tz);
+
#endif
@@ -101,6 +102,7 @@ static int sec_tab[] = {
1, 1, 60, 60,
3600, 3600, 86400, 86400, 604800, 604800,
2592000, 2592000, 31536000, 31536000};
+
#endif
/*
@@ -246,8 +248,11 @@ abstime2tm(AbsoluteTime time, int *tzp, struct tm * tm, char *tzn)
/* XXX FreeBSD man pages indicate that this should work - tgl 97/04/23 */
if (tzn != NULL)
{
- /* Copy no more than MAXTZLEN bytes of timezone to tzn, in case it
- contains an error message, which doesn't fit in the buffer */
+
+ /*
+ * Copy no more than MAXTZLEN bytes of timezone to tzn, in case it
+ * contains an error message, which doesn't fit in the buffer
+ */
strncpy(tzn, tm->tm_zone, MAXTZLEN);
if (strlen(tm->tm_zone) > MAXTZLEN)
{
@@ -264,8 +269,11 @@ abstime2tm(AbsoluteTime time, int *tzp, struct tm * tm, char *tzn)
#endif
if (tzn != NULL)
{
- /* Copy no more than MAXTZLEN bytes of timezone to tzn, in case it
- contains an error message, which doesn't fit in the buffer */
+
+ /*
+ * Copy no more than MAXTZLEN bytes of timezone to tzn, in case it
+ * contains an error message, which doesn't fit in the buffer
+ */
strncpy(tzn, tzname[tm->tm_isdst], MAXTZLEN);
if (strlen(tzname[tm->tm_isdst]) > MAXTZLEN)
{
@@ -634,10 +642,10 @@ timestamp_abstime(Timestamp *timestamp)
/* abstime_timestamp()
* Convert abstime to timestamp.
*/
-Timestamp *
+Timestamp *
abstime_timestamp(AbsoluteTime abstime)
{
- Timestamp *result;
+ Timestamp *result;
if (!PointerIsValid(result = palloc(sizeof(Timestamp))))
elog(ERROR, "Unable to allocate space to convert abstime to timestamp");
diff --git a/src/backend/utils/adt/name.c b/src/backend/utils/adt/name.c
index 48223b25977..630070ce3b3 100644
--- a/src/backend/utils/adt/name.c
+++ b/src/backend/utils/adt/name.c
@@ -12,7 +12,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/name.c,v 1.27 2000/01/26 05:57:14 momjian Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/name.c,v 1.28 2000/04/12 17:15:50 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -149,7 +149,8 @@ namecpy(Name n1, Name n2)
int
namecat(Name n1, Name n2)
{
- return namestrcat(n1, NameStr(*n2)); /* n2 can't be any longer than n1 */
+ return namestrcat(n1, NameStr(*n2)); /* n2 can't be any longer
+ * than n1 */
}
#endif
diff --git a/src/backend/utils/adt/network.c b/src/backend/utils/adt/network.c
index 8ee70ec276f..7e1a9ead666 100644
--- a/src/backend/utils/adt/network.c
+++ b/src/backend/utils/adt/network.c
@@ -3,7 +3,7 @@
* is for IP V4 CIDR notation, but prepared for V6: just
* add the necessary bits where the comments indicate.
*
- * $Id: network.c,v 1.20 2000/03/08 01:44:37 momjian Exp $
+ * $Id: network.c,v 1.21 2000/04/12 17:15:50 momjian Exp $
* Jon Postel RIP 16 Oct 1998
*/
@@ -448,8 +448,8 @@ network_netmask(inet *ip)
if (ip_family(ip) == AF_INET)
{
/* It's an IP V4 address: */
- int addr = htonl(ip_bits(ip) ?
- (-1 << (32 - ip_bits(ip))) & 0xffffffff : 0x00000000);
+ int addr = htonl(ip_bits(ip) ?
+ (-1 << (32 - ip_bits(ip))) & 0xffffffff : 0x00000000);
if (inet_net_ntop(AF_INET, &addr, 32, tmp, sizeof(tmp)) == NULL)
elog(ERROR, "unable to print netmask (%s)", strerror(errno));
diff --git a/src/backend/utils/adt/numeric.c b/src/backend/utils/adt/numeric.c
index 4d46992e403..36e333e1217 100644
--- a/src/backend/utils/adt/numeric.c
+++ b/src/backend/utils/adt/numeric.c
@@ -5,7 +5,7 @@
*
* 1998 Jan Wieck
*
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/numeric.c,v 1.26 2000/03/13 02:31:13 tgl Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/numeric.c,v 1.27 2000/04/12 17:15:50 momjian Exp $
*
* ----------
*/
@@ -59,8 +59,8 @@
* *after* the decimal point. Scales are always >= 0.)
*
* buf points at the physical start of the palloc'd digit buffer for the
- * NumericVar. digits points at the first digit in actual use (the one
- * with the specified weight). We normally leave an unused byte or two
+ * NumericVar. digits points at the first digit in actual use (the one
+ * with the specified weight). We normally leave an unused byte or two
* (preset to zeroes) between buf and digits, so that there is room to store
* a carry out of the top digit without special pushups. We just need to
* decrement digits (and increment weight) to make room for the carry digit.
@@ -77,11 +77,13 @@ typedef unsigned char NumericDigit;
typedef struct NumericVar
{
- int ndigits; /* number of digits in digits[] - can be 0! */
+ int ndigits; /* number of digits in digits[] - can be
+ * 0! */
int weight; /* weight of first digit */
int rscale; /* result scale */
int dscale; /* display scale */
- int sign; /* NUMERIC_POS, NUMERIC_NEG, or NUMERIC_NAN */
+ int sign; /* NUMERIC_POS, NUMERIC_NEG, or
+ * NUMERIC_NAN */
NumericDigit *buf; /* start of palloc'd space for digits[] */
NumericDigit *digits; /* decimal digits */
} NumericVar;
@@ -122,13 +124,14 @@ static NumericVar const_nan =
#ifdef NUMERIC_DEBUG
static void dump_numeric(char *str, Numeric num);
static void dump_var(char *str, NumericVar *var);
+
#else
#define dump_numeric(s,n)
#define dump_var(s,v)
#endif
#define digitbuf_alloc(size) ((NumericDigit *) palloc(size))
-#define digitbuf_free(buf) \
+#define digitbuf_free(buf) \
do { \
if ((buf) != NULL) \
pfree(buf); \
@@ -535,16 +538,16 @@ numeric_round(Numeric num, int32 scale)
if (i < arg.ndigits)
{
- /* If i = 0, the value loses all digits, but could round up if its
- * first digit is more than 4. If i < 0 the result must be 0.
+
+ /*
+ * If i = 0, the value loses all digits, but could round up if its
+ * first digit is more than 4. If i < 0 the result must be 0.
*/
if (i < 0)
- {
arg.ndigits = 0;
- }
else
{
- int carry = (arg.digits[i] > 4) ? 1 : 0;
+ int carry = (arg.digits[i] > 4) ? 1 : 0;
arg.ndigits = i;
@@ -557,7 +560,7 @@ numeric_round(Numeric num, int32 scale)
if (i < 0)
{
- Assert(i == -1); /* better not have added more than 1 digit */
+ Assert(i == -1);/* better not have added more than 1 digit */
Assert(arg.digits > arg.buf);
arg.digits--;
arg.ndigits++;
@@ -728,10 +731,10 @@ numeric_cmp(Numeric num1, Numeric num2)
NumericVar arg2;
if (num1 == NULL || num2 == NULL)
- return (int32)0;
+ return (int32) 0;
if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
- return (int32)0;
+ return (int32) 0;
init_var(&arg1);
init_var(&arg2);
@@ -744,7 +747,7 @@ numeric_cmp(Numeric num1, Numeric num2)
free_var(&arg1);
free_var(&arg2);
- return (int32)((result == 0) ? 0 : ((result < 0) ? -1 : 1));
+ return (int32) ((result == 0) ? 0 : ((result < 0) ? -1 : 1));
}
@@ -1742,7 +1745,7 @@ numeric_int4(Numeric num)
init_var(&x);
set_var_from_num(num, &x);
- str = get_str_from_var(&x, 0); /* dscale = 0 produces rounding */
+ str = get_str_from_var(&x, 0); /* dscale = 0 produces rounding */
free_var(&x);
@@ -1793,7 +1796,7 @@ numeric_int8(Numeric num)
init_var(&x);
set_var_from_num(num, &x);
- str = get_str_from_var(&x, 0); /* dscale = 0 produces rounding */
+ str = get_str_from_var(&x, 0); /* dscale = 0 produces rounding */
free_var(&x);
@@ -1844,7 +1847,7 @@ numeric_int2(Numeric num)
init_var(&x);
set_var_from_num(num, &x);
- str = get_str_from_var(&x, 0); /* dscale = 0 produces rounding */
+ str = get_str_from_var(&x, 0); /* dscale = 0 produces rounding */
free_var(&x);
@@ -2130,7 +2133,7 @@ set_var_from_str(char *str, NumericVar *dest)
cp++;
}
- if (! isdigit(*cp))
+ if (!isdigit(*cp))
elog(ERROR, "Bad numeric input format '%s'", str);
while (*cp)
@@ -2158,8 +2161,8 @@ set_var_from_str(char *str, NumericVar *dest)
/* Handle exponent, if any */
if (*cp == 'e' || *cp == 'E')
{
- long exponent;
- char *endptr;
+ long exponent;
+ char *endptr;
cp++;
exponent = strtol(cp, &endptr, 10);
@@ -2210,7 +2213,8 @@ set_var_from_num(Numeric num, NumericVar *dest)
int i;
int n;
- n = num->varlen - NUMERIC_HDRSZ; /* number of digit-pairs in packed fmt */
+ n = num->varlen - NUMERIC_HDRSZ; /* number of digit-pairs in packed
+ * fmt */
alloc_var(dest, n * 2);
@@ -2224,6 +2228,7 @@ set_var_from_num(Numeric num, NumericVar *dest)
for (i = 0; i < n; i++)
{
unsigned char digitpair = num->n_data[i];
+
*digit++ = (digitpair >> 4) & 0x0f;
*digit++ = digitpair & 0x0f;
}
@@ -2278,7 +2283,7 @@ get_str_from_var(NumericVar *var, int dscale)
i = dscale + var->weight + 1;
if (i >= 0 && var->ndigits > i)
{
- int carry = (var->digits[i] > 4) ? 1 : 0;
+ int carry = (var->digits[i] > 4) ? 1 : 0;
var->ndigits = i;
@@ -2421,6 +2426,7 @@ make_result(NumericVar *var)
while (j < n)
{
unsigned char digitpair = digit[j++] << 4;
+
if (j < n)
digitpair |= digit[j++];
result->n_data[i++] = digitpair;
@@ -2459,7 +2465,7 @@ apply_typmod(NumericVar *var, int32 typmod)
i = scale + var->weight + 1;
if (i >= 0 && var->ndigits > i)
{
- int carry = (var->digits[i] > 4) ? 1 : 0;
+ int carry = (var->digits[i] > 4) ? 1 : 0;
var->ndigits = i;
@@ -2494,7 +2500,7 @@ apply_typmod(NumericVar *var, int32 typmod)
if (var->weight >= maxweight)
{
/* Determine true weight; and check for all-zero result */
- int tweight = var->weight;
+ int tweight = var->weight;
for (i = 0; i < var->ndigits; i++)
{
@@ -2502,10 +2508,10 @@ apply_typmod(NumericVar *var, int32 typmod)
break;
tweight--;
}
-
+
if (tweight >= maxweight && i < var->ndigits)
elog(ERROR, "overflow on numeric "
- "ABS(value) >= 10^%d for field with precision %d scale %d",
+ "ABS(value) >= 10^%d for field with precision %d scale %d",
tweight, precision, scale);
}
@@ -2588,20 +2594,20 @@ add_var(NumericVar *var1, NumericVar *var2, NumericVar *result)
switch (cmp_abs(var1, var2))
{
case 0: /* ----------
- * ABS(var1) == ABS(var2)
- * result = ZERO
- * ----------
- */
+ * ABS(var1) == ABS(var2)
+ * result = ZERO
+ * ----------
+ */
zero_var(result);
result->rscale = MAX(var1->rscale, var2->rscale);
result->dscale = MAX(var1->dscale, var2->dscale);
break;
case 1: /* ----------
- * ABS(var1) > ABS(var2)
- * result = +(ABS(var1) - ABS(var2))
- * ----------
- */
+ * ABS(var1) > ABS(var2)
+ * result = +(ABS(var1) - ABS(var2))
+ * ----------
+ */
sub_abs(var1, var2, result);
result->sign = NUMERIC_POS;
break;
@@ -2629,20 +2635,20 @@ add_var(NumericVar *var1, NumericVar *var2, NumericVar *result)
switch (cmp_abs(var1, var2))
{
case 0: /* ----------
- * ABS(var1) == ABS(var2)
- * result = ZERO
- * ----------
- */
+ * ABS(var1) == ABS(var2)
+ * result = ZERO
+ * ----------
+ */
zero_var(result);
result->rscale = MAX(var1->rscale, var2->rscale);
result->dscale = MAX(var1->dscale, var2->dscale);
break;
case 1: /* ----------
- * ABS(var1) > ABS(var2)
- * result = -(ABS(var1) - ABS(var2))
- * ----------
- */
+ * ABS(var1) > ABS(var2)
+ * result = -(ABS(var1) - ABS(var2))
+ * ----------
+ */
sub_abs(var1, var2, result);
result->sign = NUMERIC_NEG;
break;
@@ -2707,20 +2713,20 @@ sub_var(NumericVar *var1, NumericVar *var2, NumericVar *result)
switch (cmp_abs(var1, var2))
{
case 0: /* ----------
- * ABS(var1) == ABS(var2)
- * result = ZERO
- * ----------
- */
+ * ABS(var1) == ABS(var2)
+ * result = ZERO
+ * ----------
+ */
zero_var(result);
result->rscale = MAX(var1->rscale, var2->rscale);
result->dscale = MAX(var1->dscale, var2->dscale);
break;
case 1: /* ----------
- * ABS(var1) > ABS(var2)
- * result = +(ABS(var1) - ABS(var2))
- * ----------
- */
+ * ABS(var1) > ABS(var2)
+ * result = +(ABS(var1) - ABS(var2))
+ * ----------
+ */
sub_abs(var1, var2, result);
result->sign = NUMERIC_POS;
break;
@@ -2748,20 +2754,20 @@ sub_var(NumericVar *var1, NumericVar *var2, NumericVar *result)
switch (cmp_abs(var1, var2))
{
case 0: /* ----------
- * ABS(var1) == ABS(var2)
- * result = ZERO
- * ----------
- */
+ * ABS(var1) == ABS(var2)
+ * result = ZERO
+ * ----------
+ */
zero_var(result);
result->rscale = MAX(var1->rscale, var2->rscale);
result->dscale = MAX(var1->dscale, var2->dscale);
break;
case 1: /* ----------
- * ABS(var1) > ABS(var2)
- * result = -(ABS(var1) - ABS(var2))
- * ----------
- */
+ * ABS(var1) > ABS(var2)
+ * result = -(ABS(var1) - ABS(var2))
+ * ----------
+ */
sub_abs(var1, var2, result);
result->sign = NUMERIC_NEG;
break;
@@ -3054,7 +3060,7 @@ div_var(NumericVar *var1, NumericVar *var2, NumericVar *result)
result->ndigits = ri + 1;
if (ri == res_ndigits + 1)
{
- int carry = (res_digits[ri] > 4) ? 1 : 0;
+ int carry = (res_digits[ri] > 4) ? 1 : 0;
result->ndigits = ri;
res_digits[ri] = 0;
diff --git a/src/backend/utils/adt/numutils.c b/src/backend/utils/adt/numutils.c
index 4e6d9a6ac4a..681a78baa85 100644
--- a/src/backend/utils/adt/numutils.c
+++ b/src/backend/utils/adt/numutils.c
@@ -11,7 +11,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/numutils.c,v 1.39 2000/01/26 05:57:14 momjian Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/numutils.c,v 1.40 2000/04/12 17:15:51 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -84,7 +84,7 @@ pg_atoi(char *s, int size, int c)
errno = ERANGE;
elog(ERROR, "pg_atoi: error reading \"%s\": %m", s);
}
-#endif /* HAVE_LONG_INT_64 */
+#endif /* HAVE_LONG_INT_64 */
break;
case sizeof(int16):
if (l < SHRT_MIN)
diff --git a/src/backend/utils/adt/oid.c b/src/backend/utils/adt/oid.c
index b7d1e2c03d3..96640af91e5 100644
--- a/src/backend/utils/adt/oid.c
+++ b/src/backend/utils/adt/oid.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/oid.c,v 1.33 2000/01/26 05:57:14 momjian Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/oid.c,v 1.34 2000/04/12 17:15:51 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -39,7 +39,7 @@ oidvectorin(char *oidString)
result = (Oid *) palloc(sizeof(Oid[INDEX_MAX_KEYS]));
- for (slot=0; *oidString && slot < INDEX_MAX_KEYS; slot++)
+ for (slot = 0; *oidString && slot < INDEX_MAX_KEYS; slot++)
{
if (sscanf(oidString, "%u", &result[slot]) != 1)
break;
@@ -51,7 +51,7 @@ oidvectorin(char *oidString)
while (*oidString && isspace(*oidString))
oidString++;
if (*oidString)
- elog(ERROR,"oidvector value has too many values");
+ elog(ERROR, "oidvector value has too many values");
while (slot < INDEX_MAX_KEYS)
result[slot++] = 0;
@@ -64,7 +64,8 @@ oidvectorin(char *oidString)
char *
oidvectorout(Oid *oidArray)
{
- int num, maxnum;
+ int num,
+ maxnum;
char *rp;
char *result;
@@ -77,12 +78,12 @@ oidvectorout(Oid *oidArray)
}
/* find last non-zero value in vector */
- for (maxnum = INDEX_MAX_KEYS-1; maxnum >= 0; maxnum--)
+ for (maxnum = INDEX_MAX_KEYS - 1; maxnum >= 0; maxnum--)
if (oidArray[maxnum] != 0)
break;
/* assumes sign, 10 digits, ' ' */
- rp = result = (char *) palloc((maxnum+1) * 12 + 1);
+ rp = result = (char *) palloc((maxnum + 1) * 12 + 1);
for (num = 0; num <= maxnum; num++)
{
if (num != 0)
diff --git a/src/backend/utils/adt/oracle_compat.c b/src/backend/utils/adt/oracle_compat.c
index 41e2563f3b0..522e6c7bce4 100644
--- a/src/backend/utils/adt/oracle_compat.c
+++ b/src/backend/utils/adt/oracle_compat.c
@@ -1,7 +1,7 @@
/*
* Edmund Mergl <E.Mergl@bawue.de>
*
- * $Id: oracle_compat.c,v 1.23 2000/04/07 13:39:41 thomas Exp $
+ * $Id: oracle_compat.c,v 1.24 2000/04/12 17:15:51 momjian Exp $
*
*/
@@ -466,10 +466,16 @@ rtrim(text *string, text *set)
text *
translate(text *string, text *from, text *to)
{
- text *result;
- char *from_ptr, *to_ptr;
- char *source, *target;
- int m, fromlen, tolen, retlen, i;
+ text *result;
+ char *from_ptr,
+ *to_ptr;
+ char *source,
+ *target;
+ int m,
+ fromlen,
+ tolen,
+ retlen,
+ i;
if (string == (text *) NULL ||
from == (text *) NULL ||
@@ -492,11 +498,11 @@ translate(text *string, text *from, text *to)
while (m-- > 0)
{
- char rep = *source++;
+ char rep = *source++;
for (i = 0; i < fromlen; i++)
{
- if (from_ptr[i] == rep)
+ if (from_ptr[i] == rep)
break;
}
if (i < fromlen)
@@ -521,6 +527,7 @@ translate(text *string, text *from, text *to)
}
VARSIZE(result) = retlen + VARHDRSZ;
+
/*
* There may be some wasted space in the result if deletions occurred,
* but it's not worth reallocating it; the function result probably
@@ -541,34 +548,35 @@ ascii(text *string)
return 0;
return ((int) *(VARDATA(string)));
-} /* ascii() */
+} /* ascii() */
text *
ichar(int4 cvalue)
{
- text *result;
+ text *result;
result = (text *) palloc(VARHDRSZ + 1);
VARSIZE(result) = VARHDRSZ + 1;
*VARDATA(result) = (char) cvalue;
return result;
-} /* ichar() */
+} /* ichar() */
text *
repeat(text *string, int4 count)
{
- text *result;
- int slen, tlen;
- int i;
- char *cp;
+ text *result;
+ int slen,
+ tlen;
+ int i;
+ char *cp;
if (count < 0)
count = 0;
- slen = (VARSIZE(string)-VARHDRSZ);
+ slen = (VARSIZE(string) - VARHDRSZ);
tlen = (VARHDRSZ + (count * slen));
result = (text *) palloc(tlen);
@@ -582,5 +590,4 @@ repeat(text *string, int4 count)
}
return result;
-} /* repeat() */
-
+} /* repeat() */
diff --git a/src/backend/utils/adt/pg_locale.c b/src/backend/utils/adt/pg_locale.c
index 114cd08e259..c7a7a149b2c 100644
--- a/src/backend/utils/adt/pg_locale.c
+++ b/src/backend/utils/adt/pg_locale.c
@@ -2,22 +2,22 @@
/* -----------------------------------------------------------------------
* pg_locale.c
*
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/pg_locale.c,v 1.3 2000/03/18 18:57:14 tgl Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/pg_locale.c,v 1.4 2000/04/12 17:15:51 momjian Exp $
*
*
- * Portions Copyright (c) 1999-2000, PostgreSQL, Inc
+ * Portions Copyright (c) 1999-2000, PostgreSQL, Inc
*
- * The PostgreSQL locale utils.
+ * The PostgreSQL locale utils.
*
* Karel Zak - Zakkr
*
* -----------------------------------------------------------------------
*/
-
+
#include <stdio.h>
-
+
#include "postgres.h"
-
+
#ifdef USE_LOCALE
#include <locale.h>
@@ -27,72 +27,72 @@
/*------
- * Return in PG_LocaleCategories current locale setting
+ * Return in PG_LocaleCategories current locale setting
*------
- */
+ */
PG_LocaleCategories *
-PGLC_current( PG_LocaleCategories *lc )
+PGLC_current(PG_LocaleCategories * lc)
{
- lc->lang = getenv("LANG");
-
-lc->lc_ctype = setlocale(LC_CTYPE, NULL);
-lc->lc_numeric = setlocale(LC_NUMERIC, NULL);
-lc->lc_time = setlocale(LC_TIME, NULL);
-lc->lc_collate = setlocale(LC_COLLATE, NULL);
-lc->lc_monetary = setlocale(LC_MONETARY, NULL);
-lc->lc_messages = setlocale(LC_MESSAGES, NULL);
+ lc->lang = getenv("LANG");
+
+ lc->lc_ctype = setlocale(LC_CTYPE, NULL);
+ lc->lc_numeric = setlocale(LC_NUMERIC, NULL);
+ lc->lc_time = setlocale(LC_TIME, NULL);
+ lc->lc_collate = setlocale(LC_COLLATE, NULL);
+ lc->lc_monetary = setlocale(LC_MONETARY, NULL);
+ lc->lc_messages = setlocale(LC_MESSAGES, NULL);
return lc;
-}
+}
-#ifdef DEBUG_LOCALE_UTILS
+#ifdef DEBUG_LOCALE_UTILS
/*------
* Print a PG_LocaleCategories struct as DEBUG
*------
*/
PG_LocaleCategories *
-PGLC_debug_lc( PG_LocaleCategories *lc )
+PGLC_debug_lc(PG_LocaleCategories * lc)
{
elog(DEBUG, "CURRENT LOCALE ENVIRONMENT:\n\nLANG: \t%s\nLC_CTYPE:\t%s\nLC_NUMERIC:\t%s\nLC_TIME:\t%s\nLC_COLLATE:\t%s\nLC_MONETARY:\t%s\nLC_MESSAGES:\t%s\n",
- lc->lang,
- lc->lc_ctype,
- lc->lc_numeric,
- lc->lc_time,
- lc->lc_collate,
- lc->lc_monetary,
- lc->lc_messages
+ lc->lang,
+ lc->lc_ctype,
+ lc->lc_numeric,
+ lc->lc_time,
+ lc->lc_collate,
+ lc->lc_monetary,
+ lc->lc_messages
);
- return lc;
+ return lc;
}
#endif
/*------
- * Set locales via a PG_LocaleCategories struct
+ * Set locales via a PG_LocaleCategories struct
*------
*/
PG_LocaleCategories *
-PGLC_setlocale( PG_LocaleCategories *lc )
+PGLC_setlocale(PG_LocaleCategories * lc)
{
- if (!setlocale(LC_CTYPE, lc->lc_ctype ))
- elog(NOTICE, "pg_setlocale(): 'LC_CTYPE=%s' cannot be honored.", lc->lc_ctype);
-
- if (!setlocale(LC_NUMERIC, lc->lc_numeric ))
+ if (!setlocale(LC_CTYPE, lc->lc_ctype))
+ elog(NOTICE, "pg_setlocale(): 'LC_CTYPE=%s' cannot be honored.", lc->lc_ctype);
+
+ if (!setlocale(LC_NUMERIC, lc->lc_numeric))
elog(NOTICE, "pg_setlocale(): 'LC_NUMERIC=%s' cannot be honored.", lc->lc_numeric);
-
- if (!setlocale(LC_TIME, lc->lc_time ))
- elog(NOTICE, "pg_setlocale(): 'LC_TIME=%s' cannot be honored.", lc->lc_time);
-
- if (!setlocale(LC_COLLATE, lc->lc_collate ))
+
+ if (!setlocale(LC_TIME, lc->lc_time))
+ elog(NOTICE, "pg_setlocale(): 'LC_TIME=%s' cannot be honored.", lc->lc_time);
+
+ if (!setlocale(LC_COLLATE, lc->lc_collate))
elog(NOTICE, "pg_setlocale(): 'LC_COLLATE=%s' cannot be honored.", lc->lc_collate);
- if (!setlocale(LC_MONETARY, lc->lc_monetary ))
- elog(NOTICE, "pg_setlocale(): 'LC_MONETARY=%s' cannot be honored.", lc->lc_monetary);
-
- if (!setlocale(LC_MESSAGES, lc->lc_messages ))
+ if (!setlocale(LC_MONETARY, lc->lc_monetary))
+ elog(NOTICE, "pg_setlocale(): 'LC_MONETARY=%s' cannot be honored.", lc->lc_monetary);
+
+ if (!setlocale(LC_MESSAGES, lc->lc_messages))
elog(NOTICE, "pg_setlocale(): 'LC_MESSAGE=%s' cannot be honored.", lc->lc_messages);
return lc;
@@ -101,28 +101,28 @@ PGLC_setlocale( PG_LocaleCategories *lc )
/*------
* Return the POSIX lconv struct (contains number/money formatting information)
* with locale information for *all* categories.
- * => Returned lconv is *independent* on current locale catogories setting - in
+ * => Returned lconv is *independent* on current locale catogories setting - in
* contrast to standard localeconv().
*
- * ! libc prepare memory space for lconv itself and all returned strings in
- * lconv are *static strings*.
+ * ! libc prepare memory space for lconv itself and all returned strings in
+ * lconv are *static strings*.
*------
*/
struct lconv *
PGLC_localeconv(void)
{
- PG_LocaleCategories lc;
- struct lconv *lconv;
+ PG_LocaleCategories lc;
+ struct lconv *lconv;
/* Save current locale setting to lc */
- PGLC_current(&lc);
-
+ PGLC_current(&lc);
+
/* Set all locale category for current lang */
setlocale(LC_ALL, "");
-
- /* Get numeric formatting information */
- lconv = localeconv();
-
+
+ /* Get numeric formatting information */
+ lconv = localeconv();
+
/* Set previous original locale */
PGLC_setlocale(&lc);
@@ -130,4 +130,4 @@ PGLC_localeconv(void)
}
-#endif /* USE_LOCALE */
+#endif /* USE_LOCALE */
diff --git a/src/backend/utils/adt/pg_lzcompress.c b/src/backend/utils/adt/pg_lzcompress.c
index c35568e9598..ddeb8b5a510 100644
--- a/src/backend/utils/adt/pg_lzcompress.c
+++ b/src/backend/utils/adt/pg_lzcompress.c
@@ -1,7 +1,7 @@
/* ----------
* pg_lzcompress.c -
*
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/pg_lzcompress.c,v 1.3 1999/11/25 01:28:04 wieck Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/pg_lzcompress.c,v 1.4 2000/04/12 17:15:51 momjian Exp $
*
* This is an implementation of LZ compression for PostgreSQL.
* It uses a simple history table and generates 2-3 byte tags
@@ -83,7 +83,7 @@
*
* So the 16 bits of a 2 byte tag are coded as
*
- * 7---T1--0 7---T2--0
+ * 7---T1--0 7---T2--0
* OOOO LLLL OOOO OOOO
*
* This limits the offset to 1-4095 (12 bits) and the length
@@ -144,9 +144,10 @@
* Linked list for the backward history lookup
* ----------
*/
-typedef struct PGLZ_HistEntry {
- struct PGLZ_HistEntry *next;
- char *pos;
+typedef struct PGLZ_HistEntry
+{
+ struct PGLZ_HistEntry *next;
+ char *pos;
} PGLZ_HistEntry;
@@ -155,35 +156,43 @@ typedef struct PGLZ_HistEntry {
* ----------
*/
static PGLZ_Strategy strategy_default_data = {
- 256, /* Data chunks smaller 256 bytes are nott compressed */
- 6144, /* Data chunks greater equal 6K force compression */
- /* except compressed result is greater uncompressed data */
- 20, /* Compression rates below 20% mean fallback to uncompressed */
- /* storage except compression is forced by previous parameter */
- 128, /* Stop history lookup if a match of 128 bytes is found */
- 10 /* Lower good match size by 10% at every lookup loop iteration. */
+ 256, /* Data chunks smaller 256 bytes are nott
+ * compressed */
+ 6144, /* Data chunks greater equal 6K force
+ * compression */
+ /* except compressed result is greater uncompressed data */
+ 20, /* Compression rates below 20% mean
+ * fallback to uncompressed */
+ /* storage except compression is forced by previous parameter */
+ 128, /* Stop history lookup if a match of 128
+ * bytes is found */
+ 10 /* Lower good match size by 10% at every
+ * lookup loop iteration. */
};
-PGLZ_Strategy *PGLZ_strategy_default = &strategy_default_data;
+PGLZ_Strategy *PGLZ_strategy_default = &strategy_default_data;
static PGLZ_Strategy strategy_allways_data = {
- 0, /* Chunks of any size are compressed */
- 0, /* */
- 0, /* We want to save at least one single byte */
- 128, /* Stop history lookup if a match of 128 bytes is found */
- 6 /* Look harder for a good match. */
+ 0, /* Chunks of any size are compressed */
+ 0, /* */
+ 0, /* We want to save at least one single
+ * byte */
+ 128, /* Stop history lookup if a match of 128
+ * bytes is found */
+ 6 /* Look harder for a good match. */
};
-PGLZ_Strategy *PGLZ_strategy_allways = &strategy_allways_data;
+PGLZ_Strategy *PGLZ_strategy_allways = &strategy_allways_data;
static PGLZ_Strategy strategy_never_data = {
- 0, /* */
- 0, /* */
- 0, /* */
- 0, /* Zero indicates "store uncompressed allways" */
- 0 /* */
+ 0, /* */
+ 0, /* */
+ 0, /* */
+ 0, /* Zero indicates "store uncompressed
+ * allways" */
+ 0 /* */
};
-PGLZ_Strategy *PGLZ_strategy_never = &strategy_never_data;
+PGLZ_Strategy *PGLZ_strategy_never = &strategy_never_data;
@@ -197,7 +206,7 @@ PGLZ_Strategy *PGLZ_strategy_never = &strategy_never_data;
#if 1
#define pglz_hist_idx(_s,_e) ( \
(((_e) - (_s)) < 4) ? 0 : \
- ((((_s)[0] << 9) ^ ((_s)[1] << 6) ^ \
+ ((((_s)[0] << 9) ^ ((_s)[1] << 6) ^ \
((_s)[2] << 3) ^ (_s)[3]) & (PGLZ_HISTORY_MASK)) \
)
#else
@@ -217,7 +226,7 @@ PGLZ_Strategy *PGLZ_strategy_never = &strategy_never_data;
#define pglz_hist_add(_hs,_hn,_s,_e) { \
int __hindex = pglz_hist_idx((_s),(_e)); \
(_hn)->next = (_hs)[__hindex]; \
- (_hn)->pos = (_s); \
+ (_hn)->pos = (_s); \
(_hs)[__hindex] = (_hn)++; \
}
@@ -288,16 +297,16 @@ PGLZ_Strategy *PGLZ_strategy_never = &strategy_never_data;
* ----------
*/
static inline int
-pglz_find_match (PGLZ_HistEntry **hstart, char *input, char *end,
- int *lenp, int *offp, int good_match, int good_drop)
+pglz_find_match(PGLZ_HistEntry **hstart, char *input, char *end,
+ int *lenp, int *offp, int good_match, int good_drop)
{
- PGLZ_HistEntry *hent;
- int32 len = 0;
- int32 off = 0;
- int32 thislen;
- int32 thisoff;
- char *ip;
- char *hp;
+ PGLZ_HistEntry *hent;
+ int32 len = 0;
+ int32 off = 0;
+ int32 thislen;
+ int32 thisoff;
+ char *ip;
+ char *hp;
/* ----------
* Traverse the linked history list until a good enough
@@ -311,7 +320,7 @@ pglz_find_match (PGLZ_HistEntry **hstart, char *input, char *end,
* Be happy with lesser good matches the more entries we visited.
* ----------
*/
- good_match -= (good_match * good_drop) /100;
+ good_match -= (good_match * good_drop) / 100;
/* ----------
* Stop if the offset does not fit into our tag anymore.
@@ -340,9 +349,9 @@ pglz_find_match (PGLZ_HistEntry **hstart, char *input, char *end,
thislen = len;
ip += len;
hp += len;
- } else {
- thislen = 0;
}
+ else
+ thislen = 0;
while (ip < end && *ip == *hp && thislen < PGLZ_MAX_MATCH)
{
thislen++;
@@ -390,29 +399,29 @@ pglz_find_match (PGLZ_HistEntry **hstart, char *input, char *end,
* ----------
*/
int
-pglz_compress (char *source, int slen, PGLZ_Header *dest, PGLZ_Strategy *strategy)
+pglz_compress(char *source, int slen, PGLZ_Header *dest, PGLZ_Strategy *strategy)
{
- PGLZ_HistEntry *hist_start[PGLZ_HISTORY_SIZE];
- PGLZ_HistEntry *hist_alloc;
- PGLZ_HistEntry hist_prealloc[PGLZ_HISTORY_PREALLOC];
- PGLZ_HistEntry *hist_next;
-
- unsigned char *bp = ((unsigned char *)dest) + sizeof(PGLZ_Header);
- unsigned char *bstart = bp;
- char *dp = source;
- char *dend = source + slen;
- unsigned char ctrl_dummy = 0;
- unsigned char *ctrlp = &ctrl_dummy;
- unsigned char ctrlb = 0;
- unsigned char ctrl = 0;
- int32 match_len;
- int32 match_off;
- int32 good_match;
- int32 good_drop;
- int32 do_compress = 1;
- int32 result_size = -1;
- int32 result_max;
- int32 need_rate;
+ PGLZ_HistEntry *hist_start[PGLZ_HISTORY_SIZE];
+ PGLZ_HistEntry *hist_alloc;
+ PGLZ_HistEntry hist_prealloc[PGLZ_HISTORY_PREALLOC];
+ PGLZ_HistEntry *hist_next;
+
+ unsigned char *bp = ((unsigned char *) dest) + sizeof(PGLZ_Header);
+ unsigned char *bstart = bp;
+ char *dp = source;
+ char *dend = source + slen;
+ unsigned char ctrl_dummy = 0;
+ unsigned char *ctrlp = &ctrl_dummy;
+ unsigned char ctrlb = 0;
+ unsigned char ctrl = 0;
+ int32 match_len;
+ int32 match_off;
+ int32 good_match;
+ int32 good_drop;
+ int32 do_compress = 1;
+ int32 result_size = -1;
+ int32 result_max;
+ int32 need_rate;
/* ----------
* Our fallback strategy is the default.
@@ -436,7 +445,9 @@ pglz_compress (char *source, int slen, PGLZ_Header *dest, PGLZ_Strategy *strateg
{
memcpy(bstart, source, slen);
return (dest->varsize = slen + sizeof(PGLZ_Header));
- } else {
+ }
+ else
+ {
if (slen < strategy->min_input_size)
{
memcpy(bstart, source, slen);
@@ -464,12 +475,12 @@ pglz_compress (char *source, int slen, PGLZ_Header *dest, PGLZ_Strategy *strateg
* table on the stack frame.
* ----------
*/
- memset((void *)hist_start, 0, sizeof(hist_start));
+ memset((void *) hist_start, 0, sizeof(hist_start));
if (slen + 1 <= PGLZ_HISTORY_PREALLOC)
hist_alloc = hist_prealloc;
else
hist_alloc = (PGLZ_HistEntry *)
- palloc(sizeof(PGLZ_HistEntry) * (slen + 1));
+ palloc(sizeof(PGLZ_HistEntry) * (slen + 1));
hist_next = hist_alloc;
/* ----------
@@ -481,9 +492,9 @@ pglz_compress (char *source, int slen, PGLZ_Header *dest, PGLZ_Strategy *strateg
* ----------
*/
if (slen >= strategy->force_input_size)
- {
result_max = slen;
- } else {
+ else
+ {
need_rate = strategy->min_comp_rate;
if (need_rate < 0)
need_rate = 0;
@@ -513,8 +524,8 @@ pglz_compress (char *source, int slen, PGLZ_Header *dest, PGLZ_Strategy *strateg
* Try to find a match in the history
* ----------
*/
- if (pglz_find_match(hist_start, dp, dend, &match_len,
- &match_off, good_match, good_drop))
+ if (pglz_find_match(hist_start, dp, dend, &match_len,
+ &match_off, good_match, good_drop))
{
/* ----------
* Create the tag and add history entries for
@@ -522,21 +533,23 @@ pglz_compress (char *source, int slen, PGLZ_Header *dest, PGLZ_Strategy *strateg
* ----------
*/
pglz_out_tag(ctrlp, ctrlb, ctrl, bp, match_len, match_off);
- while(match_len--)
+ while (match_len--)
{
pglz_hist_add(hist_start, hist_next, dp, dend);
- dp++; /* Do not do this ++ in the line above! */
- /* The macro would do it four times - Jan. */
+ dp++; /* Do not do this ++ in the line above! */
+ /* The macro would do it four times - Jan. */
}
- } else {
+ }
+ else
+ {
/* ----------
* No match found. Copy one literal byte.
* ----------
*/
pglz_out_literal(ctrlp, ctrlb, ctrl, bp, *dp);
pglz_hist_add(hist_start, hist_next, dp, dend);
- dp++; /* Do not do this ++ in the line above! */
- /* The macro would do it four times - Jan. */
+ dp++; /* Do not do this ++ in the line above! */
+ /* The macro would do it four times - Jan. */
}
}
@@ -545,7 +558,7 @@ pglz_compress (char *source, int slen, PGLZ_Header *dest, PGLZ_Strategy *strateg
* ----------
*/
if (hist_alloc != hist_prealloc)
- pfree((void *)hist_alloc);
+ pfree((void *) hist_alloc);
/* ----------
* If we are still in compressing mode, write out the last
@@ -558,9 +571,8 @@ pglz_compress (char *source, int slen, PGLZ_Header *dest, PGLZ_Strategy *strateg
*ctrlp = ctrlb;
result_size = bp - bstart;
- if (result_size >= result_max) {
+ if (result_size >= result_max)
do_compress = 0;
- }
}
/* ----------
@@ -571,10 +583,10 @@ pglz_compress (char *source, int slen, PGLZ_Header *dest, PGLZ_Strategy *strateg
* ----------
*/
if (do_compress)
- {
return (dest->varsize = result_size + sizeof(PGLZ_Header));
- } else {
- memcpy(((char *)dest) + sizeof(PGLZ_Header), source, slen);
+ else
+ {
+ memcpy(((char *) dest) + sizeof(PGLZ_Header), source, slen);
return (dest->varsize = slen + sizeof(PGLZ_Header));
}
}
@@ -587,19 +599,19 @@ pglz_compress (char *source, int slen, PGLZ_Header *dest, PGLZ_Strategy *strateg
* ----------
*/
int
-pglz_decompress (PGLZ_Header *source, char *dest)
+pglz_decompress(PGLZ_Header *source, char *dest)
{
- unsigned char *dp;
- unsigned char *dend;
- unsigned char *bp;
- unsigned char ctrl;
- int32 ctrlc;
- int32 len;
- int32 off;
-
- dp = ((unsigned char *)source) + sizeof(PGLZ_Header);
- dend = ((unsigned char *)source) + source->varsize;
- bp = (unsigned char *)dest;
+ unsigned char *dp;
+ unsigned char *dend;
+ unsigned char *bp;
+ unsigned char ctrl;
+ int32 ctrlc;
+ int32 len;
+ int32 off;
+
+ dp = ((unsigned char *) source) + sizeof(PGLZ_Header);
+ dend = ((unsigned char *) source) + source->varsize;
+ bp = (unsigned char *) dest;
if (source->varsize == source->rawsize + sizeof(PGLZ_Header))
{
@@ -630,9 +642,7 @@ pglz_decompress (PGLZ_Header *source, char *dest)
off = ((dp[0] & 0xf0) << 4) | dp[1];
dp += 2;
if (len == 18)
- {
len += *dp++;
- }
/* ----------
* Now we copy the bytes specified by the tag from
@@ -646,7 +656,9 @@ pglz_decompress (PGLZ_Header *source, char *dest)
*bp = bp[-off];
bp++;
}
- } else {
+ }
+ else
+ {
/* ----------
* An unset control bit means LITERAL BYTE. So we
* just copy one from INPUT to OUTPUT.
@@ -667,7 +679,7 @@ pglz_decompress (PGLZ_Header *source, char *dest)
* That's it.
* ----------
*/
- return (char *)bp - dest;
+ return (char *) bp - dest;
}
@@ -681,7 +693,7 @@ pglz_decompress (PGLZ_Header *source, char *dest)
int
pglz_get_next_decomp_char_from_lzdata(PGLZ_DecompState *dstate)
{
- unsigned char retval;
+ unsigned char retval;
if (dstate->tocopy > 0)
{
@@ -703,9 +715,7 @@ pglz_get_next_decomp_char_from_lzdata(PGLZ_DecompState *dstate)
* ----------
*/
if (dstate->cp_in == dstate->cp_end)
- {
return EOF;
- }
/* ----------
* This decompression method saves time only, if we stop near
@@ -721,14 +731,14 @@ pglz_get_next_decomp_char_from_lzdata(PGLZ_DecompState *dstate)
*/
if (dstate->cp_out - dstate->temp_buf >= 256)
{
- unsigned char *cp_in = dstate->cp_in;
- unsigned char *cp_out = dstate->cp_out;
- unsigned char *cp_end = dstate->cp_end;
- unsigned char *cp_copy;
- unsigned char ctrl;
- int off;
- int len;
- int i;
+ unsigned char *cp_in = dstate->cp_in;
+ unsigned char *cp_out = dstate->cp_out;
+ unsigned char *cp_end = dstate->cp_end;
+ unsigned char *cp_copy;
+ unsigned char ctrl;
+ int off;
+ int len;
+ int i;
while (cp_in < cp_end)
{
@@ -748,27 +758,27 @@ pglz_get_next_decomp_char_from_lzdata(PGLZ_DecompState *dstate)
len += *cp_in++;
cp_copy = cp_out - off;
- while(len--)
+ while (len--)
*cp_out++ = *cp_copy++;
- } else {
- *cp_out++ = *cp_in++;
}
+ else
+ *cp_out++ = *cp_in++;
ctrl >>= 1;
}
}
- dstate->cp_in = dstate->cp_out;
- dstate->cp_end = cp_out;
- dstate->next_char = pglz_get_next_decomp_char_from_plain;
+ dstate->cp_in = dstate->cp_out;
+ dstate->cp_end = cp_out;
+ dstate->next_char = pglz_get_next_decomp_char_from_plain;
- return (int)(*(dstate->cp_in++));
+ return (int) (*(dstate->cp_in++));
}
/* ----------
* Not yet, get next control byte into decomp state.
* ----------
*/
- dstate->ctrl = (unsigned char)(*(dstate->cp_in++));
+ dstate->ctrl = (unsigned char) (*(dstate->cp_in++));
dstate->ctrl_count = 8;
}
@@ -777,9 +787,7 @@ pglz_get_next_decomp_char_from_lzdata(PGLZ_DecompState *dstate)
* ----------
*/
if (dstate->cp_in == dstate->cp_end)
- {
return EOF;
- }
/* ----------
* Handle next control bit.
@@ -793,27 +801,29 @@ pglz_get_next_decomp_char_from_lzdata(PGLZ_DecompState *dstate)
* and do the copy for the first byte as above.
* ----------
*/
- int off;
+ int off;
- dstate->tocopy = (dstate->cp_in[0] & 0x0f) + 3;
- off = ((dstate->cp_in[0] & 0xf0) << 4) | dstate->cp_in[1];
- dstate->cp_in += 2;
+ dstate->tocopy = (dstate->cp_in[0] & 0x0f) + 3;
+ off = ((dstate->cp_in[0] & 0xf0) << 4) | dstate->cp_in[1];
+ dstate->cp_in += 2;
if (dstate->tocopy == 18)
dstate->tocopy += *(dstate->cp_in++);
dstate->cp_copy = dstate->cp_out - off;
dstate->tocopy--;
retval = (*(dstate->cp_out++) = *(dstate->cp_copy++));
- } else {
+ }
+ else
+ {
/* ----------
* Bit is unset, so literal byte follows.
* ----------
*/
- retval = (int)(*(dstate->cp_out++) = *(dstate->cp_in++));
+ retval = (int) (*(dstate->cp_out++) = *(dstate->cp_in++));
}
dstate->ctrl >>= 1;
- return (int)retval;
+ return (int) retval;
}
@@ -831,7 +841,5 @@ pglz_get_next_decomp_char_from_plain(PGLZ_DecompState *dstate)
if (dstate->cp_in >= dstate->cp_end)
return EOF;
- return (int)(*(dstate->cp_in++));
+ return (int) (*(dstate->cp_in++));
}
-
-
diff --git a/src/backend/utils/adt/regproc.c b/src/backend/utils/adt/regproc.c
index 7f4bd651ace..4060a846655 100644
--- a/src/backend/utils/adt/regproc.c
+++ b/src/backend/utils/adt/regproc.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/regproc.c,v 1.53 2000/02/27 03:30:27 tgl Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/regproc.c,v 1.54 2000/04/12 17:15:51 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -264,7 +264,7 @@ oidvectortypes(Oid *oidArray)
for (num = 0; num < FUNC_MAX_ARGS; num++)
{
if (oidArray[num] != InvalidOid)
- numargs = num+1;
+ numargs = num + 1;
}
result = (text *) palloc((NAMEDATALEN + 1) * numargs + VARHDRSZ + 1);
diff --git a/src/backend/utils/adt/ri_triggers.c b/src/backend/utils/adt/ri_triggers.c
index b6f9b5eead8..79010b53f75 100644
--- a/src/backend/utils/adt/ri_triggers.c
+++ b/src/backend/utils/adt/ri_triggers.c
@@ -6,7 +6,7 @@
*
* 1999 Jan Wieck
*
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/ri_triggers.c,v 1.13 2000/02/07 17:50:38 wieck Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/ri_triggers.c,v 1.14 2000/04/12 17:15:51 momjian Exp $
*
* ----------
*/
@@ -79,14 +79,15 @@
* The key identifying a prepared SPI plan in our private hashtable
* ----------
*/
-typedef struct RI_QueryKey {
- int32 constr_type;
- Oid constr_id;
- int32 constr_queryno;
- Oid fk_relid;
- Oid pk_relid;
- int32 nkeypairs;
- int16 keypair[RI_MAX_NUMKEYS][2];
+typedef struct RI_QueryKey
+{
+ int32 constr_type;
+ Oid constr_id;
+ int32 constr_queryno;
+ Oid fk_relid;
+ Oid pk_relid;
+ int32 nkeypairs;
+ int16 keypair[RI_MAX_NUMKEYS][2];
} RI_QueryKey;
@@ -94,16 +95,18 @@ typedef struct RI_QueryKey {
* RI_QueryHashEntry
* ----------
*/
-typedef struct RI_QueryHashEntry {
- RI_QueryKey key;
- void *plan;
+typedef struct RI_QueryHashEntry
+{
+ RI_QueryKey key;
+ void *plan;
} RI_QueryHashEntry;
-typedef struct RI_OpreqHashEntry {
- Oid typeid;
- Oid oprfnid;
- FmgrInfo oprfmgrinfo;
+typedef struct RI_OpreqHashEntry
+{
+ Oid typeid;
+ Oid oprfnid;
+ FmgrInfo oprfmgrinfo;
} RI_OpreqHashEntry;
@@ -112,27 +115,27 @@ typedef struct RI_OpreqHashEntry {
* Local data
* ----------
*/
-static HTAB *ri_query_cache = (HTAB *)NULL;
-static HTAB *ri_opreq_cache = (HTAB *)NULL;
+static HTAB *ri_query_cache = (HTAB *) NULL;
+static HTAB *ri_opreq_cache = (HTAB *) NULL;
/* ----------
* Local function prototypes
* ----------
*/
-static int ri_DetermineMatchType(char *str);
-static int ri_NullCheck(Relation rel, HeapTuple tup,
- RI_QueryKey *key, int pairidx);
+static int ri_DetermineMatchType(char *str);
+static int ri_NullCheck(Relation rel, HeapTuple tup,
+ RI_QueryKey *key, int pairidx);
static void ri_BuildQueryKeyFull(RI_QueryKey *key, Oid constr_id,
- int32 constr_queryno,
- Relation fk_rel, Relation pk_rel,
- int argc, char **argv);
-static bool ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup,
- RI_QueryKey *key, int pairidx);
-static bool ri_AllKeysUnequal(Relation rel, HeapTuple oldtup, HeapTuple newtup,
- RI_QueryKey *key, int pairidx);
+ int32 constr_queryno,
+ Relation fk_rel, Relation pk_rel,
+ int argc, char **argv);
+static bool ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup,
+ RI_QueryKey *key, int pairidx);
+static bool ri_AllKeysUnequal(Relation rel, HeapTuple oldtup, HeapTuple newtup,
+ RI_QueryKey *key, int pairidx);
static bool ri_OneKeyEqual(Relation rel, int column, HeapTuple oldtup,
- HeapTuple newtup, RI_QueryKey *key, int pairidx);
+ HeapTuple newtup, RI_QueryKey *key, int pairidx);
static bool ri_AttributesEqual(Oid typeid, Datum oldvalue, Datum newvalue);
static void ri_InitHashTables(void);
@@ -148,24 +151,25 @@ static void ri_HashPreparedPlan(RI_QueryKey *key, void *plan);
* ----------
*/
static HeapTuple
-RI_FKey_check (FmgrInfo *proinfo)
+RI_FKey_check(FmgrInfo *proinfo)
{
- TriggerData *trigdata;
- int tgnargs;
- char **tgargs;
- Relation fk_rel;
- Relation pk_rel;
- HeapTuple new_row;
- HeapTuple old_row;
- RI_QueryKey qkey;
- void *qplan;
- Datum check_values[RI_MAX_NUMKEYS];
- char check_nulls[RI_MAX_NUMKEYS + 1];
- bool isnull;
- int i;
- int match_type;
+ TriggerData *trigdata;
+ int tgnargs;
+ char **tgargs;
+ Relation fk_rel;
+ Relation pk_rel;
+ HeapTuple new_row;
+ HeapTuple old_row;
+ RI_QueryKey qkey;
+ void *qplan;
+ Datum check_values[RI_MAX_NUMKEYS];
+ char check_nulls[RI_MAX_NUMKEYS + 1];
+ bool isnull;
+ int i;
+ int match_type;
+
trigdata = CurrentTriggerData;
- CurrentTriggerData = NULL;
+ CurrentTriggerData = NULL;
ReferentialIntegritySnapshotOverride = true;
/* ----------
@@ -174,37 +178,39 @@ RI_FKey_check (FmgrInfo *proinfo)
*/
if (trigdata == NULL)
elog(ERROR, "RI_FKey_check() not fired by trigger manager");
- if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
- !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
+ if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
+ !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
elog(ERROR, "RI_FKey_check() must be fired AFTER ROW");
if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event) &&
- !TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
+ !TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
elog(ERROR, "RI_FKey_check() must be fired for INSERT or UPDATE");
/* ----------
- * Check for the correct # of call arguments
+ * Check for the correct # of call arguments
* ----------
*/
tgnargs = trigdata->tg_trigger->tgnargs;
- tgargs = trigdata->tg_trigger->tgargs;
+ tgargs = trigdata->tg_trigger->tgargs;
if (tgnargs < 4 || (tgnargs % 2) != 0)
elog(ERROR, "wrong # of arguments in call to RI_FKey_check()");
if (tgnargs > RI_MAX_ARGUMENTS)
elog(ERROR, "too many keys (%d max) in call to RI_FKey_check()",
- RI_MAX_NUMKEYS);
+ RI_MAX_NUMKEYS);
/* ----------
* Get the relation descriptors of the FK and PK tables and
* the new tuple.
* ----------
*/
- fk_rel = trigdata->tg_relation;
- pk_rel = heap_openr(tgargs[RI_PK_RELNAME_ARGNO], NoLock);
+ fk_rel = trigdata->tg_relation;
+ pk_rel = heap_openr(tgargs[RI_PK_RELNAME_ARGNO], NoLock);
if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
{
old_row = trigdata->tg_trigtuple;
new_row = trigdata->tg_newtuple;
- } else {
+ }
+ else
+ {
old_row = NULL;
new_row = trigdata->tg_trigtuple;
}
@@ -220,11 +226,12 @@ RI_FKey_check (FmgrInfo *proinfo)
* future enhancements.
* ----------
*/
- if (tgnargs == 4) {
+ if (tgnargs == 4)
+ {
ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
- RI_PLAN_CHECK_LOOKUPPK_NOCOLS,
- fk_rel, pk_rel,
- tgnargs, tgargs);
+ RI_PLAN_CHECK_LOOKUPPK_NOCOLS,
+ fk_rel, pk_rel,
+ tgnargs, tgargs);
if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
{
@@ -235,9 +242,9 @@ RI_FKey_check (FmgrInfo *proinfo)
* SELECT oid FROM <pktable>
* ----------
*/
- sprintf(querystr, "SELECT oid FROM \"%s\" FOR UPDATE OF \"%s\"",
- tgargs[RI_PK_RELNAME_ARGNO],
- tgargs[RI_PK_RELNAME_ARGNO]);
+ sprintf(querystr, "SELECT oid FROM \"%s\" FOR UPDATE OF \"%s\"",
+ tgargs[RI_PK_RELNAME_ARGNO],
+ tgargs[RI_PK_RELNAME_ARGNO]);
/* ----------
* Prepare, save and remember the new plan.
@@ -258,12 +265,12 @@ RI_FKey_check (FmgrInfo *proinfo)
if (SPI_execp(qplan, check_values, check_nulls, 1) != SPI_OK_SELECT)
elog(ERROR, "SPI_execp() failed in RI_FKey_check()");
-
+
if (SPI_processed == 0)
elog(ERROR, "%s referential integrity violation - "
- "no rows found in %s",
- tgargs[RI_CONSTRAINT_NAME_ARGNO],
- tgargs[RI_PK_RELNAME_ARGNO]);
+ "no rows found in %s",
+ tgargs[RI_CONSTRAINT_NAME_ARGNO],
+ tgargs[RI_PK_RELNAME_ARGNO]);
if (SPI_finish() != SPI_OK_FINISH)
elog(NOTICE, "SPI_finish() failed in RI_FKey_check()");
@@ -281,8 +288,8 @@ RI_FKey_check (FmgrInfo *proinfo)
}
ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
- RI_PLAN_CHECK_LOOKUPPK, fk_rel, pk_rel,
- tgnargs, tgargs);
+ RI_PLAN_CHECK_LOOKUPPK, fk_rel, pk_rel,
+ tgnargs, tgargs);
switch (ri_NullCheck(fk_rel, new_row, &qkey, RI_KEYPAIR_FK_IDX))
{
@@ -290,32 +297,32 @@ RI_FKey_check (FmgrInfo *proinfo)
/* ----------
* No check - if NULLs are allowed at all is
* already checked by NOT NULL constraint.
- *
- * This is true for MATCH FULL, MATCH PARTIAL, and
- * MATCH <unspecified>
+ *
+ * This is true for MATCH FULL, MATCH PARTIAL, and
+ * MATCH <unspecified>
* ----------
*/
heap_close(pk_rel, NoLock);
return NULL;
-
+
case RI_KEYS_SOME_NULL:
/* ----------
* This is the only case that differs between the
- * three kinds of MATCH.
+ * three kinds of MATCH.
* ----------
*/
switch (match_type)
{
case RI_MATCH_TYPE_FULL:
/* ----------
- * Not allowed - MATCH FULL says either all or none
+ * Not allowed - MATCH FULL says either all or none
* of the attributes can be NULLs
* ----------
*/
elog(ERROR, "%s referential integrity violation - "
- "MATCH FULL doesn't allow mixing of NULL "
- "and NON-NULL key values",
- tgargs[RI_CONSTRAINT_NAME_ARGNO]);
+ "MATCH FULL doesn't allow mixing of NULL "
+ "and NON-NULL key values",
+ tgargs[RI_CONSTRAINT_NAME_ARGNO]);
heap_close(pk_rel, NoLock);
return NULL;
@@ -332,8 +339,8 @@ RI_FKey_check (FmgrInfo *proinfo)
/* ----------
* MATCH PARTIAL - all non-null columns must match.
* (not implemented, can be done by modifying the query
- * below to only include non-null columns, or by
- * writing a special version here)
+ * below to only include non-null columns, or by
+ * writing a special version here)
* ----------
*/
elog(ERROR, "MATCH PARTIAL not yet implemented");
@@ -344,7 +351,7 @@ RI_FKey_check (FmgrInfo *proinfo)
case RI_KEYS_NONE_NULL:
/* ----------
* Have a full qualified key - continue below for all three
- * kinds of MATCH.
+ * kinds of MATCH.
* ----------
*/
break;
@@ -372,7 +379,7 @@ RI_FKey_check (FmgrInfo *proinfo)
{
char buf[256];
char querystr[8192];
- char *querysep;
+ char *querysep;
Oid queryoids[RI_MAX_NUMKEYS];
/* ----------
@@ -384,20 +391,20 @@ RI_FKey_check (FmgrInfo *proinfo)
* how to compare these two types by '='.
* ----------
*/
- sprintf(querystr, "SELECT oid FROM \"%s\"",
- tgargs[RI_PK_RELNAME_ARGNO]);
+ sprintf(querystr, "SELECT oid FROM \"%s\"",
+ tgargs[RI_PK_RELNAME_ARGNO]);
querysep = "WHERE";
for (i = 0; i < qkey.nkeypairs; i++)
{
- sprintf(buf, " %s \"%s\" = $%d", querysep,
- tgargs[5 + i * 2], i + 1);
+ sprintf(buf, " %s \"%s\" = $%d", querysep,
+ tgargs[5 + i * 2], i + 1);
strcat(querystr, buf);
querysep = "AND";
queryoids[i] = SPI_gettypeid(fk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_FK_IDX]);
+ qkey.keypair[i][RI_KEYPAIR_FK_IDX]);
}
sprintf(buf, " FOR UPDATE OF \"%s\"",
- tgargs[RI_PK_RELNAME_ARGNO]);
+ tgargs[RI_PK_RELNAME_ARGNO]);
strcat(querystr, buf);
/* ----------
@@ -418,17 +425,17 @@ RI_FKey_check (FmgrInfo *proinfo)
{
/* ----------
* We can implement MATCH PARTIAL by excluding this column from
- * the query if it is null. Simple! Unfortunately, the
- * referential actions aren't so I've not bothered to do so
- * for the moment.
+ * the query if it is null. Simple! Unfortunately, the
+ * referential actions aren't so I've not bothered to do so
+ * for the moment.
* ----------
*/
-
+
check_values[i] = SPI_getbinval(new_row,
- fk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_FK_IDX],
- &isnull);
- if (isnull)
+ fk_rel->rd_att,
+ qkey.keypair[i][RI_KEYPAIR_FK_IDX],
+ &isnull);
+ if (isnull)
check_nulls[i] = 'n';
else
check_nulls[i] = ' ';
@@ -441,13 +448,13 @@ RI_FKey_check (FmgrInfo *proinfo)
*/
if (SPI_execp(qplan, check_values, check_nulls, 1) != SPI_OK_SELECT)
elog(ERROR, "SPI_execp() failed in RI_FKey_check()");
-
+
if (SPI_processed == 0)
elog(ERROR, "%s referential integrity violation - "
- "key referenced from %s not found in %s",
- tgargs[RI_CONSTRAINT_NAME_ARGNO],
- tgargs[RI_FK_RELNAME_ARGNO],
- tgargs[RI_PK_RELNAME_ARGNO]);
+ "key referenced from %s not found in %s",
+ tgargs[RI_CONSTRAINT_NAME_ARGNO],
+ tgargs[RI_FK_RELNAME_ARGNO],
+ tgargs[RI_PK_RELNAME_ARGNO]);
if (SPI_finish() != SPI_OK_FINISH)
elog(NOTICE, "SPI_finish() failed in RI_FKey_check()");
@@ -470,7 +477,7 @@ RI_FKey_check (FmgrInfo *proinfo)
* ----------
*/
HeapTuple
-RI_FKey_check_ins (FmgrInfo *proinfo)
+RI_FKey_check_ins(FmgrInfo *proinfo)
{
return RI_FKey_check(proinfo);
}
@@ -483,7 +490,7 @@ RI_FKey_check_ins (FmgrInfo *proinfo)
* ----------
*/
HeapTuple
-RI_FKey_check_upd (FmgrInfo *proinfo)
+RI_FKey_check_upd(FmgrInfo *proinfo)
{
return RI_FKey_check(proinfo);
}
@@ -493,28 +500,28 @@ RI_FKey_check_upd (FmgrInfo *proinfo)
* RI_FKey_noaction_del -
*
* Give an error and roll back the current transaction if the
- * delete has resulted in a violation of the given referential
- * integrity constraint.
+ * delete has resulted in a violation of the given referential
+ * integrity constraint.
* ----------
*/
HeapTuple
-RI_FKey_noaction_del (FmgrInfo *proinfo)
+RI_FKey_noaction_del(FmgrInfo *proinfo)
{
- TriggerData *trigdata;
- int tgnargs;
- char **tgargs;
- Relation fk_rel;
- Relation pk_rel;
- HeapTuple old_row;
- RI_QueryKey qkey;
- void *qplan;
- Datum del_values[RI_MAX_NUMKEYS];
- char del_nulls[RI_MAX_NUMKEYS + 1];
- bool isnull;
- int i;
+ TriggerData *trigdata;
+ int tgnargs;
+ char **tgargs;
+ Relation fk_rel;
+ Relation pk_rel;
+ HeapTuple old_row;
+ RI_QueryKey qkey;
+ void *qplan;
+ Datum del_values[RI_MAX_NUMKEYS];
+ char del_nulls[RI_MAX_NUMKEYS + 1];
+ bool isnull;
+ int i;
trigdata = CurrentTriggerData;
- CurrentTriggerData = NULL;
+ CurrentTriggerData = NULL;
ReferentialIntegritySnapshotOverride = true;
/* ----------
@@ -523,23 +530,23 @@ RI_FKey_noaction_del (FmgrInfo *proinfo)
*/
if (trigdata == NULL)
elog(ERROR, "RI_FKey_noaction_del() not fired by trigger manager");
- if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
- !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
+ if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
+ !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
elog(ERROR, "RI_FKey_noaction_del() must be fired AFTER ROW");
if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
elog(ERROR, "RI_FKey_noaction_del() must be fired for DELETE");
/* ----------
- * Check for the correct # of call arguments
+ * Check for the correct # of call arguments
* ----------
*/
tgnargs = trigdata->tg_trigger->tgnargs;
- tgargs = trigdata->tg_trigger->tgargs;
+ tgargs = trigdata->tg_trigger->tgargs;
if (tgnargs < 4 || (tgnargs % 2) != 0)
elog(ERROR, "wrong # of arguments in call to RI_FKey_noaction_del()");
if (tgnargs > RI_MAX_ARGUMENTS)
elog(ERROR, "too many keys (%d max) in call to RI_FKey_noaction_del()",
- RI_MAX_NUMKEYS);
+ RI_MAX_NUMKEYS);
/* ----------
* Nothing to do if no column names to compare given
@@ -553,25 +560,25 @@ RI_FKey_noaction_del (FmgrInfo *proinfo)
* the old tuple.
* ----------
*/
- fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
- pk_rel = trigdata->tg_relation;
+ fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
+ pk_rel = trigdata->tg_relation;
old_row = trigdata->tg_trigtuple;
switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]))
{
- /* ----------
- * SQL3 11.9 <referential constraint definition>
- * Gereral rules 6) a) iv):
- * MATCH <unspecified> or MATCH FULL
- * ... ON DELETE CASCADE
- * ----------
- */
+ /* ----------
+ * SQL3 11.9 <referential constraint definition>
+ * Gereral rules 6) a) iv):
+ * MATCH <unspecified> or MATCH FULL
+ * ... ON DELETE CASCADE
+ * ----------
+ */
case RI_MATCH_TYPE_UNSPECIFIED:
case RI_MATCH_TYPE_FULL:
ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
- RI_PLAN_NOACTION_DEL_CHECKREF,
- fk_rel, pk_rel,
- tgnargs, tgargs);
+ RI_PLAN_NOACTION_DEL_CHECKREF,
+ fk_rel, pk_rel,
+ tgnargs, tgargs);
switch (ri_NullCheck(pk_rel, old_row, &qkey, RI_KEYPAIR_PK_IDX))
{
@@ -584,7 +591,7 @@ RI_FKey_noaction_del (FmgrInfo *proinfo)
*/
heap_close(fk_rel, NoLock);
return NULL;
-
+
case RI_KEYS_NONE_NULL:
/* ----------
* Have a full qualified key - continue below
@@ -606,7 +613,7 @@ RI_FKey_noaction_del (FmgrInfo *proinfo)
{
char buf[256];
char querystr[8192];
- char *querysep;
+ char *querysep;
Oid queryoids[RI_MAX_NUMKEYS];
/* ----------
@@ -618,20 +625,20 @@ RI_FKey_noaction_del (FmgrInfo *proinfo)
* how to compare these two types by '='.
* ----------
*/
- sprintf(querystr, "SELECT oid FROM \"%s\"",
- tgargs[RI_FK_RELNAME_ARGNO]);
+ sprintf(querystr, "SELECT oid FROM \"%s\"",
+ tgargs[RI_FK_RELNAME_ARGNO]);
querysep = "WHERE";
for (i = 0; i < qkey.nkeypairs; i++)
{
- sprintf(buf, " %s \"%s\" = $%d", querysep,
- tgargs[4 + i * 2], i + 1);
+ sprintf(buf, " %s \"%s\" = $%d", querysep,
+ tgargs[4 + i * 2], i + 1);
strcat(querystr, buf);
querysep = "AND";
queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
}
- sprintf(buf, " FOR UPDATE OF \"%s\"",
- tgargs[RI_FK_RELNAME_ARGNO]);
+ sprintf(buf, " FOR UPDATE OF \"%s\"",
+ tgargs[RI_FK_RELNAME_ARGNO]);
strcat(querystr, buf);
/* ----------
@@ -651,10 +658,10 @@ RI_FKey_noaction_del (FmgrInfo *proinfo)
for (i = 0; i < qkey.nkeypairs; i++)
{
del_values[i] = SPI_getbinval(old_row,
- pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX],
- &isnull);
- if (isnull)
+ pk_rel->rd_att,
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX],
+ &isnull);
+ if (isnull)
del_nulls[i] = 'n';
else
del_nulls[i] = ' ';
@@ -667,23 +674,23 @@ RI_FKey_noaction_del (FmgrInfo *proinfo)
*/
if (SPI_execp(qplan, del_values, del_nulls, 1) != SPI_OK_SELECT)
elog(ERROR, "SPI_execp() failed in RI_FKey_noaction_del()");
-
+
if (SPI_processed > 0)
elog(ERROR, "%s referential integrity violation - "
- "key in %s still referenced from %s",
- tgargs[RI_CONSTRAINT_NAME_ARGNO],
- tgargs[RI_PK_RELNAME_ARGNO],
- tgargs[RI_FK_RELNAME_ARGNO]);
+ "key in %s still referenced from %s",
+ tgargs[RI_CONSTRAINT_NAME_ARGNO],
+ tgargs[RI_PK_RELNAME_ARGNO],
+ tgargs[RI_FK_RELNAME_ARGNO]);
if (SPI_finish() != SPI_OK_FINISH)
elog(NOTICE, "SPI_finish() failed in RI_FKey_noaction_del()");
return NULL;
- /* ----------
- * Handle MATCH PARTIAL restrict delete.
- * ----------
- */
+ /* ----------
+ * Handle MATCH PARTIAL restrict delete.
+ * ----------
+ */
case RI_MATCH_TYPE_PARTIAL:
elog(ERROR, "MATCH PARTIAL not yet supported");
return NULL;
@@ -702,29 +709,29 @@ RI_FKey_noaction_del (FmgrInfo *proinfo)
* RI_FKey_noaction_upd -
*
* Give an error and roll back the current transaction if the
- * update has resulted in a violation of the given referential
- * integrity constraint.
+ * update has resulted in a violation of the given referential
+ * integrity constraint.
* ----------
*/
HeapTuple
-RI_FKey_noaction_upd (FmgrInfo *proinfo)
+RI_FKey_noaction_upd(FmgrInfo *proinfo)
{
- TriggerData *trigdata;
- int tgnargs;
- char **tgargs;
- Relation fk_rel;
- Relation pk_rel;
- HeapTuple new_row;
- HeapTuple old_row;
- RI_QueryKey qkey;
- void *qplan;
- Datum upd_values[RI_MAX_NUMKEYS];
- char upd_nulls[RI_MAX_NUMKEYS + 1];
- bool isnull;
- int i;
+ TriggerData *trigdata;
+ int tgnargs;
+ char **tgargs;
+ Relation fk_rel;
+ Relation pk_rel;
+ HeapTuple new_row;
+ HeapTuple old_row;
+ RI_QueryKey qkey;
+ void *qplan;
+ Datum upd_values[RI_MAX_NUMKEYS];
+ char upd_nulls[RI_MAX_NUMKEYS + 1];
+ bool isnull;
+ int i;
trigdata = CurrentTriggerData;
- CurrentTriggerData = NULL;
+ CurrentTriggerData = NULL;
ReferentialIntegritySnapshotOverride = true;
/* ----------
@@ -733,23 +740,23 @@ RI_FKey_noaction_upd (FmgrInfo *proinfo)
*/
if (trigdata == NULL)
elog(ERROR, "RI_FKey_noaction_upd() not fired by trigger manager");
- if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
- !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
+ if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
+ !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
elog(ERROR, "RI_FKey_noaction_upd() must be fired AFTER ROW");
if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
elog(ERROR, "RI_FKey_noaction_upd() must be fired for UPDATE");
/* ----------
- * Check for the correct # of call arguments
+ * Check for the correct # of call arguments
* ----------
*/
tgnargs = trigdata->tg_trigger->tgnargs;
- tgargs = trigdata->tg_trigger->tgargs;
+ tgargs = trigdata->tg_trigger->tgargs;
if (tgnargs < 4 || (tgnargs % 2) != 0)
elog(ERROR, "wrong # of arguments in call to RI_FKey_noaction_upd()");
if (tgnargs > RI_MAX_ARGUMENTS)
elog(ERROR, "too many keys (%d max) in call to RI_FKey_noaction_upd()",
- RI_MAX_NUMKEYS);
+ RI_MAX_NUMKEYS);
/* ----------
* Nothing to do if no column names to compare given
@@ -763,26 +770,26 @@ RI_FKey_noaction_upd (FmgrInfo *proinfo)
* the new and old tuple.
* ----------
*/
- fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
- pk_rel = trigdata->tg_relation;
+ fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
+ pk_rel = trigdata->tg_relation;
new_row = trigdata->tg_newtuple;
old_row = trigdata->tg_trigtuple;
switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]))
{
- /* ----------
- * SQL3 11.9 <referential constraint definition>
- * Gereral rules 6) a) iv):
- * MATCH <unspecified> or MATCH FULL
- * ... ON DELETE CASCADE
- * ----------
- */
+ /* ----------
+ * SQL3 11.9 <referential constraint definition>
+ * Gereral rules 6) a) iv):
+ * MATCH <unspecified> or MATCH FULL
+ * ... ON DELETE CASCADE
+ * ----------
+ */
case RI_MATCH_TYPE_UNSPECIFIED:
case RI_MATCH_TYPE_FULL:
ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
- RI_PLAN_NOACTION_UPD_CHECKREF,
- fk_rel, pk_rel,
- tgnargs, tgargs);
+ RI_PLAN_NOACTION_UPD_CHECKREF,
+ fk_rel, pk_rel,
+ tgnargs, tgargs);
switch (ri_NullCheck(pk_rel, old_row, &qkey, RI_KEYPAIR_PK_IDX))
{
@@ -795,7 +802,7 @@ RI_FKey_noaction_upd (FmgrInfo *proinfo)
*/
heap_close(fk_rel, NoLock);
return NULL;
-
+
case RI_KEYS_NONE_NULL:
/* ----------
* Have a full qualified key - continue below
@@ -810,7 +817,7 @@ RI_FKey_noaction_upd (FmgrInfo *proinfo)
* ----------
*/
if (ri_KeysEqual(pk_rel, old_row, new_row, &qkey,
- RI_KEYPAIR_PK_IDX))
+ RI_KEYPAIR_PK_IDX))
return NULL;
if (SPI_connect() != SPI_OK_CONNECT)
@@ -825,7 +832,7 @@ RI_FKey_noaction_upd (FmgrInfo *proinfo)
{
char buf[256];
char querystr[8192];
- char *querysep;
+ char *querysep;
Oid queryoids[RI_MAX_NUMKEYS];
/* ----------
@@ -837,20 +844,20 @@ RI_FKey_noaction_upd (FmgrInfo *proinfo)
* how to compare these two types by '='.
* ----------
*/
- sprintf(querystr, "SELECT oid FROM \"%s\"",
- tgargs[RI_FK_RELNAME_ARGNO]);
+ sprintf(querystr, "SELECT oid FROM \"%s\"",
+ tgargs[RI_FK_RELNAME_ARGNO]);
querysep = "WHERE";
for (i = 0; i < qkey.nkeypairs; i++)
{
- sprintf(buf, " %s \"%s\" = $%d", querysep,
- tgargs[4 + i * 2], i + 1);
+ sprintf(buf, " %s \"%s\" = $%d", querysep,
+ tgargs[4 + i * 2], i + 1);
strcat(querystr, buf);
querysep = "AND";
queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
}
- sprintf(buf, " FOR UPDATE OF \"%s\"",
- tgargs[RI_FK_RELNAME_ARGNO]);
+ sprintf(buf, " FOR UPDATE OF \"%s\"",
+ tgargs[RI_FK_RELNAME_ARGNO]);
strcat(querystr, buf);
/* ----------
@@ -870,10 +877,10 @@ RI_FKey_noaction_upd (FmgrInfo *proinfo)
for (i = 0; i < qkey.nkeypairs; i++)
{
upd_values[i] = SPI_getbinval(old_row,
- pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX],
- &isnull);
- if (isnull)
+ pk_rel->rd_att,
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX],
+ &isnull);
+ if (isnull)
upd_nulls[i] = 'n';
else
upd_nulls[i] = ' ';
@@ -886,23 +893,23 @@ RI_FKey_noaction_upd (FmgrInfo *proinfo)
*/
if (SPI_execp(qplan, upd_values, upd_nulls, 1) != SPI_OK_SELECT)
elog(ERROR, "SPI_execp() failed in RI_FKey_noaction_upd()");
-
+
if (SPI_processed > 0)
elog(ERROR, "%s referential integrity violation - "
- "key in %s still referenced from %s",
- tgargs[RI_CONSTRAINT_NAME_ARGNO],
- tgargs[RI_PK_RELNAME_ARGNO],
- tgargs[RI_FK_RELNAME_ARGNO]);
+ "key in %s still referenced from %s",
+ tgargs[RI_CONSTRAINT_NAME_ARGNO],
+ tgargs[RI_PK_RELNAME_ARGNO],
+ tgargs[RI_FK_RELNAME_ARGNO]);
if (SPI_finish() != SPI_OK_FINISH)
elog(NOTICE, "SPI_finish() failed in RI_FKey_noaction_upd()");
return NULL;
- /* ----------
- * Handle MATCH PARTIAL noaction update.
- * ----------
- */
+ /* ----------
+ * Handle MATCH PARTIAL noaction update.
+ * ----------
+ */
case RI_MATCH_TYPE_PARTIAL:
elog(ERROR, "MATCH PARTIAL not yet supported");
return NULL;
@@ -924,23 +931,23 @@ RI_FKey_noaction_upd (FmgrInfo *proinfo)
* ----------
*/
HeapTuple
-RI_FKey_cascade_del (FmgrInfo *proinfo)
+RI_FKey_cascade_del(FmgrInfo *proinfo)
{
- TriggerData *trigdata;
- int tgnargs;
- char **tgargs;
- Relation fk_rel;
- Relation pk_rel;
- HeapTuple old_row;
- RI_QueryKey qkey;
- void *qplan;
- Datum del_values[RI_MAX_NUMKEYS];
- char del_nulls[RI_MAX_NUMKEYS + 1];
- bool isnull;
- int i;
+ TriggerData *trigdata;
+ int tgnargs;
+ char **tgargs;
+ Relation fk_rel;
+ Relation pk_rel;
+ HeapTuple old_row;
+ RI_QueryKey qkey;
+ void *qplan;
+ Datum del_values[RI_MAX_NUMKEYS];
+ char del_nulls[RI_MAX_NUMKEYS + 1];
+ bool isnull;
+ int i;
trigdata = CurrentTriggerData;
- CurrentTriggerData = NULL;
+ CurrentTriggerData = NULL;
ReferentialIntegritySnapshotOverride = true;
/* ----------
@@ -949,23 +956,23 @@ RI_FKey_cascade_del (FmgrInfo *proinfo)
*/
if (trigdata == NULL)
elog(ERROR, "RI_FKey_cascade_del() not fired by trigger manager");
- if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
- !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
+ if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
+ !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
elog(ERROR, "RI_FKey_cascade_del() must be fired AFTER ROW");
if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
elog(ERROR, "RI_FKey_cascade_del() must be fired for DELETE");
/* ----------
- * Check for the correct # of call arguments
+ * Check for the correct # of call arguments
* ----------
*/
tgnargs = trigdata->tg_trigger->tgnargs;
- tgargs = trigdata->tg_trigger->tgargs;
+ tgargs = trigdata->tg_trigger->tgargs;
if (tgnargs < 4 || (tgnargs % 2) != 0)
elog(ERROR, "wrong # of arguments in call to RI_FKey_cascade_del()");
if (tgnargs > RI_MAX_ARGUMENTS)
elog(ERROR, "too many keys (%d max) in call to RI_FKey_cascade_del()",
- RI_MAX_NUMKEYS);
+ RI_MAX_NUMKEYS);
/* ----------
* Nothing to do if no column names to compare given
@@ -979,25 +986,25 @@ RI_FKey_cascade_del (FmgrInfo *proinfo)
* the old tuple.
* ----------
*/
- fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
- pk_rel = trigdata->tg_relation;
+ fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
+ pk_rel = trigdata->tg_relation;
old_row = trigdata->tg_trigtuple;
switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]))
{
- /* ----------
- * SQL3 11.9 <referential constraint definition>
- * Gereral rules 6) a) i):
- * MATCH <unspecified> or MATCH FULL
- * ... ON DELETE CASCADE
- * ----------
- */
+ /* ----------
+ * SQL3 11.9 <referential constraint definition>
+ * Gereral rules 6) a) i):
+ * MATCH <unspecified> or MATCH FULL
+ * ... ON DELETE CASCADE
+ * ----------
+ */
case RI_MATCH_TYPE_UNSPECIFIED:
case RI_MATCH_TYPE_FULL:
ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
- RI_PLAN_CASCADE_DEL_DODELETE,
- fk_rel, pk_rel,
- tgnargs, tgargs);
+ RI_PLAN_CASCADE_DEL_DODELETE,
+ fk_rel, pk_rel,
+ tgnargs, tgargs);
switch (ri_NullCheck(pk_rel, old_row, &qkey, RI_KEYPAIR_PK_IDX))
{
@@ -1010,7 +1017,7 @@ RI_FKey_cascade_del (FmgrInfo *proinfo)
*/
heap_close(fk_rel, NoLock);
return NULL;
-
+
case RI_KEYS_NONE_NULL:
/* ----------
* Have a full qualified key - continue below
@@ -1031,7 +1038,7 @@ RI_FKey_cascade_del (FmgrInfo *proinfo)
{
char buf[256];
char querystr[8192];
- char *querysep;
+ char *querysep;
Oid queryoids[RI_MAX_NUMKEYS];
/* ----------
@@ -1043,17 +1050,17 @@ RI_FKey_cascade_del (FmgrInfo *proinfo)
* how to compare these two types by '='.
* ----------
*/
- sprintf(querystr, "DELETE FROM \"%s\"",
- tgargs[RI_FK_RELNAME_ARGNO]);
+ sprintf(querystr, "DELETE FROM \"%s\"",
+ tgargs[RI_FK_RELNAME_ARGNO]);
querysep = "WHERE";
for (i = 0; i < qkey.nkeypairs; i++)
{
- sprintf(buf, " %s \"%s\" = $%d", querysep,
- tgargs[4 + i * 2], i + 1);
+ sprintf(buf, " %s \"%s\" = $%d", querysep,
+ tgargs[4 + i * 2], i + 1);
strcat(querystr, buf);
querysep = "AND";
queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
}
/* ----------
@@ -1073,10 +1080,10 @@ RI_FKey_cascade_del (FmgrInfo *proinfo)
for (i = 0; i < qkey.nkeypairs; i++)
{
del_values[i] = SPI_getbinval(old_row,
- pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX],
- &isnull);
- if (isnull)
+ pk_rel->rd_att,
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX],
+ &isnull);
+ if (isnull)
del_nulls[i] = 'n';
else
del_nulls[i] = ' ';
@@ -1089,16 +1096,16 @@ RI_FKey_cascade_del (FmgrInfo *proinfo)
*/
if (SPI_execp(qplan, del_values, del_nulls, 0) != SPI_OK_DELETE)
elog(ERROR, "SPI_execp() failed in RI_FKey_cascade_del()");
-
+
if (SPI_finish() != SPI_OK_FINISH)
elog(NOTICE, "SPI_finish() failed in RI_FKey_cascade_del()");
return NULL;
- /* ----------
- * Handle MATCH PARTIAL cascaded delete.
- * ----------
- */
+ /* ----------
+ * Handle MATCH PARTIAL cascaded delete.
+ * ----------
+ */
case RI_MATCH_TYPE_PARTIAL:
elog(ERROR, "MATCH PARTIAL not yet supported");
return NULL;
@@ -1120,25 +1127,25 @@ RI_FKey_cascade_del (FmgrInfo *proinfo)
* ----------
*/
HeapTuple
-RI_FKey_cascade_upd (FmgrInfo *proinfo)
+RI_FKey_cascade_upd(FmgrInfo *proinfo)
{
- TriggerData *trigdata;
- int tgnargs;
- char **tgargs;
- Relation fk_rel;
- Relation pk_rel;
- HeapTuple new_row;
- HeapTuple old_row;
- RI_QueryKey qkey;
- void *qplan;
- Datum upd_values[RI_MAX_NUMKEYS * 2];
- char upd_nulls[RI_MAX_NUMKEYS * 2 + 1];
- bool isnull;
- int i;
- int j;
+ TriggerData *trigdata;
+ int tgnargs;
+ char **tgargs;
+ Relation fk_rel;
+ Relation pk_rel;
+ HeapTuple new_row;
+ HeapTuple old_row;
+ RI_QueryKey qkey;
+ void *qplan;
+ Datum upd_values[RI_MAX_NUMKEYS * 2];
+ char upd_nulls[RI_MAX_NUMKEYS * 2 + 1];
+ bool isnull;
+ int i;
+ int j;
trigdata = CurrentTriggerData;
- CurrentTriggerData = NULL;
+ CurrentTriggerData = NULL;
ReferentialIntegritySnapshotOverride = true;
/* ----------
@@ -1147,23 +1154,23 @@ RI_FKey_cascade_upd (FmgrInfo *proinfo)
*/
if (trigdata == NULL)
elog(ERROR, "RI_FKey_cascade_upd() not fired by trigger manager");
- if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
- !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
+ if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
+ !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
elog(ERROR, "RI_FKey_cascade_upd() must be fired AFTER ROW");
if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
elog(ERROR, "RI_FKey_cascade_upd() must be fired for UPDATE");
/* ----------
- * Check for the correct # of call arguments
+ * Check for the correct # of call arguments
* ----------
*/
tgnargs = trigdata->tg_trigger->tgnargs;
- tgargs = trigdata->tg_trigger->tgargs;
+ tgargs = trigdata->tg_trigger->tgargs;
if (tgnargs < 4 || (tgnargs % 2) != 0)
elog(ERROR, "wrong # of arguments in call to RI_FKey_cascade_upd()");
if (tgnargs > RI_MAX_ARGUMENTS)
elog(ERROR, "too many keys (%d max) in call to RI_FKey_cascade_upd()",
- RI_MAX_NUMKEYS);
+ RI_MAX_NUMKEYS);
/* ----------
* Nothing to do if no column names to compare given
@@ -1177,26 +1184,26 @@ RI_FKey_cascade_upd (FmgrInfo *proinfo)
* the new and old tuple.
* ----------
*/
- fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
- pk_rel = trigdata->tg_relation;
+ fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
+ pk_rel = trigdata->tg_relation;
new_row = trigdata->tg_newtuple;
old_row = trigdata->tg_trigtuple;
switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]))
{
- /* ----------
- * SQL3 11.9 <referential constraint definition>
- * Gereral rules 7) a) i):
- * MATCH <unspecified> or MATCH FULL
- * ... ON UPDATE CASCADE
- * ----------
- */
+ /* ----------
+ * SQL3 11.9 <referential constraint definition>
+ * Gereral rules 7) a) i):
+ * MATCH <unspecified> or MATCH FULL
+ * ... ON UPDATE CASCADE
+ * ----------
+ */
case RI_MATCH_TYPE_UNSPECIFIED:
case RI_MATCH_TYPE_FULL:
ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
- RI_PLAN_CASCADE_UPD_DOUPDATE,
- fk_rel, pk_rel,
- tgnargs, tgargs);
+ RI_PLAN_CASCADE_UPD_DOUPDATE,
+ fk_rel, pk_rel,
+ tgnargs, tgargs);
switch (ri_NullCheck(pk_rel, old_row, &qkey, RI_KEYPAIR_PK_IDX))
{
@@ -1209,7 +1216,7 @@ RI_FKey_cascade_upd (FmgrInfo *proinfo)
*/
heap_close(fk_rel, NoLock);
return NULL;
-
+
case RI_KEYS_NONE_NULL:
/* ----------
* Have a full qualified key - continue below
@@ -1224,7 +1231,7 @@ RI_FKey_cascade_upd (FmgrInfo *proinfo)
* ----------
*/
if (ri_KeysEqual(pk_rel, old_row, new_row, &qkey,
- RI_KEYPAIR_PK_IDX))
+ RI_KEYPAIR_PK_IDX))
return NULL;
if (SPI_connect() != SPI_OK_CONNECT)
@@ -1240,8 +1247,8 @@ RI_FKey_cascade_upd (FmgrInfo *proinfo)
char buf[256];
char querystr[8192];
char qualstr[8192];
- char *querysep;
- char *qualsep;
+ char *querysep;
+ char *qualsep;
Oid queryoids[RI_MAX_NUMKEYS * 2];
/* ----------
@@ -1254,23 +1261,23 @@ RI_FKey_cascade_upd (FmgrInfo *proinfo)
* how to compare these two types by '='.
* ----------
*/
- sprintf(querystr, "UPDATE \"%s\" SET",
- tgargs[RI_FK_RELNAME_ARGNO]);
+ sprintf(querystr, "UPDATE \"%s\" SET",
+ tgargs[RI_FK_RELNAME_ARGNO]);
qualstr[0] = '\0';
querysep = "";
qualsep = "WHERE";
for (i = 0, j = qkey.nkeypairs; i < qkey.nkeypairs; i++, j++)
{
- sprintf(buf, "%s \"%s\" = $%d", querysep,
- tgargs[4 + i * 2], i + 1);
+ sprintf(buf, "%s \"%s\" = $%d", querysep,
+ tgargs[4 + i * 2], i + 1);
strcat(querystr, buf);
sprintf(buf, " %s \"%s\" = $%d", qualsep,
- tgargs[4 + i * 2], j + 1);
+ tgargs[4 + i * 2], j + 1);
strcat(qualstr, buf);
querysep = ",";
qualsep = "AND";
queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
queryoids[j] = queryoids[i];
}
strcat(querystr, qualstr);
@@ -1292,19 +1299,19 @@ RI_FKey_cascade_upd (FmgrInfo *proinfo)
for (i = 0, j = qkey.nkeypairs; i < qkey.nkeypairs; i++, j++)
{
upd_values[i] = SPI_getbinval(new_row,
- pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX],
- &isnull);
- if (isnull)
+ pk_rel->rd_att,
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX],
+ &isnull);
+ if (isnull)
upd_nulls[i] = 'n';
else
upd_nulls[i] = ' ';
upd_values[j] = SPI_getbinval(old_row,
- pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX],
- &isnull);
- if (isnull)
+ pk_rel->rd_att,
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX],
+ &isnull);
+ if (isnull)
upd_nulls[j] = 'n';
else
upd_nulls[j] = ' ';
@@ -1317,16 +1324,16 @@ RI_FKey_cascade_upd (FmgrInfo *proinfo)
*/
if (SPI_execp(qplan, upd_values, upd_nulls, 0) != SPI_OK_UPDATE)
elog(ERROR, "SPI_execp() failed in RI_FKey_cascade_upd()");
-
+
if (SPI_finish() != SPI_OK_FINISH)
elog(NOTICE, "SPI_finish() failed in RI_FKey_cascade_upd()");
return NULL;
- /* ----------
- * Handle MATCH PARTIAL cascade update.
- * ----------
- */
+ /* ----------
+ * Handle MATCH PARTIAL cascade update.
+ * ----------
+ */
case RI_MATCH_TYPE_PARTIAL:
elog(ERROR, "MATCH PARTIAL not yet supported");
return NULL;
@@ -1346,32 +1353,32 @@ RI_FKey_cascade_upd (FmgrInfo *proinfo)
*
* Restrict delete from PK table to rows unreferenced by foreign key.
*
- * SQL3 intends that this referential action occur BEFORE the
- * update is performed, rather than after. This appears to be
- * the only difference between "NO ACTION" and "RESTRICT".
+ * SQL3 intends that this referential action occur BEFORE the
+ * update is performed, rather than after. This appears to be
+ * the only difference between "NO ACTION" and "RESTRICT".
*
- * For now, however, we treat "RESTRICT" and "NO ACTION" as
- * equivalent.
+ * For now, however, we treat "RESTRICT" and "NO ACTION" as
+ * equivalent.
* ----------
*/
HeapTuple
-RI_FKey_restrict_del (FmgrInfo *proinfo)
+RI_FKey_restrict_del(FmgrInfo *proinfo)
{
- TriggerData *trigdata;
- int tgnargs;
- char **tgargs;
- Relation fk_rel;
- Relation pk_rel;
- HeapTuple old_row;
- RI_QueryKey qkey;
- void *qplan;
- Datum del_values[RI_MAX_NUMKEYS];
- char del_nulls[RI_MAX_NUMKEYS + 1];
- bool isnull;
- int i;
+ TriggerData *trigdata;
+ int tgnargs;
+ char **tgargs;
+ Relation fk_rel;
+ Relation pk_rel;
+ HeapTuple old_row;
+ RI_QueryKey qkey;
+ void *qplan;
+ Datum del_values[RI_MAX_NUMKEYS];
+ char del_nulls[RI_MAX_NUMKEYS + 1];
+ bool isnull;
+ int i;
trigdata = CurrentTriggerData;
- CurrentTriggerData = NULL;
+ CurrentTriggerData = NULL;
ReferentialIntegritySnapshotOverride = true;
/* ----------
@@ -1380,23 +1387,23 @@ RI_FKey_restrict_del (FmgrInfo *proinfo)
*/
if (trigdata == NULL)
elog(ERROR, "RI_FKey_restrict_del() not fired by trigger manager");
- if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
- !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
+ if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
+ !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
elog(ERROR, "RI_FKey_restrict_del() must be fired AFTER ROW");
if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
elog(ERROR, "RI_FKey_restrict_del() must be fired for DELETE");
/* ----------
- * Check for the correct # of call arguments
+ * Check for the correct # of call arguments
* ----------
*/
tgnargs = trigdata->tg_trigger->tgnargs;
- tgargs = trigdata->tg_trigger->tgargs;
+ tgargs = trigdata->tg_trigger->tgargs;
if (tgnargs < 4 || (tgnargs % 2) != 0)
elog(ERROR, "wrong # of arguments in call to RI_FKey_restrict_del()");
if (tgnargs > RI_MAX_ARGUMENTS)
elog(ERROR, "too many keys (%d max) in call to RI_FKey_restrict_del()",
- RI_MAX_NUMKEYS);
+ RI_MAX_NUMKEYS);
/* ----------
* Nothing to do if no column names to compare given
@@ -1410,25 +1417,25 @@ RI_FKey_restrict_del (FmgrInfo *proinfo)
* the old tuple.
* ----------
*/
- fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
- pk_rel = trigdata->tg_relation;
+ fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
+ pk_rel = trigdata->tg_relation;
old_row = trigdata->tg_trigtuple;
switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]))
{
- /* ----------
- * SQL3 11.9 <referential constraint definition>
- * Gereral rules 6) a) iv):
- * MATCH <unspecified> or MATCH FULL
- * ... ON DELETE CASCADE
- * ----------
- */
+ /* ----------
+ * SQL3 11.9 <referential constraint definition>
+ * Gereral rules 6) a) iv):
+ * MATCH <unspecified> or MATCH FULL
+ * ... ON DELETE CASCADE
+ * ----------
+ */
case RI_MATCH_TYPE_UNSPECIFIED:
case RI_MATCH_TYPE_FULL:
ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
- RI_PLAN_RESTRICT_DEL_CHECKREF,
- fk_rel, pk_rel,
- tgnargs, tgargs);
+ RI_PLAN_RESTRICT_DEL_CHECKREF,
+ fk_rel, pk_rel,
+ tgnargs, tgargs);
switch (ri_NullCheck(pk_rel, old_row, &qkey, RI_KEYPAIR_PK_IDX))
{
@@ -1441,7 +1448,7 @@ RI_FKey_restrict_del (FmgrInfo *proinfo)
*/
heap_close(fk_rel, NoLock);
return NULL;
-
+
case RI_KEYS_NONE_NULL:
/* ----------
* Have a full qualified key - continue below
@@ -1463,7 +1470,7 @@ RI_FKey_restrict_del (FmgrInfo *proinfo)
{
char buf[256];
char querystr[8192];
- char *querysep;
+ char *querysep;
Oid queryoids[RI_MAX_NUMKEYS];
/* ----------
@@ -1475,20 +1482,20 @@ RI_FKey_restrict_del (FmgrInfo *proinfo)
* how to compare these two types by '='.
* ----------
*/
- sprintf(querystr, "SELECT oid FROM \"%s\"",
- tgargs[RI_FK_RELNAME_ARGNO]);
+ sprintf(querystr, "SELECT oid FROM \"%s\"",
+ tgargs[RI_FK_RELNAME_ARGNO]);
querysep = "WHERE";
for (i = 0; i < qkey.nkeypairs; i++)
{
- sprintf(buf, " %s \"%s\" = $%d", querysep,
- tgargs[4 + i * 2], i + 1);
+ sprintf(buf, " %s \"%s\" = $%d", querysep,
+ tgargs[4 + i * 2], i + 1);
strcat(querystr, buf);
querysep = "AND";
queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
}
- sprintf(buf, " FOR UPDATE OF \"%s\"",
- tgargs[RI_FK_RELNAME_ARGNO]);
+ sprintf(buf, " FOR UPDATE OF \"%s\"",
+ tgargs[RI_FK_RELNAME_ARGNO]);
strcat(querystr, buf);
/* ----------
@@ -1508,10 +1515,10 @@ RI_FKey_restrict_del (FmgrInfo *proinfo)
for (i = 0; i < qkey.nkeypairs; i++)
{
del_values[i] = SPI_getbinval(old_row,
- pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX],
- &isnull);
- if (isnull)
+ pk_rel->rd_att,
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX],
+ &isnull);
+ if (isnull)
del_nulls[i] = 'n';
else
del_nulls[i] = ' ';
@@ -1524,23 +1531,23 @@ RI_FKey_restrict_del (FmgrInfo *proinfo)
*/
if (SPI_execp(qplan, del_values, del_nulls, 1) != SPI_OK_SELECT)
elog(ERROR, "SPI_execp() failed in RI_FKey_restrict_del()");
-
+
if (SPI_processed > 0)
elog(ERROR, "%s referential integrity violation - "
- "key in %s still referenced from %s",
- tgargs[RI_CONSTRAINT_NAME_ARGNO],
- tgargs[RI_PK_RELNAME_ARGNO],
- tgargs[RI_FK_RELNAME_ARGNO]);
+ "key in %s still referenced from %s",
+ tgargs[RI_CONSTRAINT_NAME_ARGNO],
+ tgargs[RI_PK_RELNAME_ARGNO],
+ tgargs[RI_FK_RELNAME_ARGNO]);
if (SPI_finish() != SPI_OK_FINISH)
elog(NOTICE, "SPI_finish() failed in RI_FKey_restrict_del()");
return NULL;
- /* ----------
- * Handle MATCH PARTIAL restrict delete.
- * ----------
- */
+ /* ----------
+ * Handle MATCH PARTIAL restrict delete.
+ * ----------
+ */
case RI_MATCH_TYPE_PARTIAL:
elog(ERROR, "MATCH PARTIAL not yet supported");
return NULL;
@@ -1560,33 +1567,33 @@ RI_FKey_restrict_del (FmgrInfo *proinfo)
*
* Restrict update of PK to rows unreferenced by foreign key.
*
- * SQL3 intends that this referential action occur BEFORE the
- * update is performed, rather than after. This appears to be
- * the only difference between "NO ACTION" and "RESTRICT".
+ * SQL3 intends that this referential action occur BEFORE the
+ * update is performed, rather than after. This appears to be
+ * the only difference between "NO ACTION" and "RESTRICT".
*
- * For now, however, we treat "RESTRICT" and "NO ACTION" as
- * equivalent.
+ * For now, however, we treat "RESTRICT" and "NO ACTION" as
+ * equivalent.
* ----------
*/
HeapTuple
-RI_FKey_restrict_upd (FmgrInfo *proinfo)
+RI_FKey_restrict_upd(FmgrInfo *proinfo)
{
- TriggerData *trigdata;
- int tgnargs;
- char **tgargs;
- Relation fk_rel;
- Relation pk_rel;
- HeapTuple new_row;
- HeapTuple old_row;
- RI_QueryKey qkey;
- void *qplan;
- Datum upd_values[RI_MAX_NUMKEYS];
- char upd_nulls[RI_MAX_NUMKEYS + 1];
- bool isnull;
- int i;
+ TriggerData *trigdata;
+ int tgnargs;
+ char **tgargs;
+ Relation fk_rel;
+ Relation pk_rel;
+ HeapTuple new_row;
+ HeapTuple old_row;
+ RI_QueryKey qkey;
+ void *qplan;
+ Datum upd_values[RI_MAX_NUMKEYS];
+ char upd_nulls[RI_MAX_NUMKEYS + 1];
+ bool isnull;
+ int i;
trigdata = CurrentTriggerData;
- CurrentTriggerData = NULL;
+ CurrentTriggerData = NULL;
ReferentialIntegritySnapshotOverride = true;
/* ----------
@@ -1595,23 +1602,23 @@ RI_FKey_restrict_upd (FmgrInfo *proinfo)
*/
if (trigdata == NULL)
elog(ERROR, "RI_FKey_restrict_upd() not fired by trigger manager");
- if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
- !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
+ if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
+ !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
elog(ERROR, "RI_FKey_restrict_upd() must be fired AFTER ROW");
if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
elog(ERROR, "RI_FKey_restrict_upd() must be fired for UPDATE");
/* ----------
- * Check for the correct # of call arguments
+ * Check for the correct # of call arguments
* ----------
*/
tgnargs = trigdata->tg_trigger->tgnargs;
- tgargs = trigdata->tg_trigger->tgargs;
+ tgargs = trigdata->tg_trigger->tgargs;
if (tgnargs < 4 || (tgnargs % 2) != 0)
elog(ERROR, "wrong # of arguments in call to RI_FKey_restrict_upd()");
if (tgnargs > RI_MAX_ARGUMENTS)
elog(ERROR, "too many keys (%d max) in call to RI_FKey_restrict_upd()",
- RI_MAX_NUMKEYS);
+ RI_MAX_NUMKEYS);
/* ----------
* Nothing to do if no column names to compare given
@@ -1625,26 +1632,26 @@ RI_FKey_restrict_upd (FmgrInfo *proinfo)
* the new and old tuple.
* ----------
*/
- fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
- pk_rel = trigdata->tg_relation;
+ fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
+ pk_rel = trigdata->tg_relation;
new_row = trigdata->tg_newtuple;
old_row = trigdata->tg_trigtuple;
switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]))
{
- /* ----------
- * SQL3 11.9 <referential constraint definition>
- * Gereral rules 6) a) iv):
- * MATCH <unspecified> or MATCH FULL
- * ... ON DELETE CASCADE
- * ----------
- */
+ /* ----------
+ * SQL3 11.9 <referential constraint definition>
+ * Gereral rules 6) a) iv):
+ * MATCH <unspecified> or MATCH FULL
+ * ... ON DELETE CASCADE
+ * ----------
+ */
case RI_MATCH_TYPE_UNSPECIFIED:
case RI_MATCH_TYPE_FULL:
ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
- RI_PLAN_RESTRICT_UPD_CHECKREF,
- fk_rel, pk_rel,
- tgnargs, tgargs);
+ RI_PLAN_RESTRICT_UPD_CHECKREF,
+ fk_rel, pk_rel,
+ tgnargs, tgargs);
switch (ri_NullCheck(pk_rel, old_row, &qkey, RI_KEYPAIR_PK_IDX))
{
@@ -1657,7 +1664,7 @@ RI_FKey_restrict_upd (FmgrInfo *proinfo)
*/
heap_close(fk_rel, NoLock);
return NULL;
-
+
case RI_KEYS_NONE_NULL:
/* ----------
* Have a full qualified key - continue below
@@ -1672,7 +1679,7 @@ RI_FKey_restrict_upd (FmgrInfo *proinfo)
* ----------
*/
if (ri_KeysEqual(pk_rel, old_row, new_row, &qkey,
- RI_KEYPAIR_PK_IDX))
+ RI_KEYPAIR_PK_IDX))
return NULL;
if (SPI_connect() != SPI_OK_CONNECT)
@@ -1687,7 +1694,7 @@ RI_FKey_restrict_upd (FmgrInfo *proinfo)
{
char buf[256];
char querystr[8192];
- char *querysep;
+ char *querysep;
Oid queryoids[RI_MAX_NUMKEYS];
/* ----------
@@ -1699,20 +1706,20 @@ RI_FKey_restrict_upd (FmgrInfo *proinfo)
* how to compare these two types by '='.
* ----------
*/
- sprintf(querystr, "SELECT oid FROM \"%s\"",
- tgargs[RI_FK_RELNAME_ARGNO]);
+ sprintf(querystr, "SELECT oid FROM \"%s\"",
+ tgargs[RI_FK_RELNAME_ARGNO]);
querysep = "WHERE";
for (i = 0; i < qkey.nkeypairs; i++)
{
- sprintf(buf, " %s \"%s\" = $%d", querysep,
- tgargs[4 + i * 2], i + 1);
+ sprintf(buf, " %s \"%s\" = $%d", querysep,
+ tgargs[4 + i * 2], i + 1);
strcat(querystr, buf);
querysep = "AND";
queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
}
- sprintf(buf, " FOR UPDATE OF \"%s\"",
- tgargs[RI_FK_RELNAME_ARGNO]);
+ sprintf(buf, " FOR UPDATE OF \"%s\"",
+ tgargs[RI_FK_RELNAME_ARGNO]);
strcat(querystr, buf);
/* ----------
@@ -1732,10 +1739,10 @@ RI_FKey_restrict_upd (FmgrInfo *proinfo)
for (i = 0; i < qkey.nkeypairs; i++)
{
upd_values[i] = SPI_getbinval(old_row,
- pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX],
- &isnull);
- if (isnull)
+ pk_rel->rd_att,
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX],
+ &isnull);
+ if (isnull)
upd_nulls[i] = 'n';
else
upd_nulls[i] = ' ';
@@ -1748,23 +1755,23 @@ RI_FKey_restrict_upd (FmgrInfo *proinfo)
*/
if (SPI_execp(qplan, upd_values, upd_nulls, 1) != SPI_OK_SELECT)
elog(ERROR, "SPI_execp() failed in RI_FKey_restrict_upd()");
-
+
if (SPI_processed > 0)
elog(ERROR, "%s referential integrity violation - "
- "key in %s still referenced from %s",
- tgargs[RI_CONSTRAINT_NAME_ARGNO],
- tgargs[RI_PK_RELNAME_ARGNO],
- tgargs[RI_FK_RELNAME_ARGNO]);
+ "key in %s still referenced from %s",
+ tgargs[RI_CONSTRAINT_NAME_ARGNO],
+ tgargs[RI_PK_RELNAME_ARGNO],
+ tgargs[RI_FK_RELNAME_ARGNO]);
if (SPI_finish() != SPI_OK_FINISH)
elog(NOTICE, "SPI_finish() failed in RI_FKey_restrict_upd()");
return NULL;
- /* ----------
- * Handle MATCH PARTIAL restrict update.
- * ----------
- */
+ /* ----------
+ * Handle MATCH PARTIAL restrict update.
+ * ----------
+ */
case RI_MATCH_TYPE_PARTIAL:
elog(ERROR, "MATCH PARTIAL not yet supported");
return NULL;
@@ -1786,23 +1793,23 @@ RI_FKey_restrict_upd (FmgrInfo *proinfo)
* ----------
*/
HeapTuple
-RI_FKey_setnull_del (FmgrInfo *proinfo)
+RI_FKey_setnull_del(FmgrInfo *proinfo)
{
- TriggerData *trigdata;
- int tgnargs;
- char **tgargs;
- Relation fk_rel;
- Relation pk_rel;
- HeapTuple old_row;
- RI_QueryKey qkey;
- void *qplan;
- Datum upd_values[RI_MAX_NUMKEYS];
- char upd_nulls[RI_MAX_NUMKEYS + 1];
- bool isnull;
- int i;
+ TriggerData *trigdata;
+ int tgnargs;
+ char **tgargs;
+ Relation fk_rel;
+ Relation pk_rel;
+ HeapTuple old_row;
+ RI_QueryKey qkey;
+ void *qplan;
+ Datum upd_values[RI_MAX_NUMKEYS];
+ char upd_nulls[RI_MAX_NUMKEYS + 1];
+ bool isnull;
+ int i;
trigdata = CurrentTriggerData;
- CurrentTriggerData = NULL;
+ CurrentTriggerData = NULL;
ReferentialIntegritySnapshotOverride = true;
/* ----------
@@ -1811,23 +1818,23 @@ RI_FKey_setnull_del (FmgrInfo *proinfo)
*/
if (trigdata == NULL)
elog(ERROR, "RI_FKey_setnull_del() not fired by trigger manager");
- if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
- !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
+ if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
+ !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
elog(ERROR, "RI_FKey_setnull_del() must be fired AFTER ROW");
if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
elog(ERROR, "RI_FKey_setnull_del() must be fired for DELETE");
/* ----------
- * Check for the correct # of call arguments
+ * Check for the correct # of call arguments
* ----------
*/
tgnargs = trigdata->tg_trigger->tgnargs;
- tgargs = trigdata->tg_trigger->tgargs;
+ tgargs = trigdata->tg_trigger->tgargs;
if (tgnargs < 4 || (tgnargs % 2) != 0)
elog(ERROR, "wrong # of arguments in call to RI_FKey_setnull_del()");
if (tgnargs > RI_MAX_ARGUMENTS)
elog(ERROR, "too many keys (%d max) in call to RI_FKey_setnull_del()",
- RI_MAX_NUMKEYS);
+ RI_MAX_NUMKEYS);
/* ----------
* Nothing to do if no column names to compare given
@@ -1841,25 +1848,25 @@ RI_FKey_setnull_del (FmgrInfo *proinfo)
* the old tuple.
* ----------
*/
- fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
- pk_rel = trigdata->tg_relation;
+ fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
+ pk_rel = trigdata->tg_relation;
old_row = trigdata->tg_trigtuple;
switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]))
{
- /* ----------
- * SQL3 11.9 <referential constraint definition>
- * Gereral rules 6) a) ii):
- * MATCH <UNSPECIFIED> or MATCH FULL
- * ... ON DELETE SET NULL
- * ----------
- */
+ /* ----------
+ * SQL3 11.9 <referential constraint definition>
+ * Gereral rules 6) a) ii):
+ * MATCH <UNSPECIFIED> or MATCH FULL
+ * ... ON DELETE SET NULL
+ * ----------
+ */
case RI_MATCH_TYPE_UNSPECIFIED:
case RI_MATCH_TYPE_FULL:
ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
- RI_PLAN_SETNULL_DEL_DOUPDATE,
- fk_rel, pk_rel,
- tgnargs, tgargs);
+ RI_PLAN_SETNULL_DEL_DOUPDATE,
+ fk_rel, pk_rel,
+ tgnargs, tgargs);
switch (ri_NullCheck(pk_rel, old_row, &qkey, RI_KEYPAIR_PK_IDX))
{
@@ -1872,7 +1879,7 @@ RI_FKey_setnull_del (FmgrInfo *proinfo)
*/
heap_close(fk_rel, NoLock);
return NULL;
-
+
case RI_KEYS_NONE_NULL:
/* ----------
* Have a full qualified key - continue below
@@ -1895,8 +1902,8 @@ RI_FKey_setnull_del (FmgrInfo *proinfo)
char buf[256];
char querystr[8192];
char qualstr[8192];
- char *querysep;
- char *qualsep;
+ char *querysep;
+ char *qualsep;
Oid queryoids[RI_MAX_NUMKEYS];
/* ----------
@@ -1909,23 +1916,23 @@ RI_FKey_setnull_del (FmgrInfo *proinfo)
* how to compare these two types by '='.
* ----------
*/
- sprintf(querystr, "UPDATE \"%s\" SET",
- tgargs[RI_FK_RELNAME_ARGNO]);
+ sprintf(querystr, "UPDATE \"%s\" SET",
+ tgargs[RI_FK_RELNAME_ARGNO]);
qualstr[0] = '\0';
querysep = "";
qualsep = "WHERE";
for (i = 0; i < qkey.nkeypairs; i++)
{
- sprintf(buf, "%s \"%s\" = NULL", querysep,
- tgargs[4 + i * 2]);
+ sprintf(buf, "%s \"%s\" = NULL", querysep,
+ tgargs[4 + i * 2]);
strcat(querystr, buf);
sprintf(buf, " %s \"%s\" = $%d", qualsep,
- tgargs[4 + i * 2], i + 1);
+ tgargs[4 + i * 2], i + 1);
strcat(qualstr, buf);
querysep = ",";
qualsep = "AND";
queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
}
strcat(querystr, qualstr);
@@ -1946,10 +1953,10 @@ RI_FKey_setnull_del (FmgrInfo *proinfo)
for (i = 0; i < qkey.nkeypairs; i++)
{
upd_values[i] = SPI_getbinval(old_row,
- pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX],
- &isnull);
- if (isnull)
+ pk_rel->rd_att,
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX],
+ &isnull);
+ if (isnull)
upd_nulls[i] = 'n';
else
upd_nulls[i] = ' ';
@@ -1962,16 +1969,16 @@ RI_FKey_setnull_del (FmgrInfo *proinfo)
*/
if (SPI_execp(qplan, upd_values, upd_nulls, 0) != SPI_OK_UPDATE)
elog(ERROR, "SPI_execp() failed in RI_FKey_setnull_del()");
-
+
if (SPI_finish() != SPI_OK_FINISH)
elog(NOTICE, "SPI_finish() failed in RI_FKey_setnull_del()");
return NULL;
- /* ----------
- * Handle MATCH PARTIAL set null delete.
- * ----------
- */
+ /* ----------
+ * Handle MATCH PARTIAL set null delete.
+ * ----------
+ */
case RI_MATCH_TYPE_PARTIAL:
elog(ERROR, "MATCH PARTIAL not yet supported");
return NULL;
@@ -1993,26 +2000,26 @@ RI_FKey_setnull_del (FmgrInfo *proinfo)
* ----------
*/
HeapTuple
-RI_FKey_setnull_upd (FmgrInfo *proinfo)
+RI_FKey_setnull_upd(FmgrInfo *proinfo)
{
- TriggerData *trigdata;
- int tgnargs;
- char **tgargs;
- Relation fk_rel;
- Relation pk_rel;
- HeapTuple new_row;
- HeapTuple old_row;
- RI_QueryKey qkey;
- void *qplan;
- Datum upd_values[RI_MAX_NUMKEYS];
- char upd_nulls[RI_MAX_NUMKEYS + 1];
- bool isnull;
- int i;
- int match_type;
- bool use_cached_query;
+ TriggerData *trigdata;
+ int tgnargs;
+ char **tgargs;
+ Relation fk_rel;
+ Relation pk_rel;
+ HeapTuple new_row;
+ HeapTuple old_row;
+ RI_QueryKey qkey;
+ void *qplan;
+ Datum upd_values[RI_MAX_NUMKEYS];
+ char upd_nulls[RI_MAX_NUMKEYS + 1];
+ bool isnull;
+ int i;
+ int match_type;
+ bool use_cached_query;
trigdata = CurrentTriggerData;
- CurrentTriggerData = NULL;
+ CurrentTriggerData = NULL;
ReferentialIntegritySnapshotOverride = true;
/* ----------
@@ -2021,23 +2028,23 @@ RI_FKey_setnull_upd (FmgrInfo *proinfo)
*/
if (trigdata == NULL)
elog(ERROR, "RI_FKey_setnull_upd() not fired by trigger manager");
- if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
- !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
+ if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
+ !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
elog(ERROR, "RI_FKey_setnull_upd() must be fired AFTER ROW");
if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
elog(ERROR, "RI_FKey_setnull_upd() must be fired for UPDATE");
/* ----------
- * Check for the correct # of call arguments
+ * Check for the correct # of call arguments
* ----------
*/
tgnargs = trigdata->tg_trigger->tgnargs;
- tgargs = trigdata->tg_trigger->tgargs;
+ tgargs = trigdata->tg_trigger->tgargs;
if (tgnargs < 4 || (tgnargs % 2) != 0)
elog(ERROR, "wrong # of arguments in call to RI_FKey_setnull_upd()");
if (tgnargs > RI_MAX_ARGUMENTS)
elog(ERROR, "too many keys (%d max) in call to RI_FKey_setnull_upd()",
- RI_MAX_NUMKEYS);
+ RI_MAX_NUMKEYS);
/* ----------
* Nothing to do if no column names to compare given
@@ -2051,27 +2058,27 @@ RI_FKey_setnull_upd (FmgrInfo *proinfo)
* the old tuple.
* ----------
*/
- fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
- pk_rel = trigdata->tg_relation;
+ fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
+ pk_rel = trigdata->tg_relation;
new_row = trigdata->tg_newtuple;
old_row = trigdata->tg_trigtuple;
match_type = ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]);
switch (match_type)
{
- /* ----------
- * SQL3 11.9 <referential constraint definition>
- * Gereral rules 7) a) ii) 2):
- * MATCH FULL
- * ... ON UPDATE SET NULL
- * ----------
- */
+ /* ----------
+ * SQL3 11.9 <referential constraint definition>
+ * Gereral rules 7) a) ii) 2):
+ * MATCH FULL
+ * ... ON UPDATE SET NULL
+ * ----------
+ */
case RI_MATCH_TYPE_UNSPECIFIED:
case RI_MATCH_TYPE_FULL:
ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
- RI_PLAN_SETNULL_UPD_DOUPDATE,
- fk_rel, pk_rel,
- tgnargs, tgargs);
+ RI_PLAN_SETNULL_UPD_DOUPDATE,
+ fk_rel, pk_rel,
+ tgnargs, tgargs);
switch (ri_NullCheck(pk_rel, old_row, &qkey, RI_KEYPAIR_PK_IDX))
{
@@ -2084,7 +2091,7 @@ RI_FKey_setnull_upd (FmgrInfo *proinfo)
*/
heap_close(fk_rel, NoLock);
return NULL;
-
+
case RI_KEYS_NONE_NULL:
/* ----------
* Have a full qualified key - continue below
@@ -2100,28 +2107,29 @@ RI_FKey_setnull_upd (FmgrInfo *proinfo)
* ----------
*/
if (ri_KeysEqual(pk_rel, old_row, new_row, &qkey,
- RI_KEYPAIR_PK_IDX))
+ RI_KEYPAIR_PK_IDX))
return NULL;
if (SPI_connect() != SPI_OK_CONNECT)
elog(NOTICE, "SPI_connect() failed in RI_FKey_setnull_upd()");
- /* "MATCH <unspecified>" only changes columns corresponding to
- * the referenced columns that have changed in pk_rel. This means
- * the "SET attrn=NULL [, attrn=NULL]" string will be change as
- * well. In this case, we need to build a temporary plan
- * rather than use our cached plan, unless the update happens
- * to change all columns in the key. Fortunately, for the most
- * common case of a single-column foreign key, this will be
- * true.
+ /*
+ * "MATCH <unspecified>" only changes columns corresponding to
+ * the referenced columns that have changed in pk_rel. This
+ * means the "SET attrn=NULL [, attrn=NULL]" string will be
+ * change as well. In this case, we need to build a temporary
+ * plan rather than use our cached plan, unless the update
+ * happens to change all columns in the key. Fortunately, for
+ * the most common case of a single-column foreign key, this
+ * will be true.
*
* In case you're wondering, the inequality check works because
* we know that the old key value has no NULLs (see above).
*/
use_cached_query = match_type == RI_MATCH_TYPE_FULL ||
- ri_AllKeysUnequal(pk_rel, old_row, new_row,
- &qkey, RI_KEYPAIR_PK_IDX);
+ ri_AllKeysUnequal(pk_rel, old_row, new_row,
+ &qkey, RI_KEYPAIR_PK_IDX);
/* ----------
* Fetch or prepare a saved plan for the set null update
@@ -2134,8 +2142,8 @@ RI_FKey_setnull_upd (FmgrInfo *proinfo)
char buf[256];
char querystr[8192];
char qualstr[8192];
- char *querysep;
- char *qualsep;
+ char *querysep;
+ char *qualsep;
Oid queryoids[RI_MAX_NUMKEYS];
/* ----------
@@ -2148,31 +2156,33 @@ RI_FKey_setnull_upd (FmgrInfo *proinfo)
* how to compare these two types by '='.
* ----------
*/
- sprintf(querystr, "UPDATE \"%s\" SET",
- tgargs[RI_FK_RELNAME_ARGNO]);
+ sprintf(querystr, "UPDATE \"%s\" SET",
+ tgargs[RI_FK_RELNAME_ARGNO]);
qualstr[0] = '\0';
querysep = "";
qualsep = "WHERE";
for (i = 0; i < qkey.nkeypairs; i++)
{
- /* MATCH <unspecified> - only change columns corresponding
- * to changed columns in pk_rel's key
+
+ /*
+ * MATCH <unspecified> - only change columns
+ * corresponding to changed columns in pk_rel's key
*/
if (match_type == RI_MATCH_TYPE_FULL ||
- !ri_OneKeyEqual(pk_rel, i, old_row, new_row, &qkey,
- RI_KEYPAIR_PK_IDX))
+ !ri_OneKeyEqual(pk_rel, i, old_row, new_row, &qkey,
+ RI_KEYPAIR_PK_IDX))
{
- sprintf(buf, "%s \"%s\" = NULL", querysep,
- tgargs[4 + i * 2]);
+ sprintf(buf, "%s \"%s\" = NULL", querysep,
+ tgargs[4 + i * 2]);
strcat(querystr, buf);
querysep = ",";
}
sprintf(buf, " %s \"%s\" = $%d", qualsep,
- tgargs[4 + i * 2], i + 1);
+ tgargs[4 + i * 2], i + 1);
strcat(qualstr, buf);
qualsep = "AND";
queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
}
strcat(querystr, qualstr);
@@ -2182,8 +2192,9 @@ RI_FKey_setnull_upd (FmgrInfo *proinfo)
*/
qplan = SPI_prepare(querystr, qkey.nkeypairs, queryoids);
- /* Save and remember the plan if we're building the "standard"
- * plan.
+ /*
+ * Save and remember the plan if we're building the
+ * "standard" plan.
*/
if (use_cached_query)
{
@@ -2200,10 +2211,10 @@ RI_FKey_setnull_upd (FmgrInfo *proinfo)
for (i = 0; i < qkey.nkeypairs; i++)
{
upd_values[i] = SPI_getbinval(old_row,
- pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX],
- &isnull);
- if (isnull)
+ pk_rel->rd_att,
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX],
+ &isnull);
+ if (isnull)
upd_nulls[i] = 'n';
else
upd_nulls[i] = ' ';
@@ -2216,16 +2227,16 @@ RI_FKey_setnull_upd (FmgrInfo *proinfo)
*/
if (SPI_execp(qplan, upd_values, upd_nulls, 0) != SPI_OK_UPDATE)
elog(ERROR, "SPI_execp() failed in RI_FKey_setnull_upd()");
-
+
if (SPI_finish() != SPI_OK_FINISH)
elog(NOTICE, "SPI_finish() failed in RI_FKey_setnull_upd()");
return NULL;
- /* ----------
- * Handle MATCH PARTIAL set null update.
- * ----------
- */
+ /* ----------
+ * Handle MATCH PARTIAL set null update.
+ * ----------
+ */
case RI_MATCH_TYPE_PARTIAL:
elog(ERROR, "MATCH PARTIAL not yet supported");
return NULL;
@@ -2247,23 +2258,23 @@ RI_FKey_setnull_upd (FmgrInfo *proinfo)
* ----------
*/
HeapTuple
-RI_FKey_setdefault_del (FmgrInfo *proinfo)
+RI_FKey_setdefault_del(FmgrInfo *proinfo)
{
- TriggerData *trigdata;
- int tgnargs;
- char **tgargs;
- Relation fk_rel;
- Relation pk_rel;
- HeapTuple old_row;
- RI_QueryKey qkey;
- void *qplan;
- Datum upd_values[RI_MAX_NUMKEYS];
- char upd_nulls[RI_MAX_NUMKEYS + 1];
- bool isnull;
- int i;
+ TriggerData *trigdata;
+ int tgnargs;
+ char **tgargs;
+ Relation fk_rel;
+ Relation pk_rel;
+ HeapTuple old_row;
+ RI_QueryKey qkey;
+ void *qplan;
+ Datum upd_values[RI_MAX_NUMKEYS];
+ char upd_nulls[RI_MAX_NUMKEYS + 1];
+ bool isnull;
+ int i;
trigdata = CurrentTriggerData;
- CurrentTriggerData = NULL;
+ CurrentTriggerData = NULL;
ReferentialIntegritySnapshotOverride = true;
/* ----------
@@ -2272,23 +2283,23 @@ RI_FKey_setdefault_del (FmgrInfo *proinfo)
*/
if (trigdata == NULL)
elog(ERROR, "RI_FKey_setdefault_del() not fired by trigger manager");
- if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
- !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
+ if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
+ !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
elog(ERROR, "RI_FKey_setdefault_del() must be fired AFTER ROW");
if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
elog(ERROR, "RI_FKey_setdefault_del() must be fired for DELETE");
/* ----------
- * Check for the correct # of call arguments
+ * Check for the correct # of call arguments
* ----------
*/
tgnargs = trigdata->tg_trigger->tgnargs;
- tgargs = trigdata->tg_trigger->tgargs;
+ tgargs = trigdata->tg_trigger->tgargs;
if (tgnargs < 4 || (tgnargs % 2) != 0)
elog(ERROR, "wrong # of arguments in call to RI_FKey_setdefault_del()");
if (tgnargs > RI_MAX_ARGUMENTS)
elog(ERROR, "too many keys (%d max) in call to RI_FKey_setdefault_del()",
- RI_MAX_NUMKEYS);
+ RI_MAX_NUMKEYS);
/* ----------
* Nothing to do if no column names to compare given
@@ -2302,25 +2313,25 @@ RI_FKey_setdefault_del (FmgrInfo *proinfo)
* the old tuple.
* ----------
*/
- fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
- pk_rel = trigdata->tg_relation;
+ fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
+ pk_rel = trigdata->tg_relation;
old_row = trigdata->tg_trigtuple;
switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]))
{
- /* ----------
- * SQL3 11.9 <referential constraint definition>
- * Gereral rules 6) a) iii):
- * MATCH <UNSPECIFIED> or MATCH FULL
- * ... ON DELETE SET DEFAULT
- * ----------
- */
+ /* ----------
+ * SQL3 11.9 <referential constraint definition>
+ * Gereral rules 6) a) iii):
+ * MATCH <UNSPECIFIED> or MATCH FULL
+ * ... ON DELETE SET DEFAULT
+ * ----------
+ */
case RI_MATCH_TYPE_UNSPECIFIED:
case RI_MATCH_TYPE_FULL:
ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
- RI_PLAN_SETNULL_DEL_DOUPDATE,
- fk_rel, pk_rel,
- tgnargs, tgargs);
+ RI_PLAN_SETNULL_DEL_DOUPDATE,
+ fk_rel, pk_rel,
+ tgnargs, tgargs);
switch (ri_NullCheck(pk_rel, old_row, &qkey, RI_KEYPAIR_PK_IDX))
{
@@ -2333,7 +2344,7 @@ RI_FKey_setdefault_del (FmgrInfo *proinfo)
*/
heap_close(fk_rel, NoLock);
return NULL;
-
+
case RI_KEYS_NONE_NULL:
/* ----------
* Have a full qualified key - continue below
@@ -2357,13 +2368,14 @@ RI_FKey_setdefault_del (FmgrInfo *proinfo)
char buf[256];
char querystr[8192];
char qualstr[8192];
- char *querysep;
- char *qualsep;
+ char *querysep;
+ char *qualsep;
Oid queryoids[RI_MAX_NUMKEYS];
- Plan *spi_plan;
- AttrDefault *defval;
- TargetEntry *spi_qptle;
- int i, j;
+ Plan *spi_plan;
+ AttrDefault *defval;
+ TargetEntry *spi_qptle;
+ int i,
+ j;
/* ----------
* The query string built is
@@ -2375,23 +2387,23 @@ RI_FKey_setdefault_del (FmgrInfo *proinfo)
* how to compare these two types by '='.
* ----------
*/
- sprintf(querystr, "UPDATE \"%s\" SET",
- tgargs[RI_FK_RELNAME_ARGNO]);
+ sprintf(querystr, "UPDATE \"%s\" SET",
+ tgargs[RI_FK_RELNAME_ARGNO]);
qualstr[0] = '\0';
querysep = "";
qualsep = "WHERE";
for (i = 0; i < qkey.nkeypairs; i++)
{
- sprintf(buf, "%s \"%s\" = NULL", querysep,
- tgargs[4 + i * 2]);
+ sprintf(buf, "%s \"%s\" = NULL", querysep,
+ tgargs[4 + i * 2]);
strcat(querystr, buf);
sprintf(buf, " %s \"%s\" = $%d", qualsep,
- tgargs[4 + i * 2], i + 1);
+ tgargs[4 + i * 2], i + 1);
strcat(qualstr, buf);
querysep = ",";
qualsep = "AND";
queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
}
strcat(querystr, qualstr);
@@ -2412,7 +2424,7 @@ RI_FKey_setdefault_del (FmgrInfo *proinfo)
* in the tuple constructor.
* ----------
*/
- spi_plan = (Plan *)lfirst(((_SPI_plan *)qplan)->ptlist);
+ spi_plan = (Plan *) lfirst(((_SPI_plan *) qplan)->ptlist);
if (fk_rel->rd_att->constr != NULL)
defval = fk_rel->rd_att->constr->defval;
else
@@ -2426,8 +2438,8 @@ RI_FKey_setdefault_del (FmgrInfo *proinfo)
*/
for (j = 0; j < fk_rel->rd_att->constr->num_defval; j++)
{
- if (defval[j].adnum ==
- qkey.keypair[i][RI_KEYPAIR_FK_IDX])
+ if (defval[j].adnum ==
+ qkey.keypair[i][RI_KEYPAIR_FK_IDX])
{
/* ----------
* That's the one - push the expression
@@ -2435,8 +2447,8 @@ RI_FKey_setdefault_del (FmgrInfo *proinfo)
* ----------
*/
spi_qptle = (TargetEntry *)
- nth(defval[j].adnum - 1,
- spi_plan->targetlist);
+ nth(defval[j].adnum - 1,
+ spi_plan->targetlist);
spi_qptle->expr = stringToNode(defval[j].adbin);
break;
@@ -2453,10 +2465,10 @@ RI_FKey_setdefault_del (FmgrInfo *proinfo)
for (i = 0; i < qkey.nkeypairs; i++)
{
upd_values[i] = SPI_getbinval(old_row,
- pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX],
- &isnull);
- if (isnull)
+ pk_rel->rd_att,
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX],
+ &isnull);
+ if (isnull)
upd_nulls[i] = 'n';
else
upd_nulls[i] = ' ';
@@ -2469,16 +2481,16 @@ RI_FKey_setdefault_del (FmgrInfo *proinfo)
*/
if (SPI_execp(qplan, upd_values, upd_nulls, 0) != SPI_OK_UPDATE)
elog(ERROR, "SPI_execp() failed in RI_FKey_setdefault_del()");
-
+
if (SPI_finish() != SPI_OK_FINISH)
elog(NOTICE, "SPI_finish() failed in RI_FKey_setdefault_del()");
return NULL;
- /* ----------
- * Handle MATCH PARTIAL set null delete.
- * ----------
- */
+ /* ----------
+ * Handle MATCH PARTIAL set null delete.
+ * ----------
+ */
case RI_MATCH_TYPE_PARTIAL:
elog(ERROR, "MATCH PARTIAL not yet supported");
return NULL;
@@ -2500,25 +2512,25 @@ RI_FKey_setdefault_del (FmgrInfo *proinfo)
* ----------
*/
HeapTuple
-RI_FKey_setdefault_upd (FmgrInfo *proinfo)
+RI_FKey_setdefault_upd(FmgrInfo *proinfo)
{
- TriggerData *trigdata;
- int tgnargs;
- char **tgargs;
- Relation fk_rel;
- Relation pk_rel;
- HeapTuple new_row;
- HeapTuple old_row;
- RI_QueryKey qkey;
- void *qplan;
- Datum upd_values[RI_MAX_NUMKEYS];
- char upd_nulls[RI_MAX_NUMKEYS + 1];
- bool isnull;
- int i;
- int match_type;
+ TriggerData *trigdata;
+ int tgnargs;
+ char **tgargs;
+ Relation fk_rel;
+ Relation pk_rel;
+ HeapTuple new_row;
+ HeapTuple old_row;
+ RI_QueryKey qkey;
+ void *qplan;
+ Datum upd_values[RI_MAX_NUMKEYS];
+ char upd_nulls[RI_MAX_NUMKEYS + 1];
+ bool isnull;
+ int i;
+ int match_type;
trigdata = CurrentTriggerData;
- CurrentTriggerData = NULL;
+ CurrentTriggerData = NULL;
ReferentialIntegritySnapshotOverride = true;
/* ----------
@@ -2527,23 +2539,23 @@ RI_FKey_setdefault_upd (FmgrInfo *proinfo)
*/
if (trigdata == NULL)
elog(ERROR, "RI_FKey_setdefault_upd() not fired by trigger manager");
- if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
- !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
+ if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
+ !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
elog(ERROR, "RI_FKey_setdefault_upd() must be fired AFTER ROW");
if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
elog(ERROR, "RI_FKey_setdefault_upd() must be fired for UPDATE");
/* ----------
- * Check for the correct # of call arguments
+ * Check for the correct # of call arguments
* ----------
*/
tgnargs = trigdata->tg_trigger->tgnargs;
- tgargs = trigdata->tg_trigger->tgargs;
+ tgargs = trigdata->tg_trigger->tgargs;
if (tgnargs < 4 || (tgnargs % 2) != 0)
elog(ERROR, "wrong # of arguments in call to RI_FKey_setdefault_upd()");
if (tgnargs > RI_MAX_ARGUMENTS)
elog(ERROR, "too many keys (%d max) in call to RI_FKey_setdefault_upd()",
- RI_MAX_NUMKEYS);
+ RI_MAX_NUMKEYS);
/* ----------
* Nothing to do if no column names to compare given
@@ -2557,8 +2569,8 @@ RI_FKey_setdefault_upd (FmgrInfo *proinfo)
* the old tuple.
* ----------
*/
- fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
- pk_rel = trigdata->tg_relation;
+ fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
+ pk_rel = trigdata->tg_relation;
new_row = trigdata->tg_newtuple;
old_row = trigdata->tg_trigtuple;
@@ -2566,19 +2578,19 @@ RI_FKey_setdefault_upd (FmgrInfo *proinfo)
switch (match_type)
{
- /* ----------
- * SQL3 11.9 <referential constraint definition>
- * Gereral rules 7) a) iii):
- * MATCH <UNSPECIFIED> or MATCH FULL
- * ... ON UPDATE SET DEFAULT
- * ----------
- */
+ /* ----------
+ * SQL3 11.9 <referential constraint definition>
+ * Gereral rules 7) a) iii):
+ * MATCH <UNSPECIFIED> or MATCH FULL
+ * ... ON UPDATE SET DEFAULT
+ * ----------
+ */
case RI_MATCH_TYPE_UNSPECIFIED:
case RI_MATCH_TYPE_FULL:
ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
- RI_PLAN_SETNULL_DEL_DOUPDATE,
- fk_rel, pk_rel,
- tgnargs, tgargs);
+ RI_PLAN_SETNULL_DEL_DOUPDATE,
+ fk_rel, pk_rel,
+ tgnargs, tgargs);
switch (ri_NullCheck(pk_rel, old_row, &qkey, RI_KEYPAIR_PK_IDX))
{
@@ -2591,7 +2603,7 @@ RI_FKey_setdefault_upd (FmgrInfo *proinfo)
*/
heap_close(fk_rel, NoLock);
return NULL;
-
+
case RI_KEYS_NONE_NULL:
/* ----------
* Have a full qualified key - continue below
@@ -2606,7 +2618,7 @@ RI_FKey_setdefault_upd (FmgrInfo *proinfo)
* ----------
*/
if (ri_KeysEqual(pk_rel, old_row, new_row, &qkey,
- RI_KEYPAIR_PK_IDX))
+ RI_KEYPAIR_PK_IDX))
return NULL;
if (SPI_connect() != SPI_OK_CONNECT)
@@ -2623,13 +2635,14 @@ RI_FKey_setdefault_upd (FmgrInfo *proinfo)
char buf[256];
char querystr[8192];
char qualstr[8192];
- char *querysep;
- char *qualsep;
+ char *querysep;
+ char *qualsep;
Oid queryoids[RI_MAX_NUMKEYS];
- Plan *spi_plan;
- AttrDefault *defval;
- TargetEntry *spi_qptle;
- int i, j;
+ Plan *spi_plan;
+ AttrDefault *defval;
+ TargetEntry *spi_qptle;
+ int i,
+ j;
/* ----------
* The query string built is
@@ -2641,31 +2654,33 @@ RI_FKey_setdefault_upd (FmgrInfo *proinfo)
* how to compare these two types by '='.
* ----------
*/
- sprintf(querystr, "UPDATE \"%s\" SET",
- tgargs[RI_FK_RELNAME_ARGNO]);
+ sprintf(querystr, "UPDATE \"%s\" SET",
+ tgargs[RI_FK_RELNAME_ARGNO]);
qualstr[0] = '\0';
querysep = "";
qualsep = "WHERE";
for (i = 0; i < qkey.nkeypairs; i++)
{
- /* MATCH <unspecified> - only change columns corresponding
- * to changed columns in pk_rel's key
+
+ /*
+ * MATCH <unspecified> - only change columns
+ * corresponding to changed columns in pk_rel's key
*/
if (match_type == RI_MATCH_TYPE_FULL ||
!ri_OneKeyEqual(pk_rel, i, old_row,
- new_row, &qkey, RI_KEYPAIR_PK_IDX))
+ new_row, &qkey, RI_KEYPAIR_PK_IDX))
{
- sprintf(buf, "%s \"%s\" = NULL", querysep,
- tgargs[4 + i * 2]);
+ sprintf(buf, "%s \"%s\" = NULL", querysep,
+ tgargs[4 + i * 2]);
strcat(querystr, buf);
querysep = ",";
}
sprintf(buf, " %s \"%s\" = $%d", qualsep,
- tgargs[4 + i * 2], i + 1);
+ tgargs[4 + i * 2], i + 1);
strcat(qualstr, buf);
qualsep = "AND";
queryoids[i] = SPI_gettypeid(pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX]);
}
strcat(querystr, qualstr);
@@ -2681,21 +2696,23 @@ RI_FKey_setdefault_upd (FmgrInfo *proinfo)
* in the tuple constructor.
* ----------
*/
- spi_plan = (Plan *)lfirst(((_SPI_plan *)qplan)->ptlist);
+ spi_plan = (Plan *) lfirst(((_SPI_plan *) qplan)->ptlist);
if (fk_rel->rd_att->constr != NULL)
defval = fk_rel->rd_att->constr->defval;
else
defval = NULL;
for (i = 0; i < qkey.nkeypairs && defval != NULL; i++)
{
- /* MATCH <unspecified> - only change columns corresponding
- * to changed columns in pk_rel's key. This conditional
- * must match the one in the loop above that built the
- * SET attrn=NULL list.
+
+ /*
+ * MATCH <unspecified> - only change columns
+ * corresponding to changed columns in pk_rel's key.
+ * This conditional must match the one in the loop
+ * above that built the SET attrn=NULL list.
*/
if (match_type == RI_MATCH_TYPE_FULL ||
!ri_OneKeyEqual(pk_rel, i, old_row,
- new_row, &qkey, RI_KEYPAIR_PK_IDX))
+ new_row, &qkey, RI_KEYPAIR_PK_IDX))
{
/* ----------
* For each key attribute lookup the tuple constructor
@@ -2704,8 +2721,8 @@ RI_FKey_setdefault_upd (FmgrInfo *proinfo)
*/
for (j = 0; j < fk_rel->rd_att->constr->num_defval; j++)
{
- if (defval[j].adnum ==
- qkey.keypair[i][RI_KEYPAIR_FK_IDX])
+ if (defval[j].adnum ==
+ qkey.keypair[i][RI_KEYPAIR_FK_IDX])
{
/* ----------
* That's the one - push the expression
@@ -2713,12 +2730,12 @@ RI_FKey_setdefault_upd (FmgrInfo *proinfo)
* ----------
*/
spi_qptle = (TargetEntry *)
- nth(defval[j].adnum - 1,
+ nth(defval[j].adnum - 1,
spi_plan->targetlist);
spi_qptle->expr = stringToNode(defval[j].adbin);
break;
- }
+ }
}
}
}
@@ -2732,10 +2749,10 @@ RI_FKey_setdefault_upd (FmgrInfo *proinfo)
for (i = 0; i < qkey.nkeypairs; i++)
{
upd_values[i] = SPI_getbinval(old_row,
- pk_rel->rd_att,
- qkey.keypair[i][RI_KEYPAIR_PK_IDX],
- &isnull);
- if (isnull)
+ pk_rel->rd_att,
+ qkey.keypair[i][RI_KEYPAIR_PK_IDX],
+ &isnull);
+ if (isnull)
upd_nulls[i] = 'n';
else
upd_nulls[i] = ' ';
@@ -2748,16 +2765,16 @@ RI_FKey_setdefault_upd (FmgrInfo *proinfo)
*/
if (SPI_execp(qplan, upd_values, upd_nulls, 0) != SPI_OK_UPDATE)
elog(ERROR, "SPI_execp() failed in RI_FKey_setdefault_upd()");
-
+
if (SPI_finish() != SPI_OK_FINISH)
elog(NOTICE, "SPI_finish() failed in RI_FKey_setdefault_upd()");
return NULL;
- /* ----------
- * Handle MATCH PARTIAL set null delete.
- * ----------
- */
+ /* ----------
+ * Handle MATCH PARTIAL set null delete.
+ * ----------
+ */
case RI_MATCH_TYPE_PARTIAL:
elog(ERROR, "MATCH PARTIAL not yet supported");
return NULL;
@@ -2782,31 +2799,31 @@ RI_FKey_setdefault_upd (FmgrInfo *proinfo)
* ----------
*/
bool
-RI_FKey_keyequal_upd (void)
+RI_FKey_keyequal_upd(void)
{
- TriggerData *trigdata;
- int tgnargs;
- char **tgargs;
- Relation fk_rel;
- Relation pk_rel;
- HeapTuple new_row;
- HeapTuple old_row;
- RI_QueryKey qkey;
+ TriggerData *trigdata;
+ int tgnargs;
+ char **tgargs;
+ Relation fk_rel;
+ Relation pk_rel;
+ HeapTuple new_row;
+ HeapTuple old_row;
+ RI_QueryKey qkey;
trigdata = CurrentTriggerData;
- CurrentTriggerData = NULL;
+ CurrentTriggerData = NULL;
/* ----------
- * Check for the correct # of call arguments
+ * Check for the correct # of call arguments
* ----------
*/
tgnargs = trigdata->tg_trigger->tgnargs;
- tgargs = trigdata->tg_trigger->tgargs;
+ tgargs = trigdata->tg_trigger->tgargs;
if (tgnargs < 4 || (tgnargs % 2) != 0)
elog(ERROR, "wrong # of arguments in call to RI_FKey_keyequal_upd()");
if (tgnargs > RI_MAX_ARGUMENTS)
elog(ERROR, "too many keys (%d max) in call to RI_FKey_keyequal_upd()",
- RI_MAX_NUMKEYS);
+ RI_MAX_NUMKEYS);
/* ----------
* Nothing to do if no column names to compare given
@@ -2820,23 +2837,23 @@ RI_FKey_keyequal_upd (void)
* the new and old tuple.
* ----------
*/
- fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
- pk_rel = trigdata->tg_relation;
+ fk_rel = heap_openr(tgargs[RI_FK_RELNAME_ARGNO], NoLock);
+ pk_rel = trigdata->tg_relation;
new_row = trigdata->tg_newtuple;
old_row = trigdata->tg_trigtuple;
switch (ri_DetermineMatchType(tgargs[RI_MATCH_TYPE_ARGNO]))
{
- /* ----------
- * MATCH <UNSPECIFIED>
- * ----------
- */
+ /* ----------
+ * MATCH <UNSPECIFIED>
+ * ----------
+ */
case RI_MATCH_TYPE_UNSPECIFIED:
case RI_MATCH_TYPE_FULL:
ri_BuildQueryKeyFull(&qkey, trigdata->tg_trigger->tgoid,
- 0,
- fk_rel, pk_rel,
- tgnargs, tgargs);
+ 0,
+ fk_rel, pk_rel,
+ tgnargs, tgargs);
heap_close(fk_rel, NoLock);
/* ----------
@@ -2844,12 +2861,12 @@ RI_FKey_keyequal_upd (void)
* ----------
*/
return ri_KeysEqual(pk_rel, old_row, new_row, &qkey,
- RI_KEYPAIR_PK_IDX);
+ RI_KEYPAIR_PK_IDX);
- /* ----------
- * Handle MATCH PARTIAL set null delete.
- * ----------
- */
+ /* ----------
+ * Handle MATCH PARTIAL set null delete.
+ * ----------
+ */
case RI_MATCH_TYPE_PARTIAL:
elog(ERROR, "MATCH PARTIAL not yet supported");
break;
@@ -2914,26 +2931,26 @@ ri_DetermineMatchType(char *str)
* At least for MATCH FULL this builds a unique key per plan.
* ----------
*/
-static void
+static void
ri_BuildQueryKeyFull(RI_QueryKey *key, Oid constr_id, int32 constr_queryno,
- Relation fk_rel, Relation pk_rel,
- int argc, char **argv)
+ Relation fk_rel, Relation pk_rel,
+ int argc, char **argv)
{
- int i;
- int j;
- int fno;
+ int i;
+ int j;
+ int fno;
/* ----------
* Initialize the key and fill in type, oid's and number of keypairs
* ----------
*/
- memset ((void *)key, 0, sizeof(RI_QueryKey));
- key->constr_type = RI_MATCH_TYPE_FULL;
- key->constr_id = constr_id;
- key->constr_queryno = constr_queryno;
- key->fk_relid = fk_rel->rd_id;
- key->pk_relid = pk_rel->rd_id;
- key->nkeypairs = (argc - RI_FIRST_ATTNAME_ARGNO) / 2;
+ memset((void *) key, 0, sizeof(RI_QueryKey));
+ key->constr_type = RI_MATCH_TYPE_FULL;
+ key->constr_id = constr_id;
+ key->constr_queryno = constr_queryno;
+ key->fk_relid = fk_rel->rd_id;
+ key->pk_relid = pk_rel->rd_id;
+ key->nkeypairs = (argc - RI_FIRST_ATTNAME_ARGNO) / 2;
/* ----------
* Lookup the attribute numbers of the arguments to the trigger call
@@ -2945,17 +2962,17 @@ ri_BuildQueryKeyFull(RI_QueryKey *key, Oid constr_id, int32 constr_queryno,
fno = SPI_fnumber(fk_rel->rd_att, argv[j]);
if (fno == SPI_ERROR_NOATTRIBUTE)
elog(ERROR, "constraint %s: table %s does not have an attribute %s",
- argv[RI_CONSTRAINT_NAME_ARGNO],
- argv[RI_FK_RELNAME_ARGNO],
- argv[j]);
+ argv[RI_CONSTRAINT_NAME_ARGNO],
+ argv[RI_FK_RELNAME_ARGNO],
+ argv[j]);
key->keypair[i][RI_KEYPAIR_FK_IDX] = fno;
fno = SPI_fnumber(pk_rel->rd_att, argv[j + 1]);
if (fno == SPI_ERROR_NOATTRIBUTE)
elog(ERROR, "constraint %s: table %s does not have an attribute %s",
- argv[RI_CONSTRAINT_NAME_ARGNO],
- argv[RI_PK_RELNAME_ARGNO],
- argv[j + 1]);
+ argv[RI_CONSTRAINT_NAME_ARGNO],
+ argv[RI_PK_RELNAME_ARGNO],
+ argv[j + 1]);
key->keypair[i][RI_KEYPAIR_PK_IDX] = fno;
}
@@ -2971,13 +2988,13 @@ ri_BuildQueryKeyFull(RI_QueryKey *key, Oid constr_id, int32 constr_queryno,
* Returns one of RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL or RI_KEYS_SOME_NULL.
* ----------
*/
-static int
+static int
ri_NullCheck(Relation rel, HeapTuple tup, RI_QueryKey *key, int pairidx)
{
- int i;
- bool isnull;
- bool allnull = true;
- bool nonenull = true;
+ int i;
+ bool isnull;
+ bool allnull = true;
+ bool nonenull = true;
for (i = 0; i < key->nkeypairs; i++)
{
@@ -3012,16 +3029,16 @@ ri_InitHashTables(void)
HASHCTL ctl;
memset(&ctl, 0, sizeof(ctl));
- ctl.keysize = sizeof(RI_QueryKey);
- ctl.datasize = sizeof(void *);
+ ctl.keysize = sizeof(RI_QueryKey);
+ ctl.datasize = sizeof(void *);
ri_query_cache = hash_create(RI_INIT_QUERYHASHSIZE, &ctl, HASH_ELEM);
memset(&ctl, 0, sizeof(ctl));
- ctl.keysize = sizeof(Oid);
- ctl.datasize = sizeof(Oid) + sizeof(FmgrInfo);
- ctl.hash = tag_hash;
- ri_opreq_cache = hash_create(RI_INIT_OPREQHASHSIZE, &ctl,
- HASH_ELEM | HASH_FUNCTION);
+ ctl.keysize = sizeof(Oid);
+ ctl.datasize = sizeof(Oid) + sizeof(FmgrInfo);
+ ctl.hash = tag_hash;
+ ri_opreq_cache = hash_create(RI_INIT_OPREQHASHSIZE, &ctl,
+ HASH_ELEM | HASH_FUNCTION);
}
@@ -3035,8 +3052,8 @@ ri_InitHashTables(void)
static void *
ri_FetchPreparedPlan(RI_QueryKey *key)
{
- RI_QueryHashEntry *entry;
- bool found;
+ RI_QueryHashEntry *entry;
+ bool found;
/* ----------
* On the first call initialize the hashtable
@@ -3049,8 +3066,8 @@ ri_FetchPreparedPlan(RI_QueryKey *key)
* Lookup for the key
* ----------
*/
- entry = (RI_QueryHashEntry *)hash_search(ri_query_cache,
- (char *)key, HASH_FIND, &found);
+ entry = (RI_QueryHashEntry *) hash_search(ri_query_cache,
+ (char *) key, HASH_FIND, &found);
if (entry == NULL)
elog(FATAL, "error in RI plan cache");
if (!found)
@@ -3068,8 +3085,8 @@ ri_FetchPreparedPlan(RI_QueryKey *key)
static void
ri_HashPreparedPlan(RI_QueryKey *key, void *plan)
{
- RI_QueryHashEntry *entry;
- bool found;
+ RI_QueryHashEntry *entry;
+ bool found;
/* ----------
* On the first call initialize the hashtable
@@ -3082,8 +3099,8 @@ ri_HashPreparedPlan(RI_QueryKey *key, void *plan)
* Add the new plan.
* ----------
*/
- entry = (RI_QueryHashEntry *)hash_search(ri_query_cache,
- (char *)key, HASH_ENTER, &found);
+ entry = (RI_QueryHashEntry *) hash_search(ri_query_cache,
+ (char *) key, HASH_ENTER, &found);
if (entry == NULL)
elog(FATAL, "can't insert into RI plan cache");
entry->plan = plan;
@@ -3097,14 +3114,14 @@ ri_HashPreparedPlan(RI_QueryKey *key, void *plan)
* ----------
*/
static bool
-ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup,
- RI_QueryKey *key, int pairidx)
+ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup,
+ RI_QueryKey *key, int pairidx)
{
- int i;
- Oid typeid;
- Datum oldvalue;
- Datum newvalue;
- bool isnull;
+ int i;
+ Oid typeid;
+ Datum oldvalue;
+ Datum newvalue;
+ bool isnull;
for (i = 0; i < key->nkeypairs; i++)
{
@@ -3112,8 +3129,8 @@ ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup,
* Get one attributes oldvalue. If it is NULL - they're not equal.
* ----------
*/
- oldvalue = SPI_getbinval(oldtup, rel->rd_att,
- key->keypair[i][pairidx], &isnull);
+ oldvalue = SPI_getbinval(oldtup, rel->rd_att,
+ key->keypair[i][pairidx], &isnull);
if (isnull)
return false;
@@ -3121,8 +3138,8 @@ ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup,
* Get one attributes oldvalue. If it is NULL - they're not equal.
* ----------
*/
- newvalue = SPI_getbinval(newtup, rel->rd_att,
- key->keypair[i][pairidx], &isnull);
+ newvalue = SPI_getbinval(newtup, rel->rd_att,
+ key->keypair[i][pairidx], &isnull);
if (isnull)
return false;
@@ -3147,15 +3164,15 @@ ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup,
* ----------
*/
static bool
-ri_AllKeysUnequal(Relation rel, HeapTuple oldtup, HeapTuple newtup,
- RI_QueryKey *key, int pairidx)
+ri_AllKeysUnequal(Relation rel, HeapTuple oldtup, HeapTuple newtup,
+ RI_QueryKey *key, int pairidx)
{
- int i;
- Oid typeid;
- Datum oldvalue;
- Datum newvalue;
- bool isnull;
- bool keys_unequal;
+ int i;
+ Oid typeid;
+ Datum oldvalue;
+ Datum newvalue;
+ bool isnull;
+ bool keys_unequal;
keys_unequal = true;
for (i = 0; keys_unequal && i < key->nkeypairs; i++)
@@ -3164,8 +3181,8 @@ ri_AllKeysUnequal(Relation rel, HeapTuple oldtup, HeapTuple newtup,
* Get one attributes oldvalue. If it is NULL - they're not equal.
* ----------
*/
- oldvalue = SPI_getbinval(oldtup, rel->rd_att,
- key->keypair[i][pairidx], &isnull);
+ oldvalue = SPI_getbinval(oldtup, rel->rd_att,
+ key->keypair[i][pairidx], &isnull);
if (isnull)
continue;
@@ -3173,8 +3190,8 @@ ri_AllKeysUnequal(Relation rel, HeapTuple oldtup, HeapTuple newtup,
* Get one attributes oldvalue. If it is NULL - they're not equal.
* ----------
*/
- newvalue = SPI_getbinval(newtup, rel->rd_att,
- key->keypair[i][pairidx], &isnull);
+ newvalue = SPI_getbinval(newtup, rel->rd_att,
+ key->keypair[i][pairidx], &isnull);
if (isnull)
continue;
@@ -3198,25 +3215,25 @@ ri_AllKeysUnequal(Relation rel, HeapTuple oldtup, HeapTuple newtup,
*
* Check if one key value in OLD and NEW is equal.
*
- * ri_KeysEqual could call this but would run a bit slower. For
- * now, let's duplicate the code.
+ * ri_KeysEqual could call this but would run a bit slower. For
+ * now, let's duplicate the code.
* ----------
*/
static bool
-ri_OneKeyEqual(Relation rel, int column, HeapTuple oldtup, HeapTuple newtup,
- RI_QueryKey *key, int pairidx)
+ri_OneKeyEqual(Relation rel, int column, HeapTuple oldtup, HeapTuple newtup,
+ RI_QueryKey *key, int pairidx)
{
- Oid typeid;
- Datum oldvalue;
- Datum newvalue;
- bool isnull;
+ Oid typeid;
+ Datum oldvalue;
+ Datum newvalue;
+ bool isnull;
/* ----------
* Get one attributes oldvalue. If it is NULL - they're not equal.
* ----------
*/
- oldvalue = SPI_getbinval(oldtup, rel->rd_att,
- key->keypair[column][pairidx], &isnull);
+ oldvalue = SPI_getbinval(oldtup, rel->rd_att,
+ key->keypair[column][pairidx], &isnull);
if (isnull)
return false;
@@ -3224,8 +3241,8 @@ ri_OneKeyEqual(Relation rel, int column, HeapTuple oldtup, HeapTuple newtup,
* Get one attributes oldvalue. If it is NULL - they're not equal.
* ----------
*/
- newvalue = SPI_getbinval(newtup, rel->rd_att,
- key->keypair[column][pairidx], &isnull);
+ newvalue = SPI_getbinval(newtup, rel->rd_att,
+ key->keypair[column][pairidx], &isnull);
if (isnull)
return false;
@@ -3236,7 +3253,7 @@ ri_OneKeyEqual(Relation rel, int column, HeapTuple oldtup, HeapTuple newtup,
*/
typeid = SPI_gettypeid(rel->rd_att, key->keypair[column][pairidx]);
if (!ri_AttributesEqual(typeid, oldvalue, newvalue))
- return false;
+ return false;
return true;
}
@@ -3252,9 +3269,9 @@ ri_OneKeyEqual(Relation rel, int column, HeapTuple oldtup, HeapTuple newtup,
static bool
ri_AttributesEqual(Oid typeid, Datum oldvalue, Datum newvalue)
{
- RI_OpreqHashEntry *entry;
- bool found;
- Datum result;
+ RI_OpreqHashEntry *entry;
+ bool found;
+ Datum result;
/* ----------
* On the first call initialize the hashtable
@@ -3267,8 +3284,8 @@ ri_AttributesEqual(Oid typeid, Datum oldvalue, Datum newvalue)
* Try to find the '=' operator for this type in our cache
* ----------
*/
- entry = (RI_OpreqHashEntry *)hash_search(ri_opreq_cache,
- (char *)&typeid, HASH_FIND, &found);
+ entry = (RI_OpreqHashEntry *) hash_search(ri_opreq_cache,
+ (char *) &typeid, HASH_FIND, &found);
if (entry == NULL)
elog(FATAL, "error in RI operator cache");
@@ -3279,22 +3296,22 @@ ri_AttributesEqual(Oid typeid, Datum oldvalue, Datum newvalue)
*/
if (!found)
{
- HeapTuple opr_tup;
- Form_pg_operator opr_struct;
+ HeapTuple opr_tup;
+ Form_pg_operator opr_struct;
opr_tup = SearchSysCacheTuple(OPERNAME,
- PointerGetDatum("="),
- ObjectIdGetDatum(typeid),
- ObjectIdGetDatum(typeid),
- CharGetDatum('b'));
+ PointerGetDatum("="),
+ ObjectIdGetDatum(typeid),
+ ObjectIdGetDatum(typeid),
+ CharGetDatum('b'));
if (!HeapTupleIsValid(opr_tup))
elog(ERROR, "ri_AttributesEqual(): cannot find '=' operator "
- "for type %d", typeid);
+ "for type %d", typeid);
opr_struct = (Form_pg_operator) GETSTRUCT(opr_tup);
- entry = (RI_OpreqHashEntry *)hash_search(ri_opreq_cache,
- (char *)&typeid, HASH_ENTER, &found);
+ entry = (RI_OpreqHashEntry *) hash_search(ri_opreq_cache,
+ (char *) &typeid, HASH_ENTER, &found);
if (entry == NULL)
elog(FATAL, "can't insert into RI operator cache");
@@ -3307,8 +3324,6 @@ ri_AttributesEqual(Oid typeid, Datum oldvalue, Datum newvalue)
* ----------
*/
fmgr_info(entry->oprfnid, &(entry->oprfmgrinfo));
- result = (Datum)(*fmgr_faddr(&(entry->oprfmgrinfo)))(oldvalue, newvalue);
- return (bool)result;
+ result = (Datum) (*fmgr_faddr(&(entry->oprfmgrinfo))) (oldvalue, newvalue);
+ return (bool) result;
}
-
-
diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
index 9397ec6c0d3..69305acf55a 100644
--- a/src/backend/utils/adt/ruleutils.c
+++ b/src/backend/utils/adt/ruleutils.c
@@ -3,7 +3,7 @@
* out of its tuple
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/ruleutils.c,v 1.47 2000/03/17 02:36:23 tgl Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/ruleutils.c,v 1.48 2000/04/12 17:15:51 momjian Exp $
*
* This software is copyrighted by Jan Wieck - Hamburg.
*
@@ -66,7 +66,8 @@ typedef struct
bool varprefix; /* TRUE to print prefixes on Vars */
} deparse_context;
-typedef struct {
+typedef struct
+{
Index rt_index;
int levelsup;
} check_if_rte_used_context;
@@ -113,7 +114,7 @@ static char *get_relation_name(Oid relid);
static char *get_attribute_name(Oid relid, int2 attnum);
static bool check_if_rte_used(Node *node, Index rt_index, int levelsup);
static bool check_if_rte_used_walker(Node *node,
- check_if_rte_used_context *context);
+ check_if_rte_used_context *context);
#define inherit_marker(rte) ((rte)->inh ? "*" : "")
@@ -133,7 +134,7 @@ pg_get_ruledef(NameData *rname)
int spirc;
HeapTuple ruletup;
TupleDesc rulettc;
- StringInfoData buf;
+ StringInfoData buf;
int len;
/* ----------
@@ -231,7 +232,7 @@ pg_get_viewdef(NameData *rname)
int spirc;
HeapTuple ruletup;
TupleDesc rulettc;
- StringInfoData buf;
+ StringInfoData buf;
int len;
char name1[NAMEDATALEN + 5];
char name2[NAMEDATALEN + 5];
@@ -338,8 +339,8 @@ pg_get_indexdef(Oid indexrelid)
int spirc;
int len;
int keyno;
- StringInfoData buf;
- StringInfoData keybuf;
+ StringInfoData buf;
+ StringInfoData keybuf;
char *sep;
/* ----------
@@ -427,8 +428,8 @@ pg_get_indexdef(Oid indexrelid)
initStringInfo(&buf);
appendStringInfo(&buf, "CREATE %sINDEX %s ON %s USING %s (",
idxrec->indisunique ? "UNIQUE " : "",
- quote_identifier(pstrdup(NameStr(idxrelrec->relname))),
- quote_identifier(pstrdup(NameStr(indrelrec->relname))),
+ quote_identifier(pstrdup(NameStr(idxrelrec->relname))),
+ quote_identifier(pstrdup(NameStr(indrelrec->relname))),
quote_identifier(SPI_getvalue(spi_tup, spi_ttc,
spi_fno)));
@@ -451,8 +452,8 @@ pg_get_indexdef(Oid indexrelid)
* ----------
*/
appendStringInfo(&keybuf, "%s",
- quote_identifier(get_attribute_name(idxrec->indrelid,
- idxrec->indkey[keyno])));
+ quote_identifier(get_attribute_name(idxrec->indrelid,
+ idxrec->indkey[keyno])));
/* ----------
* If not a functional index, add the operator class name
@@ -472,8 +473,8 @@ pg_get_indexdef(Oid indexrelid)
spi_ttc = SPI_tuptable->tupdesc;
spi_fno = SPI_fnumber(spi_ttc, "opcname");
appendStringInfo(&keybuf, " %s",
- quote_identifier(SPI_getvalue(spi_tup, spi_ttc,
- spi_fno)));
+ quote_identifier(SPI_getvalue(spi_tup, spi_ttc,
+ spi_fno)));
}
}
@@ -493,7 +494,7 @@ pg_get_indexdef(Oid indexrelid)
procStruct = (Form_pg_proc) GETSTRUCT(proctup);
appendStringInfo(&buf, "%s(%s) ",
- quote_identifier(pstrdup(NameStr(procStruct->proname))),
+ quote_identifier(pstrdup(NameStr(procStruct->proname))),
keybuf.data);
spi_args[0] = ObjectIdGetDatum(idxrec->indclass[0]);
@@ -589,8 +590,8 @@ pg_get_userbyid(int32 uid)
* tree (ie, not the raw output of gram.y).
*
* rangetables is a List of Lists of RangeTblEntry nodes: first sublist is for
- * varlevelsup = 0, next for varlevelsup = 1, etc. In each sublist the first
- * item is for varno = 1, next varno = 2, etc. (Each sublist has the same
+ * varlevelsup = 0, next for varlevelsup = 1, etc. In each sublist the first
+ * item is for varno = 1, next varno = 2, etc. (Each sublist has the same
* format as the rtable list of a parsetree or query.)
*
* forceprefix is TRUE to force all Vars to be prefixed with their table names.
@@ -603,8 +604,8 @@ pg_get_userbyid(int32 uid)
char *
deparse_expression(Node *expr, List *rangetables, bool forceprefix)
{
- StringInfoData buf;
- deparse_context context;
+ StringInfoData buf;
+ deparse_context context;
initStringInfo(&buf);
context.buf = &buf;
@@ -710,7 +711,7 @@ make_ruledef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc)
{
Node *qual;
Query *query;
- deparse_context context;
+ deparse_context context;
appendStringInfo(buf, " WHERE ");
@@ -834,7 +835,7 @@ make_viewdef(StringInfo buf, HeapTuple ruletup, TupleDesc rulettc)
static void
get_query_def(Query *query, StringInfo buf, List *parentrtables)
{
- deparse_context context;
+ deparse_context context;
context.buf = buf;
context.rangetables = lcons(query->rtable, parentrtables);
@@ -954,7 +955,7 @@ get_select_query_def(Query *query, deparse_context *context)
get_rule_expr(tle->expr, context);
/* Check if we must say AS ... */
- if (! IsA(tle->expr, Var))
+ if (!IsA(tle->expr, Var))
tell_as = strcmp(tle->resdom->resname, "?column?");
else
{
@@ -996,11 +997,12 @@ get_select_query_def(Query *query, deparse_context *context)
appendStringInfo(buf, "%s%s",
quote_identifier(rte->relname),
inherit_marker(rte));
+
/*
* NOTE: SQL92 says you can't write column aliases unless
- * you write a table alias --- so, if there's an alias list,
- * make sure we emit a table alias even if it's the same as
- * the table's real name.
+ * you write a table alias --- so, if there's an alias
+ * list, make sure we emit a table alias even if it's the
+ * same as the table's real name.
*/
if ((rte->ref != NULL)
&& ((strcmp(rte->relname, rte->ref->relname) != 0)
@@ -1010,7 +1012,7 @@ get_select_query_def(Query *query, deparse_context *context)
quote_identifier(rte->ref->relname));
if (rte->ref->attrs != NIL)
{
- List *col;
+ List *col;
appendStringInfo(buf, " (");
foreach(col, rte->ref->attrs)
@@ -1018,7 +1020,7 @@ get_select_query_def(Query *query, deparse_context *context)
if (col != rte->ref->attrs)
appendStringInfo(buf, ", ");
appendStringInfo(buf, "%s",
- quote_identifier(strVal(lfirst(col))));
+ quote_identifier(strVal(lfirst(col))));
}
appendStringInfoChar(buf, ')');
}
@@ -1042,7 +1044,7 @@ get_select_query_def(Query *query, deparse_context *context)
foreach(l, query->groupClause)
{
GroupClause *grp = (GroupClause *) lfirst(l);
- Node *groupexpr;
+ Node *groupexpr;
groupexpr = get_sortgroupclause_expr(grp,
query->targetList);
@@ -1228,8 +1230,8 @@ get_delete_query_def(Query *query, deparse_context *context)
static RangeTblEntry *
get_rte_for_var(Var *var, deparse_context *context)
{
- List *rtlist = context->rangetables;
- int sup = var->varlevelsup;
+ List *rtlist = context->rangetables;
+ int sup = var->varlevelsup;
while (sup-- > 0)
rtlist = lnext(rtlist);
@@ -1281,11 +1283,11 @@ get_rule_expr(Node *node, deparse_context *context)
appendStringInfo(buf, "old.");
else
appendStringInfo(buf, "%s.",
- quote_identifier(rte->ref->relname));
+ quote_identifier(rte->ref->relname));
}
appendStringInfo(buf, "%s",
- quote_identifier(get_attribute_name(rte->relid,
- var->varattno)));
+ quote_identifier(get_attribute_name(rte->relid,
+ var->varattno)));
}
break;
@@ -1307,7 +1309,7 @@ get_rule_expr(Node *node, deparse_context *context)
/* binary operator */
get_rule_expr((Node *) lfirst(args), context);
appendStringInfo(buf, " %s ",
- get_opname(((Oper *) expr->oper)->opno));
+ get_opname(((Oper *) expr->oper)->opno));
get_rule_expr((Node *) lsecond(args), context);
}
else
@@ -1318,7 +1320,7 @@ get_rule_expr(Node *node, deparse_context *context)
Form_pg_operator optup;
tp = SearchSysCacheTuple(OPEROID,
- ObjectIdGetDatum(opno),
+ ObjectIdGetDatum(opno),
0, 0, 0);
Assert(HeapTupleIsValid(tp));
optup = (Form_pg_operator) GETSTRUCT(tp);
@@ -1435,7 +1437,7 @@ get_rule_expr(Node *node, deparse_context *context)
appendStringInfoChar(buf, '(');
get_rule_expr(relabel->arg, context);
typetup = SearchSysCacheTuple(TYPEOID,
- ObjectIdGetDatum(relabel->resulttype),
+ ObjectIdGetDatum(relabel->resulttype),
0, 0, 0);
if (!HeapTupleIsValid(typetup))
elog(ERROR, "cache lookup of type %u failed",
@@ -1510,7 +1512,8 @@ get_func_expr(Expr *expr, deparse_context *context)
proname = pstrdup(NameStr(procStruct->proname));
/*
- * nullvalue() and nonnullvalue() should get turned into special syntax
+ * nullvalue() and nonnullvalue() should get turned into special
+ * syntax
*/
if (procStruct->pronargs == 1 && procStruct->proargtypes[0] == InvalidOid)
{
@@ -1540,18 +1543,19 @@ get_func_expr(Expr *expr, deparse_context *context)
/*
* Strip off any RelabelType on the input, so we don't print
- * redundancies like x::bpchar::char(8).
- * XXX Are there any cases where this is a bad idea?
+ * redundancies like x::bpchar::char(8). XXX Are there any cases
+ * where this is a bad idea?
*/
if (IsA(arg, RelabelType))
arg = ((RelabelType *) arg)->arg;
appendStringInfoChar(buf, '(');
get_rule_expr(arg, context);
appendStringInfo(buf, ")::");
+
/*
- * Show typename with appropriate length decoration.
- * Note that since exprIsLengthCoercion succeeded, the function
- * name is the same as its output type name.
+ * Show typename with appropriate length decoration. Note that
+ * since exprIsLengthCoercion succeeded, the function name is the
+ * same as its output type name.
*/
if (strcmp(proname, "bpchar") == 0)
{
@@ -1571,7 +1575,7 @@ get_func_expr(Expr *expr, deparse_context *context)
{
if (coercedTypmod >= (int32) VARHDRSZ)
appendStringInfo(buf, "numeric(%d,%d)",
- ((coercedTypmod - VARHDRSZ) >> 16) & 0xffff,
+ ((coercedTypmod - VARHDRSZ) >> 16) & 0xffff,
(coercedTypmod - VARHDRSZ) & 0xffff);
else
appendStringInfo(buf, "numeric");
@@ -1621,8 +1625,8 @@ get_tle_expr(TargetEntry *tle, deparse_context *context)
int32 coercedTypmod;
/*
- * If top level is a length coercion to the correct length, suppress it;
- * else dump the expression normally.
+ * If top level is a length coercion to the correct length, suppress
+ * it; else dump the expression normally.
*/
if (tle->resdom->restypmod >= 0 &&
exprIsLengthCoercion((Node *) expr, &coercedTypmod) &&
@@ -1659,10 +1663,11 @@ get_const_expr(Const *constval, deparse_context *context)
if (constval->constisnull)
{
+
/*
* Always label the type of a NULL constant. This not only
- * prevents misdecisions about the type, but it ensures that
- * our output is a valid b_expr.
+ * prevents misdecisions about the type, but it ensures that our
+ * output is a valid b_expr.
*/
extval = pstrdup(NameStr(typeStruct->typname));
appendStringInfo(buf, "NULL::%s", quote_identifier(extval));
@@ -1681,20 +1686,21 @@ get_const_expr(Const *constval, deparse_context *context)
case INT4OID:
case OIDOID: /* int types */
case FLOAT4OID:
- case FLOAT8OID: /* float types */
+ case FLOAT8OID: /* float types */
/* These types are printed without quotes */
appendStringInfo(buf, extval);
break;
default:
+
/*
* We must quote any funny characters in the constant's
- * representation.
- * XXX Any MULTIBYTE considerations here?
+ * representation. XXX Any MULTIBYTE considerations here?
*/
appendStringInfoChar(buf, '\'');
for (valptr = extval; *valptr; valptr++)
{
- char ch = *valptr;
+ char ch = *valptr;
+
if (ch == '\'' || ch == '\\')
{
appendStringInfoChar(buf, '\\');
@@ -1818,10 +1824,11 @@ get_sublink_expr(Node *node, deparse_context *context)
static char *
quote_identifier(char *ident)
{
+
/*
* Can avoid quoting if ident starts with a lowercase letter and
- * contains only lowercase letters, digits, and underscores,
- * *and* is not any SQL keyword. Otherwise, supply quotes.
+ * contains only lowercase letters, digits, and underscores, *and* is
+ * not any SQL keyword. Otherwise, supply quotes.
*/
bool safe;
char *result;
@@ -1835,20 +1842,21 @@ quote_identifier(char *ident)
{
char *ptr;
- for (ptr = ident+1; *ptr; ptr++)
+ for (ptr = ident + 1; *ptr; ptr++)
{
- char ch = *ptr;
+ char ch = *ptr;
safe = ((ch >= 'a' && ch <= 'z') ||
(ch >= '0' && ch <= '9') ||
(ch == '_'));
- if (! safe)
+ if (!safe)
break;
}
}
if (safe)
{
+
/*
* Check for keyword. This test is overly strong, since many of
* the "keywords" known to the parser are usable as column names,
@@ -1955,7 +1963,11 @@ check_if_rte_used_walker(Node *node,
check_if_rte_used(query->havingQual,
context->rt_index, context->levelsup + 1))
return true;
- /* fall through to let expression_tree_walker examine lefthand args */
+
+ /*
+ * fall through to let expression_tree_walker examine lefthand
+ * args
+ */
}
return expression_tree_walker(node, check_if_rte_used_walker,
(void *) context);
diff --git a/src/backend/utils/adt/selfuncs.c b/src/backend/utils/adt/selfuncs.c
index 7e03b10d431..fc6852c1490 100644
--- a/src/backend/utils/adt/selfuncs.c
+++ b/src/backend/utils/adt/selfuncs.c
@@ -15,7 +15,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/selfuncs.c,v 1.63 2000/04/09 04:31:37 tgl Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/selfuncs.c,v 1.64 2000/04/12 17:15:51 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -45,25 +45,25 @@
#define FunctionalSelectivity(nIndKeys,attNum) ((attNum)==InvalidAttrNumber)
/* default selectivity estimate for equalities such as "A = b" */
-#define DEFAULT_EQ_SEL 0.01
+#define DEFAULT_EQ_SEL 0.01
/* default selectivity estimate for inequalities such as "A < b" */
#define DEFAULT_INEQ_SEL (1.0 / 3.0)
static bool convert_string_to_scalar(char *str, int strlength,
- double *scaleval);
+ double *scaleval);
static void getattproperties(Oid relid, AttrNumber attnum,
- Oid *typid,
- int *typlen,
- bool *typbyval,
- int32 *typmod);
+ Oid *typid,
+ int *typlen,
+ bool *typbyval,
+ int32 *typmod);
static bool getattstatistics(Oid relid, AttrNumber attnum,
- Oid typid, int32 typmod,
- double *nullfrac,
- double *commonfrac,
- Datum *commonval,
- Datum *loval,
- Datum *hival);
+ Oid typid, int32 typmod,
+ double *nullfrac,
+ double *commonfrac,
+ Datum *commonval,
+ Datum *loval,
+ Datum *hival);
/*
@@ -109,15 +109,17 @@ eqsel(Oid opid,
{
if (flag & SEL_CONSTANT)
{
- /* Is the constant "=" to the column's most common value?
- * (Although the operator may not really be "=",
- * we will assume that seeing whether it returns TRUE
- * for the most common value is useful information.
- * If you don't like it, maybe you shouldn't be using
- * eqsel for your operator...)
+
+ /*
+ * Is the constant "=" to the column's most common value?
+ * (Although the operator may not really be "=", we will
+ * assume that seeing whether it returns TRUE for the most
+ * common value is useful information. If you don't like
+ * it, maybe you shouldn't be using eqsel for your
+ * operator...)
*/
- RegProcedure eqproc = get_opcode(opid);
- bool mostcommon;
+ RegProcedure eqproc = get_opcode(opid);
+ bool mostcommon;
if (eqproc == (RegProcedure) NULL)
elog(ERROR, "eqsel: no procedure for operator %u",
@@ -133,7 +135,9 @@ eqsel(Oid opid,
if (mostcommon)
{
- /* Constant is "=" to the most common value. We know
+
+ /*
+ * Constant is "=" to the most common value. We know
* selectivity exactly (or as exactly as VACUUM could
* calculate it, anyway).
*/
@@ -141,17 +145,22 @@ eqsel(Oid opid,
}
else
{
- /* Comparison is against a constant that is neither the
- * most common value nor null. Its selectivity cannot
- * be more than this:
+
+ /*
+ * Comparison is against a constant that is neither
+ * the most common value nor null. Its selectivity
+ * cannot be more than this:
*/
selec = 1.0 - commonfrac - nullfrac;
if (selec > commonfrac)
selec = commonfrac;
- /* and in fact it's probably less, so we should apply
- * a fudge factor. The only case where we don't is
- * for a boolean column, where indeed we have estimated
- * the less-common value's frequency exactly!
+
+ /*
+ * and in fact it's probably less, so we should apply
+ * a fudge factor. The only case where we don't is
+ * for a boolean column, where indeed we have
+ * estimated the less-common value's frequency
+ * exactly!
*/
if (typid != BOOLOID)
selec *= 0.5;
@@ -159,14 +168,18 @@ eqsel(Oid opid,
}
else
{
- /* Search is for a value that we do not know a priori,
- * but we will assume it is not NULL. Selectivity
- * cannot be more than this:
+
+ /*
+ * Search is for a value that we do not know a priori, but
+ * we will assume it is not NULL. Selectivity cannot be
+ * more than this:
*/
selec = 1.0 - nullfrac;
if (selec > commonfrac)
selec = commonfrac;
- /* and in fact it's probably less, so apply a fudge
+
+ /*
+ * and in fact it's probably less, so apply a fudge
* factor.
*/
selec *= 0.5;
@@ -178,15 +191,17 @@ eqsel(Oid opid,
else if (selec > 1.0)
selec = 1.0;
- if (! typbyval)
+ if (!typbyval)
pfree(DatumGetPointer(commonval));
}
else
{
- /* No VACUUM ANALYZE stats available, so make a guess using
- * the disbursion stat (if we have that, which is unlikely
- * for a normal attribute; but for a system attribute we may
- * be able to estimate it).
+
+ /*
+ * No VACUUM ANALYZE stats available, so make a guess using
+ * the disbursion stat (if we have that, which is unlikely for
+ * a normal attribute; but for a system attribute we may be
+ * able to estimate it).
*/
selec = get_attdisbursion(relid, attno, 0.01);
}
@@ -234,7 +249,7 @@ scalarltsel(Oid opid,
float64 result;
result = (float64) palloc(sizeof(float64data));
- if (! (flag & SEL_CONSTANT) || NONVALUE(attno) || NONVALUE(relid))
+ if (!(flag & SEL_CONSTANT) || NONVALUE(attno) || NONVALUE(relid))
*result = DEFAULT_INEQ_SEL;
else
{
@@ -253,21 +268,24 @@ scalarltsel(Oid opid,
numerator,
denominator;
- /* Get left and right datatypes of the operator so we know
- * what type the constant is.
+ /*
+ * Get left and right datatypes of the operator so we know what
+ * type the constant is.
*/
oprtuple = get_operator_tuple(opid);
- if (! HeapTupleIsValid(oprtuple))
+ if (!HeapTupleIsValid(oprtuple))
elog(ERROR, "scalarltsel: no tuple for operator %u", opid);
ltype = ((Form_pg_operator) GETSTRUCT(oprtuple))->oprleft;
rtype = ((Form_pg_operator) GETSTRUCT(oprtuple))->oprright;
/* Convert the constant to a uniform comparison scale. */
- if (! convert_to_scalar(value,
- ((flag & SEL_RIGHT) ? rtype : ltype),
- &val))
+ if (!convert_to_scalar(value,
+ ((flag & SEL_RIGHT) ? rtype : ltype),
+ &val))
{
- /* Ideally we'd produce an error here, on the grounds that the
+
+ /*
+ * Ideally we'd produce an error here, on the grounds that the
* given operator shouldn't have scalarltsel registered as its
* selectivity func unless we can deal with its operand types.
* But currently, all manner of stuff is invoking scalarltsel,
@@ -281,9 +299,9 @@ scalarltsel(Oid opid,
getattproperties(relid, attno,
&typid, &typlen, &typbyval, &typmod);
- if (! getattstatistics(relid, attno, typid, typmod,
- NULL, NULL, NULL,
- &loval, &hival))
+ if (!getattstatistics(relid, attno, typid, typmod,
+ NULL, NULL, NULL,
+ &loval, &hival))
{
/* no stats available, so default result */
*result = DEFAULT_INEQ_SEL;
@@ -291,11 +309,11 @@ scalarltsel(Oid opid,
}
/* Convert the attribute's loval/hival to common scale. */
- if (! convert_to_scalar(loval, typid, &low) ||
- ! convert_to_scalar(hival, typid, &high))
+ if (!convert_to_scalar(loval, typid, &low) ||
+ !convert_to_scalar(hival, typid, &high))
{
/* See above comments... */
- if (! typbyval)
+ if (!typbyval)
{
pfree(DatumGetPointer(hival));
pfree(DatumGetPointer(loval));
@@ -306,7 +324,7 @@ scalarltsel(Oid opid,
}
/* release temp storage if needed */
- if (! typbyval)
+ if (!typbyval)
{
pfree(DatumGetPointer(hival));
pfree(DatumGetPointer(loval));
@@ -314,18 +332,22 @@ scalarltsel(Oid opid,
if (high <= low)
{
- /* If we trusted the stats fully, we could return a small or
- * large selec depending on which side of the single data point
- * the constant is on. But it seems better to assume that the
- * stats are wrong and return a default...
+
+ /*
+ * If we trusted the stats fully, we could return a small or
+ * large selec depending on which side of the single data
+ * point the constant is on. But it seems better to assume
+ * that the stats are wrong and return a default...
*/
*result = DEFAULT_INEQ_SEL;
}
else if (val < low || val > high)
{
- /* If given value is outside the statistical range, return a
- * small or large value; but not 0.0/1.0 since there is a chance
- * the stats are out of date.
+
+ /*
+ * If given value is outside the statistical range, return a
+ * small or large value; but not 0.0/1.0 since there is a
+ * chance the stats are out of date.
*/
if (flag & SEL_RIGHT)
*result = (val < low) ? 0.001 : 0.999;
@@ -359,8 +381,9 @@ scalargtsel(Oid opid,
{
float64 result;
- /* Compute selectivity of "<", then invert --- but only if we
- * were able to produce a non-default estimate.
+ /*
+ * Compute selectivity of "<", then invert --- but only if we were
+ * able to produce a non-default estimate.
*/
result = scalarltsel(opid, relid, attno, value, flag);
if (*result != DEFAULT_INEQ_SEL)
@@ -392,23 +415,24 @@ eqjoinsel(Oid opid,
{
num1 = unknown1 ? 1.0 : get_attdisbursion(relid1, attno1, 0.01);
num2 = unknown2 ? 1.0 : get_attdisbursion(relid2, attno2, 0.01);
+
/*
- * The join selectivity cannot be more than num2, since each
- * tuple in table 1 could match no more than num2 fraction of
- * tuples in table 2 (and that's only if the table-1 tuple
- * matches the most common value in table 2, so probably it's
- * less). By the same reasoning it is not more than num1.
- * The min is therefore an upper bound.
+ * The join selectivity cannot be more than num2, since each tuple
+ * in table 1 could match no more than num2 fraction of tuples in
+ * table 2 (and that's only if the table-1 tuple matches the most
+ * common value in table 2, so probably it's less). By the same
+ * reasoning it is not more than num1. The min is therefore an
+ * upper bound.
*
* If we know the disbursion of only one side, use it; the reasoning
* above still works.
*
- * XXX can we make a better estimate here? Using the nullfrac
+ * XXX can we make a better estimate here? Using the nullfrac
* statistic might be helpful, for example. Assuming the operator
- * is strict (does not succeed for null inputs) then the selectivity
- * couldn't be more than (1-nullfrac1)*(1-nullfrac2), which might
- * be usefully small if there are many nulls. How about applying
- * the operator to the most common values?
+ * is strict (does not succeed for null inputs) then the
+ * selectivity couldn't be more than (1-nullfrac1)*(1-nullfrac2),
+ * which might be usefully small if there are many nulls. How
+ * about applying the operator to the most common values?
*/
min = (num1 < num2) ? num1 : num2;
*result = min;
@@ -434,7 +458,7 @@ neqjoinsel(Oid opid,
}
/*
- * scalarltjoinsel - Join selectivity of "<" and "<=" for scalars
+ * scalarltjoinsel - Join selectivity of "<" and "<=" for scalars
*/
float64
scalarltjoinsel(Oid opid,
@@ -451,7 +475,7 @@ scalarltjoinsel(Oid opid,
}
/*
- * scalargtjoinsel - Join selectivity of ">" and ">=" for scalars
+ * scalargtjoinsel - Join selectivity of ">" and ">=" for scalars
*/
float64
scalargtjoinsel(Oid opid,
@@ -493,10 +517,11 @@ convert_to_scalar(Datum value, Oid typid,
{
switch (typid)
{
- /*
- * Built-in numeric types
- */
- case BOOLOID:
+
+ /*
+ * Built-in numeric types
+ */
+ case BOOLOID:
*scaleval = (double) DatumGetUInt8(value);
return true;
case INT2OID:
@@ -506,16 +531,16 @@ convert_to_scalar(Datum value, Oid typid,
*scaleval = (double) DatumGetInt32(value);
return true;
case INT8OID:
- *scaleval = (double) (* i8tod((int64 *) DatumGetPointer(value)));
+ *scaleval = (double) (*i8tod((int64 *) DatumGetPointer(value)));
return true;
case FLOAT4OID:
- *scaleval = (double) (* DatumGetFloat32(value));
+ *scaleval = (double) (*DatumGetFloat32(value));
return true;
case FLOAT8OID:
- *scaleval = (double) (* DatumGetFloat64(value));
+ *scaleval = (double) (*DatumGetFloat64(value));
return true;
case NUMERICOID:
- *scaleval = (double) (* numeric_float8((Numeric) DatumGetPointer(value)));
+ *scaleval = (double) (*numeric_float8((Numeric) DatumGetPointer(value)));
return true;
case OIDOID:
case REGPROCOID:
@@ -523,110 +548,114 @@ convert_to_scalar(Datum value, Oid typid,
*scaleval = (double) DatumGetObjectId(value);
return true;
- /*
- * Built-in string types
- */
+ /*
+ * Built-in string types
+ */
case CHAROID:
- {
- char ch = DatumGetChar(value);
+ {
+ char ch = DatumGetChar(value);
- return convert_string_to_scalar(&ch, 1, scaleval);
- }
+ return convert_string_to_scalar(&ch, 1, scaleval);
+ }
case BPCHAROID:
case VARCHAROID:
case TEXTOID:
- {
- char *str = (char *) VARDATA(DatumGetPointer(value));
- int strlength = VARSIZE(DatumGetPointer(value)) - VARHDRSZ;
+ {
+ char *str = (char *) VARDATA(DatumGetPointer(value));
+ int strlength = VARSIZE(DatumGetPointer(value)) - VARHDRSZ;
- return convert_string_to_scalar(str, strlength, scaleval);
- }
+ return convert_string_to_scalar(str, strlength, scaleval);
+ }
case NAMEOID:
- {
- NameData *nm = (NameData *) DatumGetPointer(value);
+ {
+ NameData *nm = (NameData *) DatumGetPointer(value);
- return convert_string_to_scalar(NameStr(*nm), strlen(NameStr(*nm)),
- scaleval);
- }
+ return convert_string_to_scalar(NameStr(*nm), strlen(NameStr(*nm)),
+ scaleval);
+ }
- /*
- * Built-in absolute-time types
- */
+ /*
+ * Built-in absolute-time types
+ */
case TIMESTAMPOID:
- *scaleval = * ((Timestamp *) DatumGetPointer(value));
+ *scaleval = *((Timestamp *) DatumGetPointer(value));
return true;
case ABSTIMEOID:
- *scaleval = * abstime_timestamp(value);
+ *scaleval = *abstime_timestamp(value);
return true;
case DATEOID:
- *scaleval = * date_timestamp(value);
+ *scaleval = *date_timestamp(value);
return true;
- /*
- * Built-in relative-time types
- */
- case INTERVALOID:
- {
- Interval *interval = (Interval *) DatumGetPointer(value);
-
/*
- * Convert the month part of Interval to days using assumed
- * average month length of 365.25/12.0 days. Not too accurate,
- * but plenty good enough for our purposes.
+ * Built-in relative-time types
*/
- *scaleval = interval->time +
- interval->month * (365.25/12.0 * 24.0 * 60.0 * 60.0);
- return true;
- }
+ case INTERVALOID:
+ {
+ Interval *interval = (Interval *) DatumGetPointer(value);
+
+ /*
+ * Convert the month part of Interval to days using
+ * assumed average month length of 365.25/12.0 days. Not
+ * too accurate, but plenty good enough for our purposes.
+ */
+ *scaleval = interval->time +
+ interval->month * (365.25 / 12.0 * 24.0 * 60.0 * 60.0);
+ return true;
+ }
case RELTIMEOID:
*scaleval = (RelativeTime) DatumGetInt32(value);
return true;
case TINTERVALOID:
- {
- TimeInterval interval = (TimeInterval) DatumGetPointer(value);
-
- if (interval->status != 0)
{
- *scaleval = interval->data[1] - interval->data[0];
- return true;
+ TimeInterval interval = (TimeInterval) DatumGetPointer(value);
+
+ if (interval->status != 0)
+ {
+ *scaleval = interval->data[1] - interval->data[0];
+ return true;
+ }
+ break;
}
- break;
- }
case TIMEOID:
- *scaleval = * ((TimeADT *) DatumGetPointer(value));
+ *scaleval = *((TimeADT *) DatumGetPointer(value));
return true;
default:
- {
- /*
- * See whether there is a registered type-conversion function,
- * namely a procedure named "float8" with the right signature.
- * If so, assume we can convert the value to the numeric scale.
- *
- * NOTE: there are no such procedures in the standard distribution,
- * except with argument types that we already dealt with above.
- * This code is just here as an escape for user-defined types.
- */
- Oid oid_array[FUNC_MAX_ARGS];
- HeapTuple ftup;
-
- MemSet(oid_array, 0, FUNC_MAX_ARGS * sizeof(Oid));
- oid_array[0] = typid;
- ftup = SearchSysCacheTuple(PROCNAME,
- PointerGetDatum("float8"),
- Int32GetDatum(1),
- PointerGetDatum(oid_array),
- 0);
- if (HeapTupleIsValid(ftup) &&
- ((Form_pg_proc) GETSTRUCT(ftup))->prorettype == FLOAT8OID)
{
- RegProcedure convertproc = (RegProcedure) ftup->t_data->t_oid;
- Datum converted = (Datum) fmgr(convertproc, value);
- *scaleval = (double) (* DatumGetFloat64(converted));
- return true;
+
+ /*
+ * See whether there is a registered type-conversion
+ * function, namely a procedure named "float8" with the
+ * right signature. If so, assume we can convert the value
+ * to the numeric scale.
+ *
+ * NOTE: there are no such procedures in the standard
+ * distribution, except with argument types that we
+ * already dealt with above. This code is just here as an
+ * escape for user-defined types.
+ */
+ Oid oid_array[FUNC_MAX_ARGS];
+ HeapTuple ftup;
+
+ MemSet(oid_array, 0, FUNC_MAX_ARGS * sizeof(Oid));
+ oid_array[0] = typid;
+ ftup = SearchSysCacheTuple(PROCNAME,
+ PointerGetDatum("float8"),
+ Int32GetDatum(1),
+ PointerGetDatum(oid_array),
+ 0);
+ if (HeapTupleIsValid(ftup) &&
+ ((Form_pg_proc) GETSTRUCT(ftup))->prorettype == FLOAT8OID)
+ {
+ RegProcedure convertproc = (RegProcedure) ftup->t_data->t_oid;
+ Datum converted = (Datum) fmgr(convertproc, value);
+
+ *scaleval = (double) (*DatumGetFloat64(converted));
+ return true;
+ }
+ break;
}
- break;
- }
}
/* Don't know how to convert */
return false;
@@ -649,16 +678,18 @@ static bool
convert_string_to_scalar(char *str, int strlength,
double *scaleval)
{
- unsigned char *sptr;
- int slen;
+ unsigned char *sptr;
+ int slen;
+
#ifdef USE_LOCALE
- char *rawstr;
- char *xfrmstr;
- size_t xfrmsize;
- size_t xfrmlen;
+ char *rawstr;
+ char *xfrmstr;
+ size_t xfrmsize;
+ size_t xfrmlen;
+
#endif
- double num,
- denom;
+ double num,
+ denom;
if (strlength <= 0)
{
@@ -680,8 +711,8 @@ convert_string_to_scalar(char *str, int strlength,
{
/* Oops, didn't make it */
pfree(xfrmstr);
- xfrmstr = (char *) palloc(xfrmlen+1);
- xfrmlen = strxfrm(xfrmstr, rawstr, xfrmlen+1);
+ xfrmstr = (char *) palloc(xfrmlen + 1);
+ xfrmlen = strxfrm(xfrmstr, rawstr, xfrmlen + 1);
}
pfree(rawstr);
@@ -730,7 +761,7 @@ getattproperties(Oid relid, AttrNumber attnum,
ObjectIdGetDatum(relid),
Int16GetDatum(attnum),
0, 0);
- if (! HeapTupleIsValid(atp))
+ if (!HeapTupleIsValid(atp))
elog(ERROR, "getattproperties: no attribute tuple %u %d",
relid, (int) attnum);
att_tup = (Form_pg_attribute) GETSTRUCT(atp);
@@ -778,14 +809,14 @@ getattstatistics(Oid relid,
bool isnull;
/*
- * We assume that there will only be one entry in pg_statistic for
- * the given rel/att, so we search WITHOUT considering the staop
- * column. Someday, VACUUM might store more than one entry per rel/att,
+ * We assume that there will only be one entry in pg_statistic for the
+ * given rel/att, so we search WITHOUT considering the staop column.
+ * Someday, VACUUM might store more than one entry per rel/att,
* corresponding to more than one possible sort ordering defined for
* the column type. However, to make that work we will need to figure
* out which staop to search for --- it's not necessarily the one we
- * have at hand! (For example, we might have a '>' operator rather than
- * the '<' operator that will appear in staop.)
+ * have at hand! (For example, we might have a '>' operator rather
+ * than the '<' operator that will appear in staop.)
*/
tuple = SearchSysCacheTuple(STATRELID,
ObjectIdGetDatum(relid),
@@ -807,20 +838,22 @@ getattstatistics(Oid relid,
typeTuple = SearchSysCacheTuple(TYPEOID,
ObjectIdGetDatum(typid),
0, 0, 0);
- if (! HeapTupleIsValid(typeTuple))
+ if (!HeapTupleIsValid(typeTuple))
elog(ERROR, "getattstatistics: Cache lookup failed for type %u",
typid);
fmgr_info(((Form_pg_type) GETSTRUCT(typeTuple))->typinput, &inputproc);
typelem = ((Form_pg_type) GETSTRUCT(typeTuple))->typelem;
- /* Values are variable-length fields, so cannot access as struct fields.
- * Must do it the hard way with SysCacheGetAttr.
+ /*
+ * Values are variable-length fields, so cannot access as struct
+ * fields. Must do it the hard way with SysCacheGetAttr.
*/
if (commonval)
{
- text *val = (text *) SysCacheGetAttr(STATRELID, tuple,
- Anum_pg_statistic_stacommonval,
- &isnull);
+ text *val = (text *) SysCacheGetAttr(STATRELID, tuple,
+ Anum_pg_statistic_stacommonval,
+ &isnull);
+
if (isnull)
{
elog(DEBUG, "getattstatistics: stacommonval is null");
@@ -828,7 +861,8 @@ getattstatistics(Oid relid,
}
else
{
- char *strval = textout(val);
+ char *strval = textout(val);
+
*commonval = (Datum)
(*fmgr_faddr(&inputproc)) (strval, typelem, typmod);
pfree(strval);
@@ -837,9 +871,10 @@ getattstatistics(Oid relid,
if (loval)
{
- text *val = (text *) SysCacheGetAttr(STATRELID, tuple,
- Anum_pg_statistic_staloval,
- &isnull);
+ text *val = (text *) SysCacheGetAttr(STATRELID, tuple,
+ Anum_pg_statistic_staloval,
+ &isnull);
+
if (isnull)
{
elog(DEBUG, "getattstatistics: staloval is null");
@@ -847,7 +882,8 @@ getattstatistics(Oid relid,
}
else
{
- char *strval = textout(val);
+ char *strval = textout(val);
+
*loval = (Datum)
(*fmgr_faddr(&inputproc)) (strval, typelem, typmod);
pfree(strval);
@@ -856,9 +892,10 @@ getattstatistics(Oid relid,
if (hival)
{
- text *val = (text *) SysCacheGetAttr(STATRELID, tuple,
- Anum_pg_statistic_stahival,
- &isnull);
+ text *val = (text *) SysCacheGetAttr(STATRELID, tuple,
+ Anum_pg_statistic_stahival,
+ &isnull);
+
if (isnull)
{
elog(DEBUG, "getattstatistics: stahival is null");
@@ -866,7 +903,8 @@ getattstatistics(Oid relid,
}
else
{
- char *strval = textout(val);
+ char *strval = textout(val);
+
*hival = (Datum)
(*fmgr_faddr(&inputproc)) (strval, typelem, typmod);
pfree(strval);
@@ -894,11 +932,11 @@ genericcostestimate(Query *root, RelOptInfo *rel,
Cost *indexTotalCost,
Selectivity *indexSelectivity)
{
- double numIndexTuples;
- double numIndexPages;
+ double numIndexTuples;
+ double numIndexPages;
/* Estimate the fraction of main-table tuples that will be visited */
- *indexSelectivity = clauselist_selectivity(root, indexQuals,
+ *indexSelectivity = clauselist_selectivity(root, indexQuals,
lfirsti(rel->relids));
/* Estimate the number of index tuples that will be visited */
@@ -908,8 +946,8 @@ genericcostestimate(Query *root, RelOptInfo *rel,
numIndexPages = *indexSelectivity * index->pages;
/*
- * Always estimate at least one tuple and page are touched,
- * even when indexSelectivity estimate is tiny.
+ * Always estimate at least one tuple and page are touched, even when
+ * indexSelectivity estimate is tiny.
*/
if (numIndexTuples < 1.0)
numIndexTuples = 1.0;
@@ -921,11 +959,12 @@ genericcostestimate(Query *root, RelOptInfo *rel,
*
* Our generic assumption is that the index pages will be read
* sequentially, so they have cost 1.0 each, not random_page_cost.
- * Also, we charge for evaluation of the indexquals at each index tuple.
- * All the costs are assumed to be paid incrementally during the scan.
- */
- *indexStartupCost = 0;
- *indexTotalCost = numIndexPages +
+ * Also, we charge for evaluation of the indexquals at each index
+ * tuple. All the costs are assumed to be paid incrementally during
+ * the scan.
+ */
+ *indexStartupCost = 0;
+ *indexTotalCost = numIndexPages +
(cpu_index_tuple_cost + cost_qual_eval(indexQuals)) * numIndexTuples;
}
@@ -941,7 +980,7 @@ btcostestimate(Query *root, RelOptInfo *rel,
Selectivity *indexSelectivity)
{
genericcostestimate(root, rel, index, indexQuals,
- indexStartupCost, indexTotalCost, indexSelectivity);
+ indexStartupCost, indexTotalCost, indexSelectivity);
}
void
@@ -952,7 +991,7 @@ rtcostestimate(Query *root, RelOptInfo *rel,
Selectivity *indexSelectivity)
{
genericcostestimate(root, rel, index, indexQuals,
- indexStartupCost, indexTotalCost, indexSelectivity);
+ indexStartupCost, indexTotalCost, indexSelectivity);
}
void
@@ -963,7 +1002,7 @@ hashcostestimate(Query *root, RelOptInfo *rel,
Selectivity *indexSelectivity)
{
genericcostestimate(root, rel, index, indexQuals,
- indexStartupCost, indexTotalCost, indexSelectivity);
+ indexStartupCost, indexTotalCost, indexSelectivity);
}
void
@@ -974,5 +1013,5 @@ gistcostestimate(Query *root, RelOptInfo *rel,
Selectivity *indexSelectivity)
{
genericcostestimate(root, rel, index, indexQuals,
- indexStartupCost, indexTotalCost, indexSelectivity);
+ indexStartupCost, indexTotalCost, indexSelectivity);
}
diff --git a/src/backend/utils/adt/tid.c b/src/backend/utils/adt/tid.c
index 06ab6d7a3c5..070cb05018d 100644
--- a/src/backend/utils/adt/tid.c
+++ b/src/backend/utils/adt/tid.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/tid.c,v 1.15 2000/01/26 05:57:14 momjian Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/tid.c,v 1.16 2000/04/12 17:15:51 momjian Exp $
*
* NOTES
* input routine largely stolen from boxin().
@@ -31,7 +31,7 @@
ItemPointer
tidin(const char *str)
{
- const char *p,
+ const char *p,
*coord[NTIDARGS];
int i;
ItemPointer result;
@@ -105,25 +105,21 @@ bool
tideq(ItemPointer arg1, ItemPointer arg2)
{
if ((!arg1) || (!arg2))
- {
return false;
- }
-
- return ( BlockIdGetBlockNumber(&(arg1->ip_blkid)) ==
- BlockIdGetBlockNumber(&(arg2->ip_blkid)) &&
- arg1->ip_posid == arg2->ip_posid );
+
+ return (BlockIdGetBlockNumber(&(arg1->ip_blkid)) ==
+ BlockIdGetBlockNumber(&(arg2->ip_blkid)) &&
+ arg1->ip_posid == arg2->ip_posid);
}
bool
tidne(ItemPointer arg1, ItemPointer arg2)
{
if ((!arg1) || (!arg2))
- {
return false;
- }
- return ( BlockIdGetBlockNumber(&(arg1->ip_blkid)) !=
- BlockIdGetBlockNumber(&(arg2->ip_blkid)) ||
- arg1->ip_posid != arg2->ip_posid );
+ return (BlockIdGetBlockNumber(&(arg1->ip_blkid)) !=
+ BlockIdGetBlockNumber(&(arg2->ip_blkid)) ||
+ arg1->ip_posid != arg2->ip_posid);
}
text *
@@ -131,7 +127,8 @@ tid_text(ItemPointer tid)
{
char *str;
- if (!tid) return (text *)NULL;
+ if (!tid)
+ return (text *) NULL;
str = tidout(tid);
return textin(str);
@@ -140,10 +137,11 @@ tid_text(ItemPointer tid)
ItemPointer
text_tid(const text *string)
{
- ItemPointer result;
- char *str;
+ ItemPointer result;
+ char *str;
- if (!string) return (ItemPointer)0;
+ if (!string)
+ return (ItemPointer) 0;
str = textout((text *) string);
result = tidin(str);
@@ -162,7 +160,8 @@ text_tid(const text *string)
ItemPointer
currtid_byreloid(Oid reloid, ItemPointer tid)
{
- ItemPointer result = NULL, ret;
+ ItemPointer result = NULL,
+ ret;
Relation rel;
result = (ItemPointer) palloc(sizeof(ItemPointerData));
@@ -183,11 +182,13 @@ currtid_byreloid(Oid reloid, ItemPointer tid)
ItemPointer
currtid_byrelname(const text *relname, ItemPointer tid)
{
- ItemPointer result = NULL, ret;
- char *str;
+ ItemPointer result = NULL,
+ ret;
+ char *str;
Relation rel;
- if (!relname) return result;
+ if (!relname)
+ return result;
str = textout((text *) relname);
@@ -201,7 +202,7 @@ currtid_byrelname(const text *relname, ItemPointer tid)
heap_close(rel, AccessShareLock);
}
else
- elog(ERROR, "Relation %s not found", textout((text *)relname));
+ elog(ERROR, "Relation %s not found", textout((text *) relname));
pfree(str);
return result;
diff --git a/src/backend/utils/adt/timestamp.c b/src/backend/utils/adt/timestamp.c
index 7a94ddd804d..a731ce3cef5 100644
--- a/src/backend/utils/adt/timestamp.c
+++ b/src/backend/utils/adt/timestamp.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/timestamp.c,v 1.24 2000/04/07 13:39:41 thomas Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/timestamp.c,v 1.25 2000/04/12 17:15:51 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -42,10 +42,10 @@ static double time2t(const int hour, const int min, const double sec);
/* timestamp_in()
* Convert a string to internal form.
*/
-Timestamp *
+Timestamp *
timestamp_in(char *str)
{
- Timestamp *result;
+ Timestamp *result;
double fsec;
struct tm tt,
@@ -249,10 +249,10 @@ EncodeSpecialTimestamp(Timestamp dt, char *str)
return FALSE;
} /* EncodeSpecialTimestamp() */
-Timestamp *
+Timestamp *
now(void)
{
- Timestamp *result;
+ Timestamp *result;
AbsoluteTime sec;
result = palloc(sizeof(Timestamp));
@@ -469,9 +469,9 @@ tm2interval(struct tm * tm, double fsec, Interval *span)
{
span->month = ((tm->tm_year * 12) + tm->tm_mon);
span->time = ((((((tm->tm_mday * 24.0)
- + tm->tm_hour) * 60.0)
- + tm->tm_min) * 60.0)
- + tm->tm_sec);
+ + tm->tm_hour) * 60.0)
+ + tm->tm_min) * 60.0)
+ + tm->tm_sec);
span->time = JROUND(span->time + fsec);
return 0;
@@ -562,7 +562,7 @@ SetTimestamp(Timestamp dt)
return dt;
} /* SetTimestamp() */
-/* timestamp_relop - is timestamp1 relop timestamp2
+/* timestamp_relop - is timestamp1 relop timestamp2
*/
bool
timestamp_eq(Timestamp *timestamp1, Timestamp *timestamp2)
@@ -896,13 +896,15 @@ overlaps_timestamp(Timestamp *ts1, Timestamp *te1, Timestamp *ts2, Timestamp *te
/* Make sure we have ordered pairs... */
if (timestamp_gt(ts1, te1))
{
- Timestamp *tt = ts1;
+ Timestamp *tt = ts1;
+
ts1 = te1;
te1 = tt;
}
if (timestamp_gt(ts2, te2))
{
- Timestamp *tt = ts2;
+ Timestamp *tt = ts2;
+
ts2 = te2;
te2 = tt;
}
@@ -910,7 +912,7 @@ overlaps_timestamp(Timestamp *ts1, Timestamp *te1, Timestamp *ts2, Timestamp *te
return ((timestamp_gt(ts1, ts2) && (timestamp_lt(ts1, te2) || timestamp_lt(te1, te2)))
|| (timestamp_gt(ts2, ts1) && (timestamp_lt(ts2, te1) || timestamp_lt(te2, te1)))
|| timestamp_eq(ts1, ts2));
-} /* overlaps_timestamp() */
+} /* overlaps_timestamp() */
/*----------------------------------------------------------
@@ -921,10 +923,10 @@ overlaps_timestamp(Timestamp *ts1, Timestamp *te1, Timestamp *ts2, Timestamp *te
* actual value.
*---------------------------------------------------------*/
-Timestamp *
+Timestamp *
timestamp_smaller(Timestamp *timestamp1, Timestamp *timestamp2)
{
- Timestamp *result;
+ Timestamp *result;
Timestamp dt1,
dt2;
@@ -952,10 +954,10 @@ timestamp_smaller(Timestamp *timestamp1, Timestamp *timestamp2)
return result;
} /* timestamp_smaller() */
-Timestamp *
+Timestamp *
timestamp_larger(Timestamp *timestamp1, Timestamp *timestamp2)
{
- Timestamp *result;
+ Timestamp *result;
Timestamp dt1,
dt2;
@@ -1028,10 +1030,10 @@ timestamp_mi(Timestamp *timestamp1, Timestamp *timestamp2)
* to the last day of month.
* Lastly, add in the "quantitative time".
*/
-Timestamp *
+Timestamp *
timestamp_pl_span(Timestamp *timestamp, Interval *span)
{
- Timestamp *result;
+ Timestamp *result;
Timestamp dt;
int tz;
char *tzn;
@@ -1099,10 +1101,10 @@ timestamp_pl_span(Timestamp *timestamp, Interval *span)
return result;
} /* timestamp_pl_span() */
-Timestamp *
+Timestamp *
timestamp_mi_span(Timestamp *timestamp, Interval *span)
{
- Timestamp *result;
+ Timestamp *result;
Interval tspan;
if (!PointerIsValid(timestamp) || !PointerIsValid(span))
@@ -1485,10 +1487,10 @@ timestamp_text(Timestamp *timestamp)
* Text type is not null terminated, so use temporary string
* then call the standard input routine.
*/
-Timestamp *
+Timestamp *
text_timestamp(text *str)
{
- Timestamp *result;
+ Timestamp *result;
int i;
char *sp,
*dp,
@@ -1571,10 +1573,10 @@ text_interval(text *str)
/* timestamp_trunc()
* Extract specified field from timestamp.
*/
-Timestamp *
+Timestamp *
timestamp_trunc(text *units, Timestamp *timestamp)
{
- Timestamp *result;
+ Timestamp *result;
Timestamp dt;
int tz;
diff --git a/src/backend/utils/adt/varbit.c b/src/backend/utils/adt/varbit.c
index 47946faccc0..cd2839c6929 100644
--- a/src/backend/utils/adt/varbit.c
+++ b/src/backend/utils/adt/varbit.c
@@ -4,7 +4,7 @@
* Functions for the built-in type bit() and varying bit().
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/varbit.c,v 1.1 2000/04/08 02:12:54 thomas Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/varbit.c,v 1.2 2000/04/12 17:15:52 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -35,235 +35,261 @@
#include "utils/builtins.h"
#include "access/htup.h"
-/*
+/*
Prefixes:
- zp -- zero-padded fixed length bit string
- var -- varying bit string
+ zp -- zero-padded fixed length bit string
+ var -- varying bit string
attypmod -- contains the length of the bit string in bits, or for
- varying bits the maximum length.
+ varying bits the maximum length.
The data structure contains the following elements:
- header -- length of the whole data structure (incl header)
- in bytes. (as with all varying length datatypes)
- data section -- private data section for the bits data structures
- bitlength -- lenght of the bit string in bits
+ header -- length of the whole data structure (incl header)
+ in bytes. (as with all varying length datatypes)
+ data section -- private data section for the bits data structures
+ bitlength -- lenght of the bit string in bits
bitdata -- least significant byte first string
*/
-char *
-varbit_out (bits8 *s) {
- return zpbits_out(s);
+char *
+varbit_out(bits8 *s)
+{
+ return zpbits_out(s);
}
/*
* zpbit_in -
* converts a string to the internal representation of a bitstring.
- * The length is determined by the number of bits required plus
- * VARHDRSZ bytes or from atttypmod.
- * (XXX dummy is here because we pass typelem as the second argument
- * for array_in. copied this, no idea what it means??)
+ * The length is determined by the number of bits required plus
+ * VARHDRSZ bytes or from atttypmod.
+ * (XXX dummy is here because we pass typelem as the second argument
+ * for array_in. copied this, no idea what it means??)
*/
bits8 *
-zpbit_in(char *s, int dummy, int32 atttypmod)
-{
- bits8 *result; /* the bits string that was read in */
- char *sp; /* pointer into the character string */
- bits8 *r;
- int len, /* Length of the whole data structure */
- bitlen, /* Number of bits in the bit string */
- slen; /* Length of the input string */
- int bit_not_hex = 0; /* 0 = hex string 1=bit string */
- int bc, ipad;
- bits8 x = 0;
-
-
- if (s == NULL)
- return (bits8 *) NULL;
-
- /* Check that the first character is a b or an x */
- if (s[0]=='b' || s[0]=='B')
- bit_not_hex = 1;
- else if (s[0]=='x' || s[0]=='X')
- bit_not_hex = 0;
- else
- elog(ERROR, "zpbit_in: %s is not a valid bitstring",s);
-
- slen = strlen(s) - 1;
- /* Determine bitlength from input string */
- bitlen = slen;
- if (!bit_not_hex)
- bitlen *= 4;
-
- /* Sometimes atttypmod is not supplied. If it is supplied we need to make
- sure that the bitstring fits. Note that the number of infered bits can
- be larger than the number of actual bits needed, but only if we are
- reading a hex string and not by more than 3 bits, as a hex string gives
- and accurate length upto 4 bits */
- if (atttypmod == -1)
- atttypmod = bitlen;
- else
- if ((bitlen>atttypmod && bit_not_hex) ||
- (bitlen>atttypmod+3 && !bit_not_hex))
- elog(ERROR, "zpbit_in: bit string of size %d cannot be written into bits(%d)",
- bitlen,atttypmod);
-
-
- len = VARBITDATALEN(atttypmod);
-
- if (len > MaxAttrSize)
- elog(ERROR, "zpbit_in: length of bit() must be less than %ld",
- (MaxAttrSize-VARHDRSZ-VARBITHDRSZ)*BITSPERBYTE);
-
- result = (bits8 *) palloc(len);
- /* set to 0 so that *r is always initialised and strin is zero-padded */
- memset(result, 0, len);
- VARSIZE(result) = len;
- VARBITLEN(result) = atttypmod;
-
- /* We need to read the bitstring from the end, as we store it least
- significant byte first. s points to the byte before the beginning
- of the bitstring */
- sp = s+1;
- r = VARBITS(result);
- if (bit_not_hex)
- {
- /* Parse the bit representation of the string */
- /* We know it fits, as bitlen was compared to atttypmod */
- x = BITHIGH;
- for (bc = 0; sp != s+slen+1; sp++, bc++)
+zpbit_in(char *s, int dummy, int32 atttypmod)
+{
+ bits8 *result; /* the bits string that was read in */
+ char *sp; /* pointer into the character string */
+ bits8 *r;
+ int len, /* Length of the whole data structure */
+ bitlen, /* Number of bits in the bit string */
+ slen; /* Length of the input string */
+ int bit_not_hex = 0;/* 0 = hex string 1=bit string */
+ int bc,
+ ipad;
+ bits8 x = 0;
+
+
+ if (s == NULL)
+ return (bits8 *) NULL;
+
+ /* Check that the first character is a b or an x */
+ if (s[0] == 'b' || s[0] == 'B')
+ bit_not_hex = 1;
+ else if (s[0] == 'x' || s[0] == 'X')
+ bit_not_hex = 0;
+ else
+ elog(ERROR, "zpbit_in: %s is not a valid bitstring", s);
+
+ slen = strlen(s) - 1;
+ /* Determine bitlength from input string */
+ bitlen = slen;
+ if (!bit_not_hex)
+ bitlen *= 4;
+
+ /*
+ * Sometimes atttypmod is not supplied. If it is supplied we need to
+ * make sure that the bitstring fits. Note that the number of infered
+ * bits can be larger than the number of actual bits needed, but only
+ * if we are reading a hex string and not by more than 3 bits, as a
+ * hex string gives and accurate length upto 4 bits
+ */
+ if (atttypmod == -1)
+ atttypmod = bitlen;
+ else if ((bitlen > atttypmod && bit_not_hex) ||
+ (bitlen > atttypmod + 3 && !bit_not_hex))
+ elog(ERROR, "zpbit_in: bit string of size %d cannot be written into bits(%d)",
+ bitlen, atttypmod);
+
+
+ len = VARBITDATALEN(atttypmod);
+
+ if (len > MaxAttrSize)
+ elog(ERROR, "zpbit_in: length of bit() must be less than %ld",
+ (MaxAttrSize - VARHDRSZ - VARBITHDRSZ) * BITSPERBYTE);
+
+ result = (bits8 *) palloc(len);
+ /* set to 0 so that *r is always initialised and strin is zero-padded */
+ memset(result, 0, len);
+ VARSIZE(result) = len;
+ VARBITLEN(result) = atttypmod;
+
+ /*
+ * We need to read the bitstring from the end, as we store it least
+ * significant byte first. s points to the byte before the beginning
+ * of the bitstring
+ */
+ sp = s + 1;
+ r = VARBITS(result);
+ if (bit_not_hex)
{
- if (*sp=='1')
- *r |= x;
- if (bc==7) {
- bc = 0;
- x = BITHIGH;
- r++;
- } else
- x >>= 1;
+ /* Parse the bit representation of the string */
+ /* We know it fits, as bitlen was compared to atttypmod */
+ x = BITHIGH;
+ for (bc = 0; sp != s + slen + 1; sp++, bc++)
+ {
+ if (*sp == '1')
+ *r |= x;
+ if (bc == 7)
+ {
+ bc = 0;
+ x = BITHIGH;
+ r++;
+ }
+ else
+ x >>= 1;
+ }
}
- }
- else
- {
- /* Parse the hex representation of the string */
- for (bc = 0; sp != s+slen+1; sp++)
+ else
{
- if (*sp>='0' && *sp<='9')
- x = (bits8) (*sp - '0');
- else if (*sp>='A' && *sp<='F')
- x = (bits8) (*sp - 'A') + 10;
- else if (*sp>='a' && *sp<='f')
- x = (bits8) (*sp - 'a') + 10;
- else
- elog(ERROR,"Cannot parse %c as a hex digit",*sp);
- if (bc) {
- bc = 0;
- *r++ |= x;
- } else {
- bc++;
- *r = x<<4;
- }
+ /* Parse the hex representation of the string */
+ for (bc = 0; sp != s + slen + 1; sp++)
+ {
+ if (*sp >= '0' && *sp <= '9')
+ x = (bits8) (*sp - '0');
+ else if (*sp >= 'A' && *sp <= 'F')
+ x = (bits8) (*sp - 'A') + 10;
+ else if (*sp >= 'a' && *sp <= 'f')
+ x = (bits8) (*sp - 'a') + 10;
+ else
+ elog(ERROR, "Cannot parse %c as a hex digit", *sp);
+ if (bc)
+ {
+ bc = 0;
+ *r++ |= x;
+ }
+ else
+ {
+ bc++;
+ *r = x << 4;
+ }
+ }
}
- }
- if (bitlen > atttypmod) {
- /* Check that this fitted */
- r = (bits8 *) (result + len - 1);
- ipad = VARBITPAD(result);
- /* The bottom ipad bits of the byte pointed to by r need to be zero */
- if (((*r << (BITSPERBYTE-ipad)) & BITMASK) > 0)
- elog(ERROR, "zpbit_in: bit string too large for bit(%d) data type",
- atttypmod);
- }
+ if (bitlen > atttypmod)
+ {
+ /* Check that this fitted */
+ r = (bits8 *) (result + len - 1);
+ ipad = VARBITPAD(result);
+
+ /*
+ * The bottom ipad bits of the byte pointed to by r need to be
+ * zero
+ */
+ if (((*r << (BITSPERBYTE - ipad)) & BITMASK) > 0)
+ elog(ERROR, "zpbit_in: bit string too large for bit(%d) data type",
+ atttypmod);
+ }
- return result;
+ return result;
}
/* zpbit_out -
- * for the time being we print everything as hex strings, as this is likely
- * to be more compact than bit strings, and consequently much more efficient
- * for long strings
+ * for the time being we print everything as hex strings, as this is likely
+ * to be more compact than bit strings, and consequently much more efficient
+ * for long strings
*/
char *
zpbit_out(bits8 *s)
{
- char *result, *r;
- bits8 *sp;
- int i, len, bitlen;
-
- if (s == NULL)
- {
- result = (char *) palloc(2);
- result[0] = '-';
- result[1] = '\0';
- }
- else
- {
- bitlen = VARBITLEN(s);
- len = bitlen/4 + (bitlen%4>0 ? 1 : 0);
- result = (char *) palloc(len + 4);
- sp = VARBITS(s);
- r = result;
- *r++ = 'X';
- *r++ = '\'';
- /* we cheat by knowing that we store full bytes zero padded */
- for (i=0; i<len; i+=2, sp++) {
- *r++ = HEXDIG((*sp)>>4);
- *r++ = HEXDIG((*sp) & 0xF);
- }
- /* Go back one step if we printed a hex number that was not part
- of the bitstring anymore */
- if (i==len+1)
- r--;
- *r++ = '\'';
- *r = '\0';
- }
- return result;
+ char *result,
+ *r;
+ bits8 *sp;
+ int i,
+ len,
+ bitlen;
+
+ if (s == NULL)
+ {
+ result = (char *) palloc(2);
+ result[0] = '-';
+ result[1] = '\0';
+ }
+ else
+ {
+ bitlen = VARBITLEN(s);
+ len = bitlen / 4 + (bitlen % 4 > 0 ? 1 : 0);
+ result = (char *) palloc(len + 4);
+ sp = VARBITS(s);
+ r = result;
+ *r++ = 'X';
+ *r++ = '\'';
+ /* we cheat by knowing that we store full bytes zero padded */
+ for (i = 0; i < len; i += 2, sp++)
+ {
+ *r++ = HEXDIG((*sp) >> 4);
+ *r++ = HEXDIG((*sp) & 0xF);
+ }
+
+ /*
+ * Go back one step if we printed a hex number that was not part
+ * of the bitstring anymore
+ */
+ if (i == len + 1)
+ r--;
+ *r++ = '\'';
+ *r = '\0';
+ }
+ return result;
}
/* zpbits_out -
- * Prints the string a bits
+ * Prints the string a bits
*/
char *
zpbits_out(bits8 *s)
{
- char *result, *r;
- bits8 *sp;
- bits8 x;
- int i, k, len;
-
- if (s == NULL)
- {
- result = (char *) palloc(2);
- result[0] = '-';
- result[1] = '\0';
- }
- else
- {
- len = VARBITLEN(s);
- result = (char *) palloc(len + 4);
- sp = VARBITS(s);
- r = result;
- *r++ = 'B';
- *r++ = '\'';
- for (i=0; i<len-BITSPERBYTE; i+=BITSPERBYTE, sp++) {
- x = *sp;
- for (k=0; k<BITSPERBYTE; k++)
- {
- *r++ = (x & BITHIGH) ? '1' : '0';
- x <<= 1;
- }
- }
- x = *sp;
- for (k=i; k<len; k++)
+ char *result,
+ *r;
+ bits8 *sp;
+ bits8 x;
+ int i,
+ k,
+ len;
+
+ if (s == NULL)
{
- *r++ = (x & BITHIGH) ? '1' : '0';
- x <<= 1;
+ result = (char *) palloc(2);
+ result[0] = '-';
+ result[1] = '\0';
}
- *r++ = '\'';
- *r = '\0';
- }
- return result;
+ else
+ {
+ len = VARBITLEN(s);
+ result = (char *) palloc(len + 4);
+ sp = VARBITS(s);
+ r = result;
+ *r++ = 'B';
+ *r++ = '\'';
+ for (i = 0; i < len - BITSPERBYTE; i += BITSPERBYTE, sp++)
+ {
+ x = *sp;
+ for (k = 0; k < BITSPERBYTE; k++)
+ {
+ *r++ = (x & BITHIGH) ? '1' : '0';
+ x <<= 1;
+ }
+ }
+ x = *sp;
+ for (k = i; k < len; k++)
+ {
+ *r++ = (x & BITHIGH) ? '1' : '0';
+ x <<= 1;
+ }
+ *r++ = '\'';
+ *r = '\0';
+ }
+ return result;
}
@@ -272,118 +298,133 @@ zpbits_out(bits8 *s)
* converts a string to the internal representation of a bitstring.
*/
bits8 *
-varbit_in(char *s, int dummy, int32 atttypmod)
-{
- bits8 *result; /* The resulting bit string */
- char *sp; /* pointer into the character string */
- bits8 *r;
- int len, /* Length of the whole data structure */
- bitlen, /* Number of bits in the bit string */
- slen; /* Length of the input string */
- int bit_not_hex = 0;
- int bc, ipad;
- bits8 x = 0;
-
-
- if (s == NULL)
- return (bits8 *) NULL;
-
- /* Check that the first character is a b or an x */
- if (s[0]=='b' || s[0]=='B')
- bit_not_hex = 1;
- else if (s[0]=='x' || s[0]=='X')
- bit_not_hex = 0;
- else
- elog(ERROR, "zpbit_in: %s is not a valid bitstring",s);
-
- slen = strlen(s) - 1;
- /* Determine bitlength from input string */
- bitlen = slen;
- if (!bit_not_hex)
- bitlen *= 4;
-
- /* Sometimes atttypmod is not supplied. If it is supplied we need to make
- sure that the bitstring fits. Note that the number of infered bits can
- be larger than the number of actual bits needed, but only if we are
- reading a hex string and not by more than 3 bits, as a hex string gives
- and accurate length upto 4 bits */
- if (atttypmod > -1)
- if ((bitlen>atttypmod && bit_not_hex) ||
- (bitlen>atttypmod+3 && !bit_not_hex))
- elog(ERROR, "varbit_in: bit string of size %d cannot be written into varying bits(%d)",
- bitlen,atttypmod);
-
-
- len = VARBITDATALEN(bitlen);
-
- if (len > MaxAttrSize)
- elog(ERROR, "varbit_in: length of bit() must be less than %ld",
- (MaxAttrSize-VARHDRSZ-VARBITHDRSZ)*BITSPERBYTE);
-
- result = (bits8 *) palloc(len);
- /* set to 0 so that *r is always initialised and strin is zero-padded */
- memset(result, 0, len);
- VARSIZE(result) = len;
- VARBITLEN(result) = bitlen;
-
- /* We need to read the bitstring from the end, as we store it least
- significant byte first. s points to the byte before the beginning
- of the bitstring */
- sp = s + 1;
- r = VARBITS(result);
- if (bit_not_hex)
- {
- /* Parse the bit representation of the string */
- x = BITHIGH;
- for (bc = 0; sp != s+slen+1; sp++, bc++)
+varbit_in(char *s, int dummy, int32 atttypmod)
+{
+ bits8 *result; /* The resulting bit string */
+ char *sp; /* pointer into the character string */
+ bits8 *r;
+ int len, /* Length of the whole data structure */
+ bitlen, /* Number of bits in the bit string */
+ slen; /* Length of the input string */
+ int bit_not_hex = 0;
+ int bc,
+ ipad;
+ bits8 x = 0;
+
+
+ if (s == NULL)
+ return (bits8 *) NULL;
+
+ /* Check that the first character is a b or an x */
+ if (s[0] == 'b' || s[0] == 'B')
+ bit_not_hex = 1;
+ else if (s[0] == 'x' || s[0] == 'X')
+ bit_not_hex = 0;
+ else
+ elog(ERROR, "zpbit_in: %s is not a valid bitstring", s);
+
+ slen = strlen(s) - 1;
+ /* Determine bitlength from input string */
+ bitlen = slen;
+ if (!bit_not_hex)
+ bitlen *= 4;
+
+ /*
+ * Sometimes atttypmod is not supplied. If it is supplied we need to
+ * make sure that the bitstring fits. Note that the number of infered
+ * bits can be larger than the number of actual bits needed, but only
+ * if we are reading a hex string and not by more than 3 bits, as a
+ * hex string gives and accurate length upto 4 bits
+ */
+ if (atttypmod > -1)
+ if ((bitlen > atttypmod && bit_not_hex) ||
+ (bitlen > atttypmod + 3 && !bit_not_hex))
+ elog(ERROR, "varbit_in: bit string of size %d cannot be written into varying bits(%d)",
+ bitlen, atttypmod);
+
+
+ len = VARBITDATALEN(bitlen);
+
+ if (len > MaxAttrSize)
+ elog(ERROR, "varbit_in: length of bit() must be less than %ld",
+ (MaxAttrSize - VARHDRSZ - VARBITHDRSZ) * BITSPERBYTE);
+
+ result = (bits8 *) palloc(len);
+ /* set to 0 so that *r is always initialised and strin is zero-padded */
+ memset(result, 0, len);
+ VARSIZE(result) = len;
+ VARBITLEN(result) = bitlen;
+
+ /*
+ * We need to read the bitstring from the end, as we store it least
+ * significant byte first. s points to the byte before the beginning
+ * of the bitstring
+ */
+ sp = s + 1;
+ r = VARBITS(result);
+ if (bit_not_hex)
{
- if (*sp=='1')
- *r |= x;
- if (bc==7) {
- bc = 0;
- x = BITHIGH;
- r++;
- } else
- x >>= 1;
+ /* Parse the bit representation of the string */
+ x = BITHIGH;
+ for (bc = 0; sp != s + slen + 1; sp++, bc++)
+ {
+ if (*sp == '1')
+ *r |= x;
+ if (bc == 7)
+ {
+ bc = 0;
+ x = BITHIGH;
+ r++;
+ }
+ else
+ x >>= 1;
+ }
}
- }
- else
- {
- for (bc = 0; sp != s+slen+1; sp++)
+ else
{
- if (*sp>='0' && *sp<='9')
- x = (bits8) (*sp - '0');
- else if (*sp>='A' && *sp<='F')
- x = (bits8) (*sp - 'A') + 10;
- else if (*sp>='a' && *sp<='f')
- x = (bits8) (*sp - 'a') + 10;
- else
- elog(ERROR,"Cannot parse %c as a hex digit",*sp);
- if (bc) {
- bc = 0;
- *r++ |= x;
- } else {
- bc++;
- *r = x<<4;
- }
+ for (bc = 0; sp != s + slen + 1; sp++)
+ {
+ if (*sp >= '0' && *sp <= '9')
+ x = (bits8) (*sp - '0');
+ else if (*sp >= 'A' && *sp <= 'F')
+ x = (bits8) (*sp - 'A') + 10;
+ else if (*sp >= 'a' && *sp <= 'f')
+ x = (bits8) (*sp - 'a') + 10;
+ else
+ elog(ERROR, "Cannot parse %c as a hex digit", *sp);
+ if (bc)
+ {
+ bc = 0;
+ *r++ |= x;
+ }
+ else
+ {
+ bc++;
+ *r = x << 4;
+ }
+ }
}
- }
- if (bitlen > atttypmod) {
- /* Check that this fitted */
- r = (bits8 *) (result + len - 1);
- ipad = VARBITPAD(result);
- /* The bottom ipad bits of the byte pointed to by r need to be zero */
- if (((*r << (BITSPERBYTE-ipad)) & BITMASK) > 0)
- elog(ERROR, "varbit_in: bit string too large for varying bit(%d) data type",
- atttypmod);
- }
+ if (bitlen > atttypmod)
+ {
+ /* Check that this fitted */
+ r = (bits8 *) (result + len - 1);
+ ipad = VARBITPAD(result);
+
+ /*
+ * The bottom ipad bits of the byte pointed to by r need to be
+ * zero
+ */
+ if (((*r << (BITSPERBYTE - ipad)) & BITMASK) > 0)
+ elog(ERROR, "varbit_in: bit string too large for varying bit(%d) data type",
+ atttypmod);
+ }
- return result;
+ return result;
}
/*
- the zpbit_out routines are fine for varying bits as well
+ the zpbit_out routines are fine for varying bits as well
*/
@@ -391,227 +432,243 @@ varbit_in(char *s, int dummy, int32 atttypmod)
* Comparison operators
*
* We only need one set of comparison operators for bitstrings, as the lengths
- * are stored in the same way for zero-padded and varying bit strings.
+ * are stored in the same way for zero-padded and varying bit strings.
*
- * Note that the standard is not unambiguous about the comparison between
+ * Note that the standard is not unambiguous about the comparison between
* zero-padded bit strings and varying bitstrings. If the same value is written
- * into a zero padded bitstring as into a varying bitstring, but the zero
- * padded bitstring has greater length, it will be bigger.
+ * into a zero padded bitstring as into a varying bitstring, but the zero
+ * padded bitstring has greater length, it will be bigger.
*
* Zeros from the beginning of a bitstring cannot simply be ignored, as they
* may be part of a bit string and may be significant.
*/
bool
-biteq (bits8 *arg1, bits8 *arg2)
+biteq(bits8 *arg1, bits8 *arg2)
{
- int bitlen1,
- bitlen2;
+ int bitlen1,
+ bitlen2;
+
+ if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
+ return (bool) 0;
+ bitlen1 = VARBITLEN(arg1);
+ bitlen2 = VARBITLEN(arg2);
+ if (bitlen1 != bitlen2)
+ return (bool) 0;
- if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
- return (bool) 0;
- bitlen1 = VARBITLEN(arg1);
- bitlen2 = VARBITLEN(arg2);
- if (bitlen1 != bitlen2)
- return (bool) 0;
-
- /* bit strings are always stored in a full number of bytes */
- return memcmp((void *)VARBITS(arg1),(void *)VARBITS(arg2),
- VARBITBYTES(arg1)) == 0;
+ /* bit strings are always stored in a full number of bytes */
+ return memcmp((void *) VARBITS(arg1), (void *) VARBITS(arg2),
+ VARBITBYTES(arg1)) == 0;
}
bool
-bitne (bits8 *arg1, bits8 *arg2)
+bitne(bits8 *arg1, bits8 *arg2)
{
- int bitlen1,
- bitlen2;
+ int bitlen1,
+ bitlen2;
- if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
- return (bool) 0;
- bitlen1 = VARBITLEN(arg1);
- bitlen2 = VARBITLEN(arg2);
- if (bitlen1 != bitlen2)
- return (bool) 1;
-
- /* bit strings are always stored in a full number of bytes */
- return memcmp((void *)VARBITS(arg1),(void *)VARBITS(arg2),
- VARBITBYTES(arg1)) != 0;
+ if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
+ return (bool) 0;
+ bitlen1 = VARBITLEN(arg1);
+ bitlen2 = VARBITLEN(arg2);
+ if (bitlen1 != bitlen2)
+ return (bool) 1;
+
+ /* bit strings are always stored in a full number of bytes */
+ return memcmp((void *) VARBITS(arg1), (void *) VARBITS(arg2),
+ VARBITBYTES(arg1)) != 0;
}
/* bitcmp
- *
+ *
* Compares two bitstrings and returns -1, 0, 1 depending on whether the first
* string is smaller, equal, or bigger than the second. All bits are considered
* and additional zero bits may make one string smaller/larger than the other,
* even if their zero-padded values would be the same.
- * Anything is equal to undefined.
+ * Anything is equal to undefined.
*/
-int
-bitcmp (bits8 *arg1, bits8 *arg2)
-{
- int bitlen1, bytelen1,
- bitlen2, bytelen2;
- int cmp;
-
- if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
- return (bool) 0;
- bytelen1 = VARBITBYTES(arg1);
- bytelen2 = VARBITBYTES(arg2);
-
- cmp = memcmp(VARBITS(arg1),VARBITS(arg2),Min(bytelen1,bytelen2));
- if (cmp==0) {
- bitlen1 = VARBITLEN(arg1);
- bitlen2 = VARBITLEN(arg2);
- if (bitlen1 != bitlen2)
- return bitlen1 < bitlen2 ? -1 : 1;
- }
- return cmp;
+int
+bitcmp(bits8 *arg1, bits8 *arg2)
+{
+ int bitlen1,
+ bytelen1,
+ bitlen2,
+ bytelen2;
+ int cmp;
+
+ if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
+ return (bool) 0;
+ bytelen1 = VARBITBYTES(arg1);
+ bytelen2 = VARBITBYTES(arg2);
+
+ cmp = memcmp(VARBITS(arg1), VARBITS(arg2), Min(bytelen1, bytelen2));
+ if (cmp == 0)
+ {
+ bitlen1 = VARBITLEN(arg1);
+ bitlen2 = VARBITLEN(arg2);
+ if (bitlen1 != bitlen2)
+ return bitlen1 < bitlen2 ? -1 : 1;
+ }
+ return cmp;
}
bool
-bitlt (bits8 *arg1, bits8 *arg2)
+bitlt(bits8 *arg1, bits8 *arg2)
{
- return (bool) (bitcmp(arg1,arg2) == -1);
+ return (bool) (bitcmp(arg1, arg2) == -1);
}
bool
-bitle (bits8 *arg1, bits8 *arg2)
+bitle(bits8 *arg1, bits8 *arg2)
{
- return (bool) (bitcmp(arg1,arg2) <= 0);
+ return (bool) (bitcmp(arg1, arg2) <= 0);
}
bool
-bitge (bits8 *arg1, bits8 *arg2)
+bitge(bits8 *arg1, bits8 *arg2)
{
- return (bool) (bitcmp(arg1,arg2) >= 0);
+ return (bool) (bitcmp(arg1, arg2) >= 0);
}
bool
-bitgt (bits8 *arg1, bits8 *arg2)
+bitgt(bits8 *arg1, bits8 *arg2)
{
- return (bool) (bitcmp(arg1,arg2) == 1);
+ return (bool) (bitcmp(arg1, arg2) == 1);
}
/* bitcat
* Concatenation of bit strings
*/
bits8 *
-bitcat (bits8 *arg1, bits8 *arg2)
-{
- int bitlen1, bitlen2, bytelen, bit1pad, bit2shift;
- bits8 *result;
- bits8 *pr, *pa;
-
- if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
- return NULL;
-
- bitlen1 = VARBITLEN(arg1);
- bitlen2 = VARBITLEN(arg2);
-
- bytelen = VARBITDATALEN(bitlen1+bitlen2);
-
- result = (bits8 *) palloc(bytelen*sizeof(bits8));
- VARSIZE(result) = bytelen;
- VARBITLEN(result) = bitlen1+bitlen2;
- /* Copy the first bitstring in */
- memcpy(VARBITS(result),VARBITS(arg1),VARBITBYTES(arg1));
- /* Copy the second bit string */
- bit1pad = VARBITPAD(arg1);
- if (bit1pad==0)
- {
- memcpy(VARBITS(result)+VARBITBYTES(arg1),VARBITS(arg2),
- VARBITBYTES(arg2));
- }
- else if (bitlen2>0)
- {
- /* We need to shift all the results to fit */
- bit2shift = BITSPERBYTE - bit1pad;
- pa = VARBITS(arg2);
- pr = VARBITS(result)+VARBITBYTES(arg1)-1;
- for ( ; pa < VARBITEND(arg2); pa++) {
- *pr |= ((*pa >> bit2shift) & BITMASK);
- pr++;
- if (pr < VARBITEND(result))
- *pr = (*pa << bit1pad) & BITMASK;
- }
- }
-
- return result;
+bitcat(bits8 *arg1, bits8 *arg2)
+{
+ int bitlen1,
+ bitlen2,
+ bytelen,
+ bit1pad,
+ bit2shift;
+ bits8 *result;
+ bits8 *pr,
+ *pa;
+
+ if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
+ return NULL;
+
+ bitlen1 = VARBITLEN(arg1);
+ bitlen2 = VARBITLEN(arg2);
+
+ bytelen = VARBITDATALEN(bitlen1 + bitlen2);
+
+ result = (bits8 *) palloc(bytelen * sizeof(bits8));
+ VARSIZE(result) = bytelen;
+ VARBITLEN(result) = bitlen1 + bitlen2;
+ /* Copy the first bitstring in */
+ memcpy(VARBITS(result), VARBITS(arg1), VARBITBYTES(arg1));
+ /* Copy the second bit string */
+ bit1pad = VARBITPAD(arg1);
+ if (bit1pad == 0)
+ {
+ memcpy(VARBITS(result) + VARBITBYTES(arg1), VARBITS(arg2),
+ VARBITBYTES(arg2));
+ }
+ else if (bitlen2 > 0)
+ {
+ /* We need to shift all the results to fit */
+ bit2shift = BITSPERBYTE - bit1pad;
+ pa = VARBITS(arg2);
+ pr = VARBITS(result) + VARBITBYTES(arg1) - 1;
+ for (; pa < VARBITEND(arg2); pa++)
+ {
+ *pr |= ((*pa >> bit2shift) & BITMASK);
+ pr++;
+ if (pr < VARBITEND(result))
+ *pr = (*pa << bit1pad) & BITMASK;
+ }
+ }
+
+ return result;
}
/* bitsubstr
- * retrieve a substring from the bit string.
+ * retrieve a substring from the bit string.
* Note, s is 1-based.
* SQL draft 6.10 9)
*/
-bits8 *
-bitsubstr (bits8 *arg, int32 s, int32 l)
-{
- int bitlen,
- rbitlen,
- len,
- ipad = 0,
- ishift,
- i;
- int e, s1, e1;
- bits8 * result;
- bits8 mask, *r, *ps;
-
- if (!PointerIsValid(arg))
- return NULL;
-
- bitlen = VARBITLEN(arg);
- e = s+l;
- s1 = Max(s,1);
- e1 = Min(e,bitlen+1);
- if (s1>bitlen || e1<1)
- {
- /* Need to return a null string */
- len = VARBITDATALEN(0);
- result = (bits8 *) palloc(len);
- VARBITLEN(result) = 0;
- VARSIZE(result) = len;
- }
- else
- {
- /* OK, we've got a true substring starting at position s1-1 and
- ending at position e1-1 */
- rbitlen = e1-s1;
- len = VARBITDATALEN(rbitlen);
- result = (bits8 *) palloc(len);
- VARBITLEN(result) = rbitlen;
- VARSIZE(result) = len;
- len -= VARHDRSZ + VARBITHDRSZ;
- /* Are we copying from a byte boundary? */
- if ((s1-1)%BITSPERBYTE==0)
- {
- /* Yep, we are copying bytes */
- memcpy(VARBITS(result),VARBITS(arg)+(s1-1)/BITSPERBYTE,len);
- }
- else
+bits8 *
+bitsubstr(bits8 *arg, int32 s, int32 l)
+{
+ int bitlen,
+ rbitlen,
+ len,
+ ipad = 0,
+ ishift,
+ i;
+ int e,
+ s1,
+ e1;
+ bits8 *result;
+ bits8 mask,
+ *r,
+ *ps;
+
+ if (!PointerIsValid(arg))
+ return NULL;
+
+ bitlen = VARBITLEN(arg);
+ e = s + l;
+ s1 = Max(s, 1);
+ e1 = Min(e, bitlen + 1);
+ if (s1 > bitlen || e1 < 1)
{
- /* Figure out how much we need to shift the sequence by */
- ishift = (s1-1)%BITSPERBYTE;
- r = VARBITS(result);
- ps = VARBITS(arg) + (s1-1)/BITSPERBYTE;
- for (i=0; i<len; i++)
- {
- *r = (*ps <<ishift) & BITMASK;
- if ((++ps) < VARBITEND(arg))
- *r |= *ps >>(BITSPERBYTE-ishift);
- r++;
- }
+ /* Need to return a null string */
+ len = VARBITDATALEN(0);
+ result = (bits8 *) palloc(len);
+ VARBITLEN(result) = 0;
+ VARSIZE(result) = len;
}
- /* Do we need to pad at the end? */
- ipad = VARBITPAD(result);
- if (ipad > 0)
+ else
{
- mask = BITMASK << ipad;
- *(VARBITS(result) + len - 1) &= mask;
+
+ /*
+ * OK, we've got a true substring starting at position s1-1 and
+ * ending at position e1-1
+ */
+ rbitlen = e1 - s1;
+ len = VARBITDATALEN(rbitlen);
+ result = (bits8 *) palloc(len);
+ VARBITLEN(result) = rbitlen;
+ VARSIZE(result) = len;
+ len -= VARHDRSZ + VARBITHDRSZ;
+ /* Are we copying from a byte boundary? */
+ if ((s1 - 1) % BITSPERBYTE == 0)
+ {
+ /* Yep, we are copying bytes */
+ memcpy(VARBITS(result), VARBITS(arg) + (s1 - 1) / BITSPERBYTE, len);
+ }
+ else
+ {
+ /* Figure out how much we need to shift the sequence by */
+ ishift = (s1 - 1) % BITSPERBYTE;
+ r = VARBITS(result);
+ ps = VARBITS(arg) + (s1 - 1) / BITSPERBYTE;
+ for (i = 0; i < len; i++)
+ {
+ *r = (*ps << ishift) & BITMASK;
+ if ((++ps) < VARBITEND(arg))
+ *r |= *ps >> (BITSPERBYTE - ishift);
+ r++;
+ }
+ }
+ /* Do we need to pad at the end? */
+ ipad = VARBITPAD(result);
+ if (ipad > 0)
+ {
+ mask = BITMASK << ipad;
+ *(VARBITS(result) + len - 1) &= mask;
+ }
}
- }
- return result;
+ return result;
}
/* bitand
@@ -619,32 +676,32 @@ bitsubstr (bits8 *arg, int32 s, int32 l)
* truncated to the shorter bit string
*/
bits8 *
-bitand (bits8 * arg1, bits8 * arg2)
-{
- int len,
- i;
- bits8 *result;
- bits8 *p1,
- *p2,
- *r;
-
- if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
- return (bool) 0;
-
- len = Min(VARSIZE(arg1),VARSIZE(arg2));
- result = (bits8 *) palloc(len);
- VARSIZE(result) = len;
- VARBITLEN(result) = Min(VARBITLEN(arg1),VARBITLEN(arg2));
-
- p1 = (bits8 *) VARBITS(arg1);
- p2 = (bits8 *) VARBITS(arg2);
- r = (bits8 *) VARBITS(result);
- for (i=0; i<Min(VARBITBYTES(arg1),VARBITBYTES(arg2)); i++)
- *r++ = *p1++ & *p2++;
-
- /* Padding is not needed as & of 0 pad is 0 */
-
- return result;
+bitand(bits8 *arg1, bits8 *arg2)
+{
+ int len,
+ i;
+ bits8 *result;
+ bits8 *p1,
+ *p2,
+ *r;
+
+ if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
+ return (bool) 0;
+
+ len = Min(VARSIZE(arg1), VARSIZE(arg2));
+ result = (bits8 *) palloc(len);
+ VARSIZE(result) = len;
+ VARBITLEN(result) = Min(VARBITLEN(arg1), VARBITLEN(arg2));
+
+ p1 = (bits8 *) VARBITS(arg1);
+ p2 = (bits8 *) VARBITS(arg2);
+ r = (bits8 *) VARBITS(result);
+ for (i = 0; i < Min(VARBITBYTES(arg1), VARBITBYTES(arg2)); i++)
+ *r++ = *p1++ & *p2++;
+
+ /* Padding is not needed as & of 0 pad is 0 */
+
+ return result;
}
/* bitor
@@ -652,35 +709,35 @@ bitand (bits8 * arg1, bits8 * arg2)
* truncated to the shorter bit string.
*/
bits8 *
-bitor (bits8 * arg1, bits8 * arg2)
+bitor(bits8 *arg1, bits8 *arg2)
{
- int len,
- i;
- bits8 *result;
- bits8 *p1,
- *p2,
- *r;
- bits8 mask;
+ int len,
+ i;
+ bits8 *result;
+ bits8 *p1,
+ *p2,
+ *r;
+ bits8 mask;
- if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
- return (bool) 0;
+ if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
+ return (bool) 0;
- len = Min(VARSIZE(arg1),VARSIZE(arg2));
- result = (bits8 *) palloc(len);
- VARSIZE(result) = len;
- VARBITLEN(result) = Min(VARBITLEN(arg1),VARBITLEN(arg2));
+ len = Min(VARSIZE(arg1), VARSIZE(arg2));
+ result = (bits8 *) palloc(len);
+ VARSIZE(result) = len;
+ VARBITLEN(result) = Min(VARBITLEN(arg1), VARBITLEN(arg2));
- p1 = (bits8 *) VARBITS(arg1);
- p2 = (bits8 *) VARBITS(arg2);
- r = (bits8 *) VARBITS(result);
- for (i=0; i<Min(VARBITBYTES(arg1),VARBITBYTES(arg2)); i++)
- *r++ = *p1++ | *p2++;
+ p1 = (bits8 *) VARBITS(arg1);
+ p2 = (bits8 *) VARBITS(arg2);
+ r = (bits8 *) VARBITS(result);
+ for (i = 0; i < Min(VARBITBYTES(arg1), VARBITBYTES(arg2)); i++)
+ *r++ = *p1++ | *p2++;
- /* Pad the result */
- mask = BITMASK << VARBITPAD(result);
- *r &= mask;
-
- return result;
+ /* Pad the result */
+ mask = BITMASK << VARBITPAD(result);
+ *r &= mask;
+
+ return result;
}
/* bitxor
@@ -688,250 +745,257 @@ bitor (bits8 * arg1, bits8 * arg2)
* truncated to the shorter bit string.
*/
bits8 *
-bitxor (bits8 * arg1, bits8 * arg2)
-{
- int len,
- i;
- bits8 *result;
- bits8 *p1,
- *p2,
- *r;
- bits8 mask;
-
- if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
- return (bool) 0;
-
- len = Min(VARSIZE(arg1),VARSIZE(arg2));
- result = (bits8 *) palloc(len);
- VARSIZE(result) = len;
- VARBITLEN(result) = Min(VARBITLEN(arg1),VARBITLEN(arg2));
-
- p1 = (bits8 *) VARBITS(arg1);
- p2 = (bits8 *) VARBITS(arg2);
- r = (bits8 *) VARBITS(result);
- for (i=0; i<Min(VARBITBYTES(arg1),VARBITBYTES(arg2)); i++)
- {
- *r++ = *p1++ ^ *p2++;
- }
-
- /* Pad the result */
- mask = BITMASK << VARBITPAD(result);
- *r &= mask;
-
- return result;
+bitxor(bits8 *arg1, bits8 *arg2)
+{
+ int len,
+ i;
+ bits8 *result;
+ bits8 *p1,
+ *p2,
+ *r;
+ bits8 mask;
+
+ if (!PointerIsValid(arg1) || !PointerIsValid(arg2))
+ return (bool) 0;
+
+ len = Min(VARSIZE(arg1), VARSIZE(arg2));
+ result = (bits8 *) palloc(len);
+ VARSIZE(result) = len;
+ VARBITLEN(result) = Min(VARBITLEN(arg1), VARBITLEN(arg2));
+
+ p1 = (bits8 *) VARBITS(arg1);
+ p2 = (bits8 *) VARBITS(arg2);
+ r = (bits8 *) VARBITS(result);
+ for (i = 0; i < Min(VARBITBYTES(arg1), VARBITBYTES(arg2)); i++)
+ *r++ = *p1++ ^ *p2++;
+
+ /* Pad the result */
+ mask = BITMASK << VARBITPAD(result);
+ *r &= mask;
+
+ return result;
}
/* bitnot
* perform a logical NOT on a bit strings.
*/
bits8 *
-bitnot (bits8 * arg)
+bitnot(bits8 *arg)
{
- bits8 *result;
- bits8 *p,
- *r;
- bits8 mask;
+ bits8 *result;
+ bits8 *p,
+ *r;
+ bits8 mask;
+
+ if (!PointerIsValid(arg))
+ return (bool) 0;
- if (!PointerIsValid(arg))
- return (bool) 0;
+ result = (bits8 *) palloc(VARSIZE(arg));
+ VARSIZE(result) = VARSIZE(arg);
+ VARBITLEN(result) = VARBITLEN(arg);
- result = (bits8 *) palloc(VARSIZE(arg));
- VARSIZE(result) = VARSIZE(arg);
- VARBITLEN(result) = VARBITLEN(arg);
+ p = (bits8 *) VARBITS(arg);
+ r = (bits8 *) VARBITS(result);
+ for (; p < VARBITEND(arg); p++, r++)
+ *r = ~*p;
- p = (bits8 *) VARBITS(arg);
- r = (bits8 *) VARBITS(result);
- for ( ; p < VARBITEND(arg); p++, r++)
- *r = ~*p;
+ /* Pad the result */
+ mask = BITMASK << VARBITPAD(result);
+ *r &= mask;
- /* Pad the result */
- mask = BITMASK << VARBITPAD(result);
- *r &= mask;
-
- return result;
+ return result;
}
/* bitshiftleft
* do a left shift (i.e. to the beginning of the string) of the bit string
*/
bits8 *
-bitshiftleft (bits8 * arg, int shft)
-{
- int byte_shift, ishift, len;
- bits8 *result;
- bits8 *p,
- *r;
-
- if (!PointerIsValid(arg))
- return (bool) 0;
-
- /* Negative shift is a shift to the right */
- if (shft < 0)
- return bitshiftright(arg, -shft);
-
- result = (bits8 *) palloc(VARSIZE(arg));
- VARSIZE(result) = VARSIZE(arg);
- VARBITLEN(result) = VARBITLEN(arg);
- r = (bits8 *) VARBITS(result);
-
- byte_shift = shft/BITSPERBYTE;
- ishift = shft % BITSPERBYTE;
- p = ((bits8 *) VARBITS(arg)) + byte_shift;
-
- if (ishift == 0) {
- /* Special case: we can do a memcpy */
- len = VARBITBYTES(arg) - byte_shift;
- memcpy(r, p, len);
- memset(r+len, 0, byte_shift);
- } else {
- for ( ; p < VARBITEND(arg); r++) {
- *r = *p <<ishift;
- if ((++p) < VARBITEND(arg))
- *r |= *p >>(BITSPERBYTE-ishift);
- }
- for ( ; r < VARBITEND(result) ; r++ )
- *r = (bits8) 0;
- }
-
- return result;
+bitshiftleft(bits8 *arg, int shft)
+{
+ int byte_shift,
+ ishift,
+ len;
+ bits8 *result;
+ bits8 *p,
+ *r;
+
+ if (!PointerIsValid(arg))
+ return (bool) 0;
+
+ /* Negative shift is a shift to the right */
+ if (shft < 0)
+ return bitshiftright(arg, -shft);
+
+ result = (bits8 *) palloc(VARSIZE(arg));
+ VARSIZE(result) = VARSIZE(arg);
+ VARBITLEN(result) = VARBITLEN(arg);
+ r = (bits8 *) VARBITS(result);
+
+ byte_shift = shft / BITSPERBYTE;
+ ishift = shft % BITSPERBYTE;
+ p = ((bits8 *) VARBITS(arg)) + byte_shift;
+
+ if (ishift == 0)
+ {
+ /* Special case: we can do a memcpy */
+ len = VARBITBYTES(arg) - byte_shift;
+ memcpy(r, p, len);
+ memset(r + len, 0, byte_shift);
+ }
+ else
+ {
+ for (; p < VARBITEND(arg); r++)
+ {
+ *r = *p << ishift;
+ if ((++p) < VARBITEND(arg))
+ *r |= *p >> (BITSPERBYTE - ishift);
+ }
+ for (; r < VARBITEND(result); r++)
+ *r = (bits8) 0;
+ }
+
+ return result;
}
/* bitshiftright
* do a right shift (i.e. to the beginning of the string) of the bit string
*/
bits8 *
-bitshiftright (bits8 * arg, int shft)
-{
- int byte_shift, ishift, len;
- bits8 *result;
- bits8 *p,
- *r;
-
- if (!PointerIsValid(arg))
- return (bits8 *) 0;
-
- /* Negative shift is a shift to the left */
- if (shft < 0)
- return bitshiftleft(arg, -shft);
-
- result = (bits8 *) palloc(VARSIZE(arg));
- VARSIZE(result) = VARSIZE(arg);
- VARBITLEN(result) = VARBITLEN(arg);
- r = (bits8 *) VARBITS(result);
-
- byte_shift = shft/BITSPERBYTE;
- ishift = shft % BITSPERBYTE;
- p = (bits8 *) VARBITS(arg);
-
- /* Set the first part of the result to 0 */
- memset(r, 0, byte_shift);
-
- if (ishift == 0)
- {
- /* Special case: we can do a memcpy */
- len = VARBITBYTES(arg) - byte_shift;
- memcpy(r+byte_shift, p, len);
- }
- else
- {
- r += byte_shift;
- *r = 0; /* Initialise first byte */
- for ( ; r < VARBITEND(result); p++) {
- *r |= *p >> ishift;
- if ((++r) < VARBITEND(result))
- *r = (*p <<(BITSPERBYTE-ishift)) & BITMASK;
- }
- }
-
- return result;
+bitshiftright(bits8 *arg, int shft)
+{
+ int byte_shift,
+ ishift,
+ len;
+ bits8 *result;
+ bits8 *p,
+ *r;
+
+ if (!PointerIsValid(arg))
+ return (bits8 *) 0;
+
+ /* Negative shift is a shift to the left */
+ if (shft < 0)
+ return bitshiftleft(arg, -shft);
+
+ result = (bits8 *) palloc(VARSIZE(arg));
+ VARSIZE(result) = VARSIZE(arg);
+ VARBITLEN(result) = VARBITLEN(arg);
+ r = (bits8 *) VARBITS(result);
+
+ byte_shift = shft / BITSPERBYTE;
+ ishift = shft % BITSPERBYTE;
+ p = (bits8 *) VARBITS(arg);
+
+ /* Set the first part of the result to 0 */
+ memset(r, 0, byte_shift);
+
+ if (ishift == 0)
+ {
+ /* Special case: we can do a memcpy */
+ len = VARBITBYTES(arg) - byte_shift;
+ memcpy(r + byte_shift, p, len);
+ }
+ else
+ {
+ r += byte_shift;
+ *r = 0; /* Initialise first byte */
+ for (; r < VARBITEND(result); p++)
+ {
+ *r |= *p >> ishift;
+ if ((++r) < VARBITEND(result))
+ *r = (*p << (BITSPERBYTE - ishift)) & BITMASK;
+ }
+ }
+
+ return result;
}
bool
-varbiteq (bits8 *arg1, bits8 *arg2)
+varbiteq(bits8 *arg1, bits8 *arg2)
{
return biteq(arg1, arg2);
}
bool
-varbitne (bits8 *arg1, bits8 *arg2)
+varbitne(bits8 *arg1, bits8 *arg2)
{
return bitne(arg1, arg2);
}
bool
-varbitge (bits8 *arg1, bits8 *arg2)
+varbitge(bits8 *arg1, bits8 *arg2)
{
return bitge(arg1, arg2);
}
bool
-varbitgt (bits8 *arg1, bits8 *arg2)
+varbitgt(bits8 *arg1, bits8 *arg2)
{
return bitgt(arg1, arg2);
}
bool
-varbitle (bits8 *arg1, bits8 *arg2)
+varbitle(bits8 *arg1, bits8 *arg2)
{
return bitle(arg1, arg2);
}
bool
-varbitlt (bits8 *arg1, bits8 *arg2)
+varbitlt(bits8 *arg1, bits8 *arg2)
{
return bitlt(arg1, arg2);
}
int
-varbitcmp (bits8 *arg1, bits8 *arg2)
+varbitcmp(bits8 *arg1, bits8 *arg2)
{
return bitcmp(arg1, arg2);
}
bits8 *
-varbitand (bits8 * arg1, bits8 * arg2)
+varbitand(bits8 *arg1, bits8 *arg2)
{
return bitand(arg1, arg2);
}
bits8 *
-varbitor (bits8 * arg1, bits8 * arg2)
+varbitor(bits8 *arg1, bits8 *arg2)
{
return bitor(arg1, arg2);
}
bits8 *
-varbitxor (bits8 * arg1, bits8 * arg2)
+varbitxor(bits8 *arg1, bits8 *arg2)
{
return bitxor(arg1, arg2);
}
bits8 *
-varbitnot (bits8 * arg)
+varbitnot(bits8 *arg)
{
return bitnot(arg);
}
bits8 *
-varbitshiftright (bits8 * arg, int shft)
+varbitshiftright(bits8 *arg, int shft)
{
return bitshiftright(arg, shft);
}
bits8 *
-varbitshiftleft (bits8 * arg, int shft)
+varbitshiftleft(bits8 *arg, int shft)
{
return bitshiftleft(arg, shft);
}
bits8 *
-varbitcat (bits8 *arg1, bits8 *arg2)
+varbitcat(bits8 *arg1, bits8 *arg2)
{
return bitcat(arg1, arg2);
}
bits8 *
-varbitsubstr (bits8 *arg, int32 s, int32 l)
+varbitsubstr(bits8 *arg, int32 s, int32 l)
{
return bitsubstr(arg, s, l);
}
diff --git a/src/backend/utils/adt/varchar.c b/src/backend/utils/adt/varchar.c
index 8028f0bce82..0837b8b63a1 100644
--- a/src/backend/utils/adt/varchar.c
+++ b/src/backend/utils/adt/varchar.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/varchar.c,v 1.59 2000/03/13 01:54:07 tgl Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/varchar.c,v 1.60 2000/04/12 17:15:52 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -24,6 +24,7 @@
#ifdef CYR_RECODE
char *convertstr(char *, int, int);
+
#endif
diff --git a/src/backend/utils/adt/varlena.c b/src/backend/utils/adt/varlena.c
index b333a0ed4e3..154d8beb270 100644
--- a/src/backend/utils/adt/varlena.c
+++ b/src/backend/utils/adt/varlena.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/adt/varlena.c,v 1.57 2000/03/24 02:41:46 tgl Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/adt/varlena.c,v 1.58 2000/04/12 17:15:52 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -682,9 +682,9 @@ byteaGetBit(bytea *v, int32 n)
len = VARSIZE(v) - VARHDRSZ;
- if (n < 0 || n >= len*8)
+ if (n < 0 || n >= len * 8)
elog(ERROR, "byteaGetBit: index %d out of range [0..%d]",
- n, len*8 - 1);
+ n, len * 8 - 1);
byteNo = n / 8;
bitNo = n % 8;
@@ -757,9 +757,9 @@ byteaSetBit(bytea *v, int32 n, int32 newBit)
len = VARSIZE(v) - VARHDRSZ;
- if (n < 0 || n >= len*8)
+ if (n < 0 || n >= len * 8)
elog(ERROR, "byteaSetBit: index %d out of range [0..%d]",
- n, len*8 - 1);
+ n, len * 8 - 1);
byteNo = n / 8;
bitNo = n % 8;
diff --git a/src/backend/utils/cache/catcache.c b/src/backend/utils/cache/catcache.c
index 297c92b56e7..b593920b1a8 100644
--- a/src/backend/utils/cache/catcache.c
+++ b/src/backend/utils/cache/catcache.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/cache/catcache.c,v 1.62 2000/02/21 03:36:49 tgl Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/cache/catcache.c,v 1.63 2000/04/12 17:15:52 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -30,10 +30,10 @@
static void CatCacheRemoveCTup(CatCache *cache, Dlelem *e);
static Index CatalogCacheComputeHashIndex(struct catcache * cacheInP);
static Index CatalogCacheComputeTupleHashIndex(struct catcache * cacheInOutP,
- Relation relation,
- HeapTuple tuple);
+ Relation relation,
+ HeapTuple tuple);
static void CatalogCacheInitializeCache(struct catcache * cache,
- Relation relation);
+ Relation relation);
static uint32 cc_hashname(NameData *n);
/* ----------------
@@ -57,9 +57,10 @@ static uint32 cc_hashname(NameData *n);
#define CACHE6_elog(a,b,c,d,e,f,g)
#endif
-static CatCache *Caches = NULL; /* head of list of caches */
+static CatCache *Caches = NULL; /* head of list of caches */
GlobalMemory CacheCxt; /* context in which caches are allocated */
+
/* CacheCxt is global because relcache uses it too. */
@@ -90,8 +91,8 @@ GetCCHashFunc(Oid keytype)
{
switch (keytype)
{
- case BOOLOID:
- case CHAROID:
+ case BOOLOID:
+ case CHAROID:
return (CCHashFunc) hashchar;
case NAMEOID:
return (CCHashFunc) cc_hashname;
@@ -118,11 +119,12 @@ GetCCHashFunc(Oid keytype)
static uint32
cc_hashname(NameData *n)
{
+
/*
* We need our own variant of hashname because we want to accept
- * null-terminated C strings as search values for name fields.
- * So, we have to make sure the data is correctly padded before
- * we compute the hash value.
+ * null-terminated C strings as search values for name fields. So, we
+ * have to make sure the data is correctly padded before we compute
+ * the hash value.
*/
NameData my_n;
@@ -242,11 +244,14 @@ CatalogCacheInitializeCache(struct catcache * cache,
if (cache->cc_key[i] > 0)
{
- Oid keytype = tupdesc->attrs[cache->cc_key[i] - 1]->atttypid;
+ Oid keytype = tupdesc->attrs[cache->cc_key[i] - 1]->atttypid;
cache->cc_hashfunc[i] = GetCCHashFunc(keytype);
- /* If GetCCHashFunc liked the type, safe to index into eqproc[] */
+ /*
+ * If GetCCHashFunc liked the type, safe to index into
+ * eqproc[]
+ */
cache->cc_skey[i].sk_procedure = EQPROC(keytype);
fmgr_info(cache->cc_skey[i].sk_procedure,
@@ -314,19 +319,19 @@ CatalogCacheComputeHashIndex(struct catcache * cacheInP)
{
case 4:
hashIndex ^=
- (*cacheInP->cc_hashfunc[3])(cacheInP->cc_skey[3].sk_argument) << 9;
+ (*cacheInP->cc_hashfunc[3]) (cacheInP->cc_skey[3].sk_argument) << 9;
/* FALLTHROUGH */
case 3:
hashIndex ^=
- (*cacheInP->cc_hashfunc[2])(cacheInP->cc_skey[2].sk_argument) << 6;
+ (*cacheInP->cc_hashfunc[2]) (cacheInP->cc_skey[2].sk_argument) << 6;
/* FALLTHROUGH */
case 2:
hashIndex ^=
- (*cacheInP->cc_hashfunc[1])(cacheInP->cc_skey[1].sk_argument) << 3;
+ (*cacheInP->cc_hashfunc[1]) (cacheInP->cc_skey[1].sk_argument) << 3;
/* FALLTHROUGH */
case 1:
hashIndex ^=
- (*cacheInP->cc_hashfunc[0])(cacheInP->cc_skey[0].sk_argument);
+ (*cacheInP->cc_hashfunc[0]) (cacheInP->cc_skey[0].sk_argument);
break;
default:
elog(FATAL, "CCComputeHashIndex: %d cc_nkeys", cacheInP->cc_nkeys);
@@ -612,10 +617,11 @@ ResetSystemCache()
void
SystemCacheRelationFlushed(Oid relId)
{
+
/*
- * XXX Ideally we'd search the caches and just zap entries that actually
- * refer to or come from the indicated relation. For now, we take the
- * brute-force approach: just flush the caches entirely.
+ * XXX Ideally we'd search the caches and just zap entries that
+ * actually refer to or come from the indicated relation. For now, we
+ * take the brute-force approach: just flush the caches entirely.
*/
ResetSystemCache();
}
@@ -688,6 +694,7 @@ InitSysCache(char *relname,
* ----------------
*/
{
+
/*
* We can only do this optimization because the number of hash
* buckets never changes. Without it, we call palloc() too much.
@@ -782,8 +789,8 @@ InitSysCache(char *relname,
*
* This call searches for self-referencing information,
* which causes infinite recursion in the system catalog cache.
- * This code short-circuits the normal index lookup for cache loads
- * in those cases and replaces it with a heap scan.
+ * This code short-circuits the normal index lookup for cache loads
+ * in those cases and replaces it with a heap scan.
*
* cache should already be initailized
* --------------------------------
@@ -791,40 +798,41 @@ InitSysCache(char *relname,
static HeapTuple
SearchSelfReferences(struct catcache * cache)
{
- HeapTuple ntp;
- Relation rel;
+ HeapTuple ntp;
+ Relation rel;
if (cache->id == INDEXRELID)
{
- static Oid indexSelfOid = InvalidOid;
- static HeapTuple indexSelfTuple = NULL;
+ static Oid indexSelfOid = InvalidOid;
+ static HeapTuple indexSelfTuple = NULL;
if (!OidIsValid(indexSelfOid))
{
- ScanKeyData key;
- HeapScanDesc sd;
+ ScanKeyData key;
+ HeapScanDesc sd;
+
/* Find oid of pg_index_indexrelid_index */
rel = heap_openr(RelationRelationName, AccessShareLock);
ScanKeyEntryInitialize(&key, 0, Anum_pg_class_relname,
- F_NAMEEQ, PointerGetDatum(IndexRelidIndex));
+ F_NAMEEQ, PointerGetDatum(IndexRelidIndex));
sd = heap_beginscan(rel, false, SnapshotNow, 1, &key);
ntp = heap_getnext(sd, 0);
if (!HeapTupleIsValid(ntp))
elog(ERROR, "SearchSelfReferences: %s not found in %s",
- IndexRelidIndex, RelationRelationName);
+ IndexRelidIndex, RelationRelationName);
indexSelfOid = ntp->t_data->t_oid;
heap_endscan(sd);
heap_close(rel, AccessShareLock);
}
/* Looking for something other than pg_index_indexrelid_index? */
- if ((Oid)cache->cc_skey[0].sk_argument != indexSelfOid)
- return (HeapTuple)0;
+ if ((Oid) cache->cc_skey[0].sk_argument != indexSelfOid)
+ return (HeapTuple) 0;
/* Do we need to load our private copy of the tuple? */
if (!HeapTupleIsValid(indexSelfTuple))
{
- HeapScanDesc sd;
- MemoryContext oldcxt;
+ HeapScanDesc sd;
+ MemoryContext oldcxt;
if (!CacheCxt)
CacheCxt = CreateGlobalMemory("Cache");
@@ -844,16 +852,16 @@ SearchSelfReferences(struct catcache * cache)
else if (cache->id == OPEROID)
{
/* bootstrapping this requires preloading a range of rows. bjm */
- static HeapTuple operatorSelfTuple[MAX_OIDCMP-MIN_OIDCMP+1];
- Oid lookup_oid = (Oid)cache->cc_skey[0].sk_argument;
+ static HeapTuple operatorSelfTuple[MAX_OIDCMP - MIN_OIDCMP + 1];
+ Oid lookup_oid = (Oid) cache->cc_skey[0].sk_argument;
if (lookup_oid < MIN_OIDCMP || lookup_oid > MAX_OIDCMP)
- return (HeapTuple)0;
+ return (HeapTuple) 0;
- if (!HeapTupleIsValid(operatorSelfTuple[lookup_oid-MIN_OIDCMP]))
+ if (!HeapTupleIsValid(operatorSelfTuple[lookup_oid - MIN_OIDCMP]))
{
- HeapScanDesc sd;
- MemoryContext oldcxt;
+ HeapScanDesc sd;
+ MemoryContext oldcxt;
if (!CacheCxt)
CacheCxt = CreateGlobalMemory("Cache");
@@ -863,15 +871,15 @@ SearchSelfReferences(struct catcache * cache)
if (!HeapTupleIsValid(ntp))
elog(ERROR, "SearchSelfReferences: tuple not found");
oldcxt = MemoryContextSwitchTo((MemoryContext) CacheCxt);
- operatorSelfTuple[lookup_oid-MIN_OIDCMP] = heap_copytuple(ntp);
+ operatorSelfTuple[lookup_oid - MIN_OIDCMP] = heap_copytuple(ntp);
MemoryContextSwitchTo(oldcxt);
heap_endscan(sd);
heap_close(rel, AccessShareLock);
}
- return operatorSelfTuple[lookup_oid-MIN_OIDCMP];
+ return operatorSelfTuple[lookup_oid - MIN_OIDCMP];
}
else
- return (HeapTuple)0;
+ return (HeapTuple) 0;
}
@@ -916,7 +924,7 @@ SearchSysCache(struct catcache * cache,
cache->cc_skey[3].sk_argument = v4;
/*
- * resolve self referencing informtion
+ * resolve self referencing informtion
*/
if ((ntp = SearchSelfReferences(cache)))
return ntp;
@@ -1052,12 +1060,13 @@ SearchSysCache(struct catcache * cache,
}
/* ----------
* Back to Cache context. If we got a tuple copy it
- * into our context. wieck - 10/18/1996
+ * into our context. wieck - 10/18/1996
* And free the tuple that was allocated in the
* transaction's context. tgl - 02/03/2000
* ----------
*/
- if (HeapTupleIsValid(indextp)) {
+ if (HeapTupleIsValid(indextp))
+ {
MemoryContextSwitchTo((MemoryContext) CacheCxt);
ntp = heap_copytuple(indextp);
MemoryContextSwitchTo(oldcxt);
diff --git a/src/backend/utils/cache/fcache.c b/src/backend/utils/cache/fcache.c
index 6660dc0ac40..26f4cbd8d06 100644
--- a/src/backend/utils/cache/fcache.c
+++ b/src/backend/utils/cache/fcache.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/cache/Attic/fcache.c,v 1.29 2000/01/26 05:57:17 momjian Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/cache/Attic/fcache.c,v 1.30 2000/04/12 17:15:53 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -126,6 +126,7 @@ init_fcache(Oid foid,
}
else
{
+
/*
* This is a hack. We assume here that any function returning a
* relation returns it by reference. This needs to be fixed.
@@ -137,7 +138,7 @@ init_fcache(Oid foid,
retval->func_state = (char *) NULL;
retval->setArg = NULL;
retval->hasSetArg = false;
- retval->oneResult = ! procedureStruct->proretset;
+ retval->oneResult = !procedureStruct->proretset;
retval->istrusted = procedureStruct->proistrusted;
/*
@@ -148,7 +149,7 @@ init_fcache(Oid foid,
*/
if ((retval->language == SQLlanguageId) &&
retval->oneResult &&
- ! retval->typbyval)
+ !retval->typbyval)
{
Form_pg_class relationStruct;
HeapTuple relationTuple;
diff --git a/src/backend/utils/cache/inval.c b/src/backend/utils/cache/inval.c
index 17071f8e235..7094ed86f38 100644
--- a/src/backend/utils/cache/inval.c
+++ b/src/backend/utils/cache/inval.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/cache/inval.c,v 1.34 2000/01/31 04:35:52 tgl Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/cache/inval.c,v 1.35 2000/04/12 17:15:53 momjian Exp $
*
* Note - this code is real crufty...
*
@@ -95,11 +95,13 @@ typedef InvalidationMessageData *InvalidationMessage;
* eaten by AtCommit_Cache() in CommitTransaction()
*/
static LocalInvalid InvalidForall = EmptyLocalInvalid;
+
/*
* head of invalidation linked list for the backend itself
* eaten by AtCommit_LocalCache() in CommandCounterIncrement()
*/
static LocalInvalid InvalidLocal = EmptyLocalInvalid;
+
/*
* head of rollback linked list for the backend itself
* eaten by AtAbort_Cache() in AbortTransaction()
@@ -110,7 +112,7 @@ static LocalInvalid RollbackStack = EmptyLocalInvalid;
static InvalidationEntry InvalidationEntryAllocate(uint16 size);
static void LocalInvalidInvalidate(LocalInvalid invalid, void (*function) (), bool freemember);
static LocalInvalid LocalInvalidRegister(LocalInvalid invalid,
- InvalidationEntry entry);
+ InvalidationEntry entry);
static void DiscardInvalidStack(LocalInvalid *invalid);
static void InvalidationMessageRegisterSharedInvalid(InvalidationMessage message);
@@ -161,7 +163,7 @@ LocalInvalidRegister(LocalInvalid invalid,
* --------------------------------
*/
static void
-LocalInvalidInvalidate(LocalInvalid invalid, void (*function) (), bool freemember)
+ LocalInvalidInvalidate(LocalInvalid invalid, void (*function) (), bool freemember)
{
InvalidationEntryData *entryDataP;
@@ -187,12 +189,12 @@ LocalInvalidInvalidate(LocalInvalid invalid, void (*function) (), bool freemembe
static void
DiscardInvalidStack(LocalInvalid *invalid)
{
- LocalInvalid locinv;
+ LocalInvalid locinv;
locinv = *invalid;
*invalid = EmptyLocalInvalid;
if (locinv)
- LocalInvalidInvalidate(locinv, (void (*)()) NULL, true);
+ LocalInvalidInvalidate(locinv, (void (*) ()) NULL, true);
}
/* ----------------------------------------------------------------
@@ -234,7 +236,7 @@ elog(DEBUG, "CacheIdImmediateRegisterSharedInvalid(%d, %d, [%d, %d])", \
*/
static LocalInvalid
CacheIdRegisterSpecifiedLocalInvalid(LocalInvalid invalid,
- Index cacheId, Index hashIndex, ItemPointer pointer)
+ Index cacheId, Index hashIndex, ItemPointer pointer)
{
InvalidationMessage message;
@@ -286,13 +288,13 @@ CacheIdRegisterLocalInvalid(Index cacheId,
* ----------------
*/
InvalidForall = CacheIdRegisterSpecifiedLocalInvalid(InvalidForall,
- cacheId, hashIndex, pointer);
+ cacheId, hashIndex, pointer);
/* ----------------
* Add message to InvalidLocal linked list.
* ----------------
*/
InvalidLocal = CacheIdRegisterSpecifiedLocalInvalid(InvalidLocal,
- cacheId, hashIndex, pointer);
+ cacheId, hashIndex, pointer);
}
/* --------------------------------
@@ -301,7 +303,7 @@ CacheIdRegisterLocalInvalid(Index cacheId,
*/
static void
CacheIdRegisterLocalRollback(Index cacheId, Index hashIndex,
- ItemPointer pointer)
+ ItemPointer pointer)
{
/* ----------------
@@ -315,7 +317,7 @@ CacheIdRegisterLocalRollback(Index cacheId, Index hashIndex,
* ----------------
*/
RollbackStack = CacheIdRegisterSpecifiedLocalInvalid(
- RollbackStack, cacheId, hashIndex, pointer);
+ RollbackStack, cacheId, hashIndex, pointer);
}
/* --------------------------------
@@ -324,7 +326,7 @@ CacheIdRegisterLocalRollback(Index cacheId, Index hashIndex,
*/
static void
CacheIdImmediateRegisterSharedInvalid(Index cacheId, Index hashIndex,
- ItemPointer pointer)
+ ItemPointer pointer)
{
InvalidationMessage message;
@@ -361,7 +363,7 @@ CacheIdImmediateRegisterSharedInvalid(Index cacheId, Index hashIndex,
*/
static LocalInvalid
RelationIdRegisterSpecifiedLocalInvalid(LocalInvalid invalid,
- Oid relationId, Oid objectId)
+ Oid relationId, Oid objectId)
{
InvalidationMessage message;
@@ -415,13 +417,13 @@ RelationIdRegisterLocalInvalid(Oid relationId, Oid objectId)
* ----------------
*/
InvalidForall = RelationIdRegisterSpecifiedLocalInvalid(InvalidForall,
- relationId, objectId);
+ relationId, objectId);
/* ----------------
* Add message to InvalidLocal linked list.
* ----------------
*/
InvalidLocal = RelationIdRegisterSpecifiedLocalInvalid(InvalidLocal,
- relationId, objectId);
+ relationId, objectId);
}
/* --------------------------------
@@ -446,7 +448,7 @@ RelationIdRegisterLocalRollback(Oid relationId, Oid objectId)
* ----------------
*/
RollbackStack = RelationIdRegisterSpecifiedLocalInvalid(
- RollbackStack, relationId, objectId);
+ RollbackStack, relationId, objectId);
}
/* --------------------------------
@@ -643,16 +645,16 @@ InvalidationMessageCacheInvalidate(InvalidationMessage message)
InvalidationMessageCacheInvalidate_DEBUG1;
CacheIdInvalidate(message->any.catalog.cacheId,
- message->any.catalog.hashIndex,
- &message->any.catalog.pointerData);
+ message->any.catalog.hashIndex,
+ &message->any.catalog.pointerData);
break;
case 'r': /* cached relation descriptor */
InvalidationMessageCacheInvalidate_DEBUG2;
CacheIdInvalidate(message->any.relation.relationId,
- message->any.relation.objectId,
- (ItemPointer) NULL);
+ message->any.relation.objectId,
+ (ItemPointer) NULL);
break;
default:
@@ -753,14 +755,14 @@ RegisterInvalid(bool send)
{
DiscardInvalidStack(&RollbackStack);
invalid = InvalidForall;
- InvalidForall = EmptyLocalInvalid; /* clear InvalidForall */
+ InvalidForall = EmptyLocalInvalid; /* clear InvalidForall */
LocalInvalidInvalidate(invalid, InvalidationMessageRegisterSharedInvalid, true);
}
else
{
DiscardInvalidStack(&InvalidForall);
invalid = RollbackStack;
- RollbackStack = EmptyLocalInvalid; /* clear RollbackStack */
+ RollbackStack = EmptyLocalInvalid; /* clear RollbackStack */
LocalInvalidInvalidate(invalid, InvalidationMessageCacheInvalidate, true);
}
@@ -794,14 +796,15 @@ ImmediateLocalInvalidation(bool send)
if (send)
{
invalid = InvalidLocal;
- InvalidLocal = EmptyLocalInvalid; /* clear InvalidLocal */
+ InvalidLocal = EmptyLocalInvalid; /* clear InvalidLocal */
LocalInvalidInvalidate(invalid, InvalidationMessageCacheInvalidate, true);
}
else
{
+
/*
- * This may be used for rollback to a savepoint.
- * Don't clear InvalidForall and RollbackStack here.
+ * This may be used for rollback to a savepoint. Don't clear
+ * InvalidForall and RollbackStack here.
*/
DiscardInvalidStack(&InvalidLocal);
invalid = RollbackStack;
@@ -813,8 +816,8 @@ ImmediateLocalInvalidation(bool send)
/*
* InvokeHeapTupleInvalidation
* Invoke functions for the tuple which register invalidation
- * of catalog/relation cache.
- * Note:
+ * of catalog/relation cache.
+ * Note:
* Assumes object id is valid.
* Assumes tuple is valid.
*/
@@ -831,9 +834,9 @@ elog(DEBUG, "%s(%s, [%d,%d])", \
static void
InvokeHeapTupleInvalidation(Relation relation, HeapTuple tuple,
- void (*CacheIdRegisterFunc)(),
- void (*RelationIdRegisterFunc)(),
- const char *funcname)
+ void (*CacheIdRegisterFunc) (),
+ void (*RelationIdRegisterFunc) (),
+ const char *funcname)
{
/* ----------------
* sanity checks
@@ -857,13 +860,13 @@ InvokeHeapTupleInvalidation(Relation relation, HeapTuple tuple,
*/
InvokeHeapTupleInvalidation_DEBUG1;
- RelationInvalidateCatalogCacheTuple(relation, tuple,
- CacheIdRegisterFunc);
+ RelationInvalidateCatalogCacheTuple(relation, tuple,
+ CacheIdRegisterFunc);
RelationInvalidateRelationCache(relation, tuple,
- RelationIdRegisterFunc);
+ RelationIdRegisterFunc);
}
-
+
/*
* RelationInvalidateHeapTuple
* Causes the given tuple in a relation to be invalidated.
@@ -871,10 +874,10 @@ InvokeHeapTupleInvalidation(Relation relation, HeapTuple tuple,
void
RelationInvalidateHeapTuple(Relation relation, HeapTuple tuple)
{
- InvokeHeapTupleInvalidation(relation, tuple,
- CacheIdRegisterLocalInvalid,
- RelationIdRegisterLocalInvalid,
- "RelationInvalidateHeapTuple");
+ InvokeHeapTupleInvalidation(relation, tuple,
+ CacheIdRegisterLocalInvalid,
+ RelationIdRegisterLocalInvalid,
+ "RelationInvalidateHeapTuple");
}
/*
@@ -886,9 +889,9 @@ void
RelationMark4RollbackHeapTuple(Relation relation, HeapTuple tuple)
{
InvokeHeapTupleInvalidation(relation, tuple,
- CacheIdRegisterLocalRollback,
- RelationIdRegisterLocalRollback,
- "RelationMark4RollbackHeapTuple");
+ CacheIdRegisterLocalRollback,
+ RelationIdRegisterLocalRollback,
+ "RelationMark4RollbackHeapTuple");
}
/*
@@ -900,9 +903,9 @@ void
ImmediateInvalidateSharedHeapTuple(Relation relation, HeapTuple tuple)
{
InvokeHeapTupleInvalidation(relation, tuple,
- CacheIdImmediateRegisterSharedInvalid,
- RelationIdImmediateRegisterSharedInvalid,
- "ImmediateInvalidateSharedHeapTuple");
+ CacheIdImmediateRegisterSharedInvalid,
+ RelationIdImmediateRegisterSharedInvalid,
+ "ImmediateInvalidateSharedHeapTuple");
}
/*
@@ -912,8 +915,8 @@ ImmediateInvalidateSharedHeapTuple(Relation relation, HeapTuple tuple)
* This is needed for smgrunlink()/smgrtruncate().
* Those functions unlink/truncate the base file immediately
* and couldn't be rollbacked in case of abort/crash.
- * So relation cache invalidation must be registerd immediately.
- * Note:
+ * So relation cache invalidation must be registerd immediately.
+ * Note:
* Assumes Relation is valid.
*/
void
@@ -933,10 +936,10 @@ ImmediateSharedRelationCacheInvalidate(Relation relation)
* ----------------
*/
#ifdef INVALIDDEBUG
-elog(DEBUG, "ImmediateSharedRelationCacheInvalidate(%s)", \
- RelationGetPhysicalRelationName(relation));
+ elog(DEBUG, "ImmediateSharedRelationCacheInvalidate(%s)", \
+ RelationGetPhysicalRelationName(relation));
#endif /* defined(INVALIDDEBUG) */
RelationIdImmediateRegisterSharedInvalid(
- RelOid_pg_class, RelationGetRelid(relation));
+ RelOid_pg_class, RelationGetRelid(relation));
}
diff --git a/src/backend/utils/cache/lsyscache.c b/src/backend/utils/cache/lsyscache.c
index 688740e32da..d91f47b7ca2 100644
--- a/src/backend/utils/cache/lsyscache.c
+++ b/src/backend/utils/cache/lsyscache.c
@@ -7,7 +7,7 @@
* Portions Copyright (c) 1994, Regents of the University of California
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/cache/lsyscache.c,v 1.40 2000/02/16 01:00:23 tgl Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/cache/lsyscache.c,v 1.41 2000/04/12 17:15:53 momjian Exp $
*
* NOTES
* Eventually, the index information should go through here, too.
@@ -64,6 +64,7 @@ get_attname(Oid relid, AttrNumber attnum)
if (HeapTupleIsValid(tp))
{
Form_pg_attribute att_tup = (Form_pg_attribute) GETSTRUCT(tp);
+
return pstrdup(NameStr(att_tup->attname));
}
else
@@ -89,6 +90,7 @@ get_attnum(Oid relid, char *attname)
if (HeapTupleIsValid(tp))
{
Form_pg_attribute att_tup = (Form_pg_attribute) GETSTRUCT(tp);
+
return att_tup->attnum;
}
else
@@ -114,6 +116,7 @@ get_atttype(Oid relid, AttrNumber attnum)
if (HeapTupleIsValid(tp))
{
Form_pg_attribute att_tup = (Form_pg_attribute) GETSTRUCT(tp);
+
return att_tup->atttypid;
}
else
@@ -136,6 +139,7 @@ get_attisset(Oid relid, char *attname)
if (HeapTupleIsValid(tp))
{
Form_pg_attribute att_tup = (Form_pg_attribute) GETSTRUCT(tp);
+
return att_tup->attisset;
}
else
@@ -161,6 +165,7 @@ get_atttypmod(Oid relid, AttrNumber attnum)
if (HeapTupleIsValid(tp))
{
Form_pg_attribute att_tup = (Form_pg_attribute) GETSTRUCT(tp);
+
return att_tup->atttypmod;
}
else
@@ -206,8 +211,8 @@ get_attdisbursion(Oid relid, AttrNumber attnum, double min_estimate)
/*
* Special-case boolean columns: the disbursion of a boolean is highly
- * unlikely to be anywhere near 1/numtuples, instead it's probably more
- * like 0.5.
+ * unlikely to be anywhere near 1/numtuples, instead it's probably
+ * more like 0.5.
*
* Are there any other cases we should wire in special estimates for?
*/
@@ -215,8 +220,8 @@ get_attdisbursion(Oid relid, AttrNumber attnum, double min_estimate)
return 0.5;
/*
- * Disbursion is either 0 (no data available) or -1 (disbursion
- * is 1/numtuples). Either way, we need the relation size.
+ * Disbursion is either 0 (no data available) or -1 (disbursion is
+ * 1/numtuples). Either way, we need the relation size.
*/
atp = SearchSysCacheTuple(RELOID,
@@ -246,10 +251,9 @@ get_attdisbursion(Oid relid, AttrNumber attnum, double min_estimate)
return 1.0 / (double) ntuples;
/*
- * VACUUM ANALYZE has not been run for this table.
- * Produce an estimate = 1/numtuples. This may produce
- * unreasonably small estimates for large tables, so limit
- * the estimate to no less than min_estimate.
+ * VACUUM ANALYZE has not been run for this table. Produce an estimate
+ * = 1/numtuples. This may produce unreasonably small estimates for
+ * large tables, so limit the estimate to no less than min_estimate.
*/
disbursion = 1.0 / (double) ntuples;
if (disbursion < min_estimate)
@@ -283,6 +287,7 @@ get_opcode(Oid opno)
if (HeapTupleIsValid(tp))
{
Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
+
return optup->oprcode;
}
else
@@ -306,6 +311,7 @@ get_opname(Oid opno)
if (HeapTupleIsValid(tp))
{
Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
+
return pstrdup(NameStr(optup->oprname));
}
else
@@ -401,6 +407,7 @@ get_commutator(Oid opno)
if (HeapTupleIsValid(tp))
{
Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
+
return optup->oprcom;
}
else
@@ -424,6 +431,7 @@ get_negator(Oid opno)
if (HeapTupleIsValid(tp))
{
Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
+
return optup->oprnegate;
}
else
@@ -447,6 +455,7 @@ get_oprrest(Oid opno)
if (HeapTupleIsValid(tp))
{
Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
+
return optup->oprrest;
}
else
@@ -470,6 +479,7 @@ get_oprjoin(Oid opno)
if (HeapTupleIsValid(tp))
{
Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
+
return optup->oprjoin;
}
else
@@ -520,6 +530,7 @@ get_relnatts(Oid relid)
if (HeapTupleIsValid(tp))
{
Form_pg_class reltup = (Form_pg_class) GETSTRUCT(tp);
+
return reltup->relnatts;
}
else
@@ -543,6 +554,7 @@ get_rel_name(Oid relid)
if (HeapTupleIsValid(tp))
{
Form_pg_class reltup = (Form_pg_class) GETSTRUCT(tp);
+
return pstrdup(NameStr(reltup->relname));
}
else
@@ -568,6 +580,7 @@ get_typlen(Oid typid)
if (HeapTupleIsValid(tp))
{
Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
+
return typtup->typlen;
}
else
@@ -592,6 +605,7 @@ get_typbyval(Oid typid)
if (HeapTupleIsValid(tp))
{
Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
+
return (bool) typtup->typbyval;
}
else
@@ -610,6 +624,7 @@ get_typalign(Oid typid)
if (HeapTupleIsValid(tp))
{
Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
+
return typtup->typalign;
}
else
@@ -649,11 +664,12 @@ get_typdefault(Oid typid)
type = (Form_pg_type) GETSTRUCT(typeTuple);
/*
- * First, see if there is a non-null typdefault field (usually there isn't)
+ * First, see if there is a non-null typdefault field (usually there
+ * isn't)
*/
typDefault = (struct varlena *) SysCacheGetAttr(TYPEOID,
typeTuple,
- Anum_pg_type_typdefault,
+ Anum_pg_type_typdefault,
&isNull);
if (isNull)
@@ -743,6 +759,7 @@ get_typtype(Oid typid)
if (HeapTupleIsValid(tp))
{
Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
+
return typtup->typtype;
}
else
diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c
index 97ec7d300d1..41fcdf1d273 100644
--- a/src/backend/utils/cache/relcache.c
+++ b/src/backend/utils/cache/relcache.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/cache/relcache.c,v 1.94 2000/03/31 19:39:22 tgl Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/cache/relcache.c,v 1.95 2000/04/12 17:15:54 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -80,8 +80,8 @@ static FormData_pg_attribute Desc_pg_log[Natts_pg_log] = {Schema_pg_log};
* thus there are two hash tables for referencing them.
* ----------------
*/
-static HTAB *RelationNameCache;
-static HTAB *RelationIdCache;
+static HTAB *RelationNameCache;
+static HTAB *RelationIdCache;
/*
* newlyCreatedRelns -
@@ -204,20 +204,20 @@ do { \
static void RelationClearRelation(Relation relation, bool rebuildIt);
static void RelationFlushRelation(Relation *relationPtr,
- int skipLocalRelations);
+ int skipLocalRelations);
static Relation RelationNameCacheGetRelation(const char *relationName);
static void RelationCacheAbortWalker(Relation *relationPtr, int dummy);
static void init_irels(void);
static void write_irels(void);
static void formrdesc(char *relationName, u_int natts,
- FormData_pg_attribute *att);
+ FormData_pg_attribute *att);
static HeapTuple ScanPgRelation(RelationBuildDescInfo buildinfo);
static HeapTuple scan_pg_rel_seq(RelationBuildDescInfo buildinfo);
static HeapTuple scan_pg_rel_ind(RelationBuildDescInfo buildinfo);
static Relation AllocateRelationDesc(Relation relation, u_int natts,
- Form_pg_class relp);
+ Form_pg_class relp);
static void RelationBuildTupleDesc(RelationBuildDescInfo buildinfo,
Relation relation, u_int natts);
static void build_tupdesc_seq(RelationBuildDescInfo buildinfo,
@@ -225,12 +225,13 @@ static void build_tupdesc_seq(RelationBuildDescInfo buildinfo,
static void build_tupdesc_ind(RelationBuildDescInfo buildinfo,
Relation relation, u_int natts);
static Relation RelationBuildDesc(RelationBuildDescInfo buildinfo,
- Relation oldrelation);
+ Relation oldrelation);
static void IndexedAccessMethodInitialize(Relation relation);
static void AttrDefaultFetch(Relation relation);
static void RelCheckFetch(Relation relation);
-static bool criticalRelcacheBuild = false;
+static bool criticalRelcacheBuild = false;
+
/* ----------------------------------------------------------------
* RelationIdGetRelation() and RelationNameGetRelation()
* support functions
@@ -350,7 +351,7 @@ scan_pg_rel_ind(RelationBuildDescInfo buildinfo)
default:
elog(ERROR, "ScanPgRelation: bad buildinfo");
- return_tuple = NULL; /* keep compiler quiet */
+ return_tuple = NULL;/* keep compiler quiet */
}
heap_close(pg_class_desc, AccessShareLock);
@@ -483,7 +484,7 @@ build_tupdesc_seq(RelationBuildDescInfo buildinfo,
int need;
TupleConstr *constr = (TupleConstr *) palloc(sizeof(TupleConstr));
AttrDefault *attrdef = NULL;
- int ndef = 0;
+ int ndef = 0;
constr->has_not_null = false;
/* ----------------
@@ -531,7 +532,7 @@ build_tupdesc_seq(RelationBuildDescInfo buildinfo,
if (attrdef == NULL)
{
attrdef = (AttrDefault *) palloc(relation->rd_rel->relnatts *
- sizeof(AttrDefault));
+ sizeof(AttrDefault));
MemSet(attrdef, 0,
relation->rd_rel->relnatts * sizeof(AttrDefault));
}
@@ -569,9 +570,11 @@ build_tupdesc_ind(RelationBuildDescInfo buildinfo,
AttrDefault *attrdef = NULL;
int ndef = 0;
int i;
+
#ifdef _DROP_COLUMN_HACK__
- bool columnDropped;
-#endif /* _DROP_COLUMN_HACK__ */
+ bool columnDropped;
+
+#endif /* _DROP_COLUMN_HACK__ */
constr->has_not_null = false;
@@ -581,7 +584,7 @@ build_tupdesc_ind(RelationBuildDescInfo buildinfo,
{
#ifdef _DROP_COLUMN_HACK__
columnDropped = false;
-#endif /* _DROP_COLUMN_HACK__ */
+#endif /* _DROP_COLUMN_HACK__ */
atttup = (HeapTuple) AttributeRelidNumIndexScan(attrel,
RelationGetRelid(relation), i);
@@ -589,15 +592,15 @@ build_tupdesc_ind(RelationBuildDescInfo buildinfo,
#ifdef _DROP_COLUMN_HACK__
{
atttup = (HeapTuple) AttributeRelidNumIndexScan(attrel,
- RelationGetRelid(relation), DROPPED_COLUMN_INDEX(i));
+ RelationGetRelid(relation), DROPPED_COLUMN_INDEX(i));
if (!HeapTupleIsValid(atttup))
-#endif /* _DROP_COLUMN_HACK__ */
- elog(ERROR, "cannot find attribute %d of relation %s", i,
- RelationGetRelationName(relation));
+#endif /* _DROP_COLUMN_HACK__ */
+ elog(ERROR, "cannot find attribute %d of relation %s", i,
+ RelationGetRelationName(relation));
#ifdef _DROP_COLUMN_HACK__
columnDropped = true;
}
-#endif /* _DROP_COLUMN_HACK__ */
+#endif /* _DROP_COLUMN_HACK__ */
attp = (Form_pg_attribute) GETSTRUCT(atttup);
relation->rd_att->attrs[i - 1] =
@@ -610,7 +613,7 @@ build_tupdesc_ind(RelationBuildDescInfo buildinfo,
#ifdef _DROP_COLUMN_HACK__
if (columnDropped)
continue;
-#endif /* _DROP_COLUMN_HACK__ */
+#endif /* _DROP_COLUMN_HACK__ */
/* Update if this attribute have a constraint */
if (attp->attnotnull)
constr->has_not_null = true;
@@ -758,7 +761,7 @@ RelationBuildRuleLock(Relation relation)
static void
FreeRuleLock(RuleLock *rlock)
{
- int i;
+ int i;
if (rlock == NULL)
return;
@@ -787,8 +790,8 @@ FreeRuleLock(RuleLock *rlock)
static bool
equalRuleLocks(RuleLock *rlock1, RuleLock *rlock2)
{
- int i,
- j;
+ int i,
+ j;
if (rlock1 != NULL)
{
@@ -821,9 +824,9 @@ equalRuleLocks(RuleLock *rlock1, RuleLock *rlock2)
return false;
if (rule1->isInstead != rule2->isInstead)
return false;
- if (! equal(rule1->qual, rule2->qual))
+ if (!equal(rule1->qual, rule2->qual))
return false;
- if (! equal(rule1->actions, rule2->actions))
+ if (!equal(rule1->actions, rule2->actions))
return false;
}
}
@@ -852,7 +855,7 @@ equalRuleLocks(RuleLock *rlock1, RuleLock *rlock2)
* Form_pg_am rd_am; AM tuple
* Form_pg_class rd_rel; RELATION tuple
* Oid rd_id; relation's object id
- * LockInfoData rd_lockInfo; lock manager's info
+ * LockInfoData rd_lockInfo; lock manager's info
* TupleDesc rd_att; tuple descriptor
*
* Note: rd_ismem (rel is in-memory only) is currently unused
@@ -1309,7 +1312,7 @@ RelationNameGetRelation(const char *relationName)
* ----------------
*/
buildinfo.infotype = INFO_RELNAME;
- buildinfo.i.info_name = (char *)relationName;
+ buildinfo.i.info_name = (char *) relationName;
rd = RelationBuildDesc(buildinfo, NULL);
return rd;
@@ -1352,11 +1355,11 @@ RelationClearRelation(Relation relation, bool rebuildIt)
MemoryContext oldcxt;
/*
- * Make sure smgr and lower levels close the relation's files,
- * if they weren't closed already. We do this unconditionally;
- * if the relation is not deleted, the next smgr access should
- * reopen the files automatically. This ensures that the low-level
- * file access state is updated after, say, a vacuum truncation.
+ * Make sure smgr and lower levels close the relation's files, if they
+ * weren't closed already. We do this unconditionally; if the
+ * relation is not deleted, the next smgr access should reopen the
+ * files automatically. This ensures that the low-level file access
+ * state is updated after, say, a vacuum truncation.
*
* NOTE: this call is a no-op if the relation's smgr file is already
* closed or unlinked.
@@ -1364,15 +1367,16 @@ RelationClearRelation(Relation relation, bool rebuildIt)
smgrclose(DEFAULT_SMGR, relation);
/*
- * Never, never ever blow away a nailed-in system relation,
- * because we'd be unable to recover.
+ * Never, never ever blow away a nailed-in system relation, because
+ * we'd be unable to recover.
*/
if (relation->rd_isnailed)
return;
oldcxt = MemoryContextSwitchTo((MemoryContext) CacheCxt);
- /* Remove relation from hash tables
+ /*
+ * Remove relation from hash tables
*
* Note: we might be reinserting it momentarily, but we must not have it
* visible in the hash tables until it's valid again, so don't try to
@@ -1384,12 +1388,12 @@ RelationClearRelation(Relation relation, bool rebuildIt)
SystemCacheRelationFlushed(RelationGetRelid(relation));
/*
- * Free all the subsidiary data structures of the relcache entry.
- * We cannot free rd_att if we are trying to rebuild the entry,
- * however, because pointers to it may be cached in various places.
- * The trigger manager might also have pointers into the trigdesc,
- * and the rule manager might have pointers into the rewrite rules.
- * So to begin with, we can only get rid of these fields:
+ * Free all the subsidiary data structures of the relcache entry. We
+ * cannot free rd_att if we are trying to rebuild the entry, however,
+ * because pointers to it may be cached in various places. The trigger
+ * manager might also have pointers into the trigdesc, and the rule
+ * manager might have pointers into the rewrite rules. So to begin
+ * with, we can only get rid of these fields:
*/
if (relation->rd_am)
pfree(relation->rd_am);
@@ -1401,12 +1405,12 @@ RelationClearRelation(Relation relation, bool rebuildIt)
pfree(relation->rd_support);
/*
- * If we're really done with the relcache entry, blow it away.
- * But if someone is still using it, reconstruct the whole deal
- * without moving the physical RelationData record (so that the
- * someone's pointer is still valid).
+ * If we're really done with the relcache entry, blow it away. But if
+ * someone is still using it, reconstruct the whole deal without
+ * moving the physical RelationData record (so that the someone's
+ * pointer is still valid).
*/
- if (! rebuildIt)
+ if (!rebuildIt)
{
/* ok to zap remaining substructure */
FreeTupleDesc(relation->rd_att);
@@ -1416,20 +1420,21 @@ RelationClearRelation(Relation relation, bool rebuildIt)
}
else
{
+
/*
* When rebuilding an open relcache entry, must preserve ref count
* and myxactonly flag. Also attempt to preserve the tupledesc,
- * rewrite rules, and trigger substructures in place.
- * Furthermore we save/restore rd_nblocks (in case it is a local
- * relation) *and* call RelationGetNumberOfBlocks (in case it isn't).
+ * rewrite rules, and trigger substructures in place. Furthermore
+ * we save/restore rd_nblocks (in case it is a local relation)
+ * *and* call RelationGetNumberOfBlocks (in case it isn't).
*/
- uint16 old_refcnt = relation->rd_refcnt;
- bool old_myxactonly = relation->rd_myxactonly;
- TupleDesc old_att = relation->rd_att;
- RuleLock *old_rules = relation->rd_rules;
- TriggerDesc *old_trigdesc = relation->trigdesc;
- int old_nblocks = relation->rd_nblocks;
- bool relDescChanged = false;
+ uint16 old_refcnt = relation->rd_refcnt;
+ bool old_myxactonly = relation->rd_myxactonly;
+ TupleDesc old_att = relation->rd_att;
+ RuleLock *old_rules = relation->rd_rules;
+ TriggerDesc *old_trigdesc = relation->trigdesc;
+ int old_nblocks = relation->rd_nblocks;
+ bool relDescChanged = false;
RelationBuildDescInfo buildinfo;
buildinfo.infotype = INFO_RELID;
@@ -1478,12 +1483,14 @@ RelationClearRelation(Relation relation, bool rebuildIt)
relDescChanged = true;
}
relation->rd_nblocks = old_nblocks;
- /* this is kind of expensive, but I think we must do it in case
+
+ /*
+ * this is kind of expensive, but I think we must do it in case
* relation has been truncated...
*/
relation->rd_nblocks = RelationGetNumberOfBlocks(relation);
- if (relDescChanged && ! RelationHasReferenceCountZero(relation))
+ if (relDescChanged && !RelationHasReferenceCountZero(relation))
elog(ERROR, "RelationClearRelation: relation %u modified while in use",
buildinfo.i.info_id);
}
@@ -1514,6 +1521,7 @@ RelationFlushRelation(Relation *relationPtr,
{
if (skipLocalRelations)
return; /* don't touch local rels if so commanded */
+
/*
* Local rels should always be rebuilt, not flushed; the relcache
* entry must live until RelationPurgeLocalRelation().
@@ -1522,10 +1530,11 @@ RelationFlushRelation(Relation *relationPtr,
}
else
{
+
/*
* Nonlocal rels can be dropped from the relcache if not open.
*/
- rebuildIt = ! RelationHasReferenceCountZero(relation);
+ rebuildIt = !RelationHasReferenceCountZero(relation);
}
RelationClearRelation(relation, rebuildIt);
@@ -1633,6 +1642,7 @@ RelationFlushIndexes(Relation *r,
void
RelationIdInvalidateRelationCacheByAccessMethodId(Oid accessMethodId)
{
+
/*
* 25 aug 1992: mao commented out the ht walk below. it should be
* doing the right thing, in theory, but flushing reldescs for index
@@ -1641,13 +1651,14 @@ RelationIdInvalidateRelationCacheByAccessMethodId(Oid accessMethodId)
* so i'm turning it off for now. after the release is cut, i'll fix
* this up.
*
- * 20 nov 1999: this code has still never done anything, so I'm
- * cutting the routine out of the system entirely. tgl
+ * 20 nov 1999: this code has still never done anything, so I'm cutting
+ * the routine out of the system entirely. tgl
*/
HashTableWalk(RelationNameCache, (HashtFunc) RelationFlushIndexes,
accessMethodId);
}
+
#endif
/*
@@ -1756,7 +1767,7 @@ RelationPurgeLocalRelation(bool xactCommitted)
Assert(reln != NULL && reln->rd_myxactonly);
- reln->rd_myxactonly = false; /* mark it not on list anymore */
+ reln->rd_myxactonly = false; /* mark it not on list anymore */
newlyCreatedRelns = lnext(newlyCreatedRelns);
pfree(l);
@@ -1862,8 +1873,8 @@ AttrDefaultFetch(Relation relation)
HeapTupleData tuple;
HeapTuple htup;
Form_pg_attrdef adform;
- IndexScanDesc sd = (IndexScanDesc) NULL;
- HeapScanDesc adscan = (HeapScanDesc) NULL;
+ IndexScanDesc sd = (IndexScanDesc) NULL;
+ HeapScanDesc adscan = (HeapScanDesc) NULL;
RetrieveIndexResult indexRes;
struct varlena *val;
bool isnull;
@@ -1885,7 +1896,7 @@ AttrDefaultFetch(Relation relation)
sd = index_beginscan(irel, false, 1, &skey);
}
else
- adscan = heap_beginscan(adrel, false, SnapshotNow, 1, &skey);
+ adscan = heap_beginscan(adrel, false, SnapshotNow, 1, &skey);
tuple.t_datamcxt = NULL;
tuple.t_data = NULL;
@@ -1920,7 +1931,7 @@ AttrDefaultFetch(Relation relation)
continue;
if (attrdef[i].adbin != NULL)
elog(NOTICE, "AttrDefaultFetch: second record found for attr %s in rel %s",
- NameStr(relation->rd_att->attrs[adform->adnum - 1]->attname),
+ NameStr(relation->rd_att->attrs[adform->adnum - 1]->attname),
RelationGetRelationName(relation));
val = (struct varlena *) fastgetattr(htup,
@@ -1928,7 +1939,7 @@ AttrDefaultFetch(Relation relation)
adrel->rd_att, &isnull);
if (isnull)
elog(NOTICE, "AttrDefaultFetch: adbin IS NULL for attr %s in rel %s",
- NameStr(relation->rd_att->attrs[adform->adnum - 1]->attname),
+ NameStr(relation->rd_att->attrs[adform->adnum - 1]->attname),
RelationGetRelationName(relation));
attrdef[i].adbin = textout(val);
break;
@@ -1962,12 +1973,12 @@ RelCheckFetch(Relation relation)
ConstrCheck *check = relation->rd_att->constr->check;
int ncheck = relation->rd_att->constr->num_check;
Relation rcrel;
- Relation irel = (Relation)NULL;
+ Relation irel = (Relation) NULL;
ScanKeyData skey;
HeapTupleData tuple;
HeapTuple htup;
- IndexScanDesc sd = (IndexScanDesc)NULL;
- HeapScanDesc rcscan = (HeapScanDesc)NULL;
+ IndexScanDesc sd = (IndexScanDesc) NULL;
+ HeapScanDesc rcscan = (HeapScanDesc) NULL;
RetrieveIndexResult indexRes;
Name rcname;
struct varlena *val;
@@ -2271,9 +2282,9 @@ write_irels(void)
char finalfilename[MAXPGPATH];
/*
- * We must write a temporary file and rename it into place. Otherwise,
- * another backend starting at about the same time might crash trying to
- * read the partially-complete file.
+ * We must write a temporary file and rename it into place. Otherwise,
+ * another backend starting at about the same time might crash trying
+ * to read the partially-complete file.
*/
snprintf(tempfilename, sizeof(tempfilename), "%s%c%s.%d",
DatabasePath, SEP_CHAR, RELCACHE_INIT_FILENAME, MyProcPid);
@@ -2292,19 +2303,18 @@ write_irels(void)
/*
* Build relation descriptors for the critical system indexes without
- * resort to the descriptor cache. In order to do this, we set
- * ProcessingMode to Bootstrap. The effect of this is to disable indexed
- * relation searches -- a necessary step, since we're trying to
- * instantiate the index relation descriptors here. Once we have the
- * descriptors, nail them into cache so we never lose them.
+ * resort to the descriptor cache. In order to do this, we set
+ * ProcessingMode to Bootstrap. The effect of this is to disable
+ * indexed relation searches -- a necessary step, since we're trying
+ * to instantiate the index relation descriptors here. Once we have
+ * the descriptors, nail them into cache so we never lose them.
*/
- /* Removed the following ProcessingMode change -- inoue
- * At this point
- * 1) Catalog Cache isn't initialized
- * 2) Relation Cache for the following critical indexes aren't built
- oldmode = GetProcessingMode();
- SetProcessingMode(BootstrapProcessing);
+ /*
+ * Removed the following ProcessingMode change -- inoue At this point
+ * 1) Catalog Cache isn't initialized 2) Relation Cache for the
+ * following critical indexes aren't built oldmode =
+ * GetProcessingMode(); SetProcessingMode(BootstrapProcessing);
*/
bi.infotype = INFO_RELNAME;
@@ -2321,8 +2331,10 @@ write_irels(void)
irel[2]->rd_isnailed = true;
criticalRelcacheBuild = true;
- /* Removed the following ProcessingMode -- inoue
- SetProcessingMode(oldmode);
+
+ /*
+ * Removed the following ProcessingMode -- inoue
+ * SetProcessingMode(oldmode);
*/
/*
@@ -2411,9 +2423,9 @@ write_irels(void)
FileClose(fd);
- /*
- * And rename the temp file to its final name, deleting any previously-
- * existing init file.
- */
- rename(tempfilename, finalfilename);
+ /*
+ * And rename the temp file to its final name, deleting any
+ * previously- existing init file.
+ */
+ rename(tempfilename, finalfilename);
}
diff --git a/src/backend/utils/cache/syscache.c b/src/backend/utils/cache/syscache.c
index 087002ab76f..5379873350b 100644
--- a/src/backend/utils/cache/syscache.c
+++ b/src/backend/utils/cache/syscache.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/cache/syscache.c,v 1.49 2000/02/18 09:28:56 inoue Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/cache/syscache.c,v 1.50 2000/04/12 17:15:54 momjian Exp $
*
* NOTES
* These routines allow the parser/planner/executor to perform
@@ -57,28 +57,28 @@ typedef HeapTuple (*ScanFunc) ();
the list sorted alphabetically and adjust the cache numbers
accordingly.
- Add your entry to the cacheinfo[] array below. All cache lists are
+ Add your entry to the cacheinfo[] array below. All cache lists are
alphabetical, so add it in the proper place. Specify the relation
- name, number of arguments, argument names, size of tuple, index lookup
+ name, number of arguments, argument names, size of tuple, index lookup
function, and index name.
- In include/catalog/indexing.h, add a define for the number of indexes
- in the relation, add a define for the index name, add an extern
- array to hold the index names, define the index lookup function
- prototype, and use DECLARE_UNIQUE_INDEX to define the index. Cache
- lookups return only one row, so the index should be unique.
+ In include/catalog/indexing.h, add a define for the number of indexes
+ in the relation, add a define for the index name, add an extern
+ array to hold the index names, define the index lookup function
+ prototype, and use DECLARE_UNIQUE_INDEX to define the index. Cache
+ lookups return only one row, so the index should be unique.
- In backend/catalog/indexing.c, initialize the relation array with
- the index names for the relation, fixed size of relation (or marking
- first non-fixed length field), and create the index lookup function.
- Pick one that takes similar arguments and use that one, but keep the
- function names in the same order as the cache list for clarity.
+ In backend/catalog/indexing.c, initialize the relation array with
+ the index names for the relation, fixed size of relation (or marking
+ first non-fixed length field), and create the index lookup function.
+ Pick one that takes similar arguments and use that one, but keep the
+ function names in the same order as the cache list for clarity.
- Finally, any place your relation gets heap_insert() or
+ Finally, any place your relation gets heap_insert() or
heap_update calls, include code to do a CatalogIndexInsert() to update
the system indexes. The heap_* calls do not update indexes.
- bjm 1999/11/22
+ bjm 1999/11/22
---------------------------------------------------------------------------
*/
@@ -394,10 +394,12 @@ static struct cachedesc cacheinfo[] = {
TypeOidIndexScan}
};
-static struct catcache *SysCache[lengthof(cacheinfo)];
+static struct catcache *SysCache[
+ lengthof(cacheinfo)];
static int32 SysCacheSize = lengthof(cacheinfo);
-static bool CacheInitialized = false;
-extern bool IsCacheInitialized(void)
+static bool CacheInitialized = false;
+extern bool
+IsCacheInitialized(void)
{
return CacheInitialized;
}
@@ -520,7 +522,7 @@ SearchSysCacheTuple(int cacheId,/* cache selection code */
/* temp table name remapping */
if (cacheId == RELNAME)
{
- char *nontemp_relname;
+ char *nontemp_relname;
if ((nontemp_relname =
get_temp_rel_by_username(DatumGetPointer(key1))) != NULL)
@@ -549,7 +551,7 @@ SearchSysCacheTuple(int cacheId,/* cache selection code */
* SearchSysCacheTupleCopy(), extract a specific attribute.
*
* This is equivalent to using heap_getattr() on a tuple fetched
- * from a non-cached relation. Usually, this is only used for attributes
+ * from a non-cached relation. Usually, this is only used for attributes
* that could be NULL or variable length; the fixed-size attributes in
* a system table are accessed just by mapping the tuple onto the C struct
* declarations from include/catalog/.
@@ -563,17 +565,18 @@ SysCacheGetAttr(int cacheId, HeapTuple tup,
AttrNumber attributeNumber,
bool *isnull)
{
+
/*
- * We just need to get the TupleDesc out of the cache entry,
- * and then we can apply heap_getattr(). We expect that the cache
- * control data is currently valid --- if the caller just fetched
- * the tuple, then it should be.
+ * We just need to get the TupleDesc out of the cache entry, and then
+ * we can apply heap_getattr(). We expect that the cache control data
+ * is currently valid --- if the caller just fetched the tuple, then
+ * it should be.
*/
if (cacheId < 0 || cacheId >= SysCacheSize)
elog(ERROR, "SysCacheGetAttr: Bad cache id %d", cacheId);
- if (! PointerIsValid(SysCache[cacheId]) ||
+ if (!PointerIsValid(SysCache[cacheId]) ||
SysCache[cacheId]->relationId == InvalidOid ||
- ! PointerIsValid(SysCache[cacheId]->cc_tupdesc))
+ !PointerIsValid(SysCache[cacheId]->cc_tupdesc))
elog(ERROR, "SysCacheGetAttr: missing cache data for id %d", cacheId);
return heap_getattr(tup, attributeNumber,
diff --git a/src/backend/utils/cache/temprel.c b/src/backend/utils/cache/temprel.c
index 0da4f3bd5e4..d5e7ba2dce9 100644
--- a/src/backend/utils/cache/temprel.c
+++ b/src/backend/utils/cache/temprel.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/cache/Attic/temprel.c,v 1.20 2000/01/26 05:57:18 momjian Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/cache/Attic/temprel.c,v 1.21 2000/04/12 17:15:54 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -64,7 +64,7 @@ create_temp_relation(const char *relname, HeapTuple pg_class_tuple)
/* save user-supplied name */
strcpy(temp_rel->user_relname, relname);
StrNCpy(temp_rel->relname, NameStr(((Form_pg_class)
- GETSTRUCT(pg_class_tuple))->relname), NAMEDATALEN);
+ GETSTRUCT(pg_class_tuple))->relname), NAMEDATALEN);
temp_rel->relid = pg_class_tuple->t_data->t_oid;
temp_rel->relkind = ((Form_pg_class) GETSTRUCT(pg_class_tuple))->relkind;
temp_rel->xid = GetCurrentTransactionId();
@@ -95,7 +95,7 @@ remove_all_temp_relations(void)
if (temp_rel->relkind != RELKIND_INDEX)
{
- char relname[NAMEDATALEN];
+ char relname[NAMEDATALEN];
/* safe from deallocation */
strcpy(relname, temp_rel->user_relname);
@@ -118,7 +118,7 @@ remove_temp_relation(Oid relid)
MemoryContext oldcxt;
List *l,
*prev;
-
+
oldcxt = MemoryContextSwitchTo((MemoryContext) CacheCxt);
prev = NIL;
diff --git a/src/backend/utils/error/elog.c b/src/backend/utils/error/elog.c
index 1a61d7e6d17..8296b1d919f 100644
--- a/src/backend/utils/error/elog.c
+++ b/src/backend/utils/error/elog.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/error/elog.c,v 1.55 2000/02/13 18:59:50 momjian Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/error/elog.c,v 1.56 2000/04/12 17:15:55 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -40,7 +40,7 @@
extern int errno;
extern int sys_nerr;
-extern CommandDest whereToSendOutput;
+extern CommandDest whereToSendOutput;
#ifdef USE_SYSLOG
/*
@@ -79,9 +79,10 @@ static int ElogDebugIndentLevel = 0;
*--------------------
*/
void
-elog(int lev, const char *fmt, ...)
+elog(int lev, const char *fmt,...)
{
va_list ap;
+
/*
* The expanded format and final output message are dynamically
* allocated if necessary, but not if they fit in the "reasonable
@@ -95,6 +96,7 @@ elog(int lev, const char *fmt, ...)
char msg_fixedbuf[256];
char *fmt_buf = fmt_fixedbuf;
char *msg_buf = msg_fixedbuf;
+
/* this buffer is only used if errno has a bogus value: */
char errorstr_buf[32];
const char *errorstr;
@@ -103,8 +105,10 @@ elog(int lev, const char *fmt, ...)
char *bp;
int indent = 0;
int space_needed;
+
#ifdef USE_SYSLOG
int log_level;
+
#endif
int len;
@@ -160,10 +164,10 @@ elog(int lev, const char *fmt, ...)
}
/*
- * Set up the expanded format, consisting of the prefix string
- * plus input format, with any %m replaced by strerror() string
- * (since vsnprintf won't know what to do with %m). To keep
- * space calculation simple, we only allow one %m.
+ * Set up the expanded format, consisting of the prefix string plus
+ * input format, with any %m replaced by strerror() string (since
+ * vsnprintf won't know what to do with %m). To keep space
+ * calculation simple, we only allow one %m.
*/
space_needed = TIMESTAMP_SIZE + strlen(prefix) + indent + (lineno ? 24 : 0)
+ strlen(fmt) + strlen(errorstr) + 1;
@@ -175,7 +179,8 @@ elog(int lev, const char *fmt, ...)
/* We're up against it, convert to fatal out-of-memory error */
fmt_buf = fmt_fixedbuf;
lev = REALLYFATAL;
- fmt = "elog: out of memory"; /* this must fit in fmt_fixedbuf! */
+ fmt = "elog: out of memory"; /* this must fit in
+ * fmt_fixedbuf! */
}
}
#ifdef ELOG_TIMESTAMPS
@@ -189,10 +194,11 @@ elog(int lev, const char *fmt, ...)
*bp++ = ' ';
/* If error was in CopyFrom() print the offending line number -- dz */
- if (lineno) {
- sprintf(bp, "copy: line %d, ", lineno);
- bp = fmt_buf + strlen(fmt_buf);
- lineno = 0;
+ if (lineno)
+ {
+ sprintf(bp, "copy: line %d, ", lineno);
+ bp = fmt_buf + strlen(fmt_buf);
+ lineno = 0;
}
for (cp = fmt; *cp; cp++)
@@ -201,15 +207,19 @@ elog(int lev, const char *fmt, ...)
{
if (cp[1] == 'm')
{
- /* XXX If there are any %'s in errorstr then vsnprintf
- * will do the Wrong Thing; do we need to cope?
- * Seems unlikely that % would appear in system errors.
+
+ /*
+ * XXX If there are any %'s in errorstr then vsnprintf
+ * will do the Wrong Thing; do we need to cope? Seems
+ * unlikely that % would appear in system errors.
*/
strcpy(bp, errorstr);
- /* copy the rest of fmt literally, since we can't
- * afford to insert another %m.
+
+ /*
+ * copy the rest of fmt literally, since we can't afford
+ * to insert another %m.
*/
- strcat(bp, cp+2);
+ strcat(bp, cp + 2);
bp += strlen(bp);
break;
}
@@ -226,21 +236,22 @@ elog(int lev, const char *fmt, ...)
*bp = '\0';
/*
- * Now generate the actual output text using vsnprintf().
- * Be sure to leave space for \n added later as well as trailing null.
+ * Now generate the actual output text using vsnprintf(). Be sure to
+ * leave space for \n added later as well as trailing null.
*/
space_needed = sizeof(msg_fixedbuf);
for (;;)
{
- int nprinted;
+ int nprinted;
va_start(ap, fmt);
nprinted = vsnprintf(msg_buf, space_needed - 2, fmt_buf, ap);
va_end(ap);
+
/*
* Note: some versions of vsnprintf return the number of chars
- * actually stored, but at least one returns -1 on failure.
- * Be conservative about believing whether the print worked.
+ * actually stored, but at least one returns -1 on failure. Be
+ * conservative about believing whether the print worked.
*/
if (nprinted >= 0 && nprinted < space_needed - 3)
break;
@@ -252,8 +263,8 @@ elog(int lev, const char *fmt, ...)
if (msg_buf == NULL)
{
/* We're up against it, convert to fatal out-of-memory error */
- msg_buf = msg_fixedbuf;
- lev = REALLYFATAL;
+ msg_buf = msg_fixedbuf;
+ lev = REALLYFATAL;
#ifdef ELOG_TIMESTAMPS
strcpy(msg_buf, tprintf_timestamp());
strcat(msg_buf, "FATAL: elog: out of memory");
@@ -307,7 +318,7 @@ elog(int lev, const char *fmt, ...)
* then writing here can cause this backend to exit without warning
* that is, write() does an exit(). In this case, our only hope of
* finding out what's going on is if Err_file was set to some disk
- * log. This is a major pain. (It's probably also long-dead code...
+ * log. This is a major pain. (It's probably also long-dead code...
* does anyone still use ultrix?)
*/
if (lev > DEBUG && Err_file >= 0 &&
@@ -332,6 +343,7 @@ elog(int lev, const char *fmt, ...)
msgtype = 'N';
else
{
+
/*
* Abort any COPY OUT in progress when an error is detected.
* This hack is necessary because of poor design of copy
@@ -357,8 +369,10 @@ elog(int lev, const char *fmt, ...)
if (lev > DEBUG && whereToSendOutput != Remote)
{
- /* We are running as an interactive backend, so just send
- * the message to stderr.
+
+ /*
+ * We are running as an interactive backend, so just send the
+ * message to stderr.
*/
fputs(msg_buf, stderr);
}
@@ -376,34 +390,37 @@ elog(int lev, const char *fmt, ...)
*/
if (lev == ERROR || lev == FATAL)
{
+
/*
* If we have not yet entered the main backend loop (ie, we are in
* the postmaster or in backend startup), then go directly to
* proc_exit. The same is true if anyone tries to report an error
- * after proc_exit has begun to run. (It's proc_exit's responsibility
- * to see that this doesn't turn into infinite recursion!) But in
- * the latter case, we exit with nonzero exit code to indicate that
- * something's pretty wrong.
+ * after proc_exit has begun to run. (It's proc_exit's
+ * responsibility to see that this doesn't turn into infinite
+ * recursion!) But in the latter case, we exit with nonzero exit
+ * code to indicate that something's pretty wrong.
*/
- if (proc_exit_inprogress || ! Warn_restart_ready)
+ if (proc_exit_inprogress || !Warn_restart_ready)
{
fflush(stdout);
fflush(stderr);
- ProcReleaseSpins(NULL); /* get rid of spinlocks we hold */
- ProcReleaseLocks(); /* get rid of real locks we hold */
+ ProcReleaseSpins(NULL); /* get rid of spinlocks we hold */
+ ProcReleaseLocks(); /* get rid of real locks we hold */
/* XXX shouldn't proc_exit be doing the above?? */
proc_exit((int) proc_exit_inprogress);
}
+
/*
* Guard against infinite loop from elog() during error recovery.
*/
if (InError)
elog(REALLYFATAL, "elog: error during error recovery, giving up!");
InError = true;
+
/*
- * Otherwise we can return to the main loop in postgres.c.
- * In the FATAL case, postgres.c will call proc_exit, but not
- * till after completing a standard transaction-abort sequence.
+ * Otherwise we can return to the main loop in postgres.c. In the
+ * FATAL case, postgres.c will call proc_exit, but not till after
+ * completing a standard transaction-abort sequence.
*/
ProcReleaseSpins(NULL); /* get rid of spinlocks we hold */
if (lev == FATAL)
@@ -413,19 +430,20 @@ elog(int lev, const char *fmt, ...)
if (lev > FATAL)
{
+
/*
- * Serious crash time. Postmaster will observe nonzero
- * process exit status and kill the other backends too.
+ * Serious crash time. Postmaster will observe nonzero process
+ * exit status and kill the other backends too.
*
- * XXX: what if we are *in* the postmaster? proc_exit()
- * won't kill our children...
+ * XXX: what if we are *in* the postmaster? proc_exit() won't kill
+ * our children...
*/
fflush(stdout);
fflush(stderr);
proc_exit(lev);
}
- /* We reach here if lev <= NOTICE. OK to return to caller. */
+ /* We reach here if lev <= NOTICE. OK to return to caller. */
}
#ifndef PG_STANDALONE
diff --git a/src/backend/utils/fmgr/dfmgr.c b/src/backend/utils/fmgr/dfmgr.c
index 2e3750a7126..a460fab05c2 100644
--- a/src/backend/utils/fmgr/dfmgr.c
+++ b/src/backend/utils/fmgr/dfmgr.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/fmgr/dfmgr.c,v 1.38 2000/01/26 05:57:22 momjian Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/fmgr/dfmgr.c,v 1.39 2000/04/12 17:15:57 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -61,10 +61,10 @@ fmgr_dynamic(Oid procedureId, int *pronargs)
/*
* The procedure isn't a builtin, so we'll have to do a catalog lookup
- * to find its pg_proc entry. Moreover, since probin is varlena, we're
- * going to have to use heap_getattr, which means we need the reldesc,
- * which means we need to open the relation. So we might as well do that
- * first and get the benefit of SI inval if needed.
+ * to find its pg_proc entry. Moreover, since probin is varlena,
+ * we're going to have to use heap_getattr, which means we need the
+ * reldesc, which means we need to open the relation. So we might as
+ * well do that first and get the benefit of SI inval if needed.
*/
rel = heap_openr(ProcedureRelationName, AccessShareLock);
@@ -123,7 +123,8 @@ fmgr_dynamic(Oid procedureId, int *pronargs)
user_fn = handle_load(probinstring, linksymbol);
pfree(probinstring);
- if (prosrcstring) pfree(prosrcstring);
+ if (prosrcstring)
+ pfree(prosrcstring);
procedureId_save = procedureId;
user_fn_save = user_fn;
diff --git a/src/backend/utils/hash/dynahash.c b/src/backend/utils/hash/dynahash.c
index 871144bf764..93707fcba91 100644
--- a/src/backend/utils/hash/dynahash.c
+++ b/src/backend/utils/hash/dynahash.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/hash/dynahash.c,v 1.30 2000/03/17 02:36:28 tgl Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/hash/dynahash.c,v 1.31 2000/04/12 17:16:00 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -701,7 +701,7 @@ hash_search(HTAB *hashp,
long *
hash_seq(HTAB *hashp)
{
- static long curBucket = 0;
+ static long curBucket = 0;
static BUCKET_INDEX curIndex;
ELEMENT *curElem;
long segment_num;
@@ -813,9 +813,10 @@ expand_table(HTAB *hashp)
/*
* *Before* changing masks, find old bucket corresponding to same hash
- * values; values in that bucket may need to be relocated to new bucket.
- * Note that new_bucket is certainly larger than low_mask at this point,
- * so we can skip the first step of the regular hash mask calc.
+ * values; values in that bucket may need to be relocated to new
+ * bucket. Note that new_bucket is certainly larger than low_mask at
+ * this point, so we can skip the first step of the regular hash mask
+ * calc.
*/
old_bucket = (new_bucket & hctl->low_mask);
@@ -829,9 +830,9 @@ expand_table(HTAB *hashp)
}
/*
- * Relocate records to the new bucket. NOTE: because of the way the
+ * Relocate records to the new bucket. NOTE: because of the way the
* hash masking is done in call_hash, only one old bucket can need to
- * be split at this point. With a different way of reducing the hash
+ * be split at this point. With a different way of reducing the hash
* value, that might not be true!
*/
old_segnum = old_bucket >> hctl->sshift;
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 5170be28615..8c4642d1ee2 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/init/globals.c,v 1.41 2000/02/16 17:25:49 thomas Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/init/globals.c,v 1.42 2000/04/12 17:16:02 momjian Exp $
*
* NOTES
* Globals used all over the place should be declared here and not
@@ -93,7 +93,8 @@ char *IndexedCatalogNames[] = {
* ps status buffer
*/
#ifndef linux
-char Ps_status_buffer[1024];
+char Ps_status_buffer[1024];
+
#endif
/* ----------------
diff --git a/src/backend/utils/init/miscinit.c b/src/backend/utils/init/miscinit.c
index 41b4020c713..a1ba1e1ff9b 100644
--- a/src/backend/utils/init/miscinit.c
+++ b/src/backend/utils/init/miscinit.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/init/miscinit.c,v 1.44 2000/02/18 09:28:58 inoue Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/init/miscinit.c,v 1.45 2000/04/12 17:16:02 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -34,6 +34,7 @@
#ifdef CYR_RECODE
unsigned char RecodeForwTable[128];
unsigned char RecodeBackTable[128];
+
#endif
ProcessingMode Mode = InitProcessing;
@@ -43,7 +44,7 @@ ProcessingMode Mode = InitProcessing;
* ----------------------------------------------------------------
*/
-static bool isIgnoringSystemIndexes = false;
+static bool isIgnoringSystemIndexes = false;
/*
* IsIgnoringSystemIndexes
@@ -74,24 +75,24 @@ IgnoreSystemIndexes(bool mode)
void
SetDatabasePath(const char *path)
{
- free(DatabasePath);
+ free(DatabasePath);
/* use strdup since this is done before memory contexts are set up */
- if (path)
- {
- DatabasePath = strdup(path);
- AssertState(DatabasePath);
- }
+ if (path)
+ {
+ DatabasePath = strdup(path);
+ AssertState(DatabasePath);
+ }
}
void
SetDatabaseName(const char *name)
{
- free(DatabaseName);
- if (name)
- {
- DatabaseName = strdup(name);
- AssertState(DatabaseName);
- }
+ free(DatabaseName);
+ if (name)
+ {
+ DatabaseName = strdup(name);
+ AssertState(DatabaseName);
+ }
}
#ifndef MULTIBYTE
@@ -105,13 +106,15 @@ getdatabaseencoding()
return ("");
}
-const char *pg_encoding_to_char(int encoding)
+const char *
+pg_encoding_to_char(int encoding)
{
elog(ERROR, "MultiByte support must be enabled to use this function");
return ("");
}
-int pg_char_to_encoding(const char *encoding_string)
+int
+pg_char_to_encoding(const char *encoding_string)
{
elog(ERROR, "MultiByte support must be enabled to use this function");
return (0);
@@ -332,7 +335,7 @@ SetUserId()
HeapTuple userTup;
char *userName;
- AssertState(!OidIsValid(UserId));/* only once */
+ AssertState(!OidIsValid(UserId)); /* only once */
/*
* Don't do scans if we're bootstrapping, none of the system catalogs
@@ -361,10 +364,10 @@ SetUserId()
*
* (1) postmaster starts. In this case pid > 0.
* (2) postgres starts in standalone mode. In this case
- * pid < 0
+ * pid < 0
*
* to gain an interlock.
- *
+ *
* SetPidFname(datadir)
* Remember the the pid file name. This is neccesary
* UnlinkPidFile() is called from proc_exit().
@@ -392,7 +395,8 @@ static char PidFile[MAXPGPATH];
/*
* Remove the pid file. This function is called from proc_exit.
*/
-void UnlinkPidFile(void)
+void
+UnlinkPidFile(void)
{
unlink(PidFile);
}
@@ -400,7 +404,8 @@ void UnlinkPidFile(void)
/*
* Set path to the pid file
*/
-void SetPidFname(char * datadir)
+void
+SetPidFname(char *datadir)
{
snprintf(PidFile, sizeof(PidFile), "%s/%s", datadir, PIDFNAME);
}
@@ -408,45 +413,50 @@ void SetPidFname(char * datadir)
/*
* Get path to the pid file
*/
-char *GetPidFname(void)
+char *
+GetPidFname(void)
{
- return(PidFile);
+ return (PidFile);
}
/*
* Create the pid file
*/
-int SetPidFile(pid_t pid)
+int
+SetPidFile(pid_t pid)
{
- int fd;
- char *pidfile;
- char pidstr[32];
- int len;
- pid_t post_pid;
- int is_postgres = 0;
+ int fd;
+ char *pidfile;
+ char pidstr[32];
+ int len;
+ pid_t post_pid;
+ int is_postgres = 0;
/*
* Creating pid file
*/
pidfile = GetPidFname();
fd = open(pidfile, O_RDWR | O_CREAT | O_EXCL, 0600);
- if (fd < 0) {
+ if (fd < 0)
+ {
+
/*
- * Couldn't create the pid file. Probably
- * it already exists. Read the file to see if the process
- * actually exists
+ * Couldn't create the pid file. Probably it already exists. Read
+ * the file to see if the process actually exists
*/
fd = open(pidfile, O_RDONLY, 0600);
- if (fd < 0) {
+ if (fd < 0)
+ {
fprintf(stderr, "Can't open pid file: %s\n", pidfile);
fprintf(stderr, "Please check the permission and try again.\n");
- return(-1);
+ return (-1);
}
- if ((len = read(fd, pidstr, sizeof(pidstr)-1)) < 0) {
+ if ((len = read(fd, pidstr, sizeof(pidstr) - 1)) < 0)
+ {
fprintf(stderr, "Can't read pid file: %s\n", pidfile);
fprintf(stderr, "Please check the permission and try again.\n");
close(fd);
- return(-1);
+ return (-1);
}
close(fd);
@@ -454,56 +464,62 @@ int SetPidFile(pid_t pid)
* Check to see if the process actually exists
*/
pidstr[len] = '\0';
- post_pid = (pid_t)atoi(pidstr);
+ post_pid = (pid_t) atoi(pidstr);
/* if pid < 0, the pid is for postgres, not postmatser */
- if (post_pid < 0) {
+ if (post_pid < 0)
+ {
is_postgres++;
post_pid = -post_pid;
}
- if (post_pid == 0 || (post_pid > 0 && kill(post_pid, 0) < 0)) {
+ if (post_pid == 0 || (post_pid > 0 && kill(post_pid, 0) < 0))
+ {
+
/*
- * No, the process did not exist. Unlink
- * the file and try to create it
+ * No, the process did not exist. Unlink the file and try to
+ * create it
*/
- if (unlink(pidfile) < 0) {
+ if (unlink(pidfile) < 0)
+ {
fprintf(stderr, "Can't remove pid file: %s\n", pidfile);
fprintf(stderr, "The file seems accidently left, but I couldn't remove it.\n");
fprintf(stderr, "Please remove the file by hand and try again.\n");
- return(-1);
+ return (-1);
}
fd = open(pidfile, O_RDWR | O_CREAT | O_EXCL, 0600);
- if (fd < 0) {
+ if (fd < 0)
+ {
fprintf(stderr, "Can't create pid file: %s\n", pidfile);
fprintf(stderr, "Please check the permission and try again.\n");
- return(-1);
+ return (-1);
}
- } else {
+ }
+ else
+ {
+
/*
* Another postmaster is running
*/
fprintf(stderr, "Can't create pid file: %s\n", pidfile);
- if (is_postgres) {
- fprintf(stderr, "Is another postgres (pid: %d) running?\n", post_pid);
- }
+ if (is_postgres)
+ fprintf(stderr, "Is another postgres (pid: %d) running?\n", post_pid);
else
- {
- fprintf(stderr, "Is another postmaster (pid: %s) running?\n", pidstr);
- }
- return(-1);
+ fprintf(stderr, "Is another postmaster (pid: %s) running?\n", pidstr);
+ return (-1);
}
}
sprintf(pidstr, "%d", pid);
- if (write(fd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
- fprintf(stderr,"Write to pid file failed\n");
+ if (write(fd, pidstr, strlen(pidstr)) != strlen(pidstr))
+ {
+ fprintf(stderr, "Write to pid file failed\n");
fprintf(stderr, "Please check the permission and try again.\n");
close(fd);
unlink(pidfile);
- return(-1);
+ return (-1);
}
close(fd);
- return(0);
+ return (0);
}
diff --git a/src/backend/utils/init/postinit.c b/src/backend/utils/init/postinit.c
index 597e6ced8b6..c4675a6b57d 100644
--- a/src/backend/utils/init/postinit.c
+++ b/src/backend/utils/init/postinit.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/init/postinit.c,v 1.56 2000/01/26 05:57:26 momjian Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/init/postinit.c,v 1.57 2000/04/12 17:16:02 momjian Exp $
*
*
*-------------------------------------------------------------------------
@@ -77,12 +77,12 @@ ReverifyMyDatabase(const char *name)
{
Relation pgdbrel;
HeapScanDesc pgdbscan;
- ScanKeyData key;
+ ScanKeyData key;
HeapTuple tup;
/*
- * Because we grab AccessShareLock here, we can be sure that
- * destroydb is not running in parallel with us (any more).
+ * Because we grab AccessShareLock here, we can be sure that destroydb
+ * is not running in parallel with us (any more).
*/
pgdbrel = heap_openr(DatabaseRelationName, AccessShareLock);
@@ -97,12 +97,12 @@ ReverifyMyDatabase(const char *name)
{
/* OOPS */
heap_close(pgdbrel, AccessShareLock);
+
/*
* The only real problem I could have created is to load dirty
- * buffers for the dead database into shared buffer cache;
- * if I did, some other backend will eventually try to write
- * them and die in mdblindwrt. Flush any such pages to forestall
- * trouble.
+ * buffers for the dead database into shared buffer cache; if I
+ * did, some other backend will eventually try to write them and
+ * die in mdblindwrt. Flush any such pages to forestall trouble.
*/
DropBuffers(MyDatabaseId);
/* Now I can commit hara-kiri with a clear conscience... */
@@ -112,15 +112,15 @@ ReverifyMyDatabase(const char *name)
/*
* OK, we're golden. Only other to-do item is to save the MULTIBYTE
- * encoding info out of the pg_database tuple. Note we also set the
- * "template encoding", which is the default encoding for any
- * CREATE DATABASE commands executed in this backend; essentially,
- * you get the same encoding of the database you connected to as
- * the default. (This replaces code that unreliably grabbed
- * template1's encoding out of pg_database. We could do an extra
- * scan to find template1's tuple, but for 99.99% of all backend
- * startups it'd be wasted cycles --- and the 'createdb' script
- * connects to template1 anyway, so there's no difference.)
+ * encoding info out of the pg_database tuple. Note we also set the
+ * "template encoding", which is the default encoding for any CREATE
+ * DATABASE commands executed in this backend; essentially, you get
+ * the same encoding of the database you connected to as the default.
+ * (This replaces code that unreliably grabbed template1's encoding
+ * out of pg_database. We could do an extra scan to find template1's
+ * tuple, but for 99.99% of all backend startups it'd be wasted cycles
+ * --- and the 'createdb' script connects to template1 anyway, so
+ * there's no difference.)
*/
#ifdef MULTIBYTE
SetDatabaseEncoding(((Form_pg_database) GETSTRUCT(tup))->encoding);
@@ -250,7 +250,7 @@ InitPostgres(const char *dbname)
on_shmem_exit(FlushBufferPool, (caddr_t) NULL);
#endif
- SetDatabaseName(dbname);
+ SetDatabaseName(dbname);
/* ----------------
* initialize the database id used for system caches and lock tables
* ----------------
@@ -262,56 +262,56 @@ InitPostgres(const char *dbname)
}
else
{
- char *reason;
- char *fullpath,
- datpath[MAXPGPATH];
-
- /* Verify if DataDir is ok */
- if (access(DataDir, F_OK) == -1)
- elog(FATAL, "Database system not found. Data directory '%s' does not exist.",
- DataDir);
-
- ValidatePgVersion(DataDir, &reason);
- if (reason != NULL)
- elog(FATAL, reason);
-
- /*-----------------
- * Find oid and path of the database we're about to open. Since we're
- * not yet up and running we have to use the hackish GetRawDatabaseInfo.
- *
- * OLD COMMENTS:
- * The database's oid forms half of the unique key for the system
- * caches and lock tables. We therefore want it initialized before
- * we open any relations, since opening relations puts things in the
- * cache. To get around this problem, this code opens and scans the
- * pg_database relation by hand.
- */
-
- GetRawDatabaseInfo(dbname, &MyDatabaseId, datpath);
-
- if (!OidIsValid(MyDatabaseId))
- elog(FATAL,
- "Database \"%s\" does not exist in the system catalog.",
- dbname);
-
- fullpath = ExpandDatabasePath(datpath);
- if (!fullpath)
- elog(FATAL, "Database path could not be resolved.");
-
- /* Verify the database path */
-
- if (access(fullpath, F_OK) == -1)
- elog(FATAL, "Database \"%s\" does not exist. The data directory '%s' is missing.",
- dbname, fullpath);
-
- ValidatePgVersion(fullpath, &reason);
- if (reason != NULL)
- elog(FATAL, "%s", reason);
-
- if(chdir(fullpath) == -1)
- elog(FATAL, "Unable to change directory to '%s': %s", fullpath, strerror(errno));
-
- SetDatabasePath(fullpath);
+ char *reason;
+ char *fullpath,
+ datpath[MAXPGPATH];
+
+ /* Verify if DataDir is ok */
+ if (access(DataDir, F_OK) == -1)
+ elog(FATAL, "Database system not found. Data directory '%s' does not exist.",
+ DataDir);
+
+ ValidatePgVersion(DataDir, &reason);
+ if (reason != NULL)
+ elog(FATAL, reason);
+
+ /*-----------------
+ * Find oid and path of the database we're about to open. Since we're
+ * not yet up and running we have to use the hackish GetRawDatabaseInfo.
+ *
+ * OLD COMMENTS:
+ * The database's oid forms half of the unique key for the system
+ * caches and lock tables. We therefore want it initialized before
+ * we open any relations, since opening relations puts things in the
+ * cache. To get around this problem, this code opens and scans the
+ * pg_database relation by hand.
+ */
+
+ GetRawDatabaseInfo(dbname, &MyDatabaseId, datpath);
+
+ if (!OidIsValid(MyDatabaseId))
+ elog(FATAL,
+ "Database \"%s\" does not exist in the system catalog.",
+ dbname);
+
+ fullpath = ExpandDatabasePath(datpath);
+ if (!fullpath)
+ elog(FATAL, "Database path could not be resolved.");
+
+ /* Verify the database path */
+
+ if (access(fullpath, F_OK) == -1)
+ elog(FATAL, "Database \"%s\" does not exist. The data directory '%s' is missing.",
+ dbname, fullpath);
+
+ ValidatePgVersion(fullpath, &reason);
+ if (reason != NULL)
+ elog(FATAL, "%s", reason);
+
+ if (chdir(fullpath) == -1)
+ elog(FATAL, "Unable to change directory to '%s': %s", fullpath, strerror(errno));
+
+ SetDatabasePath(fullpath);
}
/*
@@ -319,8 +319,9 @@ InitPostgres(const char *dbname)
*/
/*
- * Initialize the transaction system and the relation descriptor cache.
- * Note we have to make certain the lock manager is off while we do this.
+ * Initialize the transaction system and the relation descriptor
+ * cache. Note we have to make certain the lock manager is off while
+ * we do this.
*/
AmiTransactionOverride(IsBootstrapProcessingMode());
LockDisable(true);
@@ -344,10 +345,10 @@ InitPostgres(const char *dbname)
InitProcess(PostgresIpcKey);
/*
- * Initialize my entry in the shared-invalidation manager's
- * array of per-backend data. (Formerly this came before
- * InitProcess, but now it must happen after, because it uses
- * MyProc.) Once I have done this, I am visible to other backends!
+ * Initialize my entry in the shared-invalidation manager's array of
+ * per-backend data. (Formerly this came before InitProcess, but now
+ * it must happen after, because it uses MyProc.) Once I have done
+ * this, I am visible to other backends!
*
* Sets up MyBackendId, a unique backend identifier.
*/
@@ -361,8 +362,8 @@ InitPostgres(const char *dbname)
}
/*
- * Initialize the access methods.
- * Does not touch files (?) - thomas 1997-11-01
+ * Initialize the access methods. Does not touch files (?) - thomas
+ * 1997-11-01
*/
initam();
@@ -412,9 +413,9 @@ BaseInit(void)
EnableExceptionHandling(true);
/*
- * Memory system initialization - we may call palloc after
- * EnableMemoryContext()). Note that EnableMemoryContext()
- * must happen before EnablePortalManager().
+ * Memory system initialization - we may call palloc after
+ * EnableMemoryContext()). Note that EnableMemoryContext() must
+ * happen before EnablePortalManager().
*/
EnableMemoryContext(true); /* initializes the "top context" */
EnablePortalManager(true); /* memory for portal/transaction stuff */
diff --git a/src/backend/utils/mb/conv.c b/src/backend/utils/mb/conv.c
index 80c1622947e..b274440e7f0 100644
--- a/src/backend/utils/mb/conv.c
+++ b/src/backend/utils/mb/conv.c
@@ -4,7 +4,7 @@
* Tatsuo Ishii
* WIN1250 client encoding support contributed by Pavel Behal
*
- * $Id: conv.c,v 1.13 2000/01/13 01:08:14 ishii Exp $
+ * $Id: conv.c,v 1.14 2000/04/12 17:16:06 momjian Exp $
*
*
*/
@@ -24,399 +24,1180 @@
/*
* conversion table between SJIS UDC (IBM kanji) and EUC_JP
*/
-static struct {
- int sjis; /* SJIS UDC (IBM kanji) */
- int euc; /* EUC_JP */
-} ibmkanji[] = {
- {0xfa40, 0x8ff3f3},
- {0xfa41, 0x8ff3f4},
- {0xfa42, 0x8ff3f5},
- {0xfa43, 0x8ff3f6},
- {0xfa44, 0x8ff3f7},
- {0xfa45, 0x8ff3f8},
- {0xfa46, 0x8ff3f9},
- {0xfa47, 0x8ff3fa},
- {0xfa48, 0x8ff3fb},
- {0xfa49, 0x8ff3fc},
- {0xfa4a, 0x8ff3fd},
- {0xfa4b, 0x8ff3fe},
- {0xfa4c, 0x8ff4a1},
- {0xfa4d, 0x8ff4a2},
- {0xfa4e, 0x8ff4a3},
- {0xfa4f, 0x8ff4a4},
- {0xfa50, 0x8ff4a5},
- {0xfa51, 0x8ff4a6},
- {0xfa52, 0x8ff4a7},
- {0xfa53, 0x8ff4a8},
- {0xfa54, 0xa2cc},
- {0xfa55, 0x8fa2c3},
- {0xfa56, 0x8ff4a9},
- {0xfa57, 0x8ff4aa},
- {0xfa58, 0x8ff4ab},
- {0xfa59, 0x8ff4ac},
- {0xfa5a, 0x8ff4ad},
- {0xfa5b, 0xa2e8},
- {0xfa5c, 0x8fd4e3},
- {0xfa5d, 0x8fdcdf},
- {0xfa5e, 0x8fe4e9},
- {0xfa5f, 0x8fe3f8},
- {0xfa60, 0x8fd9a1},
- {0xfa61, 0x8fb1bb},
- {0xfa62, 0x8ff4ae},
- {0xfa63, 0x8fc2ad},
- {0xfa64, 0x8fc3fc},
- {0xfa65, 0x8fe4d0},
- {0xfa66, 0x8fc2bf},
- {0xfa67, 0x8fbcf4},
- {0xfa68, 0x8fb0a9},
- {0xfa69, 0x8fb0c8},
- {0xfa6a, 0x8ff4af},
- {0xfa6b, 0x8fb0d2},
- {0xfa6c, 0x8fb0d4},
- {0xfa6d, 0x8fb0e3},
- {0xfa6e, 0x8fb0ee},
- {0xfa6f, 0x8fb1a7},
- {0xfa70, 0x8fb1a3},
- {0xfa71, 0x8fb1ac},
- {0xfa72, 0x8fb1a9},
- {0xfa73, 0x8fb1be},
- {0xfa74, 0x8fb1df},
- {0xfa75, 0x8fb1d8},
- {0xfa76, 0x8fb1c8},
- {0xfa77, 0x8fb1d7},
- {0xfa78, 0x8fb1e3},
- {0xfa79, 0x8fb1f4},
- {0xfa7a, 0x8fb1e1},
- {0xfa7b, 0x8fb2a3},
- {0xfa7c, 0x8ff4b0},
- {0xfa7d, 0x8fb2bb},
- {0xfa7e, 0x8fb2e6},
- {0xfa80, 0x8fb2ed},
- {0xfa81, 0x8fb2f5},
- {0xfa82, 0x8fb2fc},
- {0xfa83, 0x8ff4b1},
- {0xfa84, 0x8fb3b5},
- {0xfa85, 0x8fb3d8},
- {0xfa86, 0x8fb3db},
- {0xfa87, 0x8fb3e5},
- {0xfa88, 0x8fb3ee},
- {0xfa89, 0x8fb3fb},
- {0xfa8a, 0x8ff4b2},
- {0xfa8b, 0x8ff4b3},
- {0xfa8c, 0x8fb4c0},
- {0xfa8d, 0x8fb4c7},
- {0xfa8e, 0x8fb4d0},
- {0xfa8f, 0x8fb4de},
- {0xfa90, 0x8ff4b4},
- {0xfa91, 0x8fb5aa},
- {0xfa92, 0x8ff4b5},
- {0xfa93, 0x8fb5af},
- {0xfa94, 0x8fb5c4},
- {0xfa95, 0x8fb5e8},
- {0xfa96, 0x8ff4b6},
- {0xfa97, 0x8fb7c2},
- {0xfa98, 0x8fb7e4},
- {0xfa99, 0x8fb7e8},
- {0xfa9a, 0x8fb7e7},
- {0xfa9b, 0x8ff4b7},
- {0xfa9c, 0x8ff4b8},
- {0xfa9d, 0x8ff4b9},
- {0xfa9e, 0x8fb8ce},
- {0xfa9f, 0x8fb8e1},
- {0xfaa0, 0x8fb8f5},
- {0xfaa1, 0x8fb8f7},
- {0xfaa2, 0x8fb8f8},
- {0xfaa3, 0x8fb8fc},
- {0xfaa4, 0x8fb9af},
- {0xfaa5, 0x8fb9b7},
- {0xfaa6, 0x8fbabe},
- {0xfaa7, 0x8fbadb},
- {0xfaa8, 0x8fcdaa},
- {0xfaa9, 0x8fbae1},
- {0xfaaa, 0x8ff4ba},
- {0xfaab, 0x8fbaeb},
- {0xfaac, 0x8fbbb3},
- {0xfaad, 0x8fbbb8},
- {0xfaae, 0x8ff4bb},
- {0xfaaf, 0x8fbbca},
- {0xfab0, 0x8ff4bc},
- {0xfab1, 0x8ff4bd},
- {0xfab2, 0x8fbbd0},
- {0xfab3, 0x8fbbde},
- {0xfab4, 0x8fbbf4},
- {0xfab5, 0x8fbbf5},
- {0xfab6, 0x8fbbf9},
- {0xfab7, 0x8fbce4},
- {0xfab8, 0x8fbced},
- {0xfab9, 0x8fbcfe},
- {0xfaba, 0x8ff4be},
- {0xfabb, 0x8fbdc2},
- {0xfabc, 0x8fbde7},
- {0xfabd, 0x8ff4bf},
- {0xfabe, 0x8fbdf0},
- {0xfabf, 0x8fbeb0},
- {0xfac0, 0x8fbeac},
- {0xfac1, 0x8ff4c0},
- {0xfac2, 0x8fbeb3},
- {0xfac3, 0x8fbebd},
- {0xfac4, 0x8fbecd},
- {0xfac5, 0x8fbec9},
- {0xfac6, 0x8fbee4},
- {0xfac7, 0x8fbfa8},
- {0xfac8, 0x8fbfc9},
- {0xfac9, 0x8fc0c4},
- {0xfaca, 0x8fc0e4},
- {0xfacb, 0x8fc0f4},
- {0xfacc, 0x8fc1a6},
- {0xfacd, 0x8ff4c1},
- {0xface, 0x8fc1f5},
- {0xfacf, 0x8fc1fc},
- {0xfad0, 0x8ff4c2},
- {0xfad1, 0x8fc1f8},
- {0xfad2, 0x8fc2ab},
- {0xfad3, 0x8fc2a1},
- {0xfad4, 0x8fc2a5},
- {0xfad5, 0x8ff4c3},
- {0xfad6, 0x8fc2b8},
- {0xfad7, 0x8fc2ba},
- {0xfad8, 0x8ff4c4},
- {0xfad9, 0x8fc2c4},
- {0xfada, 0x8fc2d2},
- {0xfadb, 0x8fc2d7},
- {0xfadc, 0x8fc2db},
- {0xfadd, 0x8fc2de},
- {0xfade, 0x8fc2ed},
- {0xfadf, 0x8fc2f0},
- {0xfae0, 0x8ff4c5},
- {0xfae1, 0x8fc3a1},
- {0xfae2, 0x8fc3b5},
- {0xfae3, 0x8fc3c9},
- {0xfae4, 0x8fc3b9},
- {0xfae5, 0x8ff4c6},
- {0xfae6, 0x8fc3d8},
- {0xfae7, 0x8fc3fe},
- {0xfae8, 0x8ff4c7},
- {0xfae9, 0x8fc4cc},
- {0xfaea, 0x8ff4c8},
- {0xfaeb, 0x8fc4d9},
- {0xfaec, 0x8fc4ea},
- {0xfaed, 0x8fc4fd},
- {0xfaee, 0x8ff4c9},
- {0xfaef, 0x8fc5a7},
- {0xfaf0, 0x8fc5b5},
- {0xfaf1, 0x8fc5b6},
- {0xfaf2, 0x8ff4ca},
- {0xfaf3, 0x8fc5d5},
- {0xfaf4, 0x8fc6b8},
- {0xfaf5, 0x8fc6d7},
- {0xfaf6, 0x8fc6e0},
- {0xfaf7, 0x8fc6ea},
- {0xfaf8, 0x8fc6e3},
- {0xfaf9, 0x8fc7a1},
- {0xfafa, 0x8fc7ab},
- {0xfafb, 0x8fc7c7},
- {0xfafc, 0x8fc7c3},
- {0xfb40, 0x8fc7cb},
- {0xfb41, 0x8fc7cf},
- {0xfb42, 0x8fc7d9},
- {0xfb43, 0x8ff4cb},
- {0xfb44, 0x8ff4cc},
- {0xfb45, 0x8fc7e6},
- {0xfb46, 0x8fc7ee},
- {0xfb47, 0x8fc7fc},
- {0xfb48, 0x8fc7eb},
- {0xfb49, 0x8fc7f0},
- {0xfb4a, 0x8fc8b1},
- {0xfb4b, 0x8fc8e5},
- {0xfb4c, 0x8fc8f8},
- {0xfb4d, 0x8fc9a6},
- {0xfb4e, 0x8fc9ab},
- {0xfb4f, 0x8fc9ad},
- {0xfb50, 0x8ff4cd},
- {0xfb51, 0x8fc9ca},
- {0xfb52, 0x8fc9d3},
- {0xfb53, 0x8fc9e9},
- {0xfb54, 0x8fc9e3},
- {0xfb55, 0x8fc9fc},
- {0xfb56, 0x8fc9f4},
- {0xfb57, 0x8fc9f5},
- {0xfb58, 0x8ff4ce},
- {0xfb59, 0x8fcab3},
- {0xfb5a, 0x8fcabd},
- {0xfb5b, 0x8fcaef},
- {0xfb5c, 0x8fcaf1},
- {0xfb5d, 0x8fcbae},
- {0xfb5e, 0x8ff4cf},
- {0xfb5f, 0x8fcbca},
- {0xfb60, 0x8fcbe6},
- {0xfb61, 0x8fcbea},
- {0xfb62, 0x8fcbf0},
- {0xfb63, 0x8fcbf4},
- {0xfb64, 0x8fcbee},
- {0xfb65, 0x8fcca5},
- {0xfb66, 0x8fcbf9},
- {0xfb67, 0x8fccab},
- {0xfb68, 0x8fccae},
- {0xfb69, 0x8fccad},
- {0xfb6a, 0x8fccb2},
- {0xfb6b, 0x8fccc2},
- {0xfb6c, 0x8fccd0},
- {0xfb6d, 0x8fccd9},
- {0xfb6e, 0x8ff4d0},
- {0xfb6f, 0x8fcdbb},
- {0xfb70, 0x8ff4d1},
- {0xfb71, 0x8fcebb},
- {0xfb72, 0x8ff4d2},
- {0xfb73, 0x8fceba},
- {0xfb74, 0x8fcec3},
- {0xfb75, 0x8ff4d3},
- {0xfb76, 0x8fcef2},
- {0xfb77, 0x8fb3dd},
- {0xfb78, 0x8fcfd5},
- {0xfb79, 0x8fcfe2},
- {0xfb7a, 0x8fcfe9},
- {0xfb7b, 0x8fcfed},
- {0xfb7c, 0x8ff4d4},
- {0xfb7d, 0x8ff4d5},
- {0xfb7e, 0x8ff4d6},
- {0xfb80, 0x8ff4d7},
- {0xfb81, 0x8fd0e5},
- {0xfb82, 0x8ff4d8},
- {0xfb83, 0x8fd0e9},
- {0xfb84, 0x8fd1e8},
- {0xfb85, 0x8ff4d9},
- {0xfb86, 0x8ff4da},
- {0xfb87, 0x8fd1ec},
- {0xfb88, 0x8fd2bb},
- {0xfb89, 0x8ff4db},
- {0xfb8a, 0x8fd3e1},
- {0xfb8b, 0x8fd3e8},
- {0xfb8c, 0x8fd4a7},
- {0xfb8d, 0x8ff4dc},
- {0xfb8e, 0x8ff4dd},
- {0xfb8f, 0x8fd4d4},
- {0xfb90, 0x8fd4f2},
- {0xfb91, 0x8fd5ae},
- {0xfb92, 0x8ff4de},
- {0xfb93, 0x8fd7de},
- {0xfb94, 0x8ff4df},
- {0xfb95, 0x8fd8a2},
- {0xfb96, 0x8fd8b7},
- {0xfb97, 0x8fd8c1},
- {0xfb98, 0x8fd8d1},
- {0xfb99, 0x8fd8f4},
- {0xfb9a, 0x8fd9c6},
- {0xfb9b, 0x8fd9c8},
- {0xfb9c, 0x8fd9d1},
- {0xfb9d, 0x8ff4e0},
- {0xfb9e, 0x8ff4e1},
- {0xfb9f, 0x8ff4e2},
- {0xfba0, 0x8ff4e3},
- {0xfba1, 0x8ff4e4},
- {0xfba2, 0x8fdcd3},
- {0xfba3, 0x8fddc8},
- {0xfba4, 0x8fddd4},
- {0xfba5, 0x8fddea},
- {0xfba6, 0x8fddfa},
- {0xfba7, 0x8fdea4},
- {0xfba8, 0x8fdeb0},
- {0xfba9, 0x8ff4e5},
- {0xfbaa, 0x8fdeb5},
- {0xfbab, 0x8fdecb},
- {0xfbac, 0x8ff4e6},
- {0xfbad, 0x8fdfb9},
- {0xfbae, 0x8ff4e7},
- {0xfbaf, 0x8fdfc3},
- {0xfbb0, 0x8ff4e8},
- {0xfbb1, 0x8ff4e9},
- {0xfbb2, 0x8fe0d9},
- {0xfbb3, 0x8ff4ea},
- {0xfbb4, 0x8ff4eb},
- {0xfbb5, 0x8fe1e2},
- {0xfbb6, 0x8ff4ec},
- {0xfbb7, 0x8ff4ed},
- {0xfbb8, 0x8ff4ee},
- {0xfbb9, 0x8fe2c7},
- {0xfbba, 0x8fe3a8},
- {0xfbbb, 0x8fe3a6},
- {0xfbbc, 0x8fe3a9},
- {0xfbbd, 0x8fe3af},
- {0xfbbe, 0x8fe3b0},
- {0xfbbf, 0x8fe3aa},
- {0xfbc0, 0x8fe3ab},
- {0xfbc1, 0x8fe3bc},
- {0xfbc2, 0x8fe3c1},
- {0xfbc3, 0x8fe3bf},
- {0xfbc4, 0x8fe3d5},
- {0xfbc5, 0x8fe3d8},
- {0xfbc6, 0x8fe3d6},
- {0xfbc7, 0x8fe3df},
- {0xfbc8, 0x8fe3e3},
- {0xfbc9, 0x8fe3e1},
- {0xfbca, 0x8fe3d4},
- {0xfbcb, 0x8fe3e9},
- {0xfbcc, 0x8fe4a6},
- {0xfbcd, 0x8fe3f1},
- {0xfbce, 0x8fe3f2},
- {0xfbcf, 0x8fe4cb},
- {0xfbd0, 0x8fe4c1},
- {0xfbd1, 0x8fe4c3},
- {0xfbd2, 0x8fe4be},
- {0xfbd3, 0x8ff4ef},
- {0xfbd4, 0x8fe4c0},
- {0xfbd5, 0x8fe4c7},
- {0xfbd6, 0x8fe4bf},
- {0xfbd7, 0x8fe4e0},
- {0xfbd8, 0x8fe4de},
- {0xfbd9, 0x8fe4d1},
- {0xfbda, 0x8ff4f0},
- {0xfbdb, 0x8fe4dc},
- {0xfbdc, 0x8fe4d2},
- {0xfbdd, 0x8fe4db},
- {0xfbde, 0x8fe4d4},
- {0xfbdf, 0x8fe4fa},
- {0xfbe0, 0x8fe4ef},
- {0xfbe1, 0x8fe5b3},
- {0xfbe2, 0x8fe5bf},
- {0xfbe3, 0x8fe5c9},
- {0xfbe4, 0x8fe5d0},
- {0xfbe5, 0x8fe5e2},
- {0xfbe6, 0x8fe5ea},
- {0xfbe7, 0x8fe5eb},
- {0xfbe8, 0x8ff4f1},
- {0xfbe9, 0x8ff4f2},
- {0xfbea, 0x8ff4f3},
- {0xfbeb, 0x8fe6e8},
- {0xfbec, 0x8fe6ef},
- {0xfbed, 0x8fe7ac},
- {0xfbee, 0x8ff4f4},
- {0xfbef, 0x8fe7ae},
- {0xfbf0, 0x8ff4f5},
- {0xfbf1, 0x8fe7b1},
- {0xfbf2, 0x8ff4f6},
- {0xfbf3, 0x8fe7b2},
- {0xfbf4, 0x8fe8b1},
- {0xfbf5, 0x8fe8b6},
- {0xfbf6, 0x8ff4f7},
- {0xfbf7, 0x8ff4f8},
- {0xfbf8, 0x8fe8dd},
- {0xfbf9, 0x8ff4f9},
- {0xfbfa, 0x8ff4fa},
- {0xfbfb, 0x8fe9d1},
- {0xfbfc, 0x8ff4fb},
- {0xfc40, 0x8fe9ed},
- {0xfc41, 0x8feacd},
- {0xfc42, 0x8ff4fc},
- {0xfc43, 0x8feadb},
- {0xfc44, 0x8feae6},
- {0xfc45, 0x8feaea},
- {0xfc46, 0x8feba5},
- {0xfc47, 0x8febfb},
- {0xfc48, 0x8febfa},
- {0xfc49, 0x8ff4fd},
- {0xfc4a, 0x8fecd6},
- {0xfc4b, 0x8ff4fe},
- {0xffff, 0xffff} /* stop code */
+static struct
+{
+ int sjis; /* SJIS UDC (IBM kanji) */
+ int euc; /* EUC_JP */
+} ibmkanji[] =
+
+{
+ {
+ 0xfa40, 0x8ff3f3
+ },
+ {
+ 0xfa41, 0x8ff3f4
+ },
+ {
+ 0xfa42, 0x8ff3f5
+ },
+ {
+ 0xfa43, 0x8ff3f6
+ },
+ {
+ 0xfa44, 0x8ff3f7
+ },
+ {
+ 0xfa45, 0x8ff3f8
+ },
+ {
+ 0xfa46, 0x8ff3f9
+ },
+ {
+ 0xfa47, 0x8ff3fa
+ },
+ {
+ 0xfa48, 0x8ff3fb
+ },
+ {
+ 0xfa49, 0x8ff3fc
+ },
+ {
+ 0xfa4a, 0x8ff3fd
+ },
+ {
+ 0xfa4b, 0x8ff3fe
+ },
+ {
+ 0xfa4c, 0x8ff4a1
+ },
+ {
+ 0xfa4d, 0x8ff4a2
+ },
+ {
+ 0xfa4e, 0x8ff4a3
+ },
+ {
+ 0xfa4f, 0x8ff4a4
+ },
+ {
+ 0xfa50, 0x8ff4a5
+ },
+ {
+ 0xfa51, 0x8ff4a6
+ },
+ {
+ 0xfa52, 0x8ff4a7
+ },
+ {
+ 0xfa53, 0x8ff4a8
+ },
+ {
+ 0xfa54, 0xa2cc
+ },
+ {
+ 0xfa55, 0x8fa2c3
+ },
+ {
+ 0xfa56, 0x8ff4a9
+ },
+ {
+ 0xfa57, 0x8ff4aa
+ },
+ {
+ 0xfa58, 0x8ff4ab
+ },
+ {
+ 0xfa59, 0x8ff4ac
+ },
+ {
+ 0xfa5a, 0x8ff4ad
+ },
+ {
+ 0xfa5b, 0xa2e8
+ },
+ {
+ 0xfa5c, 0x8fd4e3
+ },
+ {
+ 0xfa5d, 0x8fdcdf
+ },
+ {
+ 0xfa5e, 0x8fe4e9
+ },
+ {
+ 0xfa5f, 0x8fe3f8
+ },
+ {
+ 0xfa60, 0x8fd9a1
+ },
+ {
+ 0xfa61, 0x8fb1bb
+ },
+ {
+ 0xfa62, 0x8ff4ae
+ },
+ {
+ 0xfa63, 0x8fc2ad
+ },
+ {
+ 0xfa64, 0x8fc3fc
+ },
+ {
+ 0xfa65, 0x8fe4d0
+ },
+ {
+ 0xfa66, 0x8fc2bf
+ },
+ {
+ 0xfa67, 0x8fbcf4
+ },
+ {
+ 0xfa68, 0x8fb0a9
+ },
+ {
+ 0xfa69, 0x8fb0c8
+ },
+ {
+ 0xfa6a, 0x8ff4af
+ },
+ {
+ 0xfa6b, 0x8fb0d2
+ },
+ {
+ 0xfa6c, 0x8fb0d4
+ },
+ {
+ 0xfa6d, 0x8fb0e3
+ },
+ {
+ 0xfa6e, 0x8fb0ee
+ },
+ {
+ 0xfa6f, 0x8fb1a7
+ },
+ {
+ 0xfa70, 0x8fb1a3
+ },
+ {
+ 0xfa71, 0x8fb1ac
+ },
+ {
+ 0xfa72, 0x8fb1a9
+ },
+ {
+ 0xfa73, 0x8fb1be
+ },
+ {
+ 0xfa74, 0x8fb1df
+ },
+ {
+ 0xfa75, 0x8fb1d8
+ },
+ {
+ 0xfa76, 0x8fb1c8
+ },
+ {
+ 0xfa77, 0x8fb1d7
+ },
+ {
+ 0xfa78, 0x8fb1e3
+ },
+ {
+ 0xfa79, 0x8fb1f4
+ },
+ {
+ 0xfa7a, 0x8fb1e1
+ },
+ {
+ 0xfa7b, 0x8fb2a3
+ },
+ {
+ 0xfa7c, 0x8ff4b0
+ },
+ {
+ 0xfa7d, 0x8fb2bb
+ },
+ {
+ 0xfa7e, 0x8fb2e6
+ },
+ {
+ 0xfa80, 0x8fb2ed
+ },
+ {
+ 0xfa81, 0x8fb2f5
+ },
+ {
+ 0xfa82, 0x8fb2fc
+ },
+ {
+ 0xfa83, 0x8ff4b1
+ },
+ {
+ 0xfa84, 0x8fb3b5
+ },
+ {
+ 0xfa85, 0x8fb3d8
+ },
+ {
+ 0xfa86, 0x8fb3db
+ },
+ {
+ 0xfa87, 0x8fb3e5
+ },
+ {
+ 0xfa88, 0x8fb3ee
+ },
+ {
+ 0xfa89, 0x8fb3fb
+ },
+ {
+ 0xfa8a, 0x8ff4b2
+ },
+ {
+ 0xfa8b, 0x8ff4b3
+ },
+ {
+ 0xfa8c, 0x8fb4c0
+ },
+ {
+ 0xfa8d, 0x8fb4c7
+ },
+ {
+ 0xfa8e, 0x8fb4d0
+ },
+ {
+ 0xfa8f, 0x8fb4de
+ },
+ {
+ 0xfa90, 0x8ff4b4
+ },
+ {
+ 0xfa91, 0x8fb5aa
+ },
+ {
+ 0xfa92, 0x8ff4b5
+ },
+ {
+ 0xfa93, 0x8fb5af
+ },
+ {
+ 0xfa94, 0x8fb5c4
+ },
+ {
+ 0xfa95, 0x8fb5e8
+ },
+ {
+ 0xfa96, 0x8ff4b6
+ },
+ {
+ 0xfa97, 0x8fb7c2
+ },
+ {
+ 0xfa98, 0x8fb7e4
+ },
+ {
+ 0xfa99, 0x8fb7e8
+ },
+ {
+ 0xfa9a, 0x8fb7e7
+ },
+ {
+ 0xfa9b, 0x8ff4b7
+ },
+ {
+ 0xfa9c, 0x8ff4b8
+ },
+ {
+ 0xfa9d, 0x8ff4b9
+ },
+ {
+ 0xfa9e, 0x8fb8ce
+ },
+ {
+ 0xfa9f, 0x8fb8e1
+ },
+ {
+ 0xfaa0, 0x8fb8f5
+ },
+ {
+ 0xfaa1, 0x8fb8f7
+ },
+ {
+ 0xfaa2, 0x8fb8f8
+ },
+ {
+ 0xfaa3, 0x8fb8fc
+ },
+ {
+ 0xfaa4, 0x8fb9af
+ },
+ {
+ 0xfaa5, 0x8fb9b7
+ },
+ {
+ 0xfaa6, 0x8fbabe
+ },
+ {
+ 0xfaa7, 0x8fbadb
+ },
+ {
+ 0xfaa8, 0x8fcdaa
+ },
+ {
+ 0xfaa9, 0x8fbae1
+ },
+ {
+ 0xfaaa, 0x8ff4ba
+ },
+ {
+ 0xfaab, 0x8fbaeb
+ },
+ {
+ 0xfaac, 0x8fbbb3
+ },
+ {
+ 0xfaad, 0x8fbbb8
+ },
+ {
+ 0xfaae, 0x8ff4bb
+ },
+ {
+ 0xfaaf, 0x8fbbca
+ },
+ {
+ 0xfab0, 0x8ff4bc
+ },
+ {
+ 0xfab1, 0x8ff4bd
+ },
+ {
+ 0xfab2, 0x8fbbd0
+ },
+ {
+ 0xfab3, 0x8fbbde
+ },
+ {
+ 0xfab4, 0x8fbbf4
+ },
+ {
+ 0xfab5, 0x8fbbf5
+ },
+ {
+ 0xfab6, 0x8fbbf9
+ },
+ {
+ 0xfab7, 0x8fbce4
+ },
+ {
+ 0xfab8, 0x8fbced
+ },
+ {
+ 0xfab9, 0x8fbcfe
+ },
+ {
+ 0xfaba, 0x8ff4be
+ },
+ {
+ 0xfabb, 0x8fbdc2
+ },
+ {
+ 0xfabc, 0x8fbde7
+ },
+ {
+ 0xfabd, 0x8ff4bf
+ },
+ {
+ 0xfabe, 0x8fbdf0
+ },
+ {
+ 0xfabf, 0x8fbeb0
+ },
+ {
+ 0xfac0, 0x8fbeac
+ },
+ {
+ 0xfac1, 0x8ff4c0
+ },
+ {
+ 0xfac2, 0x8fbeb3
+ },
+ {
+ 0xfac3, 0x8fbebd
+ },
+ {
+ 0xfac4, 0x8fbecd
+ },
+ {
+ 0xfac5, 0x8fbec9
+ },
+ {
+ 0xfac6, 0x8fbee4
+ },
+ {
+ 0xfac7, 0x8fbfa8
+ },
+ {
+ 0xfac8, 0x8fbfc9
+ },
+ {
+ 0xfac9, 0x8fc0c4
+ },
+ {
+ 0xfaca, 0x8fc0e4
+ },
+ {
+ 0xfacb, 0x8fc0f4
+ },
+ {
+ 0xfacc, 0x8fc1a6
+ },
+ {
+ 0xfacd, 0x8ff4c1
+ },
+ {
+ 0xface, 0x8fc1f5
+ },
+ {
+ 0xfacf, 0x8fc1fc
+ },
+ {
+ 0xfad0, 0x8ff4c2
+ },
+ {
+ 0xfad1, 0x8fc1f8
+ },
+ {
+ 0xfad2, 0x8fc2ab
+ },
+ {
+ 0xfad3, 0x8fc2a1
+ },
+ {
+ 0xfad4, 0x8fc2a5
+ },
+ {
+ 0xfad5, 0x8ff4c3
+ },
+ {
+ 0xfad6, 0x8fc2b8
+ },
+ {
+ 0xfad7, 0x8fc2ba
+ },
+ {
+ 0xfad8, 0x8ff4c4
+ },
+ {
+ 0xfad9, 0x8fc2c4
+ },
+ {
+ 0xfada, 0x8fc2d2
+ },
+ {
+ 0xfadb, 0x8fc2d7
+ },
+ {
+ 0xfadc, 0x8fc2db
+ },
+ {
+ 0xfadd, 0x8fc2de
+ },
+ {
+ 0xfade, 0x8fc2ed
+ },
+ {
+ 0xfadf, 0x8fc2f0
+ },
+ {
+ 0xfae0, 0x8ff4c5
+ },
+ {
+ 0xfae1, 0x8fc3a1
+ },
+ {
+ 0xfae2, 0x8fc3b5
+ },
+ {
+ 0xfae3, 0x8fc3c9
+ },
+ {
+ 0xfae4, 0x8fc3b9
+ },
+ {
+ 0xfae5, 0x8ff4c6
+ },
+ {
+ 0xfae6, 0x8fc3d8
+ },
+ {
+ 0xfae7, 0x8fc3fe
+ },
+ {
+ 0xfae8, 0x8ff4c7
+ },
+ {
+ 0xfae9, 0x8fc4cc
+ },
+ {
+ 0xfaea, 0x8ff4c8
+ },
+ {
+ 0xfaeb, 0x8fc4d9
+ },
+ {
+ 0xfaec, 0x8fc4ea
+ },
+ {
+ 0xfaed, 0x8fc4fd
+ },
+ {
+ 0xfaee, 0x8ff4c9
+ },
+ {
+ 0xfaef, 0x8fc5a7
+ },
+ {
+ 0xfaf0, 0x8fc5b5
+ },
+ {
+ 0xfaf1, 0x8fc5b6
+ },
+ {
+ 0xfaf2, 0x8ff4ca
+ },
+ {
+ 0xfaf3, 0x8fc5d5
+ },
+ {
+ 0xfaf4, 0x8fc6b8
+ },
+ {
+ 0xfaf5, 0x8fc6d7
+ },
+ {
+ 0xfaf6, 0x8fc6e0
+ },
+ {
+ 0xfaf7, 0x8fc6ea
+ },
+ {
+ 0xfaf8, 0x8fc6e3
+ },
+ {
+ 0xfaf9, 0x8fc7a1
+ },
+ {
+ 0xfafa, 0x8fc7ab
+ },
+ {
+ 0xfafb, 0x8fc7c7
+ },
+ {
+ 0xfafc, 0x8fc7c3
+ },
+ {
+ 0xfb40, 0x8fc7cb
+ },
+ {
+ 0xfb41, 0x8fc7cf
+ },
+ {
+ 0xfb42, 0x8fc7d9
+ },
+ {
+ 0xfb43, 0x8ff4cb
+ },
+ {
+ 0xfb44, 0x8ff4cc
+ },
+ {
+ 0xfb45, 0x8fc7e6
+ },
+ {
+ 0xfb46, 0x8fc7ee
+ },
+ {
+ 0xfb47, 0x8fc7fc
+ },
+ {
+ 0xfb48, 0x8fc7eb
+ },
+ {
+ 0xfb49, 0x8fc7f0
+ },
+ {
+ 0xfb4a, 0x8fc8b1
+ },
+ {
+ 0xfb4b, 0x8fc8e5
+ },
+ {
+ 0xfb4c, 0x8fc8f8
+ },
+ {
+ 0xfb4d, 0x8fc9a6
+ },
+ {
+ 0xfb4e, 0x8fc9ab
+ },
+ {
+ 0xfb4f, 0x8fc9ad
+ },
+ {
+ 0xfb50, 0x8ff4cd
+ },
+ {
+ 0xfb51, 0x8fc9ca
+ },
+ {
+ 0xfb52, 0x8fc9d3
+ },
+ {
+ 0xfb53, 0x8fc9e9
+ },
+ {
+ 0xfb54, 0x8fc9e3
+ },
+ {
+ 0xfb55, 0x8fc9fc
+ },
+ {
+ 0xfb56, 0x8fc9f4
+ },
+ {
+ 0xfb57, 0x8fc9f5
+ },
+ {
+ 0xfb58, 0x8ff4ce
+ },
+ {
+ 0xfb59, 0x8fcab3
+ },
+ {
+ 0xfb5a, 0x8fcabd
+ },
+ {
+ 0xfb5b, 0x8fcaef
+ },
+ {
+ 0xfb5c, 0x8fcaf1
+ },
+ {
+ 0xfb5d, 0x8fcbae
+ },
+ {
+ 0xfb5e, 0x8ff4cf
+ },
+ {
+ 0xfb5f, 0x8fcbca
+ },
+ {
+ 0xfb60, 0x8fcbe6
+ },
+ {
+ 0xfb61, 0x8fcbea
+ },
+ {
+ 0xfb62, 0x8fcbf0
+ },
+ {
+ 0xfb63, 0x8fcbf4
+ },
+ {
+ 0xfb64, 0x8fcbee
+ },
+ {
+ 0xfb65, 0x8fcca5
+ },
+ {
+ 0xfb66, 0x8fcbf9
+ },
+ {
+ 0xfb67, 0x8fccab
+ },
+ {
+ 0xfb68, 0x8fccae
+ },
+ {
+ 0xfb69, 0x8fccad
+ },
+ {
+ 0xfb6a, 0x8fccb2
+ },
+ {
+ 0xfb6b, 0x8fccc2
+ },
+ {
+ 0xfb6c, 0x8fccd0
+ },
+ {
+ 0xfb6d, 0x8fccd9
+ },
+ {
+ 0xfb6e, 0x8ff4d0
+ },
+ {
+ 0xfb6f, 0x8fcdbb
+ },
+ {
+ 0xfb70, 0x8ff4d1
+ },
+ {
+ 0xfb71, 0x8fcebb
+ },
+ {
+ 0xfb72, 0x8ff4d2
+ },
+ {
+ 0xfb73, 0x8fceba
+ },
+ {
+ 0xfb74, 0x8fcec3
+ },
+ {
+ 0xfb75, 0x8ff4d3
+ },
+ {
+ 0xfb76, 0x8fcef2
+ },
+ {
+ 0xfb77, 0x8fb3dd
+ },
+ {
+ 0xfb78, 0x8fcfd5
+ },
+ {
+ 0xfb79, 0x8fcfe2
+ },
+ {
+ 0xfb7a, 0x8fcfe9
+ },
+ {
+ 0xfb7b, 0x8fcfed
+ },
+ {
+ 0xfb7c, 0x8ff4d4
+ },
+ {
+ 0xfb7d, 0x8ff4d5
+ },
+ {
+ 0xfb7e, 0x8ff4d6
+ },
+ {
+ 0xfb80, 0x8ff4d7
+ },
+ {
+ 0xfb81, 0x8fd0e5
+ },
+ {
+ 0xfb82, 0x8ff4d8
+ },
+ {
+ 0xfb83, 0x8fd0e9
+ },
+ {
+ 0xfb84, 0x8fd1e8
+ },
+ {
+ 0xfb85, 0x8ff4d9
+ },
+ {
+ 0xfb86, 0x8ff4da
+ },
+ {
+ 0xfb87, 0x8fd1ec
+ },
+ {
+ 0xfb88, 0x8fd2bb
+ },
+ {
+ 0xfb89, 0x8ff4db
+ },
+ {
+ 0xfb8a, 0x8fd3e1
+ },
+ {
+ 0xfb8b, 0x8fd3e8
+ },
+ {
+ 0xfb8c, 0x8fd4a7
+ },
+ {
+ 0xfb8d, 0x8ff4dc
+ },
+ {
+ 0xfb8e, 0x8ff4dd
+ },
+ {
+ 0xfb8f, 0x8fd4d4
+ },
+ {
+ 0xfb90, 0x8fd4f2
+ },
+ {
+ 0xfb91, 0x8fd5ae
+ },
+ {
+ 0xfb92, 0x8ff4de
+ },
+ {
+ 0xfb93, 0x8fd7de
+ },
+ {
+ 0xfb94, 0x8ff4df
+ },
+ {
+ 0xfb95, 0x8fd8a2
+ },
+ {
+ 0xfb96, 0x8fd8b7
+ },
+ {
+ 0xfb97, 0x8fd8c1
+ },
+ {
+ 0xfb98, 0x8fd8d1
+ },
+ {
+ 0xfb99, 0x8fd8f4
+ },
+ {
+ 0xfb9a, 0x8fd9c6
+ },
+ {
+ 0xfb9b, 0x8fd9c8
+ },
+ {
+ 0xfb9c, 0x8fd9d1
+ },
+ {
+ 0xfb9d, 0x8ff4e0
+ },
+ {
+ 0xfb9e, 0x8ff4e1
+ },
+ {
+ 0xfb9f, 0x8ff4e2
+ },
+ {
+ 0xfba0, 0x8ff4e3
+ },
+ {
+ 0xfba1, 0x8ff4e4
+ },
+ {
+ 0xfba2, 0x8fdcd3
+ },
+ {
+ 0xfba3, 0x8fddc8
+ },
+ {
+ 0xfba4, 0x8fddd4
+ },
+ {
+ 0xfba5, 0x8fddea
+ },
+ {
+ 0xfba6, 0x8fddfa
+ },
+ {
+ 0xfba7, 0x8fdea4
+ },
+ {
+ 0xfba8, 0x8fdeb0
+ },
+ {
+ 0xfba9, 0x8ff4e5
+ },
+ {
+ 0xfbaa, 0x8fdeb5
+ },
+ {
+ 0xfbab, 0x8fdecb
+ },
+ {
+ 0xfbac, 0x8ff4e6
+ },
+ {
+ 0xfbad, 0x8fdfb9
+ },
+ {
+ 0xfbae, 0x8ff4e7
+ },
+ {
+ 0xfbaf, 0x8fdfc3
+ },
+ {
+ 0xfbb0, 0x8ff4e8
+ },
+ {
+ 0xfbb1, 0x8ff4e9
+ },
+ {
+ 0xfbb2, 0x8fe0d9
+ },
+ {
+ 0xfbb3, 0x8ff4ea
+ },
+ {
+ 0xfbb4, 0x8ff4eb
+ },
+ {
+ 0xfbb5, 0x8fe1e2
+ },
+ {
+ 0xfbb6, 0x8ff4ec
+ },
+ {
+ 0xfbb7, 0x8ff4ed
+ },
+ {
+ 0xfbb8, 0x8ff4ee
+ },
+ {
+ 0xfbb9, 0x8fe2c7
+ },
+ {
+ 0xfbba, 0x8fe3a8
+ },
+ {
+ 0xfbbb, 0x8fe3a6
+ },
+ {
+ 0xfbbc, 0x8fe3a9
+ },
+ {
+ 0xfbbd, 0x8fe3af
+ },
+ {
+ 0xfbbe, 0x8fe3b0
+ },
+ {
+ 0xfbbf, 0x8fe3aa
+ },
+ {
+ 0xfbc0, 0x8fe3ab
+ },
+ {
+ 0xfbc1, 0x8fe3bc
+ },
+ {
+ 0xfbc2, 0x8fe3c1
+ },
+ {
+ 0xfbc3, 0x8fe3bf
+ },
+ {
+ 0xfbc4, 0x8fe3d5
+ },
+ {
+ 0xfbc5, 0x8fe3d8
+ },
+ {
+ 0xfbc6, 0x8fe3d6
+ },
+ {
+ 0xfbc7, 0x8fe3df
+ },
+ {
+ 0xfbc8, 0x8fe3e3
+ },
+ {
+ 0xfbc9, 0x8fe3e1
+ },
+ {
+ 0xfbca, 0x8fe3d4
+ },
+ {
+ 0xfbcb, 0x8fe3e9
+ },
+ {
+ 0xfbcc, 0x8fe4a6
+ },
+ {
+ 0xfbcd, 0x8fe3f1
+ },
+ {
+ 0xfbce, 0x8fe3f2
+ },
+ {
+ 0xfbcf, 0x8fe4cb
+ },
+ {
+ 0xfbd0, 0x8fe4c1
+ },
+ {
+ 0xfbd1, 0x8fe4c3
+ },
+ {
+ 0xfbd2, 0x8fe4be
+ },
+ {
+ 0xfbd3, 0x8ff4ef
+ },
+ {
+ 0xfbd4, 0x8fe4c0
+ },
+ {
+ 0xfbd5, 0x8fe4c7
+ },
+ {
+ 0xfbd6, 0x8fe4bf
+ },
+ {
+ 0xfbd7, 0x8fe4e0
+ },
+ {
+ 0xfbd8, 0x8fe4de
+ },
+ {
+ 0xfbd9, 0x8fe4d1
+ },
+ {
+ 0xfbda, 0x8ff4f0
+ },
+ {
+ 0xfbdb, 0x8fe4dc
+ },
+ {
+ 0xfbdc, 0x8fe4d2
+ },
+ {
+ 0xfbdd, 0x8fe4db
+ },
+ {
+ 0xfbde, 0x8fe4d4
+ },
+ {
+ 0xfbdf, 0x8fe4fa
+ },
+ {
+ 0xfbe0, 0x8fe4ef
+ },
+ {
+ 0xfbe1, 0x8fe5b3
+ },
+ {
+ 0xfbe2, 0x8fe5bf
+ },
+ {
+ 0xfbe3, 0x8fe5c9
+ },
+ {
+ 0xfbe4, 0x8fe5d0
+ },
+ {
+ 0xfbe5, 0x8fe5e2
+ },
+ {
+ 0xfbe6, 0x8fe5ea
+ },
+ {
+ 0xfbe7, 0x8fe5eb
+ },
+ {
+ 0xfbe8, 0x8ff4f1
+ },
+ {
+ 0xfbe9, 0x8ff4f2
+ },
+ {
+ 0xfbea, 0x8ff4f3
+ },
+ {
+ 0xfbeb, 0x8fe6e8
+ },
+ {
+ 0xfbec, 0x8fe6ef
+ },
+ {
+ 0xfbed, 0x8fe7ac
+ },
+ {
+ 0xfbee, 0x8ff4f4
+ },
+ {
+ 0xfbef, 0x8fe7ae
+ },
+ {
+ 0xfbf0, 0x8ff4f5
+ },
+ {
+ 0xfbf1, 0x8fe7b1
+ },
+ {
+ 0xfbf2, 0x8ff4f6
+ },
+ {
+ 0xfbf3, 0x8fe7b2
+ },
+ {
+ 0xfbf4, 0x8fe8b1
+ },
+ {
+ 0xfbf5, 0x8fe8b6
+ },
+ {
+ 0xfbf6, 0x8ff4f7
+ },
+ {
+ 0xfbf7, 0x8ff4f8
+ },
+ {
+ 0xfbf8, 0x8fe8dd
+ },
+ {
+ 0xfbf9, 0x8ff4f9
+ },
+ {
+ 0xfbfa, 0x8ff4fa
+ },
+ {
+ 0xfbfb, 0x8fe9d1
+ },
+ {
+ 0xfbfc, 0x8ff4fb
+ },
+ {
+ 0xfc40, 0x8fe9ed
+ },
+ {
+ 0xfc41, 0x8feacd
+ },
+ {
+ 0xfc42, 0x8ff4fc
+ },
+ {
+ 0xfc43, 0x8feadb
+ },
+ {
+ 0xfc44, 0x8feae6
+ },
+ {
+ 0xfc45, 0x8feaea
+ },
+ {
+ 0xfc46, 0x8feba5
+ },
+ {
+ 0xfc47, 0x8febfb
+ },
+ {
+ 0xfc48, 0x8febfa
+ },
+ {
+ 0xfc49, 0x8ff4fd
+ },
+ {
+ 0xfc4a, 0x8fecd6
+ },
+ {
+ 0xfc4b, 0x8ff4fe
+ },
+ {
+ 0xffff, 0xffff
+ } /* stop code */
};
/*
@@ -461,8 +1242,10 @@ sjis2mic(unsigned char *sjis, unsigned char *p, int len)
}
else if (c1 > 0x7f)
{
- /* JIS X0208, X0212, user defined extended
- characters */
+
+ /*
+ * JIS X0208, X0212, user defined extended characters
+ */
c2 = *sjis++;
k = (c1 << 8) + c2;
@@ -479,15 +1262,15 @@ sjis2mic(unsigned char *sjis, unsigned char *p, int len)
/* NEC sentei IBM kanji */
*p++ = LC_JISX0208;
*p++ = PGEUCALTCODE >> 8;
- *p++ = PGEUCALTCODE & 0xff;
+ *p++ = PGEUCALTCODE & 0xff;
}
else if (k >= 0xf040 && k < 0xf540)
{
- /* UDC1
- * mapping to X0208 85 ku - 94 ku
- * JIS code 0x7521 - 0x7e7e
- * EUC 0xf5a1 - 0xfefe
- */
+
+ /*
+ * UDC1 mapping to X0208 85 ku - 94 ku JIS code 0x7521 -
+ * 0x7e7e EUC 0xf5a1 - 0xfefe
+ */
len -= 2;
*p++ = LC_JISX0208;
c1 -= 0x6f;
@@ -496,11 +1279,11 @@ sjis2mic(unsigned char *sjis, unsigned char *p, int len)
}
else if (k >= 0xf540 && k < 0xfa40)
{
- /* UDC2
- * mapping to X0212 85 ku - 94 ku
- * JIS code 0x7521 - 0x7e7e
- * EUC 0x8ff5a1 - 0x8ffefe
- */
+
+ /*
+ * UDC2 mapping to X0212 85 ku - 94 ku JIS code 0x7521 -
+ * 0x7e7e EUC 0x8ff5a1 - 0x8ffefe
+ */
len -= 2;
*p++ = LC_JISX0212;
c1 -= 0x74;
@@ -509,28 +1292,36 @@ sjis2mic(unsigned char *sjis, unsigned char *p, int len)
}
else if (k >= 0xfa40)
{
- /* mapping IBM kanji to X0208 and X0212
+
+ /*
+ * mapping IBM kanji to X0208 and X0212
*
*/
- int i,k2;
+ int i,
+ k2;
+
len -= 2;
- for (i=0;;i++) {
- k2 = ibmkanji[i].sjis;
- if (k2 == 0xffff)
- break;
- if (k2 == k) {
- k = ibmkanji[i].euc;
- if (k >= 0x8f0000)
- {
- *p++ = LC_JISX0212;
- *p++ = 0x80 | ((k & 0xff00) >> 8);
- *p++ = 0x80 | (k & 0xff);
- } else {
- *p++ = LC_JISX0208;
- *p++ = 0x80 | (k >> 8);
- *p++ = 0x80 | (k & 0xff);
- }
- }
+ for (i = 0;; i++)
+ {
+ k2 = ibmkanji[i].sjis;
+ if (k2 == 0xffff)
+ break;
+ if (k2 == k)
+ {
+ k = ibmkanji[i].euc;
+ if (k >= 0x8f0000)
+ {
+ *p++ = LC_JISX0212;
+ *p++ = 0x80 | ((k & 0xff00) >> 8);
+ *p++ = 0x80 | (k & 0xff);
+ }
+ else
+ {
+ *p++ = LC_JISX0208;
+ *p++ = 0x80 | (k >> 8);
+ *p++ = 0x80 | (k & 0xff);
+ }
+ }
}
}
}
@@ -571,14 +1362,14 @@ mic2sjis(unsigned char *mic, unsigned char *p, int len)
*p++ = ((c1 - 0xa1) >> 1) + ((c1 < 0xdf) ? 0x81 : 0xc1) + 0x6f;
}
else
- {
*p++ = ((c1 - 0xa1) >> 1) + ((c1 < 0xdf) ? 0x81 : 0xc1);
- }
*p++ = c2 - ((c1 & 1) ? ((c2 < 0xe0) ? 0x61 : 0x60) : 2);
}
else if (c1 == LC_JISX0212)
{
- int i,k2;
+ int i,
+ k2;
+
c1 = *mic++;
c2 = *mic++;
k = c1 << 8 | c2;
@@ -591,21 +1382,24 @@ mic2sjis(unsigned char *mic, unsigned char *p, int len)
}
else
{
- /* IBM kanji */
- for (i=0;;i++) {
- k2 = ibmkanji[i].euc & 0xffff;
- if (k2 == 0xffff) {
- *p++ = PGSJISALTCODE >> 8;
- *p++ = PGSJISALTCODE & 0xff;
- break;
- }
- if (k2 == k) {
- k = ibmkanji[i].sjis;
- *p++ = k >> 8;
- *p++ = k & 0xff;
- break;
- }
- }
+ /* IBM kanji */
+ for (i = 0;; i++)
+ {
+ k2 = ibmkanji[i].euc & 0xffff;
+ if (k2 == 0xffff)
+ {
+ *p++ = PGSJISALTCODE >> 8;
+ *p++ = PGSJISALTCODE & 0xff;
+ break;
+ }
+ if (k2 == k)
+ {
+ k = ibmkanji[i].sjis;
+ *p++ = k >> 8;
+ *p++ = k & 0xff;
+ break;
+ }
+ }
}
}
else if (c1 > 0x7f)
@@ -1081,6 +1875,7 @@ mic2latin4(unsigned char *mic, unsigned char *p, int len)
{
mic2latin(mic, p, len, LC_ISO8859_4);
}
+
#ifdef NOT_USED
static void
latin52mic(unsigned char *l, unsigned char *p, int len)
@@ -1456,6 +2251,7 @@ mic2win1250(unsigned char *mic, unsigned char *p, int len)
mic2latin_with_table(mic, p, len, LC_ISO8859_2, iso88592_2_win1250);
}
+
/*-----------------------------------------------------------------*/
pg_encoding_conv_tbl pg_conv_tbl[] = {
@@ -1483,45 +2279,63 @@ pg_encoding_conv_tbl pg_conv_tbl[] = {
#ifdef DEBUGMAIN
#include "utils/mcxt.h"
/*
- * testing for sjis2mic() and mic2sjis()
+ * testing for sjis2mic() and mic2sjis()
*/
-int main()
+int
+main()
{
- unsigned char eucbuf[1024];
- unsigned char sjisbuf[1024];
- unsigned char sjis[] = {0x81, 0x40, 0xa1, 0xf0, 0x40, 0xf0, 0x9e, 0xf5, 0x40, 0xfa, 0x40, 0xfa, 0x54, 0xfa, 0x7b, 0x00};
-
- int i;
-
- sjis2mic(sjis, eucbuf, 1024);
- for (i=0;i<1024;i++) {
- if (eucbuf[i]) {
- printf("%02x ", eucbuf[i]);
- } else {
- printf("\n");
- break;
- }
- }
-
- mic2sjis(eucbuf, sjisbuf, 1024);
- for (i=0;i<1024;i++) {
- if (sjisbuf[i]) {
- printf("%02x ", sjisbuf[i]);
- } else {
- printf("\n");
- break;
- }
- }
-
- return(0);
+ unsigned char eucbuf[1024];
+ unsigned char sjisbuf[1024];
+ unsigned char sjis[] = {0x81, 0x40, 0xa1, 0xf0, 0x40, 0xf0, 0x9e, 0xf5, 0x40, 0xfa, 0x40, 0xfa, 0x54, 0xfa, 0x7b, 0x00};
+
+ int i;
+
+ sjis2mic(sjis, eucbuf, 1024);
+ for (i = 0; i < 1024; i++)
+ {
+ if (eucbuf[i])
+ printf("%02x ", eucbuf[i]);
+ else
+ {
+ printf("\n");
+ break;
+ }
+ }
+
+ mic2sjis(eucbuf, sjisbuf, 1024);
+ for (i = 0; i < 1024; i++)
+ {
+ if (sjisbuf[i])
+ printf("%02x ", sjisbuf[i]);
+ else
+ {
+ printf("\n");
+ break;
+ }
+ }
+
+ return (0);
}
-void elog(int lev, const char *fmt,...) {};
+void
+elog(int lev, const char *fmt,...)
+{
+};
MemoryContext CurrentMemoryContext;
-Pointer MemoryContextAlloc(MemoryContext context, Size size) {};
-Pointer MemoryContextRealloc(MemoryContext context,
+Pointer
+MemoryContextAlloc(MemoryContext context, Size size)
+{
+};
+Pointer
+MemoryContextRealloc(MemoryContext context,
Pointer pointer,
- Size size) {};
-void MemoryContextFree(MemoryContext context, Pointer pointer) {};
+ Size size)
+{
+};
+void
+MemoryContextFree(MemoryContext context, Pointer pointer)
+{
+};
+
#endif
diff --git a/src/backend/utils/mb/wchar.c b/src/backend/utils/mb/wchar.c
index e1a665ca847..bc576a1789b 100644
--- a/src/backend/utils/mb/wchar.c
+++ b/src/backend/utils/mb/wchar.c
@@ -1,7 +1,7 @@
/*
* conversion functions between pg_wchar and multi-byte streams.
* Tatsuo Ishii
- * $Id: wchar.c,v 1.10 2000/01/25 02:12:27 ishii Exp $
+ * $Id: wchar.c,v 1.11 2000/04/12 17:16:06 momjian Exp $
*
* WIN1250 client encoding updated by Pavel Behal
*
@@ -454,7 +454,7 @@ pg_wchar_tbl pg_wchar_table[] = {
{pg_latin12wchar_with_len, pg_latin1_mblen}, /* 31 */
{0, pg_sjis_mblen}, /* 32 */
{0, pg_big5_mblen}, /* 33 */
- {pg_latin12wchar_with_len, pg_latin1_mblen} /* 34 */
+ {pg_latin12wchar_with_len, pg_latin1_mblen} /* 34 */
};
/* returns the byte length of a word for mule internal code */
diff --git a/src/backend/utils/misc/database.c b/src/backend/utils/misc/database.c
index 05b32ac62e7..64347f00fee 100644
--- a/src/backend/utils/misc/database.c
+++ b/src/backend/utils/misc/database.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/misc/Attic/database.c,v 1.36 2000/03/08 01:46:47 momjian Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/misc/Attic/database.c,v 1.37 2000/04/12 17:16:07 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -42,8 +42,8 @@ ExpandDatabasePath(const char *dbpath)
const char *cp;
int len;
- AssertArg(dbpath);
- Assert(DataDir);
+ AssertArg(dbpath);
+ Assert(DataDir);
if (strlen(dbpath) >= MAXPGPATH)
return NULL; /* ain't gonna fit nohow */
@@ -55,7 +55,7 @@ ExpandDatabasePath(const char *dbpath)
cp = strrchr(dbpath, SEP_CHAR);
len = cp - dbpath;
strncpy(buf, dbpath, len);
- snprintf(&buf[len], MAXPGPATH-len, "%cbase%c%s",
+ snprintf(&buf[len], MAXPGPATH - len, "%cbase%c%s",
SEP_CHAR, SEP_CHAR, (cp + 1));
#else
return NULL;
@@ -64,7 +64,7 @@ ExpandDatabasePath(const char *dbpath)
/* path delimiter somewhere? then has leading environment variable */
else if ((cp = strchr(dbpath, SEP_CHAR)) != NULL)
{
- const char *envvar;
+ const char *envvar;
len = cp - dbpath;
strncpy(buf, dbpath, len);
@@ -83,28 +83,33 @@ ExpandDatabasePath(const char *dbpath)
DataDir, SEP_CHAR, SEP_CHAR, dbpath);
}
- /* check for illegal characters in dbpath
- * these should really throw an error, shouldn't they? or else all callers
- * need to test for NULL */
- for(cp = buf; *cp; cp++)
- {
- /* The following characters will not be allowed anywhere in the database
- path. (Do not include the slash or '.' here.) */
- char illegal_dbpath_chars[] =
- "\001\002\003\004\005\006\007\010"
- "\011\012\013\014\015\016\017\020"
- "\021\022\023\024\025\026\027\030"
- "\031\032\033\034\035\036\037"
- "'`";
-
- const char *cx;
- for (cx = illegal_dbpath_chars; *cx; cx++)
- if (*cp == *cx)
- return NULL;
- /* don't allow access to parent dirs */
- if (strncmp(cp, "/../", 4) == 0 )
- return NULL ;
- }
+ /*
+ * check for illegal characters in dbpath these should really throw an
+ * error, shouldn't they? or else all callers need to test for NULL
+ */
+ for (cp = buf; *cp; cp++)
+ {
+
+ /*
+ * The following characters will not be allowed anywhere in the
+ * database path. (Do not include the slash or '.' here.)
+ */
+ char illegal_dbpath_chars[] =
+ "\001\002\003\004\005\006\007\010"
+ "\011\012\013\014\015\016\017\020"
+ "\021\022\023\024\025\026\027\030"
+ "\031\032\033\034\035\036\037"
+ "'`";
+
+ const char *cx;
+
+ for (cx = illegal_dbpath_chars; *cx; cx++)
+ if (*cp == *cx)
+ return NULL;
+ /* don't allow access to parent dirs */
+ if (strncmp(cp, "/../", 4) == 0)
+ return NULL;
+ }
return pstrdup(buf);
} /* ExpandDatabasePath() */
@@ -197,18 +202,18 @@ GetRawDatabaseInfo(const char *name, Oid *db_id, char *path)
* the log relation by hand, too. Instead we take the
* conservative assumption that if someone tried to delete it,
* it's gone. The other side of the coin is that we might
- * accept a tuple that was stored and never committed. All in
- * all, this code is pretty shaky. We will cross-check our
+ * accept a tuple that was stored and never committed. All in
+ * all, this code is pretty shaky. We will cross-check our
* result in ReverifyMyDatabase() in postinit.c.
*
- * NOTE: if a bogus tuple in pg_database prevents connection
- * to a valid database, a fix is to connect to another database
- * and do "select * from pg_database". That should cause
+ * NOTE: if a bogus tuple in pg_database prevents connection to a
+ * valid database, a fix is to connect to another database and
+ * do "select * from pg_database". That should cause
* committed and dead tuples to be marked with correct states.
*
* XXX wouldn't it be better to let new backends read the
- * database OID from a flat file, handled the same way
- * we handle the password relation?
+ * database OID from a flat file, handled the same way we
+ * handle the password relation?
*/
if (TransactionIdIsValid((TransactionId) tup.t_data->t_xmax))
continue;
diff --git a/src/backend/utils/misc/trace.c b/src/backend/utils/misc/trace.c
index b2ff231d038..69634e1f3f4 100644
--- a/src/backend/utils/misc/trace.c
+++ b/src/backend/utils/misc/trace.c
@@ -50,7 +50,8 @@
* Trace option names, must match the constants in trace_opts[].
*/
static char *opt_names[] = {
- "all", /* 0=trace some, 1=trace all, -1=trace none */
+ "all", /* 0=trace some, 1=trace all, -1=trace
+ * none */
"verbose",
"query",
"plan",
@@ -78,7 +79,7 @@ static char *opt_names[] = {
"hostlookup", /* enable hostname lookup in ps_status */
"showportnumber", /* show port number in ps_status */
- /* NUM_PG_OPTIONS */ /* must be the last item of enum */
+ /* NUM_PG_OPTIONS *//* must be the last item of enum */
};
/*
@@ -95,8 +96,10 @@ tprintf(int flag, const char *fmt,...)
{
va_list ap;
char line[TRACEMSG_MAXLEN + TIMESTAMP_SIZE + 1];
+
#ifdef USE_SYSLOG
int log_level;
+
#endif
if ((flag == TRACE_ALL) || (pg_options[TRACE_ALL] > 0))
@@ -161,6 +164,7 @@ tprintf1(const char *fmt,...)
return 1;
}
+
#endif
/*
@@ -212,6 +216,7 @@ write_syslog(int level, char *line)
syslog(level, "%s", line);
}
}
+
#endif
#ifdef ELOG_TIMESTAMPS
@@ -222,7 +227,7 @@ char *
tprintf_timestamp()
{
struct timeval tv;
- struct timezone tz = { 0, 0 };
+ struct timezone tz = {0, 0};
struct tm *time;
time_t tm;
static char timestamp[32],
@@ -236,10 +241,11 @@ tprintf_timestamp()
sprintf(timestamp, "%02d%02d%02d.%02d:%02d:%02d.%03d %7s ",
time->tm_year % 100, time->tm_mon + 1, time->tm_mday,
time->tm_hour, time->tm_min, time->tm_sec,
- (int) (tv.tv_usec/1000), pid);
+ (int) (tv.tv_usec / 1000), pid);
return timestamp;
}
+
#endif
#ifdef NOT_USED
@@ -260,6 +266,7 @@ set_option_flag(int flag, int value)
pg_options[flag] = value;
return value;
}
+
#endif
/*
@@ -409,13 +416,12 @@ read_pg_options(SIGNAL_ARGS)
void
show_options(void)
{
- int i;
+ int i;
- for (i=0; i<NUM_PG_OPTIONS; i++) {
+ for (i = 0; i < NUM_PG_OPTIONS; i++)
elog(NOTICE, "%s=%d", opt_names[i], pg_options[i]);
- }
}
-
+
/*
* Local variables:
* tab-width: 4
diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c
index 5220ec2d412..4bc96c5a2aa 100644
--- a/src/backend/utils/mmgr/aset.c
+++ b/src/backend/utils/mmgr/aset.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/mmgr/aset.c,v 1.25 2000/03/08 23:42:58 tgl Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/mmgr/aset.c,v 1.26 2000/04/12 17:16:09 momjian Exp $
*
* NOTE:
* This is a new (Feb. 05, 1999) implementation of the allocation set
@@ -43,7 +43,7 @@
/*--------------------
* Chunk freelist k holds chunks of size 1 << (k + ALLOC_MINBITS),
* for k = 0 .. ALLOCSET_NUM_FREELISTS-2.
- * The last freelist holds all larger free chunks. Those chunks come in
+ * The last freelist holds all larger free chunks. Those chunks come in
* varying sizes depending on the request size, whereas smaller chunks are
* coerced to powers of 2 to improve their "recyclability".
*
@@ -261,9 +261,9 @@ AllocSetAlloc(AllocSet set, Size size)
Assert(chunk_size >= size);
/*
- * If there is enough room in the active allocation block, *and*
- * the chunk is less than ALLOC_BIGCHUNK_LIMIT, put the chunk
- * into the active allocation block.
+ * If there is enough room in the active allocation block, *and* the
+ * chunk is less than ALLOC_BIGCHUNK_LIMIT, put the chunk into the
+ * active allocation block.
*/
if ((block = set->blocks) != NULL)
{
@@ -400,8 +400,10 @@ AllocSetFree(AllocSet set, AllocPointer pointer)
if (chunk->size >= ALLOC_BIGCHUNK_LIMIT)
{
- /* Big chunks are certain to have been allocated as single-chunk
- * blocks. Find the containing block and return it to malloc().
+
+ /*
+ * Big chunks are certain to have been allocated as single-chunk
+ * blocks. Find the containing block and return it to malloc().
*/
AllocBlock block = set->blocks;
AllocBlock prevblock = NULL;
@@ -471,10 +473,12 @@ AllocSetRealloc(AllocSet set, AllocPointer pointer, Size size)
if (oldsize >= ALLOC_BIGCHUNK_LIMIT)
{
+
/*
- * If the chunk is already >= bigchunk limit, then it must have been
- * allocated as a single-chunk block. Find the containing block and
- * use realloc() to make it bigger with minimum space wastage.
+ * If the chunk is already >= bigchunk limit, then it must have
+ * been allocated as a single-chunk block. Find the containing
+ * block and use realloc() to make it bigger with minimum space
+ * wastage.
*/
AllocChunk chunk = AllocPointerGetChunk(pointer);
AllocBlock block = set->blocks;
diff --git a/src/backend/utils/mmgr/oset.c b/src/backend/utils/mmgr/oset.c
index 0bb046653f5..86487ab07d3 100644
--- a/src/backend/utils/mmgr/oset.c
+++ b/src/backend/utils/mmgr/oset.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/mmgr/Attic/oset.c,v 1.16 2000/01/26 05:57:31 momjian Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/mmgr/Attic/oset.c,v 1.17 2000/04/12 17:16:10 momjian Exp $
*
* NOTE
* XXX This is a preliminary implementation which lacks fail-fast
@@ -59,6 +59,7 @@ OrderedSetContains(OrderedSet set, OrderedElem elem)
{
return (bool) (elem->set == set && (elem->next || elem->prev));
}
+
#endif
/*
diff --git a/src/backend/utils/mmgr/portalmem.c b/src/backend/utils/mmgr/portalmem.c
index 83bb7b099a7..71e94b7096d 100644
--- a/src/backend/utils/mmgr/portalmem.c
+++ b/src/backend/utils/mmgr/portalmem.c
@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/mmgr/portalmem.c,v 1.35 2000/03/17 02:36:29 tgl Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/mmgr/portalmem.c,v 1.36 2000/04/12 17:16:10 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -411,8 +411,8 @@ PortalNameIsSpecial(char *pname)
{
if (strcmp(pname, VACPNAME) == 0)
return true;
- if (strcmp(pname, TRUNCPNAME) == 0)
- return true;
+ if (strcmp(pname, TRUNCPNAME) == 0)
+ return true;
return false;
}
diff --git a/src/backend/utils/sort/logtape.c b/src/backend/utils/sort/logtape.c
index e6bfbf80b42..654bae71be4 100644
--- a/src/backend/utils/sort/logtape.c
+++ b/src/backend/utils/sort/logtape.c
@@ -7,14 +7,14 @@
* tuplesort.c). Merging is an ideal algorithm for tape devices, but if
* we implement it on disk by creating a separate file for each "tape",
* there is an annoying problem: the peak space usage is at least twice
- * the volume of actual data to be sorted. (This must be so because each
+ * the volume of actual data to be sorted. (This must be so because each
* datum will appear in both the input and output tapes of the final
- * merge pass. For seven-tape polyphase merge, which is otherwise a
+ * merge pass. For seven-tape polyphase merge, which is otherwise a
* pretty good algorithm, peak usage is more like 4x actual data volume.)
*
* We can work around this problem by recognizing that any one tape
* dataset (with the possible exception of the final output) is written
- * and read exactly once in a perfectly sequential manner. Therefore,
+ * and read exactly once in a perfectly sequential manner. Therefore,
* a datum once read will not be required again, and we can recycle its
* space for use by the new tape dataset(s) being generated. In this way,
* the total space usage is essentially just the actual data volume, plus
@@ -59,12 +59,12 @@
* is aborted by elog(ERROR). To avoid confusion, the caller should take
* care that all calls for a single LogicalTapeSet are made in the same
* palloc context.
- *
+ *
* Portions Copyright (c) 1996-2000, PostgreSQL, Inc
* Portions Copyright (c) 1994, Regents of the University of California
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/sort/logtape.c,v 1.4 2000/03/17 02:36:30 tgl Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/sort/logtape.c,v 1.5 2000/04/12 17:16:11 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -78,7 +78,7 @@
* Block indexes are "long"s, so we can fit this many per indirect block.
* NB: we assume this is an exact fit!
*/
-#define BLOCKS_PER_INDIR_BLOCK ((int) (BLCKSZ / sizeof(long)))
+#define BLOCKS_PER_INDIR_BLOCK ((int) (BLCKSZ / sizeof(long)))
/*
* We use a struct like this for each active indirection level of each
@@ -91,8 +91,10 @@
typedef struct IndirectBlock
{
int nextSlot; /* next pointer slot to write or read */
- struct IndirectBlock *nextup; /* parent indirect level, or NULL if top */
- long ptrs[BLOCKS_PER_INDIR_BLOCK]; /* indexes of contained blocks */
+ struct IndirectBlock *nextup; /* parent indirect level, or NULL
+ * if top */
+ long ptrs[BLOCKS_PER_INDIR_BLOCK]; /* indexes of contained
+ * blocks */
} IndirectBlock;
/*
@@ -105,23 +107,26 @@ typedef struct LogicalTape
{
IndirectBlock *indirect; /* bottom of my indirect-block hierarchy */
bool writing; /* T while in write phase */
- bool frozen; /* T if blocks should not be freed when read */
+ bool frozen; /* T if blocks should not be freed when
+ * read */
bool dirty; /* does buffer need to be written? */
+
/*
* The total data volume in the logical tape is numFullBlocks * BLCKSZ
- * + lastBlockBytes. BUT: we do not update lastBlockBytes during writing,
- * only at completion of a write phase.
+ * + lastBlockBytes. BUT: we do not update lastBlockBytes during
+ * writing, only at completion of a write phase.
*/
long numFullBlocks; /* number of complete blocks in log tape */
- int lastBlockBytes; /* valid bytes in last (incomplete) block */
+ int lastBlockBytes; /* valid bytes in last (incomplete) block */
+
/*
* Buffer for current data block. Note we don't bother to store the
* actual file block number of the data block (during the write phase
- * it hasn't been assigned yet, and during read we don't care anymore).
- * But we do need the relative block number so we can detect end-of-tape
- * while reading.
+ * it hasn't been assigned yet, and during read we don't care
+ * anymore). But we do need the relative block number so we can detect
+ * end-of-tape while reading.
*/
- long curBlockNumber; /* this block's logical blk# within tape */
+ long curBlockNumber; /* this block's logical blk# within tape */
int pos; /* next read/write position in buffer */
int nbytes; /* total # of valid bytes in buffer */
char buffer[BLCKSZ];
@@ -135,17 +140,21 @@ typedef struct LogicalTape
*/
struct LogicalTapeSet
{
- BufFile *pfile; /* underlying file for whole tape set */
+ BufFile *pfile; /* underlying file for whole tape set */
long nFileBlocks; /* # of blocks used in underlying file */
+
/*
- * We store the numbers of recycled-and-available blocks in freeBlocks[].
- * When there are no such blocks, we extend the underlying file. Note
- * that the block numbers in freeBlocks are always in *decreasing* order,
- * so that removing the last entry gives us the lowest free block.
+ * We store the numbers of recycled-and-available blocks in
+ * freeBlocks[]. When there are no such blocks, we extend the
+ * underlying file. Note that the block numbers in freeBlocks are
+ * always in *decreasing* order, so that removing the last entry gives
+ * us the lowest free block.
*/
long *freeBlocks; /* resizable array */
int nFreeBlocks; /* # of currently free blocks */
- int freeBlocksLen; /* current allocated length of freeBlocks[] */
+ int freeBlocksLen; /* current allocated length of
+ * freeBlocks[] */
+
/*
* tapes[] is declared size 1 since C wants a fixed size, but actually
* it is of length nTapes.
@@ -159,17 +168,17 @@ static void ltsReadBlock(LogicalTapeSet *lts, long blocknum, void *buffer);
static long ltsGetFreeBlock(LogicalTapeSet *lts);
static void ltsReleaseBlock(LogicalTapeSet *lts, long blocknum);
static void ltsRecordBlockNum(LogicalTapeSet *lts, IndirectBlock *indirect,
- long blocknum);
+ long blocknum);
static long ltsRewindIndirectBlock(LogicalTapeSet *lts,
- IndirectBlock *indirect,
- bool freezing);
+ IndirectBlock *indirect,
+ bool freezing);
static long ltsRewindFrozenIndirectBlock(LogicalTapeSet *lts,
- IndirectBlock *indirect);
+ IndirectBlock *indirect);
static long ltsRecallNextBlockNum(LogicalTapeSet *lts,
- IndirectBlock *indirect,
- bool frozen);
+ IndirectBlock *indirect,
+ bool frozen);
static long ltsRecallPrevBlockNum(LogicalTapeSet *lts,
- IndirectBlock *indirect);
+ IndirectBlock *indirect);
static void ltsDumpBuffer(LogicalTapeSet *lts, LogicalTape *lt);
@@ -194,7 +203,7 @@ ltsWriteBlock(LogicalTapeSet *lts, long blocknum, void *buffer)
/*
* Read a block-sized buffer from the specified block of the underlying file.
*
- * No need for an error return convention; we elog() on any error. This
+ * No need for an error return convention; we elog() on any error. This
* module should never attempt to read a block it doesn't know is there.
*/
static void
@@ -215,9 +224,11 @@ ltsReadBlock(LogicalTapeSet *lts, long blocknum, void *buffer)
static long
ltsGetFreeBlock(LogicalTapeSet *lts)
{
- /* If there are multiple free blocks, we select the one appearing last
- * in freeBlocks[]. If there are none, assign the next block at the end
- * of the file.
+
+ /*
+ * If there are multiple free blocks, we select the one appearing last
+ * in freeBlocks[]. If there are none, assign the next block at the
+ * end of the file.
*/
if (lts->nFreeBlocks > 0)
return lts->freeBlocks[--lts->nFreeBlocks];
@@ -231,8 +242,8 @@ ltsGetFreeBlock(LogicalTapeSet *lts)
static void
ltsReleaseBlock(LogicalTapeSet *lts, long blocknum)
{
- int ndx;
- long *ptr;
+ int ndx;
+ long *ptr;
/*
* Enlarge freeBlocks array if full.
@@ -241,13 +252,14 @@ ltsReleaseBlock(LogicalTapeSet *lts, long blocknum)
{
lts->freeBlocksLen *= 2;
lts->freeBlocks = (long *) repalloc(lts->freeBlocks,
- lts->freeBlocksLen * sizeof(long));
+ lts->freeBlocksLen * sizeof(long));
}
+
/*
* Insert blocknum into array, preserving decreasing order (so that
- * ltsGetFreeBlock returns the lowest available block number).
- * This could get fairly slow if there were many free blocks, but
- * we don't expect there to be very many at one time.
+ * ltsGetFreeBlock returns the lowest available block number). This
+ * could get fairly slow if there were many free blocks, but we don't
+ * expect there to be very many at one time.
*/
ndx = lts->nFreeBlocks++;
ptr = lts->freeBlocks + ndx;
@@ -274,12 +286,13 @@ ltsRecordBlockNum(LogicalTapeSet *lts, IndirectBlock *indirect,
{
if (indirect->nextSlot >= BLOCKS_PER_INDIR_BLOCK)
{
+
/*
* This indirect block is full, so dump it out and recursively
- * save its address in the next indirection level. Create a
- * new indirection level if there wasn't one before.
+ * save its address in the next indirection level. Create a new
+ * indirection level if there wasn't one before.
*/
- long indirblock = ltsGetFreeBlock(lts);
+ long indirblock = ltsGetFreeBlock(lts);
ltsWriteBlock(lts, indirblock, (void *) indirect->ptrs);
if (indirect->nextup == NULL)
@@ -289,6 +302,7 @@ ltsRecordBlockNum(LogicalTapeSet *lts, IndirectBlock *indirect,
indirect->nextup->nextup = NULL;
}
ltsRecordBlockNum(lts, indirect->nextup, indirblock);
+
/*
* Reset to fill another indirect block at this level.
*/
@@ -299,7 +313,7 @@ ltsRecordBlockNum(LogicalTapeSet *lts, IndirectBlock *indirect,
/*
* Reset a logical tape's indirect-block hierarchy after a write pass
- * to prepare for reading. We dump out partly-filled blocks except
+ * to prepare for reading. We dump out partly-filled blocks except
* at the top of the hierarchy, and we rewind each level to the start.
* This call returns the first data block number, or -1L if the tape
* is empty.
@@ -315,22 +329,24 @@ ltsRewindIndirectBlock(LogicalTapeSet *lts,
/* Insert sentinel if block is not full */
if (indirect->nextSlot < BLOCKS_PER_INDIR_BLOCK)
indirect->ptrs[indirect->nextSlot] = -1L;
+
/*
* If block is not topmost, write it out, and recurse to obtain
- * address of first block in this hierarchy level. Read that one in.
+ * address of first block in this hierarchy level. Read that one in.
*/
if (indirect->nextup != NULL)
{
- long indirblock = ltsGetFreeBlock(lts);
+ long indirblock = ltsGetFreeBlock(lts);
ltsWriteBlock(lts, indirblock, (void *) indirect->ptrs);
ltsRecordBlockNum(lts, indirect->nextup, indirblock);
indirblock = ltsRewindIndirectBlock(lts, indirect->nextup, freezing);
Assert(indirblock != -1L);
ltsReadBlock(lts, indirblock, (void *) indirect->ptrs);
- if (! freezing)
+ if (!freezing)
ltsReleaseBlock(lts, indirblock);
}
+
/*
* Reset my next-block pointer, and then fetch a block number if any.
*/
@@ -349,18 +365,20 @@ static long
ltsRewindFrozenIndirectBlock(LogicalTapeSet *lts,
IndirectBlock *indirect)
{
+
/*
- * If block is not topmost, recurse to obtain
- * address of first block in this hierarchy level. Read that one in.
+ * If block is not topmost, recurse to obtain address of first block
+ * in this hierarchy level. Read that one in.
*/
if (indirect->nextup != NULL)
{
- long indirblock;
+ long indirblock;
indirblock = ltsRewindFrozenIndirectBlock(lts, indirect->nextup);
Assert(indirblock != -1L);
ltsReadBlock(lts, indirblock, (void *) indirect->ptrs);
}
+
/*
* Reset my next-block pointer, and then fetch a block number if any.
*/
@@ -384,7 +402,7 @@ ltsRecallNextBlockNum(LogicalTapeSet *lts,
if (indirect->nextSlot >= BLOCKS_PER_INDIR_BLOCK ||
indirect->ptrs[indirect->nextSlot] == -1L)
{
- long indirblock;
+ long indirblock;
if (indirect->nextup == NULL)
return -1L; /* nothing left at this level */
@@ -392,7 +410,7 @@ ltsRecallNextBlockNum(LogicalTapeSet *lts,
if (indirblock == -1L)
return -1L; /* nothing left at this level */
ltsReadBlock(lts, indirblock, (void *) indirect->ptrs);
- if (! frozen)
+ if (!frozen)
ltsReleaseBlock(lts, indirblock);
indirect->nextSlot = 0;
}
@@ -416,7 +434,7 @@ ltsRecallPrevBlockNum(LogicalTapeSet *lts,
{
if (indirect->nextSlot <= 1)
{
- long indirblock;
+ long indirblock;
if (indirect->nextup == NULL)
return -1L; /* nothing left at this level */
@@ -424,13 +442,15 @@ ltsRecallPrevBlockNum(LogicalTapeSet *lts,
if (indirblock == -1L)
return -1L; /* nothing left at this level */
ltsReadBlock(lts, indirblock, (void *) indirect->ptrs);
- /* The previous block would only have been written out if full,
- * so we need not search it for a -1 sentinel.
+
+ /*
+ * The previous block would only have been written out if full, so
+ * we need not search it for a -1 sentinel.
*/
- indirect->nextSlot = BLOCKS_PER_INDIR_BLOCK+1;
+ indirect->nextSlot = BLOCKS_PER_INDIR_BLOCK + 1;
}
indirect->nextSlot--;
- return indirect->ptrs[indirect->nextSlot-1];
+ return indirect->ptrs[indirect->nextSlot - 1];
}
@@ -443,8 +463,8 @@ LogicalTapeSet *
LogicalTapeSetCreate(int ntapes)
{
LogicalTapeSet *lts;
- LogicalTape *lt;
- int i;
+ LogicalTape *lt;
+ int i;
/*
* Create top-level struct. First LogicalTape pointer is already
@@ -452,13 +472,14 @@ LogicalTapeSetCreate(int ntapes)
*/
Assert(ntapes > 0);
lts = (LogicalTapeSet *) palloc(sizeof(LogicalTapeSet) +
- (ntapes-1) * sizeof(LogicalTape *));
+ (ntapes - 1) *sizeof(LogicalTape *));
lts->pfile = BufFileCreateTemp();
lts->nFileBlocks = 0L;
lts->freeBlocksLen = 32; /* reasonable initial guess */
lts->freeBlocks = (long *) palloc(lts->freeBlocksLen * sizeof(long));
lts->nFreeBlocks = 0;
lts->nTapes = ntapes;
+
/*
* Create per-tape structs, including first-level indirect blocks.
*/
@@ -484,12 +505,13 @@ LogicalTapeSetCreate(int ntapes)
/*
* Close a logical tape set and release all resources.
*/
-void LogicalTapeSetClose(LogicalTapeSet *lts)
+void
+LogicalTapeSetClose(LogicalTapeSet *lts)
{
- LogicalTape *lt;
- IndirectBlock *ib,
- *nextib;
- int i;
+ LogicalTape *lt;
+ IndirectBlock *ib,
+ *nextib;
+ int i;
BufFileClose(lts->pfile);
for (i = 0; i < lts->nTapes; i++)
@@ -512,7 +534,7 @@ void LogicalTapeSetClose(LogicalTapeSet *lts)
static void
ltsDumpBuffer(LogicalTapeSet *lts, LogicalTape *lt)
{
- long datablock = ltsGetFreeBlock(lts);
+ long datablock = ltsGetFreeBlock(lts);
Assert(lt->dirty);
ltsWriteBlock(lts, datablock, (void *) lt->buffer);
@@ -530,8 +552,8 @@ void
LogicalTapeWrite(LogicalTapeSet *lts, int tapenum,
void *ptr, size_t size)
{
- LogicalTape *lt;
- size_t nthistime;
+ LogicalTape *lt;
+ size_t nthistime;
Assert(tapenum >= 0 && tapenum < lts->nTapes);
lt = lts->tapes[tapenum];
@@ -543,9 +565,7 @@ LogicalTapeWrite(LogicalTapeSet *lts, int tapenum,
{
/* Buffer full, dump it out */
if (lt->dirty)
- {
ltsDumpBuffer(lts, lt);
- }
else
{
/* Hmm, went directly from reading to writing? */
@@ -582,20 +602,21 @@ LogicalTapeWrite(LogicalTapeSet *lts, int tapenum,
void
LogicalTapeRewind(LogicalTapeSet *lts, int tapenum, bool forWrite)
{
- LogicalTape *lt;
- long datablocknum;
+ LogicalTape *lt;
+ long datablocknum;
Assert(tapenum >= 0 && tapenum < lts->nTapes);
lt = lts->tapes[tapenum];
- if (! forWrite)
+ if (!forWrite)
{
if (lt->writing)
{
+
/*
* Completion of a write phase. Flush last partial data
- * block, flush any partial indirect blocks, rewind for
- * normal (destructive) read.
+ * block, flush any partial indirect blocks, rewind for normal
+ * (destructive) read.
*/
if (lt->dirty)
ltsDumpBuffer(lts, lt);
@@ -605,6 +626,7 @@ LogicalTapeRewind(LogicalTapeSet *lts, int tapenum, bool forWrite)
}
else
{
+
/*
* This is only OK if tape is frozen; we rewind for (another)
* read pass.
@@ -619,7 +641,7 @@ LogicalTapeRewind(LogicalTapeSet *lts, int tapenum, bool forWrite)
if (datablocknum != -1L)
{
ltsReadBlock(lts, datablocknum, (void *) lt->buffer);
- if (! lt->frozen)
+ if (!lt->frozen)
ltsReleaseBlock(lts, datablocknum);
lt->nbytes = (lt->curBlockNumber < lt->numFullBlocks) ?
BLCKSZ : lt->lastBlockBytes;
@@ -627,18 +649,19 @@ LogicalTapeRewind(LogicalTapeSet *lts, int tapenum, bool forWrite)
}
else
{
+
/*
- * Completion of a read phase. Rewind and prepare for write.
+ * Completion of a read phase. Rewind and prepare for write.
*
- * NOTE: we assume the caller has read the tape to the end;
- * otherwise untouched data and indirect blocks will not have
- * been freed. We could add more code to free any unread blocks,
- * but in current usage of this module it'd be useless code.
+ * NOTE: we assume the caller has read the tape to the end; otherwise
+ * untouched data and indirect blocks will not have been freed. We
+ * could add more code to free any unread blocks, but in current
+ * usage of this module it'd be useless code.
*/
- IndirectBlock *ib,
- *nextib;
+ IndirectBlock *ib,
+ *nextib;
- Assert(! lt->writing && ! lt->frozen);
+ Assert(!lt->writing && !lt->frozen);
/* Must truncate the indirect-block hierarchy down to one level. */
for (ib = lt->indirect->nextup; ib != NULL; ib = nextib)
{
@@ -666,28 +689,28 @@ size_t
LogicalTapeRead(LogicalTapeSet *lts, int tapenum,
void *ptr, size_t size)
{
- LogicalTape *lt;
- size_t nread = 0;
- size_t nthistime;
+ LogicalTape *lt;
+ size_t nread = 0;
+ size_t nthistime;
Assert(tapenum >= 0 && tapenum < lts->nTapes);
lt = lts->tapes[tapenum];
- Assert(! lt->writing);
+ Assert(!lt->writing);
while (size > 0)
{
if (lt->pos >= lt->nbytes)
{
/* Try to load more data into buffer. */
- long datablocknum = ltsRecallNextBlockNum(lts, lt->indirect,
- lt->frozen);
+ long datablocknum = ltsRecallNextBlockNum(lts, lt->indirect,
+ lt->frozen);
if (datablocknum == -1L)
break; /* EOF */
lt->curBlockNumber++;
lt->pos = 0;
ltsReadBlock(lts, datablocknum, (void *) lt->buffer);
- if (! lt->frozen)
+ if (!lt->frozen)
ltsReleaseBlock(lts, datablocknum);
lt->nbytes = (lt->curBlockNumber < lt->numFullBlocks) ?
BLCKSZ : lt->lastBlockBytes;
@@ -719,23 +742,22 @@ LogicalTapeRead(LogicalTapeSet *lts, int tapenum,
*
* This *must* be called just at the end of a write pass, before the
* tape is rewound (after rewind is too late!). It performs a rewind
- * and switch to read mode "for free". An immediately following rewind-
+ * and switch to read mode "for free". An immediately following rewind-
* for-read call is OK but not necessary.
*/
void
LogicalTapeFreeze(LogicalTapeSet *lts, int tapenum)
{
- LogicalTape *lt;
- long datablocknum;
+ LogicalTape *lt;
+ long datablocknum;
Assert(tapenum >= 0 && tapenum < lts->nTapes);
lt = lts->tapes[tapenum];
Assert(lt->writing);
/*
- * Completion of a write phase. Flush last partial data
- * block, flush any partial indirect blocks, rewind for
- * nondestructive read.
+ * Completion of a write phase. Flush last partial data block, flush
+ * any partial indirect blocks, rewind for nondestructive read.
*/
if (lt->dirty)
ltsDumpBuffer(lts, lt);
@@ -756,7 +778,7 @@ LogicalTapeFreeze(LogicalTapeSet *lts, int tapenum)
}
/*
- * Backspace the tape a given number of bytes. (We also support a more
+ * Backspace the tape a given number of bytes. (We also support a more
* general seek interface, see below.)
*
* *Only* a frozen-for-read tape can be backed up; we don't support
@@ -769,9 +791,9 @@ LogicalTapeFreeze(LogicalTapeSet *lts, int tapenum)
bool
LogicalTapeBackspace(LogicalTapeSet *lts, int tapenum, size_t size)
{
- LogicalTape *lt;
- long nblocks;
- int newpos;
+ LogicalTape *lt;
+ long nblocks;
+ int newpos;
Assert(tapenum >= 0 && tapenum < lts->nTapes);
lt = lts->tapes[tapenum];
@@ -785,6 +807,7 @@ LogicalTapeBackspace(LogicalTapeSet *lts, int tapenum, size_t size)
lt->pos -= (int) size;
return true;
}
+
/*
* Not-so-easy case. Figure out whether it's possible at all.
*/
@@ -800,14 +823,15 @@ LogicalTapeBackspace(LogicalTapeSet *lts, int tapenum, size_t size)
newpos = 0;
if (nblocks > lt->curBlockNumber)
return false; /* a seek too far... */
+
/*
- * OK, we need to back up nblocks blocks. This implementation
- * would be pretty inefficient for long seeks, but we really
- * aren't expecting that (a seek over one tuple is typical).
+ * OK, we need to back up nblocks blocks. This implementation would
+ * be pretty inefficient for long seeks, but we really aren't
+ * expecting that (a seek over one tuple is typical).
*/
while (nblocks-- > 0)
{
- long datablocknum = ltsRecallPrevBlockNum(lts, lt->indirect);
+ long datablocknum = ltsRecallPrevBlockNum(lts, lt->indirect);
if (datablocknum == -1L)
elog(ERROR, "LogicalTapeBackspace: unexpected end of tape");
@@ -834,7 +858,7 @@ bool
LogicalTapeSeek(LogicalTapeSet *lts, int tapenum,
long blocknum, int offset)
{
- LogicalTape *lt;
+ LogicalTape *lt;
Assert(tapenum >= 0 && tapenum < lts->nTapes);
lt = lts->tapes[tapenum];
@@ -849,20 +873,22 @@ LogicalTapeSeek(LogicalTapeSet *lts, int tapenum,
lt->pos = offset;
return true;
}
+
/*
* Not-so-easy case. Figure out whether it's possible at all.
*/
if (blocknum < 0 || blocknum > lt->numFullBlocks ||
(blocknum == lt->numFullBlocks && offset > lt->lastBlockBytes))
return false;
+
/*
- * OK, advance or back up to the target block. This implementation
- * would be pretty inefficient for long seeks, but we really
- * aren't expecting that (a seek over one tuple is typical).
+ * OK, advance or back up to the target block. This implementation
+ * would be pretty inefficient for long seeks, but we really aren't
+ * expecting that (a seek over one tuple is typical).
*/
while (lt->curBlockNumber > blocknum)
{
- long datablocknum = ltsRecallPrevBlockNum(lts, lt->indirect);
+ long datablocknum = ltsRecallPrevBlockNum(lts, lt->indirect);
if (datablocknum == -1L)
elog(ERROR, "LogicalTapeSeek: unexpected end of tape");
@@ -871,8 +897,8 @@ LogicalTapeSeek(LogicalTapeSet *lts, int tapenum,
}
while (lt->curBlockNumber < blocknum)
{
- long datablocknum = ltsRecallNextBlockNum(lts, lt->indirect,
- lt->frozen);
+ long datablocknum = ltsRecallNextBlockNum(lts, lt->indirect,
+ lt->frozen);
if (datablocknum == -1L)
elog(ERROR, "LogicalTapeSeek: unexpected end of tape");
@@ -889,13 +915,13 @@ LogicalTapeSeek(LogicalTapeSet *lts, int tapenum,
* Obtain current position in a form suitable for a later LogicalTapeSeek.
*
* NOTE: it'd be OK to do this during write phase with intention of using
- * the position for a seek after freezing. Not clear if anyone needs that.
+ * the position for a seek after freezing. Not clear if anyone needs that.
*/
void
LogicalTapeTell(LogicalTapeSet *lts, int tapenum,
long *blocknum, int *offset)
{
- LogicalTape *lt;
+ LogicalTape *lt;
Assert(tapenum >= 0 && tapenum < lts->nTapes);
lt = lts->tapes[tapenum];
diff --git a/src/backend/utils/sort/tuplesort.c b/src/backend/utils/sort/tuplesort.c
index 852e5cf41b3..154efd1080e 100644
--- a/src/backend/utils/sort/tuplesort.c
+++ b/src/backend/utils/sort/tuplesort.c
@@ -6,7 +6,7 @@
* This module handles sorting of heap tuples, index tuples, or single
* Datums (and could easily support other kinds of sortable objects,
* if necessary). It works efficiently for both small and large amounts
- * of data. Small amounts are sorted in-memory using qsort(). Large
+ * of data. Small amounts are sorted in-memory using qsort(). Large
* amounts are sorted using temporary files and a standard external sort
* algorithm.
*
@@ -31,7 +31,7 @@
* no more records of the prior run are left in the heap.
*
* The (approximate) amount of memory allowed for any one sort operation
- * is given in kilobytes by the external variable SortMem. Initially,
+ * is given in kilobytes by the external variable SortMem. Initially,
* we absorb tuples and simply store them in an unsorted array as long as
* we haven't exceeded SortMem. If we reach the end of the input without
* exceeding SortMem, we sort the array using qsort() and subsequently return
@@ -40,7 +40,7 @@
* into sorted runs in temporary tapes, emitting just enough tuples at each
* step to get back within the SortMem limit. Whenever the run number at
* the top of the heap changes, we begin a new run with a new output tape
- * (selected per Algorithm D). After the end of the input is reached,
+ * (selected per Algorithm D). After the end of the input is reached,
* we dump out remaining tuples in memory into a final run (or two),
* then merge the runs using Algorithm D.
*
@@ -57,17 +57,17 @@
* access at all, defeating the read-ahead methods used by most Unix kernels.
* Worse, the output tape gets written into a very random sequence of blocks
* of the temp file, ensuring that things will be even worse when it comes
- * time to read that tape. A straightforward merge pass thus ends up doing a
+ * time to read that tape. A straightforward merge pass thus ends up doing a
* lot of waiting for disk seeks. We can improve matters by prereading from
* each source tape sequentially, loading about SortMem/M bytes from each tape
* in turn. Then we run the merge algorithm, writing but not reading until
- * one of the preloaded tuple series runs out. Then we switch back to preread
+ * one of the preloaded tuple series runs out. Then we switch back to preread
* mode, fill memory again, and repeat. This approach helps to localize both
* read and write accesses.
*
* When the caller requests random access to the sort result, we form
* the final sorted run on a logical tape which is then "frozen", so
- * that we can access it randomly. When the caller does not need random
+ * that we can access it randomly. When the caller does not need random
* access, we return from tuplesort_performsort() as soon as we are down
* to one run per logical tape. The final merge is then performed
* on-the-fly as the caller repeatedly calls tuplesort_gettuple; this
@@ -78,7 +78,7 @@
* Portions Copyright (c) 1994, Regents of the University of California
*
* IDENTIFICATION
- * $Header: /cvsroot/pgsql/src/backend/utils/sort/tuplesort.c,v 1.8 2000/03/17 02:36:31 tgl Exp $
+ * $Header: /cvsroot/pgsql/src/backend/utils/sort/tuplesort.c,v 1.9 2000/04/12 17:16:12 momjian Exp $
*
*-------------------------------------------------------------------------
*/
@@ -99,18 +99,19 @@
*/
typedef enum
{
- TSS_INITIAL, /* Loading tuples; still within memory limit */
- TSS_BUILDRUNS, /* Loading tuples; writing to tape */
- TSS_SORTEDINMEM, /* Sort completed entirely in memory */
- TSS_SORTEDONTAPE, /* Sort completed, final run is on tape */
- TSS_FINALMERGE /* Performing final merge on-the-fly */
+ TSS_INITIAL, /* Loading tuples; still within memory
+ * limit */
+ TSS_BUILDRUNS, /* Loading tuples; writing to tape */
+ TSS_SORTEDINMEM, /* Sort completed entirely in memory */
+ TSS_SORTEDONTAPE, /* Sort completed, final run is on tape */
+ TSS_FINALMERGE /* Performing final merge on-the-fly */
} TupSortStatus;
/*
* We use a seven-tape polyphase merge, which is the "sweet spot" on the
* tapes-to-passes curve according to Knuth's figure 70 (section 5.4.2).
*/
-#define MAXTAPES 7 /* Knuth's T */
+#define MAXTAPES 7 /* Knuth's T */
#define TAPERANGE (MAXTAPES-1) /* Knuth's P */
/*
@@ -121,54 +122,59 @@ struct Tuplesortstate
TupSortStatus status; /* enumerated value as shown above */
bool randomAccess; /* did caller request random access? */
long availMem; /* remaining memory available, in bytes */
- LogicalTapeSet *tapeset; /* logtape.c object for tapes in a temp file */
+ LogicalTapeSet *tapeset; /* logtape.c object for tapes in a temp
+ * file */
/*
- * These function pointers decouple the routines that must know what kind
- * of tuple we are sorting from the routines that don't need to know it.
- * They are set up by the tuplesort_begin_xxx routines.
+ * These function pointers decouple the routines that must know what
+ * kind of tuple we are sorting from the routines that don't need to
+ * know it. They are set up by the tuplesort_begin_xxx routines.
*
- * Function to compare two tuples; result is per qsort() convention,
- * ie, <0, 0, >0 according as a<b, a=b, a>b.
+ * Function to compare two tuples; result is per qsort() convention, ie,
+ * <0, 0, >0 according as a<b, a=b, a>b.
*/
- int (*comparetup) (Tuplesortstate *state, const void *a, const void *b);
+ int (*comparetup) (Tuplesortstate *state, const void *a, const void *b);
+
/*
- * Function to copy a supplied input tuple into palloc'd space.
- * (NB: we assume that a single pfree() is enough to release the tuple
+ * Function to copy a supplied input tuple into palloc'd space. (NB:
+ * we assume that a single pfree() is enough to release the tuple
* later, so the representation must be "flat" in one palloc chunk.)
* state->availMem must be decreased by the amount of space used.
*/
- void * (*copytup) (Tuplesortstate *state, void *tup);
+ void *(*copytup) (Tuplesortstate *state, void *tup);
+
/*
- * Function to write a stored tuple onto tape. The representation of
- * the tuple on tape need not be the same as it is in memory; requirements
- * on the tape representation are given below. After writing the tuple,
- * pfree() it, and increase state->availMem by the amount of memory space
- * thereby released.
+ * Function to write a stored tuple onto tape. The representation of
+ * the tuple on tape need not be the same as it is in memory;
+ * requirements on the tape representation are given below. After
+ * writing the tuple, pfree() it, and increase state->availMem by the
+ * amount of memory space thereby released.
*/
- void (*writetup) (Tuplesortstate *state, int tapenum, void *tup);
+ void (*writetup) (Tuplesortstate *state, int tapenum, void *tup);
+
/*
- * Function to read a stored tuple from tape back into memory.
- * 'len' is the already-read length of the stored tuple. Create and
- * return a palloc'd copy, and decrease state->availMem by the amount
- * of memory space consumed.
+ * Function to read a stored tuple from tape back into memory. 'len'
+ * is the already-read length of the stored tuple. Create and return
+ * a palloc'd copy, and decrease state->availMem by the amount of
+ * memory space consumed.
*/
- void * (*readtup) (Tuplesortstate *state, int tapenum, unsigned int len);
+ void *(*readtup) (Tuplesortstate *state, int tapenum, unsigned int len);
+
/*
- * Obtain memory space occupied by a stored tuple. (This routine is
+ * Obtain memory space occupied by a stored tuple. (This routine is
* only needed in the FINALMERGE case, since copytup, writetup, and
* readtup are expected to adjust availMem appropriately.)
*/
unsigned int (*tuplesize) (Tuplesortstate *state, void *tup);
/*
- * This array holds pointers to tuples in sort memory. If we are in
+ * This array holds pointers to tuples in sort memory. If we are in
* state INITIAL, the tuples are in no particular order; if we are in
* state SORTEDINMEM, the tuples are in final sorted order; in states
* BUILDRUNS and FINALMERGE, the tuples are organized in "heap" order
- * per Algorithm H. (Note that memtupcount only counts the tuples that
- * are part of the heap --- during merge passes, memtuples[] entries
- * beyond TAPERANGE are never in the heap and are used to hold
+ * per Algorithm H. (Note that memtupcount only counts the tuples
+ * that are part of the heap --- during merge passes, memtuples[]
+ * entries beyond TAPERANGE are never in the heap and are used to hold
* pre-read tuples.) In state SORTEDONTAPE, the array is not used.
*/
void **memtuples; /* array of pointers to palloc'd tuples */
@@ -176,19 +182,21 @@ struct Tuplesortstate
int memtupsize; /* allocated length of memtuples array */
/*
- * While building initial runs, this array holds the run number for each
- * tuple in memtuples[]. During merge passes, we re-use it to hold the
- * input tape number that each tuple in the heap was read from, or to hold
- * the index of the next tuple pre-read from the same tape in the case of
- * pre-read entries. This array is never allocated unless we need to use
- * tapes. Whenever it is allocated, it has the same length as
- * memtuples[].
+ * While building initial runs, this array holds the run number for
+ * each tuple in memtuples[]. During merge passes, we re-use it to
+ * hold the input tape number that each tuple in the heap was read
+ * from, or to hold the index of the next tuple pre-read from the same
+ * tape in the case of pre-read entries. This array is never
+ * allocated unless we need to use tapes. Whenever it is allocated,
+ * it has the same length as memtuples[].
*/
- int *memtupindex; /* index value associated with memtuples[i] */
+ int *memtupindex; /* index value associated with
+ * memtuples[i] */
/*
* While building initial runs, this is the current output run number
- * (starting at 0). Afterwards, it is the number of initial runs we made.
+ * (starting at 0). Afterwards, it is the number of initial runs we
+ * made.
*/
int currentRun;
@@ -199,20 +207,24 @@ struct Tuplesortstate
* index of the next pre-read tuple (next to be loaded into the heap)
* for tape i, or 0 if we are out of pre-read tuples. mergelast[i]
* similarly points to the last pre-read tuple from each tape.
- * mergeavailmem[i] is the amount of unused space allocated for tape i.
- * mergefreelist and mergefirstfree keep track of unused locations
+ * mergeavailmem[i] is the amount of unused space allocated for tape
+ * i. mergefreelist and mergefirstfree keep track of unused locations
* in the memtuples[] array. memtupindex[] links together pre-read
- * tuples for each tape as well as recycled locations in mergefreelist.
- * It is OK to use 0 as a null link in these lists, because memtuples[0]
- * is part of the merge heap and is never a pre-read tuple.
+ * tuples for each tape as well as recycled locations in
+ * mergefreelist. It is OK to use 0 as a null link in these lists,
+ * because memtuples[0] is part of the merge heap and is never a
+ * pre-read tuple.
*/
- bool mergeactive[MAXTAPES]; /* Active input run source? */
- int mergenext[MAXTAPES]; /* first preread tuple for each source */
- int mergelast[MAXTAPES]; /* last preread tuple for each source */
- long mergeavailmem[MAXTAPES]; /* availMem for prereading tapes */
+ bool mergeactive[MAXTAPES]; /* Active input run source? */
+ int mergenext[MAXTAPES]; /* first preread tuple for each
+ * source */
+ int mergelast[MAXTAPES]; /* last preread tuple for each
+ * source */
+ long mergeavailmem[MAXTAPES]; /* availMem for prereading
+ * tapes */
long spacePerTape; /* actual per-tape target usage */
int mergefreelist; /* head of freelist of recycled slots */
- int mergefirstfree; /* first slot never used in this merge */
+ int mergefirstfree; /* first slot never used in this merge */
/*
* Variables for Algorithm D. Note that destTape is a "logical" tape
@@ -221,10 +233,12 @@ struct Tuplesortstate
*/
int Level; /* Knuth's l */
int destTape; /* current output tape (Knuth's j, less 1) */
- int tp_fib[MAXTAPES]; /* Target Fibonacci run counts (A[]) */
- int tp_runs[MAXTAPES]; /* # of real runs on each tape */
- int tp_dummy[MAXTAPES]; /* # of dummy runs for each tape (D[]) */
- int tp_tapenum[MAXTAPES]; /* Actual tape numbers (TAPE[]) */
+ int tp_fib[MAXTAPES]; /* Target Fibonacci run counts
+ * (A[]) */
+ int tp_runs[MAXTAPES]; /* # of real runs on each tape */
+ int tp_dummy[MAXTAPES]; /* # of dummy runs for each tape
+ * (D[]) */
+ int tp_tapenum[MAXTAPES]; /* Actual tape numbers (TAPE[]) */
/*
* These variables are used after completion of sorting to keep track
@@ -237,12 +251,13 @@ struct Tuplesortstate
/* markpos_xxx holds marked position for mark and restore */
long markpos_block; /* tape block# (only used if SORTEDONTAPE) */
- int markpos_offset; /* saved "current", or offset in tape block */
+ int markpos_offset; /* saved "current", or offset in tape
+ * block */
bool markpos_eof; /* saved "eof_reached" */
/*
- * These variables are specific to the HeapTuple case; they are set
- * by tuplesort_begin_heap and used only by the HeapTuple routines.
+ * These variables are specific to the HeapTuple case; they are set by
+ * tuplesort_begin_heap and used only by the HeapTuple routines.
*/
TupleDesc tupDesc;
int nKeys;
@@ -257,8 +272,8 @@ struct Tuplesortstate
bool enforceUnique; /* complain if we find duplicate tuples */
/*
- * These variables are specific to the Datum case; they are set
- * by tuplesort_begin_datum and used only by the DatumTuple routines.
+ * These variables are specific to the Datum case; they are set by
+ * tuplesort_begin_datum and used only by the DatumTuple routines.
*/
Oid datumType;
Oid sortOperator;
@@ -271,7 +286,7 @@ struct Tuplesortstate
#define COMPARETUP(state,a,b) ((*(state)->comparetup) (state, a, b))
#define COPYTUP(state,tup) ((*(state)->copytup) (state, tup))
#define WRITETUP(state,tape,tup) ((*(state)->writetup) (state, tape, tup))
-#define READTUP(state,tape,len) ((*(state)->readtup) (state, tape, len))
+#define READTUP(state,tape,len) ((*(state)->readtup) (state, tape, len))
#define TUPLESIZE(state,tup) ((*(state)->tuplesize) (state, tup))
#define LACKMEM(state) ((state)->availMem < 0)
#define USEMEM(state,amt) ((state)->availMem -= (amt))
@@ -290,7 +305,7 @@ struct Tuplesortstate
* If state->randomAccess is true, then the stored representation of the
* tuple must be followed by another "unsigned int" that is a copy of the
* length --- so the total tape space used is actually sizeof(unsigned int)
- * more than the stored length value. This allows read-backwards. When
+ * more than the stored length value. This allows read-backwards. When
* randomAccess is not true, the write/read routines may omit the extra
* length word.
*
@@ -300,7 +315,7 @@ struct Tuplesortstate
* the back length word (if present).
*
* The write/read routines can make use of the tuple description data
- * stored in the Tuplesortstate record, if needed. They are also expected
+ * stored in the Tuplesortstate record, if needed. They are also expected
* to adjust state->availMem by the amount of memory space (not tape space!)
* released or consumed. There is no error return from either writetup
* or readtup; they should elog() on failure.
@@ -311,7 +326,7 @@ struct Tuplesortstate
* We count space requested for tuples against the SortMem limit.
* Fixed-size space (primarily the LogicalTapeSet I/O buffers) is not
* counted, nor do we count the variable-size memtuples and memtupindex
- * arrays. (Even though those could grow pretty large, they should be
+ * arrays. (Even though those could grow pretty large, they should be
* small compared to the tuples proper, so this is not unreasonable.)
*
* The major deficiency in this approach is that it ignores palloc overhead.
@@ -360,37 +375,37 @@ static void beginmerge(Tuplesortstate *state);
static void mergepreread(Tuplesortstate *state);
static void dumptuples(Tuplesortstate *state, bool alltuples);
static void tuplesort_heap_insert(Tuplesortstate *state, void *tuple,
- int tupleindex, bool checkIndex);
+ int tupleindex, bool checkIndex);
static void tuplesort_heap_siftup(Tuplesortstate *state, bool checkIndex);
static unsigned int getlen(Tuplesortstate *state, int tapenum, bool eofOK);
static void markrunend(Tuplesortstate *state, int tapenum);
-static int qsort_comparetup(const void *a, const void *b);
+static int qsort_comparetup(const void *a, const void *b);
static int comparetup_heap(Tuplesortstate *state,
- const void *a, const void *b);
+ const void *a, const void *b);
static void *copytup_heap(Tuplesortstate *state, void *tup);
static void writetup_heap(Tuplesortstate *state, int tapenum, void *tup);
static void *readtup_heap(Tuplesortstate *state, int tapenum,
- unsigned int len);
+ unsigned int len);
static unsigned int tuplesize_heap(Tuplesortstate *state, void *tup);
static int comparetup_index(Tuplesortstate *state,
- const void *a, const void *b);
+ const void *a, const void *b);
static void *copytup_index(Tuplesortstate *state, void *tup);
static void writetup_index(Tuplesortstate *state, int tapenum, void *tup);
static void *readtup_index(Tuplesortstate *state, int tapenum,
- unsigned int len);
+ unsigned int len);
static unsigned int tuplesize_index(Tuplesortstate *state, void *tup);
static int comparetup_datum(Tuplesortstate *state,
- const void *a, const void *b);
+ const void *a, const void *b);
static void *copytup_datum(Tuplesortstate *state, void *tup);
static void writetup_datum(Tuplesortstate *state, int tapenum, void *tup);
static void *readtup_datum(Tuplesortstate *state, int tapenum,
- unsigned int len);
+ unsigned int len);
static unsigned int tuplesize_datum(Tuplesortstate *state, void *tup);
/*
* Since qsort(3) will not pass any context info to qsort_comparetup(),
* we have to use this ugly static variable. It is set to point to the
- * active Tuplesortstate object just before calling qsort. It should
+ * active Tuplesortstate object just before calling qsort. It should
* not be used directly by anything except qsort_comparetup().
*/
static Tuplesortstate *qsort_tuplesortstate;
@@ -403,7 +418,7 @@ static Tuplesortstate *qsort_tuplesortstate;
*
* After calling tuplesort_begin, the caller should call tuplesort_puttuple
* zero or more times, then call tuplesort_performsort when all the tuples
- * have been supplied. After performsort, retrieve the tuples in sorted
+ * have been supplied. After performsort, retrieve the tuples in sorted
* order by calling tuplesort_gettuple until it returns NULL. (If random
* access was requested, rescan, markpos, and restorepos can also be called.)
* For Datum sorts, putdatum/getdatum are used instead of puttuple/gettuple.
@@ -434,7 +449,8 @@ tuplesort_begin_common(bool randomAccess)
/* Algorithm D variables will be initialized by inittapes, if needed */
- state->result_tape = -1; /* flag that result tape has not been formed */
+ state->result_tape = -1; /* flag that result tape has not been
+ * formed */
return state;
}
@@ -490,7 +506,7 @@ tuplesort_begin_datum(Oid datumType,
bool randomAccess)
{
Tuplesortstate *state = tuplesort_begin_common(randomAccess);
- Type typeInfo;
+ Type typeInfo;
state->comparetup = comparetup_datum;
state->copytup = copytup_datum;
@@ -518,7 +534,7 @@ tuplesort_begin_datum(Oid datumType,
void
tuplesort_end(Tuplesortstate *state)
{
- int i;
+ int i;
if (state->tapeset)
LogicalTapeSetClose(state->tapeset);
@@ -540,6 +556,7 @@ tuplesort_end(Tuplesortstate *state)
void
tuplesort_puttuple(Tuplesortstate *state, void *tuple)
{
+
/*
* Copy the given tuple into memory we control, and decrease availMem.
* Then call the code shared with the Datum case.
@@ -557,7 +574,7 @@ tuplesort_puttuple(Tuplesortstate *state, void *tuple)
void
tuplesort_putdatum(Tuplesortstate *state, Datum val, bool isNull)
{
- DatumTuple *tuple;
+ DatumTuple *tuple;
/*
* Build pseudo-tuple carrying the datum, and decrease availMem.
@@ -571,9 +588,9 @@ tuplesort_putdatum(Tuplesortstate *state, Datum val, bool isNull)
}
else
{
- int datalen = state->datumTypeLen;
- int tuplelen;
- char *newVal;
+ int datalen = state->datumTypeLen;
+ int tuplelen;
+ char *newVal;
if (datalen == -1) /* variable length type? */
datalen = VARSIZE((struct varlena *) DatumGetPointer(val));
@@ -598,7 +615,8 @@ puttuple_common(Tuplesortstate *state, void *tuple)
{
switch (state->status)
{
- case TSS_INITIAL:
+ case TSS_INITIAL:
+
/*
* Save the copied tuple into the unsorted array.
*/
@@ -611,41 +629,47 @@ puttuple_common(Tuplesortstate *state, void *tuple)
state->memtupsize * sizeof(void *));
}
state->memtuples[state->memtupcount++] = tuple;
+
/*
* Done if we still fit in available memory.
*/
- if (! LACKMEM(state))
+ if (!LACKMEM(state))
return;
+
/*
* Nope; time to switch to tape-based operation.
*/
inittapes(state);
+
/*
* Dump tuples until we are back under the limit.
*/
dumptuples(state, false);
break;
case TSS_BUILDRUNS:
+
/*
* Insert the copied tuple into the heap, with run number
* currentRun if it can go into the current run, else run
* number currentRun+1. The tuple can go into the current run
- * if it is >= the first not-yet-output tuple. (Actually,
- * it could go into the current run if it is >= the most recently
+ * if it is >= the first not-yet-output tuple. (Actually, it
+ * could go into the current run if it is >= the most recently
* output tuple ... but that would require keeping around the
- * tuple we last output, and it's simplest to let writetup free
- * each tuple as soon as it's written.)
+ * tuple we last output, and it's simplest to let writetup
+ * free each tuple as soon as it's written.)
*
- * Note there will always be at least one tuple in the heap
- * at this point; see dumptuples.
+ * Note there will always be at least one tuple in the heap at
+ * this point; see dumptuples.
*/
Assert(state->memtupcount > 0);
if (COMPARETUP(state, tuple, state->memtuples[0]) >= 0)
tuplesort_heap_insert(state, tuple, state->currentRun, true);
else
- tuplesort_heap_insert(state, tuple, state->currentRun+1, true);
+ tuplesort_heap_insert(state, tuple, state->currentRun + 1, true);
+
/*
- * If we are over the memory limit, dump tuples till we're under.
+ * If we are over the memory limit, dump tuples till we're
+ * under.
*/
dumptuples(state, false);
break;
@@ -663,7 +687,8 @@ tuplesort_performsort(Tuplesortstate *state)
{
switch (state->status)
{
- case TSS_INITIAL:
+ case TSS_INITIAL:
+
/*
* We were able to accumulate all the tuples within the
* allowed amount of memory. Just qsort 'em and we're done.
@@ -681,8 +706,9 @@ tuplesort_performsort(Tuplesortstate *state)
state->status = TSS_SORTEDINMEM;
break;
case TSS_BUILDRUNS:
+
/*
- * Finish tape-based sort. First, flush all tuples remaining
+ * Finish tape-based sort. First, flush all tuples remaining
* in memory out to tape; then merge until we have a single
* remaining run (or, if !randomAccess, one run per tape).
* Note that mergeruns sets the correct state->status.
@@ -702,15 +728,15 @@ tuplesort_performsort(Tuplesortstate *state)
/*
* Fetch the next tuple in either forward or back direction.
- * Returns NULL if no more tuples. If should_free is set, the
+ * Returns NULL if no more tuples. If should_free is set, the
* caller must pfree the returned tuple when done with it.
*/
void *
tuplesort_gettuple(Tuplesortstate *state, bool forward,
bool *should_free)
{
- unsigned int tuplen;
- void *tup;
+ unsigned int tuplen;
+ void *tup;
switch (state->status)
{
@@ -728,15 +754,16 @@ tuplesort_gettuple(Tuplesortstate *state, bool forward,
{
if (state->current <= 0)
return NULL;
+
/*
- * if all tuples are fetched already then we return last tuple,
- * else - tuple before last returned.
+ * if all tuples are fetched already then we return last
+ * tuple, else - tuple before last returned.
*/
if (state->eof_reached)
state->eof_reached = false;
else
{
- state->current--; /* last returned tuple */
+ state->current--; /* last returned tuple */
if (state->current <= 0)
return NULL;
}
@@ -762,65 +789,74 @@ tuplesort_gettuple(Tuplesortstate *state, bool forward,
return NULL;
}
}
- /* Backward.
+
+ /*
+ * Backward.
*
* if all tuples are fetched already then we return last tuple,
* else - tuple before last returned.
*/
if (state->eof_reached)
{
+
/*
- * Seek position is pointing just past the zero tuplen
- * at the end of file; back up to fetch last tuple's ending
- * length word. If seek fails we must have a completely empty
- * file.
+ * Seek position is pointing just past the zero tuplen at
+ * the end of file; back up to fetch last tuple's ending
+ * length word. If seek fails we must have a completely
+ * empty file.
*/
- if (! LogicalTapeBackspace(state->tapeset,
- state->result_tape,
- 2 * sizeof(unsigned int)))
+ if (!LogicalTapeBackspace(state->tapeset,
+ state->result_tape,
+ 2 * sizeof(unsigned int)))
return NULL;
state->eof_reached = false;
}
else
{
+
/*
- * Back up and fetch previously-returned tuple's ending length
- * word. If seek fails, assume we are at start of file.
+ * Back up and fetch previously-returned tuple's ending
+ * length word. If seek fails, assume we are at start of
+ * file.
*/
- if (! LogicalTapeBackspace(state->tapeset,
- state->result_tape,
- sizeof(unsigned int)))
+ if (!LogicalTapeBackspace(state->tapeset,
+ state->result_tape,
+ sizeof(unsigned int)))
return NULL;
tuplen = getlen(state, state->result_tape, false);
+
/*
* Back up to get ending length word of tuple before it.
*/
- if (! LogicalTapeBackspace(state->tapeset,
- state->result_tape,
- tuplen + 2 * sizeof(unsigned int)))
+ if (!LogicalTapeBackspace(state->tapeset,
+ state->result_tape,
+ tuplen + 2 * sizeof(unsigned int)))
{
- /* If that fails, presumably the prev tuple is the first
- * in the file. Back up so that it becomes next to read
- * in forward direction (not obviously right, but that is
- * what in-memory case does).
+
+ /*
+ * If that fails, presumably the prev tuple is the
+ * first in the file. Back up so that it becomes next
+ * to read in forward direction (not obviously right,
+ * but that is what in-memory case does).
*/
- if (! LogicalTapeBackspace(state->tapeset,
- state->result_tape,
- tuplen + sizeof(unsigned int)))
+ if (!LogicalTapeBackspace(state->tapeset,
+ state->result_tape,
+ tuplen + sizeof(unsigned int)))
elog(ERROR, "tuplesort_gettuple: bogus tuple len in backward scan");
return NULL;
}
}
tuplen = getlen(state, state->result_tape, false);
+
/*
- * Now we have the length of the prior tuple, back up and read it.
- * Note: READTUP expects we are positioned after the initial
- * length word of the tuple, so back up to that point.
+ * Now we have the length of the prior tuple, back up and read
+ * it. Note: READTUP expects we are positioned after the
+ * initial length word of the tuple, so back up to that point.
*/
- if (! LogicalTapeBackspace(state->tapeset,
- state->result_tape,
- tuplen))
+ if (!LogicalTapeBackspace(state->tapeset,
+ state->result_tape,
+ tuplen))
elog(ERROR, "tuplesort_gettuple: bogus tuple len in backward scan");
tup = READTUP(state, state->result_tape, tuplen);
return tup;
@@ -828,15 +864,16 @@ tuplesort_gettuple(Tuplesortstate *state, bool forward,
case TSS_FINALMERGE:
Assert(forward);
*should_free = true;
+
/*
* This code should match the inner loop of mergeonerun().
*/
if (state->memtupcount > 0)
{
- int srcTape = state->memtupindex[0];
- unsigned int tuplen;
- int tupIndex;
- void *newtup;
+ int srcTape = state->memtupindex[0];
+ unsigned int tuplen;
+ int tupIndex;
+ void *newtup;
tup = state->memtuples[0];
/* returned tuple is no longer counted in our memory space */
@@ -846,9 +883,17 @@ tuplesort_gettuple(Tuplesortstate *state, bool forward,
tuplesort_heap_siftup(state, false);
if ((tupIndex = state->mergenext[srcTape]) == 0)
{
- /* out of preloaded data on this tape, try to read more */
+
+ /*
+ * out of preloaded data on this tape, try to read
+ * more
+ */
mergepreread(state);
- /* if still no data, we've reached end of run on this tape */
+
+ /*
+ * if still no data, we've reached end of run on this
+ * tape
+ */
if ((tupIndex = state->mergenext[srcTape]) == 0)
return tup;
}
@@ -881,8 +926,8 @@ bool
tuplesort_getdatum(Tuplesortstate *state, bool forward,
Datum *val, bool *isNull)
{
- DatumTuple *tuple;
- bool should_free;
+ DatumTuple *tuple;
+ bool should_free;
tuple = (DatumTuple *) tuplesort_gettuple(state, forward, &should_free);
@@ -896,8 +941,8 @@ tuplesort_getdatum(Tuplesortstate *state, bool forward,
}
else
{
- int datalen = state->datumTypeLen;
- char *newVal;
+ int datalen = state->datumTypeLen;
+ char *newVal;
if (datalen == -1) /* variable length type? */
datalen = VARSIZE((struct varlena *) DatumGetPointer(tuple->val));
@@ -933,15 +978,15 @@ inittapes(Tuplesortstate *state)
state->memtupindex = (int *) palloc(state->memtupsize * sizeof(int));
/*
- * Convert the unsorted contents of memtuples[] into a heap.
- * Each tuple is marked as belonging to run number zero.
+ * Convert the unsorted contents of memtuples[] into a heap. Each
+ * tuple is marked as belonging to run number zero.
*
- * NOTE: we pass false for checkIndex since there's no point in
- * comparing indexes in this step, even though we do intend the
- * indexes to be part of the sort key...
+ * NOTE: we pass false for checkIndex since there's no point in comparing
+ * indexes in this step, even though we do intend the indexes to be
+ * part of the sort key...
*/
ntuples = state->memtupcount;
- state->memtupcount = 0; /* make the heap empty */
+ state->memtupcount = 0; /* make the heap empty */
for (j = 0; j < ntuples; j++)
tuplesort_heap_insert(state, state->memtuples[j], 0, false);
Assert(state->memtupcount == ntuples);
@@ -976,11 +1021,11 @@ inittapes(Tuplesortstate *state)
static void
selectnewtape(Tuplesortstate *state)
{
- int j;
- int a;
+ int j;
+ int a;
/* Step D3: advance j (destTape) */
- if (state->tp_dummy[state->destTape] < state->tp_dummy[state->destTape+1])
+ if (state->tp_dummy[state->destTape] < state->tp_dummy[state->destTape + 1])
{
state->destTape++;
return;
@@ -996,8 +1041,8 @@ selectnewtape(Tuplesortstate *state)
a = state->tp_fib[0];
for (j = 0; j < TAPERANGE; j++)
{
- state->tp_dummy[j] = a + state->tp_fib[j+1] - state->tp_fib[j];
- state->tp_fib[j] = a + state->tp_fib[j+1];
+ state->tp_dummy[j] = a + state->tp_fib[j + 1] - state->tp_fib[j];
+ state->tp_fib[j] = a + state->tp_fib[j + 1];
}
state->destTape = 0;
}
@@ -1011,17 +1056,18 @@ selectnewtape(Tuplesortstate *state)
static void
mergeruns(Tuplesortstate *state)
{
- int tapenum,
- svTape,
- svRuns,
- svDummy;
+ int tapenum,
+ svTape,
+ svRuns,
+ svDummy;
Assert(state->status == TSS_BUILDRUNS);
Assert(state->memtupcount == 0);
+
/*
- * If we produced only one initial run (quite likely if the total
- * data volume is between 1X and 2X SortMem), we can just use that
- * tape as the finished output, rather than doing a useless merge.
+ * If we produced only one initial run (quite likely if the total data
+ * volume is between 1X and 2X SortMem), we can just use that tape as
+ * the finished output, rather than doing a useless merge.
*/
if (state->currentRun == 1)
{
@@ -1039,10 +1085,10 @@ mergeruns(Tuplesortstate *state)
for (;;)
{
/* Step D5: merge runs onto tape[T] until tape[P] is empty */
- while (state->tp_runs[TAPERANGE-1] || state->tp_dummy[TAPERANGE-1])
+ while (state->tp_runs[TAPERANGE - 1] || state->tp_dummy[TAPERANGE - 1])
{
- bool allDummy = true;
- bool allOneRun = true;
+ bool allDummy = true;
+ bool allOneRun = true;
for (tapenum = 0; tapenum < TAPERANGE; tapenum++)
{
@@ -1051,28 +1097,27 @@ mergeruns(Tuplesortstate *state)
if (state->tp_runs[tapenum] + state->tp_dummy[tapenum] != 1)
allOneRun = false;
}
+
/*
* If we don't have to produce a materialized sorted tape,
* quit as soon as we're down to one real/dummy run per tape.
*/
- if (! state->randomAccess && allOneRun)
+ if (!state->randomAccess && allOneRun)
{
- Assert(! allDummy);
+ Assert(!allDummy);
/* Initialize for the final merge pass */
beginmerge(state);
state->status = TSS_FINALMERGE;
return;
}
if (allDummy)
- {
+ {
state->tp_dummy[TAPERANGE]++;
for (tapenum = 0; tapenum < TAPERANGE; tapenum++)
state->tp_dummy[tapenum]--;
}
else
- {
mergeonerun(state);
- }
}
/* Step D6: decrease level */
if (--state->Level == 0)
@@ -1081,30 +1126,35 @@ mergeruns(Tuplesortstate *state)
LogicalTapeRewind(state->tapeset, state->tp_tapenum[TAPERANGE],
false);
/* rewind used-up input tape P, and prepare it for write pass */
- LogicalTapeRewind(state->tapeset, state->tp_tapenum[TAPERANGE-1],
+ LogicalTapeRewind(state->tapeset, state->tp_tapenum[TAPERANGE - 1],
true);
- state->tp_runs[TAPERANGE-1] = 0;
- /* reassign tape units per step D6; note we no longer care about A[] */
+ state->tp_runs[TAPERANGE - 1] = 0;
+
+ /*
+ * reassign tape units per step D6; note we no longer care about
+ * A[]
+ */
svTape = state->tp_tapenum[TAPERANGE];
svDummy = state->tp_dummy[TAPERANGE];
svRuns = state->tp_runs[TAPERANGE];
for (tapenum = TAPERANGE; tapenum > 0; tapenum--)
{
- state->tp_tapenum[tapenum] = state->tp_tapenum[tapenum-1];
- state->tp_dummy[tapenum] = state->tp_dummy[tapenum-1];
- state->tp_runs[tapenum] = state->tp_runs[tapenum-1];
+ state->tp_tapenum[tapenum] = state->tp_tapenum[tapenum - 1];
+ state->tp_dummy[tapenum] = state->tp_dummy[tapenum - 1];
+ state->tp_runs[tapenum] = state->tp_runs[tapenum - 1];
}
state->tp_tapenum[0] = svTape;
state->tp_dummy[0] = svDummy;
state->tp_runs[0] = svRuns;
}
+
/*
- * Done. Knuth says that the result is on TAPE[1], but since we exited
- * the loop without performing the last iteration of step D6, we have not
- * rearranged the tape unit assignment, and therefore the result is on
- * TAPE[T]. We need to do it this way so that we can freeze the final
- * output tape while rewinding it. The last iteration of step D6 would
- * be a waste of cycles anyway...
+ * Done. Knuth says that the result is on TAPE[1], but since we
+ * exited the loop without performing the last iteration of step D6,
+ * we have not rearranged the tape unit assignment, and therefore the
+ * result is on TAPE[T]. We need to do it this way so that we can
+ * freeze the final output tape while rewinding it. The last
+ * iteration of step D6 would be a waste of cycles anyway...
*/
state->result_tape = state->tp_tapenum[TAPERANGE];
LogicalTapeFreeze(state->tapeset, state->result_tape);
@@ -1120,23 +1170,24 @@ mergeruns(Tuplesortstate *state)
static void
mergeonerun(Tuplesortstate *state)
{
- int destTape = state->tp_tapenum[TAPERANGE];
- int srcTape;
- int tupIndex;
- void *tup;
- long priorAvail,
- spaceFreed;
+ int destTape = state->tp_tapenum[TAPERANGE];
+ int srcTape;
+ int tupIndex;
+ void *tup;
+ long priorAvail,
+ spaceFreed;
/*
* Start the merge by loading one tuple from each active source tape
- * into the heap. We can also decrease the input run/dummy run counts.
+ * into the heap. We can also decrease the input run/dummy run
+ * counts.
*/
beginmerge(state);
/*
* Execute merge by repeatedly extracting lowest tuple in heap,
- * writing it out, and replacing it with next tuple from same tape
- * (if there is another one).
+ * writing it out, and replacing it with next tuple from same tape (if
+ * there is another one).
*/
while (state->memtupcount > 0)
{
@@ -1166,9 +1217,10 @@ mergeonerun(Tuplesortstate *state)
state->mergefreelist = tupIndex;
tuplesort_heap_insert(state, tup, srcTape, false);
}
+
/*
- * When the heap empties, we're done. Write an end-of-run marker
- * on the output tape, and increment its count of real runs.
+ * When the heap empties, we're done. Write an end-of-run marker on
+ * the output tape, and increment its count of real runs.
*/
markrunend(state, destTape);
state->tp_runs[TAPERANGE]++;
@@ -1178,16 +1230,16 @@ mergeonerun(Tuplesortstate *state)
* beginmerge - initialize for a merge pass
*
* We decrease the counts of real and dummy runs for each tape, and mark
- * which tapes contain active input runs in mergeactive[]. Then, load
+ * which tapes contain active input runs in mergeactive[]. Then, load
* as many tuples as we can from each active input tape, and finally
* fill the merge heap with the first tuple from each active tape.
*/
static void
beginmerge(Tuplesortstate *state)
{
- int activeTapes;
- int tapenum;
- int srcTape;
+ int activeTapes;
+ int tapenum;
+ int srcTape;
/* Heap should be empty here */
Assert(state->memtupcount == 0);
@@ -1198,16 +1250,15 @@ beginmerge(Tuplesortstate *state)
memset(state->mergelast, 0, sizeof(state->mergelast));
memset(state->mergeavailmem, 0, sizeof(state->mergeavailmem));
state->mergefreelist = 0; /* nothing in the freelist */
- state->mergefirstfree = MAXTAPES; /* first slot available for preread */
+ state->mergefirstfree = MAXTAPES; /* first slot available for
+ * preread */
/* Adjust run counts and mark the active tapes */
activeTapes = 0;
for (tapenum = 0; tapenum < TAPERANGE; tapenum++)
{
if (state->tp_dummy[tapenum] > 0)
- {
state->tp_dummy[tapenum]--;
- }
else
{
Assert(state->tp_runs[tapenum] > 0);
@@ -1219,8 +1270,8 @@ beginmerge(Tuplesortstate *state)
}
/*
- * Initialize space allocation to let each active input tape have
- * an equal share of preread space.
+ * Initialize space allocation to let each active input tape have an
+ * equal share of preread space.
*/
Assert(activeTapes > 0);
state->spacePerTape = state->availMem / activeTapes;
@@ -1261,39 +1312,41 @@ beginmerge(Tuplesortstate *state)
* This routine exists to improve sequentiality of reads during a merge pass,
* as explained in the header comments of this file. Load tuples from each
* active source tape until the tape's run is exhausted or it has used up
- * its fair share of available memory. In any case, we guarantee that there
+ * its fair share of available memory. In any case, we guarantee that there
* is at one preread tuple available from each unexhausted input tape.
*/
static void
mergepreread(Tuplesortstate *state)
{
- int srcTape;
- unsigned int tuplen;
- void *tup;
- int tupIndex;
- long priorAvail,
- spaceUsed;
+ int srcTape;
+ unsigned int tuplen;
+ void *tup;
+ int tupIndex;
+ long priorAvail,
+ spaceUsed;
for (srcTape = 0; srcTape < MAXTAPES; srcTape++)
{
- if (! state->mergeactive[srcTape])
+ if (!state->mergeactive[srcTape])
continue;
+
/*
- * Skip reading from any tape that still has at least half
- * of its target memory filled with tuples (threshold fraction
- * may need adjustment?). This avoids reading just a few tuples
- * when the incoming runs are not being consumed evenly.
+ * Skip reading from any tape that still has at least half of its
+ * target memory filled with tuples (threshold fraction may need
+ * adjustment?). This avoids reading just a few tuples when the
+ * incoming runs are not being consumed evenly.
*/
if (state->mergenext[srcTape] != 0 &&
state->mergeavailmem[srcTape] <= state->spacePerTape / 2)
continue;
+
/*
- * Read tuples from this tape until it has used up its free memory,
- * but ensure that we have at least one.
+ * Read tuples from this tape until it has used up its free
+ * memory, but ensure that we have at least one.
*/
priorAvail = state->availMem;
state->availMem = state->mergeavailmem[srcTape];
- while (! LACKMEM(state) || state->mergenext[srcTape] == 0)
+ while (!LACKMEM(state) || state->mergenext[srcTape] == 0)
{
/* read next tuple, if any */
if ((tuplen = getlen(state, srcTape, true)) == 0)
@@ -1359,17 +1412,19 @@ dumptuples(Tuplesortstate *state, bool alltuples)
while (alltuples ||
(LACKMEM(state) && state->memtupcount > 1))
{
+
/*
- * Dump the heap's frontmost entry, and sift up to remove it
- * from the heap.
+ * Dump the heap's frontmost entry, and sift up to remove it from
+ * the heap.
*/
Assert(state->memtupcount > 0);
WRITETUP(state, state->tp_tapenum[state->destTape],
state->memtuples[0]);
tuplesort_heap_siftup(state, true);
+
/*
- * If the heap is empty *or* top run number has changed,
- * we've finished the current run.
+ * If the heap is empty *or* top run number has changed, we've
+ * finished the current run.
*/
if (state->memtupcount == 0 ||
state->currentRun != state->memtupindex[0])
@@ -1377,7 +1432,8 @@ dumptuples(Tuplesortstate *state, bool alltuples)
markrunend(state, state->tp_tapenum[state->destTape]);
state->currentRun++;
state->tp_runs[state->destTape]++;
- state->tp_dummy[state->destTape]--; /* per Alg D step D2 */
+ state->tp_dummy[state->destTape]--; /* per Alg D step D2 */
+
/*
* Done if heap is empty, else prepare for new run.
*/
@@ -1437,8 +1493,8 @@ tuplesort_markpos(Tuplesortstate *state)
case TSS_SORTEDONTAPE:
LogicalTapeTell(state->tapeset,
state->result_tape,
- & state->markpos_block,
- & state->markpos_offset);
+ &state->markpos_block,
+ &state->markpos_offset);
state->markpos_eof = state->eof_reached;
break;
default:
@@ -1448,7 +1504,7 @@ tuplesort_markpos(Tuplesortstate *state)
}
/*
- * tuplesort_restorepos - restores current position in merged sort file to
+ * tuplesort_restorepos - restores current position in merged sort file to
* last saved position
*/
void
@@ -1463,10 +1519,10 @@ tuplesort_restorepos(Tuplesortstate *state)
state->eof_reached = state->markpos_eof;
break;
case TSS_SORTEDONTAPE:
- if (! LogicalTapeSeek(state->tapeset,
- state->result_tape,
- state->markpos_block,
- state->markpos_offset))
+ if (!LogicalTapeSeek(state->tapeset,
+ state->result_tape,
+ state->markpos_block,
+ state->markpos_offset))
elog(ERROR, "tuplesort_restorepos failed");
state->eof_reached = state->markpos_eof;
break;
@@ -1497,9 +1553,9 @@ static void
tuplesort_heap_insert(Tuplesortstate *state, void *tuple,
int tupleindex, bool checkIndex)
{
- void **memtuples;
- int *memtupindex;
- int j;
+ void **memtuples;
+ int *memtupindex;
+ int j;
/*
* Make sure memtuples[] can handle another entry.
@@ -1516,14 +1572,15 @@ tuplesort_heap_insert(Tuplesortstate *state, void *tuple,
}
memtuples = state->memtuples;
memtupindex = state->memtupindex;
+
/*
- * Sift-up the new entry, per Knuth 5.2.3 exercise 16.
- * Note that Knuth is using 1-based array indexes, not 0-based.
+ * Sift-up the new entry, per Knuth 5.2.3 exercise 16. Note that Knuth
+ * is using 1-based array indexes, not 0-based.
*/
j = state->memtupcount++;
while (j > 0)
{
- int i = (j-1) >> 1;
+ int i = (j - 1) >> 1;
if (HEAPCOMPARE(tuple, tupleindex,
memtuples[i], memtupindex[i]) >= 0)
@@ -1543,12 +1600,12 @@ tuplesort_heap_insert(Tuplesortstate *state, void *tuple,
static void
tuplesort_heap_siftup(Tuplesortstate *state, bool checkIndex)
{
- void **memtuples = state->memtuples;
- int *memtupindex = state->memtupindex;
- void *tuple;
- int tupindex,
- i,
- n;
+ void **memtuples = state->memtuples;
+ int *memtupindex = state->memtupindex;
+ void *tuple;
+ int tupindex,
+ i,
+ n;
if (--state->memtupcount <= 0)
return;
@@ -1556,15 +1613,15 @@ tuplesort_heap_siftup(Tuplesortstate *state, bool checkIndex)
tuple = memtuples[n]; /* tuple that must be reinserted */
tupindex = memtupindex[n];
i = 0; /* i is where the "hole" is */
- for (;;)
+ for (;;)
{
- int j = 2*i + 1;
+ int j = 2 * i + 1;
if (j >= n)
break;
- if (j+1 < n &&
+ if (j + 1 < n &&
HEAPCOMPARE(memtuples[j], memtupindex[j],
- memtuples[j+1], memtupindex[j+1]) > 0)
+ memtuples[j + 1], memtupindex[j + 1]) > 0)
j++;
if (HEAPCOMPARE(tuple, tupindex,
memtuples[j], memtupindex[j]) <= 0)
@@ -1572,8 +1629,8 @@ tuplesort_heap_siftup(Tuplesortstate *state, bool checkIndex)
memtuples[i] = memtuples[j];
memtupindex[i] = memtupindex[j];
i = j;
- }
- memtuples[i] = tuple;
+ }
+ memtuples[i] = tuple;
memtupindex[i] = tupindex;
}
@@ -1585,7 +1642,7 @@ tuplesort_heap_siftup(Tuplesortstate *state, bool checkIndex)
static unsigned int
getlen(Tuplesortstate *state, int tapenum, bool eofOK)
{
- unsigned int len;
+ unsigned int len;
if (LogicalTapeRead(state->tapeset, tapenum, (void *) &len,
sizeof(len)) != sizeof(len))
@@ -1598,7 +1655,7 @@ getlen(Tuplesortstate *state, int tapenum, bool eofOK)
static void
markrunend(Tuplesortstate *state, int tapenum)
{
- unsigned int len = 0;
+ unsigned int len = 0;
LogicalTapeWrite(state->tapeset, tapenum, (void *) &len, sizeof(len));
}
@@ -1613,7 +1670,7 @@ qsort_comparetup(const void *a, const void *b)
{
/* The passed pointers are pointers to void * ... */
- return COMPARETUP(qsort_tuplesortstate, * (void **) a, * (void **) b);
+ return COMPARETUP(qsort_tuplesortstate, *(void **) a, *(void **) b);
}
@@ -1651,14 +1708,14 @@ comparetup_heap(Tuplesortstate *state, const void *a, const void *b)
return -1;
else if (scanKey->sk_flags & SK_COMMUTE)
{
- if (!(result = - (int) (*fmgr_faddr(&scanKey->sk_func)) (rattr, lattr)))
+ if (!(result = -(int) (*fmgr_faddr(&scanKey->sk_func)) (rattr, lattr)))
result = (int) (*fmgr_faddr(&scanKey->sk_func)) (lattr, rattr);
if (result)
return result;
}
else
{
- if (!(result = - (int) (*fmgr_faddr(&scanKey->sk_func)) (lattr, rattr)))
+ if (!(result = -(int) (*fmgr_faddr(&scanKey->sk_func)) (lattr, rattr)))
result = (int) (*fmgr_faddr(&scanKey->sk_func)) (rattr, lattr);
if (result)
return result;
@@ -1684,17 +1741,17 @@ copytup_heap(Tuplesortstate *state, void *tup)
static void
writetup_heap(Tuplesortstate *state, int tapenum, void *tup)
{
- HeapTuple tuple = (HeapTuple) tup;
- unsigned int tuplen;
+ HeapTuple tuple = (HeapTuple) tup;
+ unsigned int tuplen;
tuplen = tuple->t_len + sizeof(tuplen);
LogicalTapeWrite(state->tapeset, tapenum,
- (void*) &tuplen, sizeof(tuplen));
+ (void *) &tuplen, sizeof(tuplen));
LogicalTapeWrite(state->tapeset, tapenum,
- (void*) tuple->t_data, tuple->t_len);
+ (void *) tuple->t_data, tuple->t_len);
if (state->randomAccess) /* need trailing length word? */
LogicalTapeWrite(state->tapeset, tapenum,
- (void*) &tuplen, sizeof(tuplen));
+ (void *) &tuplen, sizeof(tuplen));
FREEMEM(state, HEAPTUPLESIZE + tuple->t_len);
heap_freetuple(tuple);
@@ -1703,8 +1760,8 @@ writetup_heap(Tuplesortstate *state, int tapenum, void *tup)
static void *
readtup_heap(Tuplesortstate *state, int tapenum, unsigned int len)
{
- unsigned int tuplen = len - sizeof(unsigned int) + HEAPTUPLESIZE;
- HeapTuple tuple = (HeapTuple) palloc(tuplen);
+ unsigned int tuplen = len - sizeof(unsigned int) + HEAPTUPLESIZE;
+ HeapTuple tuple = (HeapTuple) palloc(tuplen);
USEMEM(state, tuplen);
/* reconstruct the HeapTupleData portion */
@@ -1736,7 +1793,7 @@ tuplesize_heap(Tuplesortstate *state, void *tup)
* Routines specialized for IndexTuple case
*
* NOTE: actually, these are specialized for the btree case; it's not
- * clear whether you could use them for a non-btree index. Possibly
+ * clear whether you could use them for a non-btree index. Possibly
* you'd need to make another set of routines if you needed to sort
* according to another kind of index.
*/
@@ -1744,9 +1801,10 @@ tuplesize_heap(Tuplesortstate *state, void *tup)
static int
comparetup_index(Tuplesortstate *state, const void *a, const void *b)
{
+
/*
- * This is almost the same as _bt_tuplecompare(), but we need to
- * keep track of whether any null fields are present.
+ * This is almost the same as _bt_tuplecompare(), but we need to keep
+ * track of whether any null fields are present.
*/
IndexTuple tuple1 = (IndexTuple) a;
IndexTuple tuple2 = (IndexTuple) b;
@@ -1793,7 +1851,8 @@ comparetup_index(Tuplesortstate *state, const void *a, const void *b)
}
if (compare != 0)
- return (int) compare; /* done when we find unequal attributes */
+ return (int) compare; /* done when we find unequal
+ * attributes */
}
/*
@@ -1801,9 +1860,9 @@ comparetup_index(Tuplesortstate *state, const void *a, const void *b)
* tuples are detected (unless there was at least one NULL field).
*
* It is sufficient to make the test here, because if two tuples are
- * equal they *must* get compared at some stage of the sort --- otherwise
- * the sort algorithm wouldn't have checked whether one must appear
- * before the other.
+ * equal they *must* get compared at some stage of the sort ---
+ * otherwise the sort algorithm wouldn't have checked whether one must
+ * appear before the other.
*/
if (state->enforceUnique && !equal_hasnull)
elog(ERROR, "Cannot create unique index. Table contains non-unique values");
@@ -1814,9 +1873,9 @@ comparetup_index(Tuplesortstate *state, const void *a, const void *b)
static void *
copytup_index(Tuplesortstate *state, void *tup)
{
- IndexTuple tuple = (IndexTuple) tup;
- unsigned int tuplen = IndexTupleSize(tuple);
- IndexTuple newtuple;
+ IndexTuple tuple = (IndexTuple) tup;
+ unsigned int tuplen = IndexTupleSize(tuple);
+ IndexTuple newtuple;
USEMEM(state, tuplen);
newtuple = (IndexTuple) palloc(tuplen);
@@ -1828,17 +1887,17 @@ copytup_index(Tuplesortstate *state, void *tup)
static void
writetup_index(Tuplesortstate *state, int tapenum, void *tup)
{
- IndexTuple tuple = (IndexTuple) tup;
- unsigned int tuplen;
+ IndexTuple tuple = (IndexTuple) tup;
+ unsigned int tuplen;
tuplen = IndexTupleSize(tuple) + sizeof(tuplen);
LogicalTapeWrite(state->tapeset, tapenum,
- (void*) &tuplen, sizeof(tuplen));
+ (void *) &tuplen, sizeof(tuplen));
LogicalTapeWrite(state->tapeset, tapenum,
- (void*) tuple, IndexTupleSize(tuple));
+ (void *) tuple, IndexTupleSize(tuple));
if (state->randomAccess) /* need trailing length word? */
LogicalTapeWrite(state->tapeset, tapenum,
- (void*) &tuplen, sizeof(tuplen));
+ (void *) &tuplen, sizeof(tuplen));
FREEMEM(state, IndexTupleSize(tuple));
pfree(tuple);
@@ -1847,8 +1906,8 @@ writetup_index(Tuplesortstate *state, int tapenum, void *tup)
static void *
readtup_index(Tuplesortstate *state, int tapenum, unsigned int len)
{
- unsigned int tuplen = len - sizeof(unsigned int);
- IndexTuple tuple = (IndexTuple) palloc(tuplen);
+ unsigned int tuplen = len - sizeof(unsigned int);
+ IndexTuple tuple = (IndexTuple) palloc(tuplen);
USEMEM(state, tuplen);
if (LogicalTapeRead(state->tapeset, tapenum, (void *) tuple,
@@ -1864,8 +1923,8 @@ readtup_index(Tuplesortstate *state, int tapenum, unsigned int len)
static unsigned int
tuplesize_index(Tuplesortstate *state, void *tup)
{
- IndexTuple tuple = (IndexTuple) tup;
- unsigned int tuplen = IndexTupleSize(tuple);
+ IndexTuple tuple = (IndexTuple) tup;
+ unsigned int tuplen = IndexTupleSize(tuple);
return tuplen;
}
@@ -1891,10 +1950,10 @@ comparetup_datum(Tuplesortstate *state, const void *a, const void *b)
return -1;
else
{
- int result;
+ int result;
- if (!(result = - (int) (*fmgr_faddr(&state->sortOpFn)) (ltup->val,
- rtup->val)))
+ if (!(result = -(int) (*fmgr_faddr(&state->sortOpFn)) (ltup->val,
+ rtup->val)))
result = (int) (*fmgr_faddr(&state->sortOpFn)) (rtup->val,
ltup->val);
return result;
@@ -1912,17 +1971,17 @@ copytup_datum(Tuplesortstate *state, void *tup)
static void
writetup_datum(Tuplesortstate *state, int tapenum, void *tup)
{
- DatumTuple *tuple = (DatumTuple *) tup;
- unsigned int tuplen = tuplesize_datum(state, tup);
- unsigned int writtenlen = tuplen + sizeof(unsigned int);
+ DatumTuple *tuple = (DatumTuple *) tup;
+ unsigned int tuplen = tuplesize_datum(state, tup);
+ unsigned int writtenlen = tuplen + sizeof(unsigned int);
LogicalTapeWrite(state->tapeset, tapenum,
- (void*) &writtenlen, sizeof(writtenlen));
+ (void *) &writtenlen, sizeof(writtenlen));
LogicalTapeWrite(state->tapeset, tapenum,
- (void*) tuple, tuplen);
+ (void *) tuple, tuplen);
if (state->randomAccess) /* need trailing length word? */
LogicalTapeWrite(state->tapeset, tapenum,
- (void*) &writtenlen, sizeof(writtenlen));
+ (void *) &writtenlen, sizeof(writtenlen));
FREEMEM(state, tuplen);
pfree(tuple);
@@ -1931,8 +1990,8 @@ writetup_datum(Tuplesortstate *state, int tapenum, void *tup)
static void *
readtup_datum(Tuplesortstate *state, int tapenum, unsigned int len)
{
- unsigned int tuplen = len - sizeof(unsigned int);
- DatumTuple *tuple = (DatumTuple *) palloc(tuplen);
+ unsigned int tuplen = len - sizeof(unsigned int);
+ DatumTuple *tuple = (DatumTuple *) palloc(tuplen);
USEMEM(state, tuplen);
if (LogicalTapeRead(state->tapeset, tapenum, (void *) tuple,
@@ -1952,16 +2011,14 @@ readtup_datum(Tuplesortstate *state, int tapenum, unsigned int len)
static unsigned int
tuplesize_datum(Tuplesortstate *state, void *tup)
{
- DatumTuple *tuple = (DatumTuple *) tup;
+ DatumTuple *tuple = (DatumTuple *) tup;
if (tuple->isNull || state->datumTypeByVal)
- {
return (unsigned int) sizeof(DatumTuple);
- }
else
{
- int datalen = state->datumTypeLen;
- int tuplelen;
+ int datalen = state->datumTypeLen;
+ int tuplelen;
if (datalen == -1) /* variable length type? */
datalen = VARSIZE((struct varlena *) DatumGetPointer(tuple->val));