/* GUC variable */ int bytea_output = BYTEA_OUTPUT_HEX;
typedefstruct varlena VarString;
/* *Statefortext_position_*functions.
*/ typedefstruct
{
pg_locale_t locale; /* collation used for substring matching */ bool is_multibyte_char_in_char; /* need to check char boundaries? */ bool greedy; /* find longest possible substring? */
char *str1; /* haystack string */ char *str2; /* needle string */ int len1; /* string lengths in bytes */ int len2;
/* Skip table for Boyer-Moore-Horspool search algorithm: */ int skiptablemask; /* mask for ANDing with skiptable subscripts */ int skiptable[256]; /* skip distance for given mismatched char */
/* *Notethatwithnondeterministiccollations,thelengthofthelast *matchisnotnecessarilyequaltothelengthofthe"needle"passedin.
*/ char *last_match; /* pointer to last match in 'str1' */ int last_match_len; /* length of last match */ int last_match_len_tmp; /* same but for internal use */
/* *Sometimesweneedtoconvertthebytepositionofamatchtoa *characterposition.Thesestorethelastpositionthatwasconverted, *sothatonthenextcall,wecancontinuefromthatpoint,ratherthan *countcharactersfromtheverybeginning.
*/ char *refpoint; /* pointer within original haystack string */ int refpos; /* 0-based character offset of the same point */
} TextPositionState;
typedefstruct
{ char *buf1; /* 1st string, or abbreviation original string
* buf */ char *buf2; /* 2nd string, or abbreviation strxfrm() buf */ int buflen1; /* Allocated length of buf1 */ int buflen2; /* Allocated length of buf2 */ int last_len1; /* Length of last buf1 string/strxfrm() input */ int last_len2; /* Length of last buf2 string/strxfrm() blob */ int last_returned; /* Last comparison result (cache) */ bool cache_blob; /* Does buf2 contain strxfrm() blob, etc? */ bool collate_c;
Oid typid; /* Actual datatype (text/bpchar/bytea/name) */
hyperLogLogState abbr_card; /* Abbreviated key cardinality state */
hyperLogLogState full_card; /* Full key cardinality state */ double prop_card; /* Required cardinality proportion */
pg_locale_t locale;
} VarStringSortSupport;
/* Recognize hex input */ if (inputText[0] == '\\' && inputText[1] == 'x')
{
size_t len = strlen(inputText);
bc = (len - 2) / 2 + VARHDRSZ; /* maximum possible length */
result = palloc(bc);
bc = hex_decode_safe(inputText + 2, len - 2, VARDATA(result),
escontext);
SET_VARSIZE(result, bc + VARHDRSZ); /* actual length */
if (bytea_output == BYTEA_OUTPUT_HEX)
{ /* Print hex format */
rp = result = palloc(VARSIZE_ANY_EXHDR(vlena) * 2 + 2 + 1);
*rp++ = '\\';
*rp++ = 'x';
rp += hex_encode(VARDATA_ANY(vlena), VARSIZE_ANY_EXHDR(vlena), rp);
} elseif (bytea_output == BYTEA_OUTPUT_ESCAPE)
{ /* Print traditional escaped format */ char *vp;
uint64 len; int i;
len = 1; /* empty string has 1 char */
vp = VARDATA_ANY(vlena); for (i = VARSIZE_ANY_EXHDR(vlena); i != 0; i--, vp++)
{ if (*vp == '\\')
len += 2; elseif ((unsignedchar) *vp < 0x20 || (unsignedchar) *vp > 0x7e)
len += 4; else
len++;
}
/* *Inprinciplelencan'toverflowuint32iftheinputfitin1GB,but *forsafetylet'scheckratherthanrelyingonpalloc'sinternal *check.
*/ if (len > MaxAllocSize)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg_internal("result of bytea output conversion is too large")));
rp = result = (char *) palloc(len);
vp = VARDATA_ANY(vlena); for (i = VARSIZE_ANY_EXHDR(vlena); i != 0; i--, vp++)
{ if (*vp == '\\')
{
*rp++ = '\\';
*rp++ = '\\';
} elseif ((unsignedchar) *vp < 0x20 || (unsignedchar) *vp > 0x7e)
{ int val; /* holds unprintable chars */
Datum
bytea_string_agg_transfn(PG_FUNCTION_ARGS)
{
StringInfo state;
state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
/* Append the value unless null, preceding it with the delimiter. */ if (!PG_ARGISNULL(1))
{
bytea *value = PG_GETARG_BYTEA_PP(1); bool isfirst = false;
/* *Thetransitiontypeforstring_agg()isdeclaredtobe"internal", *whichisapass-by-valuetypethesamesizeasapointer.
*/ if (state)
PG_RETURN_POINTER(state);
PG_RETURN_NULL();
}
Datum
bytea_string_agg_finalfn(PG_FUNCTION_ARGS)
{
StringInfo state;
/* cannot be called directly because of internal-type argument */
Assert(AggCheckCallContext(fcinfo, NULL));
state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
if (state != NULL)
{ /* As per comment in transfn, strip data before the cursor position */
bytea *result; int strippedlen = state->len - state->cursor;
/* *unknownin-convertscstringtointernalrepresentation
*/
Datum
unknownin(PG_FUNCTION_ARGS)
{ char *str = PG_GETARG_CSTRING(0);
/* representation is same as cstring */
PG_RETURN_CSTRING(pstrdup(str));
}
/* *unknownout-convertsinternalrepresentationtocstring
*/
Datum
unknownout(PG_FUNCTION_ARGS)
{ /* representation is same as cstring */ char *str = PG_GETARG_CSTRING(0);
PG_RETURN_CSTRING(pstrdup(str));
}
/* *unknownrecv-convertsexternalbinaryformattounknown
*/
Datum
unknownrecv(PG_FUNCTION_ARGS)
{
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0); char *str; int nbytes;
str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes); /* representation is same as cstring */
PG_RETURN_CSTRING(str);
}
/* *unknownsend-convertsunknowntobinaryformat
*/
Datum
unknownsend(PG_FUNCTION_ARGS)
{ /* representation is same as cstring */ char *str = PG_GETARG_CSTRING(0);
StringInfoData buf;
/* paranoia ... probably should throw error instead? */ if (len1 < 0)
len1 = 0; if (len2 < 0)
len2 = 0;
len = len1 + len2 + VARHDRSZ;
result = (text *) palloc(len);
/* Set size of result string... */
SET_VARSIZE(result, len);
/* Fill data field of result string... */
ptr = VARDATA(result); if (len1 > 0)
memcpy(ptr, VARDATA_ANY(t1), len1); if (len2 > 0)
memcpy(ptr + len1, VARDATA_ANY(t2), len2);
/* life is easy if the encoding max length is 1 */ if (eml == 1)
{ if (length_not_specified) /* special case - get length to end of
* string */
L1 = -1; elseif (length < 0)
{ /* SQL99 says to throw an error for E < S, i.e., negative length */
ereport(ERROR,
(errcode(ERRCODE_SUBSTRING_ERROR),
errmsg("negative substring length not allowed")));
L1 = -1; /* silence stupider compilers */
} elseif (pg_add_s32_overflow(S, length, &E))
{ /* *LcouldbelargeenoughforS+Ltooverflow,inwhichcase *thesubstringmustruntoendofstring.
*/
L1 = -1;
} else
{ /* *Azeroornegativevaluefortheendpositioncanhappenifthe *startwasnegativeorone.SQL99saystoreturnazero-length *string.
*/ if (E < 1) return cstring_to_text("");
/* see if we got back an empty string */
slice_len = VARSIZE_ANY_EXHDR(slice); if (slice_len == 0)
{ if (slice != (text *) DatumGetPointer(str))
pfree(slice); return cstring_to_text("");
}
while (len > 0 && *mbstr)
{
l = pg_mblen_with_len(mbstr, len);
nch++; if (nch == limit) break;
len -= l;
mbstr += l;
} return nch;
}
/* *textoverlay *Replacespecifiedsubstringoffirststringwithsecond * *TheSQLstandarddefinesOVERLAY()intermsofsubstringandconcatenation. *Thiscodeisadirectimplementationofwhatthestandardsays.
*/
Datum
textoverlay(PG_FUNCTION_ARGS)
{
text *t1 = PG_GETARG_TEXT_PP(0);
text *t2 = PG_GETARG_TEXT_PP(1); int sp = PG_GETARG_INT32(2); /* substring start position */ int sl = PG_GETARG_INT32(3); /* substring length */
PG_RETURN_TEXT_P(text_overlay(t1, t2, sp, sl));
}
Datum
textoverlay_no_len(PG_FUNCTION_ARGS)
{
text *t1 = PG_GETARG_TEXT_PP(0);
text *t2 = PG_GETARG_TEXT_PP(1); int sp = PG_GETARG_INT32(2); /* substring start position */ int sl;
/* *text_position- *Doestherealworkfortextpos() * *Inputs: *t1-stringtobesearched *t2-patterntomatchwithint1 *Result: *Characterindexofthefirstmatchedchar,startingfrom1, *or0ifnomatch. * *Thisisbrokenoutsoitcanbecalleddirectlybyotherstringprocessing *functions.
*/ staticint
text_position(text *t1, text *t2, Oid collid)
{
TextPositionState state; int result;
check_collation_set(collid);
/* Empty needle always matches at position 1 */ if (VARSIZE_ANY_EXHDR(t2) < 1) return1;
/* Otherwise, can't match if haystack is shorter than needle */ if (VARSIZE_ANY_EXHDR(t1) < VARSIZE_ANY_EXHDR(t2) &&
pg_newlocale_from_collation(collid)->deterministic) return0;
text_position_setup(t1, t2, collid, &state); /* don't need greedy mode here */
state.greedy = false;
if (!text_position_next(&state))
result = 0; else
result = text_position_get_match_pos(&state);
text_position_cleanup(&state); return result;
}
staticvoid
text_position_setup(text *t1, text *t2, Oid collid, TextPositionState *state)
{ int len1 = VARSIZE_ANY_EXHDR(t1); int len2 = VARSIZE_ANY_EXHDR(t2);
if (needle_len <= 0) returnfalse; /* result for empty pattern */
/* Start from the point right after the previous match. */ if (state->last_match)
start_ptr = state->last_match + state->last_match_len; else
start_ptr = state->str1;
/* Start at startpos plus the length of the needle */
hptr = start_ptr + needle_len - 1; while (hptr < haystack_end)
{ /* Match the needle scanning *backward* */ constchar *nptr; constchar *p;
nptr = needle_last;
p = hptr; while (*nptr == *p)
{ /* Matched it all? If so, return 1-based position */ if (nptr == needle) return (char *) p;
nptr--, p--;
}
staticvoid
text_position_cleanup(TextPositionState *state)
{ /* no cleanup needed */
}
staticvoid
check_collation_set(Oid collid)
{ if (!OidIsValid(collid))
{ /* *Thistypicallymeansthattheparsercouldnotresolveaconflict *ofimplicitcollations,soreportitthatway.
*/
ereport(ERROR,
(errcode(ERRCODE_INDETERMINATE_COLLATION),
errmsg("could not determine which collation to use for string comparison"),
errhint("Use the COLLATE clause to set the collation explicitly.")));
}
}
/* *varstr_cmp() * *Comparisonfunctionfortextstringswithgivenlengths,usingthe *appropriatelocale.Returnsanintegerlessthan,equalto,orgreaterthan *zero,indicatingwhetherarg1islessthan,equalto,orgreaterthanarg2. * *Note:manyfunctionsthatdependonthisaremarkedleakproof;therefore, *avoidreportingtheactualcontentsoftheinputwhenthrowingerrors. *Allerrorshereinshouldbethingsthatcan'thappenexceptoncorrupt *data,anyway;otherwisewewillhavetroublewithindexingstringsthat *wouldcausethem.
*/ int
varstr_cmp(constchar *arg1, int len1, constchar *arg2, int len2, Oid collid)
{ int result;
pg_locale_t mylocale;
check_collation_set(collid);
mylocale = pg_newlocale_from_collation(collid);
if (mylocale->collate_is_c)
{
result = memcmp(arg1, arg2, Min(len1, len2)); if ((result == 0) && (len1 != len2))
result = (len1 < len2) ? -1 : 1;
} else
{ /* *memcmp()can'ttelluswhichoftwounequalstringssortsfirst, *butit'sacheapwaytotellifthey'reequal.Testingshowsthat *memcmp()followedbystrcoll()isonlytriviallyslowerthan *strcoll()byitself,sowedon'tlosemuchifthisdoesn'tworkout *veryoften,andifitdoes-forexample,becausetherearemany *equalstringsintheinput-thenwewinbigbyavoidingexpensive *collation-awarecomparisons.
*/ if (len1 == len2 && memcmp(arg1, arg2, len1) == 0) return0;
result = pg_strncoll(arg1, len1, arg2, len2, mylocale);
/* Break tie if necessary. */ if (result == 0 && mylocale->deterministic)
{
result = memcmp(arg1, arg2, Min(len1, len2)); if ((result == 0) && (len1 != len2))
result = (len1 < len2) ? -1 : 1;
}
}
return result;
}
/* text_cmp() *Internalcomparisonfunctionfortextstrings. *Returns-1,0or1
*/ staticint
text_cmp(text *arg1, text *arg2, Oid collid)
{ char *a1p,
*a2p; int len1,
len2;
Datum
textne(PG_FUNCTION_ARGS)
{
Oid collid = PG_GET_COLLATION();
pg_locale_t mylocale; bool result;
check_collation_set(collid);
mylocale = pg_newlocale_from_collation(collid);
if (mylocale->deterministic)
{
Datum arg1 = PG_GETARG_DATUM(0);
Datum arg2 = PG_GETARG_DATUM(1);
Size len1,
len2;
/* See comment in texteq() */
len1 = toast_raw_datum_size(arg1);
len2 = toast_raw_datum_size(arg2); if (len1 != len2)
result = true; else
{
text *targ1 = DatumGetTextPP(arg1);
text *targ2 = DatumGetTextPP(arg2);
result = (memcmp(VARDATA_ANY(targ1), VARDATA_ANY(targ2),
len1 - VARHDRSZ) != 0);
PG_FREE_IF_COPY(targ1, 0);
PG_FREE_IF_COPY(targ2, 1);
}
} else
{
text *arg1 = PG_GETARG_TEXT_PP(0);
text *arg2 = PG_GETARG_TEXT_PP(1);
Datum
text_starts_with(PG_FUNCTION_ARGS)
{
Datum arg1 = PG_GETARG_DATUM(0);
Datum arg2 = PG_GETARG_DATUM(1);
Oid collid = PG_GET_COLLATION();
pg_locale_t mylocale; bool result;
Size len1,
len2;
check_collation_set(collid);
mylocale = pg_newlocale_from_collation(collid);
if (!mylocale->deterministic)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("nondeterministic collations are not supported for substring searches")));
len1 = toast_raw_datum_size(arg1);
len2 = toast_raw_datum_size(arg2); if (len2 > len1)
result = false; else
{
text *targ1 = text_substring(arg1, 1, len2, false);
text *targ2 = DatumGetTextPP(arg2);
result = (memcmp(VARDATA_ANY(targ1), VARDATA_ANY(targ2),
VARSIZE_ANY_EXHDR(targ2)) == 0);
result = memcmp(a1p, a2p, Min(len1, len2)); if ((result == 0) && (len1 != len2))
result = (len1 < len2) ? -1 : 1;
/* We can't afford to leak memory here. */ if (PointerGetDatum(arg1) != x)
pfree(arg1); if (PointerGetDatum(arg2) != y)
pfree(arg2);
return result;
}
/* *sortsupportcomparisonfunc(forNAMEClocalecase)
*/ staticint
namefastcmp_c(Datum x, Datum y, SortSupport ssup)
{
Name arg1 = DatumGetName(x);
Name arg2 = DatumGetName(y);
result = varstrfastcmp_locale(a1p, len1, a2p, len2, ssup);
/* We can't afford to leak memory here. */ if (PointerGetDatum(arg1) != x)
pfree(arg1); if (PointerGetDatum(arg2) != y)
pfree(arg2);
return result;
}
/* *sortsupportcomparisonfunc(forlocalecasewithNAMEtype)
*/ staticint
namefastcmp_locale(Datum x, Datum y, SortSupport ssup)
{
Name arg1 = DatumGetName(x);
Name arg2 = DatumGetName(y);
/* By convention, we use buffer 1 to store and NUL-terminate */ if (len >= sss->buflen1)
{
sss->buflen1 = Max(len + 1, Min(sss->buflen1 * 2, MaxAllocSize));
sss->buf1 = repalloc(sss->buf1, sss->buflen1);
}
/* Might be able to reuse strxfrm() blob from last call */ if (sss->last_len1 == len && sss->cache_blob &&
memcmp(sss->buf1, authoritative_data, len) == 0)
{
memcpy(pres, sss->buf2, Min(max_prefix_bytes, sss->last_len2)); /* No change affecting cardinality, so no hashing required */ goto done;
}
/* paranoia ... probably should throw error instead? */ if (len1 < 0)
len1 = 0; if (len2 < 0)
len2 = 0;
len = len1 + len2 + VARHDRSZ;
result = (bytea *) palloc(len);
/* Set size of result string... */
SET_VARSIZE(result, len);
/* Fill data field of result string... */
ptr = VARDATA(result); if (len1 > 0)
memcpy(ptr, VARDATA_ANY(t1), len1); if (len2 > 0)
memcpy(ptr + len1, VARDATA_ANY(t2), len2);
if (len2 <= 0)
PG_RETURN_INT32(1); /* result for empty pattern */
p1 = VARDATA_ANY(t1);
p2 = VARDATA_ANY(t2);
pos = 0;
px = (len1 - len2); for (p = 0; p <= px; p++)
{ if ((*p2 == *p1) && (memcmp(p1, p2, len2) == 0))
{
pos = p + 1; break;
};
p1++;
};
PG_RETURN_INT32(pos);
}
/*------------------------------------------------------------- *byteaGetByte * *thisroutinetreats"bytea"asanarrayofbytes. *ItreturnstheNthbyte(anumberbetween0and255). *-------------------------------------------------------------
*/
Datum
byteaGetByte(PG_FUNCTION_ARGS)
{
bytea *v = PG_GETARG_BYTEA_PP(0);
int32 n = PG_GETARG_INT32(1); int len; int byte;
len = VARSIZE_ANY_EXHDR(v);
if (n < 0 || n >= len)
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("index %d out of valid range, 0..%d",
n, len - 1)));
byte = ((unsignedchar *) VARDATA_ANY(v))[n];
PG_RETURN_INT32(byte);
}
/*------------------------------------------------------------- *byteaGetBit * *Thisroutinetreatsa"bytea"typelikeanarrayofbits. *ItreturnsthevalueoftheNthbit(0or1). * *-------------------------------------------------------------
*/
Datum
byteaGetBit(PG_FUNCTION_ARGS)
{
bytea *v = PG_GETARG_BYTEA_PP(0);
int64 n = PG_GETARG_INT64(1); int byteNo,
bitNo; int len; int byte;
len = VARSIZE_ANY_EXHDR(v);
if (n < 0 || n >= (int64) len * 8)
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("index %" PRId64 " out of valid range, 0..%" PRId64,
n, (int64) len * 8 - 1)));
/* n/8 is now known < len, so safe to cast to int */
byteNo = (int) (n / 8);
bitNo = (int) (n % 8);
byte = ((unsignedchar *) VARDATA_ANY(v))[byteNo];
if (byte & (1 << bitNo))
PG_RETURN_INT32(1); else
PG_RETURN_INT32(0);
}
/*------------------------------------------------------------- *byteaSetByte * *Givenaninstanceoftype'bytea'createsanewonewith *theNthbytesettothegivenvalue. * *-------------------------------------------------------------
*/
Datum
byteaSetByte(PG_FUNCTION_ARGS)
{
bytea *res = PG_GETARG_BYTEA_P_COPY(0);
int32 n = PG_GETARG_INT32(1);
int32 newByte = PG_GETARG_INT32(2); int len;
len = VARSIZE(res) - VARHDRSZ;
if (n < 0 || n >= len)
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("index %d out of valid range, 0..%d",
n, len - 1)));
/*------------------------------------------------------------- *byteaSetBit * *Givenaninstanceoftype'bytea'createsanewonewith *theNthbitsettothegivenvalue. * *-------------------------------------------------------------
*/
Datum
byteaSetBit(PG_FUNCTION_ARGS)
{
bytea *res = PG_GETARG_BYTEA_P_COPY(0);
int64 n = PG_GETARG_INT64(1);
int32 newBit = PG_GETARG_INT32(2); int len; int oldByte,
newByte; int byteNo,
bitNo;
len = VARSIZE(res) - VARHDRSZ;
if (n < 0 || n >= (int64) len * 8)
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("index %" PRId64 " out of valid range, 0..%" PRId64,
n, (int64) len * 8 - 1)));
/* n/8 is now known < len, so safe to cast to int */
byteNo = (int) (n / 8);
bitNo = (int) (n % 8);
/* *sanitycheck!
*/ if (newBit != 0 && newBit != 1)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("new bit must be 0 or 1")));
while (scanner_isspace(*nextp))
nextp++; /* skip leading whitespace */
if (*nextp == '\0') returntrue; /* allow empty string */
/* At the top of the loop, we are at start of a new identifier. */ do
{ char *curname; char *endp;
if (*nextp == '"')
{ /* Quoted name --- collapse quote-quote pairs, no downcasing */
curname = nextp + 1; for (;;)
{
endp = strchr(nextp + 1, '"'); if (endp == NULL) returnfalse; /* mismatched quotes */ if (endp[1] != '"') break; /* found end of quoted name */ /* Collapse adjacent quotes into one quote, and look again */
memmove(endp, endp + 1, strlen(endp));
nextp = endp;
} /* endp now points at the terminating quote */
nextp = endp + 1;
} else
{ /* Unquoted name --- extends to separator or whitespace */ char *downname; int len;
curname = nextp; while (*nextp && *nextp != separator &&
!scanner_isspace(*nextp))
nextp++;
endp = nextp; if (curname == nextp) returnfalse; /* empty unquoted name not allowed */
while (scanner_isspace(*nextp))
nextp++; /* skip trailing whitespace */
if (*nextp == separator)
{
nextp++; while (scanner_isspace(*nextp))
nextp++; /* skip leading whitespace for next */ /* we expect another name, so done remains false */
} elseif (*nextp == '\0')
done = true; else returnfalse; /* invalid syntax */
/* Now safe to overwrite separator with a null */
*endp = '\0';
/* Truncate name if it's overlength */
truncate_identifier(curname, strlen(curname), false);
while (scanner_isspace(*nextp))
nextp++; /* skip leading whitespace */
if (*nextp == '\0') returntrue; /* allow empty string */
/* At the top of the loop, we are at start of a new directory. */ do
{ char *curname; char *endp;
if (*nextp == '"')
{ /* Quoted name --- collapse quote-quote pairs */
curname = nextp + 1; for (;;)
{
endp = strchr(nextp + 1, '"'); if (endp == NULL) returnfalse; /* mismatched quotes */ if (endp[1] != '"') break; /* found end of quoted name */ /* Collapse adjacent quotes into one quote, and look again */
memmove(endp, endp + 1, strlen(endp));
nextp = endp;
} /* endp now points at the terminating quote */
nextp = endp + 1;
} else
{ /* Unquoted name --- extends to separator or end of string */
curname = endp = nextp; while (*nextp && *nextp != separator)
{ /* trailing whitespace should not be included in name */ if (!scanner_isspace(*nextp))
endp = nextp + 1;
nextp++;
} if (curname == endp) returnfalse; /* empty unquoted name not allowed */
}
while (scanner_isspace(*nextp))
nextp++; /* skip trailing whitespace */
if (*nextp == separator)
{
nextp++; while (scanner_isspace(*nextp))
nextp++; /* skip leading whitespace for next */ /* we expect another name, so done remains false */
} elseif (*nextp == '\0')
done = true; else returnfalse; /* invalid syntax */
/* Now safe to overwrite separator with a null */
*endp = '\0';
/* Truncate path if it's overlength */ if (strlen(curname) >= MAXPGPATH)
curname[MAXPGPATH - 1] = '\0';
while (scanner_isspace(*nextp))
nextp++; /* skip leading whitespace */
if (*nextp == '\0') returntrue; /* allow empty string */
/* At the top of the loop, we are at start of a new identifier. */ do
{ char *curname; char *endp;
if (*nextp == '"')
{ /* Quoted name --- collapse quote-quote pairs */
curname = nextp + 1; for (;;)
{
endp = strchr(nextp + 1, '"'); if (endp == NULL) returnfalse; /* mismatched quotes */ if (endp[1] != '"') break; /* found end of quoted name */ /* Collapse adjacent quotes into one quote, and look again */
memmove(endp, endp + 1, strlen(endp));
nextp = endp;
} /* endp now points at the terminating quote */
nextp = endp + 1;
} else
{ /* Unquoted name --- extends to separator or whitespace */
curname = nextp; while (*nextp && *nextp != separator &&
!scanner_isspace(*nextp))
nextp++;
endp = nextp; if (curname == nextp) returnfalse; /* empty unquoted name not allowed */
}
while (scanner_isspace(*nextp))
nextp++; /* skip trailing whitespace */
if (*nextp == separator)
{
nextp++; while (scanner_isspace(*nextp))
nextp++; /* skip leading whitespace for next */ /* we expect another name, so done remains false */
} elseif (*nextp == '\0')
done = true; else returnfalse; /* invalid syntax */
/* Now safe to overwrite separator with a null */
*endp = '\0';
/* Cast bytea -> int2 */
Datum
bytea_int2(PG_FUNCTION_ARGS)
{
bytea *v = PG_GETARG_BYTEA_PP(0); int len = VARSIZE_ANY_EXHDR(v);
uint16 result;
/* Check that the byte array is not too long */ if (len > sizeof(result))
ereport(ERROR,
errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
errmsg("smallint out of range"));
/* Convert it to an integer; most significant bytes come first */
result = 0; for (int i = 0; i < len; i++)
{
result <<= BITS_PER_BYTE;
result |= ((unsignedchar *) VARDATA_ANY(v))[i];
}
PG_RETURN_INT16(result);
}
/* Cast bytea -> int4 */
Datum
bytea_int4(PG_FUNCTION_ARGS)
{
bytea *v = PG_GETARG_BYTEA_PP(0); int len = VARSIZE_ANY_EXHDR(v);
uint32 result;
/* Check that the byte array is not too long */ if (len > sizeof(result))
ereport(ERROR,
errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
errmsg("integer out of range"));
/* Convert it to an integer; most significant bytes come first */
result = 0; for (int i = 0; i < len; i++)
{
result <<= BITS_PER_BYTE;
result |= ((unsignedchar *) VARDATA_ANY(v))[i];
}
PG_RETURN_INT32(result);
}
/* Cast bytea -> int8 */
Datum
bytea_int8(PG_FUNCTION_ARGS)
{
bytea *v = PG_GETARG_BYTEA_PP(0); int len = VARSIZE_ANY_EXHDR(v);
uint64 result;
/* Check that the byte array is not too long */ if (len > sizeof(result))
ereport(ERROR,
errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
errmsg("bigint out of range"));
/* Convert it to an integer; most significant bytes come first */
result = 0; for (int i = 0; i < len; i++)
{
result <<= BITS_PER_BYTE;
result |= ((unsignedchar *) VARDATA_ANY(v))[i];
}
PG_RETURN_INT64(result);
}
/* Cast int2 -> bytea; can just use int2send() */
Datum
int2_bytea(PG_FUNCTION_ARGS)
{ return int2send(fcinfo);
}
/* Cast int4 -> bytea; can just use int4send() */
Datum
int4_bytea(PG_FUNCTION_ARGS)
{ return int4send(fcinfo);
}
/* Cast int8 -> bytea; can just use int8send() */
Datum
int8_bytea(PG_FUNCTION_ARGS)
{ return int8send(fcinfo);
}
/* When the from_sub_text is not found, there is nothing to do. */ if (!found)
{
text_position_cleanup(&state);
PG_RETURN_TEXT_P(src_text);
}
curr_ptr = text_position_get_match_ptr(&state);
start_ptr = VARDATA_ANY(src_text);
initStringInfo(&str);
do
{
CHECK_FOR_INTERRUPTS();
/* copy the data skipped over by last text_position_next() */
chunk_len = curr_ptr - start_ptr;
appendBinaryStringInfo(&str, start_ptr, chunk_len);
appendStringInfoText(&str, to_sub_text);
start_ptr = curr_ptr + state.last_match_len;
found = text_position_next(&state); if (found)
curr_ptr = text_position_get_match_ptr(&state);
} while (found);
/* *check_replace_text_has_escape * *Returns0iftextcontainsnobackslashesthatneedprocessing. *Returns1iftextcontainsbackslashes,butnotregexpsubmatchspecifiers. *Returns2iftextcontainsregexpsubmatchspecifiers(\1..\9).
*/ staticint
check_replace_text_has_escape(const text *replace_text)
{ int result = 0; constchar *p = VARDATA_ANY(replace_text); constchar *p_end = p + VARSIZE_ANY_EXHDR(replace_text);
while (p < p_end)
{ /* Find next escape char, if any. */
p = memchr(p, '\\', p_end - p); if (p == NULL) break;
p++; /* Note: a backslash at the end doesn't require extra processing. */ if (p < p_end)
{ if (*p >= '1' && *p <= '9') return2; /* Found a submatch specifier, so done */
result = 1; /* Found some other sequence, keep looking */
p++;
}
} return result;
}
/* *appendStringInfoRegexpSubstr * *Appendreplace_texttostr,substitutingregexpbackreferencesfor *\nescapes.start_ptristhestartofthematchinthesourcestring, *atlogicalcharacterpositiondata_pos.
*/ staticvoid
appendStringInfoRegexpSubstr(StringInfo str, text *replace_text,
regmatch_t *pmatch, char *start_ptr, int data_pos)
{ constchar *p = VARDATA_ANY(replace_text); constchar *p_end = p + VARSIZE_ANY_EXHDR(replace_text);
while (p < p_end)
{ constchar *chunk_start = p; int so; int eo;
/* Find next escape char, if any. */
p = memchr(p, '\\', p_end - p); if (p == NULL)
p = p_end;
/* Copy the text we just scanned over, if any. */ if (p > chunk_start)
appendBinaryStringInfo(str, chunk_start, p - chunk_start);
/* Done if at end of string, else advance over escape char. */ if (p >= p_end) break;
p++;
if (p >= p_end)
{ /* Escape at very end of input. Treat same as unexpected char */
appendStringInfoChar(str, '\\'); break;
}
if (*p >= '1' && *p <= '9')
{ /* Use the back reference of regexp. */ int idx = *p - '0';
so = pmatch[idx].rm_so;
eo = pmatch[idx].rm_eo;
p++;
} elseif (*p == '&')
{ /* Use the entire matched string. */
so = pmatch[0].rm_so;
eo = pmatch[0].rm_eo;
p++;
} elseif (*p == '\\')
{ /* \\ means transfer one \ to output. */
appendStringInfoChar(str, '\\');
p++; continue;
} else
{ /* *Ifescapecharisnotfollowedbyanyexpectedchar,justtreat *itasordinarydatatocopy.(XXXwoulditbebettertothrow *anerror?)
*/
appendStringInfoChar(str, '\\'); continue;
}
if (so >= 0 && eo >= 0)
{ /* *Copythetextthatisbackreferenceofregexp.Notesoandeo *arecountedincharactersnotbytes.
*/ char *chunk_start; int chunk_len;
/* *replace_text_regexp * *replacesubstring(s)insrc_textthatmatchpatternwithreplace_text. *Thereplace_textcancontainbackslashmarkerstosubstitute *(partsof)thematchedtext. * *cflags:regexpcompileflags. *collation:collationtouse. *search_start:thecharacter(notbyte)offsetinsrc_textatwhichto *beginsearching. *n:if0,replaceallmatches;if>0,replaceonlytheN'thmatch.
*/
text *
replace_text_regexp(text *src_text, text *pattern_text,
text *replace_text, int cflags, Oid collation, int search_start, int n)
{
text *ret_text;
regex_t *re; int src_text_len = VARSIZE_ANY_EXHDR(src_text); int nmatches = 0;
StringInfoData buf;
regmatch_t pmatch[10]; /* main match, plus \1 to \9 */ int nmatch = lengthof(pmatch);
pg_wchar *data;
size_t data_len; int data_pos; char *start_ptr; int escape_status;
initStringInfo(&buf);
/* Convert data string to wide characters. */
data = (pg_wchar *) palloc((src_text_len + 1) * sizeof(pg_wchar));
data_len = pg_mb2wchar_with_len(VARDATA_ANY(src_text), data, src_text_len);
/* Check whether replace_text has escapes, especially regexp submatches. */
escape_status = check_replace_text_has_escape(replace_text);
/* If no regexp submatches, we can use REG_NOSUB. */ if (escape_status < 2)
{
cflags |= REG_NOSUB; /* Also tell pg_regexec we only want the whole-match location. */
nmatch = 1;
}
/* Prepare the regexp. */
re = RE_compile_and_cache(pattern_text, cflags, collation);
/* start_ptr points to the data_pos'th character of src_text */
start_ptr = (char *) VARDATA_ANY(src_text);
data_pos = 0;
while (search_start <= data_len)
{ int regexec_result;
/* *split_part *parseinputstringbasedonprovidedfieldseparator *returnN'thitem(1based,negativecountsfromend)
*/
Datum
split_part(PG_FUNCTION_ARGS)
{
text *inputstring = PG_GETARG_TEXT_PP(0);
text *fldsep = PG_GETARG_TEXT_PP(1); int fldnum = PG_GETARG_INT32(2); int inputstring_len; int fldsep_len;
TextPositionState state; char *start_ptr; char *end_ptr;
text *result_text; bool found;
/* field number is 1 based */ if (fldnum == 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("field position must not be zero")));
/* return empty string for empty input string */ if (inputstring_len < 1)
PG_RETURN_TEXT_P(cstring_to_text(""));
/* handle empty field separator */ if (fldsep_len < 1)
{ /* if first or last field, return input string, else empty string */ if (fldnum == 1 || fldnum == -1)
PG_RETURN_TEXT_P(inputstring); else
PG_RETURN_TEXT_P(cstring_to_text(""));
}
/* find the first field separator */
text_position_setup(inputstring, fldsep, PG_GET_COLLATION(), &state);
found = text_position_next(&state);
/* special case if fldsep not found at all */ if (!found)
{
text_position_cleanup(&state); /* if first or last field, return input string, else empty string */ if (fldnum == 1 || fldnum == -1)
PG_RETURN_TEXT_P(inputstring); else
PG_RETURN_TEXT_P(cstring_to_text(""));
}
/* *takecareofanegativefieldnumber(i.e.countfromtheright)by *convertingtoapositivefieldnumber;weneedtotalnumberoffields
*/ if (fldnum < 0)
{ /* we found a fldsep, so there are at least two fields */ int numfields = 2;
while (text_position_next(&state))
numfields++;
/* special case of last field does not require an extra pass */ if (fldnum == -1)
{
start_ptr = text_position_get_match_ptr(&state) + state.last_match_len;
end_ptr = VARDATA_ANY(inputstring) + inputstring_len;
text_position_cleanup(&state);
PG_RETURN_TEXT_P(cstring_to_text_with_len(start_ptr,
end_ptr - start_ptr));
}
/* if nonexistent field, return empty string */ if (fldnum <= 0)
{
text_position_cleanup(&state);
PG_RETURN_TEXT_P(cstring_to_text(""));
}
/* reset to pointing at first match, but now with positive fldnum */
text_position_reset(&state);
found = text_position_next(&state);
Assert(found);
}
/* identify bounds of first field */
start_ptr = VARDATA_ANY(inputstring);
end_ptr = text_position_get_match_ptr(&state);
while (found && --fldnum > 0)
{ /* identify bounds of next field */
start_ptr = end_ptr + state.last_match_len;
found = text_position_next(&state); if (found)
end_ptr = text_position_get_match_ptr(&state);
}
text_position_cleanup(&state);
if (fldnum > 0)
{ /* N'th field separator not found */ /* if last field requested, return it, else empty string */ if (fldnum == 1)
{ int last_len = start_ptr - VARDATA_ANY(inputstring);
/* *Commoncodefortext_to_array,text_to_array_null,text_to_table *andtext_to_table_nullfunctions. * *Thesearenotstrictsowehavetotestfornullinputsexplicitly. *Returnsfalseifresultistobenull,elsereturnstrue. * *Notethatiftheresultisvalidbutempty(zeroelements),wereturn *withoutchanging*tstate---callermusthandlethatcase,too.
*/ staticbool
split_text(FunctionCallInfo fcinfo, SplitTextOutputData *tstate)
{
text *inputstring;
text *fldsep;
text *null_string;
Oid collation = PG_GET_COLLATION(); int inputstring_len; int fldsep_len; char *start_ptr;
text *result_text;
/* when input string is NULL, then result is NULL too */ if (PG_ARGISNULL(0)) returnfalse;
inputstring = PG_GETARG_TEXT_PP(0);
/* fldsep can be NULL */ if (!PG_ARGISNULL(1))
fldsep = PG_GETARG_TEXT_PP(1); else
fldsep = NULL;
/* null_string can be NULL or omitted */ if (PG_NARGS() > 2 && !PG_ARGISNULL(2))
null_string = PG_GETARG_TEXT_PP(2); else
null_string = NULL;
/* return empty set for empty input string */ if (inputstring_len < 1) returntrue;
/* empty field separator: return input string as a one-element set */ if (fldsep_len < 1)
{
split_text_accum_result(tstate, inputstring,
null_string, collation); returntrue;
}
/* returns NULL when first or second parameter is NULL */ if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
PG_RETURN_NULL();
v = PG_GETARG_ARRAYTYPE_P(0);
fldsep = text_to_cstring(PG_GETARG_TEXT_PP(1));
/* NULL null string is passed through as a null pointer */ if (!PG_ARGISNULL(2))
null_string = text_to_cstring(PG_GETARG_TEXT_PP(2)); else
null_string = NULL;
p = att_addlength_pointer(p, typlen, p);
p = (char *) att_align_nominal(p, typalign);
}
/* advance bitmap pointer if any */ if (bitmap)
{
bitmask <<= 1; if (bitmask == 0x100)
{
bitmap++;
bitmask = 1;
}
}
}
result = cstring_to_text_with_len(buf.data, buf.len);
pfree(buf.data);
return result;
}
/* *Workhorseforto_bin,to_oct,andto_hex.Notethatbasemustbe>1and<= *16.
*/ staticinline text *
convert_to_base(uint64 value, int base)
{ constchar *digits = "0123456789abcdef";
/* We size the buffer for to_bin's longest possible return value. */ char buf[sizeof(uint64) * BITS_PER_BYTE]; char *const end = buf + sizeof(buf); char *ptr = end;
Assert(base > 1);
Assert(base <= 16);
do
{
*--ptr = digits[value % base];
value /= base;
} while (ptr > buf && value);
return cstring_to_text_with_len(ptr, end - ptr);
}
/* *Convertanintegertoastringcontainingabase-2(binary)representation *ofthenumber.
*/
Datum
to_bin32(PG_FUNCTION_ARGS)
{
uint64 value = (uint32) PG_GETARG_INT32(0);
PG_RETURN_TEXT_P(convert_to_base(value, 2));
}
Datum
to_bin64(PG_FUNCTION_ARGS)
{
uint64 value = (uint64) PG_GETARG_INT64(0);
PG_RETURN_TEXT_P(convert_to_base(value, 2));
}
/* *Convertanintegertoastringcontainingabase-8(oct)representationof *thenumber.
*/
Datum
to_oct32(PG_FUNCTION_ARGS)
{
uint64 value = (uint32) PG_GETARG_INT32(0);
PG_RETURN_TEXT_P(convert_to_base(value, 8));
}
Datum
to_oct64(PG_FUNCTION_ARGS)
{
uint64 value = (uint64) PG_GETARG_INT64(0);
PG_RETURN_TEXT_P(convert_to_base(value, 8));
}
/* *Convertanintegertoastringcontainingabase-16(hex)representationof *thenumber.
*/
Datum
to_hex32(PG_FUNCTION_ARGS)
{
uint64 value = (uint32) PG_GETARG_INT32(0);
PG_RETURN_TEXT_P(convert_to_base(value, 16));
}
Datum
to_hex64(PG_FUNCTION_ARGS)
{
uint64 value = (uint64) PG_GETARG_INT64(0);
PG_RETURN_TEXT_P(convert_to_base(value, 16));
}
/* *Returnthesizeofadatum,possiblycompressed * *Worksonanydatatype
*/
Datum
pg_column_size(PG_FUNCTION_ARGS)
{
Datum value = PG_GETARG_DATUM(0);
int32 result; int typlen;
/* On first call, get the input type's typlen, and save at *fn_extra */ if (fcinfo->flinfo->fn_extra == NULL)
{ /* Lookup the datatype of the supplied argument */
Oid argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
typlen = get_typlen(argtypeid); if (typlen == 0) /* should not happen */
elog(ERROR, "cache lookup failed for type %u", argtypeid);
if (typlen == -1)
{ /* varlena type, possibly toasted */
result = toast_datum_size(value);
} elseif (typlen == -2)
{ /* cstring */
result = strlen(DatumGetCString(value)) + 1;
} else
{ /* ordinary fixed-width type */
result = typlen;
}
PG_RETURN_INT32(result);
}
/* *Returnthecompressionmethodstoredinthecompressedattribute.Return *NULLfornonvarlenatypeoruncompresseddata.
*/
Datum
pg_column_compression(PG_FUNCTION_ARGS)
{ int typlen; char *result;
ToastCompressionId cmid;
/* On first call, get the input type's typlen, and save at *fn_extra */ if (fcinfo->flinfo->fn_extra == NULL)
{ /* Lookup the datatype of the supplied argument */
Oid argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
typlen = get_typlen(argtypeid); if (typlen == 0) /* should not happen */
elog(ERROR, "cache lookup failed for type %u", argtypeid);
/* get the compression method id stored in the compressed varlena */
cmid = toast_get_compression_id((struct varlena *)
DatumGetPointer(PG_GETARG_DATUM(0))); if (cmid == TOAST_INVALID_COMPRESSION_ID)
PG_RETURN_NULL();
/* convert compression method id to compression method name */ switch (cmid)
{ case TOAST_PGLZ_COMPRESSION_ID:
result = "pglz"; break; case TOAST_LZ4_COMPRESSION_ID:
result = "lz4"; break; default:
elog(ERROR, "invalid compression method id %d", cmid);
}
PG_RETURN_TEXT_P(cstring_to_text(result));
}
/* *Returnthechunk_idoftheon-diskTOASTedvalue.ReturnNULLifthevalue *isun-TOASTedornoton-disk.
*/
Datum
pg_column_toast_chunk_id(PG_FUNCTION_ARGS)
{ int typlen; struct varlena *attr; struct varatt_external toast_pointer;
/* On first call, get the input type's typlen, and save at *fn_extra */ if (fcinfo->flinfo->fn_extra == NULL)
{ /* Lookup the datatype of the supplied argument */
Oid argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
typlen = get_typlen(argtypeid); if (typlen == 0) /* should not happen */
elog(ERROR, "cache lookup failed for type %u", argtypeid);
/* subroutine to initialize state */ static StringInfo
makeStringAggState(FunctionCallInfo fcinfo)
{
StringInfo state;
MemoryContext aggcontext;
MemoryContext oldcontext;
if (!AggCheckCallContext(fcinfo, &aggcontext))
{ /* cannot be called directly because of internal-type argument */
elog(ERROR, "string_agg_transfn called in non-aggregate context");
}
/* data */
datalen = VARSIZE_ANY_EXHDR(sstate) - 4;
data = (char *) pq_getmsgbytes(&buf, datalen);
appendBinaryStringInfo(result, data, datalen);
pq_getmsgend(&buf);
PG_RETURN_POINTER(result);
}
Datum
string_agg_finalfn(PG_FUNCTION_ARGS)
{
StringInfo state;
/* cannot be called directly because of internal-type argument */
Assert(AggCheckCallContext(fcinfo, NULL));
state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
if (state != NULL)
{ /* As per comment in transfn, strip data before the cursor position */
PG_RETURN_TEXT_P(cstring_to_text_with_len(&state->data[state->cursor],
state->len - state->cursor));
} else
PG_RETURN_NULL();
}
/* *Preparecachewithfmgrinfofortheoutputfunctionsofthedatatypesof *theargumentsofaconcat-likefunction,beginningwithargument"argidx". *(Argumentsbeforethatwillhavecorrespondingslotsintheresulting *FmgrInfoarray,butwedon'tfillthoseslots.)
*/ static FmgrInfo *
build_concat_foutcache(FunctionCallInfo fcinfo, int argidx)
{
FmgrInfo *foutcache; int i;
/* We keep the info in fn_mcxt so it survives across calls */
foutcache = (FmgrInfo *) MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
PG_NARGS() * sizeof(FmgrInfo));
for (i = argidx; i < PG_NARGS(); i++)
{
Oid valtype;
Oid typOutput; bool typIsVarlena;
valtype = get_fn_expr_argtype(fcinfo->flinfo, i); if (!OidIsValid(valtype))
elog(ERROR, "could not determine data type of concat() input");
/* Normal case without explicit VARIADIC marker */
initStringInfo(&str);
/* Get output function info, building it if first time through */
foutcache = (FmgrInfo *) fcinfo->flinfo->fn_extra; if (foutcache == NULL)
foutcache = build_concat_foutcache(fcinfo, argidx);
for (i = argidx; i < PG_NARGS(); i++)
{ if (!PG_ARGISNULL(i))
{
Datum value = PG_GETARG_DATUM(i);
/* add separator if appropriate */ if (first_arg)
first_arg = false; else
appendStringInfoString(&str, sepstr);
/* call the appropriate type output function, append the result */
appendStringInfoString(&str,
OutputFunctionCall(&foutcache[i], value));
}
}
result = cstring_to_text_with_len(str.data, str.len);
pfree(str.data);
return result;
}
/* *Concatenateallarguments.NULLargumentsareignored.
*/
Datum
text_concat(PG_FUNCTION_ARGS)
{
text *result;
result = concat_internal("", 0, fcinfo); if (result == NULL)
PG_RETURN_NULL();
PG_RETURN_TEXT_P(result);
}
/* *Concatenateallbutfirstargumentvaluewithseparators.Thefirst *parameterisusedastheseparator.NULLargumentsareignored.
*/
Datum
text_concat_ws(PG_FUNCTION_ARGS)
{ char *sep;
text *result;
/* return NULL when separator is NULL */ if (PG_ARGISNULL(0))
PG_RETURN_NULL();
sep = text_to_cstring(PG_GETARG_TEXT_PP(0));
result = concat_internal(sep, 1, fcinfo); if (result == NULL)
PG_RETURN_NULL();
PG_RETURN_TEXT_P(result);
}
/* *Returnfirstncharactersinthestring.Whennisnegative, *returnallbutlast|n|characters.
*/
Datum
text_left(PG_FUNCTION_ARGS)
{ int n = PG_GETARG_INT32(1);
if (n < 0)
{
text *str = PG_GETARG_TEXT_PP(0); constchar *p = VARDATA_ANY(str); int len = VARSIZE_ANY_EXHDR(str); int rlen;
n = pg_mbstrlen_with_len(p, len) + n;
rlen = pg_mbcharcliplen(p, len, n);
PG_RETURN_TEXT_P(cstring_to_text_with_len(p, rlen));
} else
PG_RETURN_TEXT_P(text_substring(PG_GETARG_DATUM(0), 1, n, false));
}
/* *Returnlastncharactersinthestring.Whennisnegative, *returnallbutfirst|n|characters.
*/
Datum
text_right(PG_FUNCTION_ARGS)
{
text *str = PG_GETARG_TEXT_PP(0); constchar *p = VARDATA_ANY(str); int len = VARSIZE_ANY_EXHDR(str); int n = PG_GETARG_INT32(1); int off;
if (n < 0)
n = -n; else
n = pg_mbstrlen_with_len(p, len) - n;
off = pg_mbcharcliplen(p, len, n);
PG_RETURN_TEXT_P(cstring_to_text_with_len(p + off, len - off));
}
/* *Returnreversedstring
*/
Datum
text_reverse(PG_FUNCTION_ARGS)
{
text *str = PG_GETARG_TEXT_PP(0); constchar *p = VARDATA_ANY(str); int len = VARSIZE_ANY_EXHDR(str); constchar *endp = p + len;
text *result; char *dst;
result = palloc(len + VARHDRSZ);
dst = (char *) VARDATA(result) + len;
SET_VARSIZE(result, len + VARHDRSZ);
if (pg_database_encoding_max_length() > 1)
{ /* multibyte version */ while (p < endp)
{ int sz;
sz = pg_mblen_range(p, endp);
dst -= sz;
memcpy(dst, p, sz);
p += sz;
}
} else
{ /* single byte version */ while (p < endp)
*(--dst) = *p++;
}
PG_RETURN_TEXT_P(result);
}
/* *Supportmacrosfortext_format()
*/ #define TEXT_FORMAT_FLAG_MINUS 0x0001 /* is minus flag present? */
#define ADVANCE_PARSE_POINTER(ptr,end_ptr) \ do { \ if (++(ptr) >= (end_ptr)) \
ereport(ERROR, \
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), \
errmsg("unterminated format() type specifier"), \
errhint("For a single \"%%\" use \"%%%%\"."))); \
} while (0)
/* *Returnsaformattedstring
*/
Datum
text_format(PG_FUNCTION_ARGS)
{
text *fmt;
StringInfoData str; constchar *cp; constchar *start_ptr; constchar *end_ptr;
text *result; int arg; bool funcvariadic; int nargs;
Datum *elements = NULL; bool *nulls = NULL;
Oid element_type = InvalidOid;
Oid prev_type = InvalidOid;
Oid prev_width_type = InvalidOid;
FmgrInfo typoutputfinfo;
FmgrInfo typoutputinfo_width;
/* When format string is null, immediately return null */ if (PG_ARGISNULL(0))
PG_RETURN_NULL();
/* If argument is marked VARIADIC, expand array into elements */ if (get_fn_expr_variadic(fcinfo->flinfo))
{
ArrayType *arr;
int16 elmlen; bool elmbyval; char elmalign; int nitems;
/* Should have just the one argument */
Assert(PG_NARGS() == 2);
/* If argument is NULL, we treat it as zero-length array */ if (PG_ARGISNULL(1))
nitems = 0; else
{ /* *Non-nullargumenthadbetterbeanarray.Weassumethatany *callcontextthatcouldletget_fn_expr_variadicreturntrue *willhavecheckedthataVARIADIC-labeledparameteractuallyis *anarray.SoitshouldbeokaytojustAssertthatit'san *arrayratherthandoingafull-fledgederrorcheck.
*/
Assert(OidIsValid(get_base_element_type(get_fn_expr_argtype(fcinfo->flinfo, 1))));
/* OK, safe to fetch the array value */
arr = PG_GETARG_ARRAYTYPE_P(1);
/* Get info about array element type */
element_type = ARR_ELEMTYPE(arr);
get_typlenbyvalalign(element_type,
&elmlen, &elmbyval, &elmalign);
/* Extract all array elements */
deconstruct_array(arr, element_type, elmlen, elmbyval, elmalign,
&elements, &nulls, &nitems);
}
/* Setup for main loop. */
fmt = PG_GETARG_TEXT_PP(0);
start_ptr = VARDATA_ANY(fmt);
end_ptr = start_ptr + VARSIZE_ANY_EXHDR(fmt);
initStringInfo(&str);
arg = 1; /* next argument position to print */
/* Scan format string, looking for conversion specifiers. */ for (cp = start_ptr; cp < end_ptr; cp++)
{ int argpos; int widthpos; int flags; int width;
Datum value; bool isNull;
Oid typid;
/* Easy case: %% outputs a single % */ if (*cp == '%')
{
appendStringInfoCharMacro(&str, *cp); continue;
}
/* Parse the optional portions of the format specifier */
cp = text_format_parse_format(cp, end_ptr,
&argpos, &widthpos,
&flags, &width);
/* *Nextweshouldseethemainconversionspecifier.Whetherornot *anargumentpositionwaspresent,it'sknownthatatleastone *characterremainsinthestringatthispoint.Experiencesuggests *thatit'sworthcheckingthatthatcharacterisoneoftheexpected *onesbeforewetrytofetcharguments,soastoproducetheleast *confusingresponsetoamis-formattedspecifier.
*/ if (strchr("sIL", *cp) == NULL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("unrecognized format() type specifier \"%.*s\"",
pg_mblen_range(cp, end_ptr), cp),
errhint("For a single \"%%\" use \"%%%%\".")));
/* If indirect width was specified, get its value */ if (widthpos >= 0)
{ /* Collect the specified or next argument position */ if (widthpos > 0)
arg = widthpos; if (arg >= nargs)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("too few arguments for format()")));
/* Get the value and type of the selected argument */ if (!funcvariadic)
{
value = PG_GETARG_DATUM(arg);
isNull = PG_ARGISNULL(arg);
typid = get_fn_expr_argtype(fcinfo->flinfo, arg);
} else
{
value = elements[arg - 1];
isNull = nulls[arg - 1];
typid = element_type;
} if (!OidIsValid(typid))
elog(ERROR, "could not determine data type of format() input");
arg++;
/* We can treat NULL width the same as zero */ if (isNull)
width = 0; elseif (typid == INT4OID)
width = DatumGetInt32(value); elseif (typid == INT2OID)
width = DatumGetInt16(value); else
{ /* For less-usual datatypes, convert to text then to int */ char *str;
if (typid != prev_width_type)
{
Oid typoutputfunc; bool typIsVarlena;
/* pg_strtoint32 will complain about bad data or overflow */
width = pg_strtoint32(str);
pfree(str);
}
}
/* Collect the specified or next argument position */ if (argpos > 0)
arg = argpos; if (arg >= nargs)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("too few arguments for format()")));
/* Get the value and type of the selected argument */ if (!funcvariadic)
{
value = PG_GETARG_DATUM(arg);
isNull = PG_ARGISNULL(arg);
typid = get_fn_expr_argtype(fcinfo->flinfo, arg);
} else
{
value = elements[arg - 1];
isNull = nulls[arg - 1];
typid = element_type;
} if (!OidIsValid(typid))
elog(ERROR, "could not determine data type of format() input");
arg++;
/* *GettheappropriatetypOutputfunction,reusingpreviousoneif *sametypeaspreviousargument.That'sparticularlyusefulinthe *variadic-arraycase,butoftensavesworkevenforordinarycalls.
*/ if (typid != prev_type)
{
Oid typoutputfunc; bool typIsVarlena;
if (unlikely(pg_mul_s32_overflow(val, 10, &val)) ||
unlikely(pg_add_s32_overflow(val, digit, &val)))
ereport(ERROR,
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
errmsg("number is out of range")));
ADVANCE_PARSE_POINTER(cp, end_ptr);
found = true;
}
*ptr = cp;
*value = val;
return found;
}
/* *Parseaformatspecifier(generallyfollowingtheSUSprintfspec). * *Wehavealreadyadvancedovertheinitial'%',andwearelookingfor *[argpos][flags][width]type(butthetypecharacterisnotconsumedhere). * *Inputsarestart_ptr(thepositionafter'%')andend_ptr(stringend+1). *Outputparameters: *argpos:argumentpositionforvaluetobeprinted.-1meansunspecified. *widthpos:argumentpositionforwidth.Zeromeanstheargumentposition *wasunspecified(ie,takethenextarg)and-1meansnowidth *argument(widthwasomittedorspecifiedasaconstant). *flags:bitmaskofflags. *width:directly-specifiedwidthvalue.Zeromeansthewidthwasomitted *(noteit'snotnecessarytodistinguishthiscasefromanexplicit *zerowidthvalue). * *Thefunctionresultisthenextcharacterpositiontobeparsed,ie,the *locationwherethetypecharacteris/shouldbe. * *Noteparsinginvariant:atleastonecharacterisknownavailablebefore *stringend(end_ptr)atentry,andthisisstilltrueatexit.
*/ staticconstchar *
text_format_parse_format(constchar *start_ptr, constchar *end_ptr, int *argpos, int *widthpos, int *flags, int *width)
{ constchar *cp = start_ptr; int n;
/* set defaults for output parameters */
*argpos = -1;
*widthpos = -1;
*flags = 0;
*width = 0;
/* try to identify first number */ if (text_format_parse_digits(&cp, end_ptr, &n))
{ if (*cp != '$')
{ /* Must be just a width and a type, so we're done */
*width = n; return cp;
} /* The number was argument position */
*argpos = n; /* Explicit 0 for argument index is immediately refused */ if (n == 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("format specifies argument 0, but arguments are numbered from 1")));
ADVANCE_PARSE_POINTER(cp, end_ptr);
}
/* Handle flags (only minus is supported now) */ while (*cp == '-')
{
*flags |= TEXT_FORMAT_FLAG_MINUS;
ADVANCE_PARSE_POINTER(cp, end_ptr);
}
if (*cp == '*')
{ /* Handle indirect width */
ADVANCE_PARSE_POINTER(cp, end_ptr); if (text_format_parse_digits(&cp, end_ptr, &n))
{ /* number in this position must be closed by $ */ if (*cp != '$')
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("width argument position must be ended by \"$\""))); /* The number was width argument position */
*widthpos = n; /* Explicit 0 for argument index is immediately refused */ if (n == 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("format specifies argument 0, but arguments are numbered from 1")));
ADVANCE_PARSE_POINTER(cp, end_ptr);
} else
*widthpos = 0; /* width's argument position is unspecified */
} else
{ /* Check for direct width specification */ if (text_format_parse_digits(&cp, end_ptr, &n))
*width = n;
}
/* cp should now be pointing at type character */ return cp;
}
/* *Formata%s,%I,or%Lconversion
*/ staticvoid
text_format_string_conversion(StringInfo buf, char conversion,
FmgrInfo *typOutputInfo,
Datum value, bool isNull, int flags, int width)
{ char *str;
/* Handle NULL arguments before trying to stringify the value. */ if (isNull)
{ if (conversion == 's')
text_format_append_string(buf, "", flags, width); elseif (conversion == 'L')
text_format_append_string(buf, "NULL", flags, width); elseif (conversion == 'I')
ereport(ERROR,
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
errmsg("null values cannot be formatted as an SQL identifier"))); return;
}
/* Escape. */ if (conversion == 'I')
{ /* quote_identifier may or may not allocate a new string. */
text_format_append_string(buf, quote_identifier(str), flags, width);
} elseif (conversion == 'L')
{ char *qstr = quote_literal_cstr(str);
text_format_append_string(buf, qstr, flags, width); /* quote_literal_cstr() always allocates a new string */
pfree(qstr);
} else
text_format_append_string(buf, str, flags, width);
/* Cleanup. */
pfree(str);
}
/* *Appendstrtobuf,paddingasdirectedbyflags/width
*/ staticvoid
text_format_append_string(StringInfo buf, constchar *str, int flags, int width)
{ bool align_to_left = false; int len;
/* fast path for typical easy case */ if (width == 0)
{
appendStringInfoString(buf, str); return;
}
if (width < 0)
{ /* Negative width: implicit '-' flag, then take absolute value */
align_to_left = true; /* -INT_MIN is undefined */ if (width <= INT_MIN)
ereport(ERROR,
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
errmsg("number is out of range")));
width = -width;
} elseif (flags & TEXT_FORMAT_FLAG_MINUS)
align_to_left = true;
len = pg_mbstrlen(str); if (align_to_left)
{ /* left justify */
appendStringInfoString(buf, str); if (len < width)
appendStringInfoSpaces(buf, width - len);
} else
{ /* right justify */ if (len < width)
appendStringInfoSpaces(buf, width - len);
appendStringInfoString(buf, str);
}
}
static UnicodeNormalizationForm
unicode_norm_form_from_string(constchar *formstr)
{
UnicodeNormalizationForm form = -1;
/* *Mightaswellcheckthiswhilewe'rehere.
*/ if (GetDatabaseEncoding() != PG_UTF8)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("Unicode normalization can only be performed if server encoding is UTF8")));
if (pg_strcasecmp(formstr, "NFC") == 0)
form = UNICODE_NFC; elseif (pg_strcasecmp(formstr, "NFD") == 0)
form = UNICODE_NFD; elseif (pg_strcasecmp(formstr, "NFKC") == 0)
form = UNICODE_NFKC; elseif (pg_strcasecmp(formstr, "NFKD") == 0)
form = UNICODE_NFKD; else
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid normalization form: %s", formstr)));
/* *CheckwhetherthestringcontainsonlyassignedUnicodecode *points.RequiresthatthedatabaseencodingisUTF-8.
*/
Datum
unicode_assigned(PG_FUNCTION_ARGS)
{
text *input = PG_GETARG_TEXT_PP(0); unsignedchar *p; int size;
if (GetDatabaseEncoding() != PG_UTF8)
ereport(ERROR,
(errmsg("Unicode categorization can only be performed if server encoding is UTF8")));
/* convert to pg_wchar */
size = pg_mbstrlen_with_len(VARDATA_ANY(input), VARSIZE_ANY_EXHDR(input));
p = (unsignedchar *) VARDATA_ANY(input); for (int i = 0; i < size; i++)
{
pg_wchar uchar = utf8_to_unicode(p); int category = unicode_category(uchar);
if (category == PG_U_UNASSIGNED)
PG_RETURN_BOOL(false);
p += pg_utf_mblen(p);
}
PG_RETURN_BOOL(true);
}
Datum
unicode_normalize_func(PG_FUNCTION_ARGS)
{
text *input = PG_GETARG_TEXT_PP(0); char *formstr = text_to_cstring(PG_GETARG_TEXT_PP(1));
UnicodeNormalizationForm form;
size_t size;
pg_wchar *input_chars;
pg_wchar *output_chars; unsignedchar *p;
text *result;
size_t i;
form = unicode_norm_form_from_string(formstr);
/* convert to pg_wchar */
size = pg_mbstrlen_with_len(VARDATA_ANY(input), VARSIZE_ANY_EXHDR(input));
input_chars = palloc_array(pg_wchar, size + 1);
p = (unsignedchar *) VARDATA_ANY(input); for (i = 0; i < size; i++)
{
input_chars[i] = utf8_to_unicode(p);
p += pg_utf_mblen(p);
}
input_chars[i] = (pg_wchar) '\0';
Assert((char *) p == VARDATA_ANY(input) + VARSIZE_ANY_EXHDR(input));
/* *Checkiffirstncharsarehexadecimaldigits
*/ staticbool
isxdigits_n(constchar *instr, size_t n)
{ for (size_t i = 0; i < n; i++) if (!isxdigit((unsignedchar) instr[i])) returnfalse;
returntrue;
}
staticunsignedint
hexval(unsignedchar c)
{ if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 0xA; if (c >= 'A' && c <= 'F') return c - 'A' + 0xA;
elog(ERROR, "invalid hexadecimal digit"); return0; /* not reached */
}
¤ Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.0.338Bemerkung:
(vorverarbeitet am 2026-08-08)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.