Header And Logo

PostgreSQL
| The world's most advanced open source database.

Defines | Functions | Variables

builtins.h File Reference

#include "fmgr.h"
#include "nodes/parsenodes.h"
Include dependency graph for builtins.h:

Go to the source code of this file.

Defines

#define CStringGetTextDatum(s)   PointerGetDatum(cstring_to_text(s))
#define TextDatumGetCString(d)   text_to_cstring((text *) DatumGetPointer(d))

Functions

Datum has_any_column_privilege_name_name (PG_FUNCTION_ARGS)
Datum has_any_column_privilege_name_id (PG_FUNCTION_ARGS)
Datum has_any_column_privilege_id_name (PG_FUNCTION_ARGS)
Datum has_any_column_privilege_id_id (PG_FUNCTION_ARGS)
Datum has_any_column_privilege_name (PG_FUNCTION_ARGS)
Datum has_any_column_privilege_id (PG_FUNCTION_ARGS)
Datum has_column_privilege_name_name_name (PG_FUNCTION_ARGS)
Datum has_column_privilege_name_name_attnum (PG_FUNCTION_ARGS)
Datum has_column_privilege_name_id_name (PG_FUNCTION_ARGS)
Datum has_column_privilege_name_id_attnum (PG_FUNCTION_ARGS)
Datum has_column_privilege_id_name_name (PG_FUNCTION_ARGS)
Datum has_column_privilege_id_name_attnum (PG_FUNCTION_ARGS)
Datum has_column_privilege_id_id_name (PG_FUNCTION_ARGS)
Datum has_column_privilege_id_id_attnum (PG_FUNCTION_ARGS)
Datum has_column_privilege_name_name (PG_FUNCTION_ARGS)
Datum has_column_privilege_name_attnum (PG_FUNCTION_ARGS)
Datum has_column_privilege_id_name (PG_FUNCTION_ARGS)
Datum has_column_privilege_id_attnum (PG_FUNCTION_ARGS)
Datum has_table_privilege_name_name (PG_FUNCTION_ARGS)
Datum has_table_privilege_name_id (PG_FUNCTION_ARGS)
Datum has_table_privilege_id_name (PG_FUNCTION_ARGS)
Datum has_table_privilege_id_id (PG_FUNCTION_ARGS)
Datum has_table_privilege_name (PG_FUNCTION_ARGS)
Datum has_table_privilege_id (PG_FUNCTION_ARGS)
Datum has_sequence_privilege_name_name (PG_FUNCTION_ARGS)
Datum has_sequence_privilege_name_id (PG_FUNCTION_ARGS)
Datum has_sequence_privilege_id_name (PG_FUNCTION_ARGS)
Datum has_sequence_privilege_id_id (PG_FUNCTION_ARGS)
Datum has_sequence_privilege_name (PG_FUNCTION_ARGS)
Datum has_sequence_privilege_id (PG_FUNCTION_ARGS)
Datum has_database_privilege_name_name (PG_FUNCTION_ARGS)
Datum has_database_privilege_name_id (PG_FUNCTION_ARGS)
Datum has_database_privilege_id_name (PG_FUNCTION_ARGS)
Datum has_database_privilege_id_id (PG_FUNCTION_ARGS)
Datum has_database_privilege_name (PG_FUNCTION_ARGS)
Datum has_database_privilege_id (PG_FUNCTION_ARGS)
Datum has_foreign_data_wrapper_privilege_name_name (PG_FUNCTION_ARGS)
Datum has_foreign_data_wrapper_privilege_name_id (PG_FUNCTION_ARGS)
Datum has_foreign_data_wrapper_privilege_id_name (PG_FUNCTION_ARGS)
Datum has_foreign_data_wrapper_privilege_id_id (PG_FUNCTION_ARGS)
Datum has_foreign_data_wrapper_privilege_name (PG_FUNCTION_ARGS)
Datum has_foreign_data_wrapper_privilege_id (PG_FUNCTION_ARGS)
Datum has_function_privilege_name_name (PG_FUNCTION_ARGS)
Datum has_function_privilege_name_id (PG_FUNCTION_ARGS)
Datum has_function_privilege_id_name (PG_FUNCTION_ARGS)
Datum has_function_privilege_id_id (PG_FUNCTION_ARGS)
Datum has_function_privilege_name (PG_FUNCTION_ARGS)
Datum has_function_privilege_id (PG_FUNCTION_ARGS)
Datum has_language_privilege_name_name (PG_FUNCTION_ARGS)
Datum has_language_privilege_name_id (PG_FUNCTION_ARGS)
Datum has_language_privilege_id_name (PG_FUNCTION_ARGS)
Datum has_language_privilege_id_id (PG_FUNCTION_ARGS)
Datum has_language_privilege_name (PG_FUNCTION_ARGS)
Datum has_language_privilege_id (PG_FUNCTION_ARGS)
Datum has_schema_privilege_name_name (PG_FUNCTION_ARGS)
Datum has_schema_privilege_name_id (PG_FUNCTION_ARGS)
Datum has_schema_privilege_id_name (PG_FUNCTION_ARGS)
Datum has_schema_privilege_id_id (PG_FUNCTION_ARGS)
Datum has_schema_privilege_name (PG_FUNCTION_ARGS)
Datum has_schema_privilege_id (PG_FUNCTION_ARGS)
Datum has_server_privilege_name_name (PG_FUNCTION_ARGS)
Datum has_server_privilege_name_id (PG_FUNCTION_ARGS)
Datum has_server_privilege_id_name (PG_FUNCTION_ARGS)
Datum has_server_privilege_id_id (PG_FUNCTION_ARGS)
Datum has_server_privilege_name (PG_FUNCTION_ARGS)
Datum has_server_privilege_id (PG_FUNCTION_ARGS)
Datum has_tablespace_privilege_name_name (PG_FUNCTION_ARGS)
Datum has_tablespace_privilege_name_id (PG_FUNCTION_ARGS)
Datum has_tablespace_privilege_id_name (PG_FUNCTION_ARGS)
Datum has_tablespace_privilege_id_id (PG_FUNCTION_ARGS)
Datum has_tablespace_privilege_name (PG_FUNCTION_ARGS)
Datum has_tablespace_privilege_id (PG_FUNCTION_ARGS)
Datum has_type_privilege_name_name (PG_FUNCTION_ARGS)
Datum has_type_privilege_name_id (PG_FUNCTION_ARGS)
Datum has_type_privilege_id_name (PG_FUNCTION_ARGS)
Datum has_type_privilege_id_id (PG_FUNCTION_ARGS)
Datum has_type_privilege_name (PG_FUNCTION_ARGS)
Datum has_type_privilege_id (PG_FUNCTION_ARGS)
Datum pg_has_role_name_name (PG_FUNCTION_ARGS)
Datum pg_has_role_name_id (PG_FUNCTION_ARGS)
Datum pg_has_role_id_name (PG_FUNCTION_ARGS)
Datum pg_has_role_id_id (PG_FUNCTION_ARGS)
Datum pg_has_role_name (PG_FUNCTION_ARGS)
Datum pg_has_role_id (PG_FUNCTION_ARGS)
Datum boolin (PG_FUNCTION_ARGS)
Datum boolout (PG_FUNCTION_ARGS)
Datum boolrecv (PG_FUNCTION_ARGS)
Datum boolsend (PG_FUNCTION_ARGS)
Datum booltext (PG_FUNCTION_ARGS)
Datum booleq (PG_FUNCTION_ARGS)
Datum boolne (PG_FUNCTION_ARGS)
Datum boollt (PG_FUNCTION_ARGS)
Datum boolgt (PG_FUNCTION_ARGS)
Datum boolle (PG_FUNCTION_ARGS)
Datum boolge (PG_FUNCTION_ARGS)
Datum booland_statefunc (PG_FUNCTION_ARGS)
Datum boolor_statefunc (PG_FUNCTION_ARGS)
bool parse_bool (const char *value, bool *result)
bool parse_bool_with_len (const char *value, size_t len, bool *result)
Datum charin (PG_FUNCTION_ARGS)
Datum charout (PG_FUNCTION_ARGS)
Datum charrecv (PG_FUNCTION_ARGS)
Datum charsend (PG_FUNCTION_ARGS)
Datum chareq (PG_FUNCTION_ARGS)
Datum charne (PG_FUNCTION_ARGS)
Datum charlt (PG_FUNCTION_ARGS)
Datum charle (PG_FUNCTION_ARGS)
Datum chargt (PG_FUNCTION_ARGS)
Datum charge (PG_FUNCTION_ARGS)
Datum chartoi4 (PG_FUNCTION_ARGS)
Datum i4tochar (PG_FUNCTION_ARGS)
Datum text_char (PG_FUNCTION_ARGS)
Datum char_text (PG_FUNCTION_ARGS)
Datum domain_in (PG_FUNCTION_ARGS)
Datum domain_recv (PG_FUNCTION_ARGS)
void domain_check (Datum value, bool isnull, Oid domainType, void **extra, MemoryContext mcxt)
int errdatatype (Oid datatypeOid)
int errdomainconstraint (Oid datatypeOid, const char *conname)
Datum binary_encode (PG_FUNCTION_ARGS)
Datum binary_decode (PG_FUNCTION_ARGS)
unsigned hex_encode (const char *src, unsigned len, char *dst)
unsigned hex_decode (const char *src, unsigned len, char *dst)
Datum enum_in (PG_FUNCTION_ARGS)
Datum enum_out (PG_FUNCTION_ARGS)
Datum enum_recv (PG_FUNCTION_ARGS)
Datum enum_send (PG_FUNCTION_ARGS)
Datum enum_lt (PG_FUNCTION_ARGS)
Datum enum_le (PG_FUNCTION_ARGS)
Datum enum_eq (PG_FUNCTION_ARGS)
Datum enum_ne (PG_FUNCTION_ARGS)
Datum enum_ge (PG_FUNCTION_ARGS)
Datum enum_gt (PG_FUNCTION_ARGS)
Datum enum_cmp (PG_FUNCTION_ARGS)
Datum enum_smaller (PG_FUNCTION_ARGS)
Datum enum_larger (PG_FUNCTION_ARGS)
Datum enum_first (PG_FUNCTION_ARGS)
Datum enum_last (PG_FUNCTION_ARGS)
Datum enum_range_bounds (PG_FUNCTION_ARGS)
Datum enum_range_all (PG_FUNCTION_ARGS)
Datum int2in (PG_FUNCTION_ARGS)
Datum int2out (PG_FUNCTION_ARGS)
Datum int2recv (PG_FUNCTION_ARGS)
Datum int2send (PG_FUNCTION_ARGS)
Datum int2vectorin (PG_FUNCTION_ARGS)
Datum int2vectorout (PG_FUNCTION_ARGS)
Datum int2vectorrecv (PG_FUNCTION_ARGS)
Datum int2vectorsend (PG_FUNCTION_ARGS)
Datum int2vectoreq (PG_FUNCTION_ARGS)
Datum int4in (PG_FUNCTION_ARGS)
Datum int4out (PG_FUNCTION_ARGS)
Datum int4recv (PG_FUNCTION_ARGS)
Datum int4send (PG_FUNCTION_ARGS)
Datum i2toi4 (PG_FUNCTION_ARGS)
Datum i4toi2 (PG_FUNCTION_ARGS)
Datum int4_bool (PG_FUNCTION_ARGS)
Datum bool_int4 (PG_FUNCTION_ARGS)
Datum int4eq (PG_FUNCTION_ARGS)
Datum int4ne (PG_FUNCTION_ARGS)
Datum int4lt (PG_FUNCTION_ARGS)
Datum int4le (PG_FUNCTION_ARGS)
Datum int4gt (PG_FUNCTION_ARGS)
Datum int4ge (PG_FUNCTION_ARGS)
Datum int2eq (PG_FUNCTION_ARGS)
Datum int2ne (PG_FUNCTION_ARGS)
Datum int2lt (PG_FUNCTION_ARGS)
Datum int2le (PG_FUNCTION_ARGS)
Datum int2gt (PG_FUNCTION_ARGS)
Datum int2ge (PG_FUNCTION_ARGS)
Datum int24eq (PG_FUNCTION_ARGS)
Datum int24ne (PG_FUNCTION_ARGS)
Datum int24lt (PG_FUNCTION_ARGS)
Datum int24le (PG_FUNCTION_ARGS)
Datum int24gt (PG_FUNCTION_ARGS)
Datum int24ge (PG_FUNCTION_ARGS)
Datum int42eq (PG_FUNCTION_ARGS)
Datum int42ne (PG_FUNCTION_ARGS)
Datum int42lt (PG_FUNCTION_ARGS)
Datum int42le (PG_FUNCTION_ARGS)
Datum int42gt (PG_FUNCTION_ARGS)
Datum int42ge (PG_FUNCTION_ARGS)
Datum int4um (PG_FUNCTION_ARGS)
Datum int4up (PG_FUNCTION_ARGS)
Datum int4pl (PG_FUNCTION_ARGS)
Datum int4mi (PG_FUNCTION_ARGS)
Datum int4mul (PG_FUNCTION_ARGS)
Datum int4div (PG_FUNCTION_ARGS)
Datum int4abs (PG_FUNCTION_ARGS)
Datum int4inc (PG_FUNCTION_ARGS)
Datum int2um (PG_FUNCTION_ARGS)
Datum int2up (PG_FUNCTION_ARGS)
Datum int2pl (PG_FUNCTION_ARGS)
Datum int2mi (PG_FUNCTION_ARGS)
Datum int2mul (PG_FUNCTION_ARGS)
Datum int2div (PG_FUNCTION_ARGS)
Datum int2abs (PG_FUNCTION_ARGS)
Datum int24pl (PG_FUNCTION_ARGS)
Datum int24mi (PG_FUNCTION_ARGS)
Datum int24mul (PG_FUNCTION_ARGS)
Datum int24div (PG_FUNCTION_ARGS)
Datum int42pl (PG_FUNCTION_ARGS)
Datum int42mi (PG_FUNCTION_ARGS)
Datum int42mul (PG_FUNCTION_ARGS)
Datum int42div (PG_FUNCTION_ARGS)
Datum int4mod (PG_FUNCTION_ARGS)
Datum int2mod (PG_FUNCTION_ARGS)
Datum int2larger (PG_FUNCTION_ARGS)
Datum int2smaller (PG_FUNCTION_ARGS)
Datum int4larger (PG_FUNCTION_ARGS)
Datum int4smaller (PG_FUNCTION_ARGS)
Datum int4and (PG_FUNCTION_ARGS)
Datum int4or (PG_FUNCTION_ARGS)
Datum int4xor (PG_FUNCTION_ARGS)
Datum int4not (PG_FUNCTION_ARGS)
Datum int4shl (PG_FUNCTION_ARGS)
Datum int4shr (PG_FUNCTION_ARGS)
Datum int2and (PG_FUNCTION_ARGS)
Datum int2or (PG_FUNCTION_ARGS)
Datum int2xor (PG_FUNCTION_ARGS)
Datum int2not (PG_FUNCTION_ARGS)
Datum int2shl (PG_FUNCTION_ARGS)
Datum int2shr (PG_FUNCTION_ARGS)
Datum generate_series_int4 (PG_FUNCTION_ARGS)
Datum generate_series_step_int4 (PG_FUNCTION_ARGS)
int2vectorbuildint2vector (const int16 *int2s, int n)
Datum namein (PG_FUNCTION_ARGS)
Datum nameout (PG_FUNCTION_ARGS)
Datum namerecv (PG_FUNCTION_ARGS)
Datum namesend (PG_FUNCTION_ARGS)
Datum nameeq (PG_FUNCTION_ARGS)
Datum namene (PG_FUNCTION_ARGS)
Datum namelt (PG_FUNCTION_ARGS)
Datum namele (PG_FUNCTION_ARGS)
Datum namegt (PG_FUNCTION_ARGS)
Datum namege (PG_FUNCTION_ARGS)
int namecpy (Name n1, Name n2)
int namestrcpy (Name name, const char *str)
int namestrcmp (Name name, const char *str)
Datum current_user (PG_FUNCTION_ARGS)
Datum session_user (PG_FUNCTION_ARGS)
Datum current_schema (PG_FUNCTION_ARGS)
Datum current_schemas (PG_FUNCTION_ARGS)
int32 pg_atoi (char *s, int size, int c)
void pg_itoa (int16 i, char *a)
void pg_ltoa (int32 l, char *a)
void pg_lltoa (int64 ll, char *a)
Datum btboolcmp (PG_FUNCTION_ARGS)
Datum btint2cmp (PG_FUNCTION_ARGS)
Datum btint4cmp (PG_FUNCTION_ARGS)
Datum btint8cmp (PG_FUNCTION_ARGS)
Datum btfloat4cmp (PG_FUNCTION_ARGS)
Datum btfloat8cmp (PG_FUNCTION_ARGS)
Datum btint48cmp (PG_FUNCTION_ARGS)
Datum btint84cmp (PG_FUNCTION_ARGS)
Datum btint24cmp (PG_FUNCTION_ARGS)
Datum btint42cmp (PG_FUNCTION_ARGS)
Datum btint28cmp (PG_FUNCTION_ARGS)
Datum btint82cmp (PG_FUNCTION_ARGS)
Datum btfloat48cmp (PG_FUNCTION_ARGS)
Datum btfloat84cmp (PG_FUNCTION_ARGS)
Datum btoidcmp (PG_FUNCTION_ARGS)
Datum btoidvectorcmp (PG_FUNCTION_ARGS)
Datum btabstimecmp (PG_FUNCTION_ARGS)
Datum btreltimecmp (PG_FUNCTION_ARGS)
Datum bttintervalcmp (PG_FUNCTION_ARGS)
Datum btcharcmp (PG_FUNCTION_ARGS)
Datum btnamecmp (PG_FUNCTION_ARGS)
Datum bttextcmp (PG_FUNCTION_ARGS)
Datum btint2sortsupport (PG_FUNCTION_ARGS)
Datum btint4sortsupport (PG_FUNCTION_ARGS)
Datum btint8sortsupport (PG_FUNCTION_ARGS)
Datum btfloat4sortsupport (PG_FUNCTION_ARGS)
Datum btfloat8sortsupport (PG_FUNCTION_ARGS)
Datum btoidsortsupport (PG_FUNCTION_ARGS)
Datum btnamesortsupport (PG_FUNCTION_ARGS)
double get_float8_infinity (void)
float get_float4_infinity (void)
double get_float8_nan (void)
float get_float4_nan (void)
int is_infinite (double val)
Datum float4in (PG_FUNCTION_ARGS)
Datum float4out (PG_FUNCTION_ARGS)
Datum float4recv (PG_FUNCTION_ARGS)
Datum float4send (PG_FUNCTION_ARGS)
Datum float8in (PG_FUNCTION_ARGS)
Datum float8out (PG_FUNCTION_ARGS)
Datum float8recv (PG_FUNCTION_ARGS)
Datum float8send (PG_FUNCTION_ARGS)
Datum float4abs (PG_FUNCTION_ARGS)
Datum float4um (PG_FUNCTION_ARGS)
Datum float4up (PG_FUNCTION_ARGS)
Datum float4larger (PG_FUNCTION_ARGS)
Datum float4smaller (PG_FUNCTION_ARGS)
Datum float8abs (PG_FUNCTION_ARGS)
Datum float8um (PG_FUNCTION_ARGS)
Datum float8up (PG_FUNCTION_ARGS)
Datum float8larger (PG_FUNCTION_ARGS)
Datum float8smaller (PG_FUNCTION_ARGS)
Datum float4pl (PG_FUNCTION_ARGS)
Datum float4mi (PG_FUNCTION_ARGS)
Datum float4mul (PG_FUNCTION_ARGS)
Datum float4div (PG_FUNCTION_ARGS)
Datum float8pl (PG_FUNCTION_ARGS)
Datum float8mi (PG_FUNCTION_ARGS)
Datum float8mul (PG_FUNCTION_ARGS)
Datum float8div (PG_FUNCTION_ARGS)
Datum float4eq (PG_FUNCTION_ARGS)
Datum float4ne (PG_FUNCTION_ARGS)
Datum float4lt (PG_FUNCTION_ARGS)
Datum float4le (PG_FUNCTION_ARGS)
Datum float4gt (PG_FUNCTION_ARGS)
Datum float4ge (PG_FUNCTION_ARGS)
Datum float8eq (PG_FUNCTION_ARGS)
Datum float8ne (PG_FUNCTION_ARGS)
Datum float8lt (PG_FUNCTION_ARGS)
Datum float8le (PG_FUNCTION_ARGS)
Datum float8gt (PG_FUNCTION_ARGS)
Datum float8ge (PG_FUNCTION_ARGS)
Datum ftod (PG_FUNCTION_ARGS)
Datum i4tod (PG_FUNCTION_ARGS)
Datum i2tod (PG_FUNCTION_ARGS)
Datum dtof (PG_FUNCTION_ARGS)
Datum dtoi4 (PG_FUNCTION_ARGS)
Datum dtoi2 (PG_FUNCTION_ARGS)
Datum i4tof (PG_FUNCTION_ARGS)
Datum i2tof (PG_FUNCTION_ARGS)
Datum ftoi4 (PG_FUNCTION_ARGS)
Datum ftoi2 (PG_FUNCTION_ARGS)
Datum dround (PG_FUNCTION_ARGS)
Datum dceil (PG_FUNCTION_ARGS)
Datum dfloor (PG_FUNCTION_ARGS)
Datum dsign (PG_FUNCTION_ARGS)
Datum dtrunc (PG_FUNCTION_ARGS)
Datum dsqrt (PG_FUNCTION_ARGS)
Datum dcbrt (PG_FUNCTION_ARGS)
Datum dpow (PG_FUNCTION_ARGS)
Datum dexp (PG_FUNCTION_ARGS)
Datum dlog1 (PG_FUNCTION_ARGS)
Datum dlog10 (PG_FUNCTION_ARGS)
Datum dacos (PG_FUNCTION_ARGS)
Datum dasin (PG_FUNCTION_ARGS)
Datum datan (PG_FUNCTION_ARGS)
Datum datan2 (PG_FUNCTION_ARGS)
Datum dcos (PG_FUNCTION_ARGS)
Datum dcot (PG_FUNCTION_ARGS)
Datum dsin (PG_FUNCTION_ARGS)
Datum dtan (PG_FUNCTION_ARGS)
Datum degrees (PG_FUNCTION_ARGS)
Datum dpi (PG_FUNCTION_ARGS)
Datum radians (PG_FUNCTION_ARGS)
Datum drandom (PG_FUNCTION_ARGS)
Datum setseed (PG_FUNCTION_ARGS)
Datum float8_accum (PG_FUNCTION_ARGS)
Datum float4_accum (PG_FUNCTION_ARGS)
Datum float8_avg (PG_FUNCTION_ARGS)
Datum float8_var_pop (PG_FUNCTION_ARGS)
Datum float8_var_samp (PG_FUNCTION_ARGS)
Datum float8_stddev_pop (PG_FUNCTION_ARGS)
Datum float8_stddev_samp (PG_FUNCTION_ARGS)
Datum float8_regr_accum (PG_FUNCTION_ARGS)
Datum float8_regr_sxx (PG_FUNCTION_ARGS)
Datum float8_regr_syy (PG_FUNCTION_ARGS)
Datum float8_regr_sxy (PG_FUNCTION_ARGS)
Datum float8_regr_avgx (PG_FUNCTION_ARGS)
Datum float8_regr_avgy (PG_FUNCTION_ARGS)
Datum float8_covar_pop (PG_FUNCTION_ARGS)
Datum float8_covar_samp (PG_FUNCTION_ARGS)
Datum float8_corr (PG_FUNCTION_ARGS)
Datum float8_regr_r2 (PG_FUNCTION_ARGS)
Datum float8_regr_slope (PG_FUNCTION_ARGS)
Datum float8_regr_intercept (PG_FUNCTION_ARGS)
Datum float48pl (PG_FUNCTION_ARGS)
Datum float48mi (PG_FUNCTION_ARGS)
Datum float48mul (PG_FUNCTION_ARGS)
Datum float48div (PG_FUNCTION_ARGS)
Datum float84pl (PG_FUNCTION_ARGS)
Datum float84mi (PG_FUNCTION_ARGS)
Datum float84mul (PG_FUNCTION_ARGS)
Datum float84div (PG_FUNCTION_ARGS)
Datum float48eq (PG_FUNCTION_ARGS)
Datum float48ne (PG_FUNCTION_ARGS)
Datum float48lt (PG_FUNCTION_ARGS)
Datum float48le (PG_FUNCTION_ARGS)
Datum float48gt (PG_FUNCTION_ARGS)
Datum float48ge (PG_FUNCTION_ARGS)
Datum float84eq (PG_FUNCTION_ARGS)
Datum float84ne (PG_FUNCTION_ARGS)
Datum float84lt (PG_FUNCTION_ARGS)
Datum float84le (PG_FUNCTION_ARGS)
Datum float84gt (PG_FUNCTION_ARGS)
Datum float84ge (PG_FUNCTION_ARGS)
Datum width_bucket_float8 (PG_FUNCTION_ARGS)
Datum pg_tablespace_size_oid (PG_FUNCTION_ARGS)
Datum pg_tablespace_size_name (PG_FUNCTION_ARGS)
Datum pg_database_size_oid (PG_FUNCTION_ARGS)
Datum pg_database_size_name (PG_FUNCTION_ARGS)
Datum pg_relation_size (PG_FUNCTION_ARGS)
Datum pg_total_relation_size (PG_FUNCTION_ARGS)
Datum pg_size_pretty (PG_FUNCTION_ARGS)
Datum pg_size_pretty_numeric (PG_FUNCTION_ARGS)
Datum pg_table_size (PG_FUNCTION_ARGS)
Datum pg_indexes_size (PG_FUNCTION_ARGS)
Datum pg_relation_filenode (PG_FUNCTION_ARGS)
Datum pg_relation_filepath (PG_FUNCTION_ARGS)
Datum pg_relation_is_scannable (PG_FUNCTION_ARGS)
bytearead_binary_file (const char *filename, int64 seek_offset, int64 bytes_to_read)
Datum pg_stat_file (PG_FUNCTION_ARGS)
Datum pg_read_file (PG_FUNCTION_ARGS)
Datum pg_read_file_all (PG_FUNCTION_ARGS)
Datum pg_read_binary_file (PG_FUNCTION_ARGS)
Datum pg_read_binary_file_all (PG_FUNCTION_ARGS)
Datum pg_ls_dir (PG_FUNCTION_ARGS)
Datum current_database (PG_FUNCTION_ARGS)
Datum current_query (PG_FUNCTION_ARGS)
Datum pg_cancel_backend (PG_FUNCTION_ARGS)
Datum pg_terminate_backend (PG_FUNCTION_ARGS)
Datum pg_reload_conf (PG_FUNCTION_ARGS)
Datum pg_tablespace_databases (PG_FUNCTION_ARGS)
Datum pg_tablespace_location (PG_FUNCTION_ARGS)
Datum pg_rotate_logfile (PG_FUNCTION_ARGS)
Datum pg_sleep (PG_FUNCTION_ARGS)
Datum pg_get_keywords (PG_FUNCTION_ARGS)
Datum pg_typeof (PG_FUNCTION_ARGS)
Datum pg_collation_for (PG_FUNCTION_ARGS)
Datum pg_view_is_insertable (PG_FUNCTION_ARGS)
Datum pg_view_is_updatable (PG_FUNCTION_ARGS)
Datum oidin (PG_FUNCTION_ARGS)
Datum oidout (PG_FUNCTION_ARGS)
Datum oidrecv (PG_FUNCTION_ARGS)
Datum oidsend (PG_FUNCTION_ARGS)
Datum oideq (PG_FUNCTION_ARGS)
Datum oidne (PG_FUNCTION_ARGS)
Datum oidlt (PG_FUNCTION_ARGS)
Datum oidle (PG_FUNCTION_ARGS)
Datum oidge (PG_FUNCTION_ARGS)
Datum oidgt (PG_FUNCTION_ARGS)
Datum oidlarger (PG_FUNCTION_ARGS)
Datum oidsmaller (PG_FUNCTION_ARGS)
Datum oidvectorin (PG_FUNCTION_ARGS)
Datum oidvectorout (PG_FUNCTION_ARGS)
Datum oidvectorrecv (PG_FUNCTION_ARGS)
Datum oidvectorsend (PG_FUNCTION_ARGS)
Datum oidvectoreq (PG_FUNCTION_ARGS)
Datum oidvectorne (PG_FUNCTION_ARGS)
Datum oidvectorlt (PG_FUNCTION_ARGS)
Datum oidvectorle (PG_FUNCTION_ARGS)
Datum oidvectorge (PG_FUNCTION_ARGS)
Datum oidvectorgt (PG_FUNCTION_ARGS)
oidvectorbuildoidvector (const Oid *oids, int n)
Oid oidparse (Node *node)
Datum cstring_in (PG_FUNCTION_ARGS)
Datum cstring_out (PG_FUNCTION_ARGS)
Datum cstring_recv (PG_FUNCTION_ARGS)
Datum cstring_send (PG_FUNCTION_ARGS)
Datum any_in (PG_FUNCTION_ARGS)
Datum any_out (PG_FUNCTION_ARGS)
Datum anyarray_in (PG_FUNCTION_ARGS)
Datum anyarray_out (PG_FUNCTION_ARGS)
Datum anyarray_recv (PG_FUNCTION_ARGS)
Datum anyarray_send (PG_FUNCTION_ARGS)
Datum anynonarray_in (PG_FUNCTION_ARGS)
Datum anynonarray_out (PG_FUNCTION_ARGS)
Datum anyenum_in (PG_FUNCTION_ARGS)
Datum anyenum_out (PG_FUNCTION_ARGS)
Datum anyrange_in (PG_FUNCTION_ARGS)
Datum anyrange_out (PG_FUNCTION_ARGS)
Datum void_in (PG_FUNCTION_ARGS)
Datum void_out (PG_FUNCTION_ARGS)
Datum void_recv (PG_FUNCTION_ARGS)
Datum void_send (PG_FUNCTION_ARGS)
Datum trigger_in (PG_FUNCTION_ARGS)
Datum trigger_out (PG_FUNCTION_ARGS)
Datum event_trigger_in (PG_FUNCTION_ARGS)
Datum event_trigger_out (PG_FUNCTION_ARGS)
Datum language_handler_in (PG_FUNCTION_ARGS)
Datum language_handler_out (PG_FUNCTION_ARGS)
Datum fdw_handler_in (PG_FUNCTION_ARGS)
Datum fdw_handler_out (PG_FUNCTION_ARGS)
Datum internal_in (PG_FUNCTION_ARGS)
Datum internal_out (PG_FUNCTION_ARGS)
Datum opaque_in (PG_FUNCTION_ARGS)
Datum opaque_out (PG_FUNCTION_ARGS)
Datum anyelement_in (PG_FUNCTION_ARGS)
Datum anyelement_out (PG_FUNCTION_ARGS)
Datum shell_in (PG_FUNCTION_ARGS)
Datum shell_out (PG_FUNCTION_ARGS)
Datum pg_node_tree_in (PG_FUNCTION_ARGS)
Datum pg_node_tree_out (PG_FUNCTION_ARGS)
Datum pg_node_tree_recv (PG_FUNCTION_ARGS)
Datum pg_node_tree_send (PG_FUNCTION_ARGS)
Datum nameregexeq (PG_FUNCTION_ARGS)
Datum nameregexne (PG_FUNCTION_ARGS)
Datum textregexeq (PG_FUNCTION_ARGS)
Datum textregexne (PG_FUNCTION_ARGS)
Datum nameicregexeq (PG_FUNCTION_ARGS)
Datum nameicregexne (PG_FUNCTION_ARGS)
Datum texticregexeq (PG_FUNCTION_ARGS)
Datum texticregexne (PG_FUNCTION_ARGS)
Datum textregexsubstr (PG_FUNCTION_ARGS)
Datum textregexreplace_noopt (PG_FUNCTION_ARGS)
Datum textregexreplace (PG_FUNCTION_ARGS)
Datum similar_escape (PG_FUNCTION_ARGS)
Datum regexp_matches (PG_FUNCTION_ARGS)
Datum regexp_matches_no_flags (PG_FUNCTION_ARGS)
Datum regexp_split_to_table (PG_FUNCTION_ARGS)
Datum regexp_split_to_table_no_flags (PG_FUNCTION_ARGS)
Datum regexp_split_to_array (PG_FUNCTION_ARGS)
Datum regexp_split_to_array_no_flags (PG_FUNCTION_ARGS)
char * regexp_fixed_prefix (text *text_re, bool case_insensitive, Oid collation, bool *exact)
Datum regprocin (PG_FUNCTION_ARGS)
Datum regprocout (PG_FUNCTION_ARGS)
Datum regprocrecv (PG_FUNCTION_ARGS)
Datum regprocsend (PG_FUNCTION_ARGS)
Datum regprocedurein (PG_FUNCTION_ARGS)
Datum regprocedureout (PG_FUNCTION_ARGS)
Datum regprocedurerecv (PG_FUNCTION_ARGS)
Datum regproceduresend (PG_FUNCTION_ARGS)
Datum regoperin (PG_FUNCTION_ARGS)
Datum regoperout (PG_FUNCTION_ARGS)
Datum regoperrecv (PG_FUNCTION_ARGS)
Datum regopersend (PG_FUNCTION_ARGS)
Datum regoperatorin (PG_FUNCTION_ARGS)
Datum regoperatorout (PG_FUNCTION_ARGS)
Datum regoperatorrecv (PG_FUNCTION_ARGS)
Datum regoperatorsend (PG_FUNCTION_ARGS)
Datum regclassin (PG_FUNCTION_ARGS)
Datum regclassout (PG_FUNCTION_ARGS)
Datum regclassrecv (PG_FUNCTION_ARGS)
Datum regclasssend (PG_FUNCTION_ARGS)
Datum regtypein (PG_FUNCTION_ARGS)
Datum regtypeout (PG_FUNCTION_ARGS)
Datum regtyperecv (PG_FUNCTION_ARGS)
Datum regtypesend (PG_FUNCTION_ARGS)
Datum regconfigin (PG_FUNCTION_ARGS)
Datum regconfigout (PG_FUNCTION_ARGS)
Datum regconfigrecv (PG_FUNCTION_ARGS)
Datum regconfigsend (PG_FUNCTION_ARGS)
Datum regdictionaryin (PG_FUNCTION_ARGS)
Datum regdictionaryout (PG_FUNCTION_ARGS)
Datum regdictionaryrecv (PG_FUNCTION_ARGS)
Datum regdictionarysend (PG_FUNCTION_ARGS)
Datum text_regclass (PG_FUNCTION_ARGS)
ListstringToQualifiedNameList (const char *string)
char * format_procedure (Oid procedure_oid)
char * format_procedure_qualified (Oid procedure_oid)
char * format_operator (Oid operator_oid)
char * format_operator_qualified (Oid operator_oid)
Datum record_in (PG_FUNCTION_ARGS)
Datum record_out (PG_FUNCTION_ARGS)
Datum record_recv (PG_FUNCTION_ARGS)
Datum record_send (PG_FUNCTION_ARGS)
Datum record_eq (PG_FUNCTION_ARGS)
Datum record_ne (PG_FUNCTION_ARGS)
Datum record_lt (PG_FUNCTION_ARGS)
Datum record_gt (PG_FUNCTION_ARGS)
Datum record_le (PG_FUNCTION_ARGS)
Datum record_ge (PG_FUNCTION_ARGS)
Datum btrecordcmp (PG_FUNCTION_ARGS)
Datum pg_get_ruledef (PG_FUNCTION_ARGS)
Datum pg_get_ruledef_ext (PG_FUNCTION_ARGS)
Datum pg_get_viewdef (PG_FUNCTION_ARGS)
Datum pg_get_viewdef_ext (PG_FUNCTION_ARGS)
Datum pg_get_viewdef_wrap (PG_FUNCTION_ARGS)
Datum pg_get_viewdef_name (PG_FUNCTION_ARGS)
Datum pg_get_viewdef_name_ext (PG_FUNCTION_ARGS)
Datum pg_get_indexdef (PG_FUNCTION_ARGS)
Datum pg_get_indexdef_ext (PG_FUNCTION_ARGS)
char * pg_get_indexdef_string (Oid indexrelid)
char * pg_get_indexdef_columns (Oid indexrelid, bool pretty)
Datum pg_get_triggerdef (PG_FUNCTION_ARGS)
Datum pg_get_triggerdef_ext (PG_FUNCTION_ARGS)
Datum pg_get_constraintdef (PG_FUNCTION_ARGS)
Datum pg_get_constraintdef_ext (PG_FUNCTION_ARGS)
char * pg_get_constraintdef_string (Oid constraintId)
Datum pg_get_expr (PG_FUNCTION_ARGS)
Datum pg_get_expr_ext (PG_FUNCTION_ARGS)
Datum pg_get_userbyid (PG_FUNCTION_ARGS)
Datum pg_get_serial_sequence (PG_FUNCTION_ARGS)
Datum pg_get_functiondef (PG_FUNCTION_ARGS)
Datum pg_get_function_arguments (PG_FUNCTION_ARGS)
Datum pg_get_function_identity_arguments (PG_FUNCTION_ARGS)
Datum pg_get_function_result (PG_FUNCTION_ARGS)
char * deparse_expression (Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Listdeparse_context_for (const char *aliasname, Oid relid)
Listdeparse_context_for_planstate (Node *planstate, List *ancestors, List *rtable, List *rtable_names)
Listselect_rtable_names_for_explain (List *rtable, Bitmapset *rels_used)
const char * quote_identifier (const char *ident)
char * quote_qualified_identifier (const char *qualifier, const char *ident)
char * generate_collation_name (Oid collid)
Datum tidin (PG_FUNCTION_ARGS)
Datum tidout (PG_FUNCTION_ARGS)
Datum tidrecv (PG_FUNCTION_ARGS)
Datum tidsend (PG_FUNCTION_ARGS)
Datum tideq (PG_FUNCTION_ARGS)
Datum tidne (PG_FUNCTION_ARGS)
Datum tidlt (PG_FUNCTION_ARGS)
Datum tidle (PG_FUNCTION_ARGS)
Datum tidgt (PG_FUNCTION_ARGS)
Datum tidge (PG_FUNCTION_ARGS)
Datum bttidcmp (PG_FUNCTION_ARGS)
Datum tidlarger (PG_FUNCTION_ARGS)
Datum tidsmaller (PG_FUNCTION_ARGS)
Datum currtid_byreloid (PG_FUNCTION_ARGS)
Datum currtid_byrelname (PG_FUNCTION_ARGS)
Datum bpcharin (PG_FUNCTION_ARGS)
Datum bpcharout (PG_FUNCTION_ARGS)
Datum bpcharrecv (PG_FUNCTION_ARGS)
Datum bpcharsend (PG_FUNCTION_ARGS)
Datum bpchartypmodin (PG_FUNCTION_ARGS)
Datum bpchartypmodout (PG_FUNCTION_ARGS)
Datum bpchar (PG_FUNCTION_ARGS)
Datum char_bpchar (PG_FUNCTION_ARGS)
Datum name_bpchar (PG_FUNCTION_ARGS)
Datum bpchar_name (PG_FUNCTION_ARGS)
Datum bpchareq (PG_FUNCTION_ARGS)
Datum bpcharne (PG_FUNCTION_ARGS)
Datum bpcharlt (PG_FUNCTION_ARGS)
Datum bpcharle (PG_FUNCTION_ARGS)
Datum bpchargt (PG_FUNCTION_ARGS)
Datum bpcharge (PG_FUNCTION_ARGS)
Datum bpcharcmp (PG_FUNCTION_ARGS)
Datum bpchar_larger (PG_FUNCTION_ARGS)
Datum bpchar_smaller (PG_FUNCTION_ARGS)
Datum bpcharlen (PG_FUNCTION_ARGS)
Datum bpcharoctetlen (PG_FUNCTION_ARGS)
Datum hashbpchar (PG_FUNCTION_ARGS)
Datum bpchar_pattern_lt (PG_FUNCTION_ARGS)
Datum bpchar_pattern_le (PG_FUNCTION_ARGS)
Datum bpchar_pattern_gt (PG_FUNCTION_ARGS)
Datum bpchar_pattern_ge (PG_FUNCTION_ARGS)
Datum btbpchar_pattern_cmp (PG_FUNCTION_ARGS)
Datum varcharin (PG_FUNCTION_ARGS)
Datum varcharout (PG_FUNCTION_ARGS)
Datum varcharrecv (PG_FUNCTION_ARGS)
Datum varcharsend (PG_FUNCTION_ARGS)
Datum varchartypmodin (PG_FUNCTION_ARGS)
Datum varchartypmodout (PG_FUNCTION_ARGS)
Datum varchar_transform (PG_FUNCTION_ARGS)
Datum varchar (PG_FUNCTION_ARGS)
textcstring_to_text (const char *s)
textcstring_to_text_with_len (const char *s, int len)
char * text_to_cstring (const text *t)
void text_to_cstring_buffer (const text *src, char *dst, size_t dst_len)
Datum textin (PG_FUNCTION_ARGS)
Datum textout (PG_FUNCTION_ARGS)
Datum textrecv (PG_FUNCTION_ARGS)
Datum textsend (PG_FUNCTION_ARGS)
Datum textcat (PG_FUNCTION_ARGS)
Datum texteq (PG_FUNCTION_ARGS)
Datum textne (PG_FUNCTION_ARGS)
Datum text_lt (PG_FUNCTION_ARGS)
Datum text_le (PG_FUNCTION_ARGS)
Datum text_gt (PG_FUNCTION_ARGS)
Datum text_ge (PG_FUNCTION_ARGS)
Datum text_larger (PG_FUNCTION_ARGS)
Datum text_smaller (PG_FUNCTION_ARGS)
Datum text_pattern_lt (PG_FUNCTION_ARGS)
Datum text_pattern_le (PG_FUNCTION_ARGS)
Datum text_pattern_gt (PG_FUNCTION_ARGS)
Datum text_pattern_ge (PG_FUNCTION_ARGS)
Datum bttext_pattern_cmp (PG_FUNCTION_ARGS)
Datum textlen (PG_FUNCTION_ARGS)
Datum textoctetlen (PG_FUNCTION_ARGS)
Datum textpos (PG_FUNCTION_ARGS)
Datum text_substr (PG_FUNCTION_ARGS)
Datum text_substr_no_len (PG_FUNCTION_ARGS)
Datum textoverlay (PG_FUNCTION_ARGS)
Datum textoverlay_no_len (PG_FUNCTION_ARGS)
Datum name_text (PG_FUNCTION_ARGS)
Datum text_name (PG_FUNCTION_ARGS)
int varstr_cmp (char *arg1, int len1, char *arg2, int len2, Oid collid)
ListtextToQualifiedNameList (text *textval)
bool SplitIdentifierString (char *rawstring, char separator, List **namelist)
bool SplitDirectoriesString (char *rawstring, char separator, List **namelist)
Datum replace_text (PG_FUNCTION_ARGS)
textreplace_text_regexp (text *src_text, void *regexp, text *replace_text, bool glob)
Datum split_text (PG_FUNCTION_ARGS)
Datum text_to_array (PG_FUNCTION_ARGS)
Datum array_to_text (PG_FUNCTION_ARGS)
Datum text_to_array_null (PG_FUNCTION_ARGS)
Datum array_to_text_null (PG_FUNCTION_ARGS)
Datum to_hex32 (PG_FUNCTION_ARGS)
Datum to_hex64 (PG_FUNCTION_ARGS)
Datum md5_text (PG_FUNCTION_ARGS)
Datum md5_bytea (PG_FUNCTION_ARGS)
Datum unknownin (PG_FUNCTION_ARGS)
Datum unknownout (PG_FUNCTION_ARGS)
Datum unknownrecv (PG_FUNCTION_ARGS)
Datum unknownsend (PG_FUNCTION_ARGS)
Datum pg_column_size (PG_FUNCTION_ARGS)
Datum bytea_string_agg_transfn (PG_FUNCTION_ARGS)
Datum bytea_string_agg_finalfn (PG_FUNCTION_ARGS)
Datum string_agg_transfn (PG_FUNCTION_ARGS)
Datum string_agg_finalfn (PG_FUNCTION_ARGS)
Datum text_concat (PG_FUNCTION_ARGS)
Datum text_concat_ws (PG_FUNCTION_ARGS)
Datum text_left (PG_FUNCTION_ARGS)
Datum text_right (PG_FUNCTION_ARGS)
Datum text_reverse (PG_FUNCTION_ARGS)
Datum text_format (PG_FUNCTION_ARGS)
Datum text_format_nv (PG_FUNCTION_ARGS)
Datum pgsql_version (PG_FUNCTION_ARGS)
Datum xidin (PG_FUNCTION_ARGS)
Datum xidout (PG_FUNCTION_ARGS)
Datum xidrecv (PG_FUNCTION_ARGS)
Datum xidsend (PG_FUNCTION_ARGS)
Datum xideq (PG_FUNCTION_ARGS)
Datum xid_age (PG_FUNCTION_ARGS)
int xidComparator (const void *arg1, const void *arg2)
Datum cidin (PG_FUNCTION_ARGS)
Datum cidout (PG_FUNCTION_ARGS)
Datum cidrecv (PG_FUNCTION_ARGS)
Datum cidsend (PG_FUNCTION_ARGS)
Datum cideq (PG_FUNCTION_ARGS)
Datum namelike (PG_FUNCTION_ARGS)
Datum namenlike (PG_FUNCTION_ARGS)
Datum nameiclike (PG_FUNCTION_ARGS)
Datum nameicnlike (PG_FUNCTION_ARGS)
Datum textlike (PG_FUNCTION_ARGS)
Datum textnlike (PG_FUNCTION_ARGS)
Datum texticlike (PG_FUNCTION_ARGS)
Datum texticnlike (PG_FUNCTION_ARGS)
Datum bytealike (PG_FUNCTION_ARGS)
Datum byteanlike (PG_FUNCTION_ARGS)
Datum like_escape (PG_FUNCTION_ARGS)
Datum like_escape_bytea (PG_FUNCTION_ARGS)
Datum lower (PG_FUNCTION_ARGS)
Datum upper (PG_FUNCTION_ARGS)
Datum initcap (PG_FUNCTION_ARGS)
Datum lpad (PG_FUNCTION_ARGS)
Datum rpad (PG_FUNCTION_ARGS)
Datum btrim (PG_FUNCTION_ARGS)
Datum btrim1 (PG_FUNCTION_ARGS)
Datum byteatrim (PG_FUNCTION_ARGS)
Datum ltrim (PG_FUNCTION_ARGS)
Datum ltrim1 (PG_FUNCTION_ARGS)
Datum rtrim (PG_FUNCTION_ARGS)
Datum rtrim1 (PG_FUNCTION_ARGS)
Datum translate (PG_FUNCTION_ARGS)
Datum chr (PG_FUNCTION_ARGS)
Datum repeat (PG_FUNCTION_ARGS)
Datum ascii (PG_FUNCTION_ARGS)
char * inet_cidr_ntop (int af, const void *src, int bits, char *dst, size_t size)
int inet_net_pton (int af, const char *src, void *dst, size_t size)
Datum inet_in (PG_FUNCTION_ARGS)
Datum inet_out (PG_FUNCTION_ARGS)
Datum inet_recv (PG_FUNCTION_ARGS)
Datum inet_send (PG_FUNCTION_ARGS)
Datum cidr_in (PG_FUNCTION_ARGS)
Datum cidr_out (PG_FUNCTION_ARGS)
Datum cidr_recv (PG_FUNCTION_ARGS)
Datum cidr_send (PG_FUNCTION_ARGS)
Datum network_cmp (PG_FUNCTION_ARGS)
Datum network_lt (PG_FUNCTION_ARGS)
Datum network_le (PG_FUNCTION_ARGS)
Datum network_eq (PG_FUNCTION_ARGS)
Datum network_ge (PG_FUNCTION_ARGS)
Datum network_gt (PG_FUNCTION_ARGS)
Datum network_ne (PG_FUNCTION_ARGS)
Datum hashinet (PG_FUNCTION_ARGS)
Datum network_sub (PG_FUNCTION_ARGS)
Datum network_subeq (PG_FUNCTION_ARGS)
Datum network_sup (PG_FUNCTION_ARGS)
Datum network_supeq (PG_FUNCTION_ARGS)
Datum network_network (PG_FUNCTION_ARGS)
Datum network_netmask (PG_FUNCTION_ARGS)
Datum network_hostmask (PG_FUNCTION_ARGS)
Datum network_masklen (PG_FUNCTION_ARGS)
Datum network_family (PG_FUNCTION_ARGS)
Datum network_broadcast (PG_FUNCTION_ARGS)
Datum network_host (PG_FUNCTION_ARGS)
Datum network_show (PG_FUNCTION_ARGS)
Datum inet_abbrev (PG_FUNCTION_ARGS)
Datum cidr_abbrev (PG_FUNCTION_ARGS)
double convert_network_to_scalar (Datum value, Oid typid)
Datum inet_to_cidr (PG_FUNCTION_ARGS)
Datum inet_set_masklen (PG_FUNCTION_ARGS)
Datum cidr_set_masklen (PG_FUNCTION_ARGS)
Datum network_scan_first (Datum in)
Datum network_scan_last (Datum in)
Datum inet_client_addr (PG_FUNCTION_ARGS)
Datum inet_client_port (PG_FUNCTION_ARGS)
Datum inet_server_addr (PG_FUNCTION_ARGS)
Datum inet_server_port (PG_FUNCTION_ARGS)
Datum inetnot (PG_FUNCTION_ARGS)
Datum inetand (PG_FUNCTION_ARGS)
Datum inetor (PG_FUNCTION_ARGS)
Datum inetpl (PG_FUNCTION_ARGS)
Datum inetmi_int8 (PG_FUNCTION_ARGS)
Datum inetmi (PG_FUNCTION_ARGS)
void clean_ipv6_addr (int addr_family, char *addr)
Datum macaddr_in (PG_FUNCTION_ARGS)
Datum macaddr_out (PG_FUNCTION_ARGS)
Datum macaddr_recv (PG_FUNCTION_ARGS)
Datum macaddr_send (PG_FUNCTION_ARGS)
Datum macaddr_cmp (PG_FUNCTION_ARGS)
Datum macaddr_lt (PG_FUNCTION_ARGS)
Datum macaddr_le (PG_FUNCTION_ARGS)
Datum macaddr_eq (PG_FUNCTION_ARGS)
Datum macaddr_ge (PG_FUNCTION_ARGS)
Datum macaddr_gt (PG_FUNCTION_ARGS)
Datum macaddr_ne (PG_FUNCTION_ARGS)
Datum macaddr_not (PG_FUNCTION_ARGS)
Datum macaddr_and (PG_FUNCTION_ARGS)
Datum macaddr_or (PG_FUNCTION_ARGS)
Datum macaddr_trunc (PG_FUNCTION_ARGS)
Datum hashmacaddr (PG_FUNCTION_ARGS)
Datum numeric_in (PG_FUNCTION_ARGS)
Datum numeric_out (PG_FUNCTION_ARGS)
Datum numeric_recv (PG_FUNCTION_ARGS)
Datum numeric_send (PG_FUNCTION_ARGS)
Datum numerictypmodin (PG_FUNCTION_ARGS)
Datum numerictypmodout (PG_FUNCTION_ARGS)
Datum numeric_transform (PG_FUNCTION_ARGS)
Datum numeric (PG_FUNCTION_ARGS)
Datum numeric_abs (PG_FUNCTION_ARGS)
Datum numeric_uminus (PG_FUNCTION_ARGS)
Datum numeric_uplus (PG_FUNCTION_ARGS)
Datum numeric_sign (PG_FUNCTION_ARGS)
Datum numeric_round (PG_FUNCTION_ARGS)
Datum numeric_trunc (PG_FUNCTION_ARGS)
Datum numeric_ceil (PG_FUNCTION_ARGS)
Datum numeric_floor (PG_FUNCTION_ARGS)
Datum numeric_cmp (PG_FUNCTION_ARGS)
Datum numeric_eq (PG_FUNCTION_ARGS)
Datum numeric_ne (PG_FUNCTION_ARGS)
Datum numeric_gt (PG_FUNCTION_ARGS)
Datum numeric_ge (PG_FUNCTION_ARGS)
Datum numeric_lt (PG_FUNCTION_ARGS)
Datum numeric_le (PG_FUNCTION_ARGS)
Datum numeric_add (PG_FUNCTION_ARGS)
Datum numeric_sub (PG_FUNCTION_ARGS)
Datum numeric_mul (PG_FUNCTION_ARGS)
Datum numeric_div (PG_FUNCTION_ARGS)
Datum numeric_div_trunc (PG_FUNCTION_ARGS)
Datum numeric_mod (PG_FUNCTION_ARGS)
Datum numeric_inc (PG_FUNCTION_ARGS)
Datum numeric_smaller (PG_FUNCTION_ARGS)
Datum numeric_larger (PG_FUNCTION_ARGS)
Datum numeric_fac (PG_FUNCTION_ARGS)
Datum numeric_sqrt (PG_FUNCTION_ARGS)
Datum numeric_exp (PG_FUNCTION_ARGS)
Datum numeric_ln (PG_FUNCTION_ARGS)
Datum numeric_log (PG_FUNCTION_ARGS)
Datum numeric_power (PG_FUNCTION_ARGS)
Datum int4_numeric (PG_FUNCTION_ARGS)
Datum numeric_int4 (PG_FUNCTION_ARGS)
Datum int8_numeric (PG_FUNCTION_ARGS)
Datum numeric_int8 (PG_FUNCTION_ARGS)
Datum int2_numeric (PG_FUNCTION_ARGS)
Datum numeric_int2 (PG_FUNCTION_ARGS)
Datum float8_numeric (PG_FUNCTION_ARGS)
Datum numeric_float8 (PG_FUNCTION_ARGS)
Datum numeric_float8_no_overflow (PG_FUNCTION_ARGS)
Datum float4_numeric (PG_FUNCTION_ARGS)
Datum numeric_float4 (PG_FUNCTION_ARGS)
Datum numeric_accum (PG_FUNCTION_ARGS)
Datum numeric_avg_accum (PG_FUNCTION_ARGS)
Datum int2_accum (PG_FUNCTION_ARGS)
Datum int4_accum (PG_FUNCTION_ARGS)
Datum int8_accum (PG_FUNCTION_ARGS)
Datum int8_avg_accum (PG_FUNCTION_ARGS)
Datum numeric_avg (PG_FUNCTION_ARGS)
Datum numeric_var_pop (PG_FUNCTION_ARGS)
Datum numeric_var_samp (PG_FUNCTION_ARGS)
Datum numeric_stddev_pop (PG_FUNCTION_ARGS)
Datum numeric_stddev_samp (PG_FUNCTION_ARGS)
Datum int2_sum (PG_FUNCTION_ARGS)
Datum int4_sum (PG_FUNCTION_ARGS)
Datum int8_sum (PG_FUNCTION_ARGS)
Datum int2_avg_accum (PG_FUNCTION_ARGS)
Datum int4_avg_accum (PG_FUNCTION_ARGS)
Datum int8_avg (PG_FUNCTION_ARGS)
Datum width_bucket_numeric (PG_FUNCTION_ARGS)
Datum hash_numeric (PG_FUNCTION_ARGS)
Datum RI_FKey_check_ins (PG_FUNCTION_ARGS)
Datum RI_FKey_check_upd (PG_FUNCTION_ARGS)
Datum RI_FKey_noaction_del (PG_FUNCTION_ARGS)
Datum RI_FKey_noaction_upd (PG_FUNCTION_ARGS)
Datum RI_FKey_cascade_del (PG_FUNCTION_ARGS)
Datum RI_FKey_cascade_upd (PG_FUNCTION_ARGS)
Datum RI_FKey_restrict_del (PG_FUNCTION_ARGS)
Datum RI_FKey_restrict_upd (PG_FUNCTION_ARGS)
Datum RI_FKey_setnull_del (PG_FUNCTION_ARGS)
Datum RI_FKey_setnull_upd (PG_FUNCTION_ARGS)
Datum RI_FKey_setdefault_del (PG_FUNCTION_ARGS)
Datum RI_FKey_setdefault_upd (PG_FUNCTION_ARGS)
Datum suppress_redundant_updates_trigger (PG_FUNCTION_ARGS)
Datum getdatabaseencoding (PG_FUNCTION_ARGS)
Datum database_character_set (PG_FUNCTION_ARGS)
Datum pg_client_encoding (PG_FUNCTION_ARGS)
Datum PG_encoding_to_char (PG_FUNCTION_ARGS)
Datum PG_char_to_encoding (PG_FUNCTION_ARGS)
Datum PG_character_set_name (PG_FUNCTION_ARGS)
Datum PG_character_set_id (PG_FUNCTION_ARGS)
Datum pg_convert (PG_FUNCTION_ARGS)
Datum pg_convert_to (PG_FUNCTION_ARGS)
Datum pg_convert_from (PG_FUNCTION_ARGS)
Datum length_in_encoding (PG_FUNCTION_ARGS)
Datum pg_encoding_max_length_sql (PG_FUNCTION_ARGS)
Datum format_type (PG_FUNCTION_ARGS)
char * format_type_be (Oid type_oid)
char * format_type_be_qualified (Oid type_oid)
char * format_type_with_typemod (Oid type_oid, int32 typemod)
Datum oidvectortypes (PG_FUNCTION_ARGS)
int32 type_maximum_size (Oid type_oid, int32 typemod)
Datum quote_ident (PG_FUNCTION_ARGS)
Datum quote_literal (PG_FUNCTION_ARGS)
char * quote_literal_cstr (const char *rawstr)
Datum quote_nullable (PG_FUNCTION_ARGS)
Datum show_config_by_name (PG_FUNCTION_ARGS)
Datum set_config_by_name (PG_FUNCTION_ARGS)
Datum show_all_settings (PG_FUNCTION_ARGS)
Datum pg_lock_status (PG_FUNCTION_ARGS)
Datum pg_advisory_lock_int8 (PG_FUNCTION_ARGS)
Datum pg_advisory_xact_lock_int8 (PG_FUNCTION_ARGS)
Datum pg_advisory_lock_shared_int8 (PG_FUNCTION_ARGS)
Datum pg_advisory_xact_lock_shared_int8 (PG_FUNCTION_ARGS)
Datum pg_try_advisory_lock_int8 (PG_FUNCTION_ARGS)
Datum pg_try_advisory_xact_lock_int8 (PG_FUNCTION_ARGS)
Datum pg_try_advisory_lock_shared_int8 (PG_FUNCTION_ARGS)
Datum pg_try_advisory_xact_lock_shared_int8 (PG_FUNCTION_ARGS)
Datum pg_advisory_unlock_int8 (PG_FUNCTION_ARGS)
Datum pg_advisory_unlock_shared_int8 (PG_FUNCTION_ARGS)
Datum pg_advisory_lock_int4 (PG_FUNCTION_ARGS)
Datum pg_advisory_xact_lock_int4 (PG_FUNCTION_ARGS)
Datum pg_advisory_lock_shared_int4 (PG_FUNCTION_ARGS)
Datum pg_advisory_xact_lock_shared_int4 (PG_FUNCTION_ARGS)
Datum pg_try_advisory_lock_int4 (PG_FUNCTION_ARGS)
Datum pg_try_advisory_xact_lock_int4 (PG_FUNCTION_ARGS)
Datum pg_try_advisory_lock_shared_int4 (PG_FUNCTION_ARGS)
Datum pg_try_advisory_xact_lock_shared_int4 (PG_FUNCTION_ARGS)
Datum pg_advisory_unlock_int4 (PG_FUNCTION_ARGS)
Datum pg_advisory_unlock_shared_int4 (PG_FUNCTION_ARGS)
Datum pg_advisory_unlock_all (PG_FUNCTION_ARGS)
Datum txid_snapshot_in (PG_FUNCTION_ARGS)
Datum txid_snapshot_out (PG_FUNCTION_ARGS)
Datum txid_snapshot_recv (PG_FUNCTION_ARGS)
Datum txid_snapshot_send (PG_FUNCTION_ARGS)
Datum txid_current (PG_FUNCTION_ARGS)
Datum txid_current_snapshot (PG_FUNCTION_ARGS)
Datum txid_snapshot_xmin (PG_FUNCTION_ARGS)
Datum txid_snapshot_xmax (PG_FUNCTION_ARGS)
Datum txid_snapshot_xip (PG_FUNCTION_ARGS)
Datum txid_visible_in_snapshot (PG_FUNCTION_ARGS)
Datum uuid_in (PG_FUNCTION_ARGS)
Datum uuid_out (PG_FUNCTION_ARGS)
Datum uuid_send (PG_FUNCTION_ARGS)
Datum uuid_recv (PG_FUNCTION_ARGS)
Datum uuid_lt (PG_FUNCTION_ARGS)
Datum uuid_le (PG_FUNCTION_ARGS)
Datum uuid_eq (PG_FUNCTION_ARGS)
Datum uuid_ge (PG_FUNCTION_ARGS)
Datum uuid_gt (PG_FUNCTION_ARGS)
Datum uuid_ne (PG_FUNCTION_ARGS)
Datum uuid_cmp (PG_FUNCTION_ARGS)
Datum uuid_hash (PG_FUNCTION_ARGS)
Datum window_row_number (PG_FUNCTION_ARGS)
Datum window_rank (PG_FUNCTION_ARGS)
Datum window_dense_rank (PG_FUNCTION_ARGS)
Datum window_percent_rank (PG_FUNCTION_ARGS)
Datum window_cume_dist (PG_FUNCTION_ARGS)
Datum window_ntile (PG_FUNCTION_ARGS)
Datum window_lag (PG_FUNCTION_ARGS)
Datum window_lag_with_offset (PG_FUNCTION_ARGS)
Datum window_lag_with_offset_and_default (PG_FUNCTION_ARGS)
Datum window_lead (PG_FUNCTION_ARGS)
Datum window_lead_with_offset (PG_FUNCTION_ARGS)
Datum window_lead_with_offset_and_default (PG_FUNCTION_ARGS)
Datum window_first_value (PG_FUNCTION_ARGS)
Datum window_last_value (PG_FUNCTION_ARGS)
Datum window_nth_value (PG_FUNCTION_ARGS)
Datum spg_quad_config (PG_FUNCTION_ARGS)
Datum spg_quad_choose (PG_FUNCTION_ARGS)
Datum spg_quad_picksplit (PG_FUNCTION_ARGS)
Datum spg_quad_inner_consistent (PG_FUNCTION_ARGS)
Datum spg_quad_leaf_consistent (PG_FUNCTION_ARGS)
Datum spg_kd_config (PG_FUNCTION_ARGS)
Datum spg_kd_choose (PG_FUNCTION_ARGS)
Datum spg_kd_picksplit (PG_FUNCTION_ARGS)
Datum spg_kd_inner_consistent (PG_FUNCTION_ARGS)
Datum spg_text_config (PG_FUNCTION_ARGS)
Datum spg_text_choose (PG_FUNCTION_ARGS)
Datum spg_text_picksplit (PG_FUNCTION_ARGS)
Datum spg_text_inner_consistent (PG_FUNCTION_ARGS)
Datum spg_text_leaf_consistent (PG_FUNCTION_ARGS)
Datum ginarrayextract (PG_FUNCTION_ARGS)
Datum ginarrayextract_2args (PG_FUNCTION_ARGS)
Datum ginqueryarrayextract (PG_FUNCTION_ARGS)
Datum ginarrayconsistent (PG_FUNCTION_ARGS)
Datum pg_prepared_xact (PG_FUNCTION_ARGS)
Datum pg_get_multixact_members (PG_FUNCTION_ARGS)
Datum pg_describe_object (PG_FUNCTION_ARGS)
Datum pg_identify_object (PG_FUNCTION_ARGS)
Datum unique_key_recheck (PG_FUNCTION_ARGS)
Datum pg_event_trigger_dropped_objects (PG_FUNCTION_ARGS)
Datum pg_available_extensions (PG_FUNCTION_ARGS)
Datum pg_available_extension_versions (PG_FUNCTION_ARGS)
Datum pg_extension_update_paths (PG_FUNCTION_ARGS)
Datum pg_extension_config_dump (PG_FUNCTION_ARGS)
Datum pg_prepared_statement (PG_FUNCTION_ARGS)
Datum pg_cursor (PG_FUNCTION_ARGS)

Variables

PGDLLIMPORT int extra_float_digits
bool quote_all_identifiers

Define Documentation

#define CStringGetTextDatum (   s  )     PointerGetDatum(cstring_to_text(s))
#define TextDatumGetCString (   d  )     text_to_cstring((text *) DatumGetPointer(d))

Definition at line 736 of file builtins.h.

Referenced by AlterDomainValidateConstraint(), AttrDefaultFetch(), binary_decode(), binary_encode(), bpcharout(), build_function_result_tupdesc_d(), CheckConstraintFetch(), compile_plperl_function(), compile_pltcl_function(), convert_string_datum(), DecodeTextArrayToCString(), decompile_conbin(), DefineDomain(), do_compile(), exec_stmt_close(), exec_stmt_fetch(), exec_stmt_forc(), exec_stmt_open(), fetch_cursor_param_value(), fetch_function_defaults(), find_language_template(), flatten_reloptions(), fmgr_c_validator(), fmgr_info_C_lang(), fmgr_info_cxt_security(), fmgr_internal_validator(), fmgr_sql_validator(), func_get_detail(), generateClonedIndexStmt(), get_func_arg_info(), get_func_input_arg_names(), get_func_result_name(), get_path_all(), get_text_array_contents(), get_typdefault(), GetAggInitVal(), GetComment(), GetDomainConstraints(), GetForeignServer(), GetSecurityLabel(), GetSharedSecurityLabel(), GUCArrayAdd(), GUCArrayDelete(), GUCArrayReset(), init_sql_fcache(), inline_function(), inline_set_returning_function(), json_out(), like_fixed_prefix(), make_greater_string(), md5_crypt_verify(), MergeWithExistingConstraint(), metaphone(), parseRelOptions(), patternsel(), pg_get_constraintdef_worker(), pg_get_functiondef(), pg_get_indexdef_worker(), pg_get_triggerdef_worker(), PLy_procedure_create(), prefix_quals(), print_function_arguments(), ProcedureCreate(), ProcessGUCArray(), regex_fixed_prefix(), RelationBuildRuleLock(), RelationBuildTriggers(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), RenameRole(), sepgsql_restorecon(), sepgsql_setcon(), set_config_by_name(), show_config_by_name(), textout(), tsa_headline_byname(), untransformRelOptions(), validateCheckConstraint(), and varcharout().


Function Documentation

Datum any_in ( PG_FUNCTION_ARGS   ) 

Definition at line 91 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot accept a value of type any")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum any_out ( PG_FUNCTION_ARGS   ) 

Definition at line 104 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot display a value of type any")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum anyarray_in ( PG_FUNCTION_ARGS   ) 

Definition at line 118 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot accept a value of type anyarray")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum anyarray_out ( PG_FUNCTION_ARGS   ) 

Definition at line 133 of file pseudotypes.c.

References array_out().

{
    return array_out(fcinfo);
}

Datum anyarray_recv ( PG_FUNCTION_ARGS   ) 

Definition at line 146 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot accept a value of type anyarray")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum anyarray_send ( PG_FUNCTION_ARGS   ) 

Definition at line 161 of file pseudotypes.c.

References array_send().

{
    return array_send(fcinfo);
}

Datum anyelement_in ( PG_FUNCTION_ARGS   ) 

Definition at line 434 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot accept a value of type anyelement")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum anyelement_out ( PG_FUNCTION_ARGS   ) 

Definition at line 447 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot display a value of type anyelement")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum anyenum_in ( PG_FUNCTION_ARGS   ) 

Definition at line 171 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot accept a value of type anyenum")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum anyenum_out ( PG_FUNCTION_ARGS   ) 

Definition at line 186 of file pseudotypes.c.

References enum_out().

{
    return enum_out(fcinfo);
}

Datum anynonarray_in ( PG_FUNCTION_ARGS   ) 

Definition at line 460 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot accept a value of type anynonarray")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum anynonarray_out ( PG_FUNCTION_ARGS   ) 

Definition at line 473 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot display a value of type anynonarray")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum anyrange_in ( PG_FUNCTION_ARGS   ) 

Definition at line 195 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot accept a value of type anyrange")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum anyrange_out ( PG_FUNCTION_ARGS   ) 

Definition at line 210 of file pseudotypes.c.

References range_out().

{
    return range_out(fcinfo);
}

Datum array_to_text ( PG_FUNCTION_ARGS   ) 
Datum array_to_text_null ( PG_FUNCTION_ARGS   ) 

Definition at line 3436 of file varlena.c.

References array_to_text_internal(), PG_ARGISNULL, PG_GETARG_ARRAYTYPE_P, PG_GETARG_TEXT_PP, PG_RETURN_NULL, PG_RETURN_TEXT_P, and text_to_cstring().

{
    ArrayType  *v;
    char       *fldsep;
    char       *null_string;

    /* 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;

    PG_RETURN_TEXT_P(array_to_text_internal(fcinfo, v, fldsep, null_string));
}

Datum ascii ( PG_FUNCTION_ARGS   ) 

Definition at line 844 of file oracle_compat.c.

References Assert, encoding, ereport, errcode(), errmsg(), ERROR, GetDatabaseEncoding(), i, pg_encoding_max_length(), PG_GETARG_TEXT_PP, PG_RETURN_INT32, PG_UTF8, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

Referenced by float4out(), and float8out().

{
    text       *string = PG_GETARG_TEXT_PP(0);
    int         encoding = GetDatabaseEncoding();
    unsigned char *data;

    if (VARSIZE_ANY_EXHDR(string) <= 0)
        PG_RETURN_INT32(0);

    data = (unsigned char *) VARDATA_ANY(string);

    if (encoding == PG_UTF8 && *data > 127)
    {
        /* return the code point for Unicode */

        int         result = 0,
                    tbytes = 0,
                    i;

        if (*data >= 0xF0)
        {
            result = *data & 0x07;
            tbytes = 3;
        }
        else if (*data >= 0xE0)
        {
            result = *data & 0x0F;
            tbytes = 2;
        }
        else
        {
            Assert(*data > 0xC0);
            result = *data & 0x1f;
            tbytes = 1;
        }

        Assert(tbytes > 0);

        for (i = 1; i <= tbytes; i++)
        {
            Assert((data[i] & 0xC0) == 0x80);
            result = (result << 6) + (data[i] & 0x3f);
        }

        PG_RETURN_INT32(result);
    }
    else
    {
        if (pg_encoding_max_length(encoding) > 1 && *data > 127)
            ereport(ERROR,
                    (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                     errmsg("requested character too large")));


        PG_RETURN_INT32((int32) *data);
    }
}

Datum binary_decode ( PG_FUNCTION_ARGS   ) 

Definition at line 72 of file encode.c.

References pg_encoding::decode, pg_encoding::decode_len, elog, enc, ereport, errcode(), errmsg(), ERROR, FATAL, name, NULL, palloc(), pg_find_encoding(), PG_GETARG_DATUM, PG_GETARG_TEXT_P, PG_RETURN_BYTEA_P, SET_VARSIZE, TextDatumGetCString, VARDATA, VARHDRSZ, and VARSIZE.

{
    text       *data = PG_GETARG_TEXT_P(0);
    Datum       name = PG_GETARG_DATUM(1);
    bytea      *result;
    char       *namebuf;
    int         datalen,
                resultlen,
                res;
    const struct pg_encoding *enc;

    datalen = VARSIZE(data) - VARHDRSZ;

    namebuf = TextDatumGetCString(name);

    enc = pg_find_encoding(namebuf);
    if (enc == NULL)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("unrecognized encoding: \"%s\"", namebuf)));

    resultlen = enc->decode_len(VARDATA(data), datalen);
    result = palloc(VARHDRSZ + resultlen);

    res = enc->decode(VARDATA(data), datalen, VARDATA(result));

    /* Make this FATAL 'cause we've trodden on memory ... */
    if (res > resultlen)
        elog(FATAL, "overflow - decode estimate too small");

    SET_VARSIZE(result, VARHDRSZ + res);

    PG_RETURN_BYTEA_P(result);
}

Datum binary_encode ( PG_FUNCTION_ARGS   ) 

Definition at line 36 of file encode.c.

References elog, enc, pg_encoding::encode, pg_encoding::encode_len, ereport, errcode(), errmsg(), ERROR, FATAL, name, NULL, palloc(), pg_find_encoding(), PG_GETARG_BYTEA_P, PG_GETARG_DATUM, PG_RETURN_TEXT_P, SET_VARSIZE, TextDatumGetCString, VARDATA, VARHDRSZ, and VARSIZE.

{
    bytea      *data = PG_GETARG_BYTEA_P(0);
    Datum       name = PG_GETARG_DATUM(1);
    text       *result;
    char       *namebuf;
    int         datalen,
                resultlen,
                res;
    const struct pg_encoding *enc;

    datalen = VARSIZE(data) - VARHDRSZ;

    namebuf = TextDatumGetCString(name);

    enc = pg_find_encoding(namebuf);
    if (enc == NULL)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("unrecognized encoding: \"%s\"", namebuf)));

    resultlen = enc->encode_len(VARDATA(data), datalen);
    result = palloc(VARHDRSZ + resultlen);

    res = enc->encode(VARDATA(data), datalen, VARDATA(result));

    /* Make this FATAL 'cause we've trodden on memory ... */
    if (res > resultlen)
        elog(FATAL, "overflow - encode estimate too small");

    SET_VARSIZE(result, VARHDRSZ + res);

    PG_RETURN_TEXT_P(result);
}

Datum bool_int4 ( PG_FUNCTION_ARGS   ) 

Definition at line 366 of file int.c.

References PG_GETARG_BOOL, and PG_RETURN_INT32.

{
    if (PG_GETARG_BOOL(0) == false)
        PG_RETURN_INT32(0);
    else
        PG_RETURN_INT32(1);
}

Datum booland_statefunc ( PG_FUNCTION_ARGS   ) 

Definition at line 290 of file bool.c.

References PG_GETARG_BOOL, and PG_RETURN_BOOL.

Datum booleq ( PG_FUNCTION_ARGS   ) 

Definition at line 229 of file bool.c.

References PG_GETARG_BOOL, and PG_RETURN_BOOL.

{
    bool        arg1 = PG_GETARG_BOOL(0);
    bool        arg2 = PG_GETARG_BOOL(1);

    PG_RETURN_BOOL(arg1 == arg2);
}

Datum boolge ( PG_FUNCTION_ARGS   ) 

Definition at line 274 of file bool.c.

References PG_GETARG_BOOL, and PG_RETURN_BOOL.

{
    bool        arg1 = PG_GETARG_BOOL(0);
    bool        arg2 = PG_GETARG_BOOL(1);

    PG_RETURN_BOOL(arg1 >= arg2);
}

Datum boolgt ( PG_FUNCTION_ARGS   ) 

Definition at line 256 of file bool.c.

References PG_GETARG_BOOL, and PG_RETURN_BOOL.

{
    bool        arg1 = PG_GETARG_BOOL(0);
    bool        arg2 = PG_GETARG_BOOL(1);

    PG_RETURN_BOOL(arg1 > arg2);
}

Datum boolin ( PG_FUNCTION_ARGS   ) 

Definition at line 130 of file bool.c.

References ereport, errcode(), errmsg(), ERROR, parse_bool_with_len(), PG_GETARG_CSTRING, and PG_RETURN_BOOL.

{
    const char *in_str = PG_GETARG_CSTRING(0);
    const char *str;
    size_t      len;
    bool        result;

    /*
     * Skip leading and trailing whitespace
     */
    str = in_str;
    while (isspace((unsigned char) *str))
        str++;

    len = strlen(str);
    while (len > 0 && isspace((unsigned char) str[len - 1]))
        len--;

    if (parse_bool_with_len(str, len, &result))
        PG_RETURN_BOOL(result);

    ereport(ERROR,
            (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
           errmsg("invalid input syntax for type boolean: \"%s\"", in_str)));

    /* not reached */
    PG_RETURN_BOOL(false);
}

Datum boolle ( PG_FUNCTION_ARGS   ) 

Definition at line 265 of file bool.c.

References PG_GETARG_BOOL, and PG_RETURN_BOOL.

{
    bool        arg1 = PG_GETARG_BOOL(0);
    bool        arg2 = PG_GETARG_BOOL(1);

    PG_RETURN_BOOL(arg1 <= arg2);
}

Datum boollt ( PG_FUNCTION_ARGS   ) 

Definition at line 247 of file bool.c.

References PG_GETARG_BOOL, and PG_RETURN_BOOL.

{
    bool        arg1 = PG_GETARG_BOOL(0);
    bool        arg2 = PG_GETARG_BOOL(1);

    PG_RETURN_BOOL(arg1 < arg2);
}

Datum boolne ( PG_FUNCTION_ARGS   ) 

Definition at line 238 of file bool.c.

References PG_GETARG_BOOL, and PG_RETURN_BOOL.

{
    bool        arg1 = PG_GETARG_BOOL(0);
    bool        arg2 = PG_GETARG_BOOL(1);

    PG_RETURN_BOOL(arg1 != arg2);
}

Datum boolor_statefunc ( PG_FUNCTION_ARGS   ) 

Definition at line 299 of file bool.c.

References PG_GETARG_BOOL, and PG_RETURN_BOOL.

Datum boolout ( PG_FUNCTION_ARGS   ) 

Definition at line 163 of file bool.c.

References palloc(), PG_GETARG_BOOL, and PG_RETURN_CSTRING.

{
    bool        b = PG_GETARG_BOOL(0);
    char       *result = (char *) palloc(2);

    result[0] = (b) ? 't' : 'f';
    result[1] = '\0';
    PG_RETURN_CSTRING(result);
}

Datum boolrecv ( PG_FUNCTION_ARGS   ) 

Definition at line 180 of file bool.c.

References buf, PG_GETARG_POINTER, PG_RETURN_BOOL, and pq_getmsgbyte().

{
    StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
    int         ext;

    ext = pq_getmsgbyte(buf);
    PG_RETURN_BOOL((ext != 0) ? true : false);
}

Datum boolsend ( PG_FUNCTION_ARGS   ) 

Definition at line 193 of file bool.c.

References buf, PG_GETARG_BOOL, PG_RETURN_BYTEA_P, pq_begintypsend(), pq_endtypsend(), and pq_sendbyte().

{
    bool        arg1 = PG_GETARG_BOOL(0);
    StringInfoData buf;

    pq_begintypsend(&buf);
    pq_sendbyte(&buf, arg1 ? 1 : 0);
    PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
}

Datum booltext ( PG_FUNCTION_ARGS   ) 

Definition at line 210 of file bool.c.

References cstring_to_text(), PG_GETARG_BOOL, and PG_RETURN_TEXT_P.

{
    bool        arg1 = PG_GETARG_BOOL(0);
    const char *str;

    if (arg1)
        str = "true";
    else
        str = "false";

    PG_RETURN_TEXT_P(cstring_to_text(str));
}

Datum bpchar ( PG_FUNCTION_ARGS   ) 

Definition at line 265 of file varchar.c.

References Assert, ereport, errcode(), errmsg(), ERROR, i, palloc(), PG_GETARG_BOOL, PG_GETARG_BPCHAR_PP, PG_GETARG_INT32, pg_mbcharcliplen(), pg_mbstrlen_with_len(), PG_RETURN_BPCHAR_P, SET_VARSIZE, VARDATA, VARDATA_ANY, VARHDRSZ, and VARSIZE_ANY_EXHDR.

{
    BpChar     *source = PG_GETARG_BPCHAR_PP(0);
    int32       maxlen = PG_GETARG_INT32(1);
    bool        isExplicit = PG_GETARG_BOOL(2);
    BpChar     *result;
    int32       len;
    char       *r;
    char       *s;
    int         i;
    int         charlen;        /* number of characters in the input string +
                                 * VARHDRSZ */

    /* No work if typmod is invalid */
    if (maxlen < (int32) VARHDRSZ)
        PG_RETURN_BPCHAR_P(source);

    maxlen -= VARHDRSZ;

    len = VARSIZE_ANY_EXHDR(source);
    s = VARDATA_ANY(source);

    charlen = pg_mbstrlen_with_len(s, len);

    /* No work if supplied data matches typmod already */
    if (charlen == maxlen)
        PG_RETURN_BPCHAR_P(source);

    if (charlen > maxlen)
    {
        /* Verify that extra characters are spaces, and clip them off */
        size_t      maxmblen;

        maxmblen = pg_mbcharcliplen(s, len, maxlen);

        if (!isExplicit)
        {
            for (i = maxmblen; i < len; i++)
                if (s[i] != ' ')
                    ereport(ERROR,
                            (errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION),
                             errmsg("value too long for type character(%d)",
                                    maxlen)));
        }

        len = maxmblen;

        /*
         * At this point, maxlen is the necessary byte length, not the number
         * of CHARACTERS!
         */
        maxlen = len;
    }
    else
    {
        /*
         * At this point, maxlen is the necessary byte length, not the number
         * of CHARACTERS!
         */
        maxlen = len + (maxlen - charlen);
    }

    Assert(maxlen >= len);

    result = palloc(maxlen + VARHDRSZ);
    SET_VARSIZE(result, maxlen + VARHDRSZ);
    r = VARDATA(result);

    memcpy(r, s, len);

    /* blank pad the string if necessary */
    if (maxlen > len)
        memset(r + len, ' ', maxlen - len);

    PG_RETURN_BPCHAR_P(result);
}

Datum bpchar_larger ( PG_FUNCTION_ARGS   ) 

Definition at line 862 of file varchar.c.

References bcTruelen(), PG_GET_COLLATION, PG_GETARG_BPCHAR_PP, PG_RETURN_BPCHAR_P, VARDATA_ANY, and varstr_cmp().

{
    BpChar     *arg1 = PG_GETARG_BPCHAR_PP(0);
    BpChar     *arg2 = PG_GETARG_BPCHAR_PP(1);
    int         len1,
                len2;
    int         cmp;

    len1 = bcTruelen(arg1);
    len2 = bcTruelen(arg2);

    cmp = varstr_cmp(VARDATA_ANY(arg1), len1, VARDATA_ANY(arg2), len2,
                     PG_GET_COLLATION());

    PG_RETURN_BPCHAR_P((cmp >= 0) ? arg1 : arg2);
}

Datum bpchar_name ( PG_FUNCTION_ARGS   ) 

Definition at line 365 of file varchar.c.

References NAMEDATALEN, NameStr, palloc0(), PG_GETARG_BPCHAR_PP, pg_mbcliplen(), PG_RETURN_NAME, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    BpChar     *s = PG_GETARG_BPCHAR_PP(0);
    char       *s_data;
    Name        result;
    int         len;

    len = VARSIZE_ANY_EXHDR(s);
    s_data = VARDATA_ANY(s);

    /* Truncate oversize input */
    if (len >= NAMEDATALEN)
        len = pg_mbcliplen(s_data, len, NAMEDATALEN - 1);

    /* Remove trailing blanks */
    while (len > 0)
    {
        if (s_data[len - 1] != ' ')
            break;
        len--;
    }

    /* We use palloc0 here to ensure result is zero-padded */
    result = (Name) palloc0(NAMEDATALEN);
    memcpy(NameStr(*result), s_data, len);

    PG_RETURN_NAME(result);
}

Datum bpchar_pattern_ge ( PG_FUNCTION_ARGS   ) 

Definition at line 988 of file varchar.c.

References internal_bpchar_pattern_compare(), PG_FREE_IF_COPY, PG_GETARG_BPCHAR_PP, and PG_RETURN_BOOL.

{
    BpChar     *arg1 = PG_GETARG_BPCHAR_PP(0);
    BpChar     *arg2 = PG_GETARG_BPCHAR_PP(1);
    int         result;

    result = internal_bpchar_pattern_compare(arg1, arg2);

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_BOOL(result >= 0);
}

Datum bpchar_pattern_gt ( PG_FUNCTION_ARGS   ) 

Definition at line 1004 of file varchar.c.

References internal_bpchar_pattern_compare(), PG_FREE_IF_COPY, PG_GETARG_BPCHAR_PP, and PG_RETURN_BOOL.

{
    BpChar     *arg1 = PG_GETARG_BPCHAR_PP(0);
    BpChar     *arg2 = PG_GETARG_BPCHAR_PP(1);
    int         result;

    result = internal_bpchar_pattern_compare(arg1, arg2);

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_BOOL(result > 0);
}

Datum bpchar_pattern_le ( PG_FUNCTION_ARGS   ) 

Definition at line 972 of file varchar.c.

References internal_bpchar_pattern_compare(), PG_FREE_IF_COPY, PG_GETARG_BPCHAR_PP, and PG_RETURN_BOOL.

{
    BpChar     *arg1 = PG_GETARG_BPCHAR_PP(0);
    BpChar     *arg2 = PG_GETARG_BPCHAR_PP(1);
    int         result;

    result = internal_bpchar_pattern_compare(arg1, arg2);

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_BOOL(result <= 0);
}

Datum bpchar_pattern_lt ( PG_FUNCTION_ARGS   ) 

Definition at line 956 of file varchar.c.

References internal_bpchar_pattern_compare(), PG_FREE_IF_COPY, PG_GETARG_BPCHAR_PP, and PG_RETURN_BOOL.

{
    BpChar     *arg1 = PG_GETARG_BPCHAR_PP(0);
    BpChar     *arg2 = PG_GETARG_BPCHAR_PP(1);
    int         result;

    result = internal_bpchar_pattern_compare(arg1, arg2);

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_BOOL(result < 0);
}

Datum bpchar_smaller ( PG_FUNCTION_ARGS   ) 

Definition at line 880 of file varchar.c.

References bcTruelen(), PG_GET_COLLATION, PG_GETARG_BPCHAR_PP, PG_RETURN_BPCHAR_P, VARDATA_ANY, and varstr_cmp().

{
    BpChar     *arg1 = PG_GETARG_BPCHAR_PP(0);
    BpChar     *arg2 = PG_GETARG_BPCHAR_PP(1);
    int         len1,
                len2;
    int         cmp;

    len1 = bcTruelen(arg1);
    len2 = bcTruelen(arg2);

    cmp = varstr_cmp(VARDATA_ANY(arg1), len1, VARDATA_ANY(arg2), len2,
                     PG_GET_COLLATION());

    PG_RETURN_BPCHAR_P((cmp <= 0) ? arg1 : arg2);
}

Datum bpcharcmp ( PG_FUNCTION_ARGS   ) 

Definition at line 841 of file varchar.c.

References bcTruelen(), PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_BPCHAR_PP, PG_RETURN_INT32, VARDATA_ANY, and varstr_cmp().

{
    BpChar     *arg1 = PG_GETARG_BPCHAR_PP(0);
    BpChar     *arg2 = PG_GETARG_BPCHAR_PP(1);
    int         len1,
                len2;
    int         cmp;

    len1 = bcTruelen(arg1);
    len2 = bcTruelen(arg2);

    cmp = varstr_cmp(VARDATA_ANY(arg1), len1, VARDATA_ANY(arg2), len2,
                     PG_GET_COLLATION());

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_INT32(cmp);
}

Datum bpchareq ( PG_FUNCTION_ARGS   ) 

Definition at line 703 of file varchar.c.

References bcTruelen(), memcmp(), PG_FREE_IF_COPY, PG_GETARG_BPCHAR_PP, PG_RETURN_BOOL, and VARDATA_ANY.

{
    BpChar     *arg1 = PG_GETARG_BPCHAR_PP(0);
    BpChar     *arg2 = PG_GETARG_BPCHAR_PP(1);
    int         len1,
                len2;
    bool        result;

    len1 = bcTruelen(arg1);
    len2 = bcTruelen(arg2);

    /*
     * Since we only care about equality or not-equality, we can avoid all the
     * expense of strcoll() here, and just do bitwise comparison.
     */
    if (len1 != len2)
        result = false;
    else
        result = (memcmp(VARDATA_ANY(arg1), VARDATA_ANY(arg2), len1) == 0);

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_BOOL(result);
}

Datum bpcharge ( PG_FUNCTION_ARGS   ) 

Definition at line 820 of file varchar.c.

References bcTruelen(), PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_BPCHAR_PP, PG_RETURN_BOOL, VARDATA_ANY, and varstr_cmp().

{
    BpChar     *arg1 = PG_GETARG_BPCHAR_PP(0);
    BpChar     *arg2 = PG_GETARG_BPCHAR_PP(1);
    int         len1,
                len2;
    int         cmp;

    len1 = bcTruelen(arg1);
    len2 = bcTruelen(arg2);

    cmp = varstr_cmp(VARDATA_ANY(arg1), len1, VARDATA_ANY(arg2), len2,
                     PG_GET_COLLATION());

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_BOOL(cmp >= 0);
}

Datum bpchargt ( PG_FUNCTION_ARGS   ) 

Definition at line 799 of file varchar.c.

References bcTruelen(), PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_BPCHAR_PP, PG_RETURN_BOOL, VARDATA_ANY, and varstr_cmp().

{
    BpChar     *arg1 = PG_GETARG_BPCHAR_PP(0);
    BpChar     *arg2 = PG_GETARG_BPCHAR_PP(1);
    int         len1,
                len2;
    int         cmp;

    len1 = bcTruelen(arg1);
    len2 = bcTruelen(arg2);

    cmp = varstr_cmp(VARDATA_ANY(arg1), len1, VARDATA_ANY(arg2), len2,
                     PG_GET_COLLATION());

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_BOOL(cmp > 0);
}

Datum bpcharin ( PG_FUNCTION_ARGS   ) 

Definition at line 190 of file varchar.c.

References bpchar_input(), PG_GETARG_CSTRING, PG_GETARG_INT32, PG_GETARG_OID, and PG_RETURN_BPCHAR_P.

{
    char       *s = PG_GETARG_CSTRING(0);

#ifdef NOT_USED
    Oid         typelem = PG_GETARG_OID(1);
#endif
    int32       atttypmod = PG_GETARG_INT32(2);
    BpChar     *result;

    result = bpchar_input(s, strlen(s), atttypmod);
    PG_RETURN_BPCHAR_P(result);
}

Datum bpcharle ( PG_FUNCTION_ARGS   ) 

Definition at line 778 of file varchar.c.

References bcTruelen(), PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_BPCHAR_PP, PG_RETURN_BOOL, VARDATA_ANY, and varstr_cmp().

{
    BpChar     *arg1 = PG_GETARG_BPCHAR_PP(0);
    BpChar     *arg2 = PG_GETARG_BPCHAR_PP(1);
    int         len1,
                len2;
    int         cmp;

    len1 = bcTruelen(arg1);
    len2 = bcTruelen(arg2);

    cmp = varstr_cmp(VARDATA_ANY(arg1), len1, VARDATA_ANY(arg2), len2,
                     PG_GET_COLLATION());

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_BOOL(cmp <= 0);
}

Datum bpcharlen ( PG_FUNCTION_ARGS   ) 

Definition at line 669 of file varchar.c.

References arg, bcTruelen(), pg_database_encoding_max_length(), PG_GETARG_BPCHAR_PP, pg_mbstrlen_with_len(), PG_RETURN_INT32, and VARDATA_ANY.

{
    BpChar     *arg = PG_GETARG_BPCHAR_PP(0);
    int         len;

    /* get number of bytes, ignoring trailing spaces */
    len = bcTruelen(arg);

    /* in multibyte encoding, convert to number of characters */
    if (pg_database_encoding_max_length() != 1)
        len = pg_mbstrlen_with_len(VARDATA_ANY(arg), len);

    PG_RETURN_INT32(len);
}

Datum bpcharlt ( PG_FUNCTION_ARGS   ) 

Definition at line 757 of file varchar.c.

References bcTruelen(), PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_BPCHAR_PP, PG_RETURN_BOOL, VARDATA_ANY, and varstr_cmp().

{
    BpChar     *arg1 = PG_GETARG_BPCHAR_PP(0);
    BpChar     *arg2 = PG_GETARG_BPCHAR_PP(1);
    int         len1,
                len2;
    int         cmp;

    len1 = bcTruelen(arg1);
    len2 = bcTruelen(arg2);

    cmp = varstr_cmp(VARDATA_ANY(arg1), len1, VARDATA_ANY(arg2), len2,
                     PG_GET_COLLATION());

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_BOOL(cmp < 0);
}

Datum bpcharne ( PG_FUNCTION_ARGS   ) 

Definition at line 730 of file varchar.c.

References bcTruelen(), memcmp(), PG_FREE_IF_COPY, PG_GETARG_BPCHAR_PP, PG_RETURN_BOOL, and VARDATA_ANY.

{
    BpChar     *arg1 = PG_GETARG_BPCHAR_PP(0);
    BpChar     *arg2 = PG_GETARG_BPCHAR_PP(1);
    int         len1,
                len2;
    bool        result;

    len1 = bcTruelen(arg1);
    len2 = bcTruelen(arg2);

    /*
     * Since we only care about equality or not-equality, we can avoid all the
     * expense of strcoll() here, and just do bitwise comparison.
     */
    if (len1 != len2)
        result = true;
    else
        result = (memcmp(VARDATA_ANY(arg1), VARDATA_ANY(arg2), len1) != 0);

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_BOOL(result);
}

Datum bpcharoctetlen ( PG_FUNCTION_ARGS   ) 

Definition at line 685 of file varchar.c.

References arg, PG_GETARG_DATUM, PG_RETURN_INT32, toast_raw_datum_size(), and VARHDRSZ.

{
    Datum       arg = PG_GETARG_DATUM(0);

    /* We need not detoast the input at all */
    PG_RETURN_INT32(toast_raw_datum_size(arg) - VARHDRSZ);
}

Datum bpcharout ( PG_FUNCTION_ARGS   ) 
Datum bpcharrecv ( PG_FUNCTION_ARGS   ) 

Definition at line 223 of file varchar.c.

References bpchar_input(), buf, StringInfoData::cursor, StringInfoData::len, pfree(), PG_GETARG_INT32, PG_GETARG_OID, PG_GETARG_POINTER, PG_RETURN_BPCHAR_P, and pq_getmsgtext().

{
    StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);

#ifdef NOT_USED
    Oid         typelem = PG_GETARG_OID(1);
#endif
    int32       atttypmod = PG_GETARG_INT32(2);
    BpChar     *result;
    char       *str;
    int         nbytes;

    str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
    result = bpchar_input(str, nbytes, atttypmod);
    pfree(str);
    PG_RETURN_BPCHAR_P(result);
}

Datum bpcharsend ( PG_FUNCTION_ARGS   ) 

Definition at line 245 of file varchar.c.

References textsend().

{
    /* Exactly the same as textsend, so share code */
    return textsend(fcinfo);
}

Datum bpchartypmodin ( PG_FUNCTION_ARGS   ) 
Datum bpchartypmodout ( PG_FUNCTION_ARGS   ) 

Definition at line 419 of file varchar.c.

References anychar_typmodout(), PG_GETARG_INT32, and PG_RETURN_CSTRING.

Datum btabstimecmp ( PG_FUNCTION_ARGS   ) 
Datum btboolcmp ( PG_FUNCTION_ARGS   ) 

Definition at line 56 of file nbtcompare.c.

References PG_GETARG_BOOL, and PG_RETURN_INT32.

{
    bool        a = PG_GETARG_BOOL(0);
    bool        b = PG_GETARG_BOOL(1);

    PG_RETURN_INT32((int32) a - (int32) b);
}

Datum btbpchar_pattern_cmp ( PG_FUNCTION_ARGS   ) 

Definition at line 1020 of file varchar.c.

References internal_bpchar_pattern_compare(), PG_FREE_IF_COPY, PG_GETARG_BPCHAR_PP, and PG_RETURN_INT32.

{
    BpChar     *arg1 = PG_GETARG_BPCHAR_PP(0);
    BpChar     *arg2 = PG_GETARG_BPCHAR_PP(1);
    int         result;

    result = internal_bpchar_pattern_compare(arg1, arg2);

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_INT32(result);
}

Datum btcharcmp ( PG_FUNCTION_ARGS   ) 

Definition at line 311 of file nbtcompare.c.

References PG_GETARG_CHAR, and PG_RETURN_INT32.

{
    char        a = PG_GETARG_CHAR(0);
    char        b = PG_GETARG_CHAR(1);

    /* Be careful to compare chars as unsigned */
    PG_RETURN_INT32((int32) ((uint8) a) - (int32) ((uint8) b));
}

Datum btfloat48cmp ( PG_FUNCTION_ARGS   ) 

Definition at line 1097 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_INT32.

{
    float4      arg1 = PG_GETARG_FLOAT4(0);
    float8      arg2 = PG_GETARG_FLOAT8(1);

    /* widen float4 to float8 and then compare */
    PG_RETURN_INT32(float8_cmp_internal(arg1, arg2));
}

Datum btfloat4cmp ( PG_FUNCTION_ARGS   ) 

Definition at line 956 of file float.c.

References float4_cmp_internal(), PG_GETARG_FLOAT4, and PG_RETURN_INT32.

Datum btfloat4sortsupport ( PG_FUNCTION_ARGS   ) 

Definition at line 974 of file float.c.

References SortSupportData::comparator, PG_GETARG_POINTER, and PG_RETURN_VOID.

{
    SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);

    ssup->comparator = btfloat4fastcmp;
    PG_RETURN_VOID();
}

Datum btfloat84cmp ( PG_FUNCTION_ARGS   ) 

Definition at line 1107 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_INT32.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float4      arg2 = PG_GETARG_FLOAT4(1);

    /* widen float4 to float8 and then compare */
    PG_RETURN_INT32(float8_cmp_internal(arg1, arg2));
}

Datum btfloat8cmp ( PG_FUNCTION_ARGS   ) 

Definition at line 1070 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT8, and PG_RETURN_INT32.

Datum btfloat8sortsupport ( PG_FUNCTION_ARGS   ) 

Definition at line 1088 of file float.c.

References SortSupportData::comparator, PG_GETARG_POINTER, and PG_RETURN_VOID.

{
    SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);

    ssup->comparator = btfloat8fastcmp;
    PG_RETURN_VOID();
}

Datum btint24cmp ( PG_FUNCTION_ARGS   ) 

Definition at line 194 of file nbtcompare.c.

References PG_GETARG_INT16, PG_GETARG_INT32, and PG_RETURN_INT32.

{
    int16       a = PG_GETARG_INT16(0);
    int32       b = PG_GETARG_INT32(1);

    if (a > b)
        PG_RETURN_INT32(1);
    else if (a == b)
        PG_RETURN_INT32(0);
    else
        PG_RETURN_INT32(-1);
}

Datum btint28cmp ( PG_FUNCTION_ARGS   ) 

Definition at line 222 of file nbtcompare.c.

References PG_GETARG_INT16, PG_GETARG_INT64, and PG_RETURN_INT32.

{
    int16       a = PG_GETARG_INT16(0);
    int64       b = PG_GETARG_INT64(1);

    if (a > b)
        PG_RETURN_INT32(1);
    else if (a == b)
        PG_RETURN_INT32(0);
    else
        PG_RETURN_INT32(-1);
}

Datum btint2cmp ( PG_FUNCTION_ARGS   ) 

Definition at line 65 of file nbtcompare.c.

References PG_GETARG_INT16, and PG_RETURN_INT32.

Datum btint2sortsupport ( PG_FUNCTION_ARGS   ) 

Definition at line 83 of file nbtcompare.c.

References SortSupportData::comparator, PG_GETARG_POINTER, and PG_RETURN_VOID.

{
    SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);

    ssup->comparator = btint2fastcmp;
    PG_RETURN_VOID();
}

Datum btint42cmp ( PG_FUNCTION_ARGS   ) 

Definition at line 208 of file nbtcompare.c.

References PG_GETARG_INT16, PG_GETARG_INT32, and PG_RETURN_INT32.

{
    int32       a = PG_GETARG_INT32(0);
    int16       b = PG_GETARG_INT16(1);

    if (a > b)
        PG_RETURN_INT32(1);
    else if (a == b)
        PG_RETURN_INT32(0);
    else
        PG_RETURN_INT32(-1);
}

Datum btint48cmp ( PG_FUNCTION_ARGS   ) 

Definition at line 166 of file nbtcompare.c.

References PG_GETARG_INT32, PG_GETARG_INT64, and PG_RETURN_INT32.

{
    int32       a = PG_GETARG_INT32(0);
    int64       b = PG_GETARG_INT64(1);

    if (a > b)
        PG_RETURN_INT32(1);
    else if (a == b)
        PG_RETURN_INT32(0);
    else
        PG_RETURN_INT32(-1);
}

Datum btint4cmp ( PG_FUNCTION_ARGS   ) 

Definition at line 92 of file nbtcompare.c.

References PG_GETARG_INT32, and PG_RETURN_INT32.

{
    int32       a = PG_GETARG_INT32(0);
    int32       b = PG_GETARG_INT32(1);

    if (a > b)
        PG_RETURN_INT32(1);
    else if (a == b)
        PG_RETURN_INT32(0);
    else
        PG_RETURN_INT32(-1);
}

Datum btint4sortsupport ( PG_FUNCTION_ARGS   ) 

Definition at line 120 of file nbtcompare.c.

References SortSupportData::comparator, PG_GETARG_POINTER, and PG_RETURN_VOID.

{
    SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);

    ssup->comparator = btint4fastcmp;
    PG_RETURN_VOID();
}

Datum btint82cmp ( PG_FUNCTION_ARGS   ) 

Definition at line 236 of file nbtcompare.c.

References PG_GETARG_INT16, PG_GETARG_INT64, and PG_RETURN_INT32.

{
    int64       a = PG_GETARG_INT64(0);
    int16       b = PG_GETARG_INT16(1);

    if (a > b)
        PG_RETURN_INT32(1);
    else if (a == b)
        PG_RETURN_INT32(0);
    else
        PG_RETURN_INT32(-1);
}

Datum btint84cmp ( PG_FUNCTION_ARGS   ) 

Definition at line 180 of file nbtcompare.c.

References PG_GETARG_INT32, PG_GETARG_INT64, and PG_RETURN_INT32.

{
    int64       a = PG_GETARG_INT64(0);
    int32       b = PG_GETARG_INT32(1);

    if (a > b)
        PG_RETURN_INT32(1);
    else if (a == b)
        PG_RETURN_INT32(0);
    else
        PG_RETURN_INT32(-1);
}

Datum btint8cmp ( PG_FUNCTION_ARGS   ) 

Definition at line 129 of file nbtcompare.c.

References PG_GETARG_INT64, and PG_RETURN_INT32.

{
    int64       a = PG_GETARG_INT64(0);
    int64       b = PG_GETARG_INT64(1);

    if (a > b)
        PG_RETURN_INT32(1);
    else if (a == b)
        PG_RETURN_INT32(0);
    else
        PG_RETURN_INT32(-1);
}

Datum btint8sortsupport ( PG_FUNCTION_ARGS   ) 

Definition at line 157 of file nbtcompare.c.

References SortSupportData::comparator, PG_GETARG_POINTER, and PG_RETURN_VOID.

{
    SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);

    ssup->comparator = btint8fastcmp;
    PG_RETURN_VOID();
}

Datum btnamecmp ( PG_FUNCTION_ARGS   ) 

Definition at line 321 of file nbtcompare.c.

References NAMEDATALEN, NameStr, PG_GETARG_NAME, and PG_RETURN_INT32.

Datum btnamesortsupport ( PG_FUNCTION_ARGS   ) 

Definition at line 339 of file nbtcompare.c.

References SortSupportData::comparator, PG_GETARG_POINTER, and PG_RETURN_VOID.

{
    SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);

    ssup->comparator = btnamefastcmp;
    PG_RETURN_VOID();
}

Datum btoidcmp ( PG_FUNCTION_ARGS   ) 

Definition at line 250 of file nbtcompare.c.

References PG_GETARG_OID, and PG_RETURN_INT32.

{
    Oid         a = PG_GETARG_OID(0);
    Oid         b = PG_GETARG_OID(1);

    if (a > b)
        PG_RETURN_INT32(1);
    else if (a == b)
        PG_RETURN_INT32(0);
    else
        PG_RETURN_INT32(-1);
}

Datum btoidsortsupport ( PG_FUNCTION_ARGS   ) 

Definition at line 278 of file nbtcompare.c.

References SortSupportData::comparator, PG_GETARG_POINTER, and PG_RETURN_VOID.

{
    SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);

    ssup->comparator = btoidfastcmp;
    PG_RETURN_VOID();
}

Datum btoidvectorcmp ( PG_FUNCTION_ARGS   ) 

Definition at line 287 of file nbtcompare.c.

References oidvector::dim1, i, PG_GETARG_POINTER, PG_RETURN_INT32, and oidvector::values.

Referenced by oidvectoreq(), oidvectorge(), oidvectorgt(), oidvectorle(), oidvectorlt(), and oidvectorne().

{
    oidvector  *a = (oidvector *) PG_GETARG_POINTER(0);
    oidvector  *b = (oidvector *) PG_GETARG_POINTER(1);
    int         i;

    /* We arbitrarily choose to sort first by vector length */
    if (a->dim1 != b->dim1)
        PG_RETURN_INT32(a->dim1 - b->dim1);

    for (i = 0; i < a->dim1; i++)
    {
        if (a->values[i] != b->values[i])
        {
            if (a->values[i] > b->values[i])
                PG_RETURN_INT32(1);
            else
                PG_RETURN_INT32(-1);
        }
    }
    PG_RETURN_INT32(0);
}

Datum btrecordcmp ( PG_FUNCTION_ARGS   ) 

Definition at line 1280 of file rowtypes.c.

References PG_RETURN_INT32, and record_cmp().

Datum btreltimecmp ( PG_FUNCTION_ARGS   ) 
Datum btrim ( PG_FUNCTION_ARGS   ) 

Definition at line 335 of file oracle_compat.c.

References dotrim(), PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    text       *string = PG_GETARG_TEXT_PP(0);
    text       *set = PG_GETARG_TEXT_PP(1);
    text       *ret;

    ret = dotrim(VARDATA_ANY(string), VARSIZE_ANY_EXHDR(string),
                 VARDATA_ANY(set), VARSIZE_ANY_EXHDR(set),
                 true, true);

    PG_RETURN_TEXT_P(ret);
}

Datum btrim1 ( PG_FUNCTION_ARGS   ) 

Definition at line 355 of file oracle_compat.c.

References dotrim(), PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    text       *string = PG_GETARG_TEXT_PP(0);
    text       *ret;

    ret = dotrim(VARDATA_ANY(string), VARSIZE_ANY_EXHDR(string),
                 " ", 1,
                 true, true);

    PG_RETURN_TEXT_P(ret);
}

Datum bttext_pattern_cmp ( PG_FUNCTION_ARGS   ) 

Definition at line 1806 of file varlena.c.

References internal_text_pattern_compare(), PG_FREE_IF_COPY, PG_GETARG_TEXT_PP, and PG_RETURN_INT32.

{
    text       *arg1 = PG_GETARG_TEXT_PP(0);
    text       *arg2 = PG_GETARG_TEXT_PP(1);
    int         result;

    result = internal_text_pattern_compare(arg1, arg2);

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_INT32(result);
}

Datum bttextcmp ( PG_FUNCTION_ARGS   ) 

Definition at line 1672 of file varlena.c.

References PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_INT32, and text_cmp().

Referenced by gbt_textcmp().

{
    text       *arg1 = PG_GETARG_TEXT_PP(0);
    text       *arg2 = PG_GETARG_TEXT_PP(1);
    int32       result;

    result = text_cmp(arg1, arg2, PG_GET_COLLATION());

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_INT32(result);
}

Datum bttidcmp ( PG_FUNCTION_ARGS   ) 
Datum bttintervalcmp ( PG_FUNCTION_ARGS   ) 
int2vector* buildint2vector ( const int16 int2s,
int  n 
)

Definition at line 112 of file int.c.

References int2vector::dataoffset, int2vector::dim1, int2vector::elemtype, Int2VectorSize, int2vector::lbound1, int2vector::ndim, palloc0(), SET_VARSIZE, and int2vector::values.

Referenced by CreateTrigger(), and UpdateIndexRelation().

{
    int2vector *result;

    result = (int2vector *) palloc0(Int2VectorSize(n));

    if (n > 0 && int2s)
        memcpy(result->values, int2s, n * sizeof(int16));

    /*
     * Attach standard array header.  For historical reasons, we set the index
     * lower bound to 0 not 1.
     */
    SET_VARSIZE(result, Int2VectorSize(n));
    result->ndim = 1;
    result->dataoffset = 0;     /* never any nulls */
    result->elemtype = INT2OID;
    result->dim1 = n;
    result->lbound1 = 0;

    return result;
}

oidvector* buildoidvector ( const Oid oids,
int  n 
)

Definition at line 164 of file oid.c.

References oidvector::dataoffset, oidvector::dim1, oidvector::elemtype, oidvector::lbound1, oidvector::ndim, OidVectorSize, palloc0(), SET_VARSIZE, and oidvector::values.

Referenced by AggregateCreate(), CreateProceduralLanguage(), examine_parameter_list(), makeRangeConstructors(), and UpdateIndexRelation().

{
    oidvector  *result;

    result = (oidvector *) palloc0(OidVectorSize(n));

    if (n > 0 && oids)
        memcpy(result->values, oids, n * sizeof(Oid));

    /*
     * Attach standard array header.  For historical reasons, we set the index
     * lower bound to 0 not 1.
     */
    SET_VARSIZE(result, OidVectorSize(n));
    result->ndim = 1;
    result->dataoffset = 0;     /* never any nulls */
    result->elemtype = OIDOID;
    result->dim1 = n;
    result->lbound1 = 0;

    return result;
}

Datum bytea_string_agg_finalfn ( PG_FUNCTION_ARGS   ) 

Definition at line 441 of file varlena.c.

References AggCheckCallContext(), Assert, StringInfoData::data, StringInfoData::len, NULL, palloc(), PG_ARGISNULL, PG_GETARG_POINTER, PG_RETURN_BYTEA_P, PG_RETURN_NULL, SET_VARSIZE, VARDATA, and VARHDRSZ.

{
    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)
    {
        bytea      *result;

        result = (bytea *) palloc(state->len + VARHDRSZ);
        SET_VARSIZE(result, state->len + VARHDRSZ);
        memcpy(VARDATA(result), state->data, state->len);
        PG_RETURN_BYTEA_P(result);
    }
    else
        PG_RETURN_NULL();
}

Datum bytea_string_agg_transfn ( PG_FUNCTION_ARGS   ) 

Definition at line 409 of file varlena.c.

References appendBinaryStringInfo(), makeStringAggState(), NULL, PG_ARGISNULL, PG_GETARG_BYTEA_PP, PG_GETARG_POINTER, PG_RETURN_POINTER, value, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    StringInfo  state;

    state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);

    /* Append the value unless null. */
    if (!PG_ARGISNULL(1))
    {
        bytea      *value = PG_GETARG_BYTEA_PP(1);

        /* On the first time through, we ignore the delimiter. */
        if (state == NULL)
            state = makeStringAggState(fcinfo);
        else if (!PG_ARGISNULL(2))
        {
            bytea      *delim = PG_GETARG_BYTEA_PP(2);

            appendBinaryStringInfo(state, VARDATA_ANY(delim), VARSIZE_ANY_EXHDR(delim));
        }

        appendBinaryStringInfo(state, VARDATA_ANY(value), VARSIZE_ANY_EXHDR(value));
    }

    /*
     * The transition type for string_agg() is declared to be "internal",
     * which is a pass-by-value type the same size as a pointer.
     */
    PG_RETURN_POINTER(state);
}

Datum bytealike ( PG_FUNCTION_ARGS   ) 

Definition at line 314 of file like.c.

References PG_GETARG_BYTEA_PP, PG_RETURN_BOOL, SB_MatchText(), VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    bytea      *str = PG_GETARG_BYTEA_PP(0);
    bytea      *pat = PG_GETARG_BYTEA_PP(1);
    bool        result;
    char       *s,
               *p;
    int         slen,
                plen;

    s = VARDATA_ANY(str);
    slen = VARSIZE_ANY_EXHDR(str);
    p = VARDATA_ANY(pat);
    plen = VARSIZE_ANY_EXHDR(pat);

    result = (SB_MatchText(s, slen, p, plen, 0, true) == LIKE_TRUE);

    PG_RETURN_BOOL(result);
}

Datum byteanlike ( PG_FUNCTION_ARGS   ) 

Definition at line 335 of file like.c.

References PG_GETARG_BYTEA_PP, PG_RETURN_BOOL, SB_MatchText(), VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    bytea      *str = PG_GETARG_BYTEA_PP(0);
    bytea      *pat = PG_GETARG_BYTEA_PP(1);
    bool        result;
    char       *s,
               *p;
    int         slen,
                plen;

    s = VARDATA_ANY(str);
    slen = VARSIZE_ANY_EXHDR(str);
    p = VARDATA_ANY(pat);
    plen = VARSIZE_ANY_EXHDR(pat);

    result = (SB_MatchText(s, slen, p, plen, 0, true) != LIKE_TRUE);

    PG_RETURN_BOOL(result);
}

Datum byteatrim ( PG_FUNCTION_ARGS   ) 

Definition at line 540 of file oracle_compat.c.

References palloc(), PG_GETARG_BYTEA_PP, PG_RETURN_BYTEA_P, SET_VARSIZE, VARDATA, VARDATA_ANY, VARHDRSZ, and VARSIZE_ANY_EXHDR.

{
    bytea      *string = PG_GETARG_BYTEA_PP(0);
    bytea      *set = PG_GETARG_BYTEA_PP(1);
    bytea      *ret;
    char       *ptr,
               *end,
               *ptr2,
               *ptr2start,
               *end2;
    int         m,
                stringlen,
                setlen;

    stringlen = VARSIZE_ANY_EXHDR(string);
    setlen = VARSIZE_ANY_EXHDR(set);

    if (stringlen <= 0 || setlen <= 0)
        PG_RETURN_BYTEA_P(string);

    m = stringlen;
    ptr = VARDATA_ANY(string);
    end = ptr + stringlen - 1;
    ptr2start = VARDATA_ANY(set);
    end2 = ptr2start + setlen - 1;

    while (m > 0)
    {
        ptr2 = ptr2start;
        while (ptr2 <= end2)
        {
            if (*ptr == *ptr2)
                break;
            ++ptr2;
        }
        if (ptr2 > end2)
            break;
        ptr++;
        m--;
    }

    while (m > 0)
    {
        ptr2 = ptr2start;
        while (ptr2 <= end2)
        {
            if (*end == *ptr2)
                break;
            ++ptr2;
        }
        if (ptr2 > end2)
            break;
        end--;
        m--;
    }

    ret = (bytea *) palloc(VARHDRSZ + m);
    SET_VARSIZE(ret, VARHDRSZ + m);
    memcpy(VARDATA(ret), ptr, m);

    PG_RETURN_BYTEA_P(ret);
}

Datum char_bpchar ( PG_FUNCTION_ARGS   ) 

Definition at line 347 of file varchar.c.

References palloc(), PG_GETARG_CHAR, PG_RETURN_BPCHAR_P, SET_VARSIZE, VARDATA, and VARHDRSZ.

{
    char        c = PG_GETARG_CHAR(0);
    BpChar     *result;

    result = (BpChar *) palloc(VARHDRSZ + 1);

    SET_VARSIZE(result, VARHDRSZ + 1);
    *(VARDATA(result)) = c;

    PG_RETURN_BPCHAR_P(result);
}

Datum char_text ( PG_FUNCTION_ARGS   ) 

Definition at line 195 of file char.c.

References palloc(), PG_GETARG_CHAR, PG_RETURN_TEXT_P, SET_VARSIZE, VARDATA, and VARHDRSZ.

{
    char        arg1 = PG_GETARG_CHAR(0);
    text       *result = palloc(VARHDRSZ + 1);

    /*
     * Convert \0 to an empty string, for consistency with charout (and
     * because the text stuff doesn't like embedded nulls all that well).
     */
    if (arg1 != '\0')
    {
        SET_VARSIZE(result, VARHDRSZ + 1);
        *(VARDATA(result)) = arg1;
    }
    else
        SET_VARSIZE(result, VARHDRSZ);

    PG_RETURN_TEXT_P(result);
}

Datum chareq ( PG_FUNCTION_ARGS   ) 

Definition at line 99 of file char.c.

References PG_GETARG_CHAR, and PG_RETURN_BOOL.

{
    char        arg1 = PG_GETARG_CHAR(0);
    char        arg2 = PG_GETARG_CHAR(1);

    PG_RETURN_BOOL(arg1 == arg2);
}

Datum charge ( PG_FUNCTION_ARGS   ) 

Definition at line 144 of file char.c.

References PG_GETARG_CHAR, and PG_RETURN_BOOL.

{
    char        arg1 = PG_GETARG_CHAR(0);
    char        arg2 = PG_GETARG_CHAR(1);

    PG_RETURN_BOOL((uint8) arg1 >= (uint8) arg2);
}

Datum chargt ( PG_FUNCTION_ARGS   ) 

Definition at line 135 of file char.c.

References PG_GETARG_CHAR, and PG_RETURN_BOOL.

{
    char        arg1 = PG_GETARG_CHAR(0);
    char        arg2 = PG_GETARG_CHAR(1);

    PG_RETURN_BOOL((uint8) arg1 > (uint8) arg2);
}

Datum charin ( PG_FUNCTION_ARGS   ) 

Definition at line 33 of file char.c.

References PG_GETARG_CSTRING, and PG_RETURN_CHAR.

{
    char       *ch = PG_GETARG_CSTRING(0);

    PG_RETURN_CHAR(ch[0]);
}

Datum charle ( PG_FUNCTION_ARGS   ) 

Definition at line 126 of file char.c.

References PG_GETARG_CHAR, and PG_RETURN_BOOL.

{
    char        arg1 = PG_GETARG_CHAR(0);
    char        arg2 = PG_GETARG_CHAR(1);

    PG_RETURN_BOOL((uint8) arg1 <= (uint8) arg2);
}

Datum charlt ( PG_FUNCTION_ARGS   ) 

Definition at line 117 of file char.c.

References PG_GETARG_CHAR, and PG_RETURN_BOOL.

{
    char        arg1 = PG_GETARG_CHAR(0);
    char        arg2 = PG_GETARG_CHAR(1);

    PG_RETURN_BOOL((uint8) arg1 < (uint8) arg2);
}

Datum charne ( PG_FUNCTION_ARGS   ) 

Definition at line 108 of file char.c.

References PG_GETARG_CHAR, and PG_RETURN_BOOL.

{
    char        arg1 = PG_GETARG_CHAR(0);
    char        arg2 = PG_GETARG_CHAR(1);

    PG_RETURN_BOOL(arg1 != arg2);
}

Datum charout ( PG_FUNCTION_ARGS   ) 

Definition at line 48 of file char.c.

References palloc(), PG_GETARG_CHAR, and PG_RETURN_CSTRING.

{
    char        ch = PG_GETARG_CHAR(0);
    char       *result = (char *) palloc(2);

    result[0] = ch;
    result[1] = '\0';
    PG_RETURN_CSTRING(result);
}

Datum charrecv ( PG_FUNCTION_ARGS   ) 
Datum charsend ( PG_FUNCTION_ARGS   ) 
Datum chartoi4 ( PG_FUNCTION_ARGS   ) 

Definition at line 154 of file char.c.

References PG_GETARG_CHAR, and PG_RETURN_INT32.

{
    char        arg1 = PG_GETARG_CHAR(0);

    PG_RETURN_INT32((int32) ((int8) arg1));
}

Datum chr ( PG_FUNCTION_ARGS   ) 

Definition at line 925 of file oracle_compat.c.

References encoding, ereport, errcode(), errmsg(), ERROR, GetDatabaseEncoding(), palloc(), pg_encoding_max_length(), PG_GETARG_UINT32, PG_RETURN_TEXT_P, PG_UTF8, SET_VARSIZE, VARDATA, and VARHDRSZ.

{
    uint32      cvalue = PG_GETARG_UINT32(0);
    text       *result;
    int         encoding = GetDatabaseEncoding();

    if (encoding == PG_UTF8 && cvalue > 127)
    {
        /* for Unicode we treat the argument as a code point */
        int         bytes;
        char       *wch;

        /* We only allow valid Unicode code points */
        if (cvalue > 0x001fffff)
            ereport(ERROR,
                    (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                     errmsg("requested character too large for encoding: %d",
                            cvalue)));

        if (cvalue > 0xffff)
            bytes = 4;
        else if (cvalue > 0x07ff)
            bytes = 3;
        else
            bytes = 2;

        result = (text *) palloc(VARHDRSZ + bytes);
        SET_VARSIZE(result, VARHDRSZ + bytes);
        wch = VARDATA(result);

        if (bytes == 2)
        {
            wch[0] = 0xC0 | ((cvalue >> 6) & 0x1F);
            wch[1] = 0x80 | (cvalue & 0x3F);;
        }
        else if (bytes == 3)
        {
            wch[0] = 0xE0 | ((cvalue >> 12) & 0x0F);
            wch[1] = 0x80 | ((cvalue >> 6) & 0x3F);
            wch[2] = 0x80 | (cvalue & 0x3F);
        }
        else
        {
            wch[0] = 0xF0 | ((cvalue >> 18) & 0x07);
            wch[1] = 0x80 | ((cvalue >> 12) & 0x3F);
            wch[2] = 0x80 | ((cvalue >> 6) & 0x3F);
            wch[3] = 0x80 | (cvalue & 0x3F);
        }

    }

    else
    {
        bool        is_mb;

        /*
         * Error out on arguments that make no sense or that we can't validly
         * represent in the encoding.
         */

        if (cvalue == 0)
            ereport(ERROR,
                    (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                     errmsg("null character not permitted")));

        is_mb = pg_encoding_max_length(encoding) > 1;

        if ((is_mb && (cvalue > 127)) || (!is_mb && (cvalue > 255)))
            ereport(ERROR,
                    (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                     errmsg("requested character too large for encoding: %d",
                            cvalue)));


        result = (text *) palloc(VARHDRSZ + 1);
        SET_VARSIZE(result, VARHDRSZ + 1);
        *VARDATA(result) = (char) cvalue;
    }

    PG_RETURN_TEXT_P(result);
}

Datum cideq ( PG_FUNCTION_ARGS   ) 

Definition at line 182 of file xid.c.

References PG_GETARG_COMMANDID, and PG_RETURN_BOOL.

Datum cidin ( PG_FUNCTION_ARGS   ) 

Definition at line 133 of file xid.c.

References PG_GETARG_CSTRING, and PG_RETURN_COMMANDID.

{
    char       *s = PG_GETARG_CSTRING(0);
    CommandId   c;

    c = atoi(s);

    PG_RETURN_COMMANDID(c);
}

Datum cidout ( PG_FUNCTION_ARGS   ) 

Definition at line 147 of file xid.c.

References palloc(), PG_GETARG_COMMANDID, PG_RETURN_CSTRING, and snprintf().

{
    CommandId   c = PG_GETARG_COMMANDID(0);
    char       *result = (char *) palloc(16);

    snprintf(result, 16, "%u", (unsigned int) c);
    PG_RETURN_CSTRING(result);
}

Datum cidr_abbrev ( PG_FUNCTION_ARGS   ) 

Definition at line 670 of file network.c.

References cstring_to_text(), ereport, errcode(), errmsg(), ERROR, inet_cidr_ntop(), ip_addr, ip_bits, ip_family, NULL, PG_GETARG_INET_PP, and PG_RETURN_TEXT_P.

{
    inet       *ip = PG_GETARG_INET_PP(0);
    char       *dst;
    char        tmp[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255/128")];

    dst = inet_cidr_ntop(ip_family(ip), ip_addr(ip),
                         ip_bits(ip), tmp, sizeof(tmp));

    if (dst == NULL)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
                 errmsg("could not format cidr value: %m")));

    PG_RETURN_TEXT_P(cstring_to_text(tmp));
}

Datum cidr_in ( PG_FUNCTION_ARGS   ) 

Definition at line 137 of file network.c.

References network_in(), PG_GETARG_CSTRING, and PG_RETURN_INET_P.

{
    char       *src = PG_GETARG_CSTRING(0);

    PG_RETURN_INET_P(network_in(src, true));
}

Datum cidr_out ( PG_FUNCTION_ARGS   ) 

Definition at line 181 of file network.c.

References network_out(), PG_GETARG_INET_PP, and PG_RETURN_CSTRING.

Datum cidr_recv ( PG_FUNCTION_ARGS   ) 
Datum cidr_send ( PG_FUNCTION_ARGS   ) 

Definition at line 308 of file network.c.

References network_send(), PG_GETARG_INET_PP, and PG_RETURN_BYTEA_P.

{
    inet       *addr = PG_GETARG_INET_PP(0);

    PG_RETURN_BYTEA_P(network_send(addr, true));
}

Datum cidr_set_masklen ( PG_FUNCTION_ARGS   ) 

Definition at line 382 of file network.c.

References ereport, errcode(), errmsg(), ERROR, ip_addr, ip_addrsize(), ip_bits, ip_maxbits, palloc(), PG_GETARG_INET_PP, PG_GETARG_INT32, PG_RETURN_INET_P, and VARSIZE_ANY.

{
    inet       *src = PG_GETARG_INET_PP(0);
    int         bits = PG_GETARG_INT32(1);
    inet       *dst;
    int         byte;
    int         nbits;
    int         maxbytes;

    if (bits == -1)
        bits = ip_maxbits(src);

    if ((bits < 0) || (bits > ip_maxbits(src)))
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("invalid mask length: %d", bits)));

    /* clone the original data */
    dst = (inet *) palloc(VARSIZE_ANY(src));
    memcpy(dst, src, VARSIZE_ANY(src));

    ip_bits(dst) = bits;

    /* zero out any bits to the right of the new netmask */
    byte = bits / 8;

    nbits = bits % 8;
    /* clear the first byte, this might be a partial byte */
    if (nbits != 0)
    {
        ip_addr(dst)[byte] &= ~(0xFF >> nbits);
        byte++;
    }
    /* clear remaining bytes */
    maxbytes = ip_addrsize(dst);
    while (byte < maxbytes)
    {
        ip_addr(dst)[byte] = 0;
        byte++;
    }

    PG_RETURN_INET_P(dst);
}

Datum cidrecv ( PG_FUNCTION_ARGS   ) 
Datum cidsend ( PG_FUNCTION_ARGS   ) 
void clean_ipv6_addr ( int  addr_family,
char *  addr 
)

Definition at line 1457 of file network.c.

Referenced by inet_client_addr(), inet_server_addr(), pg_stat_get_activity(), and pg_stat_get_backend_client_addr().

{
#ifdef HAVE_IPV6
    if (addr_family == AF_INET6)
    {
        char       *pct = strchr(addr, '%');

        if (pct)
            *pct = '\0';
    }
#endif
}

double convert_network_to_scalar ( Datum  value,
Oid  typid 
)

Definition at line 903 of file network.c.

References macaddr::a, macaddr::b, macaddr::c, CIDROID, macaddr::d, DatumGetInetPP, DatumGetMacaddrP, macaddr::e, elog, ERROR, macaddr::f, i, INETOID, ip_addr, ip_family, MACADDROID, and PGSQL_AF_INET.

Referenced by convert_to_scalar(), gbt_inet_compress(), and gbt_inet_consistent().

{
    switch (typid)
    {
        case INETOID:
        case CIDROID:
            {
                inet       *ip = DatumGetInetPP(value);
                int         len;
                double      res;
                int         i;

                /*
                 * Note that we don't use the full address for IPv6.
                 */
                if (ip_family(ip) == PGSQL_AF_INET)
                    len = 4;
                else
                    len = 5;

                res = ip_family(ip);
                for (i = 0; i < len; i++)
                {
                    res *= 256;
                    res += ip_addr(ip)[i];
                }
                return res;

                break;
            }
        case MACADDROID:
            {
                macaddr    *mac = DatumGetMacaddrP(value);
                double      res;

                res = (mac->a << 16) | (mac->b << 8) | (mac->c);
                res *= 256 * 256 * 256;
                res += (mac->d << 16) | (mac->e << 8) | (mac->f);
                return res;
            }
    }

    /*
     * Can't get here unless someone tries to use scalarltsel/scalargtsel on
     * an operator with one network and one non-network operand.
     */
    elog(ERROR, "unsupported type: %u", typid);
    return 0;
}

Datum cstring_in ( PG_FUNCTION_ARGS   ) 

Definition at line 37 of file pseudotypes.c.

References PG_GETARG_CSTRING, PG_RETURN_CSTRING, and pstrdup().

{
    char       *str = PG_GETARG_CSTRING(0);

    PG_RETURN_CSTRING(pstrdup(str));
}

Datum cstring_out ( PG_FUNCTION_ARGS   ) 

Definition at line 51 of file pseudotypes.c.

References PG_GETARG_CSTRING, PG_RETURN_CSTRING, and pstrdup().

{
    char       *str = PG_GETARG_CSTRING(0);

    PG_RETURN_CSTRING(pstrdup(str));
}

Datum cstring_recv ( PG_FUNCTION_ARGS   ) 

Definition at line 62 of file pseudotypes.c.

References buf, StringInfoData::cursor, StringInfoData::len, PG_GETARG_POINTER, PG_RETURN_CSTRING, and pq_getmsgtext().

{
    StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
    char       *str;
    int         nbytes;

    str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
    PG_RETURN_CSTRING(str);
}

Datum cstring_send ( PG_FUNCTION_ARGS   ) 

Definition at line 76 of file pseudotypes.c.

References buf, PG_GETARG_CSTRING, PG_RETURN_BYTEA_P, pq_begintypsend(), pq_endtypsend(), and pq_sendtext().

{
    char       *str = PG_GETARG_CSTRING(0);
    StringInfoData buf;

    pq_begintypsend(&buf);
    pq_sendtext(&buf, str, strlen(str));
    PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
}

text* cstring_to_text ( const char *  s  ) 

Definition at line 108 of file varlena.c.

References cstring_to_text_with_len().

Referenced by array_dims(), array_to_json(), array_to_json_pretty(), ASN1_STRING_to_text(), booltext(), cash_words(), chkpass_rout(), cidr_abbrev(), convert_charset(), cstring_to_xmltype(), current_query(), datetime_to_char_body(), dblink_build_sql_delete(), dblink_build_sql_insert(), dblink_build_sql_update(), dblink_cancel_query(), dblink_close(), dblink_connect(), dblink_disconnect(), dblink_error_message(), dblink_exec(), dblink_open(), dmetaphone(), dmetaphone_alt(), exec_assign_c_string(), filter_list_to_array(), format_type(), fsm_page_contents(), get_scalar(), hstore_to_json(), hstore_to_json_loose(), inet_abbrev(), initcap(), json_agg_finalfn(), json_in(), lower(), md5_bytea(), md5_text(), metaphone(), name_bpchar(), name_text(), network_host(), network_show(), oidvectortypes(), pg_collation_for(), pg_create_restore_point(), pg_crypt(), pg_current_xlog_insert_location(), pg_current_xlog_location(), pg_describe_object(), pg_export_snapshot(), pg_last_xlog_receive_location(), pg_last_xlog_replay_location(), pg_relation_filepath(), pg_size_pretty(), pg_size_pretty_numeric(), pg_start_backup(), pg_stat_get_backend_activity(), pg_stop_backup(), pg_switch_xlog(), pg_tablespace_location(), pg_xlogfile_name(), pgsql_version(), pgxml_result_to_text(), quote_ident(), quote_ident_cstr(), quote_nullable(), row_to_json(), row_to_json_pretty(), sepgsql_getcon(), sepgsql_mcstrans_in(), sepgsql_mcstrans_out(), set_config_by_name(), show_config_by_name(), ShowAllGUCConfig(), soundex(), split_text(), ssl_cipher(), ssl_version(), string_to_text(), text_substring(), textin(), timeofday(), to_hex32(), to_hex64(), to_json(), tsquerytree(), unaccent_dict(), upper(), X509_NAME_to_text(), xml_encode_special_chars(), xml_in(), and xml_recv().

{
    return cstring_to_text_with_len(s, strlen(s));
}

text* cstring_to_text_with_len ( const char *  s,
int  len 
)
Datum current_database ( PG_FUNCTION_ARGS   ) 
Datum current_query ( PG_FUNCTION_ARGS   ) 

Definition at line 67 of file misc.c.

References cstring_to_text(), debug_query_string, PG_RETURN_NULL, and PG_RETURN_TEXT_P.

Referenced by dblink_current_query().

{
    /* there is no easy way to access the more concise 'query_string' */
    if (debug_query_string)
        PG_RETURN_TEXT_P(cstring_to_text(debug_query_string));
    else
        PG_RETURN_NULL();
}

Datum current_schema ( PG_FUNCTION_ARGS   ) 

Definition at line 280 of file name.c.

References CStringGetDatum, DirectFunctionCall1, fetch_search_path(), get_namespace_name(), linitial_oid, list_free(), namein(), NIL, PG_RETURN_DATUM, and PG_RETURN_NULL.

{
    List       *search_path = fetch_search_path(false);
    char       *nspname;

    if (search_path == NIL)
        PG_RETURN_NULL();
    nspname = get_namespace_name(linitial_oid(search_path));
    list_free(search_path);
    if (!nspname)
        PG_RETURN_NULL();       /* recently-deleted namespace? */
    PG_RETURN_DATUM(DirectFunctionCall1(namein, CStringGetDatum(nspname)));
}

Datum current_schemas ( PG_FUNCTION_ARGS   ) 

Definition at line 295 of file name.c.

References construct_array(), CStringGetDatum, DirectFunctionCall1, fetch_search_path(), get_namespace_name(), lfirst_oid, list_free(), list_length(), namein(), NAMEOID, palloc(), PG_GETARG_BOOL, and PG_RETURN_POINTER.

{
    List       *search_path = fetch_search_path(PG_GETARG_BOOL(0));
    ListCell   *l;
    Datum      *names;
    int         i;
    ArrayType  *array;

    names = (Datum *) palloc(list_length(search_path) * sizeof(Datum));
    i = 0;
    foreach(l, search_path)
    {
        char       *nspname;

        nspname = get_namespace_name(lfirst_oid(l));
        if (nspname)            /* watch out for deleted namespace */
        {
            names[i] = DirectFunctionCall1(namein, CStringGetDatum(nspname));
            i++;
        }
    }
    list_free(search_path);

    array = construct_array(names, i,
                            NAMEOID,
                            NAMEDATALEN,        /* sizeof(Name) */
                            false,      /* Name is not by-val */
                            'c');       /* alignment of Name */

    PG_RETURN_POINTER(array);
}

Datum current_user ( PG_FUNCTION_ARGS   ) 
Datum currtid_byrelname ( PG_FUNCTION_ARGS   ) 
Datum currtid_byreloid ( PG_FUNCTION_ARGS   ) 
Datum dacos ( PG_FUNCTION_ARGS   ) 

Definition at line 1523 of file float.c.

References CHECKFLOATVAL, ereport, errcode(), errmsg(), ERROR, isinf(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      result;

    /*
     * We use errno here because the trigonometric functions are cyclic and
     * hard to check for underflow.
     */
    errno = 0;
    result = acos(arg1);
    if (errno != 0)
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("input is out of range")));

    CHECKFLOATVAL(result, isinf(arg1), true);
    PG_RETURN_FLOAT8(result);
}

Datum dasin ( PG_FUNCTION_ARGS   ) 

Definition at line 1548 of file float.c.

References CHECKFLOATVAL, ereport, errcode(), errmsg(), ERROR, isinf(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      result;

    errno = 0;
    result = asin(arg1);
    if (errno != 0)
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("input is out of range")));

    CHECKFLOATVAL(result, isinf(arg1), true);
    PG_RETURN_FLOAT8(result);
}

Datum database_character_set ( PG_FUNCTION_ARGS   ) 
Datum datan ( PG_FUNCTION_ARGS   ) 

Definition at line 1569 of file float.c.

References CHECKFLOATVAL, ereport, errcode(), errmsg(), ERROR, isinf(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      result;

    errno = 0;
    result = atan(arg1);
    if (errno != 0)
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("input is out of range")));

    CHECKFLOATVAL(result, isinf(arg1), true);
    PG_RETURN_FLOAT8(result);
}

Datum datan2 ( PG_FUNCTION_ARGS   ) 

Definition at line 1590 of file float.c.

References CHECKFLOATVAL, ereport, errcode(), errmsg(), ERROR, isinf(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      arg2 = PG_GETARG_FLOAT8(1);
    float8      result;

    errno = 0;
    result = atan2(arg1, arg2);
    if (errno != 0)
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("input is out of range")));

    CHECKFLOATVAL(result, isinf(arg1) || isinf(arg2), true);
    PG_RETURN_FLOAT8(result);
}

Datum dcbrt ( PG_FUNCTION_ARGS   ) 

Definition at line 1377 of file float.c.

References cbrt, CHECKFLOATVAL, isinf(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      result;

    result = cbrt(arg1);
    CHECKFLOATVAL(result, isinf(arg1), arg1 == 0);
    PG_RETURN_FLOAT8(result);
}

Datum dceil ( PG_FUNCTION_ARGS   ) 

Definition at line 1290 of file float.c.

References PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);

    PG_RETURN_FLOAT8(ceil(arg1));
}

Datum dcos ( PG_FUNCTION_ARGS   ) 

Definition at line 1612 of file float.c.

References CHECKFLOATVAL, ereport, errcode(), errmsg(), ERROR, isinf(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      result;

    errno = 0;
    result = cos(arg1);
    if (errno != 0)
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("input is out of range")));

    CHECKFLOATVAL(result, isinf(arg1), true);
    PG_RETURN_FLOAT8(result);
}

Datum dcot ( PG_FUNCTION_ARGS   ) 

Definition at line 1633 of file float.c.

References CHECKFLOATVAL, ereport, errcode(), errmsg(), ERROR, PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      result;

    errno = 0;
    result = tan(arg1);
    if (errno != 0)
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("input is out of range")));

    result = 1.0 / result;
    CHECKFLOATVAL(result, true /* cotan(pi/2) == inf */ , true);
    PG_RETURN_FLOAT8(result);
}

Datum degrees ( PG_FUNCTION_ARGS   ) 

Definition at line 1697 of file float.c.

References CHECKFLOATVAL, isinf(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      result;

    result = arg1 * (180.0 / M_PI);

    CHECKFLOATVAL(result, isinf(arg1), arg1 == 0);
    PG_RETURN_FLOAT8(result);
}

List* deparse_context_for ( const char *  aliasname,
Oid  relid 
)

Definition at line 2333 of file ruleutils.c.

References RangeTblEntry::alias, deparse_namespace::ctes, RangeTblEntry::eref, RangeTblEntry::inFromCl, RangeTblEntry::inh, RangeTblEntry::lateral, list_make1, makeAlias(), makeNode, NIL, NULL, palloc0(), RangeTblEntry::relid, RangeTblEntry::relkind, deparse_namespace::rtable, RangeTblEntry::rtekind, set_rtable_names(), and set_simple_column_names().

Referenced by pg_get_constraintdef_worker(), pg_get_expr_worker(), pg_get_indexdef_worker(), StoreAttrDefault(), and StoreRelCheck().

{
    deparse_namespace *dpns;
    RangeTblEntry *rte;

    dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));

    /* Build a minimal RTE for the rel */
    rte = makeNode(RangeTblEntry);
    rte->rtekind = RTE_RELATION;
    rte->relid = relid;
    rte->relkind = RELKIND_RELATION;    /* no need for exactness here */
    rte->alias = makeAlias(aliasname, NIL);
    rte->eref = rte->alias;
    rte->lateral = false;
    rte->inh = false;
    rte->inFromCl = true;

    /* Build one-element rtable */
    dpns->rtable = list_make1(rte);
    dpns->ctes = NIL;
    set_rtable_names(dpns, NIL, NULL);
    set_simple_column_names(dpns);

    /* Return a one-deep namespace stack */
    return list_make1(dpns);
}

List* deparse_context_for_planstate ( Node planstate,
List ancestors,
List rtable,
List rtable_names 
)

Definition at line 2387 of file ruleutils.c.

References deparse_namespace::ancestors, deparse_namespace::ctes, list_make1, palloc0(), deparse_namespace::rtable, deparse_namespace::rtable_names, set_deparse_planstate(), and set_simple_column_names().

Referenced by show_expression(), show_plan_tlist(), and show_sort_keys_common().

{
    deparse_namespace *dpns;

    dpns = (deparse_namespace *) palloc0(sizeof(deparse_namespace));

    /* Initialize fields that stay the same across the whole plan tree */
    dpns->rtable = rtable;
    dpns->rtable_names = rtable_names;
    dpns->ctes = NIL;

    /*
     * Set up column name aliases.  We will get rather bogus results for join
     * RTEs, but that doesn't matter because plan trees don't contain any join
     * alias Vars.
     */
    set_simple_column_names(dpns);

    /* Set our attention on the specific plan node passed in */
    set_deparse_planstate(dpns, (PlanState *) planstate);
    dpns->ancestors = ancestors;

    /* Return a one-deep namespace stack */
    return list_make1(dpns);
}

char* deparse_expression ( Node expr,
List dpcontext,
bool  forceprefix,
bool  showimplicit 
)
Datum dexp ( PG_FUNCTION_ARGS   ) 

Definition at line 1445 of file float.c.

References CHECKFLOATVAL, get_float8_infinity(), isinf(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      result;

    errno = 0;
    result = exp(arg1);
    if (errno == ERANGE && result != 0 && !isinf(result))
        result = get_float8_infinity();

    CHECKFLOATVAL(result, isinf(arg1), false);
    PG_RETURN_FLOAT8(result);
}

Datum dfloor ( PG_FUNCTION_ARGS   ) 

Definition at line 1302 of file float.c.

References PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);

    PG_RETURN_FLOAT8(floor(arg1));
}

Datum dlog1 ( PG_FUNCTION_ARGS   ) 

Definition at line 1464 of file float.c.

References CHECKFLOATVAL, ereport, errcode(), errmsg(), ERROR, isinf(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      result;

    /*
     * Emit particular SQLSTATE error codes for ln(). This is required by the
     * SQL standard.
     */
    if (arg1 == 0.0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
                 errmsg("cannot take logarithm of zero")));
    if (arg1 < 0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
                 errmsg("cannot take logarithm of a negative number")));

    result = log(arg1);

    CHECKFLOATVAL(result, isinf(arg1), arg1 == 1);
    PG_RETURN_FLOAT8(result);
}

Datum dlog10 ( PG_FUNCTION_ARGS   ) 

Definition at line 1493 of file float.c.

References CHECKFLOATVAL, ereport, errcode(), errmsg(), ERROR, isinf(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      result;

    /*
     * Emit particular SQLSTATE error codes for log(). The SQL spec doesn't
     * define log(), but it does define ln(), so it makes sense to emit the
     * same error code for an analogous error condition.
     */
    if (arg1 == 0.0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
                 errmsg("cannot take logarithm of zero")));
    if (arg1 < 0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
                 errmsg("cannot take logarithm of a negative number")));

    result = log10(arg1);

    CHECKFLOATVAL(result, isinf(arg1), arg1 == 1);
    PG_RETURN_FLOAT8(result);
}

void domain_check ( Datum  value,
bool  isnull,
Oid  domainType,
void **  extra,
MemoryContext  mcxt 
)

Definition at line 319 of file domains.c.

References CurrentMemoryContext, domain_check_input(), domain_state_setup(), DomainIOData::domain_type, MemoryContextAlloc(), and NULL.

Referenced by PLyObject_ToBool(), and PLyObject_ToBytea().

{
    DomainIOData *my_extra = NULL;

    if (mcxt == NULL)
        mcxt = CurrentMemoryContext;

    /*
     * We arrange to look up the needed info just once per series of calls,
     * assuming the domain type doesn't change underneath us.
     */
    if (extra)
        my_extra = (DomainIOData *) *extra;
    if (my_extra == NULL)
    {
        my_extra = (DomainIOData *) MemoryContextAlloc(mcxt,
                                                       sizeof(DomainIOData));
        domain_state_setup(my_extra, domainType, true, mcxt);
        if (extra)
            *extra = (void *) my_extra;
    }
    else if (my_extra->domain_type != domainType)
        domain_state_setup(my_extra, domainType, true, mcxt);

    /*
     * Do the necessary checks to ensure it's a valid domain value.
     */
    domain_check_input(value, isnull, my_extra);
}

Datum domain_in ( PG_FUNCTION_ARGS   ) 

Definition at line 196 of file domains.c.

References domain_check_input(), domain_state_setup(), DomainIOData::domain_type, InputFunctionCall(), MemoryContextAlloc(), NULL, PG_ARGISNULL, PG_GETARG_CSTRING, PG_GETARG_OID, PG_RETURN_DATUM, PG_RETURN_NULL, DomainIOData::proc, DomainIOData::typioparam, DomainIOData::typtypmod, and value.

{
    char       *string;
    Oid         domainType;
    DomainIOData *my_extra;
    Datum       value;

    /*
     * Since domain_in is not strict, we have to check for null inputs. The
     * typioparam argument should never be null in normal system usage, but it
     * could be null in a manual invocation --- if so, just return null.
     */
    if (PG_ARGISNULL(0))
        string = NULL;
    else
        string = PG_GETARG_CSTRING(0);
    if (PG_ARGISNULL(1))
        PG_RETURN_NULL();
    domainType = PG_GETARG_OID(1);

    /*
     * We arrange to look up the needed info just once per series of calls,
     * assuming the domain type doesn't change underneath us.
     */
    my_extra = (DomainIOData *) fcinfo->flinfo->fn_extra;
    if (my_extra == NULL)
    {
        my_extra = (DomainIOData *) MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
                                                       sizeof(DomainIOData));
        domain_state_setup(my_extra, domainType, false,
                           fcinfo->flinfo->fn_mcxt);
        fcinfo->flinfo->fn_extra = (void *) my_extra;
    }
    else if (my_extra->domain_type != domainType)
        domain_state_setup(my_extra, domainType, false,
                           fcinfo->flinfo->fn_mcxt);

    /*
     * Invoke the base type's typinput procedure to convert the data.
     */
    value = InputFunctionCall(&my_extra->proc,
                              string,
                              my_extra->typioparam,
                              my_extra->typtypmod);

    /*
     * Do the necessary checks to ensure it's a valid domain value.
     */
    domain_check_input(value, (string == NULL), my_extra);

    if (string == NULL)
        PG_RETURN_NULL();
    else
        PG_RETURN_DATUM(value);
}

Datum domain_recv ( PG_FUNCTION_ARGS   ) 

Definition at line 256 of file domains.c.

References buf, domain_check_input(), domain_state_setup(), DomainIOData::domain_type, MemoryContextAlloc(), NULL, PG_ARGISNULL, PG_GETARG_OID, PG_GETARG_POINTER, PG_RETURN_DATUM, PG_RETURN_NULL, DomainIOData::proc, ReceiveFunctionCall(), DomainIOData::typioparam, DomainIOData::typtypmod, and value.

{
    StringInfo  buf;
    Oid         domainType;
    DomainIOData *my_extra;
    Datum       value;

    /*
     * Since domain_recv is not strict, we have to check for null inputs. The
     * typioparam argument should never be null in normal system usage, but it
     * could be null in a manual invocation --- if so, just return null.
     */
    if (PG_ARGISNULL(0))
        buf = NULL;
    else
        buf = (StringInfo) PG_GETARG_POINTER(0);
    if (PG_ARGISNULL(1))
        PG_RETURN_NULL();
    domainType = PG_GETARG_OID(1);

    /*
     * We arrange to look up the needed info just once per series of calls,
     * assuming the domain type doesn't change underneath us.
     */
    my_extra = (DomainIOData *) fcinfo->flinfo->fn_extra;
    if (my_extra == NULL)
    {
        my_extra = (DomainIOData *) MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
                                                       sizeof(DomainIOData));
        domain_state_setup(my_extra, domainType, true,
                           fcinfo->flinfo->fn_mcxt);
        fcinfo->flinfo->fn_extra = (void *) my_extra;
    }
    else if (my_extra->domain_type != domainType)
        domain_state_setup(my_extra, domainType, true,
                           fcinfo->flinfo->fn_mcxt);

    /*
     * Invoke the base type's typreceive procedure to convert the data.
     */
    value = ReceiveFunctionCall(&my_extra->proc,
                                buf,
                                my_extra->typioparam,
                                my_extra->typtypmod);

    /*
     * Do the necessary checks to ensure it's a valid domain value.
     */
    domain_check_input(value, (buf == NULL), my_extra);

    if (buf == NULL)
        PG_RETURN_NULL();
    else
        PG_RETURN_DATUM(value);
}

Datum dpi ( PG_FUNCTION_ARGS   ) 

Definition at line 1713 of file float.c.

References M_PI, and PG_RETURN_FLOAT8.

Datum dpow ( PG_FUNCTION_ARGS   ) 

Definition at line 1392 of file float.c.

References CHECKFLOATVAL, ereport, errcode(), errmsg(), ERROR, get_float8_infinity(), isinf(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      arg2 = PG_GETARG_FLOAT8(1);
    float8      result;

    /*
     * The SQL spec requires that we emit a particular SQLSTATE error code for
     * certain error conditions.  Specifically, we don't return a
     * divide-by-zero error code for 0 ^ -1.
     */
    if (arg1 == 0 && arg2 < 0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
                 errmsg("zero raised to a negative power is undefined")));
    if (arg1 < 0 && floor(arg2) != arg2)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
                 errmsg("a negative number raised to a non-integer power yields a complex result")));

    /*
     * pow() sets errno only on some platforms, depending on whether it
     * follows _IEEE_, _POSIX_, _XOPEN_, or _SVID_, so we try to avoid using
     * errno.  However, some platform/CPU combinations return errno == EDOM
     * and result == Nan for negative arg1 and very large arg2 (they must be
     * using something different from our floor() test to decide it's
     * invalid).  Other platforms (HPPA) return errno == ERANGE and a large
     * (HUGE_VAL) but finite result to signal overflow.
     */
    errno = 0;
    result = pow(arg1, arg2);
    if (errno == EDOM && isnan(result))
    {
        if ((fabs(arg1) > 1 && arg2 >= 0) || (fabs(arg1) < 1 && arg2 < 0))
            /* The sign of Inf is not significant in this case. */
            result = get_float8_infinity();
        else if (fabs(arg1) != 1)
            result = 0;
        else
            result = 1;
    }
    else if (errno == ERANGE && result != 0 && !isinf(result))
        result = get_float8_infinity();

    CHECKFLOATVAL(result, isinf(arg1) || isinf(arg2), arg1 == 0);
    PG_RETURN_FLOAT8(result);
}

Datum drandom ( PG_FUNCTION_ARGS   ) 

Definition at line 1739 of file float.c.

References MAX_RANDOM_VALUE, PG_RETURN_FLOAT8, and random().

{
    float8      result;

    /* result [0.0 - 1.0) */
    result = (double) random() / ((double) MAX_RANDOM_VALUE + 1);

    PG_RETURN_FLOAT8(result);
}

Datum dround ( PG_FUNCTION_ARGS   ) 

Definition at line 1278 of file float.c.

References PG_GETARG_FLOAT8, PG_RETURN_FLOAT8, and rint().

Datum dsign ( PG_FUNCTION_ARGS   ) 

Definition at line 1315 of file float.c.

References PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      result;

    if (arg1 > 0)
        result = 1.0;
    else if (arg1 < 0)
        result = -1.0;
    else
        result = 0.0;

    PG_RETURN_FLOAT8(result);
}

Datum dsin ( PG_FUNCTION_ARGS   ) 

Definition at line 1655 of file float.c.

References CHECKFLOATVAL, ereport, errcode(), errmsg(), ERROR, isinf(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      result;

    errno = 0;
    result = sin(arg1);
    if (errno != 0)
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("input is out of range")));

    CHECKFLOATVAL(result, isinf(arg1), true);
    PG_RETURN_FLOAT8(result);
}

Datum dsqrt ( PG_FUNCTION_ARGS   ) 

Definition at line 1356 of file float.c.

References CHECKFLOATVAL, ereport, errcode(), errmsg(), ERROR, isinf(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      result;

    if (arg1 < 0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
                 errmsg("cannot take square root of a negative number")));

    result = sqrt(arg1);

    CHECKFLOATVAL(result, isinf(arg1), arg1 == 0);
    PG_RETURN_FLOAT8(result);
}

Datum dtan ( PG_FUNCTION_ARGS   ) 

Definition at line 1676 of file float.c.

References CHECKFLOATVAL, ereport, errcode(), errmsg(), ERROR, PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      result;

    errno = 0;
    result = tan(arg1);
    if (errno != 0)
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("input is out of range")));

    CHECKFLOATVAL(result, true /* tan(pi/2) == Inf */ , true);
    PG_RETURN_FLOAT8(result);
}

Datum dtof ( PG_FUNCTION_ARGS   ) 

Definition at line 1139 of file float.c.

References CHECKFLOATVAL, isinf(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT4.

{
    float8      num = PG_GETARG_FLOAT8(0);

    CHECKFLOATVAL((float4) num, isinf(num), num == 0);

    PG_RETURN_FLOAT4((float4) num);
}

Datum dtoi2 ( PG_FUNCTION_ARGS   ) 

Definition at line 1173 of file float.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_FLOAT8, PG_RETURN_INT16, and rint().

{
    float8      num = PG_GETARG_FLOAT8(0);

    if (num < SHRT_MIN || num > SHRT_MAX || isnan(num))
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("smallint out of range")));

    PG_RETURN_INT16((int16) rint(num));
}

Datum dtoi4 ( PG_FUNCTION_ARGS   ) 

Definition at line 1153 of file float.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_FLOAT8, PG_RETURN_INT32, and rint().

{
    float8      num = PG_GETARG_FLOAT8(0);
    int32       result;

    /* 'Inf' is handled by INT_MAX */
    if (num < INT_MIN || num > INT_MAX || isnan(num))
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("integer out of range")));

    result = (int32) rint(num);
    PG_RETURN_INT32(result);
}

Datum dtrunc ( PG_FUNCTION_ARGS   ) 

Definition at line 1338 of file float.c.

References PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      result;

    if (arg1 >= 0)
        result = floor(arg1);
    else
        result = -floor(-arg1);

    PG_RETURN_FLOAT8(result);
}

Datum enum_cmp ( PG_FUNCTION_ARGS   ) 

Definition at line 285 of file enum.c.

References enum_cmp_internal(), PG_GETARG_OID, and PG_RETURN_INT32.

{
    Oid         a = PG_GETARG_OID(0);
    Oid         b = PG_GETARG_OID(1);

    if (a == b)
        PG_RETURN_INT32(0);
    else if (enum_cmp_internal(a, b, fcinfo) > 0)
        PG_RETURN_INT32(1);
    else
        PG_RETURN_INT32(-1);
}

Datum enum_eq ( PG_FUNCTION_ARGS   ) 

Definition at line 231 of file enum.c.

References PG_GETARG_OID, and PG_RETURN_BOOL.

{
    Oid         a = PG_GETARG_OID(0);
    Oid         b = PG_GETARG_OID(1);

    PG_RETURN_BOOL(a == b);
}

Datum enum_first ( PG_FUNCTION_ARGS   ) 

Definition at line 343 of file enum.c.

References enum_endpoint(), ereport, errcode(), errmsg(), ERROR, format_type_be(), ForwardScanDirection, get_fn_expr_argtype(), InvalidOid, OidIsValid, and PG_RETURN_OID.

{
    Oid         enumtypoid;
    Oid         min;

    /*
     * We rely on being able to get the specific enum type from the calling
     * expression tree.  Notice that the actual value of the argument isn't
     * examined at all; in particular it might be NULL.
     */
    enumtypoid = get_fn_expr_argtype(fcinfo->flinfo, 0);
    if (enumtypoid == InvalidOid)
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("could not determine actual enum type")));

    /* Get the OID using the index */
    min = enum_endpoint(enumtypoid, ForwardScanDirection);

    if (!OidIsValid(min))
        ereport(ERROR,
                (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                 errmsg("enum %s contains no values",
                        format_type_be(enumtypoid))));

    PG_RETURN_OID(min);
}

Datum enum_ge ( PG_FUNCTION_ARGS   ) 

Definition at line 249 of file enum.c.

References enum_cmp_internal(), PG_GETARG_OID, and PG_RETURN_BOOL.

{
    Oid         a = PG_GETARG_OID(0);
    Oid         b = PG_GETARG_OID(1);

    PG_RETURN_BOOL(enum_cmp_internal(a, b, fcinfo) >= 0);
}

Datum enum_gt ( PG_FUNCTION_ARGS   ) 

Definition at line 258 of file enum.c.

References enum_cmp_internal(), PG_GETARG_OID, and PG_RETURN_BOOL.

{
    Oid         a = PG_GETARG_OID(0);
    Oid         b = PG_GETARG_OID(1);

    PG_RETURN_BOOL(enum_cmp_internal(a, b, fcinfo) > 0);
}

Datum enum_in ( PG_FUNCTION_ARGS   ) 

Definition at line 37 of file enum.c.

References CStringGetDatum, ENUMTYPOIDNAME, ereport, errcode(), errmsg(), ERROR, format_type_be(), HeapTupleGetOid, HeapTupleIsValid, name, NAMEDATALEN, ObjectIdGetDatum, PG_GETARG_CSTRING, PG_GETARG_OID, PG_RETURN_OID, ReleaseSysCache(), and SearchSysCache2.

{
    char       *name = PG_GETARG_CSTRING(0);
    Oid         enumtypoid = PG_GETARG_OID(1);
    Oid         enumoid;
    HeapTuple   tup;

    /* must check length to prevent Assert failure within SearchSysCache */
    if (strlen(name) >= NAMEDATALEN)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                 errmsg("invalid input value for enum %s: \"%s\"",
                        format_type_be(enumtypoid),
                        name)));

    tup = SearchSysCache2(ENUMTYPOIDNAME,
                          ObjectIdGetDatum(enumtypoid),
                          CStringGetDatum(name));
    if (!HeapTupleIsValid(tup))
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                 errmsg("invalid input value for enum %s: \"%s\"",
                        format_type_be(enumtypoid),
                        name)));

    /*
     * This comes from pg_enum.oid and stores system oids in user tables. This
     * oid must be preserved by binary upgrades.
     */
    enumoid = HeapTupleGetOid(tup);

    ReleaseSysCache(tup);

    PG_RETURN_OID(enumoid);
}

Datum enum_larger ( PG_FUNCTION_ARGS   ) 

Definition at line 276 of file enum.c.

References enum_cmp_internal(), PG_GETARG_OID, and PG_RETURN_OID.

{
    Oid         a = PG_GETARG_OID(0);
    Oid         b = PG_GETARG_OID(1);

    PG_RETURN_OID(enum_cmp_internal(a, b, fcinfo) > 0 ? a : b);
}

Datum enum_last ( PG_FUNCTION_ARGS   ) 

Definition at line 372 of file enum.c.

References BackwardScanDirection, enum_endpoint(), ereport, errcode(), errmsg(), ERROR, format_type_be(), get_fn_expr_argtype(), InvalidOid, OidIsValid, and PG_RETURN_OID.

{
    Oid         enumtypoid;
    Oid         max;

    /*
     * We rely on being able to get the specific enum type from the calling
     * expression tree.  Notice that the actual value of the argument isn't
     * examined at all; in particular it might be NULL.
     */
    enumtypoid = get_fn_expr_argtype(fcinfo->flinfo, 0);
    if (enumtypoid == InvalidOid)
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("could not determine actual enum type")));

    /* Get the OID using the index */
    max = enum_endpoint(enumtypoid, BackwardScanDirection);

    if (!OidIsValid(max))
        ereport(ERROR,
                (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                 errmsg("enum %s contains no values",
                        format_type_be(enumtypoid))));

    PG_RETURN_OID(max);
}

Datum enum_le ( PG_FUNCTION_ARGS   ) 

Definition at line 222 of file enum.c.

References enum_cmp_internal(), PG_GETARG_OID, and PG_RETURN_BOOL.

{
    Oid         a = PG_GETARG_OID(0);
    Oid         b = PG_GETARG_OID(1);

    PG_RETURN_BOOL(enum_cmp_internal(a, b, fcinfo) <= 0);
}

Datum enum_lt ( PG_FUNCTION_ARGS   ) 

Definition at line 213 of file enum.c.

References enum_cmp_internal(), PG_GETARG_OID, and PG_RETURN_BOOL.

{
    Oid         a = PG_GETARG_OID(0);
    Oid         b = PG_GETARG_OID(1);

    PG_RETURN_BOOL(enum_cmp_internal(a, b, fcinfo) < 0);
}

Datum enum_ne ( PG_FUNCTION_ARGS   ) 

Definition at line 240 of file enum.c.

References PG_GETARG_OID, and PG_RETURN_BOOL.

{
    Oid         a = PG_GETARG_OID(0);
    Oid         b = PG_GETARG_OID(1);

    PG_RETURN_BOOL(a != b);
}

Datum enum_out ( PG_FUNCTION_ARGS   ) 

Definition at line 74 of file enum.c.

References ENUMOID, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, HeapTupleIsValid, NameStr, ObjectIdGetDatum, PG_GETARG_OID, PG_RETURN_CSTRING, pstrdup(), ReleaseSysCache(), and SearchSysCache1.

Referenced by anyenum_out().

{
    Oid         enumval = PG_GETARG_OID(0);
    char       *result;
    HeapTuple   tup;
    Form_pg_enum en;

    tup = SearchSysCache1(ENUMOID, ObjectIdGetDatum(enumval));
    if (!HeapTupleIsValid(tup))
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
                 errmsg("invalid internal value for enum: %u",
                        enumval)));
    en = (Form_pg_enum) GETSTRUCT(tup);

    result = pstrdup(NameStr(en->enumlabel));

    ReleaseSysCache(tup);

    PG_RETURN_CSTRING(result);
}

Datum enum_range_all ( PG_FUNCTION_ARGS   ) 

Definition at line 433 of file enum.c.

References enum_range_internal(), ereport, errcode(), errmsg(), ERROR, get_fn_expr_argtype(), InvalidOid, and PG_RETURN_ARRAYTYPE_P.

{
    Oid         enumtypoid;

    /*
     * We rely on being able to get the specific enum type from the calling
     * expression tree.  Notice that the actual value of the argument isn't
     * examined at all; in particular it might be NULL.
     */
    enumtypoid = get_fn_expr_argtype(fcinfo->flinfo, 0);
    if (enumtypoid == InvalidOid)
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("could not determine actual enum type")));

    PG_RETURN_ARRAYTYPE_P(enum_range_internal(enumtypoid,
                                              InvalidOid, InvalidOid));
}

Datum enum_range_bounds ( PG_FUNCTION_ARGS   ) 

Definition at line 402 of file enum.c.

References enum_range_internal(), ereport, errcode(), errmsg(), ERROR, get_fn_expr_argtype(), InvalidOid, PG_ARGISNULL, PG_GETARG_OID, and PG_RETURN_ARRAYTYPE_P.

{
    Oid         lower;
    Oid         upper;
    Oid         enumtypoid;

    if (PG_ARGISNULL(0))
        lower = InvalidOid;
    else
        lower = PG_GETARG_OID(0);
    if (PG_ARGISNULL(1))
        upper = InvalidOid;
    else
        upper = PG_GETARG_OID(1);

    /*
     * We rely on being able to get the specific enum type from the calling
     * expression tree.  The generic type mechanism should have ensured that
     * both are of the same type.
     */
    enumtypoid = get_fn_expr_argtype(fcinfo->flinfo, 0);
    if (enumtypoid == InvalidOid)
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("could not determine actual enum type")));

    PG_RETURN_ARRAYTYPE_P(enum_range_internal(enumtypoid, lower, upper));
}

Datum enum_recv ( PG_FUNCTION_ARGS   ) 

Definition at line 98 of file enum.c.

References buf, CStringGetDatum, StringInfoData::cursor, ENUMTYPOIDNAME, ereport, errcode(), errmsg(), ERROR, format_type_be(), HeapTupleGetOid, HeapTupleIsValid, StringInfoData::len, name, NAMEDATALEN, ObjectIdGetDatum, pfree(), PG_GETARG_OID, PG_GETARG_POINTER, PG_RETURN_OID, pq_getmsgtext(), ReleaseSysCache(), and SearchSysCache2.

{
    StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
    Oid         enumtypoid = PG_GETARG_OID(1);
    Oid         enumoid;
    HeapTuple   tup;
    char       *name;
    int         nbytes;

    name = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);

    /* must check length to prevent Assert failure within SearchSysCache */
    if (strlen(name) >= NAMEDATALEN)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                 errmsg("invalid input value for enum %s: \"%s\"",
                        format_type_be(enumtypoid),
                        name)));

    tup = SearchSysCache2(ENUMTYPOIDNAME,
                          ObjectIdGetDatum(enumtypoid),
                          CStringGetDatum(name));
    if (!HeapTupleIsValid(tup))
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                 errmsg("invalid input value for enum %s: \"%s\"",
                        format_type_be(enumtypoid),
                        name)));

    enumoid = HeapTupleGetOid(tup);

    ReleaseSysCache(tup);

    pfree(name);

    PG_RETURN_OID(enumoid);
}

Datum enum_send ( PG_FUNCTION_ARGS   ) 

Definition at line 137 of file enum.c.

References buf, ENUMOID, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, HeapTupleIsValid, NameStr, ObjectIdGetDatum, PG_GETARG_OID, PG_RETURN_BYTEA_P, pq_begintypsend(), pq_endtypsend(), pq_sendtext(), ReleaseSysCache(), and SearchSysCache1.

{
    Oid         enumval = PG_GETARG_OID(0);
    StringInfoData buf;
    HeapTuple   tup;
    Form_pg_enum en;

    tup = SearchSysCache1(ENUMOID, ObjectIdGetDatum(enumval));
    if (!HeapTupleIsValid(tup))
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
                 errmsg("invalid internal value for enum: %u",
                        enumval)));
    en = (Form_pg_enum) GETSTRUCT(tup);

    pq_begintypsend(&buf);
    pq_sendtext(&buf, NameStr(en->enumlabel), strlen(NameStr(en->enumlabel)));

    ReleaseSysCache(tup);

    PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
}

Datum enum_smaller ( PG_FUNCTION_ARGS   ) 

Definition at line 267 of file enum.c.

References enum_cmp_internal(), PG_GETARG_OID, and PG_RETURN_OID.

{
    Oid         a = PG_GETARG_OID(0);
    Oid         b = PG_GETARG_OID(1);

    PG_RETURN_OID(enum_cmp_internal(a, b, fcinfo) < 0 ? a : b);
}

int errdatatype ( Oid  datatypeOid  ) 

Definition at line 355 of file domains.c.

References elog, err_generic_string(), ERROR, get_namespace_name(), GETSTRUCT, HeapTupleIsValid, NameStr, ObjectIdGetDatum, PG_DIAG_DATATYPE_NAME, PG_DIAG_SCHEMA_NAME, ReleaseSysCache(), SearchSysCache1, and TYPEOID.

Referenced by domain_check_input(), errdomainconstraint(), and ExecEvalCoerceToDomain().

{
    HeapTuple   tup;
    Form_pg_type typtup;

    tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(datatypeOid));
    if (!HeapTupleIsValid(tup))
        elog(ERROR, "cache lookup failed for type %u", datatypeOid);
    typtup = (Form_pg_type) GETSTRUCT(tup);

    err_generic_string(PG_DIAG_SCHEMA_NAME,
                       get_namespace_name(typtup->typnamespace));
    err_generic_string(PG_DIAG_DATATYPE_NAME, NameStr(typtup->typname));

    ReleaseSysCache(tup);

    return 0;                   /* return value does not matter */
}

int errdomainconstraint ( Oid  datatypeOid,
const char *  conname 
)

Definition at line 379 of file domains.c.

References err_generic_string(), errdatatype(), and PG_DIAG_CONSTRAINT_NAME.

Referenced by domain_check_input(), and ExecEvalCoerceToDomain().

{
    errdatatype(datatypeOid);
    err_generic_string(PG_DIAG_CONSTRAINT_NAME, conname);

    return 0;                   /* return value does not matter */
}

Datum event_trigger_in ( PG_FUNCTION_ARGS   ) 

Definition at line 299 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot accept a value of type event_trigger")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum event_trigger_out ( PG_FUNCTION_ARGS   ) 

Definition at line 312 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot display a value of type event_trigger")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum fdw_handler_in ( PG_FUNCTION_ARGS   ) 

Definition at line 353 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot accept a value of type fdw_handler")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum fdw_handler_out ( PG_FUNCTION_ARGS   ) 

Definition at line 366 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot display a value of type fdw_handler")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum float48div ( PG_FUNCTION_ARGS   ) 

Definition at line 2522 of file float.c.

References CHECKFLOATVAL, ereport, errcode(), errmsg(), ERROR, isinf(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float4      arg1 = PG_GETARG_FLOAT4(0);
    float8      arg2 = PG_GETARG_FLOAT8(1);
    float8      result;

    if (arg2 == 0.0)
        ereport(ERROR,
                (errcode(ERRCODE_DIVISION_BY_ZERO),
                 errmsg("division by zero")));

    result = arg1 / arg2;
    CHECKFLOATVAL(result, isinf(arg1) || isinf(arg2), arg1 == 0);
    PG_RETURN_FLOAT8(result);
}

Datum float48eq ( PG_FUNCTION_ARGS   ) 

Definition at line 2612 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_BOOL.

Datum float48ge ( PG_FUNCTION_ARGS   ) 

Definition at line 2657 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_BOOL.

Datum float48gt ( PG_FUNCTION_ARGS   ) 

Definition at line 2648 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_BOOL.

Datum float48le ( PG_FUNCTION_ARGS   ) 

Definition at line 2639 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_BOOL.

Datum float48lt ( PG_FUNCTION_ARGS   ) 

Definition at line 2630 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_BOOL.

Datum float48mi ( PG_FUNCTION_ARGS   ) 

Definition at line 2497 of file float.c.

References CHECKFLOATVAL, isinf(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float4      arg1 = PG_GETARG_FLOAT4(0);
    float8      arg2 = PG_GETARG_FLOAT8(1);
    float8      result;

    result = arg1 - arg2;
    CHECKFLOATVAL(result, isinf(arg1) || isinf(arg2), true);
    PG_RETURN_FLOAT8(result);
}

Datum float48mul ( PG_FUNCTION_ARGS   ) 

Definition at line 2509 of file float.c.

References CHECKFLOATVAL, isinf(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float4      arg1 = PG_GETARG_FLOAT4(0);
    float8      arg2 = PG_GETARG_FLOAT8(1);
    float8      result;

    result = arg1 * arg2;
    CHECKFLOATVAL(result, isinf(arg1) || isinf(arg2),
                  arg1 == 0 || arg2 == 0);
    PG_RETURN_FLOAT8(result);
}

Datum float48ne ( PG_FUNCTION_ARGS   ) 

Definition at line 2621 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_BOOL.

Datum float48pl ( PG_FUNCTION_ARGS   ) 

Definition at line 2485 of file float.c.

References CHECKFLOATVAL, isinf(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float4      arg1 = PG_GETARG_FLOAT4(0);
    float8      arg2 = PG_GETARG_FLOAT8(1);
    float8      result;

    result = arg1 + arg2;
    CHECKFLOATVAL(result, isinf(arg1) || isinf(arg2), true);
    PG_RETURN_FLOAT8(result);
}

Datum float4_accum ( PG_FUNCTION_ARGS   ) 

Definition at line 1860 of file float.c.

References AggCheckCallContext(), check_float8_array(), CHECKFLOATVAL, construct_array(), Float8GetDatumFast, FLOAT8OID, isinf(), NULL, PG_GETARG_ARRAYTYPE_P, PG_GETARG_FLOAT4, and PG_RETURN_ARRAYTYPE_P.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);

    /* do computations as float8 */
    float8      newval = PG_GETARG_FLOAT4(1);
    float8     *transvalues;
    float8      N,
                sumX,
                sumX2;

    transvalues = check_float8_array(transarray, "float4_accum", 3);
    N = transvalues[0];
    sumX = transvalues[1];
    sumX2 = transvalues[2];

    N += 1.0;
    sumX += newval;
    CHECKFLOATVAL(sumX, isinf(transvalues[1]) || isinf(newval), true);
    sumX2 += newval * newval;
    CHECKFLOATVAL(sumX2, isinf(transvalues[2]) || isinf(newval), true);

    /*
     * If we're invoked as an aggregate, we can cheat and modify our first
     * parameter in-place to reduce palloc overhead. Otherwise we construct a
     * new array with the updated transition data and return it.
     */
    if (AggCheckCallContext(fcinfo, NULL))
    {
        transvalues[0] = N;
        transvalues[1] = sumX;
        transvalues[2] = sumX2;

        PG_RETURN_ARRAYTYPE_P(transarray);
    }
    else
    {
        Datum       transdatums[3];
        ArrayType  *result;

        transdatums[0] = Float8GetDatumFast(N);
        transdatums[1] = Float8GetDatumFast(sumX);
        transdatums[2] = Float8GetDatumFast(sumX2);

        result = construct_array(transdatums, 3,
                                 FLOAT8OID,
                                 sizeof(float8), FLOAT8PASSBYVAL, 'd');

        PG_RETURN_ARRAYTYPE_P(result);
    }
}

Datum float4_numeric ( PG_FUNCTION_ARGS   ) 

Definition at line 2417 of file numeric.c.

References buf, free_var(), init_var, make_result(), PG_GETARG_FLOAT4, PG_RETURN_NUMERIC, set_var_from_str(), and val.

{
    float4      val = PG_GETARG_FLOAT4(0);
    Numeric     res;
    NumericVar  result;
    char        buf[FLT_DIG + 100];

    if (isnan(val))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    sprintf(buf, "%.*g", FLT_DIG, val);

    init_var(&result);

    /* Assume we need not worry about leading/trailing spaces */
    (void) set_var_from_str(buf, buf, &result);

    res = make_result(&result);

    free_var(&result);

    PG_RETURN_NUMERIC(res);
}

Datum float4abs ( PG_FUNCTION_ARGS   ) 

Definition at line 598 of file float.c.

References PG_GETARG_FLOAT4, and PG_RETURN_FLOAT4.

{
    float4      arg1 = PG_GETARG_FLOAT4(0);

    PG_RETURN_FLOAT4((float4) fabs(arg1));
}

Datum float4div ( PG_FUNCTION_ARGS   ) 

Definition at line 780 of file float.c.

References CHECKFLOATVAL, ereport, errcode(), errmsg(), ERROR, isinf(), PG_GETARG_FLOAT4, and PG_RETURN_FLOAT4.

{
    float4      arg1 = PG_GETARG_FLOAT4(0);
    float4      arg2 = PG_GETARG_FLOAT4(1);
    float4      result;

    if (arg2 == 0.0)
        ereport(ERROR,
                (errcode(ERRCODE_DIVISION_BY_ZERO),
                 errmsg("division by zero")));

    result = arg1 / arg2;

    CHECKFLOATVAL(result, isinf(arg1) || isinf(arg2), arg1 == 0);
    PG_RETURN_FLOAT4(result);
}

Datum float4eq ( PG_FUNCTION_ARGS   ) 

Definition at line 902 of file float.c.

References float4_cmp_internal(), PG_GETARG_FLOAT4, and PG_RETURN_BOOL.

Datum float4ge ( PG_FUNCTION_ARGS   ) 

Definition at line 947 of file float.c.

References float4_cmp_internal(), PG_GETARG_FLOAT4, and PG_RETURN_BOOL.

Datum float4gt ( PG_FUNCTION_ARGS   ) 

Definition at line 938 of file float.c.

References float4_cmp_internal(), PG_GETARG_FLOAT4, and PG_RETURN_BOOL.

Datum float4in ( PG_FUNCTION_ARGS   ) 

Definition at line 186 of file float.c.

References CHECKFLOATVAL, ereport, errcode(), errmsg(), ERROR, get_float4_infinity(), get_float4_nan(), isinf(), PG_GETARG_CSTRING, PG_RETURN_FLOAT4, pg_strncasecmp(), and val.

Referenced by numeric_float4().

{
    char       *num = PG_GETARG_CSTRING(0);
    char       *orig_num;
    double      val;
    char       *endptr;

    /*
     * endptr points to the first character _after_ the sequence we recognized
     * as a valid floating point number. orig_num points to the original input
     * string.
     */
    orig_num = num;

    /*
     * Check for an empty-string input to begin with, to avoid the vagaries of
     * strtod() on different platforms.
     */
    if (*num == '\0')
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                 errmsg("invalid input syntax for type real: \"%s\"",
                        orig_num)));

    /* skip leading whitespace */
    while (*num != '\0' && isspace((unsigned char) *num))
        num++;

    errno = 0;
    val = strtod(num, &endptr);

    /* did we not see anything that looks like a double? */
    if (endptr == num || errno != 0)
    {
        int         save_errno = errno;

        /*
         * C99 requires that strtod() accept NaN and [-]Infinity, but not all
         * platforms support that yet (and some accept them but set ERANGE
         * anyway...)  Therefore, we check for these inputs ourselves.
         */
        if (pg_strncasecmp(num, "NaN", 3) == 0)
        {
            val = get_float4_nan();
            endptr = num + 3;
        }
        else if (pg_strncasecmp(num, "Infinity", 8) == 0)
        {
            val = get_float4_infinity();
            endptr = num + 8;
        }
        else if (pg_strncasecmp(num, "-Infinity", 9) == 0)
        {
            val = -get_float4_infinity();
            endptr = num + 9;
        }
        else if (save_errno == ERANGE)
        {
            /*
             * Some platforms return ERANGE for denormalized numbers (those
             * that are not zero, but are too close to zero to have full
             * precision).  We'd prefer not to throw error for that, so try to
             * detect whether it's a "real" out-of-range condition by checking
             * to see if the result is zero or huge.
             */
            if (val == 0.0 || val >= HUGE_VAL || val <= -HUGE_VAL)
                ereport(ERROR,
                        (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                         errmsg("\"%s\" is out of range for type real",
                                orig_num)));
        }
        else
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                     errmsg("invalid input syntax for type real: \"%s\"",
                            orig_num)));
    }
#ifdef HAVE_BUGGY_SOLARIS_STRTOD
    else
    {
        /*
         * Many versions of Solaris have a bug wherein strtod sets endptr to
         * point one byte beyond the end of the string when given "inf" or
         * "infinity".
         */
        if (endptr != num && endptr[-1] == '\0')
            endptr--;
    }
#endif   /* HAVE_BUGGY_SOLARIS_STRTOD */

#ifdef HAVE_BUGGY_IRIX_STRTOD

    /*
     * In some IRIX versions, strtod() recognizes only "inf", so if the input
     * is "infinity" we have to skip over "inity".  Also, it may return
     * positive infinity for "-inf".
     */
    if (isinf(val))
    {
        if (pg_strncasecmp(num, "Infinity", 8) == 0)
        {
            val = get_float4_infinity();
            endptr = num + 8;
        }
        else if (pg_strncasecmp(num, "-Infinity", 9) == 0)
        {
            val = -get_float4_infinity();
            endptr = num + 9;
        }
        else if (pg_strncasecmp(num, "-inf", 4) == 0)
        {
            val = -get_float4_infinity();
            endptr = num + 4;
        }
    }
#endif   /* HAVE_BUGGY_IRIX_STRTOD */

    /* skip trailing whitespace */
    while (*endptr != '\0' && isspace((unsigned char) *endptr))
        endptr++;

    /* if there is any junk left at the end of the string, bail out */
    if (*endptr != '\0')
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                 errmsg("invalid input syntax for type real: \"%s\"",
                        orig_num)));

    /*
     * if we get here, we have a legal double, still need to check to see if
     * it's a legal float4
     */
    CHECKFLOATVAL((float4) val, isinf(val), val == 0);

    PG_RETURN_FLOAT4((float4) val);
}

Datum float4larger ( PG_FUNCTION_ARGS   ) 

Definition at line 627 of file float.c.

References float4_cmp_internal(), PG_GETARG_FLOAT4, and PG_RETURN_FLOAT4.

{
    float4      arg1 = PG_GETARG_FLOAT4(0);
    float4      arg2 = PG_GETARG_FLOAT4(1);
    float4      result;

    if (float4_cmp_internal(arg1, arg2) > 0)
        result = arg1;
    else
        result = arg2;
    PG_RETURN_FLOAT4(result);
}

Datum float4le ( PG_FUNCTION_ARGS   ) 

Definition at line 929 of file float.c.

References float4_cmp_internal(), PG_GETARG_FLOAT4, and PG_RETURN_BOOL.

Datum float4lt ( PG_FUNCTION_ARGS   ) 

Definition at line 920 of file float.c.

References float4_cmp_internal(), PG_GETARG_FLOAT4, and PG_RETURN_BOOL.

Datum float4mi ( PG_FUNCTION_ARGS   ) 

Definition at line 755 of file float.c.

References CHECKFLOATVAL, isinf(), PG_GETARG_FLOAT4, and PG_RETURN_FLOAT4.

{
    float4      arg1 = PG_GETARG_FLOAT4(0);
    float4      arg2 = PG_GETARG_FLOAT4(1);
    float4      result;

    result = arg1 - arg2;
    CHECKFLOATVAL(result, isinf(arg1) || isinf(arg2), true);
    PG_RETURN_FLOAT4(result);
}

Datum float4mul ( PG_FUNCTION_ARGS   ) 

Definition at line 767 of file float.c.

References CHECKFLOATVAL, isinf(), PG_GETARG_FLOAT4, and PG_RETURN_FLOAT4.

{
    float4      arg1 = PG_GETARG_FLOAT4(0);
    float4      arg2 = PG_GETARG_FLOAT4(1);
    float4      result;

    result = arg1 * arg2;
    CHECKFLOATVAL(result, isinf(arg1) || isinf(arg2),
                  arg1 == 0 || arg2 == 0);
    PG_RETURN_FLOAT4(result);
}

Datum float4ne ( PG_FUNCTION_ARGS   ) 

Definition at line 911 of file float.c.

References float4_cmp_internal(), PG_GETARG_FLOAT4, and PG_RETURN_BOOL.

Datum float4out ( PG_FUNCTION_ARGS   ) 

Definition at line 328 of file float.c.

References ascii(), extra_float_digits, is_infinite(), MAXFLOATWIDTH, palloc(), PG_GETARG_FLOAT4, PG_RETURN_CSTRING, and snprintf().

{
    float4      num = PG_GETARG_FLOAT4(0);
    char       *ascii = (char *) palloc(MAXFLOATWIDTH + 1);

    if (isnan(num))
        PG_RETURN_CSTRING(strcpy(ascii, "NaN"));

    switch (is_infinite(num))
    {
        case 1:
            strcpy(ascii, "Infinity");
            break;
        case -1:
            strcpy(ascii, "-Infinity");
            break;
        default:
            {
                int         ndig = FLT_DIG + extra_float_digits;

                if (ndig < 1)
                    ndig = 1;

                snprintf(ascii, MAXFLOATWIDTH + 1, "%.*g", ndig, num);
            }
    }

    PG_RETURN_CSTRING(ascii);
}

Datum float4pl ( PG_FUNCTION_ARGS   ) 

Definition at line 735 of file float.c.

References CHECKFLOATVAL, isinf(), PG_GETARG_FLOAT4, and PG_RETURN_FLOAT4.

{
    float4      arg1 = PG_GETARG_FLOAT4(0);
    float4      arg2 = PG_GETARG_FLOAT4(1);
    float4      result;

    result = arg1 + arg2;

    /*
     * There isn't any way to check for underflow of addition/subtraction
     * because numbers near the underflow value have already been rounded to
     * the point where we can't detect that the two values were originally
     * different, e.g. on x86, '1e-45'::float4 == '2e-45'::float4 ==
     * 1.4013e-45.
     */
    CHECKFLOATVAL(result, isinf(arg1) || isinf(arg2), true);
    PG_RETURN_FLOAT4(result);
}

Datum float4recv ( PG_FUNCTION_ARGS   ) 
Datum float4send ( PG_FUNCTION_ARGS   ) 
Datum float4smaller ( PG_FUNCTION_ARGS   ) 

Definition at line 641 of file float.c.

References float4_cmp_internal(), PG_GETARG_FLOAT4, and PG_RETURN_FLOAT4.

{
    float4      arg1 = PG_GETARG_FLOAT4(0);
    float4      arg2 = PG_GETARG_FLOAT4(1);
    float4      result;

    if (float4_cmp_internal(arg1, arg2) < 0)
        result = arg1;
    else
        result = arg2;
    PG_RETURN_FLOAT4(result);
}

Datum float4um ( PG_FUNCTION_ARGS   ) 

Definition at line 609 of file float.c.

References PG_GETARG_FLOAT4, and PG_RETURN_FLOAT4.

{
    float4      arg1 = PG_GETARG_FLOAT4(0);
    float4      result;

    result = -arg1;
    PG_RETURN_FLOAT4(result);
}

Datum float4up ( PG_FUNCTION_ARGS   ) 

Definition at line 619 of file float.c.

References arg, PG_GETARG_FLOAT4, and PG_RETURN_FLOAT4.

Datum float84div ( PG_FUNCTION_ARGS   ) 

Definition at line 2585 of file float.c.

References CHECKFLOATVAL, ereport, errcode(), errmsg(), ERROR, isinf(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float4      arg2 = PG_GETARG_FLOAT4(1);
    float8      result;

    if (arg2 == 0.0)
        ereport(ERROR,
                (errcode(ERRCODE_DIVISION_BY_ZERO),
                 errmsg("division by zero")));

    result = arg1 / arg2;

    CHECKFLOATVAL(result, isinf(arg1) || isinf(arg2), arg1 == 0);
    PG_RETURN_FLOAT8(result);
}

Datum float84eq ( PG_FUNCTION_ARGS   ) 

Definition at line 2669 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_BOOL.

Datum float84ge ( PG_FUNCTION_ARGS   ) 

Definition at line 2714 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_BOOL.

Datum float84gt ( PG_FUNCTION_ARGS   ) 

Definition at line 2705 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_BOOL.

Datum float84le ( PG_FUNCTION_ARGS   ) 

Definition at line 2696 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_BOOL.

Datum float84lt ( PG_FUNCTION_ARGS   ) 

Definition at line 2687 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_BOOL.

Datum float84mi ( PG_FUNCTION_ARGS   ) 

Definition at line 2558 of file float.c.

References CHECKFLOATVAL, isinf(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float4      arg2 = PG_GETARG_FLOAT4(1);
    float8      result;

    result = arg1 - arg2;

    CHECKFLOATVAL(result, isinf(arg1) || isinf(arg2), true);
    PG_RETURN_FLOAT8(result);
}

Datum float84mul ( PG_FUNCTION_ARGS   ) 

Definition at line 2571 of file float.c.

References CHECKFLOATVAL, isinf(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float4      arg2 = PG_GETARG_FLOAT4(1);
    float8      result;

    result = arg1 * arg2;

    CHECKFLOATVAL(result, isinf(arg1) || isinf(arg2),
                  arg1 == 0 || arg2 == 0);
    PG_RETURN_FLOAT8(result);
}

Datum float84ne ( PG_FUNCTION_ARGS   ) 

Definition at line 2678 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_BOOL.

Datum float84pl ( PG_FUNCTION_ARGS   ) 

Definition at line 2545 of file float.c.

References CHECKFLOATVAL, isinf(), PG_GETARG_FLOAT4, PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float4      arg2 = PG_GETARG_FLOAT4(1);
    float8      result;

    result = arg1 + arg2;

    CHECKFLOATVAL(result, isinf(arg1) || isinf(arg2), true);
    PG_RETURN_FLOAT8(result);
}

Datum float8_accum ( PG_FUNCTION_ARGS   ) 

Definition at line 1809 of file float.c.

References AggCheckCallContext(), check_float8_array(), CHECKFLOATVAL, construct_array(), Float8GetDatumFast, FLOAT8OID, isinf(), NULL, PG_GETARG_ARRAYTYPE_P, PG_GETARG_FLOAT8, and PG_RETURN_ARRAYTYPE_P.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    float8      newval = PG_GETARG_FLOAT8(1);
    float8     *transvalues;
    float8      N,
                sumX,
                sumX2;

    transvalues = check_float8_array(transarray, "float8_accum", 3);
    N = transvalues[0];
    sumX = transvalues[1];
    sumX2 = transvalues[2];

    N += 1.0;
    sumX += newval;
    CHECKFLOATVAL(sumX, isinf(transvalues[1]) || isinf(newval), true);
    sumX2 += newval * newval;
    CHECKFLOATVAL(sumX2, isinf(transvalues[2]) || isinf(newval), true);

    /*
     * If we're invoked as an aggregate, we can cheat and modify our first
     * parameter in-place to reduce palloc overhead. Otherwise we construct a
     * new array with the updated transition data and return it.
     */
    if (AggCheckCallContext(fcinfo, NULL))
    {
        transvalues[0] = N;
        transvalues[1] = sumX;
        transvalues[2] = sumX2;

        PG_RETURN_ARRAYTYPE_P(transarray);
    }
    else
    {
        Datum       transdatums[3];
        ArrayType  *result;

        transdatums[0] = Float8GetDatumFast(N);
        transdatums[1] = Float8GetDatumFast(sumX);
        transdatums[2] = Float8GetDatumFast(sumX2);

        result = construct_array(transdatums, 3,
                                 FLOAT8OID,
                                 sizeof(float8), FLOAT8PASSBYVAL, 'd');

        PG_RETURN_ARRAYTYPE_P(result);
    }
}

Datum float8_avg ( PG_FUNCTION_ARGS   ) 

Definition at line 1913 of file float.c.

References check_float8_array(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_FLOAT8, and PG_RETURN_NULL.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    float8     *transvalues;
    float8      N,
                sumX;

    transvalues = check_float8_array(transarray, "float8_avg", 3);
    N = transvalues[0];
    sumX = transvalues[1];
    /* ignore sumX2 */

    /* SQL defines AVG of no values to be NULL */
    if (N == 0.0)
        PG_RETURN_NULL();

    PG_RETURN_FLOAT8(sumX / N);
}

Datum float8_corr ( PG_FUNCTION_ARGS   ) 

Definition at line 2318 of file float.c.

References check_float8_array(), CHECKFLOATVAL, isinf(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_FLOAT8, and PG_RETURN_NULL.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    float8     *transvalues;
    float8      N,
                sumX,
                sumX2,
                sumY,
                sumY2,
                sumXY,
                numeratorX,
                numeratorY,
                numeratorXY;

    transvalues = check_float8_array(transarray, "float8_corr", 6);
    N = transvalues[0];
    sumX = transvalues[1];
    sumX2 = transvalues[2];
    sumY = transvalues[3];
    sumY2 = transvalues[4];
    sumXY = transvalues[5];

    /* if N is 0 we should return NULL */
    if (N < 1.0)
        PG_RETURN_NULL();

    numeratorX = N * sumX2 - sumX * sumX;
    CHECKFLOATVAL(numeratorX, isinf(sumX2) || isinf(sumX), true);
    numeratorY = N * sumY2 - sumY * sumY;
    CHECKFLOATVAL(numeratorY, isinf(sumY2) || isinf(sumY), true);
    numeratorXY = N * sumXY - sumX * sumY;
    CHECKFLOATVAL(numeratorXY, isinf(sumXY) || isinf(sumX) ||
                  isinf(sumY), true);
    if (numeratorX <= 0 || numeratorY <= 0)
        PG_RETURN_NULL();

    PG_RETURN_FLOAT8(numeratorXY / sqrt(numeratorX * numeratorY));
}

Datum float8_covar_pop ( PG_FUNCTION_ARGS   ) 

Definition at line 2262 of file float.c.

References check_float8_array(), CHECKFLOATVAL, isinf(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_FLOAT8, and PG_RETURN_NULL.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    float8     *transvalues;
    float8      N,
                sumX,
                sumY,
                sumXY,
                numerator;

    transvalues = check_float8_array(transarray, "float8_covar_pop", 6);
    N = transvalues[0];
    sumX = transvalues[1];
    sumY = transvalues[3];
    sumXY = transvalues[5];

    /* if N is 0 we should return NULL */
    if (N < 1.0)
        PG_RETURN_NULL();

    numerator = N * sumXY - sumX * sumY;
    CHECKFLOATVAL(numerator, isinf(sumXY) || isinf(sumX) ||
                  isinf(sumY), true);

    PG_RETURN_FLOAT8(numerator / (N * N));
}

Datum float8_covar_samp ( PG_FUNCTION_ARGS   ) 

Definition at line 2290 of file float.c.

References check_float8_array(), CHECKFLOATVAL, isinf(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_FLOAT8, and PG_RETURN_NULL.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    float8     *transvalues;
    float8      N,
                sumX,
                sumY,
                sumXY,
                numerator;

    transvalues = check_float8_array(transarray, "float8_covar_samp", 6);
    N = transvalues[0];
    sumX = transvalues[1];
    sumY = transvalues[3];
    sumXY = transvalues[5];

    /* if N is <= 1 we should return NULL */
    if (N < 2.0)
        PG_RETURN_NULL();

    numerator = N * sumXY - sumX * sumY;
    CHECKFLOATVAL(numerator, isinf(sumXY) || isinf(sumX) ||
                  isinf(sumY), true);

    PG_RETURN_FLOAT8(numerator / (N * (N - 1.0)));
}

Datum float8_numeric ( PG_FUNCTION_ARGS   ) 

Definition at line 2355 of file numeric.c.

References buf, free_var(), init_var, make_result(), PG_GETARG_FLOAT8, PG_RETURN_NUMERIC, set_var_from_str(), and val.

{
    float8      val = PG_GETARG_FLOAT8(0);
    Numeric     res;
    NumericVar  result;
    char        buf[DBL_DIG + 100];

    if (isnan(val))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    sprintf(buf, "%.*g", DBL_DIG, val);

    init_var(&result);

    /* Assume we need not worry about leading/trailing spaces */
    (void) set_var_from_str(buf, buf, &result);

    res = make_result(&result);

    free_var(&result);

    PG_RETURN_NUMERIC(res);
}

Datum float8_regr_accum ( PG_FUNCTION_ARGS   ) 

Definition at line 2065 of file float.c.

References AggCheckCallContext(), check_float8_array(), CHECKFLOATVAL, construct_array(), Float8GetDatumFast, FLOAT8OID, isinf(), NULL, PG_GETARG_ARRAYTYPE_P, PG_GETARG_FLOAT8, and PG_RETURN_ARRAYTYPE_P.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    float8      newvalY = PG_GETARG_FLOAT8(1);
    float8      newvalX = PG_GETARG_FLOAT8(2);
    float8     *transvalues;
    float8      N,
                sumX,
                sumX2,
                sumY,
                sumY2,
                sumXY;

    transvalues = check_float8_array(transarray, "float8_regr_accum", 6);
    N = transvalues[0];
    sumX = transvalues[1];
    sumX2 = transvalues[2];
    sumY = transvalues[3];
    sumY2 = transvalues[4];
    sumXY = transvalues[5];

    N += 1.0;
    sumX += newvalX;
    CHECKFLOATVAL(sumX, isinf(transvalues[1]) || isinf(newvalX), true);
    sumX2 += newvalX * newvalX;
    CHECKFLOATVAL(sumX2, isinf(transvalues[2]) || isinf(newvalX), true);
    sumY += newvalY;
    CHECKFLOATVAL(sumY, isinf(transvalues[3]) || isinf(newvalY), true);
    sumY2 += newvalY * newvalY;
    CHECKFLOATVAL(sumY2, isinf(transvalues[4]) || isinf(newvalY), true);
    sumXY += newvalX * newvalY;
    CHECKFLOATVAL(sumXY, isinf(transvalues[5]) || isinf(newvalX) ||
                  isinf(newvalY), true);

    /*
     * If we're invoked as an aggregate, we can cheat and modify our first
     * parameter in-place to reduce palloc overhead. Otherwise we construct a
     * new array with the updated transition data and return it.
     */
    if (AggCheckCallContext(fcinfo, NULL))
    {
        transvalues[0] = N;
        transvalues[1] = sumX;
        transvalues[2] = sumX2;
        transvalues[3] = sumY;
        transvalues[4] = sumY2;
        transvalues[5] = sumXY;

        PG_RETURN_ARRAYTYPE_P(transarray);
    }
    else
    {
        Datum       transdatums[6];
        ArrayType  *result;

        transdatums[0] = Float8GetDatumFast(N);
        transdatums[1] = Float8GetDatumFast(sumX);
        transdatums[2] = Float8GetDatumFast(sumX2);
        transdatums[3] = Float8GetDatumFast(sumY);
        transdatums[4] = Float8GetDatumFast(sumY2);
        transdatums[5] = Float8GetDatumFast(sumXY);

        result = construct_array(transdatums, 6,
                                 FLOAT8OID,
                                 sizeof(float8), FLOAT8PASSBYVAL, 'd');

        PG_RETURN_ARRAYTYPE_P(result);
    }
}

Datum float8_regr_avgx ( PG_FUNCTION_ARGS   ) 

Definition at line 2224 of file float.c.

References check_float8_array(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_FLOAT8, and PG_RETURN_NULL.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    float8     *transvalues;
    float8      N,
                sumX;

    transvalues = check_float8_array(transarray, "float8_regr_avgx", 6);
    N = transvalues[0];
    sumX = transvalues[1];

    /* if N is 0 we should return NULL */
    if (N < 1.0)
        PG_RETURN_NULL();

    PG_RETURN_FLOAT8(sumX / N);
}

Datum float8_regr_avgy ( PG_FUNCTION_ARGS   ) 

Definition at line 2243 of file float.c.

References check_float8_array(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_FLOAT8, and PG_RETURN_NULL.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    float8     *transvalues;
    float8      N,
                sumY;

    transvalues = check_float8_array(transarray, "float8_regr_avgy", 6);
    N = transvalues[0];
    sumY = transvalues[3];

    /* if N is 0 we should return NULL */
    if (N < 1.0)
        PG_RETURN_NULL();

    PG_RETURN_FLOAT8(sumY / N);
}

Datum float8_regr_intercept ( PG_FUNCTION_ARGS   ) 

Definition at line 2437 of file float.c.

References check_float8_array(), CHECKFLOATVAL, isinf(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_FLOAT8, and PG_RETURN_NULL.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    float8     *transvalues;
    float8      N,
                sumX,
                sumX2,
                sumY,
                sumXY,
                numeratorX,
                numeratorXXY;

    transvalues = check_float8_array(transarray, "float8_regr_intercept", 6);
    N = transvalues[0];
    sumX = transvalues[1];
    sumX2 = transvalues[2];
    sumY = transvalues[3];
    sumXY = transvalues[5];

    /* if N is 0 we should return NULL */
    if (N < 1.0)
        PG_RETURN_NULL();

    numeratorX = N * sumX2 - sumX * sumX;
    CHECKFLOATVAL(numeratorX, isinf(sumX2) || isinf(sumX), true);
    numeratorXXY = sumY * sumX2 - sumX * sumXY;
    CHECKFLOATVAL(numeratorXXY, isinf(sumY) || isinf(sumX2) ||
                  isinf(sumX) || isinf(sumXY), true);
    if (numeratorX <= 0)
        PG_RETURN_NULL();

    PG_RETURN_FLOAT8(numeratorXXY / numeratorX);
}

Datum float8_regr_r2 ( PG_FUNCTION_ARGS   ) 

Definition at line 2358 of file float.c.

References check_float8_array(), CHECKFLOATVAL, isinf(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_FLOAT8, and PG_RETURN_NULL.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    float8     *transvalues;
    float8      N,
                sumX,
                sumX2,
                sumY,
                sumY2,
                sumXY,
                numeratorX,
                numeratorY,
                numeratorXY;

    transvalues = check_float8_array(transarray, "float8_regr_r2", 6);
    N = transvalues[0];
    sumX = transvalues[1];
    sumX2 = transvalues[2];
    sumY = transvalues[3];
    sumY2 = transvalues[4];
    sumXY = transvalues[5];

    /* if N is 0 we should return NULL */
    if (N < 1.0)
        PG_RETURN_NULL();

    numeratorX = N * sumX2 - sumX * sumX;
    CHECKFLOATVAL(numeratorX, isinf(sumX2) || isinf(sumX), true);
    numeratorY = N * sumY2 - sumY * sumY;
    CHECKFLOATVAL(numeratorY, isinf(sumY2) || isinf(sumY), true);
    numeratorXY = N * sumXY - sumX * sumY;
    CHECKFLOATVAL(numeratorXY, isinf(sumXY) || isinf(sumX) ||
                  isinf(sumY), true);
    if (numeratorX <= 0)
        PG_RETURN_NULL();
    /* per spec, horizontal line produces 1.0 */
    if (numeratorY <= 0)
        PG_RETURN_FLOAT8(1.0);

    PG_RETURN_FLOAT8((numeratorXY * numeratorXY) /
                     (numeratorX * numeratorY));
}

Datum float8_regr_slope ( PG_FUNCTION_ARGS   ) 

Definition at line 2402 of file float.c.

References check_float8_array(), CHECKFLOATVAL, isinf(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_FLOAT8, and PG_RETURN_NULL.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    float8     *transvalues;
    float8      N,
                sumX,
                sumX2,
                sumY,
                sumXY,
                numeratorX,
                numeratorXY;

    transvalues = check_float8_array(transarray, "float8_regr_slope", 6);
    N = transvalues[0];
    sumX = transvalues[1];
    sumX2 = transvalues[2];
    sumY = transvalues[3];
    sumXY = transvalues[5];

    /* if N is 0 we should return NULL */
    if (N < 1.0)
        PG_RETURN_NULL();

    numeratorX = N * sumX2 - sumX * sumX;
    CHECKFLOATVAL(numeratorX, isinf(sumX2) || isinf(sumX), true);
    numeratorXY = N * sumXY - sumX * sumY;
    CHECKFLOATVAL(numeratorXY, isinf(sumXY) || isinf(sumX) ||
                  isinf(sumY), true);
    if (numeratorX <= 0)
        PG_RETURN_NULL();

    PG_RETURN_FLOAT8(numeratorXY / numeratorX);
}

Datum float8_regr_sxx ( PG_FUNCTION_ARGS   ) 

Definition at line 2136 of file float.c.

References check_float8_array(), CHECKFLOATVAL, isinf(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_FLOAT8, and PG_RETURN_NULL.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    float8     *transvalues;
    float8      N,
                sumX,
                sumX2,
                numerator;

    transvalues = check_float8_array(transarray, "float8_regr_sxx", 6);
    N = transvalues[0];
    sumX = transvalues[1];
    sumX2 = transvalues[2];

    /* if N is 0 we should return NULL */
    if (N < 1.0)
        PG_RETURN_NULL();

    numerator = N * sumX2 - sumX * sumX;
    CHECKFLOATVAL(numerator, isinf(sumX2) || isinf(sumX), true);

    /* Watch out for roundoff error producing a negative numerator */
    if (numerator <= 0.0)
        PG_RETURN_FLOAT8(0.0);

    PG_RETURN_FLOAT8(numerator / N);
}

Datum float8_regr_sxy ( PG_FUNCTION_ARGS   ) 

Definition at line 2194 of file float.c.

References check_float8_array(), CHECKFLOATVAL, isinf(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_FLOAT8, and PG_RETURN_NULL.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    float8     *transvalues;
    float8      N,
                sumX,
                sumY,
                sumXY,
                numerator;

    transvalues = check_float8_array(transarray, "float8_regr_sxy", 6);
    N = transvalues[0];
    sumX = transvalues[1];
    sumY = transvalues[3];
    sumXY = transvalues[5];

    /* if N is 0 we should return NULL */
    if (N < 1.0)
        PG_RETURN_NULL();

    numerator = N * sumXY - sumX * sumY;
    CHECKFLOATVAL(numerator, isinf(sumXY) || isinf(sumX) ||
                  isinf(sumY), true);

    /* A negative result is valid here */

    PG_RETURN_FLOAT8(numerator / N);
}

Datum float8_regr_syy ( PG_FUNCTION_ARGS   ) 

Definition at line 2165 of file float.c.

References check_float8_array(), CHECKFLOATVAL, isinf(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_FLOAT8, and PG_RETURN_NULL.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    float8     *transvalues;
    float8      N,
                sumY,
                sumY2,
                numerator;

    transvalues = check_float8_array(transarray, "float8_regr_syy", 6);
    N = transvalues[0];
    sumY = transvalues[3];
    sumY2 = transvalues[4];

    /* if N is 0 we should return NULL */
    if (N < 1.0)
        PG_RETURN_NULL();

    numerator = N * sumY2 - sumY * sumY;
    CHECKFLOATVAL(numerator, isinf(sumY2) || isinf(sumY), true);

    /* Watch out for roundoff error producing a negative numerator */
    if (numerator <= 0.0)
        PG_RETURN_FLOAT8(0.0);

    PG_RETURN_FLOAT8(numerator / N);
}

Datum float8_stddev_pop ( PG_FUNCTION_ARGS   ) 

Definition at line 1991 of file float.c.

References check_float8_array(), CHECKFLOATVAL, isinf(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_FLOAT8, and PG_RETURN_NULL.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    float8     *transvalues;
    float8      N,
                sumX,
                sumX2,
                numerator;

    transvalues = check_float8_array(transarray, "float8_stddev_pop", 3);
    N = transvalues[0];
    sumX = transvalues[1];
    sumX2 = transvalues[2];

    /* Population stddev is undefined when N is 0, so return NULL */
    if (N == 0.0)
        PG_RETURN_NULL();

    numerator = N * sumX2 - sumX * sumX;
    CHECKFLOATVAL(numerator, isinf(sumX2) || isinf(sumX), true);

    /* Watch out for roundoff error producing a negative numerator */
    if (numerator <= 0.0)
        PG_RETURN_FLOAT8(0.0);

    PG_RETURN_FLOAT8(sqrt(numerator / (N * N)));
}

Datum float8_stddev_samp ( PG_FUNCTION_ARGS   ) 

Definition at line 2020 of file float.c.

References check_float8_array(), CHECKFLOATVAL, isinf(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_FLOAT8, and PG_RETURN_NULL.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    float8     *transvalues;
    float8      N,
                sumX,
                sumX2,
                numerator;

    transvalues = check_float8_array(transarray, "float8_stddev_samp", 3);
    N = transvalues[0];
    sumX = transvalues[1];
    sumX2 = transvalues[2];

    /* Sample stddev is undefined when N is 0 or 1, so return NULL */
    if (N <= 1.0)
        PG_RETURN_NULL();

    numerator = N * sumX2 - sumX * sumX;
    CHECKFLOATVAL(numerator, isinf(sumX2) || isinf(sumX), true);

    /* Watch out for roundoff error producing a negative numerator */
    if (numerator <= 0.0)
        PG_RETURN_FLOAT8(0.0);

    PG_RETURN_FLOAT8(sqrt(numerator / (N * (N - 1.0))));
}

Datum float8_var_pop ( PG_FUNCTION_ARGS   ) 

Definition at line 1933 of file float.c.

References check_float8_array(), CHECKFLOATVAL, isinf(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_FLOAT8, and PG_RETURN_NULL.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    float8     *transvalues;
    float8      N,
                sumX,
                sumX2,
                numerator;

    transvalues = check_float8_array(transarray, "float8_var_pop", 3);
    N = transvalues[0];
    sumX = transvalues[1];
    sumX2 = transvalues[2];

    /* Population variance is undefined when N is 0, so return NULL */
    if (N == 0.0)
        PG_RETURN_NULL();

    numerator = N * sumX2 - sumX * sumX;
    CHECKFLOATVAL(numerator, isinf(sumX2) || isinf(sumX), true);

    /* Watch out for roundoff error producing a negative numerator */
    if (numerator <= 0.0)
        PG_RETURN_FLOAT8(0.0);

    PG_RETURN_FLOAT8(numerator / (N * N));
}

Datum float8_var_samp ( PG_FUNCTION_ARGS   ) 

Definition at line 1962 of file float.c.

References check_float8_array(), CHECKFLOATVAL, isinf(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_FLOAT8, and PG_RETURN_NULL.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    float8     *transvalues;
    float8      N,
                sumX,
                sumX2,
                numerator;

    transvalues = check_float8_array(transarray, "float8_var_samp", 3);
    N = transvalues[0];
    sumX = transvalues[1];
    sumX2 = transvalues[2];

    /* Sample variance is undefined when N is 0 or 1, so return NULL */
    if (N <= 1.0)
        PG_RETURN_NULL();

    numerator = N * sumX2 - sumX * sumX;
    CHECKFLOATVAL(numerator, isinf(sumX2) || isinf(sumX), true);

    /* Watch out for roundoff error producing a negative numerator */
    if (numerator <= 0.0)
        PG_RETURN_FLOAT8(0.0);

    PG_RETURN_FLOAT8(numerator / (N * (N - 1.0)));
}

Datum float8abs ( PG_FUNCTION_ARGS   ) 

Definition at line 664 of file float.c.

References PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);

    PG_RETURN_FLOAT8(fabs(arg1));
}

Datum float8div ( PG_FUNCTION_ARGS   ) 

Definition at line 844 of file float.c.

References CHECKFLOATVAL, ereport, errcode(), errmsg(), ERROR, isinf(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      arg2 = PG_GETARG_FLOAT8(1);
    float8      result;

    if (arg2 == 0.0)
        ereport(ERROR,
                (errcode(ERRCODE_DIVISION_BY_ZERO),
                 errmsg("division by zero")));

    result = arg1 / arg2;

    CHECKFLOATVAL(result, isinf(arg1) || isinf(arg2), arg1 == 0);
    PG_RETURN_FLOAT8(result);
}

Datum float8eq ( PG_FUNCTION_ARGS   ) 

Definition at line 1016 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT8, and PG_RETURN_BOOL.

Datum float8ge ( PG_FUNCTION_ARGS   ) 

Definition at line 1061 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT8, and PG_RETURN_BOOL.

Datum float8gt ( PG_FUNCTION_ARGS   ) 

Definition at line 1052 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT8, and PG_RETURN_BOOL.

Datum float8in ( PG_FUNCTION_ARGS   ) 

Definition at line 391 of file float.c.

References CHECKFLOATVAL, ereport, errcode(), errmsg(), ERROR, get_float8_infinity(), get_float8_nan(), isinf(), PG_GETARG_CSTRING, PG_RETURN_FLOAT8, pg_strncasecmp(), and val.

Referenced by numeric_float8().

{
    char       *num = PG_GETARG_CSTRING(0);
    char       *orig_num;
    double      val;
    char       *endptr;

    /*
     * endptr points to the first character _after_ the sequence we recognized
     * as a valid floating point number. orig_num points to the original input
     * string.
     */
    orig_num = num;

    /*
     * Check for an empty-string input to begin with, to avoid the vagaries of
     * strtod() on different platforms.
     */
    if (*num == '\0')
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
             errmsg("invalid input syntax for type double precision: \"%s\"",
                    orig_num)));

    /* skip leading whitespace */
    while (*num != '\0' && isspace((unsigned char) *num))
        num++;

    errno = 0;
    val = strtod(num, &endptr);

    /* did we not see anything that looks like a double? */
    if (endptr == num || errno != 0)
    {
        int         save_errno = errno;

        /*
         * C99 requires that strtod() accept NaN and [-]Infinity, but not all
         * platforms support that yet (and some accept them but set ERANGE
         * anyway...)  Therefore, we check for these inputs ourselves.
         */
        if (pg_strncasecmp(num, "NaN", 3) == 0)
        {
            val = get_float8_nan();
            endptr = num + 3;
        }
        else if (pg_strncasecmp(num, "Infinity", 8) == 0)
        {
            val = get_float8_infinity();
            endptr = num + 8;
        }
        else if (pg_strncasecmp(num, "-Infinity", 9) == 0)
        {
            val = -get_float8_infinity();
            endptr = num + 9;
        }
        else if (save_errno == ERANGE)
        {
            /*
             * Some platforms return ERANGE for denormalized numbers (those
             * that are not zero, but are too close to zero to have full
             * precision).  We'd prefer not to throw error for that, so try to
             * detect whether it's a "real" out-of-range condition by checking
             * to see if the result is zero or huge.
             */
            if (val == 0.0 || val >= HUGE_VAL || val <= -HUGE_VAL)
                ereport(ERROR,
                        (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                   errmsg("\"%s\" is out of range for type double precision",
                          orig_num)));
        }
        else
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
             errmsg("invalid input syntax for type double precision: \"%s\"",
                    orig_num)));
    }
#ifdef HAVE_BUGGY_SOLARIS_STRTOD
    else
    {
        /*
         * Many versions of Solaris have a bug wherein strtod sets endptr to
         * point one byte beyond the end of the string when given "inf" or
         * "infinity".
         */
        if (endptr != num && endptr[-1] == '\0')
            endptr--;
    }
#endif   /* HAVE_BUGGY_SOLARIS_STRTOD */

#ifdef HAVE_BUGGY_IRIX_STRTOD

    /*
     * In some IRIX versions, strtod() recognizes only "inf", so if the input
     * is "infinity" we have to skip over "inity".  Also, it may return
     * positive infinity for "-inf".
     */
    if (isinf(val))
    {
        if (pg_strncasecmp(num, "Infinity", 8) == 0)
        {
            val = get_float8_infinity();
            endptr = num + 8;
        }
        else if (pg_strncasecmp(num, "-Infinity", 9) == 0)
        {
            val = -get_float8_infinity();
            endptr = num + 9;
        }
        else if (pg_strncasecmp(num, "-inf", 4) == 0)
        {
            val = -get_float8_infinity();
            endptr = num + 4;
        }
    }
#endif   /* HAVE_BUGGY_IRIX_STRTOD */

    /* skip trailing whitespace */
    while (*endptr != '\0' && isspace((unsigned char) *endptr))
        endptr++;

    /* if there is any junk left at the end of the string, bail out */
    if (*endptr != '\0')
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
             errmsg("invalid input syntax for type double precision: \"%s\"",
                    orig_num)));

    CHECKFLOATVAL(val, true, true);

    PG_RETURN_FLOAT8(val);
}

Datum float8larger ( PG_FUNCTION_ARGS   ) 

Definition at line 694 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      arg2 = PG_GETARG_FLOAT8(1);
    float8      result;

    if (float8_cmp_internal(arg1, arg2) > 0)
        result = arg1;
    else
        result = arg2;
    PG_RETURN_FLOAT8(result);
}

Datum float8le ( PG_FUNCTION_ARGS   ) 

Definition at line 1043 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT8, and PG_RETURN_BOOL.

Datum float8lt ( PG_FUNCTION_ARGS   ) 

Definition at line 1034 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT8, and PG_RETURN_BOOL.

Datum float8mi ( PG_FUNCTION_ARGS   ) 

Definition at line 817 of file float.c.

References CHECKFLOATVAL, isinf(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      arg2 = PG_GETARG_FLOAT8(1);
    float8      result;

    result = arg1 - arg2;

    CHECKFLOATVAL(result, isinf(arg1) || isinf(arg2), true);
    PG_RETURN_FLOAT8(result);
}

Datum float8mul ( PG_FUNCTION_ARGS   ) 

Definition at line 830 of file float.c.

References CHECKFLOATVAL, isinf(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      arg2 = PG_GETARG_FLOAT8(1);
    float8      result;

    result = arg1 * arg2;

    CHECKFLOATVAL(result, isinf(arg1) || isinf(arg2),
                  arg1 == 0 || arg2 == 0);
    PG_RETURN_FLOAT8(result);
}

Datum float8ne ( PG_FUNCTION_ARGS   ) 

Definition at line 1025 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT8, and PG_RETURN_BOOL.

Datum float8out ( PG_FUNCTION_ARGS   ) 

Definition at line 529 of file float.c.

References ascii(), extra_float_digits, is_infinite(), MAXDOUBLEWIDTH, palloc(), PG_GETARG_FLOAT8, PG_RETURN_CSTRING, and snprintf().

{
    float8      num = PG_GETARG_FLOAT8(0);
    char       *ascii = (char *) palloc(MAXDOUBLEWIDTH + 1);

    if (isnan(num))
        PG_RETURN_CSTRING(strcpy(ascii, "NaN"));

    switch (is_infinite(num))
    {
        case 1:
            strcpy(ascii, "Infinity");
            break;
        case -1:
            strcpy(ascii, "-Infinity");
            break;
        default:
            {
                int         ndig = DBL_DIG + extra_float_digits;

                if (ndig < 1)
                    ndig = 1;

                snprintf(ascii, MAXDOUBLEWIDTH + 1, "%.*g", ndig, num);
            }
    }

    PG_RETURN_CSTRING(ascii);
}

Datum float8pl ( PG_FUNCTION_ARGS   ) 

Definition at line 804 of file float.c.

References CHECKFLOATVAL, isinf(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      arg2 = PG_GETARG_FLOAT8(1);
    float8      result;

    result = arg1 + arg2;

    CHECKFLOATVAL(result, isinf(arg1) || isinf(arg2), true);
    PG_RETURN_FLOAT8(result);
}

Datum float8recv ( PG_FUNCTION_ARGS   ) 
Datum float8send ( PG_FUNCTION_ARGS   ) 
Datum float8smaller ( PG_FUNCTION_ARGS   ) 

Definition at line 708 of file float.c.

References float8_cmp_internal(), PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      arg2 = PG_GETARG_FLOAT8(1);
    float8      result;

    if (float8_cmp_internal(arg1, arg2) < 0)
        result = arg1;
    else
        result = arg2;
    PG_RETURN_FLOAT8(result);
}

Datum float8um ( PG_FUNCTION_ARGS   ) 

Definition at line 676 of file float.c.

References PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      result;

    result = -arg1;
    PG_RETURN_FLOAT8(result);
}

Datum float8up ( PG_FUNCTION_ARGS   ) 

Definition at line 686 of file float.c.

References arg, PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

char* format_operator ( Oid  operator_oid  ) 

Definition at line 745 of file regproc.c.

References format_operator_internal().

Referenced by ComputeIndexAttrs(), getObjectDescription(), and regoperatorout().

{
    return format_operator_internal(operator_oid, false);
}

char* format_operator_qualified ( Oid  operator_oid  ) 

Definition at line 751 of file regproc.c.

References format_operator_internal().

Referenced by getObjectIdentity().

{
    return format_operator_internal(operator_oid, true);
}

char* format_procedure ( Oid  procedure_oid  ) 

Definition at line 307 of file regproc.c.

References format_procedure_internal().

Referenced by do_compile(), getObjectDescription(), ProcedureCreate(), and regprocedureout().

{
    return format_procedure_internal(procedure_oid, false);
}

char* format_procedure_qualified ( Oid  procedure_oid  ) 

Definition at line 313 of file regproc.c.

References format_procedure_internal().

Referenced by getObjectIdentity().

{
    return format_procedure_internal(procedure_oid, true);
}

Datum format_type ( PG_FUNCTION_ARGS   ) 

Definition at line 68 of file format_type.c.

References cstring_to_text(), format_type_internal(), PG_ARGISNULL, PG_GETARG_INT32, PG_GETARG_OID, PG_RETURN_NULL, and PG_RETURN_TEXT_P.

{
    Oid         type_oid;
    int32       typemod;
    char       *result;

    /* Since this function is not strict, we must test for null args */
    if (PG_ARGISNULL(0))
        PG_RETURN_NULL();

    type_oid = PG_GETARG_OID(0);

    if (PG_ARGISNULL(1))
        result = format_type_internal(type_oid, -1, false, true, false);
    else
    {
        typemod = PG_GETARG_INT32(1);
        result = format_type_internal(type_oid, typemod, true, true, false);
    }

    PG_RETURN_TEXT_P(cstring_to_text(result));
}

char* format_type_be ( Oid  type_oid  ) 

Definition at line 98 of file format_type.c.

References format_type_internal().

Referenced by aclcheck_error_type(), addFamilyMember(), addRangeTableEntryForFunction(), AggregateCreate(), AlterTypeNamespace(), AlterTypeNamespace_oid(), AlterTypeNamespaceInternal(), AlterTypeOwner(), appendTypeNameToBuffer(), array_cat(), array_cmp(), array_contain_compare(), array_eq(), array_recv(), array_replace_internal(), array_send(), ATAddForeignKeyConstraint(), ATExecAlterColumnType(), ATExecSetStorage(), ATPrepAlterColumnType(), build_column_default(), build_subplan(), check_object_ownership(), check_of_type(), check_sql_fn_retval(), CheckAttributeType(), checkDomainOwner(), checkEnumOwner(), coerce_record_to_complex(), coerce_to_boolean(), coerce_to_common_type(), coerce_to_specific_type(), coerce_type(), compare_values_of_enum(), compile_plperl_function(), compile_pltcl_function(), ComputeIndexAttrs(), convert_tuples_by_name(), cookDefault(), CreateCast(), CreateFunction(), DefineAggregate(), DefineDomain(), DefineRange(), DefineType(), do_compile(), does_not_exist_skipping(), domain_check_input(), domain_state_setup(), dropOperators(), dropProcedures(), enforce_generic_type_consistency(), enum_first(), enum_in(), enum_last(), enum_recv(), EvaluateParams(), exec_stmt_foreach_a(), ExecCheckPlanOutput(), ExecEvalArray(), ExecEvalCoerceToDomain(), ExecEvalFieldSelect(), ExecEvalParamExtern(), ExecEvalScalarVar(), ExecEvalWholeRowVar(), ExecInitExpr(), exprType(), fetch_cursor_param_value(), findRangeSubOpclass(), findTypeOutputFunction(), fmgr_sql_validator(), format_operator_internal(), format_procedure_internal(), funcname_signature_string(), get_cast_oid(), get_domain_constraint_oid(), get_range_io_data(), get_rels_with_domain(), get_sort_group_operators(), get_ts_parser_func(), get_ts_template_func(), GetColumnDefCollation(), GetDefaultOpClass(), GetIndexOpClass(), getObjectDescription(), getTypeBinaryInputInfo(), getTypeBinaryOutputInfo(), getTypeInputInfo(), getTypeOutputInfo(), hash_array(), hash_range(), init_sql_fcache(), internal_get_result_type(), intorel_startup(), load_enum_cache_data(), lookup_rowtype_tupdesc_internal(), LookupTypeName(), make_row_comparison_op(), make_scalar_array_op(), MergeAttributes(), op_signature_string(), ParseFuncOrColumn(), pg_collation_for(), plperl_array_to_datum(), plperl_sv_to_datum(), plperl_validator(), plpgsql_build_variable(), plpgsql_validator(), PLy_output_datum_func2(), PLy_procedure_create(), prepare_sql_fn_parse_info(), print_function_arguments(), print_function_rettype(), ProcedureCreate(), processIndirection(), record_cmp(), record_eq(), regtypeout(), RenameConstraintById(), RenameType(), resolve_generic_type(), ri_HashCompareOp(), select_common_type(), storeOperators(), storeProcedures(), transformAggregateCall(), transformArrayExpr(), transformArraySubscripts(), transformArrayType(), transformAssignedExpr(), transformAssignmentIndirection(), transformAssignmentSubscripts(), transformCollateClause(), transformColumnType(), transformTypeCast(), transformXmlSerialize(), tupledesc_match(), unknown_attribute(), validateConnectbyTupleDesc(), and variable_coerce_param_hook().

{
    return format_type_internal(type_oid, -1, false, false, false);
}

char* format_type_be_qualified ( Oid  type_oid  ) 

Definition at line 104 of file format_type.c.

References format_type_internal().

Referenced by format_operator_internal(), format_procedure_internal(), and getObjectIdentity().

{
    return format_type_internal(type_oid, -1, false, false, true);
}

char* format_type_with_typemod ( Oid  type_oid,
int32  typemod 
)
Datum ftod ( PG_FUNCTION_ARGS   ) 

Definition at line 1127 of file float.c.

References PG_GETARG_FLOAT4, and PG_RETURN_FLOAT8.

Datum ftoi2 ( PG_FUNCTION_ARGS   ) 

Definition at line 1231 of file float.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_FLOAT4, PG_RETURN_INT16, and rint().

{
    float4      num = PG_GETARG_FLOAT4(0);

    if (num < SHRT_MIN || num > SHRT_MAX || isnan(num))
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("smallint out of range")));

    PG_RETURN_INT16((int16) rint(num));
}

Datum ftoi4 ( PG_FUNCTION_ARGS   ) 

Definition at line 1214 of file float.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_FLOAT4, PG_RETURN_INT32, and rint().

{
    float4      num = PG_GETARG_FLOAT4(0);

    if (num < INT_MIN || num > INT_MAX || isnan(num))
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("integer out of range")));

    PG_RETURN_INT32((int32) rint(num));
}

char* generate_collation_name ( Oid  collid  ) 

Definition at line 8716 of file ruleutils.c.

References CollationIsVisible(), COLLOID, elog, ERROR, get_namespace_name(), GETSTRUCT, HeapTupleIsValid, NameStr, ObjectIdGetDatum, quote_qualified_identifier(), ReleaseSysCache(), and SearchSysCache1.

Referenced by get_const_collation(), get_from_clause_coldeflist(), get_rule_expr(), pg_collation_for(), and pg_get_indexdef_worker().

{
    HeapTuple   tp;
    Form_pg_collation colltup;
    char       *collname;
    char       *nspname;
    char       *result;

    tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
    if (!HeapTupleIsValid(tp))
        elog(ERROR, "cache lookup failed for collation %u", collid);
    colltup = (Form_pg_collation) GETSTRUCT(tp);
    collname = NameStr(colltup->collname);

    if (!CollationIsVisible(collid))
        nspname = get_namespace_name(colltup->collnamespace);
    else
        nspname = NULL;

    result = quote_qualified_identifier(nspname, collname);

    ReleaseSysCache(tp);

    return result;
}

Datum generate_series_int4 ( PG_FUNCTION_ARGS   ) 

Definition at line 1336 of file int.c.

References generate_series_step_int4().

{
    return generate_series_step_int4(fcinfo);
}

Datum generate_series_step_int4 ( PG_FUNCTION_ARGS   ) 

Definition at line 1342 of file int.c.

References generate_series_fctx::current, ereport, errcode(), errmsg(), ERROR, generate_series_fctx::finish, Int32GetDatum, MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, palloc(), PG_GETARG_INT32, PG_NARGS, SAMESIGN, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, generate_series_fctx::step, and FuncCallContext::user_fctx.

Referenced by generate_series_int4().

{
    FuncCallContext *funcctx;
    generate_series_fctx *fctx;
    int32       result;
    MemoryContext oldcontext;

    /* stuff done only on the first call of the function */
    if (SRF_IS_FIRSTCALL())
    {
        int32       start = PG_GETARG_INT32(0);
        int32       finish = PG_GETARG_INT32(1);
        int32       step = 1;

        /* see if we were given an explicit step size */
        if (PG_NARGS() == 3)
            step = PG_GETARG_INT32(2);
        if (step == 0)
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                     errmsg("step size cannot equal zero")));

        /* create a function context for cross-call persistence */
        funcctx = SRF_FIRSTCALL_INIT();

        /*
         * switch to memory context appropriate for multiple function calls
         */
        oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);

        /* allocate memory for user context */
        fctx = (generate_series_fctx *) palloc(sizeof(generate_series_fctx));

        /*
         * Use fctx to keep state from call to call. Seed current with the
         * original start value
         */
        fctx->current = start;
        fctx->finish = finish;
        fctx->step = step;

        funcctx->user_fctx = fctx;
        MemoryContextSwitchTo(oldcontext);
    }

    /* stuff done on every call of the function */
    funcctx = SRF_PERCALL_SETUP();

    /*
     * get the saved state and use current as the result for this iteration
     */
    fctx = funcctx->user_fctx;
    result = fctx->current;

    if ((fctx->step > 0 && fctx->current <= fctx->finish) ||
        (fctx->step < 0 && fctx->current >= fctx->finish))
    {
        /* increment current in preparation for next iteration */
        fctx->current += fctx->step;

        /* if next-value computation overflows, this is the final result */
        if (SAMESIGN(result, fctx->step) && !SAMESIGN(result, fctx->current))
            fctx->step = 0;

        /* do when there is more left to send */
        SRF_RETURN_NEXT(funcctx, Int32GetDatum(result));
    }
    else
        /* do when there is no more left */
        SRF_RETURN_DONE(funcctx);
}

float get_float4_infinity ( void   ) 

Definition at line 115 of file float.c.

Referenced by float4in(), gistpenalty(), leftmostvalue_float4(), and range_gist_penalty().

{
#ifdef INFINITY
    /* C99 standard way */
    return (float) INFINITY;
#else

    /*
     * On some platforms, HUGE_VAL is an infinity, elsewhere it's just the
     * largest normal double.  We assume forcing an overflow will get us a
     * true infinity.
     */
    return (float) (HUGE_VAL * HUGE_VAL);
#endif
}

float get_float4_nan ( void   ) 

Definition at line 145 of file float.c.

Referenced by float4in(), and numeric_float4().

{
#ifdef NAN
    /* C99 standard way */
    return (float) NAN;
#else
    /* Assume we can get a NAN via zero divide */
    return (float) (0.0 / 0.0);
#endif
}

double get_float8_infinity ( void   ) 

Definition at line 98 of file float.c.

Referenced by check_special_value(), compute_range_stats(), dexp(), dpow(), float8in(), gbt_ts_dist(), get_distance(), gistindex_keytest(), leftmostvalue_float8(), and pg_hypot().

{
#ifdef INFINITY
    /* C99 standard way */
    return (double) INFINITY;
#else

    /*
     * On some platforms, HUGE_VAL is an infinity, elsewhere it's just the
     * largest normal double.  We assume forcing an overflow will get us a
     * true infinity.
     */
    return (double) (HUGE_VAL * HUGE_VAL);
#endif
}

double get_float8_nan ( void   ) 

Definition at line 132 of file float.c.

Referenced by check_special_value(), float8in(), numeric_float8(), numeric_float8_no_overflow(), and pg_hypot().

{
    /* (double) NAN doesn't work on some NetBSD/MIPS releases */
#if defined(NAN) && !(defined(__NetBSD__) && defined(__mips__))
    /* C99 standard way */
    return (double) NAN;
#else
    /* Assume we can get a NAN via zero divide */
    return (double) (0.0 / 0.0);
#endif
}

Datum getdatabaseencoding ( PG_FUNCTION_ARGS   ) 
Datum ginarrayconsistent ( PG_FUNCTION_ARGS   ) 

Definition at line 142 of file ginarrayproc.c.

References elog, ERROR, GinContainedStrategy, GinContainsStrategy, GinEqualStrategy, GinOverlapStrategy, i, PG_GETARG_INT32, PG_GETARG_POINTER, PG_GETARG_UINT16, and PG_RETURN_BOOL.

{
    bool       *check = (bool *) PG_GETARG_POINTER(0);
    StrategyNumber strategy = PG_GETARG_UINT16(1);

    /* ArrayType  *query = PG_GETARG_ARRAYTYPE_P(2); */
    int32       nkeys = PG_GETARG_INT32(3);

    /* Pointer     *extra_data = (Pointer *) PG_GETARG_POINTER(4); */
    bool       *recheck = (bool *) PG_GETARG_POINTER(5);

    /* Datum       *queryKeys = (Datum *) PG_GETARG_POINTER(6); */
    bool       *nullFlags = (bool *) PG_GETARG_POINTER(7);
    bool        res;
    int32       i;

    switch (strategy)
    {
        case GinOverlapStrategy:
            /* result is not lossy */
            *recheck = false;
            /* must have a match for at least one non-null element */
            res = false;
            for (i = 0; i < nkeys; i++)
            {
                if (check[i] && !nullFlags[i])
                {
                    res = true;
                    break;
                }
            }
            break;
        case GinContainsStrategy:
            /* result is not lossy */
            *recheck = false;
            /* must have all elements in check[] true, and no nulls */
            res = true;
            for (i = 0; i < nkeys; i++)
            {
                if (!check[i] || nullFlags[i])
                {
                    res = false;
                    break;
                }
            }
            break;
        case GinContainedStrategy:
            /* we will need recheck */
            *recheck = true;
            /* can't do anything else useful here */
            res = true;
            break;
        case GinEqualStrategy:
            /* we will need recheck */
            *recheck = true;

            /*
             * Must have all elements in check[] true; no discrimination
             * against nulls here.  This is because array_contain_compare and
             * array_eq handle nulls differently ...
             */
            res = true;
            for (i = 0; i < nkeys; i++)
            {
                if (!check[i])
                {
                    res = false;
                    break;
                }
            }
            break;
        default:
            elog(ERROR, "ginarrayconsistent: unknown strategy number: %d",
                 strategy);
            res = false;
    }

    PG_RETURN_BOOL(res);
}

Datum ginarrayextract ( PG_FUNCTION_ARGS   ) 

Definition at line 33 of file ginarrayproc.c.

References ARR_ELEMTYPE, deconstruct_array(), get_typlenbyvalalign(), PG_GETARG_ARRAYTYPE_P_COPY, PG_GETARG_POINTER, and PG_RETURN_POINTER.

Referenced by ginarrayextract_2args().

{
    /* Make copy of array input to ensure it doesn't disappear while in use */
    ArrayType  *array = PG_GETARG_ARRAYTYPE_P_COPY(0);
    int32      *nkeys = (int32 *) PG_GETARG_POINTER(1);
    bool      **nullFlags = (bool **) PG_GETARG_POINTER(2);
    int16       elmlen;
    bool        elmbyval;
    char        elmalign;
    Datum      *elems;
    bool       *nulls;
    int         nelems;

    get_typlenbyvalalign(ARR_ELEMTYPE(array),
                         &elmlen, &elmbyval, &elmalign);

    deconstruct_array(array,
                      ARR_ELEMTYPE(array),
                      elmlen, elmbyval, elmalign,
                      &elems, &nulls, &nelems);

    *nkeys = nelems;
    *nullFlags = nulls;

    /* we should not free array, elems[i] points into it */
    PG_RETURN_POINTER(elems);
}

Datum ginarrayextract_2args ( PG_FUNCTION_ARGS   ) 

Definition at line 68 of file ginarrayproc.c.

References elog, ERROR, ginarrayextract(), and PG_NARGS.

{
    if (PG_NARGS() < 3)         /* should not happen */
        elog(ERROR, "ginarrayextract requires three arguments");
    return ginarrayextract(fcinfo);
}

Datum ginqueryarrayextract ( PG_FUNCTION_ARGS   ) 

Definition at line 79 of file ginarrayproc.c.

References ARR_ELEMTYPE, deconstruct_array(), elog, ERROR, get_typlenbyvalalign(), GinContainedStrategy, GinContainsStrategy, GinEqualStrategy, GinOverlapStrategy, PG_GETARG_ARRAYTYPE_P_COPY, PG_GETARG_POINTER, PG_GETARG_UINT16, and PG_RETURN_POINTER.

{
    /* Make copy of array input to ensure it doesn't disappear while in use */
    ArrayType  *array = PG_GETARG_ARRAYTYPE_P_COPY(0);
    int32      *nkeys = (int32 *) PG_GETARG_POINTER(1);
    StrategyNumber strategy = PG_GETARG_UINT16(2);

    /* bool   **pmatch = (bool **) PG_GETARG_POINTER(3); */
    /* Pointer     *extra_data = (Pointer *) PG_GETARG_POINTER(4); */
    bool      **nullFlags = (bool **) PG_GETARG_POINTER(5);
    int32      *searchMode = (int32 *) PG_GETARG_POINTER(6);
    int16       elmlen;
    bool        elmbyval;
    char        elmalign;
    Datum      *elems;
    bool       *nulls;
    int         nelems;

    get_typlenbyvalalign(ARR_ELEMTYPE(array),
                         &elmlen, &elmbyval, &elmalign);

    deconstruct_array(array,
                      ARR_ELEMTYPE(array),
                      elmlen, elmbyval, elmalign,
                      &elems, &nulls, &nelems);

    *nkeys = nelems;
    *nullFlags = nulls;

    switch (strategy)
    {
        case GinOverlapStrategy:
            *searchMode = GIN_SEARCH_MODE_DEFAULT;
            break;
        case GinContainsStrategy:
            if (nelems > 0)
                *searchMode = GIN_SEARCH_MODE_DEFAULT;
            else    /* everything contains the empty set */
                *searchMode = GIN_SEARCH_MODE_ALL;
            break;
        case GinContainedStrategy:
            /* empty set is contained in everything */
            *searchMode = GIN_SEARCH_MODE_INCLUDE_EMPTY;
            break;
        case GinEqualStrategy:
            if (nelems > 0)
                *searchMode = GIN_SEARCH_MODE_DEFAULT;
            else
                *searchMode = GIN_SEARCH_MODE_INCLUDE_EMPTY;
            break;
        default:
            elog(ERROR, "ginqueryarrayextract: unknown strategy number: %d",
                 strategy);
    }

    /* we should not free array, elems[i] points into it */
    PG_RETURN_POINTER(elems);
}

Datum has_any_column_privilege_id ( PG_FUNCTION_ARGS   ) 

Definition at line 2360 of file acl.c.

References ACLCHECK_OK, ACLMASK_ANY, convert_column_priv_string(), GetUserId(), ObjectIdGetDatum, pg_attribute_aclcheck_all(), pg_class_aclcheck(), PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, PG_RETURN_NULL, RELOID, and SearchSysCacheExists1.

{
    Oid         tableoid = PG_GETARG_OID(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    mode = convert_column_priv_string(priv_type_text);

    if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(tableoid)))
        PG_RETURN_NULL();

    /* First check at table level, then examine each column if needed */
    aclresult = pg_class_aclcheck(tableoid, roleid, mode);
    if (aclresult != ACLCHECK_OK)
        aclresult = pg_attribute_aclcheck_all(tableoid, roleid, mode,
                                              ACLMASK_ANY);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_any_column_privilege_id_id ( PG_FUNCTION_ARGS   ) 

Definition at line 2416 of file acl.c.

References ACLCHECK_OK, ACLMASK_ANY, convert_column_priv_string(), ObjectIdGetDatum, pg_attribute_aclcheck_all(), pg_class_aclcheck(), PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, PG_RETURN_NULL, RELOID, and SearchSysCacheExists1.

{
    Oid         roleid = PG_GETARG_OID(0);
    Oid         tableoid = PG_GETARG_OID(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    AclMode     mode;
    AclResult   aclresult;

    mode = convert_column_priv_string(priv_type_text);

    if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(tableoid)))
        PG_RETURN_NULL();

    /* First check at table level, then examine each column if needed */
    aclresult = pg_class_aclcheck(tableoid, roleid, mode);
    if (aclresult != ACLCHECK_OK)
        aclresult = pg_attribute_aclcheck_all(tableoid, roleid, mode,
                                              ACLMASK_ANY);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_any_column_privilege_id_name ( PG_FUNCTION_ARGS   ) 

Definition at line 2389 of file acl.c.

References ACLCHECK_OK, ACLMASK_ANY, convert_column_priv_string(), convert_table_name(), pg_attribute_aclcheck_all(), pg_class_aclcheck(), PG_GETARG_OID, PG_GETARG_TEXT_P, and PG_RETURN_BOOL.

{
    Oid         roleid = PG_GETARG_OID(0);
    text       *tablename = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         tableoid;
    AclMode     mode;
    AclResult   aclresult;

    tableoid = convert_table_name(tablename);
    mode = convert_column_priv_string(priv_type_text);

    /* First check at table level, then examine each column if needed */
    aclresult = pg_class_aclcheck(tableoid, roleid, mode);
    if (aclresult != ACLCHECK_OK)
        aclresult = pg_attribute_aclcheck_all(tableoid, roleid, mode,
                                              ACLMASK_ANY);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_any_column_privilege_name ( PG_FUNCTION_ARGS   ) 

Definition at line 2301 of file acl.c.

References ACLCHECK_OK, ACLMASK_ANY, convert_column_priv_string(), convert_table_name(), GetUserId(), pg_attribute_aclcheck_all(), pg_class_aclcheck(), PG_GETARG_TEXT_P, and PG_RETURN_BOOL.

{
    text       *tablename = PG_GETARG_TEXT_P(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    Oid         tableoid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    tableoid = convert_table_name(tablename);
    mode = convert_column_priv_string(priv_type_text);

    /* First check at table level, then examine each column if needed */
    aclresult = pg_class_aclcheck(tableoid, roleid, mode);
    if (aclresult != ACLCHECK_OK)
        aclresult = pg_attribute_aclcheck_all(tableoid, roleid, mode,
                                              ACLMASK_ANY);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_any_column_privilege_name_id ( PG_FUNCTION_ARGS   ) 

Definition at line 2329 of file acl.c.

References ACLCHECK_OK, ACLMASK_ANY, convert_column_priv_string(), get_role_oid_or_public(), NameStr, ObjectIdGetDatum, pg_attribute_aclcheck_all(), pg_class_aclcheck(), PG_GETARG_NAME, PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, PG_RETURN_NULL, RELOID, SearchSysCacheExists1, and username.

{
    Name        username = PG_GETARG_NAME(0);
    Oid         tableoid = PG_GETARG_OID(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = get_role_oid_or_public(NameStr(*username));
    mode = convert_column_priv_string(priv_type_text);

    if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(tableoid)))
        PG_RETURN_NULL();

    /* First check at table level, then examine each column if needed */
    aclresult = pg_class_aclcheck(tableoid, roleid, mode);
    if (aclresult != ACLCHECK_OK)
        aclresult = pg_attribute_aclcheck_all(tableoid, roleid, mode,
                                              ACLMASK_ANY);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_any_column_privilege_name_name ( PG_FUNCTION_ARGS   ) 

Definition at line 2271 of file acl.c.

References ACLCHECK_OK, ACLMASK_ANY, convert_column_priv_string(), convert_table_name(), get_role_oid_or_public(), NameStr, pg_attribute_aclcheck_all(), pg_class_aclcheck(), PG_GETARG_NAME, PG_GETARG_TEXT_P, and PG_RETURN_BOOL.

{
    Name        rolename = PG_GETARG_NAME(0);
    text       *tablename = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleid;
    Oid         tableoid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = get_role_oid_or_public(NameStr(*rolename));
    tableoid = convert_table_name(tablename);
    mode = convert_column_priv_string(priv_type_text);

    /* First check at table level, then examine each column if needed */
    aclresult = pg_class_aclcheck(tableoid, roleid, mode);
    if (aclresult != ACLCHECK_OK)
        aclresult = pg_attribute_aclcheck_all(tableoid, roleid, mode,
                                              ACLMASK_ANY);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_column_privilege_id_attnum ( PG_FUNCTION_ARGS   ) 

Definition at line 2803 of file acl.c.

References column_privilege_check(), convert_column_priv_string(), GetUserId(), PG_GETARG_INT16, PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, and PG_RETURN_NULL.

{
    Oid         tableoid = PG_GETARG_OID(0);
    AttrNumber  colattnum = PG_GETARG_INT16(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleid;
    AclMode     mode;
    int         privresult;

    roleid = GetUserId();
    mode = convert_column_priv_string(priv_type_text);

    privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
    if (privresult < 0)
        PG_RETURN_NULL();
    PG_RETURN_BOOL(privresult);
}

Datum has_column_privilege_id_id_attnum ( PG_FUNCTION_ARGS   ) 

Definition at line 2696 of file acl.c.

References column_privilege_check(), convert_column_priv_string(), PG_GETARG_INT16, PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, and PG_RETURN_NULL.

{
    Oid         roleid = PG_GETARG_OID(0);
    Oid         tableoid = PG_GETARG_OID(1);
    AttrNumber  colattnum = PG_GETARG_INT16(2);
    text       *priv_type_text = PG_GETARG_TEXT_P(3);
    AclMode     mode;
    int         privresult;

    mode = convert_column_priv_string(priv_type_text);

    privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
    if (privresult < 0)
        PG_RETURN_NULL();
    PG_RETURN_BOOL(privresult);
}

Datum has_column_privilege_id_id_name ( PG_FUNCTION_ARGS   ) 

Definition at line 2671 of file acl.c.

References column_privilege_check(), convert_column_name(), convert_column_priv_string(), PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, and PG_RETURN_NULL.

{
    Oid         roleid = PG_GETARG_OID(0);
    Oid         tableoid = PG_GETARG_OID(1);
    text       *column = PG_GETARG_TEXT_P(2);
    text       *priv_type_text = PG_GETARG_TEXT_P(3);
    AttrNumber  colattnum;
    AclMode     mode;
    int         privresult;

    colattnum = convert_column_name(tableoid, column);
    mode = convert_column_priv_string(priv_type_text);

    privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
    if (privresult < 0)
        PG_RETURN_NULL();
    PG_RETURN_BOOL(privresult);
}

Datum has_column_privilege_id_name ( PG_FUNCTION_ARGS   ) 

Definition at line 2776 of file acl.c.

References column_privilege_check(), convert_column_name(), convert_column_priv_string(), GetUserId(), PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, and PG_RETURN_NULL.

{
    Oid         tableoid = PG_GETARG_OID(0);
    text       *column = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleid;
    AttrNumber  colattnum;
    AclMode     mode;
    int         privresult;

    roleid = GetUserId();
    colattnum = convert_column_name(tableoid, column);
    mode = convert_column_priv_string(priv_type_text);

    privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
    if (privresult < 0)
        PG_RETURN_NULL();
    PG_RETURN_BOOL(privresult);
}

Datum has_column_privilege_id_name_attnum ( PG_FUNCTION_ARGS   ) 

Definition at line 2646 of file acl.c.

References column_privilege_check(), convert_column_priv_string(), convert_table_name(), PG_GETARG_INT16, PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, and PG_RETURN_NULL.

{
    Oid         roleid = PG_GETARG_OID(0);
    text       *tablename = PG_GETARG_TEXT_P(1);
    AttrNumber  colattnum = PG_GETARG_INT16(2);
    text       *priv_type_text = PG_GETARG_TEXT_P(3);
    Oid         tableoid;
    AclMode     mode;
    int         privresult;

    tableoid = convert_table_name(tablename);
    mode = convert_column_priv_string(priv_type_text);

    privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
    if (privresult < 0)
        PG_RETURN_NULL();
    PG_RETURN_BOOL(privresult);
}

Datum has_column_privilege_id_name_name ( PG_FUNCTION_ARGS   ) 

Definition at line 2619 of file acl.c.

References column_privilege_check(), convert_column_name(), convert_column_priv_string(), convert_table_name(), PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, and PG_RETURN_NULL.

{
    Oid         roleid = PG_GETARG_OID(0);
    text       *tablename = PG_GETARG_TEXT_P(1);
    text       *column = PG_GETARG_TEXT_P(2);
    text       *priv_type_text = PG_GETARG_TEXT_P(3);
    Oid         tableoid;
    AttrNumber  colattnum;
    AclMode     mode;
    int         privresult;

    tableoid = convert_table_name(tablename);
    colattnum = convert_column_name(tableoid, column);
    mode = convert_column_priv_string(priv_type_text);

    privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
    if (privresult < 0)
        PG_RETURN_NULL();
    PG_RETURN_BOOL(privresult);
}

Datum has_column_privilege_name_attnum ( PG_FUNCTION_ARGS   ) 

Definition at line 2749 of file acl.c.

References column_privilege_check(), convert_column_priv_string(), convert_table_name(), GetUserId(), PG_GETARG_INT16, PG_GETARG_TEXT_P, PG_RETURN_BOOL, and PG_RETURN_NULL.

{
    text       *tablename = PG_GETARG_TEXT_P(0);
    AttrNumber  colattnum = PG_GETARG_INT16(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleid;
    Oid         tableoid;
    AclMode     mode;
    int         privresult;

    roleid = GetUserId();
    tableoid = convert_table_name(tablename);
    mode = convert_column_priv_string(priv_type_text);

    privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
    if (privresult < 0)
        PG_RETURN_NULL();
    PG_RETURN_BOOL(privresult);
}

Datum has_column_privilege_name_id_attnum ( PG_FUNCTION_ARGS   ) 

Definition at line 2594 of file acl.c.

References column_privilege_check(), convert_column_priv_string(), get_role_oid_or_public(), NameStr, PG_GETARG_INT16, PG_GETARG_NAME, PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, PG_RETURN_NULL, and username.

{
    Name        username = PG_GETARG_NAME(0);
    Oid         tableoid = PG_GETARG_OID(1);
    AttrNumber  colattnum = PG_GETARG_INT16(2);
    text       *priv_type_text = PG_GETARG_TEXT_P(3);
    Oid         roleid;
    AclMode     mode;
    int         privresult;

    roleid = get_role_oid_or_public(NameStr(*username));
    mode = convert_column_priv_string(priv_type_text);

    privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
    if (privresult < 0)
        PG_RETURN_NULL();
    PG_RETURN_BOOL(privresult);
}

Datum has_column_privilege_name_id_name ( PG_FUNCTION_ARGS   ) 

Definition at line 2567 of file acl.c.

References column_privilege_check(), convert_column_name(), convert_column_priv_string(), get_role_oid_or_public(), NameStr, PG_GETARG_NAME, PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, PG_RETURN_NULL, and username.

{
    Name        username = PG_GETARG_NAME(0);
    Oid         tableoid = PG_GETARG_OID(1);
    text       *column = PG_GETARG_TEXT_P(2);
    text       *priv_type_text = PG_GETARG_TEXT_P(3);
    Oid         roleid;
    AttrNumber  colattnum;
    AclMode     mode;
    int         privresult;

    roleid = get_role_oid_or_public(NameStr(*username));
    colattnum = convert_column_name(tableoid, column);
    mode = convert_column_priv_string(priv_type_text);

    privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
    if (privresult < 0)
        PG_RETURN_NULL();
    PG_RETURN_BOOL(privresult);
}

Datum has_column_privilege_name_name ( PG_FUNCTION_ARGS   ) 

Definition at line 2720 of file acl.c.

References column_privilege_check(), convert_column_name(), convert_column_priv_string(), convert_table_name(), GetUserId(), PG_GETARG_TEXT_P, PG_RETURN_BOOL, and PG_RETURN_NULL.

{
    text       *tablename = PG_GETARG_TEXT_P(0);
    text       *column = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleid;
    Oid         tableoid;
    AttrNumber  colattnum;
    AclMode     mode;
    int         privresult;

    roleid = GetUserId();
    tableoid = convert_table_name(tablename);
    colattnum = convert_column_name(tableoid, column);
    mode = convert_column_priv_string(priv_type_text);

    privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
    if (privresult < 0)
        PG_RETURN_NULL();
    PG_RETURN_BOOL(privresult);
}

Datum has_column_privilege_name_name_attnum ( PG_FUNCTION_ARGS   ) 

Definition at line 2540 of file acl.c.

References column_privilege_check(), convert_column_priv_string(), convert_table_name(), get_role_oid_or_public(), NameStr, PG_GETARG_INT16, PG_GETARG_NAME, PG_GETARG_TEXT_P, PG_RETURN_BOOL, and PG_RETURN_NULL.

{
    Name        rolename = PG_GETARG_NAME(0);
    text       *tablename = PG_GETARG_TEXT_P(1);
    AttrNumber  colattnum = PG_GETARG_INT16(2);
    text       *priv_type_text = PG_GETARG_TEXT_P(3);
    Oid         roleid;
    Oid         tableoid;
    AclMode     mode;
    int         privresult;

    roleid = get_role_oid_or_public(NameStr(*rolename));
    tableoid = convert_table_name(tablename);
    mode = convert_column_priv_string(priv_type_text);

    privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
    if (privresult < 0)
        PG_RETURN_NULL();
    PG_RETURN_BOOL(privresult);
}

Datum has_column_privilege_name_name_name ( PG_FUNCTION_ARGS   ) 

Definition at line 2511 of file acl.c.

References column_privilege_check(), convert_column_name(), convert_column_priv_string(), convert_table_name(), get_role_oid_or_public(), NameStr, PG_GETARG_NAME, PG_GETARG_TEXT_P, PG_RETURN_BOOL, and PG_RETURN_NULL.

{
    Name        rolename = PG_GETARG_NAME(0);
    text       *tablename = PG_GETARG_TEXT_P(1);
    text       *column = PG_GETARG_TEXT_P(2);
    text       *priv_type_text = PG_GETARG_TEXT_P(3);
    Oid         roleid;
    Oid         tableoid;
    AttrNumber  colattnum;
    AclMode     mode;
    int         privresult;

    roleid = get_role_oid_or_public(NameStr(*rolename));
    tableoid = convert_table_name(tablename);
    colattnum = convert_column_name(tableoid, column);
    mode = convert_column_priv_string(priv_type_text);

    privresult = column_privilege_check(tableoid, colattnum, roleid, mode);
    if (privresult < 0)
        PG_RETURN_NULL();
    PG_RETURN_BOOL(privresult);
}

Datum has_database_privilege_id ( PG_FUNCTION_ARGS   ) 

Definition at line 2962 of file acl.c.

References ACLCHECK_OK, convert_database_priv_string(), DATABASEOID, GetUserId(), ObjectIdGetDatum, pg_database_aclcheck(), PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, PG_RETURN_NULL, and SearchSysCacheExists1.

{
    Oid         databaseoid = PG_GETARG_OID(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    mode = convert_database_priv_string(priv_type_text);

    if (!SearchSysCacheExists1(DATABASEOID, ObjectIdGetDatum(databaseoid)))
        PG_RETURN_NULL();

    aclresult = pg_database_aclcheck(databaseoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_database_privilege_id_id ( PG_FUNCTION_ARGS   ) 

Definition at line 3010 of file acl.c.

References ACLCHECK_OK, convert_database_priv_string(), DATABASEOID, ObjectIdGetDatum, pg_database_aclcheck(), PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, PG_RETURN_NULL, and SearchSysCacheExists1.

{
    Oid         roleid = PG_GETARG_OID(0);
    Oid         databaseoid = PG_GETARG_OID(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    AclMode     mode;
    AclResult   aclresult;

    mode = convert_database_priv_string(priv_type_text);

    if (!SearchSysCacheExists1(DATABASEOID, ObjectIdGetDatum(databaseoid)))
        PG_RETURN_NULL();

    aclresult = pg_database_aclcheck(databaseoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_database_privilege_id_name ( PG_FUNCTION_ARGS   ) 

Definition at line 2987 of file acl.c.

References ACLCHECK_OK, convert_database_name(), convert_database_priv_string(), pg_database_aclcheck(), PG_GETARG_OID, PG_GETARG_TEXT_P, and PG_RETURN_BOOL.

{
    Oid         roleid = PG_GETARG_OID(0);
    text       *databasename = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         databaseoid;
    AclMode     mode;
    AclResult   aclresult;

    databaseoid = convert_database_name(databasename);
    mode = convert_database_priv_string(priv_type_text);

    aclresult = pg_database_aclcheck(databaseoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_database_privilege_name ( PG_FUNCTION_ARGS   ) 

Definition at line 2911 of file acl.c.

References ACLCHECK_OK, convert_database_name(), convert_database_priv_string(), GetUserId(), pg_database_aclcheck(), PG_GETARG_TEXT_P, and PG_RETURN_BOOL.

{
    text       *databasename = PG_GETARG_TEXT_P(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    Oid         databaseoid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    databaseoid = convert_database_name(databasename);
    mode = convert_database_priv_string(priv_type_text);

    aclresult = pg_database_aclcheck(databaseoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_database_privilege_name_id ( PG_FUNCTION_ARGS   ) 
Datum has_database_privilege_name_name ( PG_FUNCTION_ARGS   ) 

Definition at line 2885 of file acl.c.

References ACLCHECK_OK, convert_database_name(), convert_database_priv_string(), get_role_oid_or_public(), NameStr, pg_database_aclcheck(), PG_GETARG_NAME, PG_GETARG_TEXT_P, PG_RETURN_BOOL, and username.

{
    Name        username = PG_GETARG_NAME(0);
    text       *databasename = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleid;
    Oid         databaseoid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = get_role_oid_or_public(NameStr(*username));
    databaseoid = convert_database_name(databasename);
    mode = convert_database_priv_string(priv_type_text);

    aclresult = pg_database_aclcheck(databaseoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_foreign_data_wrapper_privilege_id ( PG_FUNCTION_ARGS   ) 

Definition at line 3157 of file acl.c.

References ACLCHECK_OK, convert_foreign_data_wrapper_priv_string(), GetUserId(), pg_foreign_data_wrapper_aclcheck(), PG_GETARG_OID, PG_GETARG_TEXT_P, and PG_RETURN_BOOL.

{
    Oid         fdwid = PG_GETARG_OID(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    mode = convert_foreign_data_wrapper_priv_string(priv_type_text);

    aclresult = pg_foreign_data_wrapper_aclcheck(fdwid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_foreign_data_wrapper_privilege_id_id ( PG_FUNCTION_ARGS   ) 

Definition at line 3202 of file acl.c.

References ACLCHECK_OK, convert_foreign_data_wrapper_priv_string(), pg_foreign_data_wrapper_aclcheck(), PG_GETARG_OID, PG_GETARG_TEXT_P, and PG_RETURN_BOOL.

{
    Oid         roleid = PG_GETARG_OID(0);
    Oid         fdwid = PG_GETARG_OID(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    AclMode     mode;
    AclResult   aclresult;

    mode = convert_foreign_data_wrapper_priv_string(priv_type_text);

    aclresult = pg_foreign_data_wrapper_aclcheck(fdwid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_foreign_data_wrapper_privilege_id_name ( PG_FUNCTION_ARGS   ) 
Datum has_foreign_data_wrapper_privilege_name ( PG_FUNCTION_ARGS   ) 

Definition at line 3109 of file acl.c.

References ACLCHECK_OK, convert_foreign_data_wrapper_name(), convert_foreign_data_wrapper_priv_string(), GetUserId(), pg_foreign_data_wrapper_aclcheck(), PG_GETARG_TEXT_P, and PG_RETURN_BOOL.

{
    text       *fdwname = PG_GETARG_TEXT_P(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    Oid         fdwid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    fdwid = convert_foreign_data_wrapper_name(fdwname);
    mode = convert_foreign_data_wrapper_priv_string(priv_type_text);

    aclresult = pg_foreign_data_wrapper_aclcheck(fdwid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_foreign_data_wrapper_privilege_name_id ( PG_FUNCTION_ARGS   ) 
Datum has_foreign_data_wrapper_privilege_name_name ( PG_FUNCTION_ARGS   ) 
Datum has_function_privilege_id ( PG_FUNCTION_ARGS   ) 

Definition at line 3342 of file acl.c.

References ACLCHECK_OK, convert_function_priv_string(), GetUserId(), ObjectIdGetDatum, PG_GETARG_OID, PG_GETARG_TEXT_P, pg_proc_aclcheck(), PG_RETURN_BOOL, PG_RETURN_NULL, PROCOID, and SearchSysCacheExists1.

{
    Oid         functionoid = PG_GETARG_OID(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    mode = convert_function_priv_string(priv_type_text);

    if (!SearchSysCacheExists1(PROCOID, ObjectIdGetDatum(functionoid)))
        PG_RETURN_NULL();

    aclresult = pg_proc_aclcheck(functionoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_function_privilege_id_id ( PG_FUNCTION_ARGS   ) 

Definition at line 3390 of file acl.c.

References ACLCHECK_OK, convert_function_priv_string(), ObjectIdGetDatum, PG_GETARG_OID, PG_GETARG_TEXT_P, pg_proc_aclcheck(), PG_RETURN_BOOL, PG_RETURN_NULL, PROCOID, and SearchSysCacheExists1.

{
    Oid         roleid = PG_GETARG_OID(0);
    Oid         functionoid = PG_GETARG_OID(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    AclMode     mode;
    AclResult   aclresult;

    mode = convert_function_priv_string(priv_type_text);

    if (!SearchSysCacheExists1(PROCOID, ObjectIdGetDatum(functionoid)))
        PG_RETURN_NULL();

    aclresult = pg_proc_aclcheck(functionoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_function_privilege_id_name ( PG_FUNCTION_ARGS   ) 

Definition at line 3367 of file acl.c.

References ACLCHECK_OK, convert_function_name(), convert_function_priv_string(), PG_GETARG_OID, PG_GETARG_TEXT_P, pg_proc_aclcheck(), and PG_RETURN_BOOL.

{
    Oid         roleid = PG_GETARG_OID(0);
    text       *functionname = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         functionoid;
    AclMode     mode;
    AclResult   aclresult;

    functionoid = convert_function_name(functionname);
    mode = convert_function_priv_string(priv_type_text);

    aclresult = pg_proc_aclcheck(functionoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_function_privilege_name ( PG_FUNCTION_ARGS   ) 

Definition at line 3291 of file acl.c.

References ACLCHECK_OK, convert_function_name(), convert_function_priv_string(), GetUserId(), PG_GETARG_TEXT_P, pg_proc_aclcheck(), and PG_RETURN_BOOL.

{
    text       *functionname = PG_GETARG_TEXT_P(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    Oid         functionoid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    functionoid = convert_function_name(functionname);
    mode = convert_function_priv_string(priv_type_text);

    aclresult = pg_proc_aclcheck(functionoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_function_privilege_name_id ( PG_FUNCTION_ARGS   ) 
Datum has_function_privilege_name_name ( PG_FUNCTION_ARGS   ) 

Definition at line 3265 of file acl.c.

References ACLCHECK_OK, convert_function_name(), convert_function_priv_string(), get_role_oid_or_public(), NameStr, PG_GETARG_NAME, PG_GETARG_TEXT_P, pg_proc_aclcheck(), PG_RETURN_BOOL, and username.

{
    Name        username = PG_GETARG_NAME(0);
    text       *functionname = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleid;
    Oid         functionoid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = get_role_oid_or_public(NameStr(*username));
    functionoid = convert_function_name(functionname);
    mode = convert_function_priv_string(priv_type_text);

    aclresult = pg_proc_aclcheck(functionoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_language_privilege_id ( PG_FUNCTION_ARGS   ) 

Definition at line 3542 of file acl.c.

References ACLCHECK_OK, convert_language_priv_string(), GetUserId(), LANGOID, ObjectIdGetDatum, PG_GETARG_OID, PG_GETARG_TEXT_P, pg_language_aclcheck(), PG_RETURN_BOOL, PG_RETURN_NULL, and SearchSysCacheExists1.

{
    Oid         languageoid = PG_GETARG_OID(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    mode = convert_language_priv_string(priv_type_text);

    if (!SearchSysCacheExists1(LANGOID, ObjectIdGetDatum(languageoid)))
        PG_RETURN_NULL();

    aclresult = pg_language_aclcheck(languageoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_language_privilege_id_id ( PG_FUNCTION_ARGS   ) 

Definition at line 3590 of file acl.c.

References ACLCHECK_OK, convert_language_priv_string(), LANGOID, ObjectIdGetDatum, PG_GETARG_OID, PG_GETARG_TEXT_P, pg_language_aclcheck(), PG_RETURN_BOOL, PG_RETURN_NULL, and SearchSysCacheExists1.

{
    Oid         roleid = PG_GETARG_OID(0);
    Oid         languageoid = PG_GETARG_OID(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    AclMode     mode;
    AclResult   aclresult;

    mode = convert_language_priv_string(priv_type_text);

    if (!SearchSysCacheExists1(LANGOID, ObjectIdGetDatum(languageoid)))
        PG_RETURN_NULL();

    aclresult = pg_language_aclcheck(languageoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_language_privilege_id_name ( PG_FUNCTION_ARGS   ) 

Definition at line 3567 of file acl.c.

References ACLCHECK_OK, convert_language_name(), convert_language_priv_string(), PG_GETARG_OID, PG_GETARG_TEXT_P, pg_language_aclcheck(), and PG_RETURN_BOOL.

{
    Oid         roleid = PG_GETARG_OID(0);
    text       *languagename = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         languageoid;
    AclMode     mode;
    AclResult   aclresult;

    languageoid = convert_language_name(languagename);
    mode = convert_language_priv_string(priv_type_text);

    aclresult = pg_language_aclcheck(languageoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_language_privilege_name ( PG_FUNCTION_ARGS   ) 

Definition at line 3491 of file acl.c.

References ACLCHECK_OK, convert_language_name(), convert_language_priv_string(), GetUserId(), PG_GETARG_TEXT_P, pg_language_aclcheck(), and PG_RETURN_BOOL.

{
    text       *languagename = PG_GETARG_TEXT_P(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    Oid         languageoid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    languageoid = convert_language_name(languagename);
    mode = convert_language_priv_string(priv_type_text);

    aclresult = pg_language_aclcheck(languageoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_language_privilege_name_id ( PG_FUNCTION_ARGS   ) 
Datum has_language_privilege_name_name ( PG_FUNCTION_ARGS   ) 

Definition at line 3465 of file acl.c.

References ACLCHECK_OK, convert_language_name(), convert_language_priv_string(), get_role_oid_or_public(), NameStr, PG_GETARG_NAME, PG_GETARG_TEXT_P, pg_language_aclcheck(), PG_RETURN_BOOL, and username.

{
    Name        username = PG_GETARG_NAME(0);
    text       *languagename = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleid;
    Oid         languageoid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = get_role_oid_or_public(NameStr(*username));
    languageoid = convert_language_name(languagename);
    mode = convert_language_priv_string(priv_type_text);

    aclresult = pg_language_aclcheck(languageoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_schema_privilege_id ( PG_FUNCTION_ARGS   ) 

Definition at line 3733 of file acl.c.

References ACLCHECK_OK, convert_schema_priv_string(), GetUserId(), NAMESPACEOID, ObjectIdGetDatum, PG_GETARG_OID, PG_GETARG_TEXT_P, pg_namespace_aclcheck(), PG_RETURN_BOOL, PG_RETURN_NULL, and SearchSysCacheExists1.

{
    Oid         schemaoid = PG_GETARG_OID(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    mode = convert_schema_priv_string(priv_type_text);

    if (!SearchSysCacheExists1(NAMESPACEOID, ObjectIdGetDatum(schemaoid)))
        PG_RETURN_NULL();

    aclresult = pg_namespace_aclcheck(schemaoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_schema_privilege_id_id ( PG_FUNCTION_ARGS   ) 
Datum has_schema_privilege_id_name ( PG_FUNCTION_ARGS   ) 

Definition at line 3758 of file acl.c.

References ACLCHECK_OK, convert_schema_name(), convert_schema_priv_string(), PG_GETARG_OID, PG_GETARG_TEXT_P, pg_namespace_aclcheck(), and PG_RETURN_BOOL.

{
    Oid         roleid = PG_GETARG_OID(0);
    text       *schemaname = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         schemaoid;
    AclMode     mode;
    AclResult   aclresult;

    schemaoid = convert_schema_name(schemaname);
    mode = convert_schema_priv_string(priv_type_text);

    aclresult = pg_namespace_aclcheck(schemaoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_schema_privilege_name ( PG_FUNCTION_ARGS   ) 

Definition at line 3682 of file acl.c.

References ACLCHECK_OK, convert_schema_name(), convert_schema_priv_string(), GetUserId(), PG_GETARG_TEXT_P, pg_namespace_aclcheck(), and PG_RETURN_BOOL.

{
    text       *schemaname = PG_GETARG_TEXT_P(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    Oid         schemaoid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    schemaoid = convert_schema_name(schemaname);
    mode = convert_schema_priv_string(priv_type_text);

    aclresult = pg_namespace_aclcheck(schemaoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_schema_privilege_name_id ( PG_FUNCTION_ARGS   ) 
Datum has_schema_privilege_name_name ( PG_FUNCTION_ARGS   ) 

Definition at line 3656 of file acl.c.

References ACLCHECK_OK, convert_schema_name(), convert_schema_priv_string(), get_role_oid_or_public(), NameStr, PG_GETARG_NAME, PG_GETARG_TEXT_P, pg_namespace_aclcheck(), PG_RETURN_BOOL, and username.

{
    Name        username = PG_GETARG_NAME(0);
    text       *schemaname = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleid;
    Oid         schemaoid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = get_role_oid_or_public(NameStr(*username));
    schemaoid = convert_schema_name(schemaname);
    mode = convert_schema_priv_string(priv_type_text);

    aclresult = pg_namespace_aclcheck(schemaoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_sequence_privilege_id ( PG_FUNCTION_ARGS   ) 

Definition at line 2153 of file acl.c.

References ACLCHECK_OK, convert_sequence_priv_string(), ereport, errcode(), errmsg(), ERROR, get_rel_name(), get_rel_relkind(), GetUserId(), pg_class_aclcheck(), PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, PG_RETURN_NULL, and RELKIND_SEQUENCE.

{
    Oid         sequenceoid = PG_GETARG_OID(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    AclMode     mode;
    AclResult   aclresult;
    char        relkind;

    roleid = GetUserId();
    mode = convert_sequence_priv_string(priv_type_text);
    relkind = get_rel_relkind(sequenceoid);
    if (relkind == '\0')
        PG_RETURN_NULL();
    else if (relkind != RELKIND_SEQUENCE)
        ereport(ERROR,
                (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                 errmsg("\"%s\" is not a sequence",
                        get_rel_name(sequenceoid))));

    aclresult = pg_class_aclcheck(sequenceoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_sequence_privilege_id_id ( PG_FUNCTION_ARGS   ) 

Definition at line 2212 of file acl.c.

References ACLCHECK_OK, convert_sequence_priv_string(), ereport, errcode(), errmsg(), ERROR, get_rel_name(), get_rel_relkind(), pg_class_aclcheck(), PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, PG_RETURN_NULL, and RELKIND_SEQUENCE.

{
    Oid         roleid = PG_GETARG_OID(0);
    Oid         sequenceoid = PG_GETARG_OID(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    AclMode     mode;
    AclResult   aclresult;
    char        relkind;

    mode = convert_sequence_priv_string(priv_type_text);
    relkind = get_rel_relkind(sequenceoid);
    if (relkind == '\0')
        PG_RETURN_NULL();
    else if (relkind != RELKIND_SEQUENCE)
        ereport(ERROR,
                (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                 errmsg("\"%s\" is not a sequence",
                        get_rel_name(sequenceoid))));

    aclresult = pg_class_aclcheck(sequenceoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_sequence_privilege_id_name ( PG_FUNCTION_ARGS   ) 

Definition at line 2184 of file acl.c.

References ACLCHECK_OK, convert_sequence_priv_string(), convert_table_name(), ereport, errcode(), errmsg(), ERROR, get_rel_relkind(), pg_class_aclcheck(), PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, RELKIND_SEQUENCE, and text_to_cstring().

{
    Oid         roleid = PG_GETARG_OID(0);
    text       *sequencename = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         sequenceoid;
    AclMode     mode;
    AclResult   aclresult;

    mode = convert_sequence_priv_string(priv_type_text);
    sequenceoid = convert_table_name(sequencename);
    if (get_rel_relkind(sequenceoid) != RELKIND_SEQUENCE)
        ereport(ERROR,
                (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                 errmsg("\"%s\" is not a sequence",
                        text_to_cstring(sequencename))));

    aclresult = pg_class_aclcheck(sequenceoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_sequence_privilege_name ( PG_FUNCTION_ARGS   ) 

Definition at line 2091 of file acl.c.

References ACLCHECK_OK, convert_sequence_priv_string(), convert_table_name(), ereport, errcode(), errmsg(), ERROR, get_rel_relkind(), GetUserId(), pg_class_aclcheck(), PG_GETARG_TEXT_P, PG_RETURN_BOOL, RELKIND_SEQUENCE, and text_to_cstring().

{
    text       *sequencename = PG_GETARG_TEXT_P(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    Oid         sequenceoid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    mode = convert_sequence_priv_string(priv_type_text);
    sequenceoid = convert_table_name(sequencename);
    if (get_rel_relkind(sequenceoid) != RELKIND_SEQUENCE)
        ereport(ERROR,
                (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                 errmsg("\"%s\" is not a sequence",
                        text_to_cstring(sequencename))));

    aclresult = pg_class_aclcheck(sequenceoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_sequence_privilege_name_id ( PG_FUNCTION_ARGS   ) 

Definition at line 2120 of file acl.c.

References ACLCHECK_OK, convert_sequence_priv_string(), ereport, errcode(), errmsg(), ERROR, get_rel_name(), get_rel_relkind(), get_role_oid_or_public(), NameStr, pg_class_aclcheck(), PG_GETARG_NAME, PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, PG_RETURN_NULL, RELKIND_SEQUENCE, and username.

{
    Name        username = PG_GETARG_NAME(0);
    Oid         sequenceoid = PG_GETARG_OID(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleid;
    AclMode     mode;
    AclResult   aclresult;
    char        relkind;

    roleid = get_role_oid_or_public(NameStr(*username));
    mode = convert_sequence_priv_string(priv_type_text);
    relkind = get_rel_relkind(sequenceoid);
    if (relkind == '\0')
        PG_RETURN_NULL();
    else if (relkind != RELKIND_SEQUENCE)
        ereport(ERROR,
                (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                 errmsg("\"%s\" is not a sequence",
                        get_rel_name(sequenceoid))));

    aclresult = pg_class_aclcheck(sequenceoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_sequence_privilege_name_name ( PG_FUNCTION_ARGS   ) 

Definition at line 2060 of file acl.c.

References ACLCHECK_OK, convert_sequence_priv_string(), convert_table_name(), ereport, errcode(), errmsg(), ERROR, get_rel_relkind(), get_role_oid_or_public(), NameStr, pg_class_aclcheck(), PG_GETARG_NAME, PG_GETARG_TEXT_P, PG_RETURN_BOOL, RELKIND_SEQUENCE, and text_to_cstring().

{
    Name        rolename = PG_GETARG_NAME(0);
    text       *sequencename = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleid;
    Oid         sequenceoid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = get_role_oid_or_public(NameStr(*rolename));
    mode = convert_sequence_priv_string(priv_type_text);
    sequenceoid = convert_table_name(sequencename);
    if (get_rel_relkind(sequenceoid) != RELKIND_SEQUENCE)
        ereport(ERROR,
                (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                 errmsg("\"%s\" is not a sequence",
                        text_to_cstring(sequencename))));

    aclresult = pg_class_aclcheck(sequenceoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_server_privilege_id ( PG_FUNCTION_ARGS   ) 

Definition at line 3923 of file acl.c.

References ACLCHECK_OK, convert_server_priv_string(), GetUserId(), pg_foreign_server_aclcheck(), PG_GETARG_OID, PG_GETARG_TEXT_P, and PG_RETURN_BOOL.

{
    Oid         serverid = PG_GETARG_OID(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    mode = convert_server_priv_string(priv_type_text);

    aclresult = pg_foreign_server_aclcheck(serverid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_server_privilege_id_id ( PG_FUNCTION_ARGS   ) 

Definition at line 3968 of file acl.c.

References ACLCHECK_OK, convert_server_priv_string(), pg_foreign_server_aclcheck(), PG_GETARG_OID, PG_GETARG_TEXT_P, and PG_RETURN_BOOL.

{
    Oid         roleid = PG_GETARG_OID(0);
    Oid         serverid = PG_GETARG_OID(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    AclMode     mode;
    AclResult   aclresult;

    mode = convert_server_priv_string(priv_type_text);

    aclresult = pg_foreign_server_aclcheck(serverid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_server_privilege_id_name ( PG_FUNCTION_ARGS   ) 

Definition at line 3945 of file acl.c.

References ACLCHECK_OK, convert_server_name(), convert_server_priv_string(), pg_foreign_server_aclcheck(), PG_GETARG_OID, PG_GETARG_TEXT_P, and PG_RETURN_BOOL.

{
    Oid         roleid = PG_GETARG_OID(0);
    text       *servername = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         serverid;
    AclMode     mode;
    AclResult   aclresult;

    serverid = convert_server_name(servername);
    mode = convert_server_priv_string(priv_type_text);

    aclresult = pg_foreign_server_aclcheck(serverid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_server_privilege_name ( PG_FUNCTION_ARGS   ) 

Definition at line 3875 of file acl.c.

References ACLCHECK_OK, convert_server_name(), convert_server_priv_string(), GetUserId(), pg_foreign_server_aclcheck(), PG_GETARG_TEXT_P, and PG_RETURN_BOOL.

{
    text       *servername = PG_GETARG_TEXT_P(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    Oid         serverid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    serverid = convert_server_name(servername);
    mode = convert_server_priv_string(priv_type_text);

    aclresult = pg_foreign_server_aclcheck(serverid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_server_privilege_name_id ( PG_FUNCTION_ARGS   ) 

Definition at line 3899 of file acl.c.

References ACLCHECK_OK, convert_server_priv_string(), get_role_oid_or_public(), NameStr, pg_foreign_server_aclcheck(), PG_GETARG_NAME, PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, and username.

{
    Name        username = PG_GETARG_NAME(0);
    Oid         serverid = PG_GETARG_OID(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = get_role_oid_or_public(NameStr(*username));
    mode = convert_server_priv_string(priv_type_text);

    aclresult = pg_foreign_server_aclcheck(serverid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_server_privilege_name_name ( PG_FUNCTION_ARGS   ) 

Definition at line 3849 of file acl.c.

References ACLCHECK_OK, convert_server_name(), convert_server_priv_string(), get_role_oid_or_public(), NameStr, pg_foreign_server_aclcheck(), PG_GETARG_NAME, PG_GETARG_TEXT_P, PG_RETURN_BOOL, and username.

{
    Name        username = PG_GETARG_NAME(0);
    text       *servername = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleid;
    Oid         serverid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = get_role_oid_or_public(NameStr(*username));
    serverid = convert_server_name(servername);
    mode = convert_server_priv_string(priv_type_text);

    aclresult = pg_foreign_server_aclcheck(serverid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_table_privilege_id ( PG_FUNCTION_ARGS   ) 

Definition at line 1929 of file acl.c.

References ACLCHECK_OK, convert_table_priv_string(), GetUserId(), ObjectIdGetDatum, pg_class_aclcheck(), PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, PG_RETURN_NULL, RELOID, and SearchSysCacheExists1.

{
    Oid         tableoid = PG_GETARG_OID(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    mode = convert_table_priv_string(priv_type_text);

    if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(tableoid)))
        PG_RETURN_NULL();

    aclresult = pg_class_aclcheck(tableoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_table_privilege_id_id ( PG_FUNCTION_ARGS   ) 

Definition at line 1977 of file acl.c.

References ACLCHECK_OK, convert_table_priv_string(), ObjectIdGetDatum, pg_class_aclcheck(), PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, PG_RETURN_NULL, RELOID, and SearchSysCacheExists1.

{
    Oid         roleid = PG_GETARG_OID(0);
    Oid         tableoid = PG_GETARG_OID(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    AclMode     mode;
    AclResult   aclresult;

    mode = convert_table_priv_string(priv_type_text);

    if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(tableoid)))
        PG_RETURN_NULL();

    aclresult = pg_class_aclcheck(tableoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_table_privilege_id_name ( PG_FUNCTION_ARGS   ) 

Definition at line 1954 of file acl.c.

References ACLCHECK_OK, convert_table_name(), convert_table_priv_string(), pg_class_aclcheck(), PG_GETARG_OID, PG_GETARG_TEXT_P, and PG_RETURN_BOOL.

{
    Oid         roleid = PG_GETARG_OID(0);
    text       *tablename = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         tableoid;
    AclMode     mode;
    AclResult   aclresult;

    tableoid = convert_table_name(tablename);
    mode = convert_table_priv_string(priv_type_text);

    aclresult = pg_class_aclcheck(tableoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_table_privilege_name ( PG_FUNCTION_ARGS   ) 

Definition at line 1878 of file acl.c.

References ACLCHECK_OK, convert_table_name(), convert_table_priv_string(), GetUserId(), pg_class_aclcheck(), PG_GETARG_TEXT_P, and PG_RETURN_BOOL.

{
    text       *tablename = PG_GETARG_TEXT_P(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    Oid         tableoid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    tableoid = convert_table_name(tablename);
    mode = convert_table_priv_string(priv_type_text);

    aclresult = pg_class_aclcheck(tableoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_table_privilege_name_id ( PG_FUNCTION_ARGS   ) 
Datum has_table_privilege_name_name ( PG_FUNCTION_ARGS   ) 

Definition at line 1852 of file acl.c.

References ACLCHECK_OK, convert_table_name(), convert_table_priv_string(), get_role_oid_or_public(), NameStr, pg_class_aclcheck(), PG_GETARG_NAME, PG_GETARG_TEXT_P, and PG_RETURN_BOOL.

{
    Name        rolename = PG_GETARG_NAME(0);
    text       *tablename = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleid;
    Oid         tableoid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = get_role_oid_or_public(NameStr(*rolename));
    tableoid = convert_table_name(tablename);
    mode = convert_table_priv_string(priv_type_text);

    aclresult = pg_class_aclcheck(tableoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_tablespace_privilege_id ( PG_FUNCTION_ARGS   ) 

Definition at line 4105 of file acl.c.

References ACLCHECK_OK, convert_tablespace_priv_string(), GetUserId(), PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, and pg_tablespace_aclcheck().

{
    Oid         tablespaceoid = PG_GETARG_OID(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    mode = convert_tablespace_priv_string(priv_type_text);

    aclresult = pg_tablespace_aclcheck(tablespaceoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_tablespace_privilege_id_id ( PG_FUNCTION_ARGS   ) 

Definition at line 4150 of file acl.c.

References ACLCHECK_OK, convert_tablespace_priv_string(), PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, and pg_tablespace_aclcheck().

{
    Oid         roleid = PG_GETARG_OID(0);
    Oid         tablespaceoid = PG_GETARG_OID(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    AclMode     mode;
    AclResult   aclresult;

    mode = convert_tablespace_priv_string(priv_type_text);

    aclresult = pg_tablespace_aclcheck(tablespaceoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_tablespace_privilege_id_name ( PG_FUNCTION_ARGS   ) 

Definition at line 4127 of file acl.c.

References ACLCHECK_OK, convert_tablespace_name(), convert_tablespace_priv_string(), PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, and pg_tablespace_aclcheck().

{
    Oid         roleid = PG_GETARG_OID(0);
    text       *tablespacename = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         tablespaceoid;
    AclMode     mode;
    AclResult   aclresult;

    tablespaceoid = convert_tablespace_name(tablespacename);
    mode = convert_tablespace_priv_string(priv_type_text);

    aclresult = pg_tablespace_aclcheck(tablespaceoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_tablespace_privilege_name ( PG_FUNCTION_ARGS   ) 

Definition at line 4057 of file acl.c.

References ACLCHECK_OK, convert_tablespace_name(), convert_tablespace_priv_string(), GetUserId(), PG_GETARG_TEXT_P, PG_RETURN_BOOL, and pg_tablespace_aclcheck().

{
    text       *tablespacename = PG_GETARG_TEXT_P(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    Oid         tablespaceoid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    tablespaceoid = convert_tablespace_name(tablespacename);
    mode = convert_tablespace_priv_string(priv_type_text);

    aclresult = pg_tablespace_aclcheck(tablespaceoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_tablespace_privilege_name_id ( PG_FUNCTION_ARGS   ) 

Definition at line 4081 of file acl.c.

References ACLCHECK_OK, convert_tablespace_priv_string(), get_role_oid_or_public(), NameStr, PG_GETARG_NAME, PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, pg_tablespace_aclcheck(), and username.

{
    Name        username = PG_GETARG_NAME(0);
    Oid         tablespaceoid = PG_GETARG_OID(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = get_role_oid_or_public(NameStr(*username));
    mode = convert_tablespace_priv_string(priv_type_text);

    aclresult = pg_tablespace_aclcheck(tablespaceoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_tablespace_privilege_name_name ( PG_FUNCTION_ARGS   ) 

Definition at line 4031 of file acl.c.

References ACLCHECK_OK, convert_tablespace_name(), convert_tablespace_priv_string(), get_role_oid_or_public(), NameStr, PG_GETARG_NAME, PG_GETARG_TEXT_P, PG_RETURN_BOOL, pg_tablespace_aclcheck(), and username.

{
    Name        username = PG_GETARG_NAME(0);
    text       *tablespacename = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleid;
    Oid         tablespaceoid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = get_role_oid_or_public(NameStr(*username));
    tablespaceoid = convert_tablespace_name(tablespacename);
    mode = convert_tablespace_priv_string(priv_type_text);

    aclresult = pg_tablespace_aclcheck(tablespaceoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_type_privilege_id ( PG_FUNCTION_ARGS   ) 

Definition at line 4289 of file acl.c.

References ACLCHECK_OK, convert_type_priv_string(), GetUserId(), ObjectIdGetDatum, PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, PG_RETURN_NULL, pg_type_aclcheck(), SearchSysCacheExists1, and TYPEOID.

{
    Oid         typeoid = PG_GETARG_OID(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    mode = convert_type_priv_string(priv_type_text);

    if (!SearchSysCacheExists1(TYPEOID, ObjectIdGetDatum(typeoid)))
        PG_RETURN_NULL();

    aclresult = pg_type_aclcheck(typeoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_type_privilege_id_id ( PG_FUNCTION_ARGS   ) 

Definition at line 4337 of file acl.c.

References ACLCHECK_OK, convert_type_priv_string(), ObjectIdGetDatum, PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, PG_RETURN_NULL, pg_type_aclcheck(), SearchSysCacheExists1, and TYPEOID.

{
    Oid         roleid = PG_GETARG_OID(0);
    Oid         typeoid = PG_GETARG_OID(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    AclMode     mode;
    AclResult   aclresult;

    mode = convert_type_priv_string(priv_type_text);

    if (!SearchSysCacheExists1(TYPEOID, ObjectIdGetDatum(typeoid)))
        PG_RETURN_NULL();

    aclresult = pg_type_aclcheck(typeoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_type_privilege_id_name ( PG_FUNCTION_ARGS   ) 

Definition at line 4314 of file acl.c.

References ACLCHECK_OK, convert_type_name(), convert_type_priv_string(), PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, and pg_type_aclcheck().

{
    Oid         roleid = PG_GETARG_OID(0);
    text       *typename = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         typeoid;
    AclMode     mode;
    AclResult   aclresult;

    typeoid = convert_type_name(typename);
    mode = convert_type_priv_string(priv_type_text);

    aclresult = pg_type_aclcheck(typeoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_type_privilege_name ( PG_FUNCTION_ARGS   ) 

Definition at line 4238 of file acl.c.

References ACLCHECK_OK, convert_type_name(), convert_type_priv_string(), GetUserId(), PG_GETARG_TEXT_P, PG_RETURN_BOOL, and pg_type_aclcheck().

{
    text       *typename = PG_GETARG_TEXT_P(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    Oid         typeoid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    typeoid = convert_type_name(typename);
    mode = convert_type_priv_string(priv_type_text);

    aclresult = pg_type_aclcheck(typeoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum has_type_privilege_name_id ( PG_FUNCTION_ARGS   ) 
Datum has_type_privilege_name_name ( PG_FUNCTION_ARGS   ) 

Definition at line 4212 of file acl.c.

References ACLCHECK_OK, convert_type_name(), convert_type_priv_string(), get_role_oid_or_public(), NameStr, PG_GETARG_NAME, PG_GETARG_TEXT_P, PG_RETURN_BOOL, pg_type_aclcheck(), and username.

{
    Name        username = PG_GETARG_NAME(0);
    text       *typename = PG_GETARG_TEXT_P(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleid;
    Oid         typeoid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = get_role_oid_or_public(NameStr(*username));
    typeoid = convert_type_name(typename);
    mode = convert_type_priv_string(priv_type_text);

    aclresult = pg_type_aclcheck(typeoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum hash_numeric ( PG_FUNCTION_ARGS   ) 

Definition at line 1458 of file numeric.c.

References Assert, digits, hash_any(), i, NUMERIC_DIGITS, NUMERIC_IS_NAN, NUMERIC_NDIGITS, NUMERIC_WEIGHT, PG_GETARG_NUMERIC, PG_RETURN_DATUM, and PG_RETURN_UINT32.

{
    Numeric     key = PG_GETARG_NUMERIC(0);
    Datum       digit_hash;
    Datum       result;
    int         weight;
    int         start_offset;
    int         end_offset;
    int         i;
    int         hash_len;
    NumericDigit *digits;

    /* If it's NaN, don't try to hash the rest of the fields */
    if (NUMERIC_IS_NAN(key))
        PG_RETURN_UINT32(0);

    weight = NUMERIC_WEIGHT(key);
    start_offset = 0;
    end_offset = 0;

    /*
     * Omit any leading or trailing zeros from the input to the hash. The
     * numeric implementation *should* guarantee that leading and trailing
     * zeros are suppressed, but we're paranoid. Note that we measure the
     * starting and ending offsets in units of NumericDigits, not bytes.
     */
    digits = NUMERIC_DIGITS(key);
    for (i = 0; i < NUMERIC_NDIGITS(key); i++)
    {
        if (digits[i] != (NumericDigit) 0)
            break;

        start_offset++;

        /*
         * The weight is effectively the # of digits before the decimal point,
         * so decrement it for each leading zero we skip.
         */
        weight--;
    }

    /*
     * If there are no non-zero digits, then the value of the number is zero,
     * regardless of any other fields.
     */
    if (NUMERIC_NDIGITS(key) == start_offset)
        PG_RETURN_UINT32(-1);

    for (i = NUMERIC_NDIGITS(key) - 1; i >= 0; i--)
    {
        if (digits[i] != (NumericDigit) 0)
            break;

        end_offset++;
    }

    /* If we get here, there should be at least one non-zero digit */
    Assert(start_offset + end_offset < NUMERIC_NDIGITS(key));

    /*
     * Note that we don't hash on the Numeric's scale, since two numerics can
     * compare equal but have different scales. We also don't hash on the
     * sign, although we could: since a sign difference implies inequality,
     * this shouldn't affect correctness.
     */
    hash_len = NUMERIC_NDIGITS(key) - start_offset - end_offset;
    digit_hash = hash_any((unsigned char *) (NUMERIC_DIGITS(key) + start_offset),
                          hash_len * sizeof(NumericDigit));

    /* Mix in the weight, via XOR */
    result = digit_hash ^ weight;

    PG_RETURN_DATUM(result);
}

Datum hashbpchar ( PG_FUNCTION_ARGS   ) 

Definition at line 907 of file varchar.c.

References bcTruelen(), hash_any(), PG_FREE_IF_COPY, PG_GETARG_BPCHAR_PP, and VARDATA_ANY.

{
    BpChar     *key = PG_GETARG_BPCHAR_PP(0);
    char       *keydata;
    int         keylen;
    Datum       result;

    keydata = VARDATA_ANY(key);
    keylen = bcTruelen(key);

    result = hash_any((unsigned char *) keydata, keylen);

    /* Avoid leaking memory for toasted inputs */
    PG_FREE_IF_COPY(key, 0);

    return result;
}

Datum hashinet ( PG_FUNCTION_ARGS   ) 

Definition at line 527 of file network.c.

References hash_any(), ip_addrsize(), PG_GETARG_INET_PP, and VARDATA_ANY.

{
    inet       *addr = PG_GETARG_INET_PP(0);
    int         addrsize = ip_addrsize(addr);

    /* XXX this assumes there are no pad bytes in the data structure */
    return hash_any((unsigned char *) VARDATA_ANY(addr), addrsize + 2);
}

Datum hashmacaddr ( PG_FUNCTION_ARGS   ) 

Definition at line 237 of file mac.c.

References hash_any(), and PG_GETARG_MACADDR_P.

{
    macaddr    *key = PG_GETARG_MACADDR_P(0);

    return hash_any((unsigned char *) key, sizeof(macaddr));
}

unsigned hex_decode ( const char *  src,
unsigned  len,
char *  dst 
)

Definition at line 156 of file encode.c.

References ereport, errcode(), errmsg(), ERROR, and get_hex().

Referenced by byteain().

{
    const char *s,
               *srcend;
    char        v1,
                v2,
               *p;

    srcend = src + len;
    s = src;
    p = dst;
    while (s < srcend)
    {
        if (*s == ' ' || *s == '\n' || *s == '\t' || *s == '\r')
        {
            s++;
            continue;
        }
        v1 = get_hex(*s++) << 4;
        if (s >= srcend)
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                  errmsg("invalid hexadecimal data: odd number of digits")));

        v2 = get_hex(*s++);
        *p++ = v1 | v2;
    }

    return p - dst;
}

unsigned hex_encode ( const char *  src,
unsigned  len,
char *  dst 
)

Definition at line 126 of file encode.c.

References end, and hextbl.

Referenced by byteaout().

{
    const char *end = src + len;

    while (src < end)
    {
        *dst++ = hextbl[(*src >> 4) & 0xF];
        *dst++ = hextbl[*src & 0xF];
        src++;
    }
    return len * 2;
}

Datum i2tod ( PG_FUNCTION_ARGS   ) 

Definition at line 1202 of file float.c.

References PG_GETARG_INT16, and PG_RETURN_FLOAT8.

Datum i2tof ( PG_FUNCTION_ARGS   ) 

Definition at line 1260 of file float.c.

References PG_GETARG_INT16, and PG_RETURN_FLOAT4.

Datum i2toi4 ( PG_FUNCTION_ARGS   ) 

Definition at line 334 of file int.c.

References PG_GETARG_INT16, and PG_RETURN_INT32.

{
    int16       arg1 = PG_GETARG_INT16(0);

    PG_RETURN_INT32((int32) arg1);
}

Datum i4tochar ( PG_FUNCTION_ARGS   ) 

Definition at line 162 of file char.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT32, and PG_RETURN_CHAR.

{
    int32       arg1 = PG_GETARG_INT32(0);

    if (arg1 < SCHAR_MIN || arg1 > SCHAR_MAX)
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("\"char\" out of range")));

    PG_RETURN_CHAR((int8) arg1);
}

Datum i4tod ( PG_FUNCTION_ARGS   ) 

Definition at line 1190 of file float.c.

References PG_GETARG_INT32, and PG_RETURN_FLOAT8.

Datum i4tof ( PG_FUNCTION_ARGS   ) 

Definition at line 1248 of file float.c.

References PG_GETARG_INT32, and PG_RETURN_FLOAT4.

Datum i4toi2 ( PG_FUNCTION_ARGS   ) 

Definition at line 342 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT32, and PG_RETURN_INT16.

{
    int32       arg1 = PG_GETARG_INT32(0);

    if (arg1 < SHRT_MIN || arg1 > SHRT_MAX)
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("smallint out of range")));

    PG_RETURN_INT16((int16) arg1);
}

Datum inet_abbrev ( PG_FUNCTION_ARGS   ) 

Definition at line 652 of file network.c.

References cstring_to_text(), ereport, errcode(), errmsg(), ERROR, inet_net_ntop(), ip_addr, ip_bits, ip_family, NULL, PG_GETARG_INET_PP, and PG_RETURN_TEXT_P.

{
    inet       *ip = PG_GETARG_INET_PP(0);
    char       *dst;
    char        tmp[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255/128")];

    dst = inet_net_ntop(ip_family(ip), ip_addr(ip),
                        ip_bits(ip), tmp, sizeof(tmp));

    if (dst == NULL)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
                 errmsg("could not format inet value: %m")));

    PG_RETURN_TEXT_P(cstring_to_text(tmp));
}

char* inet_cidr_ntop ( int  af,
const void *  src,
int  bits,
char *  dst,
size_t  size 
)

Definition at line 57 of file inet_cidr_ntop.c.

References inet_cidr_ntop_ipv4(), inet_cidr_ntop_ipv6(), NULL, PGSQL_AF_INET, and PGSQL_AF_INET6.

Referenced by cidr_abbrev().

{
    switch (af)
    {
        case PGSQL_AF_INET:
            return (inet_cidr_ntop_ipv4(src, bits, dst, size));
        case PGSQL_AF_INET6:
            return (inet_cidr_ntop_ipv6(src, bits, dst, size));
        default:
            errno = EAFNOSUPPORT;
            return (NULL);
    }
}

Datum inet_client_addr ( PG_FUNCTION_ARGS   ) 

Definition at line 1070 of file network.c.

References SockAddr::addr, clean_ipv6_addr(), MyProcPort, network_in(), NI_NUMERICHOST, NI_NUMERICSERV, NULL, pg_getnameinfo_all(), PG_RETURN_INET_P, PG_RETURN_NULL, port, Port::raddr, and SockAddr::salen.

{
    Port       *port = MyProcPort;
    char        remote_host[NI_MAXHOST];
    int         ret;

    if (port == NULL)
        PG_RETURN_NULL();

    switch (port->raddr.addr.ss_family)
    {
        case AF_INET:
#ifdef HAVE_IPV6
        case AF_INET6:
#endif
            break;
        default:
            PG_RETURN_NULL();
    }

    remote_host[0] = '\0';

    ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
                             remote_host, sizeof(remote_host),
                             NULL, 0,
                             NI_NUMERICHOST | NI_NUMERICSERV);
    if (ret != 0)
        PG_RETURN_NULL();

    clean_ipv6_addr(port->raddr.addr.ss_family, remote_host);

    PG_RETURN_INET_P(network_in(remote_host, false));
}

Datum inet_client_port ( PG_FUNCTION_ARGS   ) 

Definition at line 1109 of file network.c.

References SockAddr::addr, CStringGetDatum, DirectFunctionCall1, int4in(), MyProcPort, NI_NUMERICHOST, NI_NUMERICSERV, NULL, pg_getnameinfo_all(), PG_RETURN_DATUM, PG_RETURN_NULL, port, Port::raddr, and SockAddr::salen.

{
    Port       *port = MyProcPort;
    char        remote_port[NI_MAXSERV];
    int         ret;

    if (port == NULL)
        PG_RETURN_NULL();

    switch (port->raddr.addr.ss_family)
    {
        case AF_INET:
#ifdef HAVE_IPV6
        case AF_INET6:
#endif
            break;
        default:
            PG_RETURN_NULL();
    }

    remote_port[0] = '\0';

    ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
                             NULL, 0,
                             remote_port, sizeof(remote_port),
                             NI_NUMERICHOST | NI_NUMERICSERV);
    if (ret != 0)
        PG_RETURN_NULL();

    PG_RETURN_DATUM(DirectFunctionCall1(int4in, CStringGetDatum(remote_port)));
}

Datum inet_in ( PG_FUNCTION_ARGS   ) 
int inet_net_pton ( int  af,
const char *  src,
void *  dst,
size_t  size 
)

Definition at line 63 of file inet_net_pton.c.

References inet_cidr_pton_ipv4(), inet_cidr_pton_ipv6(), inet_net_pton_ipv4(), inet_net_pton_ipv6(), PGSQL_AF_INET, and PGSQL_AF_INET6.

Referenced by network_in().

{
    switch (af)
    {
        case PGSQL_AF_INET:
            return size == -1 ?
                inet_net_pton_ipv4(src, dst) :
                inet_cidr_pton_ipv4(src, dst, size);
        case PGSQL_AF_INET6:
            return size == -1 ?
                inet_net_pton_ipv6(src, dst) :
                inet_cidr_pton_ipv6(src, dst, size);
        default:
            errno = EAFNOSUPPORT;
            return (-1);
    }
}

Datum inet_out ( PG_FUNCTION_ARGS   ) 

Definition at line 173 of file network.c.

References network_out(), PG_GETARG_INET_PP, and PG_RETURN_CSTRING.

{
    inet       *src = PG_GETARG_INET_PP(0);

    PG_RETURN_CSTRING(network_out(src, false));
}

Datum inet_recv ( PG_FUNCTION_ARGS   ) 
Datum inet_send ( PG_FUNCTION_ARGS   ) 

Definition at line 300 of file network.c.

References network_send(), PG_GETARG_INET_PP, and PG_RETURN_BYTEA_P.

{
    inet       *addr = PG_GETARG_INET_PP(0);

    PG_RETURN_BYTEA_P(network_send(addr, false));
}

Datum inet_server_addr ( PG_FUNCTION_ARGS   ) 

Definition at line 1146 of file network.c.

References SockAddr::addr, clean_ipv6_addr(), Port::laddr, MyProcPort, network_in(), NI_NUMERICHOST, NI_NUMERICSERV, NULL, pg_getnameinfo_all(), PG_RETURN_INET_P, PG_RETURN_NULL, port, and SockAddr::salen.

{
    Port       *port = MyProcPort;
    char        local_host[NI_MAXHOST];
    int         ret;

    if (port == NULL)
        PG_RETURN_NULL();

    switch (port->laddr.addr.ss_family)
    {
        case AF_INET:
#ifdef HAVE_IPV6
        case AF_INET6:
#endif
            break;
        default:
            PG_RETURN_NULL();
    }

    local_host[0] = '\0';

    ret = pg_getnameinfo_all(&port->laddr.addr, port->laddr.salen,
                             local_host, sizeof(local_host),
                             NULL, 0,
                             NI_NUMERICHOST | NI_NUMERICSERV);
    if (ret != 0)
        PG_RETURN_NULL();

    clean_ipv6_addr(port->laddr.addr.ss_family, local_host);

    PG_RETURN_INET_P(network_in(local_host, false));
}

Datum inet_server_port ( PG_FUNCTION_ARGS   ) 

Definition at line 1185 of file network.c.

References SockAddr::addr, CStringGetDatum, DirectFunctionCall1, int4in(), Port::laddr, MyProcPort, NI_NUMERICHOST, NI_NUMERICSERV, NULL, pg_getnameinfo_all(), PG_RETURN_DATUM, PG_RETURN_NULL, port, and SockAddr::salen.

{
    Port       *port = MyProcPort;
    char        local_port[NI_MAXSERV];
    int         ret;

    if (port == NULL)
        PG_RETURN_NULL();

    switch (port->laddr.addr.ss_family)
    {
        case AF_INET:
#ifdef HAVE_IPV6
        case AF_INET6:
#endif
            break;
        default:
            PG_RETURN_NULL();
    }

    local_port[0] = '\0';

    ret = pg_getnameinfo_all(&port->laddr.addr, port->laddr.salen,
                             NULL, 0,
                             local_port, sizeof(local_port),
                             NI_NUMERICHOST | NI_NUMERICSERV);
    if (ret != 0)
        PG_RETURN_NULL();

    PG_RETURN_DATUM(DirectFunctionCall1(int4in, CStringGetDatum(local_port)));
}

Datum inet_set_masklen ( PG_FUNCTION_ARGS   ) 

Definition at line 358 of file network.c.

References ereport, errcode(), errmsg(), ERROR, ip_bits, ip_maxbits, palloc(), PG_GETARG_INET_PP, PG_GETARG_INT32, PG_RETURN_INET_P, and VARSIZE_ANY.

Referenced by network_scan_last().

{
    inet       *src = PG_GETARG_INET_PP(0);
    int         bits = PG_GETARG_INT32(1);
    inet       *dst;

    if (bits == -1)
        bits = ip_maxbits(src);

    if ((bits < 0) || (bits > ip_maxbits(src)))
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("invalid mask length: %d", bits)));

    /* clone the original data */
    dst = (inet *) palloc(VARSIZE_ANY(src));
    memcpy(dst, src, VARSIZE_ANY(src));

    ip_bits(dst) = bits;

    PG_RETURN_INET_P(dst);
}

Datum inet_to_cidr ( PG_FUNCTION_ARGS   ) 

Definition at line 317 of file network.c.

References elog, ERROR, ip_addr, ip_addrsize(), ip_bits, ip_maxbits, palloc(), PG_GETARG_INET_PP, PG_RETURN_INET_P, and VARSIZE_ANY.

{
    inet       *src = PG_GETARG_INET_PP(0);
    inet       *dst;
    int         bits;
    int         byte;
    int         nbits;
    int         maxbytes;

    bits = ip_bits(src);

    /* safety check */
    if ((bits < 0) || (bits > ip_maxbits(src)))
        elog(ERROR, "invalid inet bit length: %d", bits);

    /* clone the original data */
    dst = (inet *) palloc(VARSIZE_ANY(src));
    memcpy(dst, src, VARSIZE_ANY(src));

    /* zero out any bits to the right of the netmask */
    byte = bits / 8;

    nbits = bits % 8;
    /* clear the first byte, this might be a partial byte */
    if (nbits != 0)
    {
        ip_addr(dst)[byte] &= ~(0xFF >> nbits);
        byte++;
    }
    /* clear remaining bytes */
    maxbytes = ip_addrsize(dst);
    while (byte < maxbytes)
    {
        ip_addr(dst)[byte] = 0;
        byte++;
    }

    PG_RETURN_INET_P(dst);
}

Datum inetand ( PG_FUNCTION_ARGS   ) 

Definition at line 1244 of file network.c.

References ereport, errcode(), errmsg(), ERROR, ip_addr, ip_addrsize(), ip_bits, ip_family, Max, palloc0(), PG_GETARG_INET_PP, PG_RETURN_INET_P, and SET_INET_VARSIZE.

{
    inet       *ip = PG_GETARG_INET_PP(0);
    inet       *ip2 = PG_GETARG_INET_PP(1);
    inet       *dst;

    dst = (inet *) palloc0(sizeof(inet));

    if (ip_family(ip) != ip_family(ip2))
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("cannot AND inet values of different sizes")));
    else
    {
        int         nb = ip_addrsize(ip);
        unsigned char *pip = ip_addr(ip);
        unsigned char *pip2 = ip_addr(ip2);
        unsigned char *pdst = ip_addr(dst);

        while (nb-- > 0)
            pdst[nb] = pip[nb] & pip2[nb];
    }
    ip_bits(dst) = Max(ip_bits(ip), ip_bits(ip2));

    ip_family(dst) = ip_family(ip);
    SET_INET_VARSIZE(dst);

    PG_RETURN_INET_P(dst);
}

Datum inetmi ( PG_FUNCTION_ARGS   ) 

Definition at line 1380 of file network.c.

References byte, ereport, errcode(), errmsg(), ERROR, ip_addr, ip_addrsize(), ip_family, PG_GETARG_INET_PP, and PG_RETURN_INT64.

{
    inet       *ip = PG_GETARG_INET_PP(0);
    inet       *ip2 = PG_GETARG_INET_PP(1);
    int64       res = 0;

    if (ip_family(ip) != ip_family(ip2))
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("cannot subtract inet values of different sizes")));
    else
    {
        /*
         * We form the difference using the traditional complement, increment,
         * and add rule, with the increment part being handled by starting the
         * carry off at 1.  If you don't think integer arithmetic is done in
         * two's complement, too bad.
         */
        int         nb = ip_addrsize(ip);
        int         byte = 0;
        unsigned char *pip = ip_addr(ip);
        unsigned char *pip2 = ip_addr(ip2);
        int         carry = 1;

        while (nb-- > 0)
        {
            int         lobyte;

            carry = pip[nb] + (~pip2[nb] & 0xFF) + carry;
            lobyte = carry & 0xFF;
            if (byte < sizeof(int64))
            {
                res |= ((int64) lobyte) << (byte * 8);
            }
            else
            {
                /*
                 * Input wider than int64: check for overflow.  All bytes to
                 * the left of what will fit should be 0 or 0xFF, depending on
                 * sign of the now-complete result.
                 */
                if ((res < 0) ? (lobyte != 0xFF) : (lobyte != 0))
                    ereport(ERROR,
                            (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                             errmsg("result is out of range")));
            }
            carry >>= 8;
            byte++;
        }

        /*
         * If input is narrower than int64, overflow is not possible, but we
         * have to do proper sign extension.
         */
        if (carry == 0 && byte < sizeof(int64))
            res |= ((int64) -1) << (byte * 8);
    }

    PG_RETURN_INT64(res);
}

Datum inetmi_int8 ( PG_FUNCTION_ARGS   ) 

Definition at line 1370 of file network.c.

References internal_inetpl(), PG_GETARG_INET_PP, PG_GETARG_INT64, and PG_RETURN_INET_P.

{
    inet       *ip = PG_GETARG_INET_PP(0);
    int64       addend = PG_GETARG_INT64(1);

    PG_RETURN_INET_P(internal_inetpl(ip, -addend));
}

Datum inetnot ( PG_FUNCTION_ARGS   ) 

Definition at line 1219 of file network.c.

References ip_addr, ip_addrsize(), ip_bits, ip_family, palloc0(), PG_GETARG_INET_PP, PG_RETURN_INET_P, and SET_INET_VARSIZE.

{
    inet       *ip = PG_GETARG_INET_PP(0);
    inet       *dst;

    dst = (inet *) palloc0(sizeof(inet));

    {
        int         nb = ip_addrsize(ip);
        unsigned char *pip = ip_addr(ip);
        unsigned char *pdst = ip_addr(dst);

        while (nb-- > 0)
            pdst[nb] = ~pip[nb];
    }
    ip_bits(dst) = ip_bits(ip);

    ip_family(dst) = ip_family(ip);
    SET_INET_VARSIZE(dst);

    PG_RETURN_INET_P(dst);
}

Datum inetor ( PG_FUNCTION_ARGS   ) 

Definition at line 1276 of file network.c.

References ereport, errcode(), errmsg(), ERROR, ip_addr, ip_addrsize(), ip_bits, ip_family, Max, palloc0(), PG_GETARG_INET_PP, PG_RETURN_INET_P, and SET_INET_VARSIZE.

{
    inet       *ip = PG_GETARG_INET_PP(0);
    inet       *ip2 = PG_GETARG_INET_PP(1);
    inet       *dst;

    dst = (inet *) palloc0(sizeof(inet));

    if (ip_family(ip) != ip_family(ip2))
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("cannot OR inet values of different sizes")));
    else
    {
        int         nb = ip_addrsize(ip);
        unsigned char *pip = ip_addr(ip);
        unsigned char *pip2 = ip_addr(ip2);
        unsigned char *pdst = ip_addr(dst);

        while (nb-- > 0)
            pdst[nb] = pip[nb] | pip2[nb];
    }
    ip_bits(dst) = Max(ip_bits(ip), ip_bits(ip2));

    ip_family(dst) = ip_family(ip);
    SET_INET_VARSIZE(dst);

    PG_RETURN_INET_P(dst);
}

Datum inetpl ( PG_FUNCTION_ARGS   ) 

Definition at line 1360 of file network.c.

References internal_inetpl(), PG_GETARG_INET_PP, PG_GETARG_INT64, and PG_RETURN_INET_P.

{
    inet       *ip = PG_GETARG_INET_PP(0);
    int64       addend = PG_GETARG_INT64(1);

    PG_RETURN_INET_P(internal_inetpl(ip, addend));
}

Datum initcap ( PG_FUNCTION_ARGS   ) 

Definition at line 108 of file oracle_compat.c.

References cstring_to_text(), pfree(), PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, str_initcap(), VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    text       *in_string = PG_GETARG_TEXT_PP(0);
    char       *out_string;
    text       *result;

    out_string = str_initcap(VARDATA_ANY(in_string),
                             VARSIZE_ANY_EXHDR(in_string),
                             PG_GET_COLLATION());
    result = cstring_to_text(out_string);
    pfree(out_string);

    PG_RETURN_TEXT_P(result);
}

Datum int24div ( PG_FUNCTION_ARGS   ) 

Definition at line 960 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT16, PG_GETARG_INT32, PG_RETURN_INT32, and PG_RETURN_NULL.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int32       arg2 = PG_GETARG_INT32(1);

    if (arg2 == 0)
    {
        ereport(ERROR,
                (errcode(ERRCODE_DIVISION_BY_ZERO),
                 errmsg("division by zero")));
        /* ensure compiler realizes we mustn't reach the division (gcc bug) */
        PG_RETURN_NULL();
    }

    /* No overflow is possible */
    PG_RETURN_INT32((int32) arg1 / arg2);
}

Datum int24eq ( PG_FUNCTION_ARGS   ) 

Definition at line 498 of file int.c.

References PG_GETARG_INT16, PG_GETARG_INT32, and PG_RETURN_BOOL.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_BOOL(arg1 == arg2);
}

Datum int24ge ( PG_FUNCTION_ARGS   ) 

Definition at line 543 of file int.c.

References PG_GETARG_INT16, PG_GETARG_INT32, and PG_RETURN_BOOL.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_BOOL(arg1 >= arg2);
}

Datum int24gt ( PG_FUNCTION_ARGS   ) 

Definition at line 534 of file int.c.

References PG_GETARG_INT16, PG_GETARG_INT32, and PG_RETURN_BOOL.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_BOOL(arg1 > arg2);
}

Datum int24le ( PG_FUNCTION_ARGS   ) 

Definition at line 525 of file int.c.

References PG_GETARG_INT16, PG_GETARG_INT32, and PG_RETURN_BOOL.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_BOOL(arg1 <= arg2);
}

Datum int24lt ( PG_FUNCTION_ARGS   ) 

Definition at line 516 of file int.c.

References PG_GETARG_INT16, PG_GETARG_INT32, and PG_RETURN_BOOL.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_BOOL(arg1 < arg2);
}

Datum int24mi ( PG_FUNCTION_ARGS   ) 

Definition at line 912 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT16, PG_GETARG_INT32, PG_RETURN_INT32, and SAMESIGN.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int32       arg2 = PG_GETARG_INT32(1);
    int32       result;

    result = arg1 - arg2;

    /*
     * Overflow check.  If the inputs are of the same sign then their
     * difference cannot overflow.  If they are of different signs then the
     * result should be of the same sign as the first input.
     */
    if (!SAMESIGN(arg1, arg2) && !SAMESIGN(result, arg1))
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("integer out of range")));
    PG_RETURN_INT32(result);
}

Datum int24mul ( PG_FUNCTION_ARGS   ) 

Definition at line 933 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT16, PG_GETARG_INT32, and PG_RETURN_INT32.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int32       arg2 = PG_GETARG_INT32(1);
    int32       result;

    result = arg1 * arg2;

    /*
     * Overflow check.  We basically check to see if result / arg2 gives arg1
     * again.  There is one case where this fails: arg2 = 0 (which cannot
     * overflow).
     *
     * Since the division is likely much more expensive than the actual
     * multiplication, we'd like to skip it where possible.  The best bang for
     * the buck seems to be to check whether both inputs are in the int16
     * range; if so, no overflow is possible.
     */
    if (!(arg2 >= (int32) SHRT_MIN && arg2 <= (int32) SHRT_MAX) &&
        result / arg2 != arg1)
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("integer out of range")));
    PG_RETURN_INT32(result);
}

Datum int24ne ( PG_FUNCTION_ARGS   ) 

Definition at line 507 of file int.c.

References PG_GETARG_INT16, PG_GETARG_INT32, and PG_RETURN_BOOL.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_BOOL(arg1 != arg2);
}

Datum int24pl ( PG_FUNCTION_ARGS   ) 

Definition at line 891 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT16, PG_GETARG_INT32, PG_RETURN_INT32, and SAMESIGN.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int32       arg2 = PG_GETARG_INT32(1);
    int32       result;

    result = arg1 + arg2;

    /*
     * Overflow check.  If the inputs are of different signs then their sum
     * cannot overflow.  If the inputs are of the same sign, their sum had
     * better be that sign too.
     */
    if (SAMESIGN(arg1, arg2) && !SAMESIGN(result, arg1))
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("integer out of range")));
    PG_RETURN_INT32(result);
}

Datum int2_accum ( PG_FUNCTION_ARGS   ) 
Datum int2_avg_accum ( PG_FUNCTION_ARGS   ) 

Definition at line 2981 of file numeric.c.

References AggCheckCallContext(), ARR_DATA_PTR, ARR_HASNULL, ARR_OVERHEAD_NONULLS, ARR_SIZE, Int8TransTypeData::count, elog, ERROR, NULL, PG_GETARG_ARRAYTYPE_P, PG_GETARG_ARRAYTYPE_P_COPY, PG_GETARG_INT16, PG_RETURN_ARRAYTYPE_P, and Int8TransTypeData::sum.

{
    ArrayType  *transarray;
    int16       newval = PG_GETARG_INT16(1);
    Int8TransTypeData *transdata;

    /*
     * If we're invoked as an aggregate, we can cheat and modify our first
     * parameter in-place to reduce palloc overhead. Otherwise we need to make
     * a copy of it before scribbling on it.
     */
    if (AggCheckCallContext(fcinfo, NULL))
        transarray = PG_GETARG_ARRAYTYPE_P(0);
    else
        transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);

    if (ARR_HASNULL(transarray) ||
        ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
        elog(ERROR, "expected 2-element int8 array");

    transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
    transdata->count++;
    transdata->sum += newval;

    PG_RETURN_ARRAYTYPE_P(transarray);
}

Datum int2_numeric ( PG_FUNCTION_ARGS   ) 

Definition at line 2301 of file numeric.c.

References free_var(), init_var, int8_to_numericvar(), make_result(), PG_GETARG_INT16, PG_RETURN_NUMERIC, and val.

Referenced by int2_accum().

{
    int16       val = PG_GETARG_INT16(0);
    Numeric     res;
    NumericVar  result;

    init_var(&result);

    int8_to_numericvar((int64) val, &result);

    res = make_result(&result);

    free_var(&result);

    PG_RETURN_NUMERIC(res);
}

Datum int2_sum ( PG_FUNCTION_ARGS   ) 

Definition at line 2836 of file numeric.c.

References AggCheckCallContext(), NULL, PG_ARGISNULL, PG_GETARG_INT16, PG_GETARG_INT64, PG_GETARG_POINTER, PG_RETURN_INT64, PG_RETURN_NULL, and PG_RETURN_POINTER.

{
    int64       newval;

    if (PG_ARGISNULL(0))
    {
        /* No non-null input seen so far... */
        if (PG_ARGISNULL(1))
            PG_RETURN_NULL();   /* still no non-null */
        /* This is the first non-null input. */
        newval = (int64) PG_GETARG_INT16(1);
        PG_RETURN_INT64(newval);
    }

    /*
     * If we're invoked as an aggregate, we can cheat and modify our first
     * parameter in-place to avoid palloc overhead. If not, we need to return
     * the new value of the transition variable. (If int8 is pass-by-value,
     * then of course this is useless as well as incorrect, so just ifdef it
     * out.)
     */
#ifndef USE_FLOAT8_BYVAL        /* controls int8 too */
    if (AggCheckCallContext(fcinfo, NULL))
    {
        int64      *oldsum = (int64 *) PG_GETARG_POINTER(0);

        /* Leave the running sum unchanged in the new input is null */
        if (!PG_ARGISNULL(1))
            *oldsum = *oldsum + (int64) PG_GETARG_INT16(1);

        PG_RETURN_POINTER(oldsum);
    }
    else
#endif
    {
        int64       oldsum = PG_GETARG_INT64(0);

        /* Leave sum unchanged if new input is null. */
        if (PG_ARGISNULL(1))
            PG_RETURN_INT64(oldsum);

        /* OK to do the addition. */
        newval = oldsum + (int64) PG_GETARG_INT16(1);

        PG_RETURN_INT64(newval);
    }
}

Datum int2abs ( PG_FUNCTION_ARGS   ) 

Definition at line 1164 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT16, and PG_RETURN_INT16.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int16       result;

    result = (arg1 < 0) ? -arg1 : arg1;
    /* overflow check (needed for SHRT_MIN) */
    if (result < 0)
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("smallint out of range")));
    PG_RETURN_INT16(result);
}

Datum int2and ( PG_FUNCTION_ARGS   ) 

Definition at line 1279 of file int.c.

References PG_GETARG_INT16, and PG_RETURN_INT16.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int16       arg2 = PG_GETARG_INT16(1);

    PG_RETURN_INT16(arg1 & arg2);
}

Datum int2div ( PG_FUNCTION_ARGS   ) 

Definition at line 851 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT16, PG_RETURN_INT16, PG_RETURN_NULL, and SAMESIGN.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int16       arg2 = PG_GETARG_INT16(1);
    int16       result;

    if (arg2 == 0)
    {
        ereport(ERROR,
                (errcode(ERRCODE_DIVISION_BY_ZERO),
                 errmsg("division by zero")));
        /* ensure compiler realizes we mustn't reach the division (gcc bug) */
        PG_RETURN_NULL();
    }

    /*
     * SHRT_MIN / -1 is problematic, since the result can't be represented on
     * a two's-complement machine.  Some machines produce SHRT_MIN, some
     * produce zero, some throw an exception.  We can dodge the problem by
     * recognizing that division by -1 is the same as negation.
     */
    if (arg2 == -1)
    {
        result = -arg1;
        /* overflow check (needed for SHRT_MIN) */
        if (arg1 != 0 && SAMESIGN(result, arg1))
            ereport(ERROR,
                    (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                     errmsg("smallint out of range")));
        PG_RETURN_INT16(result);
    }

    /* No overflow is possible */

    result = arg1 / arg2;

    PG_RETURN_INT16(result);
}

Datum int2eq ( PG_FUNCTION_ARGS   ) 

Definition at line 444 of file int.c.

References PG_GETARG_INT16, and PG_RETURN_BOOL.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int16       arg2 = PG_GETARG_INT16(1);

    PG_RETURN_BOOL(arg1 == arg2);
}

Datum int2ge ( PG_FUNCTION_ARGS   ) 

Definition at line 489 of file int.c.

References PG_GETARG_INT16, and PG_RETURN_BOOL.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int16       arg2 = PG_GETARG_INT16(1);

    PG_RETURN_BOOL(arg1 >= arg2);
}

Datum int2gt ( PG_FUNCTION_ARGS   ) 

Definition at line 480 of file int.c.

References PG_GETARG_INT16, and PG_RETURN_BOOL.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int16       arg2 = PG_GETARG_INT16(1);

    PG_RETURN_BOOL(arg1 > arg2);
}

Datum int2in ( PG_FUNCTION_ARGS   ) 

Definition at line 61 of file int.c.

References pg_atoi(), PG_GETARG_CSTRING, and PG_RETURN_INT16.

{
    char       *num = PG_GETARG_CSTRING(0);

    PG_RETURN_INT16(pg_atoi(num, sizeof(int16), '\0'));
}

Datum int2larger ( PG_FUNCTION_ARGS   ) 

Definition at line 1179 of file int.c.

References PG_GETARG_INT16, and PG_RETURN_INT16.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int16       arg2 = PG_GETARG_INT16(1);

    PG_RETURN_INT16((arg1 > arg2) ? arg1 : arg2);
}

Datum int2le ( PG_FUNCTION_ARGS   ) 

Definition at line 471 of file int.c.

References PG_GETARG_INT16, and PG_RETURN_BOOL.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int16       arg2 = PG_GETARG_INT16(1);

    PG_RETURN_BOOL(arg1 <= arg2);
}

Datum int2lt ( PG_FUNCTION_ARGS   ) 

Definition at line 462 of file int.c.

References PG_GETARG_INT16, and PG_RETURN_BOOL.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int16       arg2 = PG_GETARG_INT16(1);

    PG_RETURN_BOOL(arg1 < arg2);
}

Datum int2mi ( PG_FUNCTION_ARGS   ) 

Definition at line 809 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT16, PG_RETURN_INT16, and SAMESIGN.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int16       arg2 = PG_GETARG_INT16(1);
    int16       result;

    result = arg1 - arg2;

    /*
     * Overflow check.  If the inputs are of the same sign then their
     * difference cannot overflow.  If they are of different signs then the
     * result should be of the same sign as the first input.
     */
    if (!SAMESIGN(arg1, arg2) && !SAMESIGN(result, arg1))
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("smallint out of range")));
    PG_RETURN_INT16(result);
}

Datum int2mod ( PG_FUNCTION_ARGS   ) 

Definition at line 1116 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT16, PG_RETURN_INT16, and PG_RETURN_NULL.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int16       arg2 = PG_GETARG_INT16(1);

    if (arg2 == 0)
    {
        ereport(ERROR,
                (errcode(ERRCODE_DIVISION_BY_ZERO),
                 errmsg("division by zero")));
        /* ensure compiler realizes we mustn't reach the division (gcc bug) */
        PG_RETURN_NULL();
    }

    /*
     * Some machines throw a floating-point exception for INT_MIN % -1, which
     * is a bit silly since the correct answer is perfectly well-defined,
     * namely zero.  (It's not clear this ever happens when dealing with
     * int16, but we might as well have the test for safety.)
     */
    if (arg2 == -1)
        PG_RETURN_INT16(0);

    /* No overflow is possible */

    PG_RETURN_INT16(arg1 % arg2);
}

Datum int2mul ( PG_FUNCTION_ARGS   ) 

Definition at line 830 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT16, and PG_RETURN_INT16.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int16       arg2 = PG_GETARG_INT16(1);
    int32       result32;

    /*
     * The most practical way to detect overflow is to do the arithmetic in
     * int32 (so that the result can't overflow) and then do a range check.
     */
    result32 = (int32) arg1 *(int32) arg2;

    if (result32 < SHRT_MIN || result32 > SHRT_MAX)
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("smallint out of range")));

    PG_RETURN_INT16((int16) result32);
}

Datum int2ne ( PG_FUNCTION_ARGS   ) 

Definition at line 453 of file int.c.

References PG_GETARG_INT16, and PG_RETURN_BOOL.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int16       arg2 = PG_GETARG_INT16(1);

    PG_RETURN_BOOL(arg1 != arg2);
}

Datum int2not ( PG_FUNCTION_ARGS   ) 

Definition at line 1306 of file int.c.

References PG_GETARG_INT16, and PG_RETURN_INT16.

{
    int16       arg1 = PG_GETARG_INT16(0);

    PG_RETURN_INT16(~arg1);
}

Datum int2or ( PG_FUNCTION_ARGS   ) 

Definition at line 1288 of file int.c.

References PG_GETARG_INT16, and PG_RETURN_INT16.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int16       arg2 = PG_GETARG_INT16(1);

    PG_RETURN_INT16(arg1 | arg2);
}

Datum int2out ( PG_FUNCTION_ARGS   ) 

Definition at line 72 of file int.c.

References palloc(), PG_GETARG_INT16, pg_itoa(), and PG_RETURN_CSTRING.

{
    int16       arg1 = PG_GETARG_INT16(0);
    char       *result = (char *) palloc(7);    /* sign, 5 digits, '\0' */

    pg_itoa(arg1, result);
    PG_RETURN_CSTRING(result);
}

Datum int2pl ( PG_FUNCTION_ARGS   ) 

Definition at line 788 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT16, PG_RETURN_INT16, and SAMESIGN.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int16       arg2 = PG_GETARG_INT16(1);
    int16       result;

    result = arg1 + arg2;

    /*
     * Overflow check.  If the inputs are of different signs then their sum
     * cannot overflow.  If the inputs are of the same sign, their sum had
     * better be that sign too.
     */
    if (SAMESIGN(arg1, arg2) && !SAMESIGN(result, arg1))
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("smallint out of range")));
    PG_RETURN_INT16(result);
}

Datum int2recv ( PG_FUNCTION_ARGS   ) 

Definition at line 85 of file int.c.

References buf, PG_GETARG_POINTER, PG_RETURN_INT16, and pq_getmsgint().

Datum int2send ( PG_FUNCTION_ARGS   ) 
Datum int2shl ( PG_FUNCTION_ARGS   ) 

Definition at line 1315 of file int.c.

References PG_GETARG_INT16, PG_GETARG_INT32, and PG_RETURN_INT16.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_INT16(arg1 << arg2);
}

Datum int2shr ( PG_FUNCTION_ARGS   ) 

Definition at line 1324 of file int.c.

References PG_GETARG_INT16, PG_GETARG_INT32, and PG_RETURN_INT16.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_INT16(arg1 >> arg2);
}

Datum int2smaller ( PG_FUNCTION_ARGS   ) 

Definition at line 1188 of file int.c.

References PG_GETARG_INT16, and PG_RETURN_INT16.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int16       arg2 = PG_GETARG_INT16(1);

    PG_RETURN_INT16((arg1 < arg2) ? arg1 : arg2);
}

Datum int2um ( PG_FUNCTION_ARGS   ) 

Definition at line 765 of file int.c.

References arg, ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT16, PG_RETURN_INT16, and SAMESIGN.

{
    int16       arg = PG_GETARG_INT16(0);
    int16       result;

    result = -arg;
    /* overflow check (needed for SHRT_MIN) */
    if (arg != 0 && SAMESIGN(result, arg))
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("smallint out of range")));
    PG_RETURN_INT16(result);
}

Datum int2up ( PG_FUNCTION_ARGS   ) 

Definition at line 780 of file int.c.

References arg, PG_GETARG_INT16, and PG_RETURN_INT16.

Datum int2vectoreq ( PG_FUNCTION_ARGS   ) 

Definition at line 262 of file int.c.

References int2vector::dim1, memcmp(), PG_GETARG_POINTER, PG_RETURN_BOOL, and int2vector::values.

{
    int2vector *a = (int2vector *) PG_GETARG_POINTER(0);
    int2vector *b = (int2vector *) PG_GETARG_POINTER(1);

    if (a->dim1 != b->dim1)
        PG_RETURN_BOOL(false);
    PG_RETURN_BOOL(memcmp(a->values, b->values, a->dim1 * sizeof(int16)) == 0);
}

Datum int2vectorin ( PG_FUNCTION_ARGS   ) 

Definition at line 139 of file int.c.

References int2vector::dataoffset, int2vector::dim1, int2vector::elemtype, ereport, errcode(), errmsg(), ERROR, FUNC_MAX_ARGS, Int2VectorSize, int2vector::lbound1, int2vector::ndim, palloc0(), pg_atoi(), PG_GETARG_CSTRING, PG_RETURN_POINTER, SET_VARSIZE, and int2vector::values.

{
    char       *intString = PG_GETARG_CSTRING(0);
    int2vector *result;
    int         n;

    result = (int2vector *) palloc0(Int2VectorSize(FUNC_MAX_ARGS));

    for (n = 0; *intString && n < FUNC_MAX_ARGS; n++)
    {
        while (*intString && isspace((unsigned char) *intString))
            intString++;
        if (*intString == '\0')
            break;
        result->values[n] = pg_atoi(intString, sizeof(int16), ' ');
        while (*intString && !isspace((unsigned char) *intString))
            intString++;
    }
    while (*intString && isspace((unsigned char) *intString))
        intString++;
    if (*intString)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("int2vector has too many elements")));

    SET_VARSIZE(result, Int2VectorSize(n));
    result->ndim = 1;
    result->dataoffset = 0;     /* never any nulls */
    result->elemtype = INT2OID;
    result->dim1 = n;
    result->lbound1 = 0;

    PG_RETURN_POINTER(result);
}

Datum int2vectorout ( PG_FUNCTION_ARGS   ) 

Definition at line 178 of file int.c.

References int2vector::dim1, palloc(), PG_GETARG_POINTER, pg_itoa(), PG_RETURN_CSTRING, and int2vector::values.

{
    int2vector *int2Array = (int2vector *) PG_GETARG_POINTER(0);
    int         num,
                nnums = int2Array->dim1;
    char       *rp;
    char       *result;

    /* assumes sign, 5 digits, ' ' */
    rp = result = (char *) palloc(nnums * 7 + 1);
    for (num = 0; num < nnums; num++)
    {
        if (num != 0)
            *rp++ = ' ';
        pg_itoa(int2Array->values[num], rp);
        while (*++rp != '\0')
            ;
    }
    *rp = '\0';
    PG_RETURN_CSTRING(result);
}

Datum int2vectorrecv ( PG_FUNCTION_ARGS   ) 

Definition at line 204 of file int.c.

References FunctionCallInfoData::arg, FunctionCallInfoData::argnull, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_LBOUND, ARR_NDIM, array_recv(), Assert, buf, DatumGetPointer, ereport, errcode(), errmsg(), ERROR, FunctionCallInfoData::flinfo, FUNC_MAX_ARGS, InitFunctionCallInfoData, INT2OID, Int32GetDatum, InvalidOid, FunctionCallInfoData::isnull, NULL, ObjectIdGetDatum, PG_GETARG_POINTER, PG_RETURN_POINTER, and PointerGetDatum.

{
    StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
    FunctionCallInfoData locfcinfo;
    int2vector *result;

    /*
     * Normally one would call array_recv() using DirectFunctionCall3, but
     * that does not work since array_recv wants to cache some data using
     * fcinfo->flinfo->fn_extra.  So we need to pass it our own flinfo
     * parameter.
     */
    InitFunctionCallInfoData(locfcinfo, fcinfo->flinfo, 3,
                             InvalidOid, NULL, NULL);

    locfcinfo.arg[0] = PointerGetDatum(buf);
    locfcinfo.arg[1] = ObjectIdGetDatum(INT2OID);
    locfcinfo.arg[2] = Int32GetDatum(-1);
    locfcinfo.argnull[0] = false;
    locfcinfo.argnull[1] = false;
    locfcinfo.argnull[2] = false;

    result = (int2vector *) DatumGetPointer(array_recv(&locfcinfo));

    Assert(!locfcinfo.isnull);

    /* sanity checks: int2vector must be 1-D, 0-based, no nulls */
    if (ARR_NDIM(result) != 1 ||
        ARR_HASNULL(result) ||
        ARR_ELEMTYPE(result) != INT2OID ||
        ARR_LBOUND(result)[0] != 0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
                 errmsg("invalid int2vector data")));

    /* check length for consistency with int2vectorin() */
    if (ARR_DIMS(result)[0] > FUNC_MAX_ARGS)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("oidvector has too many elements")));

    PG_RETURN_POINTER(result);
}

Datum int2vectorsend ( PG_FUNCTION_ARGS   ) 

Definition at line 252 of file int.c.

References array_send().

{
    return array_send(fcinfo);
}

Datum int2xor ( PG_FUNCTION_ARGS   ) 

Definition at line 1297 of file int.c.

References PG_GETARG_INT16, and PG_RETURN_INT16.

{
    int16       arg1 = PG_GETARG_INT16(0);
    int16       arg2 = PG_GETARG_INT16(1);

    PG_RETURN_INT16(arg1 ^ arg2);
}

Datum int42div ( PG_FUNCTION_ARGS   ) 

Definition at line 1048 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT16, PG_GETARG_INT32, PG_RETURN_INT32, PG_RETURN_NULL, and SAMESIGN.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int16       arg2 = PG_GETARG_INT16(1);
    int32       result;

    if (arg2 == 0)
    {
        ereport(ERROR,
                (errcode(ERRCODE_DIVISION_BY_ZERO),
                 errmsg("division by zero")));
        /* ensure compiler realizes we mustn't reach the division (gcc bug) */
        PG_RETURN_NULL();
    }

    /*
     * INT_MIN / -1 is problematic, since the result can't be represented on a
     * two's-complement machine.  Some machines produce INT_MIN, some produce
     * zero, some throw an exception.  We can dodge the problem by recognizing
     * that division by -1 is the same as negation.
     */
    if (arg2 == -1)
    {
        result = -arg1;
        /* overflow check (needed for INT_MIN) */
        if (arg1 != 0 && SAMESIGN(result, arg1))
            ereport(ERROR,
                    (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                     errmsg("integer out of range")));
        PG_RETURN_INT32(result);
    }

    /* No overflow is possible */

    result = arg1 / arg2;

    PG_RETURN_INT32(result);
}

Datum int42eq ( PG_FUNCTION_ARGS   ) 

Definition at line 552 of file int.c.

References PG_GETARG_INT16, PG_GETARG_INT32, and PG_RETURN_BOOL.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int16       arg2 = PG_GETARG_INT16(1);

    PG_RETURN_BOOL(arg1 == arg2);
}

Datum int42ge ( PG_FUNCTION_ARGS   ) 

Definition at line 597 of file int.c.

References PG_GETARG_INT16, PG_GETARG_INT32, and PG_RETURN_BOOL.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int16       arg2 = PG_GETARG_INT16(1);

    PG_RETURN_BOOL(arg1 >= arg2);
}

Datum int42gt ( PG_FUNCTION_ARGS   ) 

Definition at line 588 of file int.c.

References PG_GETARG_INT16, PG_GETARG_INT32, and PG_RETURN_BOOL.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int16       arg2 = PG_GETARG_INT16(1);

    PG_RETURN_BOOL(arg1 > arg2);
}

Datum int42le ( PG_FUNCTION_ARGS   ) 

Definition at line 579 of file int.c.

References PG_GETARG_INT16, PG_GETARG_INT32, and PG_RETURN_BOOL.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int16       arg2 = PG_GETARG_INT16(1);

    PG_RETURN_BOOL(arg1 <= arg2);
}

Datum int42lt ( PG_FUNCTION_ARGS   ) 

Definition at line 570 of file int.c.

References PG_GETARG_INT16, PG_GETARG_INT32, and PG_RETURN_BOOL.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int16       arg2 = PG_GETARG_INT16(1);

    PG_RETURN_BOOL(arg1 < arg2);
}

Datum int42mi ( PG_FUNCTION_ARGS   ) 

Definition at line 1000 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT16, PG_GETARG_INT32, PG_RETURN_INT32, and SAMESIGN.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int16       arg2 = PG_GETARG_INT16(1);
    int32       result;

    result = arg1 - arg2;

    /*
     * Overflow check.  If the inputs are of the same sign then their
     * difference cannot overflow.  If they are of different signs then the
     * result should be of the same sign as the first input.
     */
    if (!SAMESIGN(arg1, arg2) && !SAMESIGN(result, arg1))
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("integer out of range")));
    PG_RETURN_INT32(result);
}

Datum int42mul ( PG_FUNCTION_ARGS   ) 

Definition at line 1021 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT16, PG_GETARG_INT32, and PG_RETURN_INT32.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int16       arg2 = PG_GETARG_INT16(1);
    int32       result;

    result = arg1 * arg2;

    /*
     * Overflow check.  We basically check to see if result / arg1 gives arg2
     * again.  There is one case where this fails: arg1 = 0 (which cannot
     * overflow).
     *
     * Since the division is likely much more expensive than the actual
     * multiplication, we'd like to skip it where possible.  The best bang for
     * the buck seems to be to check whether both inputs are in the int16
     * range; if so, no overflow is possible.
     */
    if (!(arg1 >= (int32) SHRT_MIN && arg1 <= (int32) SHRT_MAX) &&
        result / arg1 != arg2)
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("integer out of range")));
    PG_RETURN_INT32(result);
}

Datum int42ne ( PG_FUNCTION_ARGS   ) 

Definition at line 561 of file int.c.

References PG_GETARG_INT16, PG_GETARG_INT32, and PG_RETURN_BOOL.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int16       arg2 = PG_GETARG_INT16(1);

    PG_RETURN_BOOL(arg1 != arg2);
}

Datum int42pl ( PG_FUNCTION_ARGS   ) 

Definition at line 979 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT16, PG_GETARG_INT32, PG_RETURN_INT32, and SAMESIGN.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int16       arg2 = PG_GETARG_INT16(1);
    int32       result;

    result = arg1 + arg2;

    /*
     * Overflow check.  If the inputs are of different signs then their sum
     * cannot overflow.  If the inputs are of the same sign, their sum had
     * better be that sign too.
     */
    if (SAMESIGN(arg1, arg2) && !SAMESIGN(result, arg1))
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("integer out of range")));
    PG_RETURN_INT32(result);
}

Datum int4_accum ( PG_FUNCTION_ARGS   ) 
Datum int4_avg_accum ( PG_FUNCTION_ARGS   ) 

Definition at line 3009 of file numeric.c.

References AggCheckCallContext(), ARR_DATA_PTR, ARR_HASNULL, ARR_OVERHEAD_NONULLS, ARR_SIZE, Int8TransTypeData::count, elog, ERROR, NULL, PG_GETARG_ARRAYTYPE_P, PG_GETARG_ARRAYTYPE_P_COPY, PG_GETARG_INT32, PG_RETURN_ARRAYTYPE_P, and Int8TransTypeData::sum.

{
    ArrayType  *transarray;
    int32       newval = PG_GETARG_INT32(1);
    Int8TransTypeData *transdata;

    /*
     * If we're invoked as an aggregate, we can cheat and modify our first
     * parameter in-place to reduce palloc overhead. Otherwise we need to make
     * a copy of it before scribbling on it.
     */
    if (AggCheckCallContext(fcinfo, NULL))
        transarray = PG_GETARG_ARRAYTYPE_P(0);
    else
        transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);

    if (ARR_HASNULL(transarray) ||
        ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
        elog(ERROR, "expected 2-element int8 array");

    transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
    transdata->count++;
    transdata->sum += newval;

    PG_RETURN_ARRAYTYPE_P(transarray);
}

Datum int4_bool ( PG_FUNCTION_ARGS   ) 

Definition at line 356 of file int.c.

References PG_GETARG_INT32, and PG_RETURN_BOOL.

{
    if (PG_GETARG_INT32(0) == 0)
        PG_RETURN_BOOL(false);
    else
        PG_RETURN_BOOL(true);
}

Datum int4_numeric ( PG_FUNCTION_ARGS   ) 

Definition at line 2191 of file numeric.c.

References free_var(), init_var, int8_to_numericvar(), make_result(), PG_GETARG_INT32, PG_RETURN_NUMERIC, and val.

Referenced by gbt_numeric_penalty(), int4_accum(), and numeric_to_char().

{
    int32       val = PG_GETARG_INT32(0);
    Numeric     res;
    NumericVar  result;

    init_var(&result);

    int8_to_numericvar((int64) val, &result);

    res = make_result(&result);

    free_var(&result);

    PG_RETURN_NUMERIC(res);
}

Datum int4_sum ( PG_FUNCTION_ARGS   ) 

Definition at line 2885 of file numeric.c.

References AggCheckCallContext(), NULL, PG_ARGISNULL, PG_GETARG_INT32, PG_GETARG_INT64, PG_GETARG_POINTER, PG_RETURN_INT64, PG_RETURN_NULL, and PG_RETURN_POINTER.

{
    int64       newval;

    if (PG_ARGISNULL(0))
    {
        /* No non-null input seen so far... */
        if (PG_ARGISNULL(1))
            PG_RETURN_NULL();   /* still no non-null */
        /* This is the first non-null input. */
        newval = (int64) PG_GETARG_INT32(1);
        PG_RETURN_INT64(newval);
    }

    /*
     * If we're invoked as an aggregate, we can cheat and modify our first
     * parameter in-place to avoid palloc overhead. If not, we need to return
     * the new value of the transition variable. (If int8 is pass-by-value,
     * then of course this is useless as well as incorrect, so just ifdef it
     * out.)
     */
#ifndef USE_FLOAT8_BYVAL        /* controls int8 too */
    if (AggCheckCallContext(fcinfo, NULL))
    {
        int64      *oldsum = (int64 *) PG_GETARG_POINTER(0);

        /* Leave the running sum unchanged in the new input is null */
        if (!PG_ARGISNULL(1))
            *oldsum = *oldsum + (int64) PG_GETARG_INT32(1);

        PG_RETURN_POINTER(oldsum);
    }
    else
#endif
    {
        int64       oldsum = PG_GETARG_INT64(0);

        /* Leave sum unchanged if new input is null. */
        if (PG_ARGISNULL(1))
            PG_RETURN_INT64(oldsum);

        /* OK to do the addition. */
        newval = oldsum + (int64) PG_GETARG_INT32(1);

        PG_RETURN_INT64(newval);
    }
}

Datum int4abs ( PG_FUNCTION_ARGS   ) 

Definition at line 1149 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT32, and PG_RETURN_INT32.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int32       result;

    result = (arg1 < 0) ? -arg1 : arg1;
    /* overflow check (needed for INT_MIN) */
    if (result < 0)
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("integer out of range")));
    PG_RETURN_INT32(result);
}

Datum int4and ( PG_FUNCTION_ARGS   ) 

Definition at line 1226 of file int.c.

References PG_GETARG_INT32, and PG_RETURN_INT32.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_INT32(arg1 & arg2);
}

Datum int4div ( PG_FUNCTION_ARGS   ) 

Definition at line 709 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT32, PG_RETURN_INT32, PG_RETURN_NULL, and SAMESIGN.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int32       arg2 = PG_GETARG_INT32(1);
    int32       result;

    if (arg2 == 0)
    {
        ereport(ERROR,
                (errcode(ERRCODE_DIVISION_BY_ZERO),
                 errmsg("division by zero")));
        /* ensure compiler realizes we mustn't reach the division (gcc bug) */
        PG_RETURN_NULL();
    }

    /*
     * INT_MIN / -1 is problematic, since the result can't be represented on a
     * two's-complement machine.  Some machines produce INT_MIN, some produce
     * zero, some throw an exception.  We can dodge the problem by recognizing
     * that division by -1 is the same as negation.
     */
    if (arg2 == -1)
    {
        result = -arg1;
        /* overflow check (needed for INT_MIN) */
        if (arg1 != 0 && SAMESIGN(result, arg1))
            ereport(ERROR,
                    (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                     errmsg("integer out of range")));
        PG_RETURN_INT32(result);
    }

    /* No overflow is possible */

    result = arg1 / arg2;

    PG_RETURN_INT32(result);
}

Datum int4eq ( PG_FUNCTION_ARGS   ) 

Definition at line 390 of file int.c.

References PG_GETARG_INT32, and PG_RETURN_BOOL.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_BOOL(arg1 == arg2);
}

Datum int4ge ( PG_FUNCTION_ARGS   ) 

Definition at line 435 of file int.c.

References PG_GETARG_INT32, and PG_RETURN_BOOL.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_BOOL(arg1 >= arg2);
}

Datum int4gt ( PG_FUNCTION_ARGS   ) 

Definition at line 426 of file int.c.

References PG_GETARG_INT32, and PG_RETURN_BOOL.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_BOOL(arg1 > arg2);
}

Datum int4in ( PG_FUNCTION_ARGS   ) 

Definition at line 281 of file int.c.

References pg_atoi(), PG_GETARG_CSTRING, and PG_RETURN_INT32.

Referenced by funny_dup17(), inet_client_port(), inet_server_port(), and pg_stat_get_backend_client_port().

{
    char       *num = PG_GETARG_CSTRING(0);

    PG_RETURN_INT32(pg_atoi(num, sizeof(int32), '\0'));
}

Datum int4inc ( PG_FUNCTION_ARGS   ) 

Definition at line 749 of file int.c.

References arg, ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT32, and PG_RETURN_INT32.

{
    int32       arg = PG_GETARG_INT32(0);
    int32       result;

    result = arg + 1;
    /* Overflow check */
    if (arg > 0 && result < 0)
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("integer out of range")));

    PG_RETURN_INT32(result);
}

Datum int4larger ( PG_FUNCTION_ARGS   ) 

Definition at line 1197 of file int.c.

References PG_GETARG_INT32, and PG_RETURN_INT32.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_INT32((arg1 > arg2) ? arg1 : arg2);
}

Datum int4le ( PG_FUNCTION_ARGS   ) 

Definition at line 417 of file int.c.

References PG_GETARG_INT32, and PG_RETURN_BOOL.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_BOOL(arg1 <= arg2);
}

Datum int4lt ( PG_FUNCTION_ARGS   ) 

Definition at line 408 of file int.c.

References PG_GETARG_INT32, and PG_RETURN_BOOL.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_BOOL(arg1 < arg2);
}

Datum int4mi ( PG_FUNCTION_ARGS   ) 

Definition at line 657 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT32, PG_RETURN_INT32, and SAMESIGN.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int32       arg2 = PG_GETARG_INT32(1);
    int32       result;

    result = arg1 - arg2;

    /*
     * Overflow check.  If the inputs are of the same sign then their
     * difference cannot overflow.  If they are of different signs then the
     * result should be of the same sign as the first input.
     */
    if (!SAMESIGN(arg1, arg2) && !SAMESIGN(result, arg1))
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("integer out of range")));
    PG_RETURN_INT32(result);
}

Datum int4mod ( PG_FUNCTION_ARGS   ) 

Definition at line 1088 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT32, PG_RETURN_INT32, and PG_RETURN_NULL.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int32       arg2 = PG_GETARG_INT32(1);

    if (arg2 == 0)
    {
        ereport(ERROR,
                (errcode(ERRCODE_DIVISION_BY_ZERO),
                 errmsg("division by zero")));
        /* ensure compiler realizes we mustn't reach the division (gcc bug) */
        PG_RETURN_NULL();
    }

    /*
     * Some machines throw a floating-point exception for INT_MIN % -1, which
     * is a bit silly since the correct answer is perfectly well-defined,
     * namely zero.
     */
    if (arg2 == -1)
        PG_RETURN_INT32(0);

    /* No overflow is possible */

    PG_RETURN_INT32(arg1 % arg2);
}

Datum int4mul ( PG_FUNCTION_ARGS   ) 

Definition at line 678 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT32, and PG_RETURN_INT32.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int32       arg2 = PG_GETARG_INT32(1);
    int32       result;

    result = arg1 * arg2;

    /*
     * Overflow check.  We basically check to see if result / arg2 gives arg1
     * again.  There are two cases where this fails: arg2 = 0 (which cannot
     * overflow) and arg1 = INT_MIN, arg2 = -1 (where the division itself will
     * overflow and thus incorrectly match).
     *
     * Since the division is likely much more expensive than the actual
     * multiplication, we'd like to skip it where possible.  The best bang for
     * the buck seems to be to check whether both inputs are in the int16
     * range; if so, no overflow is possible.
     */
    if (!(arg1 >= (int32) SHRT_MIN && arg1 <= (int32) SHRT_MAX &&
          arg2 >= (int32) SHRT_MIN && arg2 <= (int32) SHRT_MAX) &&
        arg2 != 0 &&
        ((arg2 == -1 && arg1 < 0 && result < 0) ||
         result / arg2 != arg1))
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("integer out of range")));
    PG_RETURN_INT32(result);
}

Datum int4ne ( PG_FUNCTION_ARGS   ) 

Definition at line 399 of file int.c.

References PG_GETARG_INT32, and PG_RETURN_BOOL.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_BOOL(arg1 != arg2);
}

Datum int4not ( PG_FUNCTION_ARGS   ) 

Definition at line 1271 of file int.c.

References PG_GETARG_INT32, and PG_RETURN_INT32.

{
    int32       arg1 = PG_GETARG_INT32(0);

    PG_RETURN_INT32(~arg1);
}

Datum int4or ( PG_FUNCTION_ARGS   ) 

Definition at line 1235 of file int.c.

References PG_GETARG_INT32, and PG_RETURN_INT32.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_INT32(arg1 | arg2);
}

Datum int4out ( PG_FUNCTION_ARGS   ) 

Definition at line 292 of file int.c.

References palloc(), PG_GETARG_INT32, pg_ltoa(), and PG_RETURN_CSTRING.

Referenced by int4_to_char().

{
    int32       arg1 = PG_GETARG_INT32(0);
    char       *result = (char *) palloc(12);   /* sign, 10 digits, '\0' */

    pg_ltoa(arg1, result);
    PG_RETURN_CSTRING(result);
}

Datum int4pl ( PG_FUNCTION_ARGS   ) 

Definition at line 636 of file int.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT32, PG_RETURN_INT32, and SAMESIGN.

Referenced by int4range_canonical().

{
    int32       arg1 = PG_GETARG_INT32(0);
    int32       arg2 = PG_GETARG_INT32(1);
    int32       result;

    result = arg1 + arg2;

    /*
     * Overflow check.  If the inputs are of different signs then their sum
     * cannot overflow.  If the inputs are of the same sign, their sum had
     * better be that sign too.
     */
    if (SAMESIGN(arg1, arg2) && !SAMESIGN(result, arg1))
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("integer out of range")));
    PG_RETURN_INT32(result);
}

Datum int4recv ( PG_FUNCTION_ARGS   ) 

Definition at line 305 of file int.c.

References buf, PG_GETARG_POINTER, PG_RETURN_INT32, and pq_getmsgint().

Datum int4send ( PG_FUNCTION_ARGS   ) 
Datum int4shl ( PG_FUNCTION_ARGS   ) 

Definition at line 1253 of file int.c.

References PG_GETARG_INT32, and PG_RETURN_INT32.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_INT32(arg1 << arg2);
}

Datum int4shr ( PG_FUNCTION_ARGS   ) 

Definition at line 1262 of file int.c.

References PG_GETARG_INT32, and PG_RETURN_INT32.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_INT32(arg1 >> arg2);
}

Datum int4smaller ( PG_FUNCTION_ARGS   ) 

Definition at line 1206 of file int.c.

References PG_GETARG_INT32, and PG_RETURN_INT32.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_INT32((arg1 < arg2) ? arg1 : arg2);
}

Datum int4um ( PG_FUNCTION_ARGS   ) 

Definition at line 613 of file int.c.

References arg, ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT32, PG_RETURN_INT32, and SAMESIGN.

{
    int32       arg = PG_GETARG_INT32(0);
    int32       result;

    result = -arg;
    /* overflow check (needed for INT_MIN) */
    if (arg != 0 && SAMESIGN(result, arg))
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("integer out of range")));
    PG_RETURN_INT32(result);
}

Datum int4up ( PG_FUNCTION_ARGS   ) 

Definition at line 628 of file int.c.

References arg, PG_GETARG_INT32, and PG_RETURN_INT32.

Datum int4xor ( PG_FUNCTION_ARGS   ) 

Definition at line 1244 of file int.c.

References PG_GETARG_INT32, and PG_RETURN_INT32.

{
    int32       arg1 = PG_GETARG_INT32(0);
    int32       arg2 = PG_GETARG_INT32(1);

    PG_RETURN_INT32(arg1 ^ arg2);
}

Datum int8_accum ( PG_FUNCTION_ARGS   ) 
Datum int8_avg ( PG_FUNCTION_ARGS   ) 

Definition at line 3037 of file numeric.c.

References ARR_DATA_PTR, ARR_HASNULL, ARR_OVERHEAD_NONULLS, ARR_SIZE, Int8TransTypeData::count, DirectFunctionCall1, DirectFunctionCall2, elog, ERROR, Int64GetDatumFast, int8_numeric(), numeric_div(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_DATUM, PG_RETURN_NULL, and Int8TransTypeData::sum.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    Int8TransTypeData *transdata;
    Datum       countd,
                sumd;

    if (ARR_HASNULL(transarray) ||
        ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
        elog(ERROR, "expected 2-element int8 array");
    transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);

    /* SQL defines AVG of no values to be NULL */
    if (transdata->count == 0)
        PG_RETURN_NULL();

    countd = DirectFunctionCall1(int8_numeric,
                                 Int64GetDatumFast(transdata->count));
    sumd = DirectFunctionCall1(int8_numeric,
                               Int64GetDatumFast(transdata->sum));

    PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumd, countd));
}

Datum int8_avg_accum ( PG_FUNCTION_ARGS   ) 
Datum int8_numeric ( PG_FUNCTION_ARGS   ) 
Datum int8_sum ( PG_FUNCTION_ARGS   ) 

Definition at line 2934 of file numeric.c.

References DirectFunctionCall1, DirectFunctionCall2, int8_numeric(), numeric_add(), NumericGetDatum, PG_ARGISNULL, PG_GETARG_DATUM, PG_GETARG_NUMERIC, PG_RETURN_DATUM, PG_RETURN_NULL, and PG_RETURN_NUMERIC.

{
    Numeric     oldsum;
    Datum       newval;

    if (PG_ARGISNULL(0))
    {
        /* No non-null input seen so far... */
        if (PG_ARGISNULL(1))
            PG_RETURN_NULL();   /* still no non-null */
        /* This is the first non-null input. */
        newval = DirectFunctionCall1(int8_numeric, PG_GETARG_DATUM(1));
        PG_RETURN_DATUM(newval);
    }

    /*
     * Note that we cannot special-case the aggregate case here, as we do for
     * int2_sum and int4_sum: numeric is of variable size, so we cannot modify
     * our first parameter in-place.
     */

    oldsum = PG_GETARG_NUMERIC(0);

    /* Leave sum unchanged if new input is null. */
    if (PG_ARGISNULL(1))
        PG_RETURN_NUMERIC(oldsum);

    /* OK to do the addition. */
    newval = DirectFunctionCall1(int8_numeric, PG_GETARG_DATUM(1));

    PG_RETURN_DATUM(DirectFunctionCall2(numeric_add,
                                        NumericGetDatum(oldsum), newval));
}

Datum internal_in ( PG_FUNCTION_ARGS   ) 

Definition at line 380 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot accept a value of type internal")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum internal_out ( PG_FUNCTION_ARGS   ) 

Definition at line 393 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot display a value of type internal")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

int is_infinite ( double  val  ) 

Definition at line 165 of file float.c.

References isinf().

Referenced by calc_length_hist_frac(), float4_to_char(), float4out(), float8_to_char(), float8out(), and get_len_position().

{
    int         inf = isinf(val);

    if (inf == 0)
        return 0;
    else if (val > 0)
        return 1;
    else
        return -1;
}

Datum language_handler_in ( PG_FUNCTION_ARGS   ) 

Definition at line 326 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot accept a value of type language_handler")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum language_handler_out ( PG_FUNCTION_ARGS   ) 

Definition at line 339 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot display a value of type language_handler")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum length_in_encoding ( PG_FUNCTION_ARGS   ) 

Definition at line 504 of file mbutils.c.

References ereport, errcode(), errmsg(), ERROR, NameStr, pg_char_to_encoding(), PG_GETARG_BYTEA_P, PG_GETARG_NAME, PG_RETURN_INT32, pg_verify_mbstr_len(), VARDATA, and VARSIZE.

{
    bytea      *string = PG_GETARG_BYTEA_P(0);
    char       *src_encoding_name = NameStr(*PG_GETARG_NAME(1));
    int         src_encoding = pg_char_to_encoding(src_encoding_name);
    int         len = VARSIZE(string) - VARHDRSZ;
    int         retval;

    if (src_encoding < 0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("invalid encoding name \"%s\"",
                        src_encoding_name)));

    retval = pg_verify_mbstr_len(src_encoding, VARDATA(string), len, false);
    PG_RETURN_INT32(retval);

}

Datum like_escape ( PG_FUNCTION_ARGS   ) 

Definition at line 418 of file like.c.

References MB_do_like_escape(), pg_database_encoding_max_length(), PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, and SB_do_like_escape().

{
    text       *pat = PG_GETARG_TEXT_PP(0);
    text       *esc = PG_GETARG_TEXT_PP(1);
    text       *result;

    if (pg_database_encoding_max_length() == 1)
        result = SB_do_like_escape(pat, esc);
    else
        result = MB_do_like_escape(pat, esc);

    PG_RETURN_TEXT_P(result);
}

Datum like_escape_bytea ( PG_FUNCTION_ARGS   ) 

Definition at line 437 of file like.c.

References PG_GETARG_BYTEA_PP, PG_RETURN_BYTEA_P, and SB_do_like_escape().

{
    bytea      *pat = PG_GETARG_BYTEA_PP(0);
    bytea      *esc = PG_GETARG_BYTEA_PP(1);
    bytea      *result = SB_do_like_escape((text *) pat, (text *) esc);

    PG_RETURN_BYTEA_P((bytea *) result);
}

Datum lower ( PG_FUNCTION_ARGS   ) 
Datum lpad ( PG_FUNCTION_ARGS   ) 

Definition at line 141 of file oracle_compat.c.

References ereport, errcode(), errmsg(), ERROR, palloc(), pg_database_encoding_max_length(), PG_GETARG_INT32, PG_GETARG_TEXT_PP, pg_mblen(), pg_mbstrlen_with_len(), PG_RETURN_TEXT_P, SET_VARSIZE, VARDATA, VARDATA_ANY, VARHDRSZ, and VARSIZE_ANY_EXHDR.

{
    text       *string1 = PG_GETARG_TEXT_PP(0);
    int32       len = PG_GETARG_INT32(1);
    text       *string2 = PG_GETARG_TEXT_PP(2);
    text       *ret;
    char       *ptr1,
               *ptr2,
               *ptr2start,
               *ptr2end,
               *ptr_ret;
    int         m,
                s1len,
                s2len;

    int         bytelen;

    /* Negative len is silently taken as zero */
    if (len < 0)
        len = 0;

    s1len = VARSIZE_ANY_EXHDR(string1);
    if (s1len < 0)
        s1len = 0;              /* shouldn't happen */

    s2len = VARSIZE_ANY_EXHDR(string2);
    if (s2len < 0)
        s2len = 0;              /* shouldn't happen */

    s1len = pg_mbstrlen_with_len(VARDATA_ANY(string1), s1len);

    if (s1len > len)
        s1len = len;            /* truncate string1 to len chars */

    if (s2len <= 0)
        len = s1len;            /* nothing to pad with, so don't pad */

    bytelen = pg_database_encoding_max_length() * len;

    /* check for integer overflow */
    if (len != 0 && bytelen / pg_database_encoding_max_length() != len)
        ereport(ERROR,
                (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                 errmsg("requested length too large")));

    ret = (text *) palloc(VARHDRSZ + bytelen);

    m = len - s1len;

    ptr2 = ptr2start = VARDATA_ANY(string2);
    ptr2end = ptr2 + s2len;
    ptr_ret = VARDATA(ret);

    while (m--)
    {
        int         mlen = pg_mblen(ptr2);

        memcpy(ptr_ret, ptr2, mlen);
        ptr_ret += mlen;
        ptr2 += mlen;
        if (ptr2 == ptr2end)    /* wrap around at end of s2 */
            ptr2 = ptr2start;
    }

    ptr1 = VARDATA_ANY(string1);

    while (s1len--)
    {
        int         mlen = pg_mblen(ptr1);

        memcpy(ptr_ret, ptr1, mlen);
        ptr_ret += mlen;
        ptr1 += mlen;
    }

    SET_VARSIZE(ret, ptr_ret - (char *) ret);

    PG_RETURN_TEXT_P(ret);
}

Datum ltrim ( PG_FUNCTION_ARGS   ) 

Definition at line 619 of file oracle_compat.c.

References dotrim(), PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    text       *string = PG_GETARG_TEXT_PP(0);
    text       *set = PG_GETARG_TEXT_PP(1);
    text       *ret;

    ret = dotrim(VARDATA_ANY(string), VARSIZE_ANY_EXHDR(string),
                 VARDATA_ANY(set), VARSIZE_ANY_EXHDR(set),
                 true, false);

    PG_RETURN_TEXT_P(ret);
}

Datum ltrim1 ( PG_FUNCTION_ARGS   ) 

Definition at line 639 of file oracle_compat.c.

References dotrim(), PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    text       *string = PG_GETARG_TEXT_PP(0);
    text       *ret;

    ret = dotrim(VARDATA_ANY(string), VARSIZE_ANY_EXHDR(string),
                 " ", 1,
                 true, false);

    PG_RETURN_TEXT_P(ret);
}

Datum macaddr_and ( PG_FUNCTION_ARGS   ) 

Definition at line 264 of file mac.c.

References macaddr::a, macaddr::b, macaddr::c, macaddr::d, macaddr::e, macaddr::f, palloc(), PG_GETARG_MACADDR_P, and PG_RETURN_MACADDR_P.

{
    macaddr    *addr1 = PG_GETARG_MACADDR_P(0);
    macaddr    *addr2 = PG_GETARG_MACADDR_P(1);
    macaddr    *result;

    result = (macaddr *) palloc(sizeof(macaddr));
    result->a = addr1->a & addr2->a;
    result->b = addr1->b & addr2->b;
    result->c = addr1->c & addr2->c;
    result->d = addr1->d & addr2->d;
    result->e = addr1->e & addr2->e;
    result->f = addr1->f & addr2->f;
    PG_RETURN_MACADDR_P(result);
}

Datum macaddr_cmp ( PG_FUNCTION_ARGS   ) 
Datum macaddr_eq ( PG_FUNCTION_ARGS   ) 
Datum macaddr_ge ( PG_FUNCTION_ARGS   ) 
Datum macaddr_gt ( PG_FUNCTION_ARGS   ) 
Datum macaddr_in ( PG_FUNCTION_ARGS   ) 

Definition at line 30 of file mac.c.

References macaddr::a, macaddr::b, macaddr::c, macaddr::d, macaddr::e, ereport, errcode(), errmsg(), ERROR, macaddr::f, palloc(), PG_GETARG_CSTRING, and PG_RETURN_MACADDR_P.

{
    char       *str = PG_GETARG_CSTRING(0);
    macaddr    *result;
    int         a,
                b,
                c,
                d,
                e,
                f;
    char        junk[2];
    int         count;

    /* %1s matches iff there is trailing non-whitespace garbage */

    count = sscanf(str, "%x:%x:%x:%x:%x:%x%1s",
                   &a, &b, &c, &d, &e, &f, junk);
    if (count != 6)
        count = sscanf(str, "%x-%x-%x-%x-%x-%x%1s",
                       &a, &b, &c, &d, &e, &f, junk);
    if (count != 6)
        count = sscanf(str, "%2x%2x%2x:%2x%2x%2x%1s",
                       &a, &b, &c, &d, &e, &f, junk);
    if (count != 6)
        count = sscanf(str, "%2x%2x%2x-%2x%2x%2x%1s",
                       &a, &b, &c, &d, &e, &f, junk);
    if (count != 6)
        count = sscanf(str, "%2x%2x.%2x%2x.%2x%2x%1s",
                       &a, &b, &c, &d, &e, &f, junk);
    if (count != 6)
        count = sscanf(str, "%2x%2x%2x%2x%2x%2x%1s",
                       &a, &b, &c, &d, &e, &f, junk);
    if (count != 6)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
              errmsg("invalid input syntax for type macaddr: \"%s\"", str)));

    if ((a < 0) || (a > 255) || (b < 0) || (b > 255) ||
        (c < 0) || (c > 255) || (d < 0) || (d > 255) ||
        (e < 0) || (e > 255) || (f < 0) || (f > 255))
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
           errmsg("invalid octet value in \"macaddr\" value: \"%s\"", str)));

    result = (macaddr *) palloc(sizeof(macaddr));

    result->a = a;
    result->b = b;
    result->c = c;
    result->d = d;
    result->e = e;
    result->f = f;

    PG_RETURN_MACADDR_P(result);
}

Datum macaddr_le ( PG_FUNCTION_ARGS   ) 
Datum macaddr_lt ( PG_FUNCTION_ARGS   ) 
Datum macaddr_ne ( PG_FUNCTION_ARGS   ) 
Datum macaddr_not ( PG_FUNCTION_ARGS   ) 

Definition at line 248 of file mac.c.

References macaddr::a, macaddr::b, macaddr::c, macaddr::d, macaddr::e, macaddr::f, palloc(), PG_GETARG_MACADDR_P, and PG_RETURN_MACADDR_P.

{
    macaddr    *addr = PG_GETARG_MACADDR_P(0);
    macaddr    *result;

    result = (macaddr *) palloc(sizeof(macaddr));
    result->a = ~addr->a;
    result->b = ~addr->b;
    result->c = ~addr->c;
    result->d = ~addr->d;
    result->e = ~addr->e;
    result->f = ~addr->f;
    PG_RETURN_MACADDR_P(result);
}

Datum macaddr_or ( PG_FUNCTION_ARGS   ) 

Definition at line 281 of file mac.c.

References macaddr::a, macaddr::b, macaddr::c, macaddr::d, macaddr::e, macaddr::f, palloc(), PG_GETARG_MACADDR_P, and PG_RETURN_MACADDR_P.

{
    macaddr    *addr1 = PG_GETARG_MACADDR_P(0);
    macaddr    *addr2 = PG_GETARG_MACADDR_P(1);
    macaddr    *result;

    result = (macaddr *) palloc(sizeof(macaddr));
    result->a = addr1->a | addr2->a;
    result->b = addr1->b | addr2->b;
    result->c = addr1->c | addr2->c;
    result->d = addr1->d | addr2->d;
    result->e = addr1->e | addr2->e;
    result->f = addr1->f | addr2->f;
    PG_RETURN_MACADDR_P(result);
}

Datum macaddr_out ( PG_FUNCTION_ARGS   ) 

Definition at line 91 of file mac.c.

References macaddr::a, macaddr::b, macaddr::c, macaddr::d, macaddr::e, macaddr::f, palloc(), PG_GETARG_MACADDR_P, PG_RETURN_CSTRING, and snprintf().

{
    macaddr    *addr = PG_GETARG_MACADDR_P(0);
    char       *result;

    result = (char *) palloc(32);

    snprintf(result, 32, "%02x:%02x:%02x:%02x:%02x:%02x",
             addr->a, addr->b, addr->c, addr->d, addr->e, addr->f);

    PG_RETURN_CSTRING(result);
}

Datum macaddr_recv ( PG_FUNCTION_ARGS   ) 

Definition at line 110 of file mac.c.

References macaddr::a, macaddr::b, buf, macaddr::c, macaddr::d, macaddr::e, macaddr::f, palloc(), PG_GETARG_POINTER, PG_RETURN_MACADDR_P, and pq_getmsgbyte().

{
    StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
    macaddr    *addr;

    addr = (macaddr *) palloc(sizeof(macaddr));

    addr->a = pq_getmsgbyte(buf);
    addr->b = pq_getmsgbyte(buf);
    addr->c = pq_getmsgbyte(buf);
    addr->d = pq_getmsgbyte(buf);
    addr->e = pq_getmsgbyte(buf);
    addr->f = pq_getmsgbyte(buf);

    PG_RETURN_MACADDR_P(addr);
}

Datum macaddr_send ( PG_FUNCTION_ARGS   ) 
Datum macaddr_trunc ( PG_FUNCTION_ARGS   ) 

Definition at line 302 of file mac.c.

References macaddr::a, macaddr::b, macaddr::c, macaddr::d, macaddr::e, macaddr::f, palloc(), PG_GETARG_MACADDR_P, and PG_RETURN_MACADDR_P.

{
    macaddr    *addr = PG_GETARG_MACADDR_P(0);
    macaddr    *result;

    result = (macaddr *) palloc(sizeof(macaddr));

    result->a = addr->a;
    result->b = addr->b;
    result->c = addr->c;
    result->d = 0;
    result->e = 0;
    result->f = 0;

    PG_RETURN_MACADDR_P(result);
}

Datum md5_bytea ( PG_FUNCTION_ARGS   ) 

Definition at line 3660 of file varlena.c.

References cstring_to_text(), ereport, errcode(), errmsg(), ERROR, MD5_HASH_LEN, PG_GETARG_BYTEA_PP, pg_md5_hash(), PG_RETURN_TEXT_P, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    bytea      *in = PG_GETARG_BYTEA_PP(0);
    size_t      len;
    char        hexsum[MD5_HASH_LEN + 1];

    len = VARSIZE_ANY_EXHDR(in);
    if (pg_md5_hash(VARDATA_ANY(in), len, hexsum) == false)
        ereport(ERROR,
                (errcode(ERRCODE_OUT_OF_MEMORY),
                 errmsg("out of memory")));

    PG_RETURN_TEXT_P(cstring_to_text(hexsum));
}

Datum md5_text ( PG_FUNCTION_ARGS   ) 

Definition at line 3636 of file varlena.c.

References cstring_to_text(), ereport, errcode(), errmsg(), ERROR, MD5_HASH_LEN, PG_GETARG_TEXT_PP, pg_md5_hash(), PG_RETURN_TEXT_P, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    text       *in_text = PG_GETARG_TEXT_PP(0);
    size_t      len;
    char        hexsum[MD5_HASH_LEN + 1];

    /* Calculate the length of the buffer using varlena metadata */
    len = VARSIZE_ANY_EXHDR(in_text);

    /* get the hash result */
    if (pg_md5_hash(VARDATA_ANY(in_text), len, hexsum) == false)
        ereport(ERROR,
                (errcode(ERRCODE_OUT_OF_MEMORY),
                 errmsg("out of memory")));

    /* convert to text and return it */
    PG_RETURN_TEXT_P(cstring_to_text(hexsum));
}

Datum name_bpchar ( PG_FUNCTION_ARGS   ) 

Definition at line 401 of file varchar.c.

References cstring_to_text(), NameStr, PG_GETARG_NAME, and PG_RETURN_BPCHAR_P.

{
    Name        s = PG_GETARG_NAME(0);
    BpChar     *result;

    result = (BpChar *) cstring_to_text(NameStr(*s));
    PG_RETURN_BPCHAR_P(result);
}

Datum name_text ( PG_FUNCTION_ARGS   ) 

Definition at line 2282 of file varlena.c.

References cstring_to_text(), NameStr, PG_GETARG_NAME, and PG_RETURN_TEXT_P.

Referenced by nameiclike(), and nameicnlike().

int namecpy ( Name  n1,
Name  n2 
)

Definition at line 191 of file name.c.

References NAMEDATALEN, and NameStr.

{
    if (!n1 || !n2)
        return -1;
    strncpy(NameStr(*n1), NameStr(*n2), NAMEDATALEN);
    return 0;
}

Datum nameeq ( PG_FUNCTION_ARGS   ) 

Definition at line 134 of file name.c.

References NAMEDATALEN, NameStr, PG_GETARG_NAME, and PG_RETURN_BOOL.

{
    Name        arg1 = PG_GETARG_NAME(0);
    Name        arg2 = PG_GETARG_NAME(1);

    PG_RETURN_BOOL(strncmp(NameStr(*arg1), NameStr(*arg2), NAMEDATALEN) == 0);
}

Datum namege ( PG_FUNCTION_ARGS   ) 

Definition at line 179 of file name.c.

References NAMEDATALEN, NameStr, PG_GETARG_NAME, and PG_RETURN_BOOL.

{
    Name        arg1 = PG_GETARG_NAME(0);
    Name        arg2 = PG_GETARG_NAME(1);

    PG_RETURN_BOOL(strncmp(NameStr(*arg1), NameStr(*arg2), NAMEDATALEN) >= 0);
}

Datum namegt ( PG_FUNCTION_ARGS   ) 

Definition at line 170 of file name.c.

References NAMEDATALEN, NameStr, PG_GETARG_NAME, and PG_RETURN_BOOL.

{
    Name        arg1 = PG_GETARG_NAME(0);
    Name        arg2 = PG_GETARG_NAME(1);

    PG_RETURN_BOOL(strncmp(NameStr(*arg1), NameStr(*arg2), NAMEDATALEN) > 0);
}

Datum nameiclike ( PG_FUNCTION_ARGS   ) 
Datum nameicnlike ( PG_FUNCTION_ARGS   ) 
Datum nameicregexeq ( PG_FUNCTION_ARGS   ) 
Datum nameicregexne ( PG_FUNCTION_ARGS   ) 
Datum namein ( PG_FUNCTION_ARGS   ) 
Datum namele ( PG_FUNCTION_ARGS   ) 

Definition at line 161 of file name.c.

References NAMEDATALEN, NameStr, PG_GETARG_NAME, and PG_RETURN_BOOL.

{
    Name        arg1 = PG_GETARG_NAME(0);
    Name        arg2 = PG_GETARG_NAME(1);

    PG_RETURN_BOOL(strncmp(NameStr(*arg1), NameStr(*arg2), NAMEDATALEN) <= 0);
}

Datum namelike ( PG_FUNCTION_ARGS   ) 

Definition at line 230 of file like.c.

References GenericMatchText(), NameStr, PG_GETARG_NAME, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    Name        str = PG_GETARG_NAME(0);
    text       *pat = PG_GETARG_TEXT_PP(1);
    bool        result;
    char       *s,
               *p;
    int         slen,
                plen;

    s = NameStr(*str);
    slen = strlen(s);
    p = VARDATA_ANY(pat);
    plen = VARSIZE_ANY_EXHDR(pat);

    result = (GenericMatchText(s, slen, p, plen) == LIKE_TRUE);

    PG_RETURN_BOOL(result);
}

Datum namelt ( PG_FUNCTION_ARGS   ) 

Definition at line 152 of file name.c.

References NAMEDATALEN, NameStr, PG_GETARG_NAME, and PG_RETURN_BOOL.

{
    Name        arg1 = PG_GETARG_NAME(0);
    Name        arg2 = PG_GETARG_NAME(1);

    PG_RETURN_BOOL(strncmp(NameStr(*arg1), NameStr(*arg2), NAMEDATALEN) < 0);
}

Datum namene ( PG_FUNCTION_ARGS   ) 

Definition at line 143 of file name.c.

References NAMEDATALEN, NameStr, PG_GETARG_NAME, and PG_RETURN_BOOL.

{
    Name        arg1 = PG_GETARG_NAME(0);
    Name        arg2 = PG_GETARG_NAME(1);

    PG_RETURN_BOOL(strncmp(NameStr(*arg1), NameStr(*arg2), NAMEDATALEN) != 0);
}

Datum namenlike ( PG_FUNCTION_ARGS   ) 

Definition at line 251 of file like.c.

References GenericMatchText(), NameStr, PG_GETARG_NAME, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    Name        str = PG_GETARG_NAME(0);
    text       *pat = PG_GETARG_TEXT_PP(1);
    bool        result;
    char       *s,
               *p;
    int         slen,
                plen;

    s = NameStr(*str);
    slen = strlen(s);
    p = VARDATA_ANY(pat);
    plen = VARSIZE_ANY_EXHDR(pat);

    result = (GenericMatchText(s, slen, p, plen) != LIKE_TRUE);

    PG_RETURN_BOOL(result);
}

Datum nameout ( PG_FUNCTION_ARGS   ) 
Datum namerecv ( PG_FUNCTION_ARGS   ) 

Definition at line 80 of file name.c.

References buf, StringInfoData::cursor, ereport, errcode(), errdetail(), errmsg(), ERROR, StringInfoData::len, NAMEDATALEN, palloc0(), pfree(), PG_GETARG_POINTER, PG_RETURN_NAME, and pq_getmsgtext().

{
    StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
    Name        result;
    char       *str;
    int         nbytes;

    str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
    if (nbytes >= NAMEDATALEN)
        ereport(ERROR,
                (errcode(ERRCODE_NAME_TOO_LONG),
                 errmsg("identifier too long"),
                 errdetail("Identifier must be less than %d characters.",
                           NAMEDATALEN)));
    result = (NameData *) palloc0(NAMEDATALEN);
    memcpy(result, str, nbytes);
    pfree(str);
    PG_RETURN_NAME(result);
}

Datum nameregexeq ( PG_FUNCTION_ARGS   ) 
Datum nameregexne ( PG_FUNCTION_ARGS   ) 
Datum namesend ( PG_FUNCTION_ARGS   ) 
int namestrcmp ( Name  name,
const char *  str 
)

Definition at line 248 of file name.c.

References NameStr.

Referenced by attnameAttNum(), CopyGetAttnums(), CreateTrigger(), get_timetravel(), GetAttributeByName(), set_timetravel(), and SPI_fnumber().

{
    if (!name && !str)
        return 0;
    if (!name)
        return -1;              /* NULL < anything */
    if (!str)
        return 1;               /* NULL < anything */
    return strncmp(NameStr(*name), str, NAMEDATALEN);
}

int namestrcpy ( Name  name,
const char *  str 
)
Datum network_broadcast ( PG_FUNCTION_ARGS   ) 

Definition at line 715 of file network.c.

References ip_addr, ip_bits, ip_family, palloc0(), PG_GETARG_INET_PP, PG_RETURN_INET_P, and SET_INET_VARSIZE.

Referenced by network_scan_last().

{
    inet       *ip = PG_GETARG_INET_PP(0);
    inet       *dst;
    int         byte;
    int         bits;
    int         maxbytes;
    unsigned char mask;
    unsigned char *a,
               *b;

    /* make sure any unused bits are zeroed */
    dst = (inet *) palloc0(sizeof(inet));

    if (ip_family(ip) == PGSQL_AF_INET)
        maxbytes = 4;
    else
        maxbytes = 16;

    bits = ip_bits(ip);
    a = ip_addr(ip);
    b = ip_addr(dst);

    for (byte = 0; byte < maxbytes; byte++)
    {
        if (bits >= 8)
        {
            mask = 0x00;
            bits -= 8;
        }
        else if (bits == 0)
            mask = 0xff;
        else
        {
            mask = 0xff >> bits;
            bits = 0;
        }

        b[byte] = a[byte] | mask;
    }

    ip_family(dst) = ip_family(ip);
    ip_bits(dst) = ip_bits(ip);
    SET_INET_VARSIZE(dst);

    PG_RETURN_INET_P(dst);
}

Datum network_cmp ( PG_FUNCTION_ARGS   ) 
Datum network_eq ( PG_FUNCTION_ARGS   ) 
Datum network_family ( PG_FUNCTION_ARGS   ) 

Definition at line 696 of file network.c.

References ip_family, PG_GETARG_INET_PP, PG_RETURN_INT32, PGSQL_AF_INET, and PGSQL_AF_INET6.

{
    inet       *ip = PG_GETARG_INET_PP(0);

    switch (ip_family(ip))
    {
        case PGSQL_AF_INET:
            PG_RETURN_INT32(4);
            break;
        case PGSQL_AF_INET6:
            PG_RETURN_INT32(6);
            break;
        default:
            PG_RETURN_INT32(0);
            break;
    }
}

Datum network_ge ( PG_FUNCTION_ARGS   ) 
Datum network_gt ( PG_FUNCTION_ARGS   ) 
Datum network_host ( PG_FUNCTION_ARGS   ) 

Definition at line 603 of file network.c.

References cstring_to_text(), ereport, errcode(), errmsg(), ERROR, inet_net_ntop(), ip_addr, ip_family, ip_maxbits, PG_GETARG_INET_PP, and PG_RETURN_TEXT_P.

{
    inet       *ip = PG_GETARG_INET_PP(0);
    char       *ptr;
    char        tmp[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255/128")];

    /* force display of max bits, regardless of masklen... */
    if (inet_net_ntop(ip_family(ip), ip_addr(ip), ip_maxbits(ip),
                      tmp, sizeof(tmp)) == NULL)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
                 errmsg("could not format inet value: %m")));

    /* Suppress /n if present (shouldn't happen now) */
    if ((ptr = strchr(tmp, '/')) != NULL)
        *ptr = '\0';

    PG_RETURN_TEXT_P(cstring_to_text(tmp));
}

Datum network_hostmask ( PG_FUNCTION_ARGS   ) 

Definition at line 850 of file network.c.

References ip_addr, ip_bits, ip_family, ip_maxbits, palloc0(), PG_GETARG_INET_PP, PG_RETURN_INET_P, and SET_INET_VARSIZE.

{
    inet       *ip = PG_GETARG_INET_PP(0);
    inet       *dst;
    int         byte;
    int         bits;
    int         maxbytes;
    unsigned char mask;
    unsigned char *b;

    /* make sure any unused bits are zeroed */
    dst = (inet *) palloc0(sizeof(inet));

    if (ip_family(ip) == PGSQL_AF_INET)
        maxbytes = 4;
    else
        maxbytes = 16;

    bits = ip_maxbits(ip) - ip_bits(ip);
    b = ip_addr(dst);

    byte = maxbytes - 1;

    while (bits)
    {
        if (bits >= 8)
        {
            mask = 0xff;
            bits -= 8;
        }
        else
        {
            mask = 0xff >> (8 - bits);
            bits = 0;
        }

        b[byte] = mask;
        byte--;
    }

    ip_family(dst) = ip_family(ip);
    ip_bits(dst) = ip_maxbits(ip);
    SET_INET_VARSIZE(dst);

    PG_RETURN_INET_P(dst);
}

Datum network_le ( PG_FUNCTION_ARGS   ) 
Datum network_lt ( PG_FUNCTION_ARGS   ) 
Datum network_masklen ( PG_FUNCTION_ARGS   ) 

Definition at line 688 of file network.c.

References ip_bits, PG_GETARG_INET_PP, and PG_RETURN_INT32.

Datum network_ne ( PG_FUNCTION_ARGS   ) 
Datum network_netmask ( PG_FUNCTION_ARGS   ) 

Definition at line 808 of file network.c.

References ip_addr, ip_bits, ip_family, ip_maxbits, palloc0(), PG_GETARG_INET_PP, PG_RETURN_INET_P, and SET_INET_VARSIZE.

{
    inet       *ip = PG_GETARG_INET_PP(0);
    inet       *dst;
    int         byte;
    int         bits;
    unsigned char mask;
    unsigned char *b;

    /* make sure any unused bits are zeroed */
    dst = (inet *) palloc0(sizeof(inet));

    bits = ip_bits(ip);
    b = ip_addr(dst);

    byte = 0;

    while (bits)
    {
        if (bits >= 8)
        {
            mask = 0xff;
            bits -= 8;
        }
        else
        {
            mask = 0xff << (8 - bits);
            bits = 0;
        }

        b[byte] = mask;
        byte++;
    }

    ip_family(dst) = ip_family(ip);
    ip_bits(dst) = ip_maxbits(ip);
    SET_INET_VARSIZE(dst);

    PG_RETURN_INET_P(dst);
}

Datum network_network ( PG_FUNCTION_ARGS   ) 

Definition at line 764 of file network.c.

References ip_addr, ip_bits, ip_family, palloc0(), PG_GETARG_INET_PP, PG_RETURN_INET_P, and SET_INET_VARSIZE.

Referenced by network_scan_first().

{
    inet       *ip = PG_GETARG_INET_PP(0);
    inet       *dst;
    int         byte;
    int         bits;
    unsigned char mask;
    unsigned char *a,
               *b;

    /* make sure any unused bits are zeroed */
    dst = (inet *) palloc0(sizeof(inet));

    bits = ip_bits(ip);
    a = ip_addr(ip);
    b = ip_addr(dst);

    byte = 0;

    while (bits)
    {
        if (bits >= 8)
        {
            mask = 0xff;
            bits -= 8;
        }
        else
        {
            mask = 0xff << (8 - bits);
            bits = 0;
        }

        b[byte] = a[byte] & mask;
        byte++;
    }

    ip_family(dst) = ip_family(ip);
    ip_bits(dst) = ip_bits(ip);
    SET_INET_VARSIZE(dst);

    PG_RETURN_INET_P(dst);
}

Datum network_scan_first ( Datum  in  ) 

Definition at line 1044 of file network.c.

References DirectFunctionCall1, and network_network().

Referenced by network_prefix_quals().

Datum network_scan_last ( Datum  in  ) 
Datum network_show ( PG_FUNCTION_ARGS   ) 

Definition at line 629 of file network.c.

References cstring_to_text(), ereport, errcode(), errmsg(), ERROR, inet_net_ntop(), ip_addr, ip_bits, ip_family, ip_maxbits, PG_GETARG_INET_PP, PG_RETURN_TEXT_P, and snprintf().

{
    inet       *ip = PG_GETARG_INET_PP(0);
    int         len;
    char        tmp[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255/128")];

    if (inet_net_ntop(ip_family(ip), ip_addr(ip), ip_maxbits(ip),
                      tmp, sizeof(tmp)) == NULL)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
                 errmsg("could not format inet value: %m")));

    /* Add /n if not present (which it won't be) */
    if (strchr(tmp, '/') == NULL)
    {
        len = strlen(tmp);
        snprintf(tmp + len, sizeof(tmp) - len, "/%u", ip_bits(ip));
    }

    PG_RETURN_TEXT_P(cstring_to_text(tmp));
}

Datum network_sub ( PG_FUNCTION_ARGS   ) 

Definition at line 540 of file network.c.

References a1, a2, bitncmp(), ip_addr, ip_bits, ip_family, PG_GETARG_INET_PP, and PG_RETURN_BOOL.

{
    inet       *a1 = PG_GETARG_INET_PP(0);
    inet       *a2 = PG_GETARG_INET_PP(1);

    if (ip_family(a1) == ip_family(a2))
    {
        PG_RETURN_BOOL(ip_bits(a1) > ip_bits(a2)
                     && bitncmp(ip_addr(a1), ip_addr(a2), ip_bits(a2)) == 0);
    }

    PG_RETURN_BOOL(false);
}

Datum network_subeq ( PG_FUNCTION_ARGS   ) 

Definition at line 555 of file network.c.

References a1, a2, bitncmp(), ip_addr, ip_bits, ip_family, PG_GETARG_INET_PP, and PG_RETURN_BOOL.

{
    inet       *a1 = PG_GETARG_INET_PP(0);
    inet       *a2 = PG_GETARG_INET_PP(1);

    if (ip_family(a1) == ip_family(a2))
    {
        PG_RETURN_BOOL(ip_bits(a1) >= ip_bits(a2)
                     && bitncmp(ip_addr(a1), ip_addr(a2), ip_bits(a2)) == 0);
    }

    PG_RETURN_BOOL(false);
}

Datum network_sup ( PG_FUNCTION_ARGS   ) 

Definition at line 570 of file network.c.

References a1, a2, bitncmp(), ip_addr, ip_bits, ip_family, PG_GETARG_INET_PP, and PG_RETURN_BOOL.

{
    inet       *a1 = PG_GETARG_INET_PP(0);
    inet       *a2 = PG_GETARG_INET_PP(1);

    if (ip_family(a1) == ip_family(a2))
    {
        PG_RETURN_BOOL(ip_bits(a1) < ip_bits(a2)
                     && bitncmp(ip_addr(a1), ip_addr(a2), ip_bits(a1)) == 0);
    }

    PG_RETURN_BOOL(false);
}

Datum network_supeq ( PG_FUNCTION_ARGS   ) 

Definition at line 585 of file network.c.

References a1, a2, bitncmp(), ip_addr, ip_bits, ip_family, PG_GETARG_INET_PP, and PG_RETURN_BOOL.

{
    inet       *a1 = PG_GETARG_INET_PP(0);
    inet       *a2 = PG_GETARG_INET_PP(1);

    if (ip_family(a1) == ip_family(a2))
    {
        PG_RETURN_BOOL(ip_bits(a1) <= ip_bits(a2)
                     && bitncmp(ip_addr(a1), ip_addr(a2), ip_bits(a1)) == 0);
    }

    PG_RETURN_BOOL(false);
}

Datum numeric ( PG_FUNCTION_ARGS   ) 

Definition at line 768 of file numeric.c.

References apply_typmod(), NumericData::choice, DEC_DIGITS, free_var(), init_var, make_result(), maxdigits, NumericShort::n_header, NumericChoice::n_short, NUMERIC_CAN_BE_SHORT, NUMERIC_DSCALE, NUMERIC_DSCALE_MASK, NUMERIC_IS_NAN, NUMERIC_IS_SHORT, NUMERIC_SHORT_DSCALE_SHIFT, NUMERIC_SIGN, NUMERIC_WEIGHT, palloc(), PG_GETARG_INT32, PG_GETARG_NUMERIC, PG_RETURN_NUMERIC, scale, set_var_from_num(), VARHDRSZ, and VARSIZE.

{
    Numeric     num = PG_GETARG_NUMERIC(0);
    int32       typmod = PG_GETARG_INT32(1);
    Numeric     new;
    int32       tmp_typmod;
    int         precision;
    int         scale;
    int         ddigits;
    int         maxdigits;
    NumericVar  var;

    /*
     * Handle NaN
     */
    if (NUMERIC_IS_NAN(num))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    /*
     * If the value isn't a valid type modifier, simply return a copy of the
     * input value
     */
    if (typmod < (int32) (VARHDRSZ))
    {
        new = (Numeric) palloc(VARSIZE(num));
        memcpy(new, num, VARSIZE(num));
        PG_RETURN_NUMERIC(new);
    }

    /*
     * Get the precision and scale out of the typmod value
     */
    tmp_typmod = typmod - VARHDRSZ;
    precision = (tmp_typmod >> 16) & 0xffff;
    scale = tmp_typmod & 0xffff;
    maxdigits = precision - scale;

    /*
     * If the number is certainly in bounds and due to the target scale no
     * rounding could be necessary, just make a copy of the input and modify
     * its scale fields, unless the larger scale forces us to abandon the
     * short representation.  (Note we assume the existing dscale is
     * honest...)
     */
    ddigits = (NUMERIC_WEIGHT(num) + 1) * DEC_DIGITS;
    if (ddigits <= maxdigits && scale >= NUMERIC_DSCALE(num)
        && (NUMERIC_CAN_BE_SHORT(scale, NUMERIC_WEIGHT(num))
            || !NUMERIC_IS_SHORT(num)))
    {
        new = (Numeric) palloc(VARSIZE(num));
        memcpy(new, num, VARSIZE(num));
        if (NUMERIC_IS_SHORT(num))
            new->choice.n_short.n_header =
                (num->choice.n_short.n_header & ~NUMERIC_SHORT_DSCALE_MASK)
                | (scale << NUMERIC_SHORT_DSCALE_SHIFT);
        else
            new->choice.n_long.n_sign_dscale = NUMERIC_SIGN(new) |
                ((uint16) scale & NUMERIC_DSCALE_MASK);
        PG_RETURN_NUMERIC(new);
    }

    /*
     * We really need to fiddle with things - unpack the number into a
     * variable and let apply_typmod() do it.
     */
    init_var(&var);

    set_var_from_num(num, &var);
    apply_typmod(&var, typmod);
    new = make_result(&var);

    free_var(&var);

    PG_RETURN_NUMERIC(new);
}

Datum numeric_abs ( PG_FUNCTION_ARGS   ) 

Definition at line 914 of file numeric.c.

References NumericData::choice, make_result(), NumericShort::n_header, NumericChoice::n_long, NumericChoice::n_short, NumericLong::n_sign_dscale, NUMERIC_DSCALE, NUMERIC_IS_NAN, NUMERIC_IS_SHORT, NUMERIC_POS, palloc(), PG_GETARG_NUMERIC, PG_RETURN_NUMERIC, and VARSIZE.

{
    Numeric     num = PG_GETARG_NUMERIC(0);
    Numeric     res;

    /*
     * Handle NaN
     */
    if (NUMERIC_IS_NAN(num))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    /*
     * Do it the easy way directly on the packed format
     */
    res = (Numeric) palloc(VARSIZE(num));
    memcpy(res, num, VARSIZE(num));

    if (NUMERIC_IS_SHORT(num))
        res->choice.n_short.n_header =
            num->choice.n_short.n_header & ~NUMERIC_SHORT_SIGN_MASK;
    else
        res->choice.n_long.n_sign_dscale = NUMERIC_POS | NUMERIC_DSCALE(num);

    PG_RETURN_NUMERIC(res);
}

Datum numeric_accum ( PG_FUNCTION_ARGS   ) 
Datum numeric_add ( PG_FUNCTION_ARGS   ) 

Definition at line 1548 of file numeric.c.

References add_var(), free_var(), init_var, init_var_from_num(), make_result(), NUMERIC_IS_NAN, PG_GETARG_NUMERIC, and PG_RETURN_NUMERIC.

Referenced by do_numeric_accum(), do_numeric_avg_accum(), int8_sum(), and numeric_plus_one_over_two().

{
    Numeric     num1 = PG_GETARG_NUMERIC(0);
    Numeric     num2 = PG_GETARG_NUMERIC(1);
    NumericVar  arg1;
    NumericVar  arg2;
    NumericVar  result;
    Numeric     res;

    /*
     * Handle NaN
     */
    if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    /*
     * Unpack the values, let add_var() compute the result and return it.
     */
    init_var_from_num(num1, &arg1);
    init_var_from_num(num2, &arg2);

    init_var(&result);
    add_var(&arg1, &arg2, &result);

    res = make_result(&result);

    free_var(&result);

    PG_RETURN_NUMERIC(res);
}

Datum numeric_avg ( PG_FUNCTION_ARGS   ) 

Definition at line 2631 of file numeric.c.

References DatumGetNumeric, deconstruct_array(), DirectFunctionCall2, elog, ERROR, NULL, numeric_div(), NUMERIC_NDIGITS, NumericGetDatum, NUMERICOID, PG_GETARG_ARRAYTYPE_P, PG_RETURN_DATUM, and PG_RETURN_NULL.

{
    ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    Datum      *transdatums;
    int         ndatums;
    Numeric     N,
                sumX;

    /* We assume the input is array of numeric */
    deconstruct_array(transarray,
                      NUMERICOID, -1, false, 'i',
                      &transdatums, NULL, &ndatums);
    if (ndatums != 2)
        elog(ERROR, "expected 2-element numeric array");
    N = DatumGetNumeric(transdatums[0]);
    sumX = DatumGetNumeric(transdatums[1]);

    /* SQL defines AVG of no values to be NULL */
    /* N is zero iff no digits (cf. numeric_uminus) */
    if (NUMERIC_NDIGITS(N) == 0)
        PG_RETURN_NULL();

    PG_RETURN_DATUM(DirectFunctionCall2(numeric_div,
                                        NumericGetDatum(sumX),
                                        NumericGetDatum(N)));
}

Datum numeric_avg_accum ( PG_FUNCTION_ARGS   ) 
Datum numeric_ceil ( PG_FUNCTION_ARGS   ) 

Definition at line 1142 of file numeric.c.

References ceil_var(), free_var(), init_var_from_num(), make_result(), NUMERIC_IS_NAN, PG_GETARG_NUMERIC, and PG_RETURN_NUMERIC.

{
    Numeric     num = PG_GETARG_NUMERIC(0);
    Numeric     res;
    NumericVar  result;

    if (NUMERIC_IS_NAN(num))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    init_var_from_num(num, &result);
    ceil_var(&result, &result);

    res = make_result(&result);
    free_var(&result);

    PG_RETURN_NUMERIC(res);
}

Datum numeric_cmp ( PG_FUNCTION_ARGS   ) 

Definition at line 1320 of file numeric.c.

References cmp_numerics(), PG_FREE_IF_COPY, PG_GETARG_NUMERIC, and PG_RETURN_INT32.

Referenced by gbt_numeric_cmp(), and gin_numeric_cmp().

{
    Numeric     num1 = PG_GETARG_NUMERIC(0);
    Numeric     num2 = PG_GETARG_NUMERIC(1);
    int         result;

    result = cmp_numerics(num1, num2);

    PG_FREE_IF_COPY(num1, 0);
    PG_FREE_IF_COPY(num2, 1);

    PG_RETURN_INT32(result);
}

Datum numeric_div ( PG_FUNCTION_ARGS   ) 

Definition at line 1666 of file numeric.c.

References div_var(), free_var(), init_var, init_var_from_num(), make_result(), NUMERIC_IS_NAN, PG_GETARG_NUMERIC, PG_RETURN_NUMERIC, and select_div_scale().

Referenced by cash_numeric(), gbt_numeric_penalty(), int8_avg(), and numeric_avg().

{
    Numeric     num1 = PG_GETARG_NUMERIC(0);
    Numeric     num2 = PG_GETARG_NUMERIC(1);
    NumericVar  arg1;
    NumericVar  arg2;
    NumericVar  result;
    Numeric     res;
    int         rscale;

    /*
     * Handle NaN
     */
    if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    /*
     * Unpack the arguments
     */
    init_var_from_num(num1, &arg1);
    init_var_from_num(num2, &arg2);

    init_var(&result);

    /*
     * Select scale for division result
     */
    rscale = select_div_scale(&arg1, &arg2);

    /*
     * Do the divide and return the result
     */
    div_var(&arg1, &arg2, &result, rscale, true);

    res = make_result(&result);

    free_var(&result);

    PG_RETURN_NUMERIC(res);
}

Datum numeric_div_trunc ( PG_FUNCTION_ARGS   ) 

Definition at line 1714 of file numeric.c.

References div_var(), free_var(), init_var, init_var_from_num(), make_result(), NUMERIC_IS_NAN, PG_GETARG_NUMERIC, and PG_RETURN_NUMERIC.

Referenced by numeric_plus_one_over_two(), and numeric_shift_right().

{
    Numeric     num1 = PG_GETARG_NUMERIC(0);
    Numeric     num2 = PG_GETARG_NUMERIC(1);
    NumericVar  arg1;
    NumericVar  arg2;
    NumericVar  result;
    Numeric     res;

    /*
     * Handle NaN
     */
    if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    /*
     * Unpack the arguments
     */
    init_var_from_num(num1, &arg1);
    init_var_from_num(num2, &arg2);

    init_var(&result);

    /*
     * Do the divide and return the result
     */
    div_var(&arg1, &arg2, &result, 0, false);

    res = make_result(&result);

    free_var(&result);

    PG_RETURN_NUMERIC(res);
}

Datum numeric_eq ( PG_FUNCTION_ARGS   ) 

Definition at line 1336 of file numeric.c.

References cmp_numerics(), PG_FREE_IF_COPY, PG_GETARG_NUMERIC, and PG_RETURN_BOOL.

Referenced by gbt_numeric_eq().

{
    Numeric     num1 = PG_GETARG_NUMERIC(0);
    Numeric     num2 = PG_GETARG_NUMERIC(1);
    bool        result;

    result = cmp_numerics(num1, num2) == 0;

    PG_FREE_IF_COPY(num1, 0);
    PG_FREE_IF_COPY(num2, 1);

    PG_RETURN_BOOL(result);
}

Datum numeric_exp ( PG_FUNCTION_ARGS   ) 

Definition at line 1972 of file numeric.c.

References arg, NumericVar::dscale, exp_var(), free_var(), init_var, init_var_from_num(), make_result(), Max, Min, NUMERIC_IS_NAN, NUMERIC_MAX_DISPLAY_SCALE, NUMERIC_MAX_RESULT_SCALE, NUMERIC_MIN_DISPLAY_SCALE, NUMERIC_MIN_SIG_DIGITS, numericvar_to_double_no_overflow(), PG_GETARG_NUMERIC, PG_RETURN_NUMERIC, and val.

{
    Numeric     num = PG_GETARG_NUMERIC(0);
    Numeric     res;
    NumericVar  arg;
    NumericVar  result;
    int         rscale;
    double      val;

    /*
     * Handle NaN
     */
    if (NUMERIC_IS_NAN(num))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    /*
     * Unpack the argument and determine the result scale.  We choose a scale
     * to give at least NUMERIC_MIN_SIG_DIGITS significant digits; but in any
     * case not less than the input's dscale.
     */
    init_var_from_num(num, &arg);

    init_var(&result);

    /* convert input to float8, ignoring overflow */
    val = numericvar_to_double_no_overflow(&arg);

    /*
     * log10(result) = num * log10(e), so this is approximately the decimal
     * weight of the result:
     */
    val *= 0.434294481903252;

    /* limit to something that won't cause integer overflow */
    val = Max(val, -NUMERIC_MAX_RESULT_SCALE);
    val = Min(val, NUMERIC_MAX_RESULT_SCALE);

    rscale = NUMERIC_MIN_SIG_DIGITS - (int) val;
    rscale = Max(rscale, arg.dscale);
    rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
    rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);

    /*
     * Let exp_var() do the calculation and return the result.
     */
    exp_var(&arg, &result, rscale);

    res = make_result(&result);

    free_var(&result);

    PG_RETURN_NUMERIC(res);
}

Datum numeric_fac ( PG_FUNCTION_ARGS   ) 

Definition at line 1873 of file numeric.c.

References CHECK_FOR_INTERRUPTS, ereport, errcode(), errmsg(), ERROR, free_var(), init_var, int8_to_numericvar(), make_result(), mul_var(), PG_GETARG_INT64, and PG_RETURN_NUMERIC.

{
    int64       num = PG_GETARG_INT64(0);
    Numeric     res;
    NumericVar  fact;
    NumericVar  result;

    if (num <= 1)
    {
        res = make_result(&const_one);
        PG_RETURN_NUMERIC(res);
    }
    /* Fail immediately if the result would overflow */
    if (num > 32177)
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("value overflows numeric format")));

    init_var(&fact);
    init_var(&result);

    int8_to_numericvar(num, &result);

    for (num = num - 1; num > 1; num--)
    {
        /* this loop can take awhile, so allow it to be interrupted */
        CHECK_FOR_INTERRUPTS();

        int8_to_numericvar(num, &fact);

        mul_var(&result, &fact, &result, 0);
    }

    res = make_result(&result);

    free_var(&fact);
    free_var(&result);

    PG_RETURN_NUMERIC(res);
}

Datum numeric_float4 ( PG_FUNCTION_ARGS   ) 
Datum numeric_float8 ( PG_FUNCTION_ARGS   ) 
Datum numeric_float8_no_overflow ( PG_FUNCTION_ARGS   ) 
Datum numeric_floor ( PG_FUNCTION_ARGS   ) 

Definition at line 1167 of file numeric.c.

References floor_var(), free_var(), init_var_from_num(), make_result(), NUMERIC_IS_NAN, PG_GETARG_NUMERIC, and PG_RETURN_NUMERIC.

{
    Numeric     num = PG_GETARG_NUMERIC(0);
    Numeric     res;
    NumericVar  result;

    if (NUMERIC_IS_NAN(num))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    init_var_from_num(num, &result);
    floor_var(&result, &result);

    res = make_result(&result);
    free_var(&result);

    PG_RETURN_NUMERIC(res);
}

Datum numeric_ge ( PG_FUNCTION_ARGS   ) 

Definition at line 1381 of file numeric.c.

References cmp_numerics(), PG_FREE_IF_COPY, PG_GETARG_NUMERIC, and PG_RETURN_BOOL.

Referenced by gbt_numeric_ge().

{
    Numeric     num1 = PG_GETARG_NUMERIC(0);
    Numeric     num2 = PG_GETARG_NUMERIC(1);
    bool        result;

    result = cmp_numerics(num1, num2) >= 0;

    PG_FREE_IF_COPY(num1, 0);
    PG_FREE_IF_COPY(num2, 1);

    PG_RETURN_BOOL(result);
}

Datum numeric_gt ( PG_FUNCTION_ARGS   ) 

Definition at line 1366 of file numeric.c.

References cmp_numerics(), PG_FREE_IF_COPY, PG_GETARG_NUMERIC, and PG_RETURN_BOOL.

Referenced by gbt_numeric_gt(), and gbt_numeric_penalty().

{
    Numeric     num1 = PG_GETARG_NUMERIC(0);
    Numeric     num2 = PG_GETARG_NUMERIC(1);
    bool        result;

    result = cmp_numerics(num1, num2) > 0;

    PG_FREE_IF_COPY(num1, 0);
    PG_FREE_IF_COPY(num2, 1);

    PG_RETURN_BOOL(result);
}

Datum numeric_in ( PG_FUNCTION_ARGS   ) 

Definition at line 451 of file numeric.c.

References apply_typmod(), ereport, errcode(), errmsg(), ERROR, free_var(), init_var, make_result(), PG_GETARG_CSTRING, PG_GETARG_INT32, PG_GETARG_OID, PG_RETURN_NUMERIC, pg_strncasecmp(), set_var_from_str(), and value.

Referenced by make_const(), numeric_to_number(), and ssl_client_serial().

{
    char       *str = PG_GETARG_CSTRING(0);

#ifdef NOT_USED
    Oid         typelem = PG_GETARG_OID(1);
#endif
    int32       typmod = PG_GETARG_INT32(2);
    Numeric     res;
    const char *cp;

    /* Skip leading spaces */
    cp = str;
    while (*cp)
    {
        if (!isspace((unsigned char) *cp))
            break;
        cp++;
    }

    /*
     * Check for NaN
     */
    if (pg_strncasecmp(cp, "NaN", 3) == 0)
    {
        res = make_result(&const_nan);

        /* Should be nothing left but spaces */
        cp += 3;
        while (*cp)
        {
            if (!isspace((unsigned char) *cp))
                ereport(ERROR,
                        (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                      errmsg("invalid input syntax for type numeric: \"%s\"",
                             str)));
            cp++;
        }
    }
    else
    {
        /*
         * Use set_var_from_str() to parse a normal numeric value
         */
        NumericVar  value;

        init_var(&value);

        cp = set_var_from_str(str, cp, &value);

        /*
         * We duplicate a few lines of code here because we would like to
         * throw any trailing-junk syntax error before any semantic error
         * resulting from apply_typmod.  We can't easily fold the two cases
         * together because we mustn't apply apply_typmod to a NaN.
         */
        while (*cp)
        {
            if (!isspace((unsigned char) *cp))
                ereport(ERROR,
                        (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                      errmsg("invalid input syntax for type numeric: \"%s\"",
                             str)));
            cp++;
        }

        apply_typmod(&value, typmod);

        res = make_result(&value);
        free_var(&value);
    }

    PG_RETURN_NUMERIC(res);
}

Datum numeric_inc ( PG_FUNCTION_ARGS   ) 

Definition at line 1789 of file numeric.c.

References add_var(), arg, free_var(), init_var_from_num(), make_result(), NUMERIC_IS_NAN, PG_GETARG_NUMERIC, and PG_RETURN_NUMERIC.

Referenced by do_numeric_accum(), and do_numeric_avg_accum().

{
    Numeric     num = PG_GETARG_NUMERIC(0);
    NumericVar  arg;
    Numeric     res;

    /*
     * Handle NaN
     */
    if (NUMERIC_IS_NAN(num))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    /*
     * Compute the result and return it
     */
    init_var_from_num(num, &arg);

    add_var(&arg, &const_one, &arg);

    res = make_result(&arg);

    free_var(&arg);

    PG_RETURN_NUMERIC(res);
}

Datum numeric_int2 ( PG_FUNCTION_ARGS   ) 

Definition at line 2320 of file numeric.c.

References ereport, errcode(), errmsg(), ERROR, init_var_from_num(), NUMERIC_IS_NAN, numericvar_to_int8(), PG_GETARG_NUMERIC, PG_RETURN_INT16, and val.

{
    Numeric     num = PG_GETARG_NUMERIC(0);
    NumericVar  x;
    int64       val;
    int16       result;

    /* XXX would it be better to return NULL? */
    if (NUMERIC_IS_NAN(num))
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("cannot convert NaN to smallint")));

    /* Convert to variable format and thence to int8 */
    init_var_from_num(num, &x);

    if (!numericvar_to_int8(&x, &val))
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("smallint out of range")));

    /* Down-convert to int2 */
    result = (int16) val;

    /* Test for overflow by reverse-conversion. */
    if ((int64) result != val)
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("smallint out of range")));

    PG_RETURN_INT16(result);
}

Datum numeric_int4 ( PG_FUNCTION_ARGS   ) 

Definition at line 2210 of file numeric.c.

References ereport, errcode(), errmsg(), ERROR, init_var_from_num(), NUMERIC_IS_NAN, numericvar_to_int4(), PG_GETARG_NUMERIC, and PG_RETURN_INT32.

Referenced by numeric_to_char().

{
    Numeric     num = PG_GETARG_NUMERIC(0);
    NumericVar  x;
    int32       result;

    /* XXX would it be better to return NULL? */
    if (NUMERIC_IS_NAN(num))
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("cannot convert NaN to integer")));

    /* Convert to variable format, then convert to int4 */
    init_var_from_num(num, &x);
    result = numericvar_to_int4(&x);
    PG_RETURN_INT32(result);
}

Datum numeric_int8 ( PG_FUNCTION_ARGS   ) 

Definition at line 2276 of file numeric.c.

References ereport, errcode(), errmsg(), ERROR, init_var_from_num(), NUMERIC_IS_NAN, numericvar_to_int8(), PG_GETARG_NUMERIC, and PG_RETURN_INT64.

Referenced by numeric_cash().

{
    Numeric     num = PG_GETARG_NUMERIC(0);
    NumericVar  x;
    int64       result;

    /* XXX would it be better to return NULL? */
    if (NUMERIC_IS_NAN(num))
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("cannot convert NaN to bigint")));

    /* Convert to variable format and thence to int8 */
    init_var_from_num(num, &x);

    if (!numericvar_to_int8(&x, &result))
        ereport(ERROR,
                (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                 errmsg("bigint out of range")));

    PG_RETURN_INT64(result);
}

Datum numeric_larger ( PG_FUNCTION_ARGS   ) 

Definition at line 1844 of file numeric.c.

References cmp_numerics(), PG_GETARG_NUMERIC, and PG_RETURN_NUMERIC.

{
    Numeric     num1 = PG_GETARG_NUMERIC(0);
    Numeric     num2 = PG_GETARG_NUMERIC(1);

    /*
     * Use cmp_numerics so that this will agree with the comparison operators,
     * particularly as regards comparisons involving NaN.
     */
    if (cmp_numerics(num1, num2) > 0)
        PG_RETURN_NUMERIC(num1);
    else
        PG_RETURN_NUMERIC(num2);
}

Datum numeric_le ( PG_FUNCTION_ARGS   ) 

Definition at line 1411 of file numeric.c.

References cmp_numerics(), PG_FREE_IF_COPY, PG_GETARG_NUMERIC, and PG_RETURN_BOOL.

Referenced by gbt_numeric_le().

{
    Numeric     num1 = PG_GETARG_NUMERIC(0);
    Numeric     num2 = PG_GETARG_NUMERIC(1);
    bool        result;

    result = cmp_numerics(num1, num2) <= 0;

    PG_FREE_IF_COPY(num1, 0);
    PG_FREE_IF_COPY(num2, 1);

    PG_RETURN_BOOL(result);
}

Datum numeric_ln ( PG_FUNCTION_ARGS   ) 

Definition at line 2033 of file numeric.c.

References arg, DEC_DIGITS, NumericVar::dscale, free_var(), init_var, init_var_from_num(), ln_var(), make_result(), Max, Min, NUMERIC_IS_NAN, NUMERIC_MAX_DISPLAY_SCALE, NUMERIC_MIN_DISPLAY_SCALE, NUMERIC_MIN_SIG_DIGITS, PG_GETARG_NUMERIC, PG_RETURN_NUMERIC, and NumericVar::weight.

{
    Numeric     num = PG_GETARG_NUMERIC(0);
    Numeric     res;
    NumericVar  arg;
    NumericVar  result;
    int         dec_digits;
    int         rscale;

    /*
     * Handle NaN
     */
    if (NUMERIC_IS_NAN(num))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    init_var_from_num(num, &arg);
    init_var(&result);

    /* Approx decimal digits before decimal point */
    dec_digits = (arg.weight + 1) * DEC_DIGITS;

    if (dec_digits > 1)
        rscale = NUMERIC_MIN_SIG_DIGITS - (int) log10(dec_digits - 1);
    else if (dec_digits < 1)
        rscale = NUMERIC_MIN_SIG_DIGITS - (int) log10(1 - dec_digits);
    else
        rscale = NUMERIC_MIN_SIG_DIGITS;

    rscale = Max(rscale, arg.dscale);
    rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
    rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);

    ln_var(&arg, &result, rscale);

    res = make_result(&result);

    free_var(&result);

    PG_RETURN_NUMERIC(res);
}

Datum numeric_log ( PG_FUNCTION_ARGS   ) 

Definition at line 2081 of file numeric.c.

References free_var(), init_var, init_var_from_num(), log_var(), make_result(), NUMERIC_IS_NAN, PG_GETARG_NUMERIC, and PG_RETURN_NUMERIC.

{
    Numeric     num1 = PG_GETARG_NUMERIC(0);
    Numeric     num2 = PG_GETARG_NUMERIC(1);
    Numeric     res;
    NumericVar  arg1;
    NumericVar  arg2;
    NumericVar  result;

    /*
     * Handle NaN
     */
    if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    /*
     * Initialize things
     */
    init_var_from_num(num1, &arg1);
    init_var_from_num(num2, &arg2);
    init_var(&result);

    /*
     * Call log_var() to compute and return the result; note it handles scale
     * selection itself.
     */
    log_var(&arg1, &arg2, &result);

    res = make_result(&result);

    free_var(&result);

    PG_RETURN_NUMERIC(res);
}

Datum numeric_lt ( PG_FUNCTION_ARGS   ) 

Definition at line 1396 of file numeric.c.

References cmp_numerics(), PG_FREE_IF_COPY, PG_GETARG_NUMERIC, and PG_RETURN_BOOL.

Referenced by gbt_numeric_lt(), and numeric_is_less().

{
    Numeric     num1 = PG_GETARG_NUMERIC(0);
    Numeric     num2 = PG_GETARG_NUMERIC(1);
    bool        result;

    result = cmp_numerics(num1, num2) < 0;

    PG_FREE_IF_COPY(num1, 0);
    PG_FREE_IF_COPY(num2, 1);

    PG_RETURN_BOOL(result);
}

Datum numeric_mod ( PG_FUNCTION_ARGS   ) 

Definition at line 1756 of file numeric.c.

References free_var(), init_var, init_var_from_num(), make_result(), mod_var(), NUMERIC_IS_NAN, PG_GETARG_NUMERIC, and PG_RETURN_NUMERIC.

{
    Numeric     num1 = PG_GETARG_NUMERIC(0);
    Numeric     num2 = PG_GETARG_NUMERIC(1);
    Numeric     res;
    NumericVar  arg1;
    NumericVar  arg2;
    NumericVar  result;

    if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    init_var_from_num(num1, &arg1);
    init_var_from_num(num2, &arg2);

    init_var(&result);

    mod_var(&arg1, &arg2, &result);

    res = make_result(&result);

    free_var(&result);

    PG_RETURN_NUMERIC(res);
}

Datum numeric_mul ( PG_FUNCTION_ARGS   ) 

Definition at line 1624 of file numeric.c.

References NumericVar::dscale, free_var(), init_var, init_var_from_num(), make_result(), mul_var(), NUMERIC_IS_NAN, PG_GETARG_NUMERIC, and PG_RETURN_NUMERIC.

Referenced by do_numeric_accum(), numeric_cash(), and numeric_to_char().

{
    Numeric     num1 = PG_GETARG_NUMERIC(0);
    Numeric     num2 = PG_GETARG_NUMERIC(1);
    NumericVar  arg1;
    NumericVar  arg2;
    NumericVar  result;
    Numeric     res;

    /*
     * Handle NaN
     */
    if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    /*
     * Unpack the values, let mul_var() compute the result and return it.
     * Unlike add_var() and sub_var(), mul_var() will round its result. In the
     * case of numeric_mul(), which is invoked for the * operator on numerics,
     * we request exact representation for the product (rscale = sum(dscale of
     * arg1, dscale of arg2)).
     */
    init_var_from_num(num1, &arg1);
    init_var_from_num(num2, &arg2);

    init_var(&result);
    mul_var(&arg1, &arg2, &result, arg1.dscale + arg2.dscale);

    res = make_result(&result);

    free_var(&result);

    PG_RETURN_NUMERIC(res);
}

Datum numeric_ne ( PG_FUNCTION_ARGS   ) 

Definition at line 1351 of file numeric.c.

References cmp_numerics(), PG_FREE_IF_COPY, PG_GETARG_NUMERIC, and PG_RETURN_BOOL.

{
    Numeric     num1 = PG_GETARG_NUMERIC(0);
    Numeric     num2 = PG_GETARG_NUMERIC(1);
    bool        result;

    result = cmp_numerics(num1, num2) != 0;

    PG_FREE_IF_COPY(num1, 0);
    PG_FREE_IF_COPY(num2, 1);

    PG_RETURN_BOOL(result);
}

Datum numeric_out ( PG_FUNCTION_ARGS   ) 

Definition at line 533 of file numeric.c.

References get_str_from_var(), init_var_from_num(), NUMERIC_IS_NAN, PG_GETARG_NUMERIC, PG_RETURN_CSTRING, and pstrdup().

Referenced by numeric_float4(), numeric_float8(), numeric_to_char(), numeric_to_cstring(), and numeric_to_double_no_overflow().

{
    Numeric     num = PG_GETARG_NUMERIC(0);
    NumericVar  x;
    char       *str;

    /*
     * Handle NaN
     */
    if (NUMERIC_IS_NAN(num))
        PG_RETURN_CSTRING(pstrdup("NaN"));

    /*
     * Get the number in the variable format.
     */
    init_var_from_num(num, &x);

    str = get_str_from_var(&x);

    PG_RETURN_CSTRING(str);
}

Datum numeric_power ( PG_FUNCTION_ARGS   ) 

Definition at line 2123 of file numeric.c.

References cmp_var(), ereport, errcode(), errmsg(), ERROR, free_var(), init_var, init_var_from_num(), make_result(), NUMERIC_IS_NAN, PG_GETARG_NUMERIC, PG_RETURN_NUMERIC, power_var(), set_var_from_var(), and trunc_var().

Referenced by numeric_to_char().

{
    Numeric     num1 = PG_GETARG_NUMERIC(0);
    Numeric     num2 = PG_GETARG_NUMERIC(1);
    Numeric     res;
    NumericVar  arg1;
    NumericVar  arg2;
    NumericVar  arg2_trunc;
    NumericVar  result;

    /*
     * Handle NaN
     */
    if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    /*
     * Initialize things
     */
    init_var(&arg2_trunc);
    init_var(&result);
    init_var_from_num(num1, &arg1);
    init_var_from_num(num2, &arg2);

    set_var_from_var(&arg2, &arg2_trunc);
    trunc_var(&arg2_trunc, 0);

    /*
     * The SQL spec requires that we emit a particular SQLSTATE error code for
     * certain error conditions.  Specifically, we don't return a
     * divide-by-zero error code for 0 ^ -1.
     */
    if (cmp_var(&arg1, &const_zero) == 0 &&
        cmp_var(&arg2, &const_zero) < 0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
                 errmsg("zero raised to a negative power is undefined")));

    if (cmp_var(&arg1, &const_zero) < 0 &&
        cmp_var(&arg2, &arg2_trunc) != 0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
                 errmsg("a negative number raised to a non-integer power yields a complex result")));

    /*
     * Call power_var() to compute and return the result; note it handles
     * scale selection itself.
     */
    power_var(&arg1, &arg2, &result);

    res = make_result(&result);

    free_var(&result);
    free_var(&arg2_trunc);

    PG_RETURN_NUMERIC(res);
}

Datum numeric_recv ( PG_FUNCTION_ARGS   ) 

Definition at line 636 of file numeric.c.

References alloc_var(), apply_typmod(), buf, NumericVar::digits, NumericVar::dscale, ereport, errcode(), errmsg(), ERROR, free_var(), i, init_var, make_result(), NBASE, NUMERIC_MAX_PRECISION, NUMERIC_MAX_RESULT_SCALE, NUMERIC_NAN, NUMERIC_NEG, NUMERIC_POS, PG_GETARG_INT32, PG_GETARG_OID, PG_GETARG_POINTER, PG_RETURN_NUMERIC, pq_getmsgint(), NumericVar::sign, value, and NumericVar::weight.

{
    StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);

#ifdef NOT_USED
    Oid         typelem = PG_GETARG_OID(1);
#endif
    int32       typmod = PG_GETARG_INT32(2);
    NumericVar  value;
    Numeric     res;
    int         len,
                i;

    init_var(&value);

    len = (uint16) pq_getmsgint(buf, sizeof(uint16));
    if (len < 0 || len > NUMERIC_MAX_PRECISION + NUMERIC_MAX_RESULT_SCALE)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
                 errmsg("invalid length in external \"numeric\" value")));

    alloc_var(&value, len);

    value.weight = (int16) pq_getmsgint(buf, sizeof(int16));
    value.sign = (uint16) pq_getmsgint(buf, sizeof(uint16));
    if (!(value.sign == NUMERIC_POS ||
          value.sign == NUMERIC_NEG ||
          value.sign == NUMERIC_NAN))
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
                 errmsg("invalid sign in external \"numeric\" value")));

    value.dscale = (uint16) pq_getmsgint(buf, sizeof(uint16));
    for (i = 0; i < len; i++)
    {
        NumericDigit d = pq_getmsgint(buf, sizeof(NumericDigit));

        if (d < 0 || d >= NBASE)
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
                     errmsg("invalid digit in external \"numeric\" value")));
        value.digits[i] = d;
    }

    apply_typmod(&value, typmod);

    res = make_result(&value);
    free_var(&value);

    PG_RETURN_NUMERIC(res);
}

Datum numeric_round ( PG_FUNCTION_ARGS   ) 

Definition at line 1046 of file numeric.c.

References arg, NumericVar::dscale, free_var(), init_var, make_result(), Max, Min, NUMERIC_IS_NAN, NUMERIC_MAX_RESULT_SCALE, PG_GETARG_INT32, PG_GETARG_NUMERIC, PG_RETURN_NUMERIC, round_var(), scale, and set_var_from_num().

Referenced by cash_numeric(), and numeric_to_char().

{
    Numeric     num = PG_GETARG_NUMERIC(0);
    int32       scale = PG_GETARG_INT32(1);
    Numeric     res;
    NumericVar  arg;

    /*
     * Handle NaN
     */
    if (NUMERIC_IS_NAN(num))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    /*
     * Limit the scale value to avoid possible overflow in calculations
     */
    scale = Max(scale, -NUMERIC_MAX_RESULT_SCALE);
    scale = Min(scale, NUMERIC_MAX_RESULT_SCALE);

    /*
     * Unpack the argument and round it at the proper digit position
     */
    init_var(&arg);
    set_var_from_num(num, &arg);

    round_var(&arg, scale);

    /* We don't allow negative output dscale */
    if (scale < 0)
        arg.dscale = 0;

    /*
     * Return the rounded result
     */
    res = make_result(&arg);

    free_var(&arg);
    PG_RETURN_NUMERIC(res);
}

Datum numeric_send ( PG_FUNCTION_ARGS   ) 
Datum numeric_sign ( PG_FUNCTION_ARGS   ) 

Definition at line 1001 of file numeric.c.

References free_var(), init_var, make_result(), NUMERIC_IS_NAN, NUMERIC_NDIGITS, NUMERIC_SIGN, PG_GETARG_NUMERIC, PG_RETURN_NUMERIC, set_var_from_var(), and NumericVar::sign.

{
    Numeric     num = PG_GETARG_NUMERIC(0);
    Numeric     res;
    NumericVar  result;

    /*
     * Handle NaN
     */
    if (NUMERIC_IS_NAN(num))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    init_var(&result);

    /*
     * The packed format is known to be totally zero digit trimmed always. So
     * we can identify a ZERO by the fact that there are no digits at all.
     */
    if (NUMERIC_NDIGITS(num) == 0)
        set_var_from_var(&const_zero, &result);
    else
    {
        /*
         * And if there are some, we return a copy of ONE with the sign of our
         * argument
         */
        set_var_from_var(&const_one, &result);
        result.sign = NUMERIC_SIGN(num);
    }

    res = make_result(&result);
    free_var(&result);

    PG_RETURN_NUMERIC(res);
}

Datum numeric_smaller ( PG_FUNCTION_ARGS   ) 

Definition at line 1822 of file numeric.c.

References cmp_numerics(), PG_GETARG_NUMERIC, and PG_RETURN_NUMERIC.

{
    Numeric     num1 = PG_GETARG_NUMERIC(0);
    Numeric     num2 = PG_GETARG_NUMERIC(1);

    /*
     * Use cmp_numerics so that this will agree with the comparison operators,
     * particularly as regards comparisons involving NaN.
     */
    if (cmp_numerics(num1, num2) < 0)
        PG_RETURN_NUMERIC(num1);
    else
        PG_RETURN_NUMERIC(num2);
}

Datum numeric_sqrt ( PG_FUNCTION_ARGS   ) 

Definition at line 1921 of file numeric.c.

References arg, DEC_DIGITS, NumericVar::dscale, free_var(), init_var, init_var_from_num(), make_result(), Max, Min, NUMERIC_IS_NAN, NUMERIC_MAX_DISPLAY_SCALE, NUMERIC_MIN_DISPLAY_SCALE, NUMERIC_MIN_SIG_DIGITS, PG_GETARG_NUMERIC, PG_RETURN_NUMERIC, sqrt_var(), and NumericVar::weight.

{
    Numeric     num = PG_GETARG_NUMERIC(0);
    Numeric     res;
    NumericVar  arg;
    NumericVar  result;
    int         sweight;
    int         rscale;

    /*
     * Handle NaN
     */
    if (NUMERIC_IS_NAN(num))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    /*
     * Unpack the argument and determine the result scale.  We choose a scale
     * to give at least NUMERIC_MIN_SIG_DIGITS significant digits; but in any
     * case not less than the input's dscale.
     */
    init_var_from_num(num, &arg);

    init_var(&result);

    /* Assume the input was normalized, so arg.weight is accurate */
    sweight = (arg.weight + 1) * DEC_DIGITS / 2 - 1;

    rscale = NUMERIC_MIN_SIG_DIGITS - sweight;
    rscale = Max(rscale, arg.dscale);
    rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
    rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);

    /*
     * Let sqrt_var() do the calculation and return the result.
     */
    sqrt_var(&arg, &result, rscale);

    res = make_result(&result);

    free_var(&result);

    PG_RETURN_NUMERIC(res);
}

Datum numeric_stddev_pop ( PG_FUNCTION_ARGS   ) 

Definition at line 2804 of file numeric.c.

References numeric_stddev_internal(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_NULL, and PG_RETURN_NUMERIC.

{
    Numeric     res;
    bool        is_null;

    res = numeric_stddev_internal(PG_GETARG_ARRAYTYPE_P(0),
                                  false, false, &is_null);

    if (is_null)
        PG_RETURN_NULL();
    else
        PG_RETURN_NUMERIC(res);
}

Datum numeric_stddev_samp ( PG_FUNCTION_ARGS   ) 

Definition at line 2774 of file numeric.c.

References numeric_stddev_internal(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_NULL, and PG_RETURN_NUMERIC.

{
    Numeric     res;
    bool        is_null;

    res = numeric_stddev_internal(PG_GETARG_ARRAYTYPE_P(0),
                                  false, true, &is_null);

    if (is_null)
        PG_RETURN_NULL();
    else
        PG_RETURN_NUMERIC(res);
}

Datum numeric_sub ( PG_FUNCTION_ARGS   ) 

Definition at line 1586 of file numeric.c.

References free_var(), init_var, init_var_from_num(), make_result(), NUMERIC_IS_NAN, PG_GETARG_NUMERIC, PG_RETURN_NUMERIC, and sub_var().

Referenced by gbt_numeric_penalty(), numrange_subdiff(), and pg_xlog_location_diff().

{
    Numeric     num1 = PG_GETARG_NUMERIC(0);
    Numeric     num2 = PG_GETARG_NUMERIC(1);
    NumericVar  arg1;
    NumericVar  arg2;
    NumericVar  result;
    Numeric     res;

    /*
     * Handle NaN
     */
    if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    /*
     * Unpack the values, let sub_var() compute the result and return it.
     */
    init_var_from_num(num1, &arg1);
    init_var_from_num(num2, &arg2);

    init_var(&result);
    sub_var(&arg1, &arg2, &result);

    res = make_result(&result);

    free_var(&result);

    PG_RETURN_NUMERIC(res);
}

Datum numeric_transform ( PG_FUNCTION_ARGS   ) 

Definition at line 724 of file numeric.c.

References FuncExpr::args, Assert, DatumGetInt32, exprTypmod(), IsA, linitial, list_length(), lsecond, PG_GETARG_POINTER, PG_RETURN_POINTER, relabel_to_typmod(), and VARHDRSZ.

{
    FuncExpr   *expr = (FuncExpr *) PG_GETARG_POINTER(0);
    Node       *ret = NULL;
    Node       *typmod;

    Assert(IsA(expr, FuncExpr));
    Assert(list_length(expr->args) >= 2);

    typmod = (Node *) lsecond(expr->args);

    if (IsA(typmod, Const) &&!((Const *) typmod)->constisnull)
    {
        Node       *source = (Node *) linitial(expr->args);
        int32       old_typmod = exprTypmod(source);
        int32       new_typmod = DatumGetInt32(((Const *) typmod)->constvalue);
        int32       old_scale = (old_typmod - VARHDRSZ) & 0xffff;
        int32       new_scale = (new_typmod - VARHDRSZ) & 0xffff;
        int32       old_precision = (old_typmod - VARHDRSZ) >> 16 & 0xffff;
        int32       new_precision = (new_typmod - VARHDRSZ) >> 16 & 0xffff;

        /*
         * If new_typmod < VARHDRSZ, the destination is unconstrained; that's
         * always OK.  If old_typmod >= VARHDRSZ, the source is constrained,
         * and we're OK if the scale is unchanged and the precision is not
         * decreasing.  See further notes in function header comment.
         */
        if (new_typmod < (int32) VARHDRSZ ||
            (old_typmod >= (int32) VARHDRSZ &&
             new_scale == old_scale && new_precision >= old_precision))
            ret = relabel_to_typmod(source, new_typmod);
    }

    PG_RETURN_POINTER(ret);
}

Datum numeric_trunc ( PG_FUNCTION_ARGS   ) 

Definition at line 1095 of file numeric.c.

References arg, NumericVar::dscale, free_var(), init_var, make_result(), Max, Min, NUMERIC_IS_NAN, NUMERIC_MAX_RESULT_SCALE, PG_GETARG_INT32, PG_GETARG_NUMERIC, PG_RETURN_NUMERIC, scale, set_var_from_num(), and trunc_var().

{
    Numeric     num = PG_GETARG_NUMERIC(0);
    int32       scale = PG_GETARG_INT32(1);
    Numeric     res;
    NumericVar  arg;

    /*
     * Handle NaN
     */
    if (NUMERIC_IS_NAN(num))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    /*
     * Limit the scale value to avoid possible overflow in calculations
     */
    scale = Max(scale, -NUMERIC_MAX_RESULT_SCALE);
    scale = Min(scale, NUMERIC_MAX_RESULT_SCALE);

    /*
     * Unpack the argument and truncate it at the proper digit position
     */
    init_var(&arg);
    set_var_from_num(num, &arg);

    trunc_var(&arg, scale);

    /* We don't allow negative output dscale */
    if (scale < 0)
        arg.dscale = 0;

    /*
     * Return the truncated result
     */
    res = make_result(&arg);

    free_var(&arg);
    PG_RETURN_NUMERIC(res);
}

Datum numeric_uminus ( PG_FUNCTION_ARGS   ) 

Definition at line 942 of file numeric.c.

References NumericData::choice, make_result(), NumericShort::n_header, NumericChoice::n_long, NumericChoice::n_short, NumericLong::n_sign_dscale, NUMERIC_DSCALE, NUMERIC_IS_NAN, NUMERIC_IS_SHORT, NUMERIC_NDIGITS, NUMERIC_NEG, NUMERIC_POS, NUMERIC_SIGN, palloc(), PG_GETARG_NUMERIC, PG_RETURN_NUMERIC, and VARSIZE.

{
    Numeric     num = PG_GETARG_NUMERIC(0);
    Numeric     res;

    /*
     * Handle NaN
     */
    if (NUMERIC_IS_NAN(num))
        PG_RETURN_NUMERIC(make_result(&const_nan));

    /*
     * Do it the easy way directly on the packed format
     */
    res = (Numeric) palloc(VARSIZE(num));
    memcpy(res, num, VARSIZE(num));

    /*
     * The packed format is known to be totally zero digit trimmed always. So
     * we can identify a ZERO by the fact that there are no digits at all.  Do
     * nothing to a zero.
     */
    if (NUMERIC_NDIGITS(num) != 0)
    {
        /* Else, flip the sign */
        if (NUMERIC_IS_SHORT(num))
            res->choice.n_short.n_header =
                num->choice.n_short.n_header ^ NUMERIC_SHORT_SIGN_MASK;
        else if (NUMERIC_SIGN(num) == NUMERIC_POS)
            res->choice.n_long.n_sign_dscale =
                NUMERIC_NEG | NUMERIC_DSCALE(num);
        else
            res->choice.n_long.n_sign_dscale =
                NUMERIC_POS | NUMERIC_DSCALE(num);
    }

    PG_RETURN_NUMERIC(res);
}

Datum numeric_uplus ( PG_FUNCTION_ARGS   ) 

Definition at line 983 of file numeric.c.

References palloc(), PG_GETARG_NUMERIC, PG_RETURN_NUMERIC, and VARSIZE.

{
    Numeric     num = PG_GETARG_NUMERIC(0);
    Numeric     res;

    res = (Numeric) palloc(VARSIZE(num));
    memcpy(res, num, VARSIZE(num));

    PG_RETURN_NUMERIC(res);
}

Datum numeric_var_pop ( PG_FUNCTION_ARGS   ) 

Definition at line 2789 of file numeric.c.

References numeric_stddev_internal(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_NULL, and PG_RETURN_NUMERIC.

{
    Numeric     res;
    bool        is_null;

    res = numeric_stddev_internal(PG_GETARG_ARRAYTYPE_P(0),
                                  true, false, &is_null);

    if (is_null)
        PG_RETURN_NULL();
    else
        PG_RETURN_NUMERIC(res);
}

Datum numeric_var_samp ( PG_FUNCTION_ARGS   ) 

Definition at line 2759 of file numeric.c.

References numeric_stddev_internal(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_NULL, and PG_RETURN_NUMERIC.

{
    Numeric     res;
    bool        is_null;

    res = numeric_stddev_internal(PG_GETARG_ARRAYTYPE_P(0),
                                  true, true, &is_null);

    if (is_null)
        PG_RETURN_NULL();
    else
        PG_RETURN_NUMERIC(res);
}

Datum numerictypmodin ( PG_FUNCTION_ARGS   ) 

Definition at line 845 of file numeric.c.

References ArrayGetIntegerTypmods(), ereport, errcode(), errmsg(), ERROR, NUMERIC_MAX_PRECISION, PG_GETARG_ARRAYTYPE_P, PG_RETURN_INT32, and VARHDRSZ.

{
    ArrayType  *ta = PG_GETARG_ARRAYTYPE_P(0);
    int32      *tl;
    int         n;
    int32       typmod;

    tl = ArrayGetIntegerTypmods(ta, &n);

    if (n == 2)
    {
        if (tl[0] < 1 || tl[0] > NUMERIC_MAX_PRECISION)
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                     errmsg("NUMERIC precision %d must be between 1 and %d",
                            tl[0], NUMERIC_MAX_PRECISION)));
        if (tl[1] < 0 || tl[1] > tl[0])
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                errmsg("NUMERIC scale %d must be between 0 and precision %d",
                       tl[1], tl[0])));
        typmod = ((tl[0] << 16) | tl[1]) + VARHDRSZ;
    }
    else if (n == 1)
    {
        if (tl[0] < 1 || tl[0] > NUMERIC_MAX_PRECISION)
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                     errmsg("NUMERIC precision %d must be between 1 and %d",
                            tl[0], NUMERIC_MAX_PRECISION)));
        /* scale defaults to zero */
        typmod = (tl[0] << 16) + VARHDRSZ;
    }
    else
    {
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("invalid NUMERIC type modifier")));
        typmod = 0;             /* keep compiler quiet */
    }

    PG_RETURN_INT32(typmod);
}

Datum numerictypmodout ( PG_FUNCTION_ARGS   ) 

Definition at line 890 of file numeric.c.

References palloc(), PG_GETARG_INT32, PG_RETURN_CSTRING, snprintf(), and VARHDRSZ.

{
    int32       typmod = PG_GETARG_INT32(0);
    char       *res = (char *) palloc(64);

    if (typmod >= 0)
        snprintf(res, 64, "(%d,%d)",
                 ((typmod - VARHDRSZ) >> 16) & 0xffff,
                 (typmod - VARHDRSZ) & 0xffff);
    else
        *res = '\0';

    PG_RETURN_CSTRING(res);
}

Datum oideq ( PG_FUNCTION_ARGS   ) 

Definition at line 337 of file oid.c.

References PG_GETARG_OID, and PG_RETURN_BOOL.

{
    Oid         arg1 = PG_GETARG_OID(0);
    Oid         arg2 = PG_GETARG_OID(1);

    PG_RETURN_BOOL(arg1 == arg2);
}

Datum oidge ( PG_FUNCTION_ARGS   ) 

Definition at line 373 of file oid.c.

References PG_GETARG_OID, and PG_RETURN_BOOL.

{
    Oid         arg1 = PG_GETARG_OID(0);
    Oid         arg2 = PG_GETARG_OID(1);

    PG_RETURN_BOOL(arg1 >= arg2);
}

Datum oidgt ( PG_FUNCTION_ARGS   ) 

Definition at line 382 of file oid.c.

References PG_GETARG_OID, and PG_RETURN_BOOL.

{
    Oid         arg1 = PG_GETARG_OID(0);
    Oid         arg2 = PG_GETARG_OID(1);

    PG_RETURN_BOOL(arg1 > arg2);
}

Datum oidin ( PG_FUNCTION_ARGS   ) 
Datum oidlarger ( PG_FUNCTION_ARGS   ) 

Definition at line 391 of file oid.c.

References PG_GETARG_OID, and PG_RETURN_OID.

{
    Oid         arg1 = PG_GETARG_OID(0);
    Oid         arg2 = PG_GETARG_OID(1);

    PG_RETURN_OID((arg1 > arg2) ? arg1 : arg2);
}

Datum oidle ( PG_FUNCTION_ARGS   ) 

Definition at line 364 of file oid.c.

References PG_GETARG_OID, and PG_RETURN_BOOL.

{
    Oid         arg1 = PG_GETARG_OID(0);
    Oid         arg2 = PG_GETARG_OID(1);

    PG_RETURN_BOOL(arg1 <= arg2);
}

Datum oidlt ( PG_FUNCTION_ARGS   ) 

Definition at line 355 of file oid.c.

References PG_GETARG_OID, and PG_RETURN_BOOL.

{
    Oid         arg1 = PG_GETARG_OID(0);
    Oid         arg2 = PG_GETARG_OID(1);

    PG_RETURN_BOOL(arg1 < arg2);
}

Datum oidne ( PG_FUNCTION_ARGS   ) 

Definition at line 346 of file oid.c.

References PG_GETARG_OID, and PG_RETURN_BOOL.

{
    Oid         arg1 = PG_GETARG_OID(0);
    Oid         arg2 = PG_GETARG_OID(1);

    PG_RETURN_BOOL(arg1 != arg2);
}

Datum oidout ( PG_FUNCTION_ARGS   ) 

Definition at line 124 of file oid.c.

References palloc(), PG_GETARG_OID, PG_RETURN_CSTRING, and snprintf().

Referenced by CopyOneRowTo(), plperl_trigger_build_args(), pltcl_trigger_handler(), and PLy_trigger_build_args().

{
    Oid         o = PG_GETARG_OID(0);
    char       *result = (char *) palloc(12);

    snprintf(result, 12, "%u", o);
    PG_RETURN_CSTRING(result);
}

Oid oidparse ( Node node  ) 

Definition at line 311 of file oid.c.

References elog, ERROR, intVal, nodeTag, NULL, oidin_subr(), strVal, T_Float, and T_Integer.

Referenced by get_object_address(), and objectNamesToOids().

{
    switch (nodeTag(node))
    {
        case T_Integer:
            return intVal(node);
        case T_Float:

            /*
             * Values too large for int4 will be represented as Float
             * constants by the lexer.  Accept these if they are valid OID
             * strings.
             */
            return oidin_subr(strVal(node), NULL);
        default:
            elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
    }
    return InvalidOid;          /* keep compiler quiet */
}

Datum oidrecv ( PG_FUNCTION_ARGS   ) 
Datum oidsend ( PG_FUNCTION_ARGS   ) 
Datum oidsmaller ( PG_FUNCTION_ARGS   ) 

Definition at line 400 of file oid.c.

References PG_GETARG_OID, and PG_RETURN_OID.

{
    Oid         arg1 = PG_GETARG_OID(0);
    Oid         arg2 = PG_GETARG_OID(1);

    PG_RETURN_OID((arg1 < arg2) ? arg1 : arg2);
}

Datum oidvectoreq ( PG_FUNCTION_ARGS   ) 

Definition at line 409 of file oid.c.

References btoidvectorcmp(), cmp(), DatumGetInt32, and PG_RETURN_BOOL.

Datum oidvectorge ( PG_FUNCTION_ARGS   ) 

Definition at line 441 of file oid.c.

References btoidvectorcmp(), cmp(), DatumGetInt32, and PG_RETURN_BOOL.

Datum oidvectorgt ( PG_FUNCTION_ARGS   ) 

Definition at line 449 of file oid.c.

References btoidvectorcmp(), cmp(), DatumGetInt32, and PG_RETURN_BOOL.

Datum oidvectorin ( PG_FUNCTION_ARGS   ) 

Definition at line 191 of file oid.c.

References oidvector::dataoffset, oidvector::dim1, oidvector::elemtype, ereport, errcode(), errmsg(), ERROR, FUNC_MAX_ARGS, oidvector::lbound1, oidvector::ndim, oidin_subr(), OidVectorSize, palloc0(), PG_GETARG_CSTRING, PG_RETURN_POINTER, SET_VARSIZE, and oidvector::values.

{
    char       *oidString = PG_GETARG_CSTRING(0);
    oidvector  *result;
    int         n;

    result = (oidvector *) palloc0(OidVectorSize(FUNC_MAX_ARGS));

    for (n = 0; n < FUNC_MAX_ARGS; n++)
    {
        while (*oidString && isspace((unsigned char) *oidString))
            oidString++;
        if (*oidString == '\0')
            break;
        result->values[n] = oidin_subr(oidString, &oidString);
    }
    while (*oidString && isspace((unsigned char) *oidString))
        oidString++;
    if (*oidString)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("oidvector has too many elements")));

    SET_VARSIZE(result, OidVectorSize(n));
    result->ndim = 1;
    result->dataoffset = 0;     /* never any nulls */
    result->elemtype = OIDOID;
    result->dim1 = n;
    result->lbound1 = 0;

    PG_RETURN_POINTER(result);
}

Datum oidvectorle ( PG_FUNCTION_ARGS   ) 

Definition at line 433 of file oid.c.

References btoidvectorcmp(), cmp(), DatumGetInt32, and PG_RETURN_BOOL.

Datum oidvectorlt ( PG_FUNCTION_ARGS   ) 

Definition at line 425 of file oid.c.

References btoidvectorcmp(), cmp(), DatumGetInt32, and PG_RETURN_BOOL.

Datum oidvectorne ( PG_FUNCTION_ARGS   ) 

Definition at line 417 of file oid.c.

References btoidvectorcmp(), cmp(), DatumGetInt32, and PG_RETURN_BOOL.

Datum oidvectorout ( PG_FUNCTION_ARGS   ) 

Definition at line 228 of file oid.c.

References oidvector::dim1, palloc(), PG_GETARG_POINTER, PG_RETURN_CSTRING, and oidvector::values.

{
    oidvector  *oidArray = (oidvector *) PG_GETARG_POINTER(0);
    int         num,
                nnums = oidArray->dim1;
    char       *rp;
    char       *result;

    /* assumes sign, 10 digits, ' ' */
    rp = result = (char *) palloc(nnums * 12 + 1);
    for (num = 0; num < nnums; num++)
    {
        if (num != 0)
            *rp++ = ' ';
        sprintf(rp, "%u", oidArray->values[num]);
        while (*++rp != '\0')
            ;
    }
    *rp = '\0';
    PG_RETURN_CSTRING(result);
}

Datum oidvectorrecv ( PG_FUNCTION_ARGS   ) 

Definition at line 254 of file oid.c.

References FunctionCallInfoData::arg, FunctionCallInfoData::argnull, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_LBOUND, ARR_NDIM, array_recv(), Assert, buf, DatumGetPointer, ereport, errcode(), errmsg(), ERROR, FunctionCallInfoData::flinfo, FUNC_MAX_ARGS, InitFunctionCallInfoData, Int32GetDatum, InvalidOid, FunctionCallInfoData::isnull, NULL, ObjectIdGetDatum, OIDOID, PG_GETARG_POINTER, PG_RETURN_POINTER, and PointerGetDatum.

{
    StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
    FunctionCallInfoData locfcinfo;
    oidvector  *result;

    /*
     * Normally one would call array_recv() using DirectFunctionCall3, but
     * that does not work since array_recv wants to cache some data using
     * fcinfo->flinfo->fn_extra.  So we need to pass it our own flinfo
     * parameter.
     */
    InitFunctionCallInfoData(locfcinfo, fcinfo->flinfo, 3,
                             InvalidOid, NULL, NULL);

    locfcinfo.arg[0] = PointerGetDatum(buf);
    locfcinfo.arg[1] = ObjectIdGetDatum(OIDOID);
    locfcinfo.arg[2] = Int32GetDatum(-1);
    locfcinfo.argnull[0] = false;
    locfcinfo.argnull[1] = false;
    locfcinfo.argnull[2] = false;

    result = (oidvector *) DatumGetPointer(array_recv(&locfcinfo));

    Assert(!locfcinfo.isnull);

    /* sanity checks: oidvector must be 1-D, 0-based, no nulls */
    if (ARR_NDIM(result) != 1 ||
        ARR_HASNULL(result) ||
        ARR_ELEMTYPE(result) != OIDOID ||
        ARR_LBOUND(result)[0] != 0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
                 errmsg("invalid oidvector data")));

    /* check length for consistency with oidvectorin() */
    if (ARR_DIMS(result)[0] > FUNC_MAX_ARGS)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("oidvector has too many elements")));

    PG_RETURN_POINTER(result);
}

Datum oidvectorsend ( PG_FUNCTION_ARGS   ) 

Definition at line 302 of file oid.c.

References array_send().

{
    return array_send(fcinfo);
}

Datum oidvectortypes ( PG_FUNCTION_ARGS   ) 

Definition at line 413 of file format_type.c.

References cstring_to_text(), oidvector::dim1, format_type_internal(), palloc(), PG_GETARG_POINTER, PG_RETURN_TEXT_P, repalloc(), and oidvector::values.

{
    oidvector  *oidArray = (oidvector *) PG_GETARG_POINTER(0);
    char       *result;
    int         numargs = oidArray->dim1;
    int         num;
    size_t      total;
    size_t      left;

    total = 20 * numargs + 1;
    result = palloc(total);
    result[0] = '\0';
    left = total - 1;

    for (num = 0; num < numargs; num++)
    {
        char       *typename = format_type_internal(oidArray->values[num], -1,
                                                    false, true, false);
        size_t      slen = strlen(typename);

        if (left < (slen + 2))
        {
            total += slen + 2;
            result = repalloc(result, total);
            left += slen + 2;
        }

        if (num > 0)
        {
            strcat(result, ", ");
            left -= 2;
        }
        strcat(result, typename);
        left -= slen;
    }

    PG_RETURN_TEXT_P(cstring_to_text(result));
}

Datum opaque_in ( PG_FUNCTION_ARGS   ) 

Definition at line 407 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot accept a value of type opaque")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum opaque_out ( PG_FUNCTION_ARGS   ) 

Definition at line 420 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot display a value of type opaque")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

bool parse_bool ( const char *  value,
bool result 
)
bool parse_bool_with_len ( const char *  value,
size_t  len,
bool result 
)

Definition at line 36 of file bool.c.

References pg_strncasecmp().

Referenced by boolin(), and parse_bool().

{
    switch (*value)
    {
        case 't':
        case 'T':
            if (pg_strncasecmp(value, "true", len) == 0)
            {
                if (result)
                    *result = true;
                return true;
            }
            break;
        case 'f':
        case 'F':
            if (pg_strncasecmp(value, "false", len) == 0)
            {
                if (result)
                    *result = false;
                return true;
            }
            break;
        case 'y':
        case 'Y':
            if (pg_strncasecmp(value, "yes", len) == 0)
            {
                if (result)
                    *result = true;
                return true;
            }
            break;
        case 'n':
        case 'N':
            if (pg_strncasecmp(value, "no", len) == 0)
            {
                if (result)
                    *result = false;
                return true;
            }
            break;
        case 'o':
        case 'O':
            /* 'o' is not unique enough */
            if (pg_strncasecmp(value, "on", (len > 2 ? len : 2)) == 0)
            {
                if (result)
                    *result = true;
                return true;
            }
            else if (pg_strncasecmp(value, "off", (len > 2 ? len : 2)) == 0)
            {
                if (result)
                    *result = false;
                return true;
            }
            break;
        case '1':
            if (len == 1)
            {
                if (result)
                    *result = true;
                return true;
            }
            break;
        case '0':
            if (len == 1)
            {
                if (result)
                    *result = false;
                return true;
            }
            break;
        default:
            break;
    }

    if (result)
        *result = false;        /* suppress compiler warning */
    return false;
}

Datum pg_advisory_lock_int4 ( PG_FUNCTION_ARGS   ) 

Definition at line 600 of file lockfuncs.c.

References ExclusiveLock, LockAcquire(), PG_GETARG_INT32, PG_RETURN_VOID, and SET_LOCKTAG_INT32.

{
    int32       key1 = PG_GETARG_INT32(0);
    int32       key2 = PG_GETARG_INT32(1);
    LOCKTAG     tag;

    SET_LOCKTAG_INT32(tag, key1, key2);

    (void) LockAcquire(&tag, ExclusiveLock, true, false);

    PG_RETURN_VOID();
}

Datum pg_advisory_lock_int8 ( PG_FUNCTION_ARGS   ) 

Definition at line 418 of file lockfuncs.c.

References ExclusiveLock, LockAcquire(), PG_GETARG_INT64, PG_RETURN_VOID, and SET_LOCKTAG_INT64.

{
    int64       key = PG_GETARG_INT64(0);
    LOCKTAG     tag;

    SET_LOCKTAG_INT64(tag, key);

    (void) LockAcquire(&tag, ExclusiveLock, true, false);

    PG_RETURN_VOID();
}

Datum pg_advisory_lock_shared_int4 ( PG_FUNCTION_ARGS   ) 

Definition at line 635 of file lockfuncs.c.

References LockAcquire(), PG_GETARG_INT32, PG_RETURN_VOID, SET_LOCKTAG_INT32, and ShareLock.

{
    int32       key1 = PG_GETARG_INT32(0);
    int32       key2 = PG_GETARG_INT32(1);
    LOCKTAG     tag;

    SET_LOCKTAG_INT32(tag, key1, key2);

    (void) LockAcquire(&tag, ShareLock, true, false);

    PG_RETURN_VOID();
}

Datum pg_advisory_lock_shared_int8 ( PG_FUNCTION_ARGS   ) 

Definition at line 451 of file lockfuncs.c.

References LockAcquire(), PG_GETARG_INT64, PG_RETURN_VOID, SET_LOCKTAG_INT64, and ShareLock.

{
    int64       key = PG_GETARG_INT64(0);
    LOCKTAG     tag;

    SET_LOCKTAG_INT64(tag, key);

    (void) LockAcquire(&tag, ShareLock, true, false);

    PG_RETURN_VOID();
}

Datum pg_advisory_unlock_all ( PG_FUNCTION_ARGS   ) 
Datum pg_advisory_unlock_int4 ( PG_FUNCTION_ARGS   ) 

Definition at line 754 of file lockfuncs.c.

References ExclusiveLock, LockRelease(), PG_GETARG_INT32, PG_RETURN_BOOL, and SET_LOCKTAG_INT32.

{
    int32       key1 = PG_GETARG_INT32(0);
    int32       key2 = PG_GETARG_INT32(1);
    LOCKTAG     tag;
    bool        res;

    SET_LOCKTAG_INT32(tag, key1, key2);

    res = LockRelease(&tag, ExclusiveLock, true);

    PG_RETURN_BOOL(res);
}

Datum pg_advisory_unlock_int8 ( PG_FUNCTION_ARGS   ) 

Definition at line 564 of file lockfuncs.c.

References ExclusiveLock, LockRelease(), PG_GETARG_INT64, PG_RETURN_BOOL, and SET_LOCKTAG_INT64.

{
    int64       key = PG_GETARG_INT64(0);
    LOCKTAG     tag;
    bool        res;

    SET_LOCKTAG_INT64(tag, key);

    res = LockRelease(&tag, ExclusiveLock, true);

    PG_RETURN_BOOL(res);
}

Datum pg_advisory_unlock_shared_int4 ( PG_FUNCTION_ARGS   ) 

Definition at line 774 of file lockfuncs.c.

References LockRelease(), PG_GETARG_INT32, PG_RETURN_BOOL, SET_LOCKTAG_INT32, and ShareLock.

{
    int32       key1 = PG_GETARG_INT32(0);
    int32       key2 = PG_GETARG_INT32(1);
    LOCKTAG     tag;
    bool        res;

    SET_LOCKTAG_INT32(tag, key1, key2);

    res = LockRelease(&tag, ShareLock, true);

    PG_RETURN_BOOL(res);
}

Datum pg_advisory_unlock_shared_int8 ( PG_FUNCTION_ARGS   ) 

Definition at line 583 of file lockfuncs.c.

References LockRelease(), PG_GETARG_INT64, PG_RETURN_BOOL, SET_LOCKTAG_INT64, and ShareLock.

{
    int64       key = PG_GETARG_INT64(0);
    LOCKTAG     tag;
    bool        res;

    SET_LOCKTAG_INT64(tag, key);

    res = LockRelease(&tag, ShareLock, true);

    PG_RETURN_BOOL(res);
}

Datum pg_advisory_xact_lock_int4 ( PG_FUNCTION_ARGS   ) 

Definition at line 618 of file lockfuncs.c.

References ExclusiveLock, LockAcquire(), PG_GETARG_INT32, PG_RETURN_VOID, and SET_LOCKTAG_INT32.

{
    int32       key1 = PG_GETARG_INT32(0);
    int32       key2 = PG_GETARG_INT32(1);
    LOCKTAG     tag;

    SET_LOCKTAG_INT32(tag, key1, key2);

    (void) LockAcquire(&tag, ExclusiveLock, false, false);

    PG_RETURN_VOID();
}

Datum pg_advisory_xact_lock_int8 ( PG_FUNCTION_ARGS   ) 

Definition at line 435 of file lockfuncs.c.

References ExclusiveLock, LockAcquire(), PG_GETARG_INT64, PG_RETURN_VOID, and SET_LOCKTAG_INT64.

{
    int64       key = PG_GETARG_INT64(0);
    LOCKTAG     tag;

    SET_LOCKTAG_INT64(tag, key);

    (void) LockAcquire(&tag, ExclusiveLock, false, false);

    PG_RETURN_VOID();
}

Datum pg_advisory_xact_lock_shared_int4 ( PG_FUNCTION_ARGS   ) 

Definition at line 653 of file lockfuncs.c.

References LockAcquire(), PG_GETARG_INT32, PG_RETURN_VOID, SET_LOCKTAG_INT32, and ShareLock.

{
    int32       key1 = PG_GETARG_INT32(0);
    int32       key2 = PG_GETARG_INT32(1);
    LOCKTAG     tag;

    SET_LOCKTAG_INT32(tag, key1, key2);

    (void) LockAcquire(&tag, ShareLock, false, false);

    PG_RETURN_VOID();
}

Datum pg_advisory_xact_lock_shared_int8 ( PG_FUNCTION_ARGS   ) 

Definition at line 468 of file lockfuncs.c.

References LockAcquire(), PG_GETARG_INT64, PG_RETURN_VOID, SET_LOCKTAG_INT64, and ShareLock.

{
    int64       key = PG_GETARG_INT64(0);
    LOCKTAG     tag;

    SET_LOCKTAG_INT64(tag, key);

    (void) LockAcquire(&tag, ShareLock, false, false);

    PG_RETURN_VOID();
}

int32 pg_atoi ( char *  s,
int  size,
int  c 
)

Definition at line 37 of file numutils.c.

References elog, ereport, errcode(), errmsg(), ERROR, and NULL.

Referenced by ArrayGetIntegerTypmods(), check_foreign_key(), int2in(), int2vectorin(), int4in(), libpqrcv_endstreaming(), libpqrcv_identify_system(), prsd_headline(), and text_format().

{
    long        l;
    char       *badp;

    /*
     * Some versions of strtol treat the empty string as an error, but some
     * seem not to.  Make an explicit test to be sure we catch it.
     */
    if (s == NULL)
        elog(ERROR, "NULL pointer");
    if (*s == 0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                 errmsg("invalid input syntax for integer: \"%s\"",
                        s)));

    errno = 0;
    l = strtol(s, &badp, 10);

    /* We made no progress parsing the string, so bail out */
    if (s == badp)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                 errmsg("invalid input syntax for integer: \"%s\"",
                        s)));

    switch (size)
    {
        case sizeof(int32):
            if (errno == ERANGE
#if defined(HAVE_LONG_INT_64)
            /* won't get ERANGE on these with 64-bit longs... */
                || l < INT_MIN || l > INT_MAX
#endif
                )
                ereport(ERROR,
                        (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                errmsg("value \"%s\" is out of range for type integer", s)));
            break;
        case sizeof(int16):
            if (errno == ERANGE || l < SHRT_MIN || l > SHRT_MAX)
                ereport(ERROR,
                        (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                errmsg("value \"%s\" is out of range for type smallint", s)));
            break;
        case sizeof(int8):
            if (errno == ERANGE || l < SCHAR_MIN || l > SCHAR_MAX)
                ereport(ERROR,
                        (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                errmsg("value \"%s\" is out of range for 8-bit integer", s)));
            break;
        default:
            elog(ERROR, "unsupported result size: %d", size);
    }

    /*
     * Skip any trailing whitespace; if anything but whitespace remains before
     * the terminating character, bail out
     */
    while (*badp && *badp != c && isspace((unsigned char) *badp))
        badp++;

    if (*badp && *badp != c)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                 errmsg("invalid input syntax for integer: \"%s\"",
                        s)));

    return (int32) l;
}

Datum pg_available_extension_versions ( PG_FUNCTION_ARGS   ) 

Definition at line 1740 of file extension.c.

References AllocateDir(), ReturnSetInfo::allowedModes, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, elog, ereport, errcode(), errmsg(), ERROR, FreeDir(), get_available_versions_for_extension(), get_call_result_type(), get_extension_control_directory(), is_extension_control_filename(), IsA, MemoryContextSwitchTo(), NULL, pstrdup(), read_extension_control_file(), ReadDir(), ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, tuplestore_begin_heap(), tuplestore_donestoring, and work_mem.

{
    ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
    TupleDesc   tupdesc;
    Tuplestorestate *tupstore;
    MemoryContext per_query_ctx;
    MemoryContext oldcontext;
    char       *location;
    DIR        *dir;
    struct dirent *de;

    /* check to see if caller supports us returning a tuplestore */
    if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("set-valued function called in context that cannot accept a set")));
    if (!(rsinfo->allowedModes & SFRM_Materialize))
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("materialize mode required, but it is not " \
                        "allowed in this context")));

    /* Build a tuple descriptor for our result type */
    if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
        elog(ERROR, "return type must be a row type");

    /* Build tuplestore to hold the result rows */
    per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
    oldcontext = MemoryContextSwitchTo(per_query_ctx);

    tupstore = tuplestore_begin_heap(true, false, work_mem);
    rsinfo->returnMode = SFRM_Materialize;
    rsinfo->setResult = tupstore;
    rsinfo->setDesc = tupdesc;

    MemoryContextSwitchTo(oldcontext);

    location = get_extension_control_directory();
    dir = AllocateDir(location);

    /*
     * If the control directory doesn't exist, we want to silently return an
     * empty set.  Any other error will be reported by ReadDir.
     */
    if (dir == NULL && errno == ENOENT)
    {
        /* do nothing */
    }
    else
    {
        while ((de = ReadDir(dir, location)) != NULL)
        {
            ExtensionControlFile *control;
            char       *extname;

            if (!is_extension_control_filename(de->d_name))
                continue;

            /* extract extension name from 'name.control' filename */
            extname = pstrdup(de->d_name);
            *strrchr(extname, '.') = '\0';

            /* ignore it if it's an auxiliary control file */
            if (strstr(extname, "--"))
                continue;

            /* read the control file */
            control = read_extension_control_file(extname);

            /* scan extension's script directory for install scripts */
            get_available_versions_for_extension(control, tupstore, tupdesc);
        }

        FreeDir(dir);
    }

    /* clean up and return the tuplestore */
    tuplestore_donestoring(tupstore);

    return (Datum) 0;
}

Datum pg_available_extensions ( PG_FUNCTION_ARGS   ) 

Definition at line 1631 of file extension.c.

References AllocateDir(), ReturnSetInfo::allowedModes, ExtensionControlFile::comment, CStringGetDatum, CStringGetTextDatum, ExtensionControlFile::default_version, DirectFunctionCall1, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, elog, ereport, errcode(), errmsg(), ERROR, FreeDir(), get_call_result_type(), get_extension_control_directory(), is_extension_control_filename(), IsA, MemoryContextSwitchTo(), ExtensionControlFile::name, namein(), NULL, pstrdup(), read_extension_control_file(), ReadDir(), ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, tuplestore_begin_heap(), tuplestore_donestoring, tuplestore_putvalues(), values, and work_mem.

{
    ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
    TupleDesc   tupdesc;
    Tuplestorestate *tupstore;
    MemoryContext per_query_ctx;
    MemoryContext oldcontext;
    char       *location;
    DIR        *dir;
    struct dirent *de;

    /* check to see if caller supports us returning a tuplestore */
    if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("set-valued function called in context that cannot accept a set")));
    if (!(rsinfo->allowedModes & SFRM_Materialize))
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("materialize mode required, but it is not " \
                        "allowed in this context")));

    /* Build a tuple descriptor for our result type */
    if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
        elog(ERROR, "return type must be a row type");

    /* Build tuplestore to hold the result rows */
    per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
    oldcontext = MemoryContextSwitchTo(per_query_ctx);

    tupstore = tuplestore_begin_heap(true, false, work_mem);
    rsinfo->returnMode = SFRM_Materialize;
    rsinfo->setResult = tupstore;
    rsinfo->setDesc = tupdesc;

    MemoryContextSwitchTo(oldcontext);

    location = get_extension_control_directory();
    dir = AllocateDir(location);

    /*
     * If the control directory doesn't exist, we want to silently return an
     * empty set.  Any other error will be reported by ReadDir.
     */
    if (dir == NULL && errno == ENOENT)
    {
        /* do nothing */
    }
    else
    {
        while ((de = ReadDir(dir, location)) != NULL)
        {
            ExtensionControlFile *control;
            char       *extname;
            Datum       values[3];
            bool        nulls[3];

            if (!is_extension_control_filename(de->d_name))
                continue;

            /* extract extension name from 'name.control' filename */
            extname = pstrdup(de->d_name);
            *strrchr(extname, '.') = '\0';

            /* ignore it if it's an auxiliary control file */
            if (strstr(extname, "--"))
                continue;

            control = read_extension_control_file(extname);

            memset(values, 0, sizeof(values));
            memset(nulls, 0, sizeof(nulls));

            /* name */
            values[0] = DirectFunctionCall1(namein,
                                            CStringGetDatum(control->name));
            /* default_version */
            if (control->default_version == NULL)
                nulls[1] = true;
            else
                values[1] = CStringGetTextDatum(control->default_version);
            /* comment */
            if (control->comment == NULL)
                nulls[2] = true;
            else
                values[2] = CStringGetTextDatum(control->comment);

            tuplestore_putvalues(tupstore, tupdesc, values, nulls);
        }

        FreeDir(dir);
    }

    /* clean up and return the tuplestore */
    tuplestore_donestoring(tupstore);

    return (Datum) 0;
}

Datum pg_cancel_backend ( PG_FUNCTION_ARGS   ) 

Definition at line 147 of file misc.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT32, PG_RETURN_BOOL, pg_signal_backend(), SIGNAL_BACKEND_NOPERMISSION, and SIGNAL_BACKEND_SUCCESS.

{
    int         r = pg_signal_backend(PG_GETARG_INT32(0), SIGINT);

    if (r == SIGNAL_BACKEND_NOPERMISSION)
        ereport(ERROR,
                (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                 (errmsg("must be superuser or have the same role to cancel queries running in other server processes"))));

    PG_RETURN_BOOL(r == SIGNAL_BACKEND_SUCCESS);
}

Datum PG_char_to_encoding ( PG_FUNCTION_ARGS   ) 
Datum PG_character_set_id ( PG_FUNCTION_ARGS   ) 
Datum PG_character_set_name ( PG_FUNCTION_ARGS   ) 
Datum pg_client_encoding ( PG_FUNCTION_ARGS   ) 
Datum pg_collation_for ( PG_FUNCTION_ARGS   ) 

Definition at line 509 of file misc.c.

References cstring_to_text(), ereport, errcode(), errmsg(), ERROR, format_type_be(), generate_collation_name(), get_fn_expr_argtype(), PG_GET_COLLATION, PG_RETURN_NULL, PG_RETURN_TEXT_P, type_is_collatable(), and UNKNOWNOID.

{
    Oid         typeid;
    Oid         collid;

    typeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
    if (!typeid)
        PG_RETURN_NULL();
    if (!type_is_collatable(typeid) && typeid != UNKNOWNOID)
        ereport(ERROR,
                (errcode(ERRCODE_DATATYPE_MISMATCH),
                 errmsg("collations are not supported by type %s",
                        format_type_be(typeid))));

    collid = PG_GET_COLLATION();
    if (!collid)
        PG_RETURN_NULL();
    PG_RETURN_TEXT_P(cstring_to_text(generate_collation_name(collid)));
}

Datum pg_column_size ( PG_FUNCTION_ARGS   ) 

Definition at line 3681 of file varlena.c.

References DatumGetCString, elog, ERROR, get_fn_expr_argtype(), get_typlen(), MemoryContextAlloc(), NULL, PG_GETARG_DATUM, PG_RETURN_INT32, toast_datum_size(), and value.

{
    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);

        fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
                                                      sizeof(int));
        *((int *) fcinfo->flinfo->fn_extra) = typlen;
    }
    else
        typlen = *((int *) fcinfo->flinfo->fn_extra);

    if (typlen == -1)
    {
        /* varlena type, possibly toasted */
        result = toast_datum_size(value);
    }
    else if (typlen == -2)
    {
        /* cstring */
        result = strlen(DatumGetCString(value)) + 1;
    }
    else
    {
        /* ordinary fixed-width type */
        result = typlen;
    }

    PG_RETURN_INT32(result);
}

Datum pg_convert ( PG_FUNCTION_ARGS   ) 

Definition at line 447 of file mbutils.c.

References ereport, errcode(), errmsg(), ERROR, NameStr, palloc(), pfree(), pg_char_to_encoding(), pg_do_encoding_conversion(), PG_FREE_IF_COPY, PG_GETARG_BYTEA_PP, PG_GETARG_NAME, PG_RETURN_BYTEA_P, pg_verify_mbstr_len(), SET_VARSIZE, VARDATA, VARDATA_ANY, VARHDRSZ, and VARSIZE_ANY_EXHDR.

Referenced by pg_convert_from(), and pg_convert_to().

{
    bytea      *string = PG_GETARG_BYTEA_PP(0);
    char       *src_encoding_name = NameStr(*PG_GETARG_NAME(1));
    int         src_encoding = pg_char_to_encoding(src_encoding_name);
    char       *dest_encoding_name = NameStr(*PG_GETARG_NAME(2));
    int         dest_encoding = pg_char_to_encoding(dest_encoding_name);
    const char *src_str;
    char       *dest_str;
    bytea      *retval;
    int         len;

    if (src_encoding < 0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("invalid source encoding name \"%s\"",
                        src_encoding_name)));
    if (dest_encoding < 0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("invalid destination encoding name \"%s\"",
                        dest_encoding_name)));

    /* make sure that source string is valid */
    len = VARSIZE_ANY_EXHDR(string);
    src_str = VARDATA_ANY(string);
    pg_verify_mbstr_len(src_encoding, src_str, len, false);

    dest_str = (char *) pg_do_encoding_conversion(
                (unsigned char *) src_str, len, src_encoding, dest_encoding);
    if (dest_str != src_str)
        len = strlen(dest_str);

    /*
     * build bytea data type structure.
     */
    retval = (bytea *) palloc(len + VARHDRSZ);
    SET_VARSIZE(retval, len + VARHDRSZ);
    memcpy(VARDATA(retval), dest_str, len);

    if (dest_str != src_str)
        pfree(dest_str);

    /* free memory if allocated by the toaster */
    PG_FREE_IF_COPY(string, 0);

    PG_RETURN_BYTEA_P(retval);
}

Datum pg_convert_from ( PG_FUNCTION_ARGS   ) 

Definition at line 420 of file mbutils.c.

References CStringGetDatum, DirectFunctionCall1, DirectFunctionCall3, pg_enc2name::name, namein(), pg_convert(), PG_GETARG_DATUM, and PG_RETURN_DATUM.

{
    Datum       string = PG_GETARG_DATUM(0);
    Datum       src_encoding_name = PG_GETARG_DATUM(1);
    Datum       dest_encoding_name = DirectFunctionCall1(namein,
                                    CStringGetDatum(DatabaseEncoding->name));
    Datum       result;

    result = DirectFunctionCall3(pg_convert, string,
                                 src_encoding_name, dest_encoding_name);

    /*
     * pg_convert returns a bytea, which we in turn return as text, relying on
     * the fact that they are both in fact varlena types, and thus
     * structurally identical. Although not all bytea values are valid text,
     * in this case it will be because we've told pg_convert to return one
     * that is valid as text in the current database encoding.
     */
    PG_RETURN_DATUM(result);
}

Datum pg_convert_to ( PG_FUNCTION_ARGS   ) 

Definition at line 395 of file mbutils.c.

References CStringGetDatum, DirectFunctionCall1, DirectFunctionCall3, pg_enc2name::name, namein(), pg_convert(), PG_GETARG_DATUM, and PG_RETURN_DATUM.

{
    Datum       string = PG_GETARG_DATUM(0);
    Datum       dest_encoding_name = PG_GETARG_DATUM(1);
    Datum       src_encoding_name = DirectFunctionCall1(namein,
                                    CStringGetDatum(DatabaseEncoding->name));
    Datum       result;

    /*
     * pg_convert expects a bytea as its first argument. We're passing it a
     * text argument here, relying on the fact that they are both in fact
     * varlena types, and thus structurally identical.
     */
    result = DirectFunctionCall3(pg_convert, string,
                                 src_encoding_name, dest_encoding_name);

    PG_RETURN_DATUM(result);
}

Datum pg_cursor ( PG_FUNCTION_ARGS   ) 

Definition at line 972 of file portalmem.c.

References ReturnSetInfo::allowedModes, BoolGetDatum, BOOLOID, CreateTemplateTupleDesc(), PortalData::creation_time, CStringGetTextDatum, CURSOR_OPT_BINARY, CURSOR_OPT_HOLD, CURSOR_OPT_SCROLL, PortalData::cursorOptions, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, ereport, errcode(), errmsg(), ERROR, hash_seq_init(), hash_seq_search(), IsA, MemoryContextSwitchTo(), MemSet, PortalData::name, NULL, ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, SFRM_Materialize_Random, PortalData::sourceText, TEXTOID, TimestampTzGetDatum, TIMESTAMPTZOID, TupleDescInitEntry(), tuplestore_begin_heap(), tuplestore_donestoring, tuplestore_putvalues(), values, PortalData::visible, and work_mem.

{
    ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
    TupleDesc   tupdesc;
    Tuplestorestate *tupstore;
    MemoryContext per_query_ctx;
    MemoryContext oldcontext;
    HASH_SEQ_STATUS hash_seq;
    PortalHashEnt *hentry;

    /* check to see if caller supports us returning a tuplestore */
    if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("set-valued function called in context that cannot accept a set")));
    if (!(rsinfo->allowedModes & SFRM_Materialize))
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("materialize mode required, but it is not " \
                        "allowed in this context")));

    /* need to build tuplestore in query context */
    per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
    oldcontext = MemoryContextSwitchTo(per_query_ctx);

    /*
     * build tupdesc for result tuples. This must match the definition of the
     * pg_cursors view in system_views.sql
     */
    tupdesc = CreateTemplateTupleDesc(6, false);
    TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
                       TEXTOID, -1, 0);
    TupleDescInitEntry(tupdesc, (AttrNumber) 2, "statement",
                       TEXTOID, -1, 0);
    TupleDescInitEntry(tupdesc, (AttrNumber) 3, "is_holdable",
                       BOOLOID, -1, 0);
    TupleDescInitEntry(tupdesc, (AttrNumber) 4, "is_binary",
                       BOOLOID, -1, 0);
    TupleDescInitEntry(tupdesc, (AttrNumber) 5, "is_scrollable",
                       BOOLOID, -1, 0);
    TupleDescInitEntry(tupdesc, (AttrNumber) 6, "creation_time",
                       TIMESTAMPTZOID, -1, 0);

    /*
     * We put all the tuples into a tuplestore in one scan of the hashtable.
     * This avoids any issue of the hashtable possibly changing between calls.
     */
    tupstore =
        tuplestore_begin_heap(rsinfo->allowedModes & SFRM_Materialize_Random,
                              false, work_mem);

    /* generate junk in short-term context */
    MemoryContextSwitchTo(oldcontext);

    hash_seq_init(&hash_seq, PortalHashTable);
    while ((hentry = hash_seq_search(&hash_seq)) != NULL)
    {
        Portal      portal = hentry->portal;
        Datum       values[6];
        bool        nulls[6];

        /* report only "visible" entries */
        if (!portal->visible)
            continue;

        MemSet(nulls, 0, sizeof(nulls));

        values[0] = CStringGetTextDatum(portal->name);
        values[1] = CStringGetTextDatum(portal->sourceText);
        values[2] = BoolGetDatum(portal->cursorOptions & CURSOR_OPT_HOLD);
        values[3] = BoolGetDatum(portal->cursorOptions & CURSOR_OPT_BINARY);
        values[4] = BoolGetDatum(portal->cursorOptions & CURSOR_OPT_SCROLL);
        values[5] = TimestampTzGetDatum(portal->creation_time);

        tuplestore_putvalues(tupstore, tupdesc, values, nulls);
    }

    /* clean up and return the tuplestore */
    tuplestore_donestoring(tupstore);

    rsinfo->returnMode = SFRM_Materialize;
    rsinfo->setResult = tupstore;
    rsinfo->setDesc = tupdesc;

    return (Datum) 0;
}

Datum pg_database_size_name ( PG_FUNCTION_ARGS   ) 

Definition at line 144 of file dbsize.c.

References calculate_database_size(), dbName, get_database_oid(), NameStr, PG_GETARG_NAME, PG_RETURN_INT64, and PG_RETURN_NULL.

{
    Name        dbName = PG_GETARG_NAME(0);
    Oid         dbOid = get_database_oid(NameStr(*dbName), false);
    int64       size;

    size = calculate_database_size(dbOid);

    if (size == 0)
        PG_RETURN_NULL();

    PG_RETURN_INT64(size);
}

Datum pg_database_size_oid ( PG_FUNCTION_ARGS   ) 

Definition at line 130 of file dbsize.c.

References calculate_database_size(), PG_GETARG_OID, PG_RETURN_INT64, and PG_RETURN_NULL.

{
    Oid         dbOid = PG_GETARG_OID(0);
    int64       size;

    size = calculate_database_size(dbOid);

    if (size == 0)
        PG_RETURN_NULL();

    PG_RETURN_INT64(size);
}

Datum pg_describe_object ( PG_FUNCTION_ARGS   ) 

Definition at line 2282 of file objectaddress.c.

References ObjectAddress::classId, cstring_to_text(), getObjectDescription(), ObjectAddress::objectId, ObjectAddress::objectSubId, OidIsValid, PG_GETARG_INT32, PG_GETARG_OID, PG_RETURN_NULL, and PG_RETURN_TEXT_P.

{
    Oid         classid = PG_GETARG_OID(0);
    Oid         objid = PG_GETARG_OID(1);
    int32       subobjid = PG_GETARG_INT32(2);
    char       *description;
    ObjectAddress address;

    /* for "pinned" items in pg_depend, return null */
    if (!OidIsValid(classid) && !OidIsValid(objid))
        PG_RETURN_NULL();

    address.classId = classid;
    address.objectId = objid;
    address.objectSubId = subobjid;

    description = getObjectDescription(&address);
    PG_RETURN_TEXT_P(cstring_to_text(description));
}

Datum pg_encoding_max_length_sql ( PG_FUNCTION_ARGS   ) 

Definition at line 524 of file mbutils.c.

References encoding, PG_GETARG_INT32, PG_RETURN_INT32, PG_RETURN_NULL, PG_VALID_ENCODING, and pg_wchar_table.

{
    int         encoding = PG_GETARG_INT32(0);

    if (PG_VALID_ENCODING(encoding))
        PG_RETURN_INT32(pg_wchar_table[encoding].maxmblen);
    else
        PG_RETURN_NULL();
}

Datum PG_encoding_to_char ( PG_FUNCTION_ARGS   ) 

Definition at line 548 of file encnames.c.

References CStringGetDatum, DirectFunctionCall1, encoding, namein(), pg_encoding_to_char(), and PG_GETARG_INT32.

{
    int32       encoding = PG_GETARG_INT32(0);
    const char *encoding_name = pg_encoding_to_char(encoding);

    return DirectFunctionCall1(namein, CStringGetDatum(encoding_name));
}

Datum pg_event_trigger_dropped_objects ( PG_FUNCTION_ARGS   ) 

Definition at line 1190 of file event_trigger.c.

References SQLDropObject::address, ReturnSetInfo::allowedModes, ObjectAddress::classId, CStringGetTextDatum, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, elog, ereport, errcode(), errmsg(), ERROR, get_call_result_type(), i, EventTriggerQueryState::in_sql_drop, Int32GetDatum, IsA, MemoryContextSwitchTo(), MemSet, next(), NULL, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, SQLDropObject::objecttype, SQLDropObject::objidentity, SQLDropObject::objname, ReturnSetInfo::returnMode, SQLDropObject::schemaname, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, slist_container, slist_foreach, EventTriggerQueryState::SQLDropList, tuplestore_begin_heap(), tuplestore_donestoring, tuplestore_putvalues(), TYPEFUNC_COMPOSITE, values, and work_mem.

{
    ReturnSetInfo      *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
    TupleDesc           tupdesc;
    Tuplestorestate    *tupstore;
    MemoryContext       per_query_ctx;
    MemoryContext       oldcontext;
    slist_iter          iter;

    /*
     * Protect this function from being called out of context
     */
    if (!currentEventTriggerState ||
        !currentEventTriggerState->in_sql_drop)
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("%s can only be called in a sql_drop event trigger function",
                        "pg_event_trigger_dropped_objects()")));

    /* check to see if caller supports us returning a tuplestore */
    if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("set-valued function called in context that cannot accept a set")));
    if (!(rsinfo->allowedModes & SFRM_Materialize))
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("materialize mode required, but it is not allowed in this context")));

    /* Build a tuple descriptor for our result type */
    if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
        elog(ERROR, "return type must be a row type");

    /* Build tuplestore to hold the result rows */
    per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
    oldcontext = MemoryContextSwitchTo(per_query_ctx);

    tupstore = tuplestore_begin_heap(true, false, work_mem);
    rsinfo->returnMode = SFRM_Materialize;
    rsinfo->setResult = tupstore;
    rsinfo->setDesc = tupdesc;

    MemoryContextSwitchTo(oldcontext);

    slist_foreach(iter, &(currentEventTriggerState->SQLDropList))
    {
        SQLDropObject *obj;
        int         i = 0;
        Datum       values[7];
        bool        nulls[7];

        obj = slist_container(SQLDropObject, next, iter.cur);

        MemSet(values, 0, sizeof(values));
        MemSet(nulls, 0, sizeof(nulls));

        /* classid */
        values[i++] = ObjectIdGetDatum(obj->address.classId);

        /* objid */
        values[i++] = ObjectIdGetDatum(obj->address.objectId);

        /* objsubid */
        values[i++] = Int32GetDatum(obj->address.objectSubId);

        /* object_type */
        values[i++] = CStringGetTextDatum(obj->objecttype);

        /* schema_name */
        if (obj->schemaname)
            values[i++] = CStringGetTextDatum(obj->schemaname);
        else
            nulls[i++] = true;

        /* object_name */
        if (obj->objname)
            values[i++] = CStringGetTextDatum(obj->objname);
        else
            nulls[i++] = true;

        /* object_identity */
        if (obj->objidentity)
            values[i++] = CStringGetTextDatum(obj->objidentity);
        else
            nulls[i++] = true;

        tuplestore_putvalues(tupstore, tupdesc, values, nulls);
    }

    /* clean up and return the tuplestore */
    tuplestore_donestoring(tupstore);

    return (Datum) 0;
}

Datum pg_extension_config_dump ( PG_FUNCTION_ARGS   ) 

Definition at line 2043 of file extension.c.

References Anum_pg_extension_extcondition, Anum_pg_extension_extconfig, ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_LBOUND, ARR_NDIM, array_set(), BTEqualStrategyNumber, CatalogUpdateIndexes(), construct_array(), creating_extension, CurrentExtensionObject, DatumGetArrayTypeP, elog, ereport, errcode(), errmsg(), ERROR, ExtensionOidIndexId, ExtensionRelationId, get_rel_name(), getExtensionOfObject(), heap_close, heap_getattr, heap_modify_tuple(), heap_open(), HeapTupleIsValid, i, NULL, ObjectIdAttributeNumber, ObjectIdGetDatum, OIDOID, PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_VOID, PointerGetDatum, RelationGetDescr, RelationRelationId, RowExclusiveLock, ScanKeyInit(), simple_heap_update(), SnapshotNow, systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, and TEXTOID.

{
    Oid         tableoid = PG_GETARG_OID(0);
    text       *wherecond = PG_GETARG_TEXT_P(1);
    char       *tablename;
    Relation    extRel;
    ScanKeyData key[1];
    SysScanDesc extScan;
    HeapTuple   extTup;
    Datum       arrayDatum;
    Datum       elementDatum;
    int         arrayLength;
    int         arrayIndex;
    bool        isnull;
    Datum       repl_val[Natts_pg_extension];
    bool        repl_null[Natts_pg_extension];
    bool        repl_repl[Natts_pg_extension];
    ArrayType  *a;

    /*
     * We only allow this to be called from an extension's SQL script. We
     * shouldn't need any permissions check beyond that.
     */
    if (!creating_extension)
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("pg_extension_config_dump() can only be called "
                        "from an SQL script executed by CREATE EXTENSION")));

    /*
     * Check that the table exists and is a member of the extension being
     * created.  This ensures that we don't need to register an additional
     * dependency to protect the extconfig entry.
     */
    tablename = get_rel_name(tableoid);
    if (tablename == NULL)
        ereport(ERROR,
                (errcode(ERRCODE_UNDEFINED_TABLE),
                 errmsg("OID %u does not refer to a table", tableoid)));
    if (getExtensionOfObject(RelationRelationId, tableoid) !=
        CurrentExtensionObject)
        ereport(ERROR,
                (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
        errmsg("table \"%s\" is not a member of the extension being created",
               tablename)));

    /*
     * Add the table OID and WHERE condition to the extension's extconfig and
     * extcondition arrays.
     *
     * If the table is already in extconfig, treat this as an update of the
     * WHERE condition.
     */

    /* Find the pg_extension tuple */
    extRel = heap_open(ExtensionRelationId, RowExclusiveLock);

    ScanKeyInit(&key[0],
                ObjectIdAttributeNumber,
                BTEqualStrategyNumber, F_OIDEQ,
                ObjectIdGetDatum(CurrentExtensionObject));

    extScan = systable_beginscan(extRel, ExtensionOidIndexId, true,
                                 SnapshotNow, 1, key);

    extTup = systable_getnext(extScan);

    if (!HeapTupleIsValid(extTup))      /* should not happen */
        elog(ERROR, "extension with oid %u does not exist",
             CurrentExtensionObject);

    memset(repl_val, 0, sizeof(repl_val));
    memset(repl_null, false, sizeof(repl_null));
    memset(repl_repl, false, sizeof(repl_repl));

    /* Build or modify the extconfig value */
    elementDatum = ObjectIdGetDatum(tableoid);

    arrayDatum = heap_getattr(extTup, Anum_pg_extension_extconfig,
                              RelationGetDescr(extRel), &isnull);
    if (isnull)
    {
        /* Previously empty extconfig, so build 1-element array */
        arrayLength = 0;
        arrayIndex = 1;

        a = construct_array(&elementDatum, 1,
                            OIDOID,
                            sizeof(Oid), true, 'i');
    }
    else
    {
        /* Modify or extend existing extconfig array */
        Oid        *arrayData;
        int         i;

        a = DatumGetArrayTypeP(arrayDatum);

        arrayLength = ARR_DIMS(a)[0];
        if (ARR_NDIM(a) != 1 ||
            ARR_LBOUND(a)[0] != 1 ||
            arrayLength < 0 ||
            ARR_HASNULL(a) ||
            ARR_ELEMTYPE(a) != OIDOID)
            elog(ERROR, "extconfig is not a 1-D Oid array");
        arrayData = (Oid *) ARR_DATA_PTR(a);

        arrayIndex = arrayLength + 1;   /* set up to add after end */

        for (i = 0; i < arrayLength; i++)
        {
            if (arrayData[i] == tableoid)
            {
                arrayIndex = i + 1;     /* replace this element instead */
                break;
            }
        }

        a = array_set(a, 1, &arrayIndex,
                      elementDatum,
                      false,
                      -1 /* varlena array */ ,
                      sizeof(Oid) /* OID's typlen */ ,
                      true /* OID's typbyval */ ,
                      'i' /* OID's typalign */ );
    }
    repl_val[Anum_pg_extension_extconfig - 1] = PointerGetDatum(a);
    repl_repl[Anum_pg_extension_extconfig - 1] = true;

    /* Build or modify the extcondition value */
    elementDatum = PointerGetDatum(wherecond);

    arrayDatum = heap_getattr(extTup, Anum_pg_extension_extcondition,
                              RelationGetDescr(extRel), &isnull);
    if (isnull)
    {
        if (arrayLength != 0)
            elog(ERROR, "extconfig and extcondition arrays do not match");

        a = construct_array(&elementDatum, 1,
                            TEXTOID,
                            -1, false, 'i');
    }
    else
    {
        a = DatumGetArrayTypeP(arrayDatum);

        if (ARR_NDIM(a) != 1 ||
            ARR_LBOUND(a)[0] != 1 ||
            ARR_HASNULL(a) ||
            ARR_ELEMTYPE(a) != TEXTOID)
            elog(ERROR, "extcondition is not a 1-D text array");
        if (ARR_DIMS(a)[0] != arrayLength)
            elog(ERROR, "extconfig and extcondition arrays do not match");

        /* Add or replace at same index as in extconfig */
        a = array_set(a, 1, &arrayIndex,
                      elementDatum,
                      false,
                      -1 /* varlena array */ ,
                      -1 /* TEXT's typlen */ ,
                      false /* TEXT's typbyval */ ,
                      'i' /* TEXT's typalign */ );
    }
    repl_val[Anum_pg_extension_extcondition - 1] = PointerGetDatum(a);
    repl_repl[Anum_pg_extension_extcondition - 1] = true;

    extTup = heap_modify_tuple(extTup, RelationGetDescr(extRel),
                               repl_val, repl_null, repl_repl);

    simple_heap_update(extRel, &extTup->t_self, extTup);
    CatalogUpdateIndexes(extRel, extTup);

    systable_endscan(extScan);

    heap_close(extRel, RowExclusiveLock);

    PG_RETURN_VOID();
}

Datum pg_extension_update_paths ( PG_FUNCTION_ARGS   ) 

Definition at line 1929 of file extension.c.

References ReturnSetInfo::allowedModes, appendStringInfoString(), check_valid_extension_name(), CStringGetTextDatum, StringInfoData::data, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, elog, ereport, errcode(), errmsg(), ERROR, find_update_path(), get_call_result_type(), get_ext_ver_list(), initStringInfo(), IsA, lfirst, MemoryContextSwitchTo(), ExtensionVersionInfo::name, NameStr, NIL, NULL, pfree(), PG_GETARG_NAME, read_extension_control_file(), ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, tuplestore_begin_heap(), tuplestore_donestoring, tuplestore_putvalues(), values, and work_mem.

{
    Name        extname = PG_GETARG_NAME(0);
    ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
    TupleDesc   tupdesc;
    Tuplestorestate *tupstore;
    MemoryContext per_query_ctx;
    MemoryContext oldcontext;
    List       *evi_list;
    ExtensionControlFile *control;
    ListCell   *lc1;

    /* Check extension name validity before any filesystem access */
    check_valid_extension_name(NameStr(*extname));

    /* check to see if caller supports us returning a tuplestore */
    if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("set-valued function called in context that cannot accept a set")));
    if (!(rsinfo->allowedModes & SFRM_Materialize))
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("materialize mode required, but it is not " \
                        "allowed in this context")));

    /* Build a tuple descriptor for our result type */
    if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
        elog(ERROR, "return type must be a row type");

    /* Build tuplestore to hold the result rows */
    per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
    oldcontext = MemoryContextSwitchTo(per_query_ctx);

    tupstore = tuplestore_begin_heap(true, false, work_mem);
    rsinfo->returnMode = SFRM_Materialize;
    rsinfo->setResult = tupstore;
    rsinfo->setDesc = tupdesc;

    MemoryContextSwitchTo(oldcontext);

    /* Read the extension's control file */
    control = read_extension_control_file(NameStr(*extname));

    /* Extract the version update graph from the script directory */
    evi_list = get_ext_ver_list(control);

    /* Iterate over all pairs of versions */
    foreach(lc1, evi_list)
    {
        ExtensionVersionInfo *evi1 = (ExtensionVersionInfo *) lfirst(lc1);
        ListCell   *lc2;

        foreach(lc2, evi_list)
        {
            ExtensionVersionInfo *evi2 = (ExtensionVersionInfo *) lfirst(lc2);
            List       *path;
            Datum       values[3];
            bool        nulls[3];

            if (evi1 == evi2)
                continue;

            /* Find shortest path from evi1 to evi2 */
            path = find_update_path(evi_list, evi1, evi2, true);

            /* Emit result row */
            memset(values, 0, sizeof(values));
            memset(nulls, 0, sizeof(nulls));

            /* source */
            values[0] = CStringGetTextDatum(evi1->name);
            /* target */
            values[1] = CStringGetTextDatum(evi2->name);
            /* path */
            if (path == NIL)
                nulls[2] = true;
            else
            {
                StringInfoData pathbuf;
                ListCell   *lcv;

                initStringInfo(&pathbuf);
                /* The path doesn't include start vertex, but show it */
                appendStringInfoString(&pathbuf, evi1->name);
                foreach(lcv, path)
                {
                    char       *versionName = (char *) lfirst(lcv);

                    appendStringInfoString(&pathbuf, "--");
                    appendStringInfoString(&pathbuf, versionName);
                }
                values[2] = CStringGetTextDatum(pathbuf.data);
                pfree(pathbuf.data);
            }

            tuplestore_putvalues(tupstore, tupdesc, values, nulls);
        }
    }

    /* clean up and return the tuplestore */
    tuplestore_donestoring(tupstore);

    return (Datum) 0;
}

Datum pg_get_constraintdef ( PG_FUNCTION_ARGS   ) 

Definition at line 1253 of file ruleutils.c.

References pg_get_constraintdef_worker(), PG_GETARG_OID, PG_RETURN_TEXT_P, and string_to_text().

{
    Oid         constraintId = PG_GETARG_OID(0);
    int         prettyFlags;

    prettyFlags = PRETTYFLAG_INDENT;
    PG_RETURN_TEXT_P(string_to_text(pg_get_constraintdef_worker(constraintId,
                                                                false,
                                                                prettyFlags)));
}

Datum pg_get_constraintdef_ext ( PG_FUNCTION_ARGS   ) 

Definition at line 1265 of file ruleutils.c.

References pg_get_constraintdef_worker(), PG_GETARG_BOOL, PG_GETARG_OID, PG_RETURN_TEXT_P, PRETTYFLAG_INDENT, PRETTYFLAG_PAREN, and string_to_text().

{
    Oid         constraintId = PG_GETARG_OID(0);
    bool        pretty = PG_GETARG_BOOL(1);
    int         prettyFlags;

    prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : PRETTYFLAG_INDENT;
    PG_RETURN_TEXT_P(string_to_text(pg_get_constraintdef_worker(constraintId,
                                                                false,
                                                                prettyFlags)));
}

char* pg_get_constraintdef_string ( Oid  constraintId  ) 

Definition at line 1279 of file ruleutils.c.

References pg_get_constraintdef_worker().

Referenced by ATExecAlterColumnType().

{
    return pg_get_constraintdef_worker(constraintId, true, 0);
}

Datum pg_get_expr ( PG_FUNCTION_ARGS   ) 

Definition at line 1626 of file ruleutils.c.

References get_rel_name(), NULL, OidIsValid, pg_get_expr_worker(), PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_NULL, and PG_RETURN_TEXT_P.

Referenced by decompile_conbin().

{
    text       *expr = PG_GETARG_TEXT_P(0);
    Oid         relid = PG_GETARG_OID(1);
    int         prettyFlags;
    char       *relname;

    prettyFlags = PRETTYFLAG_INDENT;

    if (OidIsValid(relid))
    {
        /* Get the name for the relation */
        relname = get_rel_name(relid);

        /*
         * If the OID isn't actually valid, don't throw an error, just return
         * NULL.  This is a bit questionable, but it's what we've done
         * historically, and it can help avoid unwanted failures when
         * examining catalog entries for just-deleted relations.
         */
        if (relname == NULL)
            PG_RETURN_NULL();
    }
    else
        relname = NULL;

    PG_RETURN_TEXT_P(pg_get_expr_worker(expr, relid, relname, prettyFlags));
}

Datum pg_get_expr_ext ( PG_FUNCTION_ARGS   ) 

Definition at line 1656 of file ruleutils.c.

References get_rel_name(), NULL, OidIsValid, pg_get_expr_worker(), PG_GETARG_BOOL, PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_NULL, PG_RETURN_TEXT_P, PRETTYFLAG_INDENT, and PRETTYFLAG_PAREN.

{
    text       *expr = PG_GETARG_TEXT_P(0);
    Oid         relid = PG_GETARG_OID(1);
    bool        pretty = PG_GETARG_BOOL(2);
    int         prettyFlags;
    char       *relname;

    prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : PRETTYFLAG_INDENT;

    if (OidIsValid(relid))
    {
        /* Get the name for the relation */
        relname = get_rel_name(relid);
        /* See notes above */
        if (relname == NULL)
            PG_RETURN_NULL();
    }
    else
        relname = NULL;

    PG_RETURN_TEXT_P(pg_get_expr_worker(expr, relid, relname, prettyFlags));
}

Datum pg_get_function_arguments ( PG_FUNCTION_ARGS   ) 
Datum pg_get_function_identity_arguments ( PG_FUNCTION_ARGS   ) 
Datum pg_get_function_result ( PG_FUNCTION_ARGS   ) 
Datum pg_get_functiondef ( PG_FUNCTION_ARGS   ) 

Definition at line 1866 of file ruleutils.c.

References Anum_pg_proc_probin, Anum_pg_proc_proconfig, Anum_pg_proc_prosrc, appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), ARR_DIMS, ARR_ELEMTYPE, ARR_LBOUND, ARR_NDIM, array_ref(), Assert, buf, ClanguageId, StringInfoData::data, DatumGetArrayTypeP, elog, ereport, errcode(), errmsg(), ERROR, get_namespace_name(), GETSTRUCT, HeapTupleIsValid, i, initStringInfo(), INTERNALlanguageId, LANGOID, StringInfoData::len, name, NameStr, NULL, ObjectIdGetDatum, PG_GETARG_OID, PG_RETURN_TEXT_P, pg_strcasecmp(), print_function_arguments(), print_function_rettype(), PROCOID, PROVOLATILE_IMMUTABLE, PROVOLATILE_STABLE, PROVOLATILE_VOLATILE, quote_identifier(), quote_qualified_identifier(), ReleaseSysCache(), SearchSysCache1, simple_quote_literal(), string_to_text(), SysCacheGetAttr(), TextDatumGetCString, and TEXTOID.

{
    Oid         funcid = PG_GETARG_OID(0);
    StringInfoData buf;
    StringInfoData dq;
    HeapTuple   proctup;
    HeapTuple   langtup;
    Form_pg_proc proc;
    Form_pg_language lang;
    Datum       tmp;
    bool        isnull;
    const char *prosrc;
    const char *name;
    const char *nsp;
    float4      procost;
    int         oldlen;

    initStringInfo(&buf);

    /* Look up the function */
    proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
    if (!HeapTupleIsValid(proctup))
        elog(ERROR, "cache lookup failed for function %u", funcid);
    proc = (Form_pg_proc) GETSTRUCT(proctup);
    name = NameStr(proc->proname);

    if (proc->proisagg)
        ereport(ERROR,
                (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                 errmsg("\"%s\" is an aggregate function", name)));

    /* Need its pg_language tuple for the language name */
    langtup = SearchSysCache1(LANGOID, ObjectIdGetDatum(proc->prolang));
    if (!HeapTupleIsValid(langtup))
        elog(ERROR, "cache lookup failed for language %u", proc->prolang);
    lang = (Form_pg_language) GETSTRUCT(langtup);

    /*
     * We always qualify the function name, to ensure the right function gets
     * replaced.
     */
    nsp = get_namespace_name(proc->pronamespace);
    appendStringInfo(&buf, "CREATE OR REPLACE FUNCTION %s(",
                     quote_qualified_identifier(nsp, name));
    (void) print_function_arguments(&buf, proctup, false, true);
    appendStringInfoString(&buf, ")\n RETURNS ");
    print_function_rettype(&buf, proctup);
    appendStringInfo(&buf, "\n LANGUAGE %s\n",
                     quote_identifier(NameStr(lang->lanname)));

    /* Emit some miscellaneous options on one line */
    oldlen = buf.len;

    if (proc->proiswindow)
        appendStringInfoString(&buf, " WINDOW");
    switch (proc->provolatile)
    {
        case PROVOLATILE_IMMUTABLE:
            appendStringInfoString(&buf, " IMMUTABLE");
            break;
        case PROVOLATILE_STABLE:
            appendStringInfoString(&buf, " STABLE");
            break;
        case PROVOLATILE_VOLATILE:
            break;
    }
    if (proc->proisstrict)
        appendStringInfoString(&buf, " STRICT");
    if (proc->prosecdef)
        appendStringInfoString(&buf, " SECURITY DEFINER");

    /* This code for the default cost and rows should match functioncmds.c */
    if (proc->prolang == INTERNALlanguageId ||
        proc->prolang == ClanguageId)
        procost = 1;
    else
        procost = 100;
    if (proc->procost != procost)
        appendStringInfo(&buf, " COST %g", proc->procost);

    if (proc->prorows > 0 && proc->prorows != 1000)
        appendStringInfo(&buf, " ROWS %g", proc->prorows);

    if (oldlen != buf.len)
        appendStringInfoChar(&buf, '\n');

    /* Emit any proconfig options, one per line */
    tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proconfig, &isnull);
    if (!isnull)
    {
        ArrayType  *a = DatumGetArrayTypeP(tmp);
        int         i;

        Assert(ARR_ELEMTYPE(a) == TEXTOID);
        Assert(ARR_NDIM(a) == 1);
        Assert(ARR_LBOUND(a)[0] == 1);

        for (i = 1; i <= ARR_DIMS(a)[0]; i++)
        {
            Datum       d;

            d = array_ref(a, 1, &i,
                          -1 /* varlenarray */ ,
                          -1 /* TEXT's typlen */ ,
                          false /* TEXT's typbyval */ ,
                          'i' /* TEXT's typalign */ ,
                          &isnull);
            if (!isnull)
            {
                char       *configitem = TextDatumGetCString(d);
                char       *pos;

                pos = strchr(configitem, '=');
                if (pos == NULL)
                    continue;
                *pos++ = '\0';

                appendStringInfo(&buf, " SET %s TO ",
                                 quote_identifier(configitem));

                /*
                 * Some GUC variable names are 'LIST' type and hence must not
                 * be quoted.
                 */
                if (pg_strcasecmp(configitem, "DateStyle") == 0
                    || pg_strcasecmp(configitem, "search_path") == 0)
                    appendStringInfoString(&buf, pos);
                else
                    simple_quote_literal(&buf, pos);
                appendStringInfoChar(&buf, '\n');
            }
        }
    }

    /* And finally the function definition ... */
    appendStringInfoString(&buf, "AS ");

    tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_probin, &isnull);
    if (!isnull)
    {
        simple_quote_literal(&buf, TextDatumGetCString(tmp));
        appendStringInfoString(&buf, ", ");     /* assume prosrc isn't null */
    }

    tmp = SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_prosrc, &isnull);
    if (isnull)
        elog(ERROR, "null prosrc");
    prosrc = TextDatumGetCString(tmp);

    /*
     * We always use dollar quoting.  Figure out a suitable delimiter.
     *
     * Since the user is likely to be editing the function body string, we
     * shouldn't use a short delimiter that he might easily create a conflict
     * with.  Hence prefer "$function$", but extend if needed.
     */
    initStringInfo(&dq);
    appendStringInfoString(&dq, "$function");
    while (strstr(prosrc, dq.data) != NULL)
        appendStringInfoChar(&dq, 'x');
    appendStringInfoChar(&dq, '$');

    appendStringInfoString(&buf, dq.data);
    appendStringInfoString(&buf, prosrc);
    appendStringInfoString(&buf, dq.data);

    appendStringInfoString(&buf, "\n");

    ReleaseSysCache(langtup);
    ReleaseSysCache(proctup);

    PG_RETURN_TEXT_P(string_to_text(buf.data));
}

Datum pg_get_indexdef ( PG_FUNCTION_ARGS   ) 

Definition at line 916 of file ruleutils.c.

References NULL, pg_get_indexdef_worker(), PG_GETARG_OID, PG_RETURN_TEXT_P, and string_to_text().

{
    Oid         indexrelid = PG_GETARG_OID(0);
    int         prettyFlags;

    prettyFlags = PRETTYFLAG_INDENT;
    PG_RETURN_TEXT_P(string_to_text(pg_get_indexdef_worker(indexrelid, 0,
                                                           NULL,
                                                           false, false,
                                                           prettyFlags)));
}

char* pg_get_indexdef_columns ( Oid  indexrelid,
bool  pretty 
)

Definition at line 953 of file ruleutils.c.

References NULL, pg_get_indexdef_worker(), PRETTYFLAG_INDENT, and PRETTYFLAG_PAREN.

Referenced by BuildIndexValueDescription().

{
    int         prettyFlags;

    prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : PRETTYFLAG_INDENT;
    return pg_get_indexdef_worker(indexrelid, 0, NULL, true, false, prettyFlags);
}

Datum pg_get_indexdef_ext ( PG_FUNCTION_ARGS   ) 

Definition at line 929 of file ruleutils.c.

References NULL, pg_get_indexdef_worker(), PG_GETARG_BOOL, PG_GETARG_INT32, PG_GETARG_OID, PG_RETURN_TEXT_P, PRETTYFLAG_INDENT, PRETTYFLAG_PAREN, and string_to_text().

{
    Oid         indexrelid = PG_GETARG_OID(0);
    int32       colno = PG_GETARG_INT32(1);
    bool        pretty = PG_GETARG_BOOL(2);
    int         prettyFlags;

    prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : PRETTYFLAG_INDENT;
    PG_RETURN_TEXT_P(string_to_text(pg_get_indexdef_worker(indexrelid, colno,
                                                           NULL,
                                                           colno != 0,
                                                           false,
                                                           prettyFlags)));
}

char* pg_get_indexdef_string ( Oid  indexrelid  ) 

Definition at line 946 of file ruleutils.c.

References NULL, and pg_get_indexdef_worker().

Referenced by ATExecAlterColumnType().

{
    return pg_get_indexdef_worker(indexrelid, 0, NULL, false, true, 0);
}

Datum pg_get_keywords ( PG_FUNCTION_ARGS   ) 

Definition at line 426 of file misc.c.

References _, FuncCallContext::attinmeta, BuildTupleFromCStrings(), FuncCallContext::call_cntr, ScanKeyword::category, CHAROID, COL_NAME_KEYWORD, CreateTemplateTupleDesc(), HeapTupleGetDatum, MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, ScanKeyword::name, NumScanKeywords, RESERVED_KEYWORD, ScanKeywords, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, TEXTOID, TupleDescGetAttInMetadata(), TupleDescInitEntry(), TYPE_FUNC_NAME_KEYWORD, UNRESERVED_KEYWORD, and values.

{
    FuncCallContext *funcctx;

    if (SRF_IS_FIRSTCALL())
    {
        MemoryContext oldcontext;
        TupleDesc   tupdesc;

        funcctx = SRF_FIRSTCALL_INIT();
        oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);

        tupdesc = CreateTemplateTupleDesc(3, false);
        TupleDescInitEntry(tupdesc, (AttrNumber) 1, "word",
                           TEXTOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 2, "catcode",
                           CHAROID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 3, "catdesc",
                           TEXTOID, -1, 0);

        funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);

        MemoryContextSwitchTo(oldcontext);
    }

    funcctx = SRF_PERCALL_SETUP();

    if (funcctx->call_cntr < NumScanKeywords)
    {
        char       *values[3];
        HeapTuple   tuple;

        /* cast-away-const is ugly but alternatives aren't much better */
        values[0] = (char *) ScanKeywords[funcctx->call_cntr].name;

        switch (ScanKeywords[funcctx->call_cntr].category)
        {
            case UNRESERVED_KEYWORD:
                values[1] = "U";
                values[2] = _("unreserved");
                break;
            case COL_NAME_KEYWORD:
                values[1] = "C";
                values[2] = _("unreserved (cannot be function or type name)");
                break;
            case TYPE_FUNC_NAME_KEYWORD:
                values[1] = "T";
                values[2] = _("reserved (can be function or type name)");
                break;
            case RESERVED_KEYWORD:
                values[1] = "R";
                values[2] = _("reserved");
                break;
            default:            /* shouldn't be possible */
                values[1] = NULL;
                values[2] = NULL;
                break;
        }

        tuple = BuildTupleFromCStrings(funcctx->attinmeta, values);

        SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
    }

    SRF_RETURN_DONE(funcctx);
}

Datum pg_get_multixact_members ( PG_FUNCTION_ARGS   ) 

Definition at line 2426 of file multixact.c.

References FuncCallContext::attinmeta, BuildTupleFromCStrings(), CreateTemplateTupleDesc(), ereport, errcode(), errmsg(), ERROR, FirstMultiXactId, GetMultiXactIdMembers(), HeapTupleGetDatum, MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, mxstatus_to_string(), palloc(), pfree(), PG_GETARG_UINT32, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, TEXTOID, TupleDescGetAttInMetadata(), TupleDescInitEntry(), FuncCallContext::user_fctx, values, and XIDOID.

{
    typedef struct
    {
        MultiXactMember *members;
        int             nmembers;
        int             iter;
    } mxact;
    MultiXactId     mxid = PG_GETARG_UINT32(0);
    mxact          *multi;
    FuncCallContext *funccxt;

    if (mxid < FirstMultiXactId)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("invalid MultiXactId: %u", mxid)));

    if (SRF_IS_FIRSTCALL())
    {
        MemoryContext oldcxt;
        TupleDesc   tupdesc;

        funccxt = SRF_FIRSTCALL_INIT();
        oldcxt = MemoryContextSwitchTo(funccxt->multi_call_memory_ctx);

        multi = palloc(sizeof(mxact));
        /* no need to allow for old values here */
        multi->nmembers = GetMultiXactIdMembers(mxid, &multi->members, false);
        multi->iter = 0;

        tupdesc = CreateTemplateTupleDesc(2, false);
        TupleDescInitEntry(tupdesc, (AttrNumber) 1, "xid",
                           XIDOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 2, "mode",
                           TEXTOID, -1, 0);

        funccxt->attinmeta = TupleDescGetAttInMetadata(tupdesc);
        funccxt->user_fctx = multi;

        MemoryContextSwitchTo(oldcxt);
    }

    funccxt = SRF_PERCALL_SETUP();
    multi = (mxact *) funccxt->user_fctx;

    while (multi->iter < multi->nmembers)
    {
        HeapTuple   tuple;
        char       *values[2];

        values[0] = palloc(32);
        sprintf(values[0], "%u", multi->members[multi->iter].xid);
        values[1] = mxstatus_to_string(multi->members[multi->iter].status);

        tuple = BuildTupleFromCStrings(funccxt->attinmeta, values);

        multi->iter++;
        pfree(values[0]);
        SRF_RETURN_NEXT(funccxt, HeapTupleGetDatum(tuple));
    }

    if (multi->nmembers > 0)
        pfree(multi->members);
    pfree(multi);

    SRF_RETURN_DONE(funccxt);
}

Datum pg_get_ruledef ( PG_FUNCTION_ARGS   ) 

Definition at line 416 of file ruleutils.c.

References pg_get_ruledef_worker(), PG_GETARG_OID, PG_RETURN_TEXT_P, and string_to_text().

{
    Oid         ruleoid = PG_GETARG_OID(0);
    int         prettyFlags;

    prettyFlags = PRETTYFLAG_INDENT;
    PG_RETURN_TEXT_P(string_to_text(pg_get_ruledef_worker(ruleoid, prettyFlags)));
}

Datum pg_get_ruledef_ext ( PG_FUNCTION_ARGS   ) 

Definition at line 427 of file ruleutils.c.

References pg_get_ruledef_worker(), PG_GETARG_BOOL, PG_GETARG_OID, PG_RETURN_TEXT_P, PRETTYFLAG_INDENT, PRETTYFLAG_PAREN, and string_to_text().

{
    Oid         ruleoid = PG_GETARG_OID(0);
    bool        pretty = PG_GETARG_BOOL(1);
    int         prettyFlags;

    prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : PRETTYFLAG_INDENT;
    PG_RETURN_TEXT_P(string_to_text(pg_get_ruledef_worker(ruleoid, prettyFlags)));
}

Datum pg_get_serial_sequence ( PG_FUNCTION_ARGS   ) 

Definition at line 1754 of file ruleutils.c.

References AccessShareLock, Anum_pg_depend_refclassid, Anum_pg_depend_refobjid, Anum_pg_depend_refobjsubid, BTEqualStrategyNumber, DEPENDENCY_AUTO, DependReferenceIndexId, DependRelationId, elog, ereport, errcode(), errmsg(), ERROR, get_attnum(), get_namespace_name(), get_rel_relkind(), GETSTRUCT, heap_close, heap_open(), HeapTupleIsValid, Int32GetDatum, InvalidAttrNumber, makeRangeVarFromNameList(), NameStr, NoLock, ObjectIdGetDatum, OidIsValid, PG_GETARG_TEXT_P, PG_GETARG_TEXT_PP, PG_RETURN_NULL, PG_RETURN_TEXT_P, quote_qualified_identifier(), RangeVarGetRelid, RelationRelationId, ReleaseSysCache(), RangeVar::relname, RELOID, ScanKeyInit(), SearchSysCache1, SnapshotNow, string_to_text(), systable_beginscan(), systable_endscan(), systable_getnext(), text_to_cstring(), and textToQualifiedNameList().

{
    text       *tablename = PG_GETARG_TEXT_P(0);
    text       *columnname = PG_GETARG_TEXT_PP(1);
    RangeVar   *tablerv;
    Oid         tableOid;
    char       *column;
    AttrNumber  attnum;
    Oid         sequenceId = InvalidOid;
    Relation    depRel;
    ScanKeyData key[3];
    SysScanDesc scan;
    HeapTuple   tup;

    /* Look up table name.  Can't lock it - we might not have privileges. */
    tablerv = makeRangeVarFromNameList(textToQualifiedNameList(tablename));
    tableOid = RangeVarGetRelid(tablerv, NoLock, false);

    /* Get the number of the column */
    column = text_to_cstring(columnname);

    attnum = get_attnum(tableOid, column);
    if (attnum == InvalidAttrNumber)
        ereport(ERROR,
                (errcode(ERRCODE_UNDEFINED_COLUMN),
                 errmsg("column \"%s\" of relation \"%s\" does not exist",
                        column, tablerv->relname)));

    /* Search the dependency table for the dependent sequence */
    depRel = heap_open(DependRelationId, AccessShareLock);

    ScanKeyInit(&key[0],
                Anum_pg_depend_refclassid,
                BTEqualStrategyNumber, F_OIDEQ,
                ObjectIdGetDatum(RelationRelationId));
    ScanKeyInit(&key[1],
                Anum_pg_depend_refobjid,
                BTEqualStrategyNumber, F_OIDEQ,
                ObjectIdGetDatum(tableOid));
    ScanKeyInit(&key[2],
                Anum_pg_depend_refobjsubid,
                BTEqualStrategyNumber, F_INT4EQ,
                Int32GetDatum(attnum));

    scan = systable_beginscan(depRel, DependReferenceIndexId, true,
                              SnapshotNow, 3, key);

    while (HeapTupleIsValid(tup = systable_getnext(scan)))
    {
        Form_pg_depend deprec = (Form_pg_depend) GETSTRUCT(tup);

        /*
         * We assume any auto dependency of a sequence on a column must be
         * what we are looking for.  (We need the relkind test because indexes
         * can also have auto dependencies on columns.)
         */
        if (deprec->classid == RelationRelationId &&
            deprec->objsubid == 0 &&
            deprec->deptype == DEPENDENCY_AUTO &&
            get_rel_relkind(deprec->objid) == RELKIND_SEQUENCE)
        {
            sequenceId = deprec->objid;
            break;
        }
    }

    systable_endscan(scan);
    heap_close(depRel, AccessShareLock);

    if (OidIsValid(sequenceId))
    {
        HeapTuple   classtup;
        Form_pg_class classtuple;
        char       *nspname;
        char       *result;

        /* Get the sequence's pg_class entry */
        classtup = SearchSysCache1(RELOID, ObjectIdGetDatum(sequenceId));
        if (!HeapTupleIsValid(classtup))
            elog(ERROR, "cache lookup failed for relation %u", sequenceId);
        classtuple = (Form_pg_class) GETSTRUCT(classtup);

        /* Get the namespace */
        nspname = get_namespace_name(classtuple->relnamespace);
        if (!nspname)
            elog(ERROR, "cache lookup failed for namespace %u",
                 classtuple->relnamespace);

        /* And construct the result string */
        result = quote_qualified_identifier(nspname,
                                            NameStr(classtuple->relname));

        ReleaseSysCache(classtup);

        PG_RETURN_TEXT_P(string_to_text(result));
    }

    PG_RETURN_NULL();
}

Datum pg_get_triggerdef ( PG_FUNCTION_ARGS   ) 
Datum pg_get_triggerdef_ext ( PG_FUNCTION_ARGS   ) 
Datum pg_get_userbyid ( PG_FUNCTION_ARGS   ) 

Definition at line 1716 of file ruleutils.c.

References AUTHOID, GETSTRUCT, HeapTupleIsValid, NAMEDATALEN, NameStr, ObjectIdGetDatum, palloc(), PG_GETARG_OID, PG_RETURN_NAME, ReleaseSysCache(), SearchSysCache1, and StrNCpy.

{
    Oid         roleid = PG_GETARG_OID(0);
    Name        result;
    HeapTuple   roletup;
    Form_pg_authid role_rec;

    /*
     * Allocate space for the result
     */
    result = (Name) palloc(NAMEDATALEN);
    memset(NameStr(*result), 0, NAMEDATALEN);

    /*
     * Get the pg_authid entry and print the result
     */
    roletup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
    if (HeapTupleIsValid(roletup))
    {
        role_rec = (Form_pg_authid) GETSTRUCT(roletup);
        StrNCpy(NameStr(*result), NameStr(role_rec->rolname), NAMEDATALEN);
        ReleaseSysCache(roletup);
    }
    else
        sprintf(NameStr(*result), "unknown (OID=%u)", roleid);

    PG_RETURN_NAME(result);
}

Datum pg_get_viewdef ( PG_FUNCTION_ARGS   ) 

Definition at line 513 of file ruleutils.c.

References pg_get_viewdef_worker(), PG_GETARG_OID, PG_RETURN_TEXT_P, string_to_text(), and WRAP_COLUMN_DEFAULT.

{
    /* By OID */
    Oid         viewoid = PG_GETARG_OID(0);
    int         prettyFlags;

    prettyFlags = PRETTYFLAG_INDENT;
    PG_RETURN_TEXT_P(string_to_text(pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT)));
}

Datum pg_get_viewdef_ext ( PG_FUNCTION_ARGS   ) 

Definition at line 525 of file ruleutils.c.

References pg_get_viewdef_worker(), PG_GETARG_BOOL, PG_GETARG_OID, PG_RETURN_TEXT_P, PRETTYFLAG_INDENT, PRETTYFLAG_PAREN, string_to_text(), and WRAP_COLUMN_DEFAULT.

{
    /* By OID */
    Oid         viewoid = PG_GETARG_OID(0);
    bool        pretty = PG_GETARG_BOOL(1);
    int         prettyFlags;

    prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : PRETTYFLAG_INDENT;
    PG_RETURN_TEXT_P(string_to_text(pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT)));
}

Datum pg_get_viewdef_name ( PG_FUNCTION_ARGS   ) 

Definition at line 550 of file ruleutils.c.

References makeRangeVarFromNameList(), NoLock, pg_get_viewdef_worker(), PG_GETARG_TEXT_P, PG_RETURN_TEXT_P, RangeVarGetRelid, string_to_text(), textToQualifiedNameList(), and WRAP_COLUMN_DEFAULT.

{
    /* By qualified name */
    text       *viewname = PG_GETARG_TEXT_P(0);
    int         prettyFlags;
    RangeVar   *viewrel;
    Oid         viewoid;

    prettyFlags = PRETTYFLAG_INDENT;

    /* Look up view name.  Can't lock it - we might not have privileges. */
    viewrel = makeRangeVarFromNameList(textToQualifiedNameList(viewname));
    viewoid = RangeVarGetRelid(viewrel, NoLock, false);

    PG_RETURN_TEXT_P(string_to_text(pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT)));
}

Datum pg_get_viewdef_name_ext ( PG_FUNCTION_ARGS   ) 

Definition at line 569 of file ruleutils.c.

References makeRangeVarFromNameList(), NoLock, pg_get_viewdef_worker(), PG_GETARG_BOOL, PG_GETARG_TEXT_P, PG_RETURN_TEXT_P, PRETTYFLAG_INDENT, PRETTYFLAG_PAREN, RangeVarGetRelid, string_to_text(), textToQualifiedNameList(), and WRAP_COLUMN_DEFAULT.

{
    /* By qualified name */
    text       *viewname = PG_GETARG_TEXT_P(0);
    bool        pretty = PG_GETARG_BOOL(1);
    int         prettyFlags;
    RangeVar   *viewrel;
    Oid         viewoid;

    prettyFlags = pretty ? PRETTYFLAG_PAREN | PRETTYFLAG_INDENT : PRETTYFLAG_INDENT;

    /* Look up view name.  Can't lock it - we might not have privileges. */
    viewrel = makeRangeVarFromNameList(textToQualifiedNameList(viewname));
    viewoid = RangeVarGetRelid(viewrel, NoLock, false);

    PG_RETURN_TEXT_P(string_to_text(pg_get_viewdef_worker(viewoid, prettyFlags, WRAP_COLUMN_DEFAULT)));
}

Datum pg_get_viewdef_wrap ( PG_FUNCTION_ARGS   ) 

Definition at line 537 of file ruleutils.c.

References pg_get_viewdef_worker(), PG_GETARG_INT32, PG_GETARG_OID, PG_RETURN_TEXT_P, PRETTYFLAG_PAREN, and string_to_text().

{
    /* By OID */
    Oid         viewoid = PG_GETARG_OID(0);
    int         wrap = PG_GETARG_INT32(1);
    int         prettyFlags;

    /* calling this implies we want pretty printing */
    prettyFlags = PRETTYFLAG_PAREN | PRETTYFLAG_INDENT;
    PG_RETURN_TEXT_P(string_to_text(pg_get_viewdef_worker(viewoid, prettyFlags, wrap)));
}

Datum pg_has_role_id ( PG_FUNCTION_ARGS   ) 

Definition at line 4486 of file acl.c.

References ACLCHECK_OK, convert_role_priv_string(), GetUserId(), PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, and pg_role_aclcheck().

{
    Oid         roleoid = PG_GETARG_OID(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    mode = convert_role_priv_string(priv_type_text);

    aclresult = pg_role_aclcheck(roleoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum pg_has_role_id_id ( PG_FUNCTION_ARGS   ) 

Definition at line 4531 of file acl.c.

References ACLCHECK_OK, convert_role_priv_string(), PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, and pg_role_aclcheck().

{
    Oid         roleid = PG_GETARG_OID(0);
    Oid         roleoid = PG_GETARG_OID(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    AclMode     mode;
    AclResult   aclresult;

    mode = convert_role_priv_string(priv_type_text);

    aclresult = pg_role_aclcheck(roleoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum pg_has_role_id_name ( PG_FUNCTION_ARGS   ) 

Definition at line 4508 of file acl.c.

References ACLCHECK_OK, convert_role_priv_string(), get_role_oid(), NameStr, PG_GETARG_NAME, PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, and pg_role_aclcheck().

{
    Oid         roleid = PG_GETARG_OID(0);
    Name        rolename = PG_GETARG_NAME(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleoid;
    AclMode     mode;
    AclResult   aclresult;

    roleoid = get_role_oid(NameStr(*rolename), false);
    mode = convert_role_priv_string(priv_type_text);

    aclresult = pg_role_aclcheck(roleoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum pg_has_role_name ( PG_FUNCTION_ARGS   ) 

Definition at line 4438 of file acl.c.

References ACLCHECK_OK, convert_role_priv_string(), get_role_oid(), GetUserId(), NameStr, PG_GETARG_NAME, PG_GETARG_TEXT_P, PG_RETURN_BOOL, and pg_role_aclcheck().

{
    Name        rolename = PG_GETARG_NAME(0);
    text       *priv_type_text = PG_GETARG_TEXT_P(1);
    Oid         roleid;
    Oid         roleoid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = GetUserId();
    roleoid = get_role_oid(NameStr(*rolename), false);
    mode = convert_role_priv_string(priv_type_text);

    aclresult = pg_role_aclcheck(roleoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum pg_has_role_name_id ( PG_FUNCTION_ARGS   ) 

Definition at line 4462 of file acl.c.

References ACLCHECK_OK, convert_role_priv_string(), get_role_oid(), NameStr, PG_GETARG_NAME, PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_BOOL, pg_role_aclcheck(), and username.

{
    Name        username = PG_GETARG_NAME(0);
    Oid         roleoid = PG_GETARG_OID(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = get_role_oid(NameStr(*username), false);
    mode = convert_role_priv_string(priv_type_text);

    aclresult = pg_role_aclcheck(roleoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum pg_has_role_name_name ( PG_FUNCTION_ARGS   ) 

Definition at line 4412 of file acl.c.

References ACLCHECK_OK, convert_role_priv_string(), get_role_oid(), NameStr, PG_GETARG_NAME, PG_GETARG_TEXT_P, PG_RETURN_BOOL, pg_role_aclcheck(), and username.

{
    Name        username = PG_GETARG_NAME(0);
    Name        rolename = PG_GETARG_NAME(1);
    text       *priv_type_text = PG_GETARG_TEXT_P(2);
    Oid         roleid;
    Oid         roleoid;
    AclMode     mode;
    AclResult   aclresult;

    roleid = get_role_oid(NameStr(*username), false);
    roleoid = get_role_oid(NameStr(*rolename), false);
    mode = convert_role_priv_string(priv_type_text);

    aclresult = pg_role_aclcheck(roleoid, roleid, mode);

    PG_RETURN_BOOL(aclresult == ACLCHECK_OK);
}

Datum pg_identify_object ( PG_FUNCTION_ARGS   ) 

Definition at line 2306 of file objectaddress.c.

References AccessShareLock, BlessTupleDesc(), ObjectAddress::classId, CreateTemplateTupleDesc(), CStringGetTextDatum, DatumGetName, elog, ERROR, get_catalog_object_by_oid(), get_namespace_name(), get_object_attnum_name(), get_object_attnum_namespace(), get_object_namensp_unique(), getObjectIdentity(), getObjectTypeDescription(), heap_close, heap_form_tuple(), heap_getattr, heap_open(), HeapTupleGetDatum, InvalidAttrNumber, is_objectclass_supported(), NameStr, NULL, ObjectAddress::objectId, ObjectAddress::objectSubId, OidIsValid, PG_GETARG_INT32, PG_GETARG_OID, PG_RETURN_DATUM, quote_identifier(), RelationGetDescr, TEXTOID, TupleDescInitEntry(), and values.

{
    Oid         classid = PG_GETARG_OID(0);
    Oid         objid = PG_GETARG_OID(1);
    int32       subobjid = PG_GETARG_INT32(2);
    Oid         schema_oid = InvalidOid;
    const char *objname = NULL;
    ObjectAddress address;
    Datum       values[4];
    bool        nulls[4];
    TupleDesc   tupdesc;
    HeapTuple   htup;

    address.classId = classid;
    address.objectId = objid;
    address.objectSubId = subobjid;

    /*
     * Construct a tuple descriptor for the result row.  This must match this
     * function's pg_proc entry!
     */
    tupdesc = CreateTemplateTupleDesc(4, false);
    TupleDescInitEntry(tupdesc, (AttrNumber) 1, "type",
                       TEXTOID, -1, 0);
    TupleDescInitEntry(tupdesc, (AttrNumber) 2, "schema",
                       TEXTOID, -1, 0);
    TupleDescInitEntry(tupdesc, (AttrNumber) 3, "name",
                       TEXTOID, -1, 0);
    TupleDescInitEntry(tupdesc, (AttrNumber) 4, "identity",
                       TEXTOID, -1, 0);

    tupdesc = BlessTupleDesc(tupdesc);

    if (is_objectclass_supported(address.classId))
    {
        HeapTuple   objtup;
        Relation    catalog = heap_open(address.classId, AccessShareLock);

        objtup = get_catalog_object_by_oid(catalog, address.objectId);
        if (objtup != NULL)
        {
            bool        isnull;
            AttrNumber  nspAttnum;
            AttrNumber  nameAttnum;

            nspAttnum = get_object_attnum_namespace(address.classId);
            if (nspAttnum != InvalidAttrNumber)
            {
                schema_oid = heap_getattr(objtup, nspAttnum,
                                          RelationGetDescr(catalog), &isnull);
                if (isnull)
                    elog(ERROR, "invalid null namespace in object %u/%u/%d",
                         address.classId, address.objectId, address.objectSubId);
            }

            /*
             * We only return the object name if it can be used (together
             * with the schema name, if any) as an unique identifier.
             */
            if (get_object_namensp_unique(address.classId))
            {
                nameAttnum = get_object_attnum_name(address.classId);
                if (nameAttnum != InvalidAttrNumber)
                {
                    Datum   nameDatum;

                    nameDatum = heap_getattr(objtup, nameAttnum,
                                             RelationGetDescr(catalog), &isnull);
                    if (isnull)
                        elog(ERROR, "invalid null name in object %u/%u/%d",
                             address.classId, address.objectId, address.objectSubId);
                    objname = quote_identifier(NameStr(*(DatumGetName(nameDatum))));
                }
            }
        }

        heap_close(catalog, AccessShareLock);
    }

    /* object type */
    values[0] = CStringGetTextDatum(getObjectTypeDescription(&address));
    nulls[0] = false;

    /* schema name */
    if (OidIsValid(schema_oid))
    {
        const char  *schema = quote_identifier(get_namespace_name(schema_oid));

        values[1] = CStringGetTextDatum(schema);
        nulls[1] = false;
    }
    else
        nulls[1] = true;

    /* object name */
    if (objname)
    {
        values[2] = CStringGetTextDatum(objname);
        nulls[2] = false;
    }
    else
        nulls[2] = true;

    /* object identity */
    values[3] = CStringGetTextDatum(getObjectIdentity(&address));
    nulls[3] = false;

    htup = heap_form_tuple(tupdesc, values, nulls);

    PG_RETURN_DATUM(HeapTupleGetDatum(htup));
}

Datum pg_indexes_size ( PG_FUNCTION_ARGS   ) 
void pg_itoa ( int16  i,
char *  a 
)

Definition at line 118 of file numutils.c.

References pg_ltoa().

Referenced by int2out(), and int2vectorout().

{
    pg_ltoa((int32) i, a);
}

void pg_lltoa ( int64  ll,
char *  a 
)

Definition at line 184 of file numutils.c.

References INT64CONST, and swap.

Referenced by int8out().

{
    char       *start = a;
    bool        neg = false;

    /*
     * Avoid problems with the most negative integer not being representable
     * as a positive integer.
     */
    if (value == (-INT64CONST(0x7FFFFFFFFFFFFFFF) - 1))
    {
        memcpy(a, "-9223372036854775808", 21);
        return;
    }
    else if (value < 0)
    {
        value = -value;
        neg = true;
    }

    /* Compute the result string backwards. */
    do
    {
        int64       remainder;
        int64       oldval = value;

        value /= 10;
        remainder = oldval - value * 10;
        *a++ = '0' + remainder;
    } while (value != 0);

    if (neg)
        *a++ = '-';

    /* Add trailing NUL byte, and back up 'a' to the last character. */
    *a-- = '\0';

    /* Reverse string. */
    while (start < a)
    {
        char        swap = *start;

        *start++ = *a;
        *a-- = swap;
    }
}

Datum pg_lock_status ( PG_FUNCTION_ARGS   ) 

Definition at line 79 of file lockfuncs.c.

References LockInstanceData::backend, VirtualTransactionId::backendId, BlessTupleDesc(), BoolGetDatum, BOOLOID, CreateTemplateTupleDesc(), CStringGetTextDatum, PG_Lock_Status::currIdx, LockInstanceData::fastpath, GET_PREDICATELOCKTARGETTAG_DB, GET_PREDICATELOCKTARGETTAG_OFFSET, GET_PREDICATELOCKTARGETTAG_PAGE, GET_PREDICATELOCKTARGETTAG_RELATION, GET_PREDICATELOCKTARGETTAG_TYPE, GetLockmodeName(), GetLockStatusData(), GetPredicateLockStatusData(), heap_form_tuple(), HeapTupleGetDatum, LockInstanceData::holdMask, Int16GetDatum, INT2OID, Int32GetDatum, INT4OID, VirtualTransactionId::localTransactionId, LOCKBIT_OFF, LOCKBIT_ON, PG_Lock_Status::lockData, LockData::locks, LockInstanceData::locktag, LOCKTAG_ADVISORY, LOCKTAG::locktag_field1, LOCKTAG::locktag_field2, LOCKTAG::locktag_field3, LOCKTAG::locktag_field4, LOCKTAG_LAST_TYPE, LOCKTAG::locktag_lockmethodid, LOCKTAG_OBJECT, LOCKTAG_PAGE, LOCKTAG_RELATION, LOCKTAG_RELATION_EXTEND, LOCKTAG_TRANSACTION, LOCKTAG_TUPLE, LOCKTAG::locktag_type, LOCKTAG_USERLOCK, LOCKTAG_VIRTUALTRANSACTION, PredicateLockData::locktags, LockTagTypeNames, LockInstanceData::lxid, MemoryContextSwitchTo(), MemSet, FuncCallContext::multi_call_memory_ctx, PredicateLockData::nelements, LockData::nelements, NoLock, NUM_LOCK_STATUS_COLUMNS, ObjectIdGetDatum, OIDOID, palloc(), SERIALIZABLEXACT::pid, LockInstanceData::pid, PredicateLockTagTypeNames, PG_Lock_Status::predLockData, PG_Lock_Status::predLockIdx, PREDLOCKTAG_PAGE, PREDLOCKTAG_TUPLE, snprintf(), SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, TEXTOID, TransactionIdGetDatum, FuncCallContext::tuple_desc, TupleDescInitEntry(), UInt16GetDatum, UInt32GetDatum, FuncCallContext::user_fctx, values, SERIALIZABLEXACT::vxid, VXIDGetDatum(), LockInstanceData::waitLockMode, PredicateLockData::xacts, and XIDOID.

{
    FuncCallContext *funcctx;
    PG_Lock_Status *mystatus;
    LockData   *lockData;
    PredicateLockData *predLockData;

    if (SRF_IS_FIRSTCALL())
    {
        TupleDesc   tupdesc;
        MemoryContext oldcontext;

        /* create a function context for cross-call persistence */
        funcctx = SRF_FIRSTCALL_INIT();

        /*
         * switch to memory context appropriate for multiple function calls
         */
        oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);

        /* build tupdesc for result tuples */
        /* this had better match pg_locks view in system_views.sql */
        tupdesc = CreateTemplateTupleDesc(NUM_LOCK_STATUS_COLUMNS, false);
        TupleDescInitEntry(tupdesc, (AttrNumber) 1, "locktype",
                           TEXTOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 2, "database",
                           OIDOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 3, "relation",
                           OIDOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 4, "page",
                           INT4OID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 5, "tuple",
                           INT2OID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 6, "virtualxid",
                           TEXTOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 7, "transactionid",
                           XIDOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 8, "classid",
                           OIDOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 9, "objid",
                           OIDOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 10, "objsubid",
                           INT2OID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 11, "virtualtransaction",
                           TEXTOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 12, "pid",
                           INT4OID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 13, "mode",
                           TEXTOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 14, "granted",
                           BOOLOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 15, "fastpath",
                           BOOLOID, -1, 0);

        funcctx->tuple_desc = BlessTupleDesc(tupdesc);

        /*
         * Collect all the locking information that we will format and send
         * out as a result set.
         */
        mystatus = (PG_Lock_Status *) palloc(sizeof(PG_Lock_Status));
        funcctx->user_fctx = (void *) mystatus;

        mystatus->lockData = GetLockStatusData();
        mystatus->currIdx = 0;
        mystatus->predLockData = GetPredicateLockStatusData();
        mystatus->predLockIdx = 0;

        MemoryContextSwitchTo(oldcontext);
    }

    funcctx = SRF_PERCALL_SETUP();
    mystatus = (PG_Lock_Status *) funcctx->user_fctx;
    lockData = mystatus->lockData;

    while (mystatus->currIdx < lockData->nelements)
    {
        bool        granted;
        LOCKMODE    mode = 0;
        const char *locktypename;
        char        tnbuf[32];
        Datum       values[NUM_LOCK_STATUS_COLUMNS];
        bool        nulls[NUM_LOCK_STATUS_COLUMNS];
        HeapTuple   tuple;
        Datum       result;
        LockInstanceData *instance;

        instance = &(lockData->locks[mystatus->currIdx]);

        /*
         * Look to see if there are any held lock modes in this PROCLOCK. If
         * so, report, and destructively modify lockData so we don't report
         * again.
         */
        granted = false;
        if (instance->holdMask)
        {
            for (mode = 0; mode < MAX_LOCKMODES; mode++)
            {
                if (instance->holdMask & LOCKBIT_ON(mode))
                {
                    granted = true;
                    instance->holdMask &= LOCKBIT_OFF(mode);
                    break;
                }
            }
        }

        /*
         * If no (more) held modes to report, see if PROC is waiting for a
         * lock on this lock.
         */
        if (!granted)
        {
            if (instance->waitLockMode != NoLock)
            {
                /* Yes, so report it with proper mode */
                mode = instance->waitLockMode;

                /*
                 * We are now done with this PROCLOCK, so advance pointer to
                 * continue with next one on next call.
                 */
                mystatus->currIdx++;
            }
            else
            {
                /*
                 * Okay, we've displayed all the locks associated with this
                 * PROCLOCK, proceed to the next one.
                 */
                mystatus->currIdx++;
                continue;
            }
        }

        /*
         * Form tuple with appropriate data.
         */
        MemSet(values, 0, sizeof(values));
        MemSet(nulls, false, sizeof(nulls));

        if (instance->locktag.locktag_type <= LOCKTAG_LAST_TYPE)
            locktypename = LockTagTypeNames[instance->locktag.locktag_type];
        else
        {
            snprintf(tnbuf, sizeof(tnbuf), "unknown %d",
                     (int) instance->locktag.locktag_type);
            locktypename = tnbuf;
        }
        values[0] = CStringGetTextDatum(locktypename);

        switch ((LockTagType) instance->locktag.locktag_type)
        {
            case LOCKTAG_RELATION:
            case LOCKTAG_RELATION_EXTEND:
                values[1] = ObjectIdGetDatum(instance->locktag.locktag_field1);
                values[2] = ObjectIdGetDatum(instance->locktag.locktag_field2);
                nulls[3] = true;
                nulls[4] = true;
                nulls[5] = true;
                nulls[6] = true;
                nulls[7] = true;
                nulls[8] = true;
                nulls[9] = true;
                break;
            case LOCKTAG_PAGE:
                values[1] = ObjectIdGetDatum(instance->locktag.locktag_field1);
                values[2] = ObjectIdGetDatum(instance->locktag.locktag_field2);
                values[3] = UInt32GetDatum(instance->locktag.locktag_field3);
                nulls[4] = true;
                nulls[5] = true;
                nulls[6] = true;
                nulls[7] = true;
                nulls[8] = true;
                nulls[9] = true;
                break;
            case LOCKTAG_TUPLE:
                values[1] = ObjectIdGetDatum(instance->locktag.locktag_field1);
                values[2] = ObjectIdGetDatum(instance->locktag.locktag_field2);
                values[3] = UInt32GetDatum(instance->locktag.locktag_field3);
                values[4] = UInt16GetDatum(instance->locktag.locktag_field4);
                nulls[5] = true;
                nulls[6] = true;
                nulls[7] = true;
                nulls[8] = true;
                nulls[9] = true;
                break;
            case LOCKTAG_TRANSACTION:
                values[6] =
                    TransactionIdGetDatum(instance->locktag.locktag_field1);
                nulls[1] = true;
                nulls[2] = true;
                nulls[3] = true;
                nulls[4] = true;
                nulls[5] = true;
                nulls[7] = true;
                nulls[8] = true;
                nulls[9] = true;
                break;
            case LOCKTAG_VIRTUALTRANSACTION:
                values[5] = VXIDGetDatum(instance->locktag.locktag_field1,
                                         instance->locktag.locktag_field2);
                nulls[1] = true;
                nulls[2] = true;
                nulls[3] = true;
                nulls[4] = true;
                nulls[6] = true;
                nulls[7] = true;
                nulls[8] = true;
                nulls[9] = true;
                break;
            case LOCKTAG_OBJECT:
            case LOCKTAG_USERLOCK:
            case LOCKTAG_ADVISORY:
            default:            /* treat unknown locktags like OBJECT */
                values[1] = ObjectIdGetDatum(instance->locktag.locktag_field1);
                values[7] = ObjectIdGetDatum(instance->locktag.locktag_field2);
                values[8] = ObjectIdGetDatum(instance->locktag.locktag_field3);
                values[9] = Int16GetDatum(instance->locktag.locktag_field4);
                nulls[2] = true;
                nulls[3] = true;
                nulls[4] = true;
                nulls[5] = true;
                nulls[6] = true;
                break;
        }

        values[10] = VXIDGetDatum(instance->backend, instance->lxid);
        if (instance->pid != 0)
            values[11] = Int32GetDatum(instance->pid);
        else
            nulls[11] = true;
        values[12] = CStringGetTextDatum(GetLockmodeName(instance->locktag.locktag_lockmethodid, mode));
        values[13] = BoolGetDatum(granted);
        values[14] = BoolGetDatum(instance->fastpath);

        tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
        result = HeapTupleGetDatum(tuple);
        SRF_RETURN_NEXT(funcctx, result);
    }

    /*
     * Have returned all regular locks. Now start on the SIREAD predicate
     * locks.
     */
    predLockData = mystatus->predLockData;
    if (mystatus->predLockIdx < predLockData->nelements)
    {
        PredicateLockTargetType lockType;

        PREDICATELOCKTARGETTAG *predTag = &(predLockData->locktags[mystatus->predLockIdx]);
        SERIALIZABLEXACT *xact = &(predLockData->xacts[mystatus->predLockIdx]);
        Datum       values[NUM_LOCK_STATUS_COLUMNS];
        bool        nulls[NUM_LOCK_STATUS_COLUMNS];
        HeapTuple   tuple;
        Datum       result;

        mystatus->predLockIdx++;

        /*
         * Form tuple with appropriate data.
         */
        MemSet(values, 0, sizeof(values));
        MemSet(nulls, false, sizeof(nulls));

        /* lock type */
        lockType = GET_PREDICATELOCKTARGETTAG_TYPE(*predTag);

        values[0] = CStringGetTextDatum(PredicateLockTagTypeNames[lockType]);

        /* lock target */
        values[1] = GET_PREDICATELOCKTARGETTAG_DB(*predTag);
        values[2] = GET_PREDICATELOCKTARGETTAG_RELATION(*predTag);
        if (lockType == PREDLOCKTAG_TUPLE)
            values[4] = GET_PREDICATELOCKTARGETTAG_OFFSET(*predTag);
        else
            nulls[4] = true;
        if ((lockType == PREDLOCKTAG_TUPLE) ||
            (lockType == PREDLOCKTAG_PAGE))
            values[3] = GET_PREDICATELOCKTARGETTAG_PAGE(*predTag);
        else
            nulls[3] = true;

        /* these fields are targets for other types of locks */
        nulls[5] = true;        /* virtualxid */
        nulls[6] = true;        /* transactionid */
        nulls[7] = true;        /* classid */
        nulls[8] = true;        /* objid */
        nulls[9] = true;        /* objsubid */

        /* lock holder */
        values[10] = VXIDGetDatum(xact->vxid.backendId,
                                  xact->vxid.localTransactionId);
        if (xact->pid != 0)
            values[11] = Int32GetDatum(xact->pid);
        else
            nulls[11] = true;

        /*
         * Lock mode. Currently all predicate locks are SIReadLocks, which are
         * always held (never waiting) and have no fast path
         */
        values[12] = CStringGetTextDatum("SIReadLock");
        values[13] = BoolGetDatum(true);
        values[14] = BoolGetDatum(false);

        tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
        result = HeapTupleGetDatum(tuple);
        SRF_RETURN_NEXT(funcctx, result);
    }

    SRF_RETURN_DONE(funcctx);
}

Datum pg_ls_dir ( PG_FUNCTION_ARGS   ) 

Definition at line 328 of file genfile.c.

References AllocateDir(), convert_and_check_filename(), CStringGetTextDatum, dirent::d_name, directory_fctx::dirdesc, ereport, errcode(), errcode_for_file_access(), errmsg(), ERROR, FreeDir(), directory_fctx::location, MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, palloc(), PG_GETARG_TEXT_P, ReadDir(), SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, superuser(), and FuncCallContext::user_fctx.

{
    FuncCallContext *funcctx;
    struct dirent *de;
    directory_fctx *fctx;

    if (!superuser())
        ereport(ERROR,
                (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                 (errmsg("must be superuser to get directory listings"))));

    if (SRF_IS_FIRSTCALL())
    {
        MemoryContext oldcontext;

        funcctx = SRF_FIRSTCALL_INIT();
        oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);

        fctx = palloc(sizeof(directory_fctx));
        fctx->location = convert_and_check_filename(PG_GETARG_TEXT_P(0));

        fctx->dirdesc = AllocateDir(fctx->location);

        if (!fctx->dirdesc)
            ereport(ERROR,
                    (errcode_for_file_access(),
                     errmsg("could not open directory \"%s\": %m",
                            fctx->location)));

        funcctx->user_fctx = fctx;
        MemoryContextSwitchTo(oldcontext);
    }

    funcctx = SRF_PERCALL_SETUP();
    fctx = (directory_fctx *) funcctx->user_fctx;

    while ((de = ReadDir(fctx->dirdesc, fctx->location)) != NULL)
    {
        if (strcmp(de->d_name, ".") == 0 ||
            strcmp(de->d_name, "..") == 0)
            continue;

        SRF_RETURN_NEXT(funcctx, CStringGetTextDatum(de->d_name));
    }

    FreeDir(fctx->dirdesc);

    SRF_RETURN_DONE(funcctx);
}

void pg_ltoa ( int32  l,
char *  a 
)

Definition at line 130 of file numutils.c.

References swap.

Referenced by int44out(), int4out(), and pg_itoa().

{
    char       *start = a;
    bool        neg = false;

    /*
     * Avoid problems with the most negative integer not being representable
     * as a positive integer.
     */
    if (value == (-2147483647 - 1))
    {
        memcpy(a, "-2147483648", 12);
        return;
    }
    else if (value < 0)
    {
        value = -value;
        neg = true;
    }

    /* Compute the result string backwards. */
    do
    {
        int32       remainder;
        int32       oldval = value;

        value /= 10;
        remainder = oldval - value * 10;
        *a++ = '0' + remainder;
    } while (value != 0);

    if (neg)
        *a++ = '-';

    /* Add trailing NUL byte, and back up 'a' to the last character. */
    *a-- = '\0';

    /* Reverse string. */
    while (start < a)
    {
        char        swap = *start;

        *start++ = *a;
        *a-- = swap;
    }
}

Datum pg_node_tree_in ( PG_FUNCTION_ARGS   ) 

Definition at line 517 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    /*
     * We disallow input of pg_node_tree values because the SQL functions that
     * operate on the type are not secure against malformed input.
     */
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot accept a value of type pg_node_tree")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum pg_node_tree_out ( PG_FUNCTION_ARGS   ) 

Definition at line 536 of file pseudotypes.c.

References textout().

{
    return textout(fcinfo);
}

Datum pg_node_tree_recv ( PG_FUNCTION_ARGS   ) 

Definition at line 545 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot accept a value of type pg_node_tree")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum pg_node_tree_send ( PG_FUNCTION_ARGS   ) 

Definition at line 558 of file pseudotypes.c.

References textsend().

{
    return textsend(fcinfo);
}

Datum pg_prepared_statement ( PG_FUNCTION_ARGS   ) 

Definition at line 690 of file prepare.c.

References ReturnSetInfo::allowedModes, BoolGetDatum, BOOLOID, build_regtype_array(), CreateTemplateTupleDesc(), CStringGetTextDatum, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, ereport, errcode(), errmsg(), ERROR, PreparedStatement::from_sql, hash_seq_init(), hash_seq_search(), IsA, MemoryContextSwitchTo(), MemSet, NULL, CachedPlanSource::num_params, CachedPlanSource::param_types, PreparedStatement::plansource, PreparedStatement::prepare_time, CachedPlanSource::query_string, REGTYPEARRAYOID, ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, SFRM_Materialize_Random, PreparedStatement::stmt_name, TEXTOID, TimestampTzGetDatum, TIMESTAMPTZOID, TupleDescInitEntry(), tuplestore_begin_heap(), tuplestore_donestoring, tuplestore_putvalues(), values, and work_mem.

{
    ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
    TupleDesc   tupdesc;
    Tuplestorestate *tupstore;
    MemoryContext per_query_ctx;
    MemoryContext oldcontext;

    /* check to see if caller supports us returning a tuplestore */
    if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("set-valued function called in context that cannot accept a set")));
    if (!(rsinfo->allowedModes & SFRM_Materialize))
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                 errmsg("materialize mode required, but it is not " \
                        "allowed in this context")));

    /* need to build tuplestore in query context */
    per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
    oldcontext = MemoryContextSwitchTo(per_query_ctx);

    /*
     * build tupdesc for result tuples. This must match the definition of the
     * pg_prepared_statements view in system_views.sql
     */
    tupdesc = CreateTemplateTupleDesc(5, false);
    TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
                       TEXTOID, -1, 0);
    TupleDescInitEntry(tupdesc, (AttrNumber) 2, "statement",
                       TEXTOID, -1, 0);
    TupleDescInitEntry(tupdesc, (AttrNumber) 3, "prepare_time",
                       TIMESTAMPTZOID, -1, 0);
    TupleDescInitEntry(tupdesc, (AttrNumber) 4, "parameter_types",
                       REGTYPEARRAYOID, -1, 0);
    TupleDescInitEntry(tupdesc, (AttrNumber) 5, "from_sql",
                       BOOLOID, -1, 0);

    /*
     * We put all the tuples into a tuplestore in one scan of the hashtable.
     * This avoids any issue of the hashtable possibly changing between calls.
     */
    tupstore =
        tuplestore_begin_heap(rsinfo->allowedModes & SFRM_Materialize_Random,
                              false, work_mem);

    /* generate junk in short-term context */
    MemoryContextSwitchTo(oldcontext);

    /* hash table might be uninitialized */
    if (prepared_queries)
    {
        HASH_SEQ_STATUS hash_seq;
        PreparedStatement *prep_stmt;

        hash_seq_init(&hash_seq, prepared_queries);
        while ((prep_stmt = hash_seq_search(&hash_seq)) != NULL)
        {
            Datum       values[5];
            bool        nulls[5];

            MemSet(nulls, 0, sizeof(nulls));

            values[0] = CStringGetTextDatum(prep_stmt->stmt_name);
            values[1] = CStringGetTextDatum(prep_stmt->plansource->query_string);
            values[2] = TimestampTzGetDatum(prep_stmt->prepare_time);
            values[3] = build_regtype_array(prep_stmt->plansource->param_types,
                                          prep_stmt->plansource->num_params);
            values[4] = BoolGetDatum(prep_stmt->from_sql);

            tuplestore_putvalues(tupstore, tupdesc, values, nulls);
        }
    }

    /* clean up and return the tuplestore */
    tuplestore_donestoring(tupstore);

    rsinfo->returnMode = SFRM_Materialize;
    rsinfo->setResult = tupstore;
    rsinfo->setDesc = tupdesc;

    return (Datum) 0;
}

Datum pg_prepared_xact ( PG_FUNCTION_ARGS   ) 

Definition at line 602 of file twophase.c.

References PROC_HDR::allPgXact, PROC_HDR::allProcs, Working_State::array, BlessTupleDesc(), CreateTemplateTupleDesc(), CStringGetTextDatum, Working_State::currIdx, PGPROC::databaseId, GetPreparedTransactionList(), GlobalTransactionData::gid, heap_form_tuple(), HeapTupleGetDatum, MemoryContextSwitchTo(), MemSet, FuncCallContext::multi_call_memory_ctx, Working_State::ngxacts, NULL, ObjectIdGetDatum, OIDOID, GlobalTransactionData::owner, palloc(), GlobalTransactionData::pgprocno, GlobalTransactionData::prepared_at, ProcGlobal, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, TEXTOID, TimestampTzGetDatum, TIMESTAMPTZOID, TransactionIdGetDatum, FuncCallContext::tuple_desc, TupleDescInitEntry(), FuncCallContext::user_fctx, GlobalTransactionData::valid, values, PGXACT::xid, and XIDOID.

{
    FuncCallContext *funcctx;
    Working_State *status;

    if (SRF_IS_FIRSTCALL())
    {
        TupleDesc   tupdesc;
        MemoryContext oldcontext;

        /* create a function context for cross-call persistence */
        funcctx = SRF_FIRSTCALL_INIT();

        /*
         * Switch to memory context appropriate for multiple function calls
         */
        oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);

        /* build tupdesc for result tuples */
        /* this had better match pg_prepared_xacts view in system_views.sql */
        tupdesc = CreateTemplateTupleDesc(5, false);
        TupleDescInitEntry(tupdesc, (AttrNumber) 1, "transaction",
                           XIDOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 2, "gid",
                           TEXTOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 3, "prepared",
                           TIMESTAMPTZOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 4, "ownerid",
                           OIDOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 5, "dbid",
                           OIDOID, -1, 0);

        funcctx->tuple_desc = BlessTupleDesc(tupdesc);

        /*
         * Collect all the 2PC status information that we will format and send
         * out as a result set.
         */
        status = (Working_State *) palloc(sizeof(Working_State));
        funcctx->user_fctx = (void *) status;

        status->ngxacts = GetPreparedTransactionList(&status->array);
        status->currIdx = 0;

        MemoryContextSwitchTo(oldcontext);
    }

    funcctx = SRF_PERCALL_SETUP();
    status = (Working_State *) funcctx->user_fctx;

    while (status->array != NULL && status->currIdx < status->ngxacts)
    {
        GlobalTransaction gxact = &status->array[status->currIdx++];
        PGPROC     *proc = &ProcGlobal->allProcs[gxact->pgprocno];
        PGXACT     *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
        Datum       values[5];
        bool        nulls[5];
        HeapTuple   tuple;
        Datum       result;

        if (!gxact->valid)
            continue;

        /*
         * Form tuple with appropriate data.
         */
        MemSet(values, 0, sizeof(values));
        MemSet(nulls, 0, sizeof(nulls));

        values[0] = TransactionIdGetDatum(pgxact->xid);
        values[1] = CStringGetTextDatum(gxact->gid);
        values[2] = TimestampTzGetDatum(gxact->prepared_at);
        values[3] = ObjectIdGetDatum(gxact->owner);
        values[4] = ObjectIdGetDatum(proc->databaseId);

        tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
        result = HeapTupleGetDatum(tuple);
        SRF_RETURN_NEXT(funcctx, result);
    }

    SRF_RETURN_DONE(funcctx);
}

Datum pg_read_binary_file ( PG_FUNCTION_ARGS   ) 

Definition at line 215 of file genfile.c.

References convert_and_check_filename(), ereport, errcode(), errmsg(), ERROR, filename, PG_GETARG_INT64, PG_GETARG_TEXT_P, PG_RETURN_BYTEA_P, read_binary_file(), and superuser().

{
    text       *filename_t = PG_GETARG_TEXT_P(0);
    int64       seek_offset = PG_GETARG_INT64(1);
    int64       bytes_to_read = PG_GETARG_INT64(2);
    char       *filename;

    if (!superuser())
        ereport(ERROR,
                (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                 (errmsg("must be superuser to read files"))));

    filename = convert_and_check_filename(filename_t);

    if (bytes_to_read < 0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("requested length cannot be negative")));

    PG_RETURN_BYTEA_P(read_binary_file(filename, seek_offset, bytes_to_read));
}

Datum pg_read_binary_file_all ( PG_FUNCTION_ARGS   ) 

Definition at line 241 of file genfile.c.

References convert_and_check_filename(), ereport, errcode(), errmsg(), ERROR, filename, PG_GETARG_TEXT_P, PG_RETURN_BYTEA_P, read_binary_file(), and superuser().

{
    text       *filename_t = PG_GETARG_TEXT_P(0);
    char       *filename;

    if (!superuser())
        ereport(ERROR,
                (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                 (errmsg("must be superuser to read files"))));

    filename = convert_and_check_filename(filename_t);

    PG_RETURN_BYTEA_P(read_binary_file(filename, 0, -1));
}

Datum pg_read_file ( PG_FUNCTION_ARGS   ) 

Definition at line 170 of file genfile.c.

References convert_and_check_filename(), ereport, errcode(), errmsg(), ERROR, filename, PG_GETARG_INT64, PG_GETARG_TEXT_P, PG_RETURN_TEXT_P, read_text_file(), and superuser().

{
    text       *filename_t = PG_GETARG_TEXT_P(0);
    int64       seek_offset = PG_GETARG_INT64(1);
    int64       bytes_to_read = PG_GETARG_INT64(2);
    char       *filename;

    if (!superuser())
        ereport(ERROR,
                (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                 (errmsg("must be superuser to read files"))));

    filename = convert_and_check_filename(filename_t);

    if (bytes_to_read < 0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("requested length cannot be negative")));

    PG_RETURN_TEXT_P(read_text_file(filename, seek_offset, bytes_to_read));
}

Datum pg_read_file_all ( PG_FUNCTION_ARGS   ) 

Definition at line 196 of file genfile.c.

References convert_and_check_filename(), ereport, errcode(), errmsg(), ERROR, filename, PG_GETARG_TEXT_P, PG_RETURN_TEXT_P, read_text_file(), and superuser().

{
    text       *filename_t = PG_GETARG_TEXT_P(0);
    char       *filename;

    if (!superuser())
        ereport(ERROR,
                (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                 (errmsg("must be superuser to read files"))));

    filename = convert_and_check_filename(filename_t);

    PG_RETURN_TEXT_P(read_text_file(filename, 0, -1));
}

Datum pg_relation_filenode ( PG_FUNCTION_ARGS   ) 

Definition at line 707 of file dbsize.c.

References GETSTRUCT, HeapTupleIsValid, ObjectIdGetDatum, OidIsValid, PG_GETARG_OID, PG_RETURN_NULL, PG_RETURN_OID, RelationMapOidToFilenode(), ReleaseSysCache(), RELKIND_INDEX, RELKIND_MATVIEW, RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_TOASTVALUE, RELOID, and SearchSysCache1.

{
    Oid         relid = PG_GETARG_OID(0);
    Oid         result;
    HeapTuple   tuple;
    Form_pg_class relform;

    tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
    if (!HeapTupleIsValid(tuple))
        PG_RETURN_NULL();
    relform = (Form_pg_class) GETSTRUCT(tuple);

    switch (relform->relkind)
    {
        case RELKIND_RELATION:
        case RELKIND_MATVIEW:
        case RELKIND_INDEX:
        case RELKIND_SEQUENCE:
        case RELKIND_TOASTVALUE:
            /* okay, these have storage */
            if (relform->relfilenode)
                result = relform->relfilenode;
            else    /* Consult the relation mapper */
                result = RelationMapOidToFilenode(relid,
                                                  relform->relisshared);
            break;

        default:
            /* no storage, return NULL */
            result = InvalidOid;
            break;
    }

    ReleaseSysCache(tuple);

    if (!OidIsValid(result))
        PG_RETURN_NULL();

    PG_RETURN_OID(result);
}

Datum pg_relation_filepath ( PG_FUNCTION_ARGS   ) 

Definition at line 754 of file dbsize.c.

References Assert, cstring_to_text(), RelFileNode::dbNode, elog, ERROR, GETSTRUCT, GetTempNamespaceBackendId(), GLOBALTABLESPACE_OID, HeapTupleIsValid, InvalidBackendId, isTempOrToastNamespace(), MAIN_FORKNUM, MyBackendId, MyDatabaseId, MyDatabaseTableSpace, ObjectIdGetDatum, OidIsValid, PG_GETARG_OID, PG_RETURN_NULL, PG_RETURN_TEXT_P, RelationMapOidToFilenode(), ReleaseSysCache(), RELKIND_INDEX, RELKIND_MATVIEW, RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_TOASTVALUE, RelFileNode::relNode, RELOID, relpathbackend(), RELPERSISTENCE_PERMANENT, RELPERSISTENCE_TEMP, RELPERSISTENCE_UNLOGGED, SearchSysCache1, and RelFileNode::spcNode.

{
    Oid         relid = PG_GETARG_OID(0);
    HeapTuple   tuple;
    Form_pg_class relform;
    RelFileNode rnode;
    BackendId   backend;
    char       *path;

    tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
    if (!HeapTupleIsValid(tuple))
        PG_RETURN_NULL();
    relform = (Form_pg_class) GETSTRUCT(tuple);

    switch (relform->relkind)
    {
        case RELKIND_RELATION:
        case RELKIND_MATVIEW:
        case RELKIND_INDEX:
        case RELKIND_SEQUENCE:
        case RELKIND_TOASTVALUE:
            /* okay, these have storage */

            /* This logic should match RelationInitPhysicalAddr */
            if (relform->reltablespace)
                rnode.spcNode = relform->reltablespace;
            else
                rnode.spcNode = MyDatabaseTableSpace;
            if (rnode.spcNode == GLOBALTABLESPACE_OID)
                rnode.dbNode = InvalidOid;
            else
                rnode.dbNode = MyDatabaseId;
            if (relform->relfilenode)
                rnode.relNode = relform->relfilenode;
            else    /* Consult the relation mapper */
                rnode.relNode = RelationMapOidToFilenode(relid,
                                                       relform->relisshared);
            break;

        default:
            /* no storage, return NULL */
            rnode.relNode = InvalidOid;
            /* some compilers generate warnings without these next two lines */
            rnode.dbNode = InvalidOid;
            rnode.spcNode = InvalidOid;
            break;
    }

    if (!OidIsValid(rnode.relNode))
    {
        ReleaseSysCache(tuple);
        PG_RETURN_NULL();
    }

    /* Determine owning backend. */
    switch (relform->relpersistence)
    {
        case RELPERSISTENCE_UNLOGGED:
        case RELPERSISTENCE_PERMANENT:
            backend = InvalidBackendId;
            break;
        case RELPERSISTENCE_TEMP:
            if (isTempOrToastNamespace(relform->relnamespace))
                backend = MyBackendId;
            else
            {
                /* Do it the hard way. */
                backend = GetTempNamespaceBackendId(relform->relnamespace);
                Assert(backend != InvalidBackendId);
            }
            break;
        default:
            elog(ERROR, "invalid relpersistence: %c", relform->relpersistence);
            backend = InvalidBackendId; /* placate compiler */
            break;
    }

    ReleaseSysCache(tuple);

    path = relpathbackend(rnode, backend, MAIN_FORKNUM);

    PG_RETURN_TEXT_P(cstring_to_text(path));
}

Datum pg_relation_is_scannable ( PG_FUNCTION_ARGS   ) 

Definition at line 847 of file dbsize.c.

References AccessShareLock, NULL, PG_GETARG_OID, PG_RETURN_BOOL, relation_close(), RelationIsScannable, and try_relation_open().

{
    Oid         relid;
    Relation    relation;
    bool        result;

    relid = PG_GETARG_OID(0);
    relation = try_relation_open(relid, AccessShareLock);

    if (relation == NULL)
        PG_RETURN_BOOL(false);

    result = RelationIsScannable(relation);

    relation_close(relation, AccessShareLock);
    PG_RETURN_BOOL(result);
}

Datum pg_relation_size ( PG_FUNCTION_ARGS   ) 

Definition at line 307 of file dbsize.c.

References AccessShareLock, calculate_relation_size(), forkname_to_number(), NULL, PG_GETARG_OID, PG_GETARG_TEXT_P, PG_RETURN_INT64, PG_RETURN_NULL, RelationData::rd_backend, RelationData::rd_node, relation_close(), text_to_cstring(), and try_relation_open().

{
    Oid         relOid = PG_GETARG_OID(0);
    text       *forkName = PG_GETARG_TEXT_P(1);
    Relation    rel;
    int64       size;

    rel = try_relation_open(relOid, AccessShareLock);

    /*
     * Before 9.2, we used to throw an error if the relation didn't exist, but
     * that makes queries like "SELECT pg_relation_size(oid) FROM pg_class"
     * less robust, because while we scan pg_class with an MVCC snapshot,
     * someone else might drop the table. It's better to return NULL for
     * already-dropped tables than throw an error and abort the whole query.
     */
    if (rel == NULL)
        PG_RETURN_NULL();

    size = calculate_relation_size(&(rel->rd_node), rel->rd_backend,
                              forkname_to_number(text_to_cstring(forkName)));

    relation_close(rel, AccessShareLock);

    PG_RETURN_INT64(size);
}

Datum pg_reload_conf ( PG_FUNCTION_ARGS   ) 

Definition at line 180 of file misc.c.

References ereport, errcode(), errmsg(), ERROR, PG_RETURN_BOOL, PostmasterPid, SIGHUP, superuser(), and WARNING.

{
    if (!superuser())
        ereport(ERROR,
                (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                 (errmsg("must be superuser to signal the postmaster"))));

    if (kill(PostmasterPid, SIGHUP))
    {
        ereport(WARNING,
                (errmsg("failed to send signal to postmaster: %m")));
        PG_RETURN_BOOL(false);
    }

    PG_RETURN_BOOL(true);
}

Datum pg_rotate_logfile ( PG_FUNCTION_ARGS   ) 

Definition at line 202 of file misc.c.

References ereport, errcode(), errmsg(), ERROR, Logging_collector, PG_RETURN_BOOL, PMSIGNAL_ROTATE_LOGFILE, SendPostmasterSignal(), superuser(), and WARNING.

{
    if (!superuser())
        ereport(ERROR,
                (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                 (errmsg("must be superuser to rotate log files"))));

    if (!Logging_collector)
    {
        ereport(WARNING,
        (errmsg("rotation not possible because log collection not active")));
        PG_RETURN_BOOL(false);
    }

    SendPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE);
    PG_RETURN_BOOL(true);
}

Datum pg_size_pretty ( PG_FUNCTION_ARGS   ) 

Definition at line 519 of file dbsize.c.

References buf, cstring_to_text(), PG_GETARG_INT64, PG_RETURN_TEXT_P, and snprintf().

{
    int64       size = PG_GETARG_INT64(0);
    char        buf[64];
    int64       limit = 10 * 1024;
    int64       limit2 = limit * 2 - 1;

    if (size < limit)
        snprintf(buf, sizeof(buf), INT64_FORMAT " bytes", size);
    else
    {
        size >>= 9;             /* keep one extra bit for rounding */
        if (size < limit2)
            snprintf(buf, sizeof(buf), INT64_FORMAT " kB",
                     (size + 1) / 2);
        else
        {
            size >>= 10;
            if (size < limit2)
                snprintf(buf, sizeof(buf), INT64_FORMAT " MB",
                         (size + 1) / 2);
            else
            {
                size >>= 10;
                if (size < limit2)
                    snprintf(buf, sizeof(buf), INT64_FORMAT " GB",
                             (size + 1) / 2);
                else
                {
                    size >>= 10;
                    snprintf(buf, sizeof(buf), INT64_FORMAT " TB",
                             (size + 1) / 2);
                }
            }
        }
    }

    PG_RETURN_TEXT_P(cstring_to_text(buf));
}

Datum pg_size_pretty_numeric ( PG_FUNCTION_ARGS   ) 

Definition at line 614 of file dbsize.c.

References buf, cstring_to_text(), int64_to_numeric(), numeric_is_less(), numeric_plus_one_over_two(), numeric_shift_right(), numeric_to_cstring(), palloc(), PG_GETARG_NUMERIC, and PG_RETURN_TEXT_P.

{
    Numeric     size = PG_GETARG_NUMERIC(0);
    Numeric     limit,
                limit2;
    char       *buf,
               *result;

    limit = int64_to_numeric(10 * 1024);
    limit2 = int64_to_numeric(10 * 1024 * 2 - 1);

    if (numeric_is_less(size, limit))
    {
        buf = numeric_to_cstring(size);
        result = palloc(strlen(buf) + 7);
        strcpy(result, buf);
        strcat(result, " bytes");
    }
    else
    {
        /* keep one extra bit for rounding */
        /* size >>= 9 */
        size = numeric_shift_right(size, 9);

        if (numeric_is_less(size, limit2))
        {
            /* size = (size + 1) / 2 */
            size = numeric_plus_one_over_two(size);
            buf = numeric_to_cstring(size);
            result = palloc(strlen(buf) + 4);
            strcpy(result, buf);
            strcat(result, " kB");
        }
        else
        {
            /* size >>= 10 */
            size = numeric_shift_right(size, 10);
            if (numeric_is_less(size, limit2))
            {
                /* size = (size + 1) / 2 */
                size = numeric_plus_one_over_two(size);
                buf = numeric_to_cstring(size);
                result = palloc(strlen(buf) + 4);
                strcpy(result, buf);
                strcat(result, " MB");
            }
            else
            {
                /* size >>= 10 */
                size = numeric_shift_right(size, 10);

                if (numeric_is_less(size, limit2))
                {
                    /* size = (size + 1) / 2 */
                    size = numeric_plus_one_over_two(size);
                    buf = numeric_to_cstring(size);
                    result = palloc(strlen(buf) + 4);
                    strcpy(result, buf);
                    strcat(result, " GB");
                }
                else
                {
                    /* size >>= 10 */
                    size = numeric_shift_right(size, 10);
                    /* size = (size + 1) / 2 */
                    size = numeric_plus_one_over_two(size);
                    buf = numeric_to_cstring(size);
                    result = palloc(strlen(buf) + 4);
                    strcpy(result, buf);
                    strcat(result, " TB");
                }
            }
        }
    }

    PG_RETURN_TEXT_P(cstring_to_text(result));
}

Datum pg_sleep ( PG_FUNCTION_ARGS   ) 

Definition at line 381 of file misc.c.

References CHECK_FOR_INTERRUPTS, GetNowFloat, PG_GETARG_FLOAT8, PG_RETURN_VOID, and pg_usleep().

{
    float8      secs = PG_GETARG_FLOAT8(0);
    float8      endtime;

    /*
     * We break the requested sleep into segments of no more than 1 second, to
     * put an upper bound on how long it will take us to respond to a cancel
     * or die interrupt.  (Note that pg_usleep is interruptible by signals on
     * some platforms but not others.)  Also, this method avoids exposing
     * pg_usleep's upper bound on allowed delays.
     *
     * By computing the intended stop time initially, we avoid accumulation of
     * extra delay across multiple sleeps.  This also ensures we won't delay
     * less than the specified time if pg_usleep is interrupted by other
     * signals such as SIGHUP.
     */

#ifdef HAVE_INT64_TIMESTAMP
#define GetNowFloat()   ((float8) GetCurrentTimestamp() / 1000000.0)
#else
#define GetNowFloat()   GetCurrentTimestamp()
#endif

    endtime = GetNowFloat() + secs;

    for (;;)
    {
        float8      delay;

        CHECK_FOR_INTERRUPTS();
        delay = endtime - GetNowFloat();
        if (delay >= 1.0)
            pg_usleep(1000000L);
        else if (delay > 0.0)
            pg_usleep((long) ceil(delay * 1000000.0));
        else
            break;
    }

    PG_RETURN_VOID();
}

Datum pg_stat_file ( PG_FUNCTION_ARGS   ) 

Definition at line 260 of file genfile.c.

References BlessTupleDesc(), BoolGetDatum, BOOLOID, convert_and_check_filename(), CreateTemplateTupleDesc(), ereport, errcode(), errcode_for_file_access(), errmsg(), ERROR, filename, heap_form_tuple(), HeapTupleGetDatum, Int64GetDatum(), INT8OID, pfree(), PG_GETARG_TEXT_P, PG_RETURN_DATUM, superuser(), time_t_to_timestamptz(), TimestampTzGetDatum, TIMESTAMPTZOID, TupleDescInitEntry(), and values.

{
    text       *filename_t = PG_GETARG_TEXT_P(0);
    char       *filename;
    struct stat fst;
    Datum       values[6];
    bool        isnull[6];
    HeapTuple   tuple;
    TupleDesc   tupdesc;

    if (!superuser())
        ereport(ERROR,
                (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                 (errmsg("must be superuser to get file information"))));

    filename = convert_and_check_filename(filename_t);

    if (stat(filename, &fst) < 0)
        ereport(ERROR,
                (errcode_for_file_access(),
                 errmsg("could not stat file \"%s\": %m", filename)));

    /*
     * This record type had better match the output parameters declared for me
     * in pg_proc.h.
     */
    tupdesc = CreateTemplateTupleDesc(6, false);
    TupleDescInitEntry(tupdesc, (AttrNumber) 1,
                       "size", INT8OID, -1, 0);
    TupleDescInitEntry(tupdesc, (AttrNumber) 2,
                       "access", TIMESTAMPTZOID, -1, 0);
    TupleDescInitEntry(tupdesc, (AttrNumber) 3,
                       "modification", TIMESTAMPTZOID, -1, 0);
    TupleDescInitEntry(tupdesc, (AttrNumber) 4,
                       "change", TIMESTAMPTZOID, -1, 0);
    TupleDescInitEntry(tupdesc, (AttrNumber) 5,
                       "creation", TIMESTAMPTZOID, -1, 0);
    TupleDescInitEntry(tupdesc, (AttrNumber) 6,
                       "isdir", BOOLOID, -1, 0);
    BlessTupleDesc(tupdesc);

    memset(isnull, false, sizeof(isnull));

    values[0] = Int64GetDatum((int64) fst.st_size);
    values[1] = TimestampTzGetDatum(time_t_to_timestamptz(fst.st_atime));
    values[2] = TimestampTzGetDatum(time_t_to_timestamptz(fst.st_mtime));
    /* Unix has file status change time, while Win32 has creation time */
#if !defined(WIN32) && !defined(__CYGWIN__)
    values[3] = TimestampTzGetDatum(time_t_to_timestamptz(fst.st_ctime));
    isnull[4] = true;
#else
    isnull[3] = true;
    values[4] = TimestampTzGetDatum(time_t_to_timestamptz(fst.st_ctime));
#endif
    values[5] = BoolGetDatum(S_ISDIR(fst.st_mode));

    tuple = heap_form_tuple(tupdesc, values, isnull);

    pfree(filename);

    PG_RETURN_DATUM(HeapTupleGetDatum(tuple));
}

Datum pg_table_size ( PG_FUNCTION_ARGS   ) 
Datum pg_tablespace_databases ( PG_FUNCTION_ARGS   ) 

Definition at line 229 of file misc.c.

References AllocateDir(), atooid, dirent::d_name, DEFAULTTABLESPACE_OID, ts_db_fctx::dirdesc, ereport, errcode_for_file_access(), errmsg(), ERROR, FreeDir(), GLOBALTABLESPACE_OID, ts_db_fctx::location, MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, NULL, ObjectIdGetDatum, OIDCHARS, palloc(), pfree(), PG_GETARG_OID, ReadDir(), SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, TABLESPACE_VERSION_DIRECTORY, FuncCallContext::user_fctx, and WARNING.

{
    FuncCallContext *funcctx;
    struct dirent *de;
    ts_db_fctx *fctx;

    if (SRF_IS_FIRSTCALL())
    {
        MemoryContext oldcontext;
        Oid         tablespaceOid = PG_GETARG_OID(0);

        funcctx = SRF_FIRSTCALL_INIT();
        oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);

        fctx = palloc(sizeof(ts_db_fctx));

        /*
         * size = tablespace dirname length + dir sep char + oid + terminator
         */
        fctx->location = (char *) palloc(9 + 1 + OIDCHARS + 1 +
                                   strlen(TABLESPACE_VERSION_DIRECTORY) + 1);
        if (tablespaceOid == GLOBALTABLESPACE_OID)
        {
            fctx->dirdesc = NULL;
            ereport(WARNING,
                    (errmsg("global tablespace never has databases")));
        }
        else
        {
            if (tablespaceOid == DEFAULTTABLESPACE_OID)
                sprintf(fctx->location, "base");
            else
                sprintf(fctx->location, "pg_tblspc/%u/%s", tablespaceOid,
                        TABLESPACE_VERSION_DIRECTORY);

            fctx->dirdesc = AllocateDir(fctx->location);

            if (!fctx->dirdesc)
            {
                /* the only expected error is ENOENT */
                if (errno != ENOENT)
                    ereport(ERROR,
                            (errcode_for_file_access(),
                             errmsg("could not open directory \"%s\": %m",
                                    fctx->location)));
                ereport(WARNING,
                      (errmsg("%u is not a tablespace OID", tablespaceOid)));
            }
        }
        funcctx->user_fctx = fctx;
        MemoryContextSwitchTo(oldcontext);
    }

    funcctx = SRF_PERCALL_SETUP();
    fctx = (ts_db_fctx *) funcctx->user_fctx;

    if (!fctx->dirdesc)         /* not a tablespace */
        SRF_RETURN_DONE(funcctx);

    while ((de = ReadDir(fctx->dirdesc, fctx->location)) != NULL)
    {
        char       *subdir;
        DIR        *dirdesc;
        Oid         datOid = atooid(de->d_name);

        /* this test skips . and .., but is awfully weak */
        if (!datOid)
            continue;

        /* if database subdir is empty, don't report tablespace as used */

        /* size = path length + dir sep char + file name + terminator */
        subdir = palloc(strlen(fctx->location) + 1 + strlen(de->d_name) + 1);
        sprintf(subdir, "%s/%s", fctx->location, de->d_name);
        dirdesc = AllocateDir(subdir);
        while ((de = ReadDir(dirdesc, subdir)) != NULL)
        {
            if (strcmp(de->d_name, ".") != 0 && strcmp(de->d_name, "..") != 0)
                break;
        }
        FreeDir(dirdesc);
        pfree(subdir);

        if (!de)
            continue;           /* indeed, nothing in it */

        SRF_RETURN_NEXT(funcctx, ObjectIdGetDatum(datOid));
    }

    FreeDir(fctx->dirdesc);
    SRF_RETURN_DONE(funcctx);
}

Datum pg_tablespace_location ( PG_FUNCTION_ARGS   ) 

Definition at line 327 of file misc.c.

References cstring_to_text(), DEFAULTTABLESPACE_OID, ereport, errcode(), errmsg(), ERROR, GLOBALTABLESPACE_OID, InvalidOid, MyDatabaseTableSpace, PG_GETARG_OID, PG_RETURN_NULL, PG_RETURN_TEXT_P, and snprintf().

{
    Oid         tablespaceOid = PG_GETARG_OID(0);
    char        sourcepath[MAXPGPATH];
    char        targetpath[MAXPGPATH];
    int         rllen;

    /*
     * It's useful to apply this function to pg_class.reltablespace, wherein
     * zero means "the database's default tablespace".  So, rather than
     * throwing an error for zero, we choose to assume that's what is meant.
     */
    if (tablespaceOid == InvalidOid)
        tablespaceOid = MyDatabaseTableSpace;

    /*
     * Return empty string for the cluster's default tablespaces
     */
    if (tablespaceOid == DEFAULTTABLESPACE_OID ||
        tablespaceOid == GLOBALTABLESPACE_OID)
        PG_RETURN_TEXT_P(cstring_to_text(""));

#if defined(HAVE_READLINK) || defined(WIN32)

    /*
     * Find the location of the tablespace by reading the symbolic link that
     * is in pg_tblspc/<oid>.
     */
    snprintf(sourcepath, sizeof(sourcepath), "pg_tblspc/%u", tablespaceOid);

    rllen = readlink(sourcepath, targetpath, sizeof(targetpath));
    if (rllen < 0)
        ereport(ERROR,
                (errmsg("could not read symbolic link \"%s\": %m",
                        sourcepath)));
    else if (rllen >= sizeof(targetpath))
        ereport(ERROR,
                (errmsg("symbolic link \"%s\" target is too long",
                        sourcepath)));
    targetpath[rllen] = '\0';

    PG_RETURN_TEXT_P(cstring_to_text(targetpath));
#else
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("tablespaces are not supported on this platform")));
    PG_RETURN_NULL();
#endif
}

Datum pg_tablespace_size_name ( PG_FUNCTION_ARGS   ) 

Definition at line 247 of file dbsize.c.

References calculate_tablespace_size(), get_tablespace_oid(), NameStr, PG_GETARG_NAME, PG_RETURN_INT64, and PG_RETURN_NULL.

{
    Name        tblspcName = PG_GETARG_NAME(0);
    Oid         tblspcOid = get_tablespace_oid(NameStr(*tblspcName), false);
    int64       size;

    size = calculate_tablespace_size(tblspcOid);

    if (size < 0)
        PG_RETURN_NULL();

    PG_RETURN_INT64(size);
}

Datum pg_tablespace_size_oid ( PG_FUNCTION_ARGS   ) 

Definition at line 233 of file dbsize.c.

References calculate_tablespace_size(), PG_GETARG_OID, PG_RETURN_INT64, and PG_RETURN_NULL.

{
    Oid         tblspcOid = PG_GETARG_OID(0);
    int64       size;

    size = calculate_tablespace_size(tblspcOid);

    if (size < 0)
        PG_RETURN_NULL();

    PG_RETURN_INT64(size);
}

Datum pg_terminate_backend ( PG_FUNCTION_ARGS   ) 

Definition at line 164 of file misc.c.

References ereport, errcode(), errmsg(), ERROR, PG_GETARG_INT32, PG_RETURN_BOOL, pg_signal_backend(), SIGNAL_BACKEND_NOPERMISSION, and SIGNAL_BACKEND_SUCCESS.

{
    int         r = pg_signal_backend(PG_GETARG_INT32(0), SIGTERM);

    if (r == SIGNAL_BACKEND_NOPERMISSION)
        ereport(ERROR,
                (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                 (errmsg("must be superuser or have the same role to terminate other server processes"))));

    PG_RETURN_BOOL(r == SIGNAL_BACKEND_SUCCESS);
}

Datum pg_total_relation_size ( PG_FUNCTION_ARGS   ) 
Datum pg_try_advisory_lock_int4 ( PG_FUNCTION_ARGS   ) 
Datum pg_try_advisory_lock_int8 ( PG_FUNCTION_ARGS   ) 
Datum pg_try_advisory_lock_shared_int4 ( PG_FUNCTION_ARGS   ) 
Datum pg_try_advisory_lock_shared_int8 ( PG_FUNCTION_ARGS   ) 
Datum pg_try_advisory_xact_lock_int4 ( PG_FUNCTION_ARGS   ) 
Datum pg_try_advisory_xact_lock_int8 ( PG_FUNCTION_ARGS   ) 
Datum pg_try_advisory_xact_lock_shared_int4 ( PG_FUNCTION_ARGS   ) 
Datum pg_try_advisory_xact_lock_shared_int8 ( PG_FUNCTION_ARGS   ) 

Definition at line 545 of file lockfuncs.c.

References LockAcquire(), LOCKACQUIRE_NOT_AVAIL, PG_GETARG_INT64, PG_RETURN_BOOL, SET_LOCKTAG_INT64, and ShareLock.

{
    int64       key = PG_GETARG_INT64(0);
    LOCKTAG     tag;
    LockAcquireResult res;

    SET_LOCKTAG_INT64(tag, key);

    res = LockAcquire(&tag, ShareLock, false, true);

    PG_RETURN_BOOL(res != LOCKACQUIRE_NOT_AVAIL);
}

Datum pg_typeof ( PG_FUNCTION_ARGS   ) 

Definition at line 498 of file misc.c.

References get_fn_expr_argtype(), and PG_RETURN_OID.

{
    PG_RETURN_OID(get_fn_expr_argtype(fcinfo->flinfo, 0));
}

Datum pg_view_is_insertable ( PG_FUNCTION_ARGS   ) 

Definition at line 542 of file misc.c.

References PG_GETARG_OID, PG_RETURN_BOOL, and relation_is_updatable().

{
    Oid         viewoid = PG_GETARG_OID(0);
    int         req_events = (1 << CMD_INSERT);

    PG_RETURN_BOOL(relation_is_updatable(viewoid, req_events));
}

Datum pg_view_is_updatable ( PG_FUNCTION_ARGS   ) 

Definition at line 551 of file misc.c.

References CMD_DELETE, PG_GETARG_OID, PG_RETURN_BOOL, and relation_is_updatable().

{
    Oid         viewoid = PG_GETARG_OID(0);
    int         req_events = (1 << CMD_UPDATE) | (1 << CMD_DELETE);

    PG_RETURN_BOOL(relation_is_updatable(viewoid, req_events));
}

Datum pgsql_version ( PG_FUNCTION_ARGS   ) 

Definition at line 21 of file version.c.

References cstring_to_text(), and PG_RETURN_TEXT_P.

{
    PG_RETURN_TEXT_P(cstring_to_text(PG_VERSION_STR));
}

Datum quote_ident ( PG_FUNCTION_ARGS   ) 

Definition at line 24 of file quote.c.

References cstring_to_text(), PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, quote_identifier(), and text_to_cstring().

Referenced by quote_ident_cstr().

{
    text       *t = PG_GETARG_TEXT_PP(0);
    const char *qstr;
    char       *str;

    str = text_to_cstring(t);
    qstr = quote_identifier(str);
    PG_RETURN_TEXT_P(cstring_to_text(qstr));
}

const char* quote_identifier ( const char *  ident  ) 

Definition at line 163 of file util.c.

References ScanKeyword::category, NULL, NumScanKeywords, palloc(), pg_malloc(), quote_all_identifiers, ScanKeywordLookup(), ScanKeywords, and UNRESERVED_KEYWORD.

{
    char       *result = pg_malloc(strlen(s) * 2 + 3);
    char       *r = result;

    *r++ = '"';
    while (*s)
    {
        if (*s == '"')
            *r++ = *s;
        *r++ = *s;
        s++;
    }
    *r++ = '"';
    *r++ = '\0';

    return result;
}

Datum quote_literal ( PG_FUNCTION_ARGS   ) 

Definition at line 77 of file quote.c.

References palloc(), PG_GETARG_TEXT_P, PG_RETURN_TEXT_P, quote_literal_internal(), SET_VARSIZE, VARDATA, VARHDRSZ, and VARSIZE.

Referenced by quote_nullable().

{
    text       *t = PG_GETARG_TEXT_P(0);
    text       *result;
    char       *cp1;
    char       *cp2;
    int         len;

    len = VARSIZE(t) - VARHDRSZ;
    /* We make a worst-case result area; wasting a little space is OK */
    result = (text *) palloc(len * 2 + 3 + VARHDRSZ);

    cp1 = VARDATA(t);
    cp2 = VARDATA(result);

    SET_VARSIZE(result, VARHDRSZ + quote_literal_internal(cp2, cp1, len));

    PG_RETURN_TEXT_P(result);
}

char* quote_literal_cstr ( const char *  rawstr  ) 

Definition at line 102 of file quote.c.

References palloc(), and quote_literal_internal().

Referenced by build_tuplestore_recursively(), get_sql_delete(), get_sql_insert(), get_sql_update(), get_tuple_of_interest(), PLy_quote_literal(), PLy_quote_nullable(), and text_format_string_conversion().

{
    char       *result;
    int         len;
    int         newlen;

    len = strlen(rawstr);
    /* We make a worst-case result area; wasting a little space is OK */
    result = palloc(len * 2 + 3);

    newlen = quote_literal_internal(result, rawstr, len);
    result[newlen] = '\0';

    return result;
}

Datum quote_nullable ( PG_FUNCTION_ARGS   ) 
char* quote_qualified_identifier ( const char *  qualifier,
const char *  ident 
)
Datum radians ( PG_FUNCTION_ARGS   ) 

Definition at line 1723 of file float.c.

References CHECKFLOATVAL, isinf(), M_PI, PG_GETARG_FLOAT8, and PG_RETURN_FLOAT8.

{
    float8      arg1 = PG_GETARG_FLOAT8(0);
    float8      result;

    result = arg1 * (M_PI / 180.0);

    CHECKFLOATVAL(result, isinf(arg1), arg1 == 0);
    PG_RETURN_FLOAT8(result);
}

bytea* read_binary_file ( const char *  filename,
int64  seek_offset,
int64  bytes_to_read 
)

Definition at line 91 of file genfile.c.

References AllocateFile(), buf, ereport, errcode(), errcode_for_file_access(), errmsg(), ERROR, FreeFile(), fseeko, MaxAllocSize, NULL, palloc(), PG_BINARY_R, SET_VARSIZE, VARDATA, and VARHDRSZ.

Referenced by pg_read_binary_file(), pg_read_binary_file_all(), read_extension_script_file(), and read_text_file().

{
    bytea      *buf;
    size_t      nbytes;
    FILE       *file;

    if (bytes_to_read < 0)
    {
        if (seek_offset < 0)
            bytes_to_read = -seek_offset;
        else
        {
            struct stat fst;

            if (stat(filename, &fst) < 0)
                ereport(ERROR,
                        (errcode_for_file_access(),
                         errmsg("could not stat file \"%s\": %m", filename)));

            bytes_to_read = fst.st_size - seek_offset;
        }
    }

    /* not sure why anyone thought that int64 length was a good idea */
    if (bytes_to_read > (MaxAllocSize - VARHDRSZ))
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("requested length too large")));

    if ((file = AllocateFile(filename, PG_BINARY_R)) == NULL)
        ereport(ERROR,
                (errcode_for_file_access(),
                 errmsg("could not open file \"%s\" for reading: %m",
                        filename)));

    if (fseeko(file, (off_t) seek_offset,
               (seek_offset >= 0) ? SEEK_SET : SEEK_END) != 0)
        ereport(ERROR,
                (errcode_for_file_access(),
                 errmsg("could not seek in file \"%s\": %m", filename)));

    buf = (bytea *) palloc((Size) bytes_to_read + VARHDRSZ);

    nbytes = fread(VARDATA(buf), 1, (size_t) bytes_to_read, file);

    if (ferror(file))
        ereport(ERROR,
                (errcode_for_file_access(),
                 errmsg("could not read file \"%s\": %m", filename)));

    SET_VARSIZE(buf, nbytes + VARHDRSZ);

    FreeFile(file);

    return buf;
}

Datum record_eq ( PG_FUNCTION_ARGS   ) 

Definition at line 1039 of file rowtypes.c.

References FunctionCallInfoData::arg, FunctionCallInfoData::argnull, tupleDesc::attrs, RecordCompareData::columns, DatumGetBool, TypeCacheEntry::eq_opr_finfo, ereport, errcode(), errmsg(), ERROR, FmgrInfo::fn_oid, format_type_be(), FunctionCallInvoke, heap_deform_tuple(), HeapTupleHeaderGetDatumLength, HeapTupleHeaderGetTypeId, HeapTupleHeaderGetTypMod, InitFunctionCallInfoData, InvalidOid, FunctionCallInfoData::isnull, ItemPointerSetInvalid, lookup_rowtype_tupdesc(), lookup_type_cache(), Max, MemoryContextAlloc(), MemSet, tupleDesc::natts, RecordCompareData::ncolumns, NULL, OidIsValid, palloc(), pfree(), PG_FREE_IF_COPY, PG_GETARG_HEAPTUPLEHEADER, PG_RETURN_BOOL, RecordCompareData::record1_type, RecordCompareData::record1_typmod, RecordCompareData::record2_type, RecordCompareData::record2_typmod, ReleaseTupleDesc, HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TypeCacheEntry::type_id, TYPECACHE_EQ_OPR_FINFO, and ColumnCompareData::typentry.

Referenced by record_ne().

{
    HeapTupleHeader record1 = PG_GETARG_HEAPTUPLEHEADER(0);
    HeapTupleHeader record2 = PG_GETARG_HEAPTUPLEHEADER(1);
    bool        result = true;
    Oid         tupType1;
    Oid         tupType2;
    int32       tupTypmod1;
    int32       tupTypmod2;
    TupleDesc   tupdesc1;
    TupleDesc   tupdesc2;
    HeapTupleData tuple1;
    HeapTupleData tuple2;
    int         ncolumns1;
    int         ncolumns2;
    RecordCompareData *my_extra;
    int         ncols;
    Datum      *values1;
    Datum      *values2;
    bool       *nulls1;
    bool       *nulls2;
    int         i1;
    int         i2;
    int         j;

    /* Extract type info from the tuples */
    tupType1 = HeapTupleHeaderGetTypeId(record1);
    tupTypmod1 = HeapTupleHeaderGetTypMod(record1);
    tupdesc1 = lookup_rowtype_tupdesc(tupType1, tupTypmod1);
    ncolumns1 = tupdesc1->natts;
    tupType2 = HeapTupleHeaderGetTypeId(record2);
    tupTypmod2 = HeapTupleHeaderGetTypMod(record2);
    tupdesc2 = lookup_rowtype_tupdesc(tupType2, tupTypmod2);
    ncolumns2 = tupdesc2->natts;

    /* Build temporary HeapTuple control structures */
    tuple1.t_len = HeapTupleHeaderGetDatumLength(record1);
    ItemPointerSetInvalid(&(tuple1.t_self));
    tuple1.t_tableOid = InvalidOid;
    tuple1.t_data = record1;
    tuple2.t_len = HeapTupleHeaderGetDatumLength(record2);
    ItemPointerSetInvalid(&(tuple2.t_self));
    tuple2.t_tableOid = InvalidOid;
    tuple2.t_data = record2;

    /*
     * We arrange to look up the needed comparison info just once per series
     * of calls, assuming the record types don't change underneath us.
     */
    ncols = Max(ncolumns1, ncolumns2);
    my_extra = (RecordCompareData *) fcinfo->flinfo->fn_extra;
    if (my_extra == NULL ||
        my_extra->ncolumns < ncols)
    {
        fcinfo->flinfo->fn_extra =
            MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
                        sizeof(RecordCompareData) - sizeof(ColumnCompareData)
                               + ncols * sizeof(ColumnCompareData));
        my_extra = (RecordCompareData *) fcinfo->flinfo->fn_extra;
        my_extra->ncolumns = ncols;
        my_extra->record1_type = InvalidOid;
        my_extra->record1_typmod = 0;
        my_extra->record2_type = InvalidOid;
        my_extra->record2_typmod = 0;
    }

    if (my_extra->record1_type != tupType1 ||
        my_extra->record1_typmod != tupTypmod1 ||
        my_extra->record2_type != tupType2 ||
        my_extra->record2_typmod != tupTypmod2)
    {
        MemSet(my_extra->columns, 0, ncols * sizeof(ColumnCompareData));
        my_extra->record1_type = tupType1;
        my_extra->record1_typmod = tupTypmod1;
        my_extra->record2_type = tupType2;
        my_extra->record2_typmod = tupTypmod2;
    }

    /* Break down the tuples into fields */
    values1 = (Datum *) palloc(ncolumns1 * sizeof(Datum));
    nulls1 = (bool *) palloc(ncolumns1 * sizeof(bool));
    heap_deform_tuple(&tuple1, tupdesc1, values1, nulls1);
    values2 = (Datum *) palloc(ncolumns2 * sizeof(Datum));
    nulls2 = (bool *) palloc(ncolumns2 * sizeof(bool));
    heap_deform_tuple(&tuple2, tupdesc2, values2, nulls2);

    /*
     * Scan corresponding columns, allowing for dropped columns in different
     * places in the two rows.  i1 and i2 are physical column indexes, j is
     * the logical column index.
     */
    i1 = i2 = j = 0;
    while (i1 < ncolumns1 || i2 < ncolumns2)
    {
        TypeCacheEntry *typentry;
        Oid         collation;
        FunctionCallInfoData locfcinfo;
        bool        oprresult;

        /*
         * Skip dropped columns
         */
        if (i1 < ncolumns1 && tupdesc1->attrs[i1]->attisdropped)
        {
            i1++;
            continue;
        }
        if (i2 < ncolumns2 && tupdesc2->attrs[i2]->attisdropped)
        {
            i2++;
            continue;
        }
        if (i1 >= ncolumns1 || i2 >= ncolumns2)
            break;              /* we'll deal with mismatch below loop */

        /*
         * Have two matching columns, they must be same type
         */
        if (tupdesc1->attrs[i1]->atttypid !=
            tupdesc2->attrs[i2]->atttypid)
            ereport(ERROR,
                    (errcode(ERRCODE_DATATYPE_MISMATCH),
                     errmsg("cannot compare dissimilar column types %s and %s at record column %d",
                            format_type_be(tupdesc1->attrs[i1]->atttypid),
                            format_type_be(tupdesc2->attrs[i2]->atttypid),
                            j + 1)));

        /*
         * If they're not same collation, we don't complain here, but the
         * equality function might.
         */
        collation = tupdesc1->attrs[i1]->attcollation;
        if (collation != tupdesc2->attrs[i2]->attcollation)
            collation = InvalidOid;

        /*
         * Lookup the equality function if not done already
         */
        typentry = my_extra->columns[j].typentry;
        if (typentry == NULL ||
            typentry->type_id != tupdesc1->attrs[i1]->atttypid)
        {
            typentry = lookup_type_cache(tupdesc1->attrs[i1]->atttypid,
                                         TYPECACHE_EQ_OPR_FINFO);
            if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
                ereport(ERROR,
                        (errcode(ERRCODE_UNDEFINED_FUNCTION),
                errmsg("could not identify an equality operator for type %s",
                       format_type_be(typentry->type_id))));
            my_extra->columns[j].typentry = typentry;
        }

        /*
         * We consider two NULLs equal; NULL > not-NULL.
         */
        if (!nulls1[i1] || !nulls2[i2])
        {
            if (nulls1[i1] || nulls2[i2])
            {
                result = false;
                break;
            }

            /* Compare the pair of elements */
            InitFunctionCallInfoData(locfcinfo, &typentry->eq_opr_finfo, 2,
                                     collation, NULL, NULL);
            locfcinfo.arg[0] = values1[i1];
            locfcinfo.arg[1] = values2[i2];
            locfcinfo.argnull[0] = false;
            locfcinfo.argnull[1] = false;
            locfcinfo.isnull = false;
            oprresult = DatumGetBool(FunctionCallInvoke(&locfcinfo));
            if (!oprresult)
            {
                result = false;
                break;
            }
        }

        /* equal, so continue to next column */
        i1++, i2++, j++;
    }

    /*
     * If we didn't break out of the loop early, check for column count
     * mismatch.  (We do not report such mismatch if we found unequal column
     * values; is that a feature or a bug?)
     */
    if (result)
    {
        if (i1 != ncolumns1 || i2 != ncolumns2)
            ereport(ERROR,
                    (errcode(ERRCODE_DATATYPE_MISMATCH),
                     errmsg("cannot compare record types with different numbers of columns")));
    }

    pfree(values1);
    pfree(nulls1);
    pfree(values2);
    pfree(nulls2);
    ReleaseTupleDesc(tupdesc1);
    ReleaseTupleDesc(tupdesc2);

    /* Avoid leaking memory when handed toasted input. */
    PG_FREE_IF_COPY(record1, 0);
    PG_FREE_IF_COPY(record2, 1);

    PG_RETURN_BOOL(result);
}

Datum record_ge ( PG_FUNCTION_ARGS   ) 

Definition at line 1274 of file rowtypes.c.

References PG_RETURN_BOOL, and record_cmp().

{
    PG_RETURN_BOOL(record_cmp(fcinfo) >= 0);
}

Datum record_gt ( PG_FUNCTION_ARGS   ) 

Definition at line 1262 of file rowtypes.c.

References PG_RETURN_BOOL, and record_cmp().

{
    PG_RETURN_BOOL(record_cmp(fcinfo) > 0);
}

Datum record_in ( PG_FUNCTION_ARGS   ) 

Definition at line 70 of file rowtypes.c.

References appendStringInfoChar(), tupleDesc::attrs, buf, ColumnIOData::column_type, RecordIOData::columns, StringInfoData::data, ereport, errcode(), errdetail(), errmsg(), ERROR, fmgr_info_cxt(), FmgrInfo::fn_mcxt, getTypeInputInfo(), heap_form_tuple(), heap_freetuple(), i, initStringInfo(), InputFunctionCall(), InvalidOid, lookup_rowtype_tupdesc(), MemoryContextAlloc(), MemSet, tupleDesc::natts, RecordIOData::ncolumns, NULL, palloc(), pfree(), PG_GETARG_CSTRING, PG_GETARG_INT32, PG_GETARG_OID, PG_RETURN_HEAPTUPLEHEADER, ColumnIOData::proc, RecordIOData::record_type, RecordIOData::record_typmod, RECORDOID, ReleaseTupleDesc, resetStringInfo(), HeapTupleData::t_data, HeapTupleData::t_len, ColumnIOData::typiofunc, ColumnIOData::typioparam, and values.

{
    char       *string = PG_GETARG_CSTRING(0);
    Oid         tupType = PG_GETARG_OID(1);

#ifdef NOT_USED
    int32       typmod = PG_GETARG_INT32(2);
#endif
    HeapTupleHeader result;
    int32       tupTypmod;
    TupleDesc   tupdesc;
    HeapTuple   tuple;
    RecordIOData *my_extra;
    bool        needComma = false;
    int         ncolumns;
    int         i;
    char       *ptr;
    Datum      *values;
    bool       *nulls;
    StringInfoData buf;

    /*
     * Use the passed type unless it's RECORD; we can't support input of
     * anonymous types, mainly because there's no good way to figure out which
     * anonymous type is wanted.  Note that for RECORD, what we'll probably
     * actually get is RECORD's typelem, ie, zero.
     */
    if (tupType == InvalidOid || tupType == RECORDOID)
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
           errmsg("input of anonymous composite types is not implemented")));
    tupTypmod = -1;             /* for all non-anonymous types */

    /*
     * This comes from the composite type's pg_type.oid and stores system oids
     * in user tables, specifically DatumTupleFields. This oid must be
     * preserved by binary upgrades.
     */
    tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
    ncolumns = tupdesc->natts;

    /*
     * We arrange to look up the needed I/O info just once per series of
     * calls, assuming the record type doesn't change underneath us.
     */
    my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
    if (my_extra == NULL ||
        my_extra->ncolumns != ncolumns)
    {
        fcinfo->flinfo->fn_extra =
            MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
                               sizeof(RecordIOData) - sizeof(ColumnIOData)
                               + ncolumns * sizeof(ColumnIOData));
        my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
        my_extra->record_type = InvalidOid;
        my_extra->record_typmod = 0;
    }

    if (my_extra->record_type != tupType ||
        my_extra->record_typmod != tupTypmod)
    {
        MemSet(my_extra, 0,
               sizeof(RecordIOData) - sizeof(ColumnIOData)
               + ncolumns * sizeof(ColumnIOData));
        my_extra->record_type = tupType;
        my_extra->record_typmod = tupTypmod;
        my_extra->ncolumns = ncolumns;
    }

    values = (Datum *) palloc(ncolumns * sizeof(Datum));
    nulls = (bool *) palloc(ncolumns * sizeof(bool));

    /*
     * Scan the string.  We use "buf" to accumulate the de-quoted data for
     * each column, which is then fed to the appropriate input converter.
     */
    ptr = string;
    /* Allow leading whitespace */
    while (*ptr && isspace((unsigned char) *ptr))
        ptr++;
    if (*ptr++ != '(')
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                 errmsg("malformed record literal: \"%s\"", string),
                 errdetail("Missing left parenthesis.")));

    initStringInfo(&buf);

    for (i = 0; i < ncolumns; i++)
    {
        ColumnIOData *column_info = &my_extra->columns[i];
        Oid         column_type = tupdesc->attrs[i]->atttypid;
        char       *column_data;

        /* Ignore dropped columns in datatype, but fill with nulls */
        if (tupdesc->attrs[i]->attisdropped)
        {
            values[i] = (Datum) 0;
            nulls[i] = true;
            continue;
        }

        if (needComma)
        {
            /* Skip comma that separates prior field from this one */
            if (*ptr == ',')
                ptr++;
            else
                /* *ptr must be ')' */
                ereport(ERROR,
                        (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                         errmsg("malformed record literal: \"%s\"", string),
                         errdetail("Too few columns.")));
        }

        /* Check for null: completely empty input means null */
        if (*ptr == ',' || *ptr == ')')
        {
            column_data = NULL;
            nulls[i] = true;
        }
        else
        {
            /* Extract string for this column */
            bool        inquote = false;

            resetStringInfo(&buf);
            while (inquote || !(*ptr == ',' || *ptr == ')'))
            {
                char        ch = *ptr++;

                if (ch == '\0')
                    ereport(ERROR,
                            (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                             errmsg("malformed record literal: \"%s\"",
                                    string),
                             errdetail("Unexpected end of input.")));
                if (ch == '\\')
                {
                    if (*ptr == '\0')
                        ereport(ERROR,
                                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                                 errmsg("malformed record literal: \"%s\"",
                                        string),
                                 errdetail("Unexpected end of input.")));
                    appendStringInfoChar(&buf, *ptr++);
                }
                else if (ch == '\"')
                {
                    if (!inquote)
                        inquote = true;
                    else if (*ptr == '\"')
                    {
                        /* doubled quote within quote sequence */
                        appendStringInfoChar(&buf, *ptr++);
                    }
                    else
                        inquote = false;
                }
                else
                    appendStringInfoChar(&buf, ch);
            }

            column_data = buf.data;
            nulls[i] = false;
        }

        /*
         * Convert the column value
         */
        if (column_info->column_type != column_type)
        {
            getTypeInputInfo(column_type,
                             &column_info->typiofunc,
                             &column_info->typioparam);
            fmgr_info_cxt(column_info->typiofunc, &column_info->proc,
                          fcinfo->flinfo->fn_mcxt);
            column_info->column_type = column_type;
        }

        values[i] = InputFunctionCall(&column_info->proc,
                                      column_data,
                                      column_info->typioparam,
                                      tupdesc->attrs[i]->atttypmod);

        /*
         * Prep for next column
         */
        needComma = true;
    }

    if (*ptr++ != ')')
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                 errmsg("malformed record literal: \"%s\"", string),
                 errdetail("Too many columns.")));
    /* Allow trailing whitespace */
    while (*ptr && isspace((unsigned char) *ptr))
        ptr++;
    if (*ptr)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                 errmsg("malformed record literal: \"%s\"", string),
                 errdetail("Junk after right parenthesis.")));

    tuple = heap_form_tuple(tupdesc, values, nulls);

    /*
     * We cannot return tuple->t_data because heap_form_tuple allocates it as
     * part of a larger chunk, and our caller may expect to be able to pfree
     * our result.  So must copy the info into a new palloc chunk.
     */
    result = (HeapTupleHeader) palloc(tuple->t_len);
    memcpy(result, tuple->t_data, tuple->t_len);

    heap_freetuple(tuple);
    pfree(buf.data);
    pfree(values);
    pfree(nulls);
    ReleaseTupleDesc(tupdesc);

    PG_RETURN_HEAPTUPLEHEADER(result);
}

Datum record_le ( PG_FUNCTION_ARGS   ) 

Definition at line 1268 of file rowtypes.c.

References PG_RETURN_BOOL, and record_cmp().

{
    PG_RETURN_BOOL(record_cmp(fcinfo) <= 0);
}

Datum record_lt ( PG_FUNCTION_ARGS   ) 

Definition at line 1256 of file rowtypes.c.

References PG_RETURN_BOOL, and record_cmp().

{
    PG_RETURN_BOOL(record_cmp(fcinfo) < 0);
}

Datum record_ne ( PG_FUNCTION_ARGS   ) 

Definition at line 1250 of file rowtypes.c.

References DatumGetBool, PG_RETURN_BOOL, and record_eq().

Datum record_out ( PG_FUNCTION_ARGS   ) 

Definition at line 298 of file rowtypes.c.

References appendStringInfoChar(), appendStringInfoCharMacro, tupleDesc::attrs, buf, ColumnIOData::column_type, RecordIOData::columns, StringInfoData::data, DatumGetPointer, fmgr_info_cxt(), FmgrInfo::fn_mcxt, getTypeOutputInfo(), heap_deform_tuple(), HeapTupleHeaderGetDatumLength, HeapTupleHeaderGetTypeId, HeapTupleHeaderGetTypMod, i, initStringInfo(), InvalidOid, ItemPointerSetInvalid, lookup_rowtype_tupdesc(), MemoryContextAlloc(), MemSet, tupleDesc::natts, RecordIOData::ncolumns, NULL, OutputFunctionCall(), palloc(), pfree(), PG_DETOAST_DATUM, PG_GETARG_HEAPTUPLEHEADER, PG_RETURN_CSTRING, PointerGetDatum, ColumnIOData::proc, RecordIOData::record_type, RecordIOData::record_typmod, ReleaseTupleDesc, HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, ColumnIOData::typiofunc, ColumnIOData::typisvarlena, value, and values.

{
    HeapTupleHeader rec = PG_GETARG_HEAPTUPLEHEADER(0);
    Oid         tupType;
    int32       tupTypmod;
    TupleDesc   tupdesc;
    HeapTupleData tuple;
    RecordIOData *my_extra;
    bool        needComma = false;
    int         ncolumns;
    int         i;
    Datum      *values;
    bool       *nulls;
    StringInfoData buf;

    /* Extract type info from the tuple itself */
    tupType = HeapTupleHeaderGetTypeId(rec);
    tupTypmod = HeapTupleHeaderGetTypMod(rec);
    tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
    ncolumns = tupdesc->natts;

    /* Build a temporary HeapTuple control structure */
    tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
    ItemPointerSetInvalid(&(tuple.t_self));
    tuple.t_tableOid = InvalidOid;
    tuple.t_data = rec;

    /*
     * We arrange to look up the needed I/O info just once per series of
     * calls, assuming the record type doesn't change underneath us.
     */
    my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
    if (my_extra == NULL ||
        my_extra->ncolumns != ncolumns)
    {
        fcinfo->flinfo->fn_extra =
            MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
                               sizeof(RecordIOData) - sizeof(ColumnIOData)
                               + ncolumns * sizeof(ColumnIOData));
        my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
        my_extra->record_type = InvalidOid;
        my_extra->record_typmod = 0;
    }

    if (my_extra->record_type != tupType ||
        my_extra->record_typmod != tupTypmod)
    {
        MemSet(my_extra, 0,
               sizeof(RecordIOData) - sizeof(ColumnIOData)
               + ncolumns * sizeof(ColumnIOData));
        my_extra->record_type = tupType;
        my_extra->record_typmod = tupTypmod;
        my_extra->ncolumns = ncolumns;
    }

    values = (Datum *) palloc(ncolumns * sizeof(Datum));
    nulls = (bool *) palloc(ncolumns * sizeof(bool));

    /* Break down the tuple into fields */
    heap_deform_tuple(&tuple, tupdesc, values, nulls);

    /* And build the result string */
    initStringInfo(&buf);

    appendStringInfoChar(&buf, '(');

    for (i = 0; i < ncolumns; i++)
    {
        ColumnIOData *column_info = &my_extra->columns[i];
        Oid         column_type = tupdesc->attrs[i]->atttypid;
        Datum       attr;
        char       *value;
        char       *tmp;
        bool        nq;

        /* Ignore dropped columns in datatype */
        if (tupdesc->attrs[i]->attisdropped)
            continue;

        if (needComma)
            appendStringInfoChar(&buf, ',');
        needComma = true;

        if (nulls[i])
        {
            /* emit nothing... */
            continue;
        }

        /*
         * Convert the column value to text
         */
        if (column_info->column_type != column_type)
        {
            getTypeOutputInfo(column_type,
                              &column_info->typiofunc,
                              &column_info->typisvarlena);
            fmgr_info_cxt(column_info->typiofunc, &column_info->proc,
                          fcinfo->flinfo->fn_mcxt);
            column_info->column_type = column_type;
        }

        /*
         * If we have a toasted datum, forcibly detoast it here to avoid
         * memory leakage inside the type's output routine.
         */
        if (column_info->typisvarlena)
            attr = PointerGetDatum(PG_DETOAST_DATUM(values[i]));
        else
            attr = values[i];

        value = OutputFunctionCall(&column_info->proc, attr);

        /* Detect whether we need double quotes for this value */
        nq = (value[0] == '\0');    /* force quotes for empty string */
        for (tmp = value; *tmp; tmp++)
        {
            char        ch = *tmp;

            if (ch == '"' || ch == '\\' ||
                ch == '(' || ch == ')' || ch == ',' ||
                isspace((unsigned char) ch))
            {
                nq = true;
                break;
            }
        }

        /* And emit the string */
        if (nq)
            appendStringInfoCharMacro(&buf, '"');
        for (tmp = value; *tmp; tmp++)
        {
            char        ch = *tmp;

            if (ch == '"' || ch == '\\')
                appendStringInfoCharMacro(&buf, ch);
            appendStringInfoCharMacro(&buf, ch);
        }
        if (nq)
            appendStringInfoCharMacro(&buf, '"');

        pfree(value);

        /* Clean up detoasted copy, if any */
        if (DatumGetPointer(attr) != DatumGetPointer(values[i]))
            pfree(DatumGetPointer(attr));
    }

    appendStringInfoChar(&buf, ')');

    pfree(values);
    pfree(nulls);
    ReleaseTupleDesc(tupdesc);

    PG_RETURN_CSTRING(buf.data);
}

Datum record_recv ( PG_FUNCTION_ARGS   ) 

Definition at line 460 of file rowtypes.c.

References tupleDesc::attrs, buf, ColumnIOData::column_type, RecordIOData::columns, StringInfoData::cursor, StringInfoData::data, ereport, errcode(), errmsg(), ERROR, fmgr_info_cxt(), FmgrInfo::fn_mcxt, getTypeBinaryInputInfo(), heap_form_tuple(), heap_freetuple(), i, InvalidOid, StringInfoData::len, lookup_rowtype_tupdesc(), StringInfoData::maxlen, MemoryContextAlloc(), MemSet, tupleDesc::natts, RecordIOData::ncolumns, NULL, palloc(), pfree(), PG_GETARG_INT32, PG_GETARG_OID, PG_GETARG_POINTER, PG_RETURN_HEAPTUPLEHEADER, pq_getmsgint(), ColumnIOData::proc, ReceiveFunctionCall(), RecordIOData::record_type, RecordIOData::record_typmod, RECORDOID, ReleaseTupleDesc, HeapTupleData::t_data, HeapTupleData::t_len, ColumnIOData::typiofunc, ColumnIOData::typioparam, and values.

{
    StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
    Oid         tupType = PG_GETARG_OID(1);

#ifdef NOT_USED
    int32       typmod = PG_GETARG_INT32(2);
#endif
    HeapTupleHeader result;
    int32       tupTypmod;
    TupleDesc   tupdesc;
    HeapTuple   tuple;
    RecordIOData *my_extra;
    int         ncolumns;
    int         usercols;
    int         validcols;
    int         i;
    Datum      *values;
    bool       *nulls;

    /*
     * Use the passed type unless it's RECORD; we can't support input of
     * anonymous types, mainly because there's no good way to figure out which
     * anonymous type is wanted.  Note that for RECORD, what we'll probably
     * actually get is RECORD's typelem, ie, zero.
     */
    if (tupType == InvalidOid || tupType == RECORDOID)
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
           errmsg("input of anonymous composite types is not implemented")));
    tupTypmod = -1;             /* for all non-anonymous types */
    tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
    ncolumns = tupdesc->natts;

    /*
     * We arrange to look up the needed I/O info just once per series of
     * calls, assuming the record type doesn't change underneath us.
     */
    my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
    if (my_extra == NULL ||
        my_extra->ncolumns != ncolumns)
    {
        fcinfo->flinfo->fn_extra =
            MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
                               sizeof(RecordIOData) - sizeof(ColumnIOData)
                               + ncolumns * sizeof(ColumnIOData));
        my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
        my_extra->record_type = InvalidOid;
        my_extra->record_typmod = 0;
    }

    if (my_extra->record_type != tupType ||
        my_extra->record_typmod != tupTypmod)
    {
        MemSet(my_extra, 0,
               sizeof(RecordIOData) - sizeof(ColumnIOData)
               + ncolumns * sizeof(ColumnIOData));
        my_extra->record_type = tupType;
        my_extra->record_typmod = tupTypmod;
        my_extra->ncolumns = ncolumns;
    }

    values = (Datum *) palloc(ncolumns * sizeof(Datum));
    nulls = (bool *) palloc(ncolumns * sizeof(bool));

    /* Fetch number of columns user thinks it has */
    usercols = pq_getmsgint(buf, 4);

    /* Need to scan to count nondeleted columns */
    validcols = 0;
    for (i = 0; i < ncolumns; i++)
    {
        if (!tupdesc->attrs[i]->attisdropped)
            validcols++;
    }
    if (usercols != validcols)
        ereport(ERROR,
                (errcode(ERRCODE_DATATYPE_MISMATCH),
                 errmsg("wrong number of columns: %d, expected %d",
                        usercols, validcols)));

    /* Process each column */
    for (i = 0; i < ncolumns; i++)
    {
        ColumnIOData *column_info = &my_extra->columns[i];
        Oid         column_type = tupdesc->attrs[i]->atttypid;
        Oid         coltypoid;
        int         itemlen;
        StringInfoData item_buf;
        StringInfo  bufptr;
        char        csave;

        /* Ignore dropped columns in datatype, but fill with nulls */
        if (tupdesc->attrs[i]->attisdropped)
        {
            values[i] = (Datum) 0;
            nulls[i] = true;
            continue;
        }

        /* Verify column datatype */
        coltypoid = pq_getmsgint(buf, sizeof(Oid));
        if (coltypoid != column_type)
            ereport(ERROR,
                    (errcode(ERRCODE_DATATYPE_MISMATCH),
                     errmsg("wrong data type: %u, expected %u",
                            coltypoid, column_type)));

        /* Get and check the item length */
        itemlen = pq_getmsgint(buf, 4);
        if (itemlen < -1 || itemlen > (buf->len - buf->cursor))
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
                     errmsg("insufficient data left in message")));

        if (itemlen == -1)
        {
            /* -1 length means NULL */
            bufptr = NULL;
            nulls[i] = true;
            csave = 0;          /* keep compiler quiet */
        }
        else
        {
            /*
             * Rather than copying data around, we just set up a phony
             * StringInfo pointing to the correct portion of the input buffer.
             * We assume we can scribble on the input buffer so as to maintain
             * the convention that StringInfos have a trailing null.
             */
            item_buf.data = &buf->data[buf->cursor];
            item_buf.maxlen = itemlen + 1;
            item_buf.len = itemlen;
            item_buf.cursor = 0;

            buf->cursor += itemlen;

            csave = buf->data[buf->cursor];
            buf->data[buf->cursor] = '\0';

            bufptr = &item_buf;
            nulls[i] = false;
        }

        /* Now call the column's receiveproc */
        if (column_info->column_type != column_type)
        {
            getTypeBinaryInputInfo(column_type,
                                   &column_info->typiofunc,
                                   &column_info->typioparam);
            fmgr_info_cxt(column_info->typiofunc, &column_info->proc,
                          fcinfo->flinfo->fn_mcxt);
            column_info->column_type = column_type;
        }

        values[i] = ReceiveFunctionCall(&column_info->proc,
                                        bufptr,
                                        column_info->typioparam,
                                        tupdesc->attrs[i]->atttypmod);

        if (bufptr)
        {
            /* Trouble if it didn't eat the whole buffer */
            if (item_buf.cursor != itemlen)
                ereport(ERROR,
                        (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
                         errmsg("improper binary format in record column %d",
                                i + 1)));

            buf->data[buf->cursor] = csave;
        }
    }

    tuple = heap_form_tuple(tupdesc, values, nulls);

    /*
     * We cannot return tuple->t_data because heap_form_tuple allocates it as
     * part of a larger chunk, and our caller may expect to be able to pfree
     * our result.  So must copy the info into a new palloc chunk.
     */
    result = (HeapTupleHeader) palloc(tuple->t_len);
    memcpy(result, tuple->t_data, tuple->t_len);

    heap_freetuple(tuple);
    pfree(values);
    pfree(nulls);
    ReleaseTupleDesc(tupdesc);

    PG_RETURN_HEAPTUPLEHEADER(result);
}

Datum record_send ( PG_FUNCTION_ARGS   ) 

Definition at line 655 of file rowtypes.c.

References tupleDesc::attrs, buf, ColumnIOData::column_type, RecordIOData::columns, DatumGetPointer, fmgr_info_cxt(), FmgrInfo::fn_mcxt, getTypeBinaryOutputInfo(), heap_deform_tuple(), HeapTupleHeaderGetDatumLength, HeapTupleHeaderGetTypeId, HeapTupleHeaderGetTypMod, i, InvalidOid, ItemPointerSetInvalid, lookup_rowtype_tupdesc(), MemoryContextAlloc(), MemSet, tupleDesc::natts, RecordIOData::ncolumns, NULL, palloc(), pfree(), PG_DETOAST_DATUM, PG_GETARG_HEAPTUPLEHEADER, PG_RETURN_BYTEA_P, PointerGetDatum, pq_begintypsend(), pq_endtypsend(), pq_sendbytes(), pq_sendint(), ColumnIOData::proc, RecordIOData::record_type, RecordIOData::record_typmod, ReleaseTupleDesc, SendFunctionCall(), HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, ColumnIOData::typiofunc, ColumnIOData::typisvarlena, values, VARDATA, VARHDRSZ, and VARSIZE.

{
    HeapTupleHeader rec = PG_GETARG_HEAPTUPLEHEADER(0);
    Oid         tupType;
    int32       tupTypmod;
    TupleDesc   tupdesc;
    HeapTupleData tuple;
    RecordIOData *my_extra;
    int         ncolumns;
    int         validcols;
    int         i;
    Datum      *values;
    bool       *nulls;
    StringInfoData buf;

    /* Extract type info from the tuple itself */
    tupType = HeapTupleHeaderGetTypeId(rec);
    tupTypmod = HeapTupleHeaderGetTypMod(rec);
    tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
    ncolumns = tupdesc->natts;

    /* Build a temporary HeapTuple control structure */
    tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
    ItemPointerSetInvalid(&(tuple.t_self));
    tuple.t_tableOid = InvalidOid;
    tuple.t_data = rec;

    /*
     * We arrange to look up the needed I/O info just once per series of
     * calls, assuming the record type doesn't change underneath us.
     */
    my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
    if (my_extra == NULL ||
        my_extra->ncolumns != ncolumns)
    {
        fcinfo->flinfo->fn_extra =
            MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
                               sizeof(RecordIOData) - sizeof(ColumnIOData)
                               + ncolumns * sizeof(ColumnIOData));
        my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
        my_extra->record_type = InvalidOid;
        my_extra->record_typmod = 0;
    }

    if (my_extra->record_type != tupType ||
        my_extra->record_typmod != tupTypmod)
    {
        MemSet(my_extra, 0,
               sizeof(RecordIOData) - sizeof(ColumnIOData)
               + ncolumns * sizeof(ColumnIOData));
        my_extra->record_type = tupType;
        my_extra->record_typmod = tupTypmod;
        my_extra->ncolumns = ncolumns;
    }

    values = (Datum *) palloc(ncolumns * sizeof(Datum));
    nulls = (bool *) palloc(ncolumns * sizeof(bool));

    /* Break down the tuple into fields */
    heap_deform_tuple(&tuple, tupdesc, values, nulls);

    /* And build the result string */
    pq_begintypsend(&buf);

    /* Need to scan to count nondeleted columns */
    validcols = 0;
    for (i = 0; i < ncolumns; i++)
    {
        if (!tupdesc->attrs[i]->attisdropped)
            validcols++;
    }
    pq_sendint(&buf, validcols, 4);

    for (i = 0; i < ncolumns; i++)
    {
        ColumnIOData *column_info = &my_extra->columns[i];
        Oid         column_type = tupdesc->attrs[i]->atttypid;
        Datum       attr;
        bytea      *outputbytes;

        /* Ignore dropped columns in datatype */
        if (tupdesc->attrs[i]->attisdropped)
            continue;

        pq_sendint(&buf, column_type, sizeof(Oid));

        if (nulls[i])
        {
            /* emit -1 data length to signify a NULL */
            pq_sendint(&buf, -1, 4);
            continue;
        }

        /*
         * Convert the column value to binary
         */
        if (column_info->column_type != column_type)
        {
            getTypeBinaryOutputInfo(column_type,
                                    &column_info->typiofunc,
                                    &column_info->typisvarlena);
            fmgr_info_cxt(column_info->typiofunc, &column_info->proc,
                          fcinfo->flinfo->fn_mcxt);
            column_info->column_type = column_type;
        }

        /*
         * If we have a toasted datum, forcibly detoast it here to avoid
         * memory leakage inside the type's output routine.
         */
        if (column_info->typisvarlena)
            attr = PointerGetDatum(PG_DETOAST_DATUM(values[i]));
        else
            attr = values[i];

        outputbytes = SendFunctionCall(&column_info->proc, attr);

        /* We assume the result will not have been toasted */
        pq_sendint(&buf, VARSIZE(outputbytes) - VARHDRSZ, 4);
        pq_sendbytes(&buf, VARDATA(outputbytes),
                     VARSIZE(outputbytes) - VARHDRSZ);

        pfree(outputbytes);

        /* Clean up detoasted copy, if any */
        if (DatumGetPointer(attr) != DatumGetPointer(values[i]))
            pfree(DatumGetPointer(attr));
    }

    pfree(values);
    pfree(nulls);
    ReleaseTupleDesc(tupdesc);

    PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
}

Datum regclassin ( PG_FUNCTION_ARGS   ) 

Definition at line 803 of file regproc.c.

References AccessShareLock, Anum_pg_class_relname, BTEqualStrategyNumber, ClassNameNspIndexId, CStringGetDatum, DatumGetObjectId, DirectFunctionCall1, ereport, errcode(), errmsg(), ERROR, heap_close, heap_open(), HeapTupleGetOid, HeapTupleIsValid, InvalidOid, IsBootstrapProcessingMode, makeRangeVarFromNameList(), NoLock, oidin(), PG_GETARG_CSTRING, PG_RETURN_OID, RangeVarGetRelid, RelationRelationId, ScanKeyInit(), SnapshotNow, stringToQualifiedNameList(), systable_beginscan(), systable_endscan(), and systable_getnext().

{
    char       *class_name_or_oid = PG_GETARG_CSTRING(0);
    Oid         result = InvalidOid;
    List       *names;

    /* '-' ? */
    if (strcmp(class_name_or_oid, "-") == 0)
        PG_RETURN_OID(InvalidOid);

    /* Numeric OID? */
    if (class_name_or_oid[0] >= '0' &&
        class_name_or_oid[0] <= '9' &&
        strspn(class_name_or_oid, "0123456789") == strlen(class_name_or_oid))
    {
        result = DatumGetObjectId(DirectFunctionCall1(oidin,
                                        CStringGetDatum(class_name_or_oid)));
        PG_RETURN_OID(result);
    }

    /* Else it's a name, possibly schema-qualified */

    /*
     * In bootstrap mode we assume the given name is not schema-qualified, and
     * just search pg_class for a match.  This is needed for initializing
     * other system catalogs (pg_namespace may not exist yet, and certainly
     * there are no schemas other than pg_catalog).
     */
    if (IsBootstrapProcessingMode())
    {
        Relation    hdesc;
        ScanKeyData skey[1];
        SysScanDesc sysscan;
        HeapTuple   tuple;

        ScanKeyInit(&skey[0],
                    Anum_pg_class_relname,
                    BTEqualStrategyNumber, F_NAMEEQ,
                    CStringGetDatum(class_name_or_oid));

        hdesc = heap_open(RelationRelationId, AccessShareLock);
        sysscan = systable_beginscan(hdesc, ClassNameNspIndexId, true,
                                     SnapshotNow, 1, skey);

        if (HeapTupleIsValid(tuple = systable_getnext(sysscan)))
            result = HeapTupleGetOid(tuple);
        else
            ereport(ERROR,
                    (errcode(ERRCODE_UNDEFINED_TABLE),
               errmsg("relation \"%s\" does not exist", class_name_or_oid)));

        /* We assume there can be only one match */

        systable_endscan(sysscan);
        heap_close(hdesc, AccessShareLock);

        PG_RETURN_OID(result);
    }

    /*
     * Normal case: parse the name into components and see if it matches any
     * pg_class entries in the current search path.
     */
    names = stringToQualifiedNameList(class_name_or_oid);

    /* We might not even have permissions on this relation; don't lock it. */
    result = RangeVarGetRelid(makeRangeVarFromNameList(names), NoLock, false);

    PG_RETURN_OID(result);
}

Datum regclassout ( PG_FUNCTION_ARGS   ) 

Definition at line 878 of file regproc.c.

References get_namespace_name(), GETSTRUCT, HeapTupleIsValid, InvalidOid, IsBootstrapProcessingMode, NAMEDATALEN, NameStr, ObjectIdGetDatum, palloc(), PG_GETARG_OID, PG_RETURN_CSTRING, pstrdup(), quote_qualified_identifier(), RelationIsVisible(), ReleaseSysCache(), RELOID, SearchSysCache1, and snprintf().

Referenced by table_to_xml_internal().

{
    Oid         classid = PG_GETARG_OID(0);
    char       *result;
    HeapTuple   classtup;

    if (classid == InvalidOid)
    {
        result = pstrdup("-");
        PG_RETURN_CSTRING(result);
    }

    classtup = SearchSysCache1(RELOID, ObjectIdGetDatum(classid));

    if (HeapTupleIsValid(classtup))
    {
        Form_pg_class classform = (Form_pg_class) GETSTRUCT(classtup);
        char       *classname = NameStr(classform->relname);

        /*
         * In bootstrap mode, skip the fancy namespace stuff and just return
         * the class name.  (This path is only needed for debugging output
         * anyway.)
         */
        if (IsBootstrapProcessingMode())
            result = pstrdup(classname);
        else
        {
            char       *nspname;

            /*
             * Would this class be found by regclassin? If not, qualify it.
             */
            if (RelationIsVisible(classid))
                nspname = NULL;
            else
                nspname = get_namespace_name(classform->relnamespace);

            result = quote_qualified_identifier(nspname, classname);
        }

        ReleaseSysCache(classtup);
    }
    else
    {
        /* If OID doesn't match any pg_class entry, return it numerically */
        result = (char *) palloc(NAMEDATALEN);
        snprintf(result, NAMEDATALEN, "%u", classid);
    }

    PG_RETURN_CSTRING(result);
}

Datum regclassrecv ( PG_FUNCTION_ARGS   ) 

Definition at line 935 of file regproc.c.

References oidrecv().

{
    /* Exactly the same as oidrecv, so share code */
    return oidrecv(fcinfo);
}

Datum regclasssend ( PG_FUNCTION_ARGS   ) 

Definition at line 945 of file regproc.c.

References oidsend().

{
    /* Exactly the same as oidsend, so share code */
    return oidsend(fcinfo);
}

Datum regconfigin ( PG_FUNCTION_ARGS   ) 

Definition at line 1116 of file regproc.c.

References CStringGetDatum, DatumGetObjectId, DirectFunctionCall1, get_ts_config_oid(), InvalidOid, oidin(), PG_GETARG_CSTRING, PG_RETURN_OID, and stringToQualifiedNameList().

Referenced by tsa_headline_byname(), tsa_plainto_tsquery_name(), tsa_to_tsquery_name(), and tsa_to_tsvector_name().

{
    char       *cfg_name_or_oid = PG_GETARG_CSTRING(0);
    Oid         result;
    List       *names;

    /* '-' ? */
    if (strcmp(cfg_name_or_oid, "-") == 0)
        PG_RETURN_OID(InvalidOid);

    /* Numeric OID? */
    if (cfg_name_or_oid[0] >= '0' &&
        cfg_name_or_oid[0] <= '9' &&
        strspn(cfg_name_or_oid, "0123456789") == strlen(cfg_name_or_oid))
    {
        result = DatumGetObjectId(DirectFunctionCall1(oidin,
                                          CStringGetDatum(cfg_name_or_oid)));
        PG_RETURN_OID(result);
    }

    /*
     * Normal case: parse the name into components and see if it matches any
     * pg_ts_config entries in the current search path.
     */
    names = stringToQualifiedNameList(cfg_name_or_oid);

    result = get_ts_config_oid(names, false);

    PG_RETURN_OID(result);
}

Datum regconfigout ( PG_FUNCTION_ARGS   ) 

Definition at line 1151 of file regproc.c.

References get_namespace_name(), GETSTRUCT, HeapTupleIsValid, InvalidOid, NAMEDATALEN, NameStr, ObjectIdGetDatum, palloc(), PG_GETARG_OID, PG_RETURN_CSTRING, pstrdup(), quote_qualified_identifier(), ReleaseSysCache(), SearchSysCache1, snprintf(), TSConfigIsVisible(), and TSCONFIGOID.

Referenced by tsa_set_curcfg().

{
    Oid         cfgid = PG_GETARG_OID(0);
    char       *result;
    HeapTuple   cfgtup;

    if (cfgid == InvalidOid)
    {
        result = pstrdup("-");
        PG_RETURN_CSTRING(result);
    }

    cfgtup = SearchSysCache1(TSCONFIGOID, ObjectIdGetDatum(cfgid));

    if (HeapTupleIsValid(cfgtup))
    {
        Form_pg_ts_config cfgform = (Form_pg_ts_config) GETSTRUCT(cfgtup);
        char       *cfgname = NameStr(cfgform->cfgname);
        char       *nspname;

        /*
         * Would this config be found by regconfigin? If not, qualify it.
         */
        if (TSConfigIsVisible(cfgid))
            nspname = NULL;
        else
            nspname = get_namespace_name(cfgform->cfgnamespace);

        result = quote_qualified_identifier(nspname, cfgname);

        ReleaseSysCache(cfgtup);
    }
    else
    {
        /* If OID doesn't match any pg_ts_config row, return it numerically */
        result = (char *) palloc(NAMEDATALEN);
        snprintf(result, NAMEDATALEN, "%u", cfgid);
    }

    PG_RETURN_CSTRING(result);
}

Datum regconfigrecv ( PG_FUNCTION_ARGS   ) 

Definition at line 1197 of file regproc.c.

References oidrecv().

{
    /* Exactly the same as oidrecv, so share code */
    return oidrecv(fcinfo);
}

Datum regconfigsend ( PG_FUNCTION_ARGS   ) 

Definition at line 1207 of file regproc.c.

References oidsend().

{
    /* Exactly the same as oidsend, so share code */
    return oidsend(fcinfo);
}

Datum regdictionaryin ( PG_FUNCTION_ARGS   ) 

Definition at line 1226 of file regproc.c.

References CStringGetDatum, DatumGetObjectId, DirectFunctionCall1, get_ts_dict_oid(), InvalidOid, oidin(), PG_GETARG_CSTRING, PG_RETURN_OID, and stringToQualifiedNameList().

Referenced by tsa_lexize_byname().

{
    char       *dict_name_or_oid = PG_GETARG_CSTRING(0);
    Oid         result;
    List       *names;

    /* '-' ? */
    if (strcmp(dict_name_or_oid, "-") == 0)
        PG_RETURN_OID(InvalidOid);

    /* Numeric OID? */
    if (dict_name_or_oid[0] >= '0' &&
        dict_name_or_oid[0] <= '9' &&
        strspn(dict_name_or_oid, "0123456789") == strlen(dict_name_or_oid))
    {
        result = DatumGetObjectId(DirectFunctionCall1(oidin,
                                         CStringGetDatum(dict_name_or_oid)));
        PG_RETURN_OID(result);
    }

    /*
     * Normal case: parse the name into components and see if it matches any
     * pg_ts_dict entries in the current search path.
     */
    names = stringToQualifiedNameList(dict_name_or_oid);

    result = get_ts_dict_oid(names, false);

    PG_RETURN_OID(result);
}

Datum regdictionaryout ( PG_FUNCTION_ARGS   ) 

Definition at line 1261 of file regproc.c.

References get_namespace_name(), GETSTRUCT, HeapTupleIsValid, InvalidOid, NAMEDATALEN, NameStr, ObjectIdGetDatum, palloc(), PG_GETARG_OID, PG_RETURN_CSTRING, pstrdup(), quote_qualified_identifier(), ReleaseSysCache(), SearchSysCache1, snprintf(), TSDictionaryIsVisible(), and TSDICTOID.

{
    Oid         dictid = PG_GETARG_OID(0);
    char       *result;
    HeapTuple   dicttup;

    if (dictid == InvalidOid)
    {
        result = pstrdup("-");
        PG_RETURN_CSTRING(result);
    }

    dicttup = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dictid));

    if (HeapTupleIsValid(dicttup))
    {
        Form_pg_ts_dict dictform = (Form_pg_ts_dict) GETSTRUCT(dicttup);
        char       *dictname = NameStr(dictform->dictname);
        char       *nspname;

        /*
         * Would this dictionary be found by regdictionaryin? If not, qualify
         * it.
         */
        if (TSDictionaryIsVisible(dictid))
            nspname = NULL;
        else
            nspname = get_namespace_name(dictform->dictnamespace);

        result = quote_qualified_identifier(nspname, dictname);

        ReleaseSysCache(dicttup);
    }
    else
    {
        /* If OID doesn't match any pg_ts_dict row, return it numerically */
        result = (char *) palloc(NAMEDATALEN);
        snprintf(result, NAMEDATALEN, "%u", dictid);
    }

    PG_RETURN_CSTRING(result);
}

Datum regdictionaryrecv ( PG_FUNCTION_ARGS   ) 

Definition at line 1308 of file regproc.c.

References oidrecv().

{
    /* Exactly the same as oidrecv, so share code */
    return oidrecv(fcinfo);
}

Datum regdictionarysend ( PG_FUNCTION_ARGS   ) 

Definition at line 1318 of file regproc.c.

References oidsend().

{
    /* Exactly the same as oidsend, so share code */
    return oidsend(fcinfo);
}

char* regexp_fixed_prefix ( text text_re,
bool  case_insensitive,
Oid  collation,
bool exact 
)

Definition at line 1180 of file regexp.c.

References Assert, ereport, errcode(), errmsg(), ERROR, free, palloc(), pg_database_encoding_max_length(), pg_regerror(), pg_regprefix(), pg_wchar2mb_with_len(), RE_compile_and_cache(), REG_EXACT, REG_NOMATCH, and REG_PREFIX.

Referenced by regex_fixed_prefix().

{
    char       *result;
    regex_t    *re;
    int         cflags;
    int         re_result;
    pg_wchar   *str;
    size_t      slen;
    size_t      maxlen;
    char        errMsg[100];

    *exact = false;             /* default result */

    /* Compile RE */
    cflags = REG_ADVANCED;
    if (case_insensitive)
        cflags |= REG_ICASE;

    re = RE_compile_and_cache(text_re, cflags, collation);

    /* Examine it to see if there's a fixed prefix */
    re_result = pg_regprefix(re, &str, &slen);

    switch (re_result)
    {
        case REG_NOMATCH:
            return NULL;

        case REG_PREFIX:
            /* continue with wchar conversion */
            break;

        case REG_EXACT:
            *exact = true;
            /* continue with wchar conversion */
            break;

        default:
            /* re failed??? */
            pg_regerror(re_result, re, errMsg, sizeof(errMsg));
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_REGULAR_EXPRESSION),
                     errmsg("regular expression failed: %s", errMsg)));
            break;
    }

    /* Convert pg_wchar result back to database encoding */
    maxlen = pg_database_encoding_max_length() * slen + 1;
    result = (char *) palloc(maxlen);
    slen = pg_wchar2mb_with_len(str, result, slen);
    Assert(slen < maxlen);

    free(str);

    return result;
}

Datum regexp_matches ( PG_FUNCTION_ARGS   ) 

Definition at line 783 of file regexp.c.

References build_regexp_matches_result(), cleanup_regexp_matches(), regexp_matches_ctx::elems, MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, regexp_matches_ctx::next_match, regexp_matches_ctx::nmatches, regexp_matches_ctx::npatterns, regexp_matches_ctx::nulls, palloc(), PG_GET_COLLATION, PG_GETARG_TEXT_P_COPY, PG_GETARG_TEXT_PP, PG_GETARG_TEXT_PP_IF_EXISTS, PointerGetDatum, setup_regexp_matches(), SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, and FuncCallContext::user_fctx.

Referenced by regexp_matches_no_flags().

{
    FuncCallContext *funcctx;
    regexp_matches_ctx *matchctx;

    if (SRF_IS_FIRSTCALL())
    {
        text       *pattern = PG_GETARG_TEXT_PP(1);
        text       *flags = PG_GETARG_TEXT_PP_IF_EXISTS(2);
        MemoryContext oldcontext;

        funcctx = SRF_FIRSTCALL_INIT();
        oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);

        /* be sure to copy the input string into the multi-call ctx */
        matchctx = setup_regexp_matches(PG_GETARG_TEXT_P_COPY(0), pattern,
                                        flags,
                                        PG_GET_COLLATION(),
                                        false, true, false);

        /* Pre-create workspace that build_regexp_matches_result needs */
        matchctx->elems = (Datum *) palloc(sizeof(Datum) * matchctx->npatterns);
        matchctx->nulls = (bool *) palloc(sizeof(bool) * matchctx->npatterns);

        MemoryContextSwitchTo(oldcontext);
        funcctx->user_fctx = (void *) matchctx;
    }

    funcctx = SRF_PERCALL_SETUP();
    matchctx = (regexp_matches_ctx *) funcctx->user_fctx;

    if (matchctx->next_match < matchctx->nmatches)
    {
        ArrayType  *result_ary;

        result_ary = build_regexp_matches_result(matchctx);
        matchctx->next_match++;
        SRF_RETURN_NEXT(funcctx, PointerGetDatum(result_ary));
    }

    /* release space in multi-call ctx to avoid intraquery memory leak */
    cleanup_regexp_matches(matchctx);

    SRF_RETURN_DONE(funcctx);
}

Datum regexp_matches_no_flags ( PG_FUNCTION_ARGS   ) 

Definition at line 831 of file regexp.c.

References regexp_matches().

{
    return regexp_matches(fcinfo);
}

Datum regexp_split_to_array ( PG_FUNCTION_ARGS   ) 

Definition at line 1098 of file regexp.c.

References accumArrayResult(), build_regexp_split_result(), CurrentMemoryContext, makeArrayResult(), regexp_matches_ctx::next_match, regexp_matches_ctx::nmatches, PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_GETARG_TEXT_PP_IF_EXISTS, PG_RETURN_ARRAYTYPE_P, setup_regexp_matches(), and TEXTOID.

Referenced by regexp_split_to_array_no_flags().

{
    ArrayBuildState *astate = NULL;
    regexp_matches_ctx *splitctx;

    splitctx = setup_regexp_matches(PG_GETARG_TEXT_PP(0),
                                    PG_GETARG_TEXT_PP(1),
                                    PG_GETARG_TEXT_PP_IF_EXISTS(2),
                                    PG_GET_COLLATION(),
                                    true, false, true);

    while (splitctx->next_match <= splitctx->nmatches)
    {
        astate = accumArrayResult(astate,
                                  build_regexp_split_result(splitctx),
                                  false,
                                  TEXTOID,
                                  CurrentMemoryContext);
        splitctx->next_match++;
    }

    /*
     * We don't call cleanup_regexp_matches here; it would try to pfree the
     * input string, which we didn't copy.  The space is not in a long-lived
     * memory context anyway.
     */

    PG_RETURN_ARRAYTYPE_P(makeArrayResult(astate, CurrentMemoryContext));
}

Datum regexp_split_to_array_no_flags ( PG_FUNCTION_ARGS   ) 

Definition at line 1130 of file regexp.c.

References regexp_split_to_array().

{
    return regexp_split_to_array(fcinfo);
}

Datum regexp_split_to_table ( PG_FUNCTION_ARGS   ) 

Definition at line 1044 of file regexp.c.

References build_regexp_split_result(), cleanup_regexp_matches(), MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, regexp_matches_ctx::next_match, regexp_matches_ctx::nmatches, PG_GET_COLLATION, PG_GETARG_TEXT_P_COPY, PG_GETARG_TEXT_PP, PG_GETARG_TEXT_PP_IF_EXISTS, setup_regexp_matches(), SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, and FuncCallContext::user_fctx.

Referenced by regexp_split_to_table_no_flags().

{
    FuncCallContext *funcctx;
    regexp_matches_ctx *splitctx;

    if (SRF_IS_FIRSTCALL())
    {
        text       *pattern = PG_GETARG_TEXT_PP(1);
        text       *flags = PG_GETARG_TEXT_PP_IF_EXISTS(2);
        MemoryContext oldcontext;

        funcctx = SRF_FIRSTCALL_INIT();
        oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);

        /* be sure to copy the input string into the multi-call ctx */
        splitctx = setup_regexp_matches(PG_GETARG_TEXT_P_COPY(0), pattern,
                                        flags,
                                        PG_GET_COLLATION(),
                                        true, false, true);

        MemoryContextSwitchTo(oldcontext);
        funcctx->user_fctx = (void *) splitctx;
    }

    funcctx = SRF_PERCALL_SETUP();
    splitctx = (regexp_matches_ctx *) funcctx->user_fctx;

    if (splitctx->next_match <= splitctx->nmatches)
    {
        Datum       result = build_regexp_split_result(splitctx);

        splitctx->next_match++;
        SRF_RETURN_NEXT(funcctx, result);
    }

    /* release space in multi-call ctx to avoid intraquery memory leak */
    cleanup_regexp_matches(splitctx);

    SRF_RETURN_DONE(funcctx);
}

Datum regexp_split_to_table_no_flags ( PG_FUNCTION_ARGS   ) 

Definition at line 1087 of file regexp.c.

References regexp_split_to_table().

{
    return regexp_split_to_table(fcinfo);
}

Datum regoperatorin ( PG_FUNCTION_ARGS   ) 

Definition at line 620 of file regproc.c.

References CStringGetDatum, DatumGetObjectId, DirectFunctionCall1, ereport, errcode(), errhint(), errmsg(), ERROR, InvalidOid, oidin(), OidIsValid, OpernameGetOprid(), parseNameAndArgTypes(), PG_GETARG_CSTRING, and PG_RETURN_OID.

{
    char       *opr_name_or_oid = PG_GETARG_CSTRING(0);
    Oid         result;
    List       *names;
    int         nargs;
    Oid         argtypes[FUNC_MAX_ARGS];

    /* '0' ? */
    if (strcmp(opr_name_or_oid, "0") == 0)
        PG_RETURN_OID(InvalidOid);

    /* Numeric OID? */
    if (opr_name_or_oid[0] >= '0' &&
        opr_name_or_oid[0] <= '9' &&
        strspn(opr_name_or_oid, "0123456789") == strlen(opr_name_or_oid))
    {
        result = DatumGetObjectId(DirectFunctionCall1(oidin,
                                          CStringGetDatum(opr_name_or_oid)));
        PG_RETURN_OID(result);
    }

    /*
     * Else it's a name and arguments.  Parse the name and arguments, look up
     * potential matches in the current namespace search list, and scan to see
     * which one exactly matches the given argument types.  (There will not be
     * more than one match.)
     *
     * XXX at present, this code will not work in bootstrap mode, hence this
     * datatype cannot be used for any system column that needs to receive
     * data during bootstrap.
     */
    parseNameAndArgTypes(opr_name_or_oid, true, &names, &nargs, argtypes);
    if (nargs == 1)
        ereport(ERROR,
                (errcode(ERRCODE_UNDEFINED_PARAMETER),
                 errmsg("missing argument"),
                 errhint("Use NONE to denote the missing argument of a unary operator.")));
    if (nargs != 2)
        ereport(ERROR,
                (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
                 errmsg("too many arguments"),
                 errhint("Provide two argument types for operator.")));

    result = OpernameGetOprid(names, argtypes[0], argtypes[1]);

    if (!OidIsValid(result))
        ereport(ERROR,
                (errcode(ERRCODE_UNDEFINED_FUNCTION),
                 errmsg("operator does not exist: %s", opr_name_or_oid)));

    PG_RETURN_OID(result);
}

Datum regoperatorout ( PG_FUNCTION_ARGS   ) 

Definition at line 760 of file regproc.c.

References format_operator(), InvalidOid, oprid(), PG_GETARG_OID, PG_RETURN_CSTRING, and pstrdup().

{
    Oid         oprid = PG_GETARG_OID(0);
    char       *result;

    if (oprid == InvalidOid)
        result = pstrdup("0");
    else
        result = format_operator(oprid);

    PG_RETURN_CSTRING(result);
}

Datum regoperatorrecv ( PG_FUNCTION_ARGS   ) 

Definition at line 777 of file regproc.c.

References oidrecv().

{
    /* Exactly the same as oidrecv, so share code */
    return oidrecv(fcinfo);
}

Datum regoperatorsend ( PG_FUNCTION_ARGS   ) 

Definition at line 787 of file regproc.c.

References oidsend().

{
    /* Exactly the same as oidsend, so share code */
    return oidsend(fcinfo);
}

Datum regoperin ( PG_FUNCTION_ARGS   ) 

Definition at line 431 of file regproc.c.

References AccessShareLock, Anum_pg_operator_oprname, BTEqualStrategyNumber, CStringGetDatum, DatumGetObjectId, DirectFunctionCall1, ereport, errcode(), errmsg(), ERROR, heap_close, heap_open(), HeapTupleGetOid, HeapTupleIsValid, InvalidOid, IsBootstrapProcessingMode, _FuncCandidateList::next, NULL, _FuncCandidateList::oid, oidin(), OperatorNameNspIndexId, OperatorRelationId, OpernameGetCandidates(), PG_GETARG_CSTRING, PG_RETURN_OID, ScanKeyInit(), SnapshotNow, stringToQualifiedNameList(), systable_beginscan(), systable_endscan(), and systable_getnext().

{
    char       *opr_name_or_oid = PG_GETARG_CSTRING(0);
    Oid         result = InvalidOid;
    List       *names;
    FuncCandidateList clist;

    /* '0' ? */
    if (strcmp(opr_name_or_oid, "0") == 0)
        PG_RETURN_OID(InvalidOid);

    /* Numeric OID? */
    if (opr_name_or_oid[0] >= '0' &&
        opr_name_or_oid[0] <= '9' &&
        strspn(opr_name_or_oid, "0123456789") == strlen(opr_name_or_oid))
    {
        result = DatumGetObjectId(DirectFunctionCall1(oidin,
                                          CStringGetDatum(opr_name_or_oid)));
        PG_RETURN_OID(result);
    }

    /* Else it's a name, possibly schema-qualified */

    /*
     * In bootstrap mode we assume the given name is not schema-qualified, and
     * just search pg_operator for a unique match.  This is needed for
     * initializing other system catalogs (pg_namespace may not exist yet, and
     * certainly there are no schemas other than pg_catalog).
     */
    if (IsBootstrapProcessingMode())
    {
        int         matches = 0;
        Relation    hdesc;
        ScanKeyData skey[1];
        SysScanDesc sysscan;
        HeapTuple   tuple;

        ScanKeyInit(&skey[0],
                    Anum_pg_operator_oprname,
                    BTEqualStrategyNumber, F_NAMEEQ,
                    CStringGetDatum(opr_name_or_oid));

        hdesc = heap_open(OperatorRelationId, AccessShareLock);
        sysscan = systable_beginscan(hdesc, OperatorNameNspIndexId, true,
                                     SnapshotNow, 1, skey);

        while (HeapTupleIsValid(tuple = systable_getnext(sysscan)))
        {
            result = HeapTupleGetOid(tuple);
            if (++matches > 1)
                break;
        }

        systable_endscan(sysscan);
        heap_close(hdesc, AccessShareLock);

        if (matches == 0)
            ereport(ERROR,
                    (errcode(ERRCODE_UNDEFINED_FUNCTION),
                     errmsg("operator does not exist: %s", opr_name_or_oid)));
        else if (matches > 1)
            ereport(ERROR,
                    (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
                     errmsg("more than one operator named %s",
                            opr_name_or_oid)));

        PG_RETURN_OID(result);
    }

    /*
     * Normal case: parse the name into components and see if it matches any
     * pg_operator entries in the current search path.
     */
    names = stringToQualifiedNameList(opr_name_or_oid);
    clist = OpernameGetCandidates(names, '\0');

    if (clist == NULL)
        ereport(ERROR,
                (errcode(ERRCODE_UNDEFINED_FUNCTION),
                 errmsg("operator does not exist: %s", opr_name_or_oid)));
    else if (clist->next != NULL)
        ereport(ERROR,
                (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
                 errmsg("more than one operator named %s",
                        opr_name_or_oid)));

    result = clist->oid;

    PG_RETURN_OID(result);
}

Datum regoperout ( PG_FUNCTION_ARGS   ) 

Definition at line 526 of file regproc.c.

References get_namespace_name(), GETSTRUCT, HeapTupleIsValid, InvalidOid, IsBootstrapProcessingMode, list_make1, makeString(), NAMEDATALEN, NameStr, _FuncCandidateList::next, NULL, ObjectIdGetDatum, _FuncCandidateList::oid, OpernameGetCandidates(), OPEROID, oprid(), palloc(), PG_GETARG_OID, PG_RETURN_CSTRING, pstrdup(), quote_identifier(), ReleaseSysCache(), SearchSysCache1, and snprintf().

{
    Oid         oprid = PG_GETARG_OID(0);
    char       *result;
    HeapTuple   opertup;

    if (oprid == InvalidOid)
    {
        result = pstrdup("0");
        PG_RETURN_CSTRING(result);
    }

    opertup = SearchSysCache1(OPEROID, ObjectIdGetDatum(oprid));

    if (HeapTupleIsValid(opertup))
    {
        Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
        char       *oprname = NameStr(operform->oprname);

        /*
         * In bootstrap mode, skip the fancy namespace stuff and just return
         * the oper name.  (This path is only needed for debugging output
         * anyway.)
         */
        if (IsBootstrapProcessingMode())
            result = pstrdup(oprname);
        else
        {
            FuncCandidateList clist;

            /*
             * Would this oper be found (uniquely!) by regoperin? If not,
             * qualify it.
             */
            clist = OpernameGetCandidates(list_make1(makeString(oprname)),
                                          '\0');
            if (clist != NULL && clist->next == NULL &&
                clist->oid == oprid)
                result = pstrdup(oprname);
            else
            {
                const char *nspname;

                nspname = get_namespace_name(operform->oprnamespace);
                nspname = quote_identifier(nspname);
                result = (char *) palloc(strlen(nspname) + strlen(oprname) + 2);
                sprintf(result, "%s.%s", nspname, oprname);
            }
        }

        ReleaseSysCache(opertup);
    }
    else
    {
        /*
         * If OID doesn't match any pg_operator entry, return it numerically
         */
        result = (char *) palloc(NAMEDATALEN);
        snprintf(result, NAMEDATALEN, "%u", oprid);
    }

    PG_RETURN_CSTRING(result);
}

Datum regoperrecv ( PG_FUNCTION_ARGS   ) 

Definition at line 594 of file regproc.c.

References oidrecv().

{
    /* Exactly the same as oidrecv, so share code */
    return oidrecv(fcinfo);
}

Datum regopersend ( PG_FUNCTION_ARGS   ) 

Definition at line 604 of file regproc.c.

References oidsend().

{
    /* Exactly the same as oidsend, so share code */
    return oidsend(fcinfo);
}

Datum regprocedurein ( PG_FUNCTION_ARGS   ) 

Definition at line 247 of file regproc.c.

References _FuncCandidateList::args, CStringGetDatum, DatumGetObjectId, DirectFunctionCall1, ereport, errcode(), errmsg(), ERROR, FuncnameGetCandidates(), InvalidOid, memcmp(), _FuncCandidateList::next, NIL, NULL, _FuncCandidateList::oid, oidin(), parseNameAndArgTypes(), PG_GETARG_CSTRING, and PG_RETURN_OID.

Referenced by convert_function_name().

{
    char       *pro_name_or_oid = PG_GETARG_CSTRING(0);
    RegProcedure result = InvalidOid;
    List       *names;
    int         nargs;
    Oid         argtypes[FUNC_MAX_ARGS];
    FuncCandidateList clist;

    /* '-' ? */
    if (strcmp(pro_name_or_oid, "-") == 0)
        PG_RETURN_OID(InvalidOid);

    /* Numeric OID? */
    if (pro_name_or_oid[0] >= '0' &&
        pro_name_or_oid[0] <= '9' &&
        strspn(pro_name_or_oid, "0123456789") == strlen(pro_name_or_oid))
    {
        result = DatumGetObjectId(DirectFunctionCall1(oidin,
                                          CStringGetDatum(pro_name_or_oid)));
        PG_RETURN_OID(result);
    }

    /*
     * Else it's a name and arguments.  Parse the name and arguments, look up
     * potential matches in the current namespace search list, and scan to see
     * which one exactly matches the given argument types.  (There will not be
     * more than one match.)
     *
     * XXX at present, this code will not work in bootstrap mode, hence this
     * datatype cannot be used for any system column that needs to receive
     * data during bootstrap.
     */
    parseNameAndArgTypes(pro_name_or_oid, false, &names, &nargs, argtypes);

    clist = FuncnameGetCandidates(names, nargs, NIL, false, false);

    for (; clist; clist = clist->next)
    {
        if (memcmp(clist->args, argtypes, nargs * sizeof(Oid)) == 0)
            break;
    }

    if (clist == NULL)
        ereport(ERROR,
                (errcode(ERRCODE_UNDEFINED_FUNCTION),
                 errmsg("function \"%s\" does not exist", pro_name_or_oid)));

    result = clist->oid;

    PG_RETURN_OID(result);
}

Datum regprocedureout ( PG_FUNCTION_ARGS   ) 

Definition at line 388 of file regproc.c.

References format_procedure(), InvalidOid, PG_GETARG_OID, PG_RETURN_CSTRING, and pstrdup().

{
    RegProcedure proid = PG_GETARG_OID(0);
    char       *result;

    if (proid == InvalidOid)
        result = pstrdup("-");
    else
        result = format_procedure(proid);

    PG_RETURN_CSTRING(result);
}

Datum regprocedurerecv ( PG_FUNCTION_ARGS   ) 

Definition at line 405 of file regproc.c.

References oidrecv().

{
    /* Exactly the same as oidrecv, so share code */
    return oidrecv(fcinfo);
}

Datum regproceduresend ( PG_FUNCTION_ARGS   ) 

Definition at line 415 of file regproc.c.

References oidsend().

{
    /* Exactly the same as oidsend, so share code */
    return oidsend(fcinfo);
}

Datum regprocin ( PG_FUNCTION_ARGS   ) 

Definition at line 63 of file regproc.c.

References AccessShareLock, Anum_pg_proc_proname, BTEqualStrategyNumber, CStringGetDatum, DatumGetObjectId, DirectFunctionCall1, ereport, errcode(), errmsg(), ERROR, FuncnameGetCandidates(), heap_close, heap_open(), HeapTupleGetOid, HeapTupleIsValid, InvalidOid, IsBootstrapProcessingMode, _FuncCandidateList::next, NIL, NULL, _FuncCandidateList::oid, oidin(), PG_GETARG_CSTRING, PG_RETURN_OID, ProcedureNameArgsNspIndexId, ProcedureRelationId, ScanKeyInit(), SnapshotNow, stringToQualifiedNameList(), systable_beginscan(), systable_endscan(), and systable_getnext().

{
    char       *pro_name_or_oid = PG_GETARG_CSTRING(0);
    RegProcedure result = InvalidOid;
    List       *names;
    FuncCandidateList clist;

    /* '-' ? */
    if (strcmp(pro_name_or_oid, "-") == 0)
        PG_RETURN_OID(InvalidOid);

    /* Numeric OID? */
    if (pro_name_or_oid[0] >= '0' &&
        pro_name_or_oid[0] <= '9' &&
        strspn(pro_name_or_oid, "0123456789") == strlen(pro_name_or_oid))
    {
        result = DatumGetObjectId(DirectFunctionCall1(oidin,
                                          CStringGetDatum(pro_name_or_oid)));
        PG_RETURN_OID(result);
    }

    /* Else it's a name, possibly schema-qualified */

    /*
     * In bootstrap mode we assume the given name is not schema-qualified, and
     * just search pg_proc for a unique match.  This is needed for
     * initializing other system catalogs (pg_namespace may not exist yet, and
     * certainly there are no schemas other than pg_catalog).
     */
    if (IsBootstrapProcessingMode())
    {
        int         matches = 0;
        Relation    hdesc;
        ScanKeyData skey[1];
        SysScanDesc sysscan;
        HeapTuple   tuple;

        ScanKeyInit(&skey[0],
                    Anum_pg_proc_proname,
                    BTEqualStrategyNumber, F_NAMEEQ,
                    CStringGetDatum(pro_name_or_oid));

        hdesc = heap_open(ProcedureRelationId, AccessShareLock);
        sysscan = systable_beginscan(hdesc, ProcedureNameArgsNspIndexId, true,
                                     SnapshotNow, 1, skey);

        while (HeapTupleIsValid(tuple = systable_getnext(sysscan)))
        {
            result = (RegProcedure) HeapTupleGetOid(tuple);
            if (++matches > 1)
                break;
        }

        systable_endscan(sysscan);
        heap_close(hdesc, AccessShareLock);

        if (matches == 0)
            ereport(ERROR,
                    (errcode(ERRCODE_UNDEFINED_FUNCTION),
                 errmsg("function \"%s\" does not exist", pro_name_or_oid)));

        else if (matches > 1)
            ereport(ERROR,
                    (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
                     errmsg("more than one function named \"%s\"",
                            pro_name_or_oid)));

        PG_RETURN_OID(result);
    }

    /*
     * Normal case: parse the name into components and see if it matches any
     * pg_proc entries in the current search path.
     */
    names = stringToQualifiedNameList(pro_name_or_oid);
    clist = FuncnameGetCandidates(names, -1, NIL, false, false);

    if (clist == NULL)
        ereport(ERROR,
                (errcode(ERRCODE_UNDEFINED_FUNCTION),
                 errmsg("function \"%s\" does not exist", pro_name_or_oid)));
    else if (clist->next != NULL)
        ereport(ERROR,
                (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
                 errmsg("more than one function named \"%s\"",
                        pro_name_or_oid)));

    result = clist->oid;

    PG_RETURN_OID(result);
}

Datum regprocout ( PG_FUNCTION_ARGS   ) 

Definition at line 159 of file regproc.c.

References FuncnameGetCandidates(), get_namespace_name(), GETSTRUCT, HeapTupleIsValid, InvalidOid, IsBootstrapProcessingMode, list_make1, makeString(), NAMEDATALEN, NameStr, _FuncCandidateList::next, NIL, NULL, ObjectIdGetDatum, _FuncCandidateList::oid, palloc(), PG_GETARG_OID, PG_RETURN_CSTRING, PROCOID, pstrdup(), quote_qualified_identifier(), ReleaseSysCache(), SearchSysCache1, and snprintf().

{
    RegProcedure proid = PG_GETARG_OID(0);
    char       *result;
    HeapTuple   proctup;

    if (proid == InvalidOid)
    {
        result = pstrdup("-");
        PG_RETURN_CSTRING(result);
    }

    proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(proid));

    if (HeapTupleIsValid(proctup))
    {
        Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
        char       *proname = NameStr(procform->proname);

        /*
         * In bootstrap mode, skip the fancy namespace stuff and just return
         * the proc name.  (This path is only needed for debugging output
         * anyway.)
         */
        if (IsBootstrapProcessingMode())
            result = pstrdup(proname);
        else
        {
            char       *nspname;
            FuncCandidateList clist;

            /*
             * Would this proc be found (uniquely!) by regprocin? If not,
             * qualify it.
             */
            clist = FuncnameGetCandidates(list_make1(makeString(proname)),
                                          -1, NIL, false, false);
            if (clist != NULL && clist->next == NULL &&
                clist->oid == proid)
                nspname = NULL;
            else
                nspname = get_namespace_name(procform->pronamespace);

            result = quote_qualified_identifier(nspname, proname);
        }

        ReleaseSysCache(proctup);
    }
    else
    {
        /* If OID doesn't match any pg_proc entry, return it numerically */
        result = (char *) palloc(NAMEDATALEN);
        snprintf(result, NAMEDATALEN, "%u", proid);
    }

    PG_RETURN_CSTRING(result);
}

Datum regprocrecv ( PG_FUNCTION_ARGS   ) 

Definition at line 221 of file regproc.c.

References oidrecv().

{
    /* Exactly the same as oidrecv, so share code */
    return oidrecv(fcinfo);
}

Datum regprocsend ( PG_FUNCTION_ARGS   ) 

Definition at line 231 of file regproc.c.

References oidsend().

{
    /* Exactly the same as oidsend, so share code */
    return oidsend(fcinfo);
}

Datum regtypein ( PG_FUNCTION_ARGS   ) 

Definition at line 967 of file regproc.c.

References AccessShareLock, Anum_pg_type_typname, BTEqualStrategyNumber, CStringGetDatum, DatumGetObjectId, DirectFunctionCall1, ereport, errcode(), errmsg(), ERROR, heap_close, heap_open(), HeapTupleGetOid, HeapTupleIsValid, InvalidOid, IsBootstrapProcessingMode, oidin(), parseTypeString(), PG_GETARG_CSTRING, PG_RETURN_OID, ScanKeyInit(), SnapshotNow, systable_beginscan(), systable_endscan(), systable_getnext(), TypeNameNspIndexId, and TypeRelationId.

Referenced by convert_type_name(), and plperl_sv_to_literal().

{
    char       *typ_name_or_oid = PG_GETARG_CSTRING(0);
    Oid         result = InvalidOid;
    int32       typmod;

    /* '-' ? */
    if (strcmp(typ_name_or_oid, "-") == 0)
        PG_RETURN_OID(InvalidOid);

    /* Numeric OID? */
    if (typ_name_or_oid[0] >= '0' &&
        typ_name_or_oid[0] <= '9' &&
        strspn(typ_name_or_oid, "0123456789") == strlen(typ_name_or_oid))
    {
        result = DatumGetObjectId(DirectFunctionCall1(oidin,
                                          CStringGetDatum(typ_name_or_oid)));
        PG_RETURN_OID(result);
    }

    /* Else it's a type name, possibly schema-qualified or decorated */

    /*
     * In bootstrap mode we assume the given name is not schema-qualified, and
     * just search pg_type for a match.  This is needed for initializing other
     * system catalogs (pg_namespace may not exist yet, and certainly there
     * are no schemas other than pg_catalog).
     */
    if (IsBootstrapProcessingMode())
    {
        Relation    hdesc;
        ScanKeyData skey[1];
        SysScanDesc sysscan;
        HeapTuple   tuple;

        ScanKeyInit(&skey[0],
                    Anum_pg_type_typname,
                    BTEqualStrategyNumber, F_NAMEEQ,
                    CStringGetDatum(typ_name_or_oid));

        hdesc = heap_open(TypeRelationId, AccessShareLock);
        sysscan = systable_beginscan(hdesc, TypeNameNspIndexId, true,
                                     SnapshotNow, 1, skey);

        if (HeapTupleIsValid(tuple = systable_getnext(sysscan)))
            result = HeapTupleGetOid(tuple);
        else
            ereport(ERROR,
                    (errcode(ERRCODE_UNDEFINED_OBJECT),
                     errmsg("type \"%s\" does not exist", typ_name_or_oid)));

        /* We assume there can be only one match */

        systable_endscan(sysscan);
        heap_close(hdesc, AccessShareLock);

        PG_RETURN_OID(result);
    }

    /*
     * Normal case: invoke the full parser to deal with special cases such as
     * array syntax.
     */
    parseTypeString(typ_name_or_oid, &result, &typmod);

    PG_RETURN_OID(result);
}

Datum regtypeout ( PG_FUNCTION_ARGS   ) 

Definition at line 1039 of file regproc.c.

References format_type_be(), GETSTRUCT, HeapTupleIsValid, InvalidOid, IsBootstrapProcessingMode, NAMEDATALEN, NameStr, ObjectIdGetDatum, palloc(), PG_GETARG_OID, PG_RETURN_CSTRING, pstrdup(), ReleaseSysCache(), SearchSysCache1, snprintf(), and TYPEOID.

{
    Oid         typid = PG_GETARG_OID(0);
    char       *result;
    HeapTuple   typetup;

    if (typid == InvalidOid)
    {
        result = pstrdup("-");
        PG_RETURN_CSTRING(result);
    }

    typetup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));

    if (HeapTupleIsValid(typetup))
    {
        Form_pg_type typeform = (Form_pg_type) GETSTRUCT(typetup);

        /*
         * In bootstrap mode, skip the fancy namespace stuff and just return
         * the type name.  (This path is only needed for debugging output
         * anyway.)
         */
        if (IsBootstrapProcessingMode())
        {
            char       *typname = NameStr(typeform->typname);

            result = pstrdup(typname);
        }
        else
            result = format_type_be(typid);

        ReleaseSysCache(typetup);
    }
    else
    {
        /* If OID doesn't match any pg_type entry, return it numerically */
        result = (char *) palloc(NAMEDATALEN);
        snprintf(result, NAMEDATALEN, "%u", typid);
    }

    PG_RETURN_CSTRING(result);
}

Datum regtyperecv ( PG_FUNCTION_ARGS   ) 

Definition at line 1087 of file regproc.c.

References oidrecv().

{
    /* Exactly the same as oidrecv, so share code */
    return oidrecv(fcinfo);
}

Datum regtypesend ( PG_FUNCTION_ARGS   ) 

Definition at line 1097 of file regproc.c.

References oidsend().

{
    /* Exactly the same as oidsend, so share code */
    return oidsend(fcinfo);
}

Datum repeat ( PG_FUNCTION_ARGS   ) 

Definition at line 1022 of file oracle_compat.c.

References ereport, errcode(), errmsg(), ERROR, i, palloc(), PG_GETARG_INT32, PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, SET_VARSIZE, VARDATA, VARDATA_ANY, VARHDRSZ, and VARSIZE_ANY_EXHDR.

{
    text       *string = PG_GETARG_TEXT_PP(0);
    int32       count = PG_GETARG_INT32(1);
    text       *result;
    int         slen,
                tlen;
    int         i;
    char       *cp,
               *sp;

    if (count < 0)
        count = 0;

    slen = VARSIZE_ANY_EXHDR(string);
    tlen = VARHDRSZ + (count * slen);

    /* Check for integer overflow */
    if (slen != 0 && count != 0)
    {
        int         check = count * slen;
        int         check2 = check + VARHDRSZ;

        if ((check / slen) != count || check2 <= check)
            ereport(ERROR,
                    (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                     errmsg("requested length too large")));
    }

    result = (text *) palloc(tlen);

    SET_VARSIZE(result, tlen);
    cp = VARDATA(result);
    sp = VARDATA_ANY(string);
    for (i = 0; i < count; i++)
    {
        memcpy(cp, sp, slen);
        cp += slen;
    }

    PG_RETURN_TEXT_P(result);
}

Datum replace_text ( PG_FUNCTION_ARGS   ) 

Definition at line 2766 of file varlena.c.

References appendBinaryStringInfo(), appendStringInfoText(), charlen_to_bytelen(), CHECK_FOR_INTERRUPTS, cstring_to_text_with_len(), StringInfoData::data, initStringInfo(), StringInfoData::len, TextPositionState::len1, TextPositionState::len2, pfree(), PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, text_position_cleanup(), text_position_next(), text_position_setup(), VARDATA_ANY, and VARSIZE_ANY.

Referenced by execute_extension_script().

{
    text       *src_text = PG_GETARG_TEXT_PP(0);
    text       *from_sub_text = PG_GETARG_TEXT_PP(1);
    text       *to_sub_text = PG_GETARG_TEXT_PP(2);
    int         src_text_len;
    int         from_sub_text_len;
    TextPositionState state;
    text       *ret_text;
    int         start_posn;
    int         curr_posn;
    int         chunk_len;
    char       *start_ptr;
    StringInfoData str;

    text_position_setup(src_text, from_sub_text, &state);

    /*
     * Note: we check the converted string length, not the original, because
     * they could be different if the input contained invalid encoding.
     */
    src_text_len = state.len1;
    from_sub_text_len = state.len2;

    /* Return unmodified source string if empty source or pattern */
    if (src_text_len < 1 || from_sub_text_len < 1)
    {
        text_position_cleanup(&state);
        PG_RETURN_TEXT_P(src_text);
    }

    start_posn = 1;
    curr_posn = text_position_next(1, &state);

    /* When the from_sub_text is not found, there is nothing to do. */
    if (curr_posn == 0)
    {
        text_position_cleanup(&state);
        PG_RETURN_TEXT_P(src_text);
    }

    /* start_ptr points to the start_posn'th character of src_text */
    start_ptr = VARDATA_ANY(src_text);

    initStringInfo(&str);

    do
    {
        CHECK_FOR_INTERRUPTS();

        /* copy the data skipped over by last text_position_next() */
        chunk_len = charlen_to_bytelen(start_ptr, curr_posn - start_posn);
        appendBinaryStringInfo(&str, start_ptr, chunk_len);

        appendStringInfoText(&str, to_sub_text);

        start_posn = curr_posn;
        start_ptr += chunk_len;
        start_posn += from_sub_text_len;
        start_ptr += charlen_to_bytelen(start_ptr, from_sub_text_len);

        curr_posn = text_position_next(start_posn, &state);
    }
    while (curr_posn > 0);

    /* copy trailing data */
    chunk_len = ((char *) src_text + VARSIZE_ANY(src_text)) - start_ptr;
    appendBinaryStringInfo(&str, start_ptr, chunk_len);

    text_position_cleanup(&state);

    ret_text = cstring_to_text_with_len(str.data, str.len);
    pfree(str.data);

    PG_RETURN_TEXT_P(ret_text);
}

text* replace_text_regexp ( text src_text,
void *  regexp,
text replace_text,
bool  glob 
)

Definition at line 2987 of file varlena.c.

References appendBinaryStringInfo(), appendStringInfoRegexpSubstr(), appendStringInfoText(), buf, charlen_to_bytelen(), CHECK_FOR_INTERRUPTS, check_replace_text_has_escape_char(), cstring_to_text_with_len(), StringInfoData::data, ereport, errcode(), errmsg(), ERROR, initStringInfo(), StringInfoData::len, NULL, palloc(), pfree(), pg_mb2wchar_with_len(), pg_regerror(), pg_regexec(), REG_NOMATCH, REG_OKAY, REGEXP_REPLACE_BACKREF_CNT, regmatch_t::rm_eo, regmatch_t::rm_so, VARDATA_ANY, VARSIZE_ANY, and VARSIZE_ANY_EXHDR.

Referenced by textregexreplace(), and textregexreplace_noopt().

{
    text       *ret_text;
    regex_t    *re = (regex_t *) regexp;
    int         src_text_len = VARSIZE_ANY_EXHDR(src_text);
    StringInfoData buf;
    regmatch_t  pmatch[REGEXP_REPLACE_BACKREF_CNT];
    pg_wchar   *data;
    size_t      data_len;
    int         search_start;
    int         data_pos;
    char       *start_ptr;
    bool        have_escape;

    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 escape char. */
    have_escape = check_replace_text_has_escape_char(replace_text);

    /* start_ptr points to the data_pos'th character of src_text */
    start_ptr = (char *) VARDATA_ANY(src_text);
    data_pos = 0;

    search_start = 0;
    while (search_start <= data_len)
    {
        int         regexec_result;

        CHECK_FOR_INTERRUPTS();

        regexec_result = pg_regexec(re,
                                    data,
                                    data_len,
                                    search_start,
                                    NULL,       /* no details */
                                    REGEXP_REPLACE_BACKREF_CNT,
                                    pmatch,
                                    0);

        if (regexec_result == REG_NOMATCH)
            break;

        if (regexec_result != REG_OKAY)
        {
            char        errMsg[100];

            pg_regerror(regexec_result, re, errMsg, sizeof(errMsg));
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_REGULAR_EXPRESSION),
                     errmsg("regular expression failed: %s", errMsg)));
        }

        /*
         * Copy the text to the left of the match position.  Note we are given
         * character not byte indexes.
         */
        if (pmatch[0].rm_so - data_pos > 0)
        {
            int         chunk_len;

            chunk_len = charlen_to_bytelen(start_ptr,
                                           pmatch[0].rm_so - data_pos);
            appendBinaryStringInfo(&buf, start_ptr, chunk_len);

            /*
             * Advance start_ptr over that text, to avoid multiple rescans of
             * it if the replace_text contains multiple back-references.
             */
            start_ptr += chunk_len;
            data_pos = pmatch[0].rm_so;
        }

        /*
         * Copy the replace_text. Process back references when the
         * replace_text has escape characters.
         */
        if (have_escape)
            appendStringInfoRegexpSubstr(&buf, replace_text, pmatch,
                                         start_ptr, data_pos);
        else
            appendStringInfoText(&buf, replace_text);

        /* Advance start_ptr and data_pos over the matched text. */
        start_ptr += charlen_to_bytelen(start_ptr,
                                        pmatch[0].rm_eo - data_pos);
        data_pos = pmatch[0].rm_eo;

        /*
         * When global option is off, replace the first instance only.
         */
        if (!glob)
            break;

        /*
         * Search from next character when the matching text is zero width.
         */
        search_start = data_pos;
        if (pmatch[0].rm_so == pmatch[0].rm_eo)
            search_start++;
    }

    /*
     * Copy the text to the right of the last match.
     */
    if (data_pos < data_len)
    {
        int         chunk_len;

        chunk_len = ((char *) src_text + VARSIZE_ANY(src_text)) - start_ptr;
        appendBinaryStringInfo(&buf, start_ptr, chunk_len);
    }

    ret_text = cstring_to_text_with_len(buf.data, buf.len);
    pfree(buf.data);
    pfree(data);

    return ret_text;
}

Datum RI_FKey_cascade_del ( PG_FUNCTION_ARGS   ) 

Definition at line 1030 of file ri_triggers.c.

References appendStringInfo(), StringInfoData::data, elog, ereport, errcode(), errmsg(), ERROR, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, heap_close, heap_open(), i, initStringInfo(), NULL, PointerGetDatum, quoteOneName(), quoteRelationName(), ri_BuildQueryKey(), ri_CheckTrigger(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL, RI_KEYS_SOME_NULL, ri_NullCheck(), ri_PerformCheck(), RI_PLAN_CASCADE_DEL_DODELETE, ri_PlanCheck(), RI_TRIGTYPE_DELETE, RIAttName, RIAttType, RowExclusiveLock, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_DELETE, SPI_OK_FINISH, TriggerData::tg_relation, TriggerData::tg_trigger, and TriggerData::tg_trigtuple.

{
    TriggerData *trigdata = (TriggerData *) fcinfo->context;
    const RI_ConstraintInfo *riinfo;
    Relation    fk_rel;
    Relation    pk_rel;
    HeapTuple   old_row;
    RI_QueryKey qkey;
    SPIPlanPtr  qplan;
    int         i;

    /*
     * Check that this is a valid trigger call on the right time and event.
     */
    ri_CheckTrigger(fcinfo, "RI_FKey_cascade_del", RI_TRIGTYPE_DELETE);

    /*
     * Get arguments.
     */
    riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
                                    trigdata->tg_relation, true);

    /*
     * Get the relation descriptors of the FK and PK tables and the old tuple.
     *
     * fk_rel is opened in RowExclusiveLock mode since that's what our
     * eventual DELETE will get on it.
     */
    fk_rel = heap_open(riinfo->fk_relid, RowExclusiveLock);
    pk_rel = trigdata->tg_relation;
    old_row = trigdata->tg_trigtuple;

    switch (riinfo->confmatchtype)
    {
            /* ----------
             * SQL:2008 15.17 <Execution of referential actions>
             *  General rules 9) a) i):
             *      MATCH SIMPLE/FULL
             *          ... ON DELETE CASCADE
             * ----------
             */
        case FKCONSTR_MATCH_SIMPLE:
        case FKCONSTR_MATCH_FULL:
            switch (ri_NullCheck(old_row, riinfo, true))
            {
                case RI_KEYS_ALL_NULL:
                case RI_KEYS_SOME_NULL:

                    /*
                     * No check needed - there cannot be any reference to old
                     * key if it contains a NULL
                     */
                    heap_close(fk_rel, RowExclusiveLock);
                    return PointerGetDatum(NULL);

                case RI_KEYS_NONE_NULL:

                    /*
                     * Have a full qualified key - continue below
                     */
                    break;
            }

            if (SPI_connect() != SPI_OK_CONNECT)
                elog(ERROR, "SPI_connect failed");

            /*
             * Fetch or prepare a saved plan for the cascaded delete
             */
            ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_CASCADE_DEL_DODELETE);

            if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
            {
                StringInfoData querybuf;
                char        fkrelname[MAX_QUOTED_REL_NAME_LEN];
                char        attname[MAX_QUOTED_NAME_LEN];
                char        paramname[16];
                const char *querysep;
                Oid         queryoids[RI_MAX_NUMKEYS];

                /* ----------
                 * The query string built is
                 *  DELETE FROM ONLY <fktable> WHERE $1 = fkatt1 [AND ...]
                 * The type id's for the $ parameters are those of the
                 * corresponding PK attributes.
                 * ----------
                 */
                initStringInfo(&querybuf);
                quoteRelationName(fkrelname, fk_rel);
                appendStringInfo(&querybuf, "DELETE FROM ONLY %s", fkrelname);
                querysep = "WHERE";
                for (i = 0; i < riinfo->nkeys; i++)
                {
                    Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
                    Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);

                    quoteOneName(attname,
                                 RIAttName(fk_rel, riinfo->fk_attnums[i]));
                    sprintf(paramname, "$%d", i + 1);
                    ri_GenerateQual(&querybuf, querysep,
                                    paramname, pk_type,
                                    riinfo->pf_eq_oprs[i],
                                    attname, fk_type);
                    querysep = "AND";
                    queryoids[i] = pk_type;
                }

                /* Prepare and save the plan */
                qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
                                     &qkey, fk_rel, pk_rel, true);
            }

            /*
             * We have a plan now. Build up the arguments from the key values
             * in the deleted PK tuple and delete the referencing rows
             */
            ri_PerformCheck(riinfo, &qkey, qplan,
                            fk_rel, pk_rel,
                            old_row, NULL,
                            true,       /* must detect new rows */
                            SPI_OK_DELETE);

            if (SPI_finish() != SPI_OK_FINISH)
                elog(ERROR, "SPI_finish failed");

            heap_close(fk_rel, RowExclusiveLock);

            return PointerGetDatum(NULL);

            /*
             * Handle MATCH PARTIAL cascaded delete.
             */
        case FKCONSTR_MATCH_PARTIAL:
            ereport(ERROR,
                    (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                     errmsg("MATCH PARTIAL not yet implemented")));
            return PointerGetDatum(NULL);

        default:
            elog(ERROR, "unrecognized confmatchtype: %d",
                 riinfo->confmatchtype);
            break;
    }

    /* Never reached */
    return PointerGetDatum(NULL);
}

Datum RI_FKey_cascade_upd ( PG_FUNCTION_ARGS   ) 

Definition at line 1186 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), StringInfoData::data, elog, ereport, errcode(), errmsg(), ERROR, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, heap_close, heap_open(), i, initStringInfo(), NULL, PointerGetDatum, quoteOneName(), quoteRelationName(), ri_BuildQueryKey(), ri_CheckTrigger(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL, RI_KEYS_SOME_NULL, ri_KeysEqual(), RI_MAX_NUMKEYS, ri_NullCheck(), ri_PerformCheck(), RI_PLAN_CASCADE_UPD_DOUPDATE, ri_PlanCheck(), RI_TRIGTYPE_UPDATE, RIAttName, RIAttType, RowExclusiveLock, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_OK_UPDATE, TriggerData::tg_newtuple, TriggerData::tg_relation, TriggerData::tg_trigger, and TriggerData::tg_trigtuple.

{
    TriggerData *trigdata = (TriggerData *) fcinfo->context;
    const RI_ConstraintInfo *riinfo;
    Relation    fk_rel;
    Relation    pk_rel;
    HeapTuple   new_row;
    HeapTuple   old_row;
    RI_QueryKey qkey;
    SPIPlanPtr  qplan;
    int         i;
    int         j;

    /*
     * Check that this is a valid trigger call on the right time and event.
     */
    ri_CheckTrigger(fcinfo, "RI_FKey_cascade_upd", RI_TRIGTYPE_UPDATE);

    /*
     * Get arguments.
     */
    riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
                                    trigdata->tg_relation, true);

    /*
     * Get the relation descriptors of the FK and PK tables and the new and
     * old tuple.
     *
     * fk_rel is opened in RowExclusiveLock mode since that's what our
     * eventual UPDATE will get on it.
     */
    fk_rel = heap_open(riinfo->fk_relid, RowExclusiveLock);
    pk_rel = trigdata->tg_relation;
    new_row = trigdata->tg_newtuple;
    old_row = trigdata->tg_trigtuple;

    switch (riinfo->confmatchtype)
    {
            /* ----------
             * SQL:2008 15.17 <Execution of referential actions>
             *  General rules 10) a) i):
             *      MATCH SIMPLE/FULL
             *          ... ON UPDATE CASCADE
             * ----------
             */
        case FKCONSTR_MATCH_SIMPLE:
        case FKCONSTR_MATCH_FULL:
            switch (ri_NullCheck(old_row, riinfo, true))
            {
                case RI_KEYS_ALL_NULL:
                case RI_KEYS_SOME_NULL:

                    /*
                     * No check needed - there cannot be any reference to old
                     * key if it contains a NULL
                     */
                    heap_close(fk_rel, RowExclusiveLock);
                    return PointerGetDatum(NULL);

                case RI_KEYS_NONE_NULL:

                    /*
                     * Have a full qualified key - continue below
                     */
                    break;
            }

            /*
             * No need to do anything if old and new keys are equal
             */
            if (ri_KeysEqual(pk_rel, old_row, new_row, riinfo, true))
            {
                heap_close(fk_rel, RowExclusiveLock);
                return PointerGetDatum(NULL);
            }

            if (SPI_connect() != SPI_OK_CONNECT)
                elog(ERROR, "SPI_connect failed");

            /*
             * Fetch or prepare a saved plan for the cascaded update
             */
            ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_CASCADE_UPD_DOUPDATE);

            if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
            {
                StringInfoData querybuf;
                StringInfoData qualbuf;
                char        fkrelname[MAX_QUOTED_REL_NAME_LEN];
                char        attname[MAX_QUOTED_NAME_LEN];
                char        paramname[16];
                const char *querysep;
                const char *qualsep;
                Oid         queryoids[RI_MAX_NUMKEYS * 2];

                /* ----------
                 * The query string built is
                 *  UPDATE ONLY <fktable> SET fkatt1 = $1 [, ...]
                 *          WHERE $n = fkatt1 [AND ...]
                 * The type id's for the $ parameters are those of the
                 * corresponding PK attributes.  Note that we are assuming
                 * there is an assignment cast from the PK to the FK type;
                 * else the parser will fail.
                 * ----------
                 */
                initStringInfo(&querybuf);
                initStringInfo(&qualbuf);
                quoteRelationName(fkrelname, fk_rel);
                appendStringInfo(&querybuf, "UPDATE ONLY %s SET", fkrelname);
                querysep = "";
                qualsep = "WHERE";
                for (i = 0, j = riinfo->nkeys; i < riinfo->nkeys; i++, j++)
                {
                    Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
                    Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);

                    quoteOneName(attname,
                                 RIAttName(fk_rel, riinfo->fk_attnums[i]));
                    appendStringInfo(&querybuf,
                                     "%s %s = $%d",
                                     querysep, attname, i + 1);
                    sprintf(paramname, "$%d", j + 1);
                    ri_GenerateQual(&qualbuf, qualsep,
                                    paramname, pk_type,
                                    riinfo->pf_eq_oprs[i],
                                    attname, fk_type);
                    querysep = ",";
                    qualsep = "AND";
                    queryoids[i] = pk_type;
                    queryoids[j] = pk_type;
                }
                appendStringInfoString(&querybuf, qualbuf.data);

                /* Prepare and save the plan */
                qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys * 2, queryoids,
                                     &qkey, fk_rel, pk_rel, true);
            }

            /*
             * We have a plan now. Run it to update the existing references.
             */
            ri_PerformCheck(riinfo, &qkey, qplan,
                            fk_rel, pk_rel,
                            old_row, new_row,
                            true,       /* must detect new rows */
                            SPI_OK_UPDATE);

            if (SPI_finish() != SPI_OK_FINISH)
                elog(ERROR, "SPI_finish failed");

            heap_close(fk_rel, RowExclusiveLock);

            return PointerGetDatum(NULL);

            /*
             * Handle MATCH PARTIAL cascade update.
             */
        case FKCONSTR_MATCH_PARTIAL:
            ereport(ERROR,
                    (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                     errmsg("MATCH PARTIAL not yet implemented")));
            return PointerGetDatum(NULL);

        default:
            elog(ERROR, "unrecognized confmatchtype: %d",
                 riinfo->confmatchtype);
            break;
    }

    /* Never reached */
    return PointerGetDatum(NULL);
}

Datum RI_FKey_check_ins ( PG_FUNCTION_ARGS   ) 

Definition at line 462 of file ri_triggers.c.

References ri_CheckTrigger(), RI_FKey_check(), and RI_TRIGTYPE_INSERT.

Referenced by validateForeignKeyConstraint().

{
    /*
     * Check that this is a valid trigger call on the right time and event.
     */
    ri_CheckTrigger(fcinfo, "RI_FKey_check_ins", RI_TRIGTYPE_INSERT);

    /*
     * Share code with UPDATE case.
     */
    return RI_FKey_check((TriggerData *) fcinfo->context);
}

Datum RI_FKey_check_upd ( PG_FUNCTION_ARGS   ) 

Definition at line 483 of file ri_triggers.c.

References ri_CheckTrigger(), RI_FKey_check(), and RI_TRIGTYPE_UPDATE.

{
    /*
     * Check that this is a valid trigger call on the right time and event.
     */
    ri_CheckTrigger(fcinfo, "RI_FKey_check_upd", RI_TRIGTYPE_UPDATE);

    /*
     * Share code with INSERT case.
     */
    return RI_FKey_check((TriggerData *) fcinfo->context);
}

Datum RI_FKey_noaction_del ( PG_FUNCTION_ARGS   ) 

Definition at line 597 of file ri_triggers.c.

References ri_CheckTrigger(), ri_restrict_del(), and RI_TRIGTYPE_DELETE.

Referenced by RI_FKey_setdefault_del().

{
    /*
     * Check that this is a valid trigger call on the right time and event.
     */
    ri_CheckTrigger(fcinfo, "RI_FKey_noaction_del", RI_TRIGTYPE_DELETE);

    /*
     * Share code with RESTRICT case.
     */
    return ri_restrict_del((TriggerData *) fcinfo->context, true);
}

Datum RI_FKey_noaction_upd ( PG_FUNCTION_ARGS   ) 

Definition at line 809 of file ri_triggers.c.

References ri_CheckTrigger(), ri_restrict_upd(), and RI_TRIGTYPE_UPDATE.

Referenced by RI_FKey_setdefault_upd().

{
    /*
     * Check that this is a valid trigger call on the right time and event.
     */
    ri_CheckTrigger(fcinfo, "RI_FKey_noaction_upd", RI_TRIGTYPE_UPDATE);

    /*
     * Share code with RESTRICT case.
     */
    return ri_restrict_upd((TriggerData *) fcinfo->context, true);
}

Datum RI_FKey_restrict_del ( PG_FUNCTION_ARGS   ) 

Definition at line 622 of file ri_triggers.c.

References ri_CheckTrigger(), ri_restrict_del(), and RI_TRIGTYPE_DELETE.

{
    /*
     * Check that this is a valid trigger call on the right time and event.
     */
    ri_CheckTrigger(fcinfo, "RI_FKey_restrict_del", RI_TRIGTYPE_DELETE);

    /*
     * Share code with NO ACTION case.
     */
    return ri_restrict_del((TriggerData *) fcinfo->context, false);
}

Datum RI_FKey_restrict_upd ( PG_FUNCTION_ARGS   ) 

Definition at line 834 of file ri_triggers.c.

References ri_CheckTrigger(), ri_restrict_upd(), and RI_TRIGTYPE_UPDATE.

{
    /*
     * Check that this is a valid trigger call on the right time and event.
     */
    ri_CheckTrigger(fcinfo, "RI_FKey_restrict_upd", RI_TRIGTYPE_UPDATE);

    /*
     * Share code with NO ACTION case.
     */
    return ri_restrict_upd((TriggerData *) fcinfo->context, false);
}

Datum RI_FKey_setdefault_del ( PG_FUNCTION_ARGS   ) 

Definition at line 1708 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), StringInfoData::data, elog, ereport, errcode(), errmsg(), ERROR, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, heap_close, heap_open(), i, initStringInfo(), NULL, PointerGetDatum, quoteOneName(), quoteRelationName(), ri_BuildQueryKey(), ri_CheckTrigger(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), RI_FKey_noaction_del(), ri_GenerateQual(), RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL, RI_KEYS_SOME_NULL, ri_NullCheck(), ri_PerformCheck(), RI_PLAN_SETDEFAULT_DEL_DOUPDATE, ri_PlanCheck(), RI_TRIGTYPE_DELETE, RIAttName, RIAttType, RowExclusiveLock, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_OK_UPDATE, TriggerData::tg_relation, TriggerData::tg_trigger, and TriggerData::tg_trigtuple.

{
    TriggerData *trigdata = (TriggerData *) fcinfo->context;
    const RI_ConstraintInfo *riinfo;
    Relation    fk_rel;
    Relation    pk_rel;
    HeapTuple   old_row;
    RI_QueryKey qkey;
    SPIPlanPtr  qplan;

    /*
     * Check that this is a valid trigger call on the right time and event.
     */
    ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_del", RI_TRIGTYPE_DELETE);

    /*
     * Get arguments.
     */
    riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
                                    trigdata->tg_relation, true);

    /*
     * Get the relation descriptors of the FK and PK tables and the old tuple.
     *
     * fk_rel is opened in RowExclusiveLock mode since that's what our
     * eventual UPDATE will get on it.
     */
    fk_rel = heap_open(riinfo->fk_relid, RowExclusiveLock);
    pk_rel = trigdata->tg_relation;
    old_row = trigdata->tg_trigtuple;

    switch (riinfo->confmatchtype)
    {
            /* ----------
             * SQL:2008 15.17 <Execution of referential actions>
             *  General rules 9) a) iii):
             *      MATCH SIMPLE/FULL
             *          ... ON DELETE SET DEFAULT
             * ----------
             */
        case FKCONSTR_MATCH_SIMPLE:
        case FKCONSTR_MATCH_FULL:
            switch (ri_NullCheck(old_row, riinfo, true))
            {
                case RI_KEYS_ALL_NULL:
                case RI_KEYS_SOME_NULL:

                    /*
                     * No check needed - there cannot be any reference to old
                     * key if it contains a NULL
                     */
                    heap_close(fk_rel, RowExclusiveLock);
                    return PointerGetDatum(NULL);

                case RI_KEYS_NONE_NULL:

                    /*
                     * Have a full qualified key - continue below
                     */
                    break;
            }

            if (SPI_connect() != SPI_OK_CONNECT)
                elog(ERROR, "SPI_connect failed");

            /*
             * Fetch or prepare a saved plan for the set default delete
             * operation
             */
            ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_SETDEFAULT_DEL_DOUPDATE);

            if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
            {
                StringInfoData querybuf;
                StringInfoData qualbuf;
                char        fkrelname[MAX_QUOTED_REL_NAME_LEN];
                char        attname[MAX_QUOTED_NAME_LEN];
                char        paramname[16];
                const char *querysep;
                const char *qualsep;
                Oid         queryoids[RI_MAX_NUMKEYS];
                int         i;

                /* ----------
                 * The query string built is
                 *  UPDATE ONLY <fktable> SET fkatt1 = DEFAULT [, ...]
                 *          WHERE $1 = fkatt1 [AND ...]
                 * The type id's for the $ parameters are those of the
                 * corresponding PK attributes.
                 * ----------
                 */
                initStringInfo(&querybuf);
                initStringInfo(&qualbuf);
                quoteRelationName(fkrelname, fk_rel);
                appendStringInfo(&querybuf, "UPDATE ONLY %s SET", fkrelname);
                querysep = "";
                qualsep = "WHERE";
                for (i = 0; i < riinfo->nkeys; i++)
                {
                    Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
                    Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);

                    quoteOneName(attname,
                                 RIAttName(fk_rel, riinfo->fk_attnums[i]));
                    appendStringInfo(&querybuf,
                                     "%s %s = DEFAULT",
                                     querysep, attname);
                    sprintf(paramname, "$%d", i + 1);
                    ri_GenerateQual(&qualbuf, qualsep,
                                    paramname, pk_type,
                                    riinfo->pf_eq_oprs[i],
                                    attname, fk_type);
                    querysep = ",";
                    qualsep = "AND";
                    queryoids[i] = pk_type;
                }
                appendStringInfoString(&querybuf, qualbuf.data);

                /* Prepare and save the plan */
                qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
                                     &qkey, fk_rel, pk_rel, true);
            }

            /*
             * We have a plan now. Run it to update the existing references.
             */
            ri_PerformCheck(riinfo, &qkey, qplan,
                            fk_rel, pk_rel,
                            old_row, NULL,
                            true,       /* must detect new rows */
                            SPI_OK_UPDATE);

            if (SPI_finish() != SPI_OK_FINISH)
                elog(ERROR, "SPI_finish failed");

            heap_close(fk_rel, RowExclusiveLock);

            /*
             * If we just deleted the PK row whose key was equal to the FK
             * columns' default values, and a referencing row exists in the FK
             * table, we would have updated that row to the same values it
             * already had --- and RI_FKey_fk_upd_check_required would hence
             * believe no check is necessary.  So we need to do another lookup
             * now and in case a reference still exists, abort the operation.
             * That is already implemented in the NO ACTION trigger, so just
             * run it.  (This recheck is only needed in the SET DEFAULT case,
             * since CASCADE would remove such rows, while SET NULL is certain
             * to result in rows that satisfy the FK constraint.)
             */
            RI_FKey_noaction_del(fcinfo);

            return PointerGetDatum(NULL);

            /*
             * Handle MATCH PARTIAL set default delete.
             */
        case FKCONSTR_MATCH_PARTIAL:
            ereport(ERROR,
                    (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                     errmsg("MATCH PARTIAL not yet implemented")));
            return PointerGetDatum(NULL);

        default:
            elog(ERROR, "unrecognized confmatchtype: %d",
                 riinfo->confmatchtype);
            break;
    }

    /* Never reached */
    return PointerGetDatum(NULL);
}

Datum RI_FKey_setdefault_upd ( PG_FUNCTION_ARGS   ) 

Definition at line 1888 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), StringInfoData::data, elog, ereport, errcode(), errmsg(), ERROR, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, heap_close, heap_open(), i, initStringInfo(), NULL, PointerGetDatum, quoteOneName(), quoteRelationName(), ri_BuildQueryKey(), ri_CheckTrigger(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), RI_FKey_noaction_upd(), ri_GenerateQual(), RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL, RI_KEYS_SOME_NULL, ri_KeysEqual(), ri_NullCheck(), ri_PerformCheck(), RI_PLAN_SETDEFAULT_UPD_DOUPDATE, ri_PlanCheck(), RI_TRIGTYPE_UPDATE, RIAttName, RIAttType, RowExclusiveLock, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_OK_UPDATE, TriggerData::tg_newtuple, TriggerData::tg_relation, TriggerData::tg_trigger, and TriggerData::tg_trigtuple.

{
    TriggerData *trigdata = (TriggerData *) fcinfo->context;
    const RI_ConstraintInfo *riinfo;
    Relation    fk_rel;
    Relation    pk_rel;
    HeapTuple   new_row;
    HeapTuple   old_row;
    RI_QueryKey qkey;
    SPIPlanPtr  qplan;

    /*
     * Check that this is a valid trigger call on the right time and event.
     */
    ri_CheckTrigger(fcinfo, "RI_FKey_setdefault_upd", RI_TRIGTYPE_UPDATE);

    /*
     * Get arguments.
     */
    riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
                                    trigdata->tg_relation, true);

    /*
     * Get the relation descriptors of the FK and PK tables and the old tuple.
     *
     * fk_rel is opened in RowExclusiveLock mode since that's what our
     * eventual UPDATE will get on it.
     */
    fk_rel = heap_open(riinfo->fk_relid, RowExclusiveLock);
    pk_rel = trigdata->tg_relation;
    new_row = trigdata->tg_newtuple;
    old_row = trigdata->tg_trigtuple;

    switch (riinfo->confmatchtype)
    {
            /* ----------
             * SQL:2008 15.17 <Execution of referential actions>
             *  General rules 10) a) iii):
             *      MATCH SIMPLE/FULL
             *          ... ON UPDATE SET DEFAULT
             * ----------
             */
        case FKCONSTR_MATCH_SIMPLE:
        case FKCONSTR_MATCH_FULL:
            switch (ri_NullCheck(old_row, riinfo, true))
            {
                case RI_KEYS_ALL_NULL:
                case RI_KEYS_SOME_NULL:

                    /*
                     * No check needed - there cannot be any reference to old
                     * key if it contains a NULL
                     */
                    heap_close(fk_rel, RowExclusiveLock);
                    return PointerGetDatum(NULL);

                case RI_KEYS_NONE_NULL:

                    /*
                     * Have a full qualified key - continue below
                     */
                    break;
            }

            /*
             * No need to do anything if old and new keys are equal
             */
            if (ri_KeysEqual(pk_rel, old_row, new_row, riinfo, true))
            {
                heap_close(fk_rel, RowExclusiveLock);
                return PointerGetDatum(NULL);
            }

            if (SPI_connect() != SPI_OK_CONNECT)
                elog(ERROR, "SPI_connect failed");

            /*
             * Fetch or prepare a saved plan for the set default update
             * operation
             */
            ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_SETDEFAULT_UPD_DOUPDATE);

            if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
            {
                StringInfoData querybuf;
                StringInfoData qualbuf;
                char        fkrelname[MAX_QUOTED_REL_NAME_LEN];
                char        attname[MAX_QUOTED_NAME_LEN];
                char        paramname[16];
                const char *querysep;
                const char *qualsep;
                Oid         queryoids[RI_MAX_NUMKEYS];
                int         i;

                /* ----------
                 * The query string built is
                 *  UPDATE ONLY <fktable> SET fkatt1 = DEFAULT [, ...]
                 *          WHERE $1 = fkatt1 [AND ...]
                 * The type id's for the $ parameters are those of the
                 * corresponding PK attributes.
                 * ----------
                 */
                initStringInfo(&querybuf);
                initStringInfo(&qualbuf);
                quoteRelationName(fkrelname, fk_rel);
                appendStringInfo(&querybuf, "UPDATE ONLY %s SET", fkrelname);
                querysep = "";
                qualsep = "WHERE";
                for (i = 0; i < riinfo->nkeys; i++)
                {
                    Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
                    Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);

                    quoteOneName(attname,
                                 RIAttName(fk_rel, riinfo->fk_attnums[i]));
                    appendStringInfo(&querybuf,
                                     "%s %s = DEFAULT",
                                     querysep, attname);
                    sprintf(paramname, "$%d", i + 1);
                    ri_GenerateQual(&qualbuf, qualsep,
                                    paramname, pk_type,
                                    riinfo->pf_eq_oprs[i],
                                    attname, fk_type);
                    querysep = ",";
                    qualsep = "AND";
                    queryoids[i] = pk_type;
                }
                appendStringInfoString(&querybuf, qualbuf.data);

                /* Prepare and save the plan */
                qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
                                     &qkey, fk_rel, pk_rel, true);
            }

            /*
             * We have a plan now. Run it to update the existing references.
             */
            ri_PerformCheck(riinfo, &qkey, qplan,
                            fk_rel, pk_rel,
                            old_row, NULL,
                            true,       /* must detect new rows */
                            SPI_OK_UPDATE);

            if (SPI_finish() != SPI_OK_FINISH)
                elog(ERROR, "SPI_finish failed");

            heap_close(fk_rel, RowExclusiveLock);

            /*
             * If we just updated the PK row whose key was equal to the FK
             * columns' default values, and a referencing row exists in the FK
             * table, we would have updated that row to the same values it
             * already had --- and RI_FKey_fk_upd_check_required would hence
             * believe no check is necessary.  So we need to do another lookup
             * now and in case a reference still exists, abort the operation.
             * That is already implemented in the NO ACTION trigger, so just
             * run it.  (This recheck is only needed in the SET DEFAULT case,
             * since CASCADE must change the FK key values, while SET NULL is
             * certain to result in rows that satisfy the FK constraint.)
             */
            RI_FKey_noaction_upd(fcinfo);

            return PointerGetDatum(NULL);

            /*
             * Handle MATCH PARTIAL set default update.
             */
        case FKCONSTR_MATCH_PARTIAL:
            ereport(ERROR,
                    (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                     errmsg("MATCH PARTIAL not yet implemented")));
            return PointerGetDatum(NULL);

        default:
            elog(ERROR, "unrecognized confmatchtype: %d",
                 riinfo->confmatchtype);
            break;
    }

    /* Never reached */
    return PointerGetDatum(NULL);
}

Datum RI_FKey_setnull_del ( PG_FUNCTION_ARGS   ) 

Definition at line 1367 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), StringInfoData::data, elog, ereport, errcode(), errmsg(), ERROR, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, heap_close, heap_open(), i, initStringInfo(), NULL, PointerGetDatum, quoteOneName(), quoteRelationName(), ri_BuildQueryKey(), ri_CheckTrigger(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL, RI_KEYS_SOME_NULL, ri_NullCheck(), ri_PerformCheck(), RI_PLAN_SETNULL_DEL_DOUPDATE, ri_PlanCheck(), RI_TRIGTYPE_DELETE, RIAttName, RIAttType, RowExclusiveLock, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_OK_UPDATE, TriggerData::tg_relation, TriggerData::tg_trigger, and TriggerData::tg_trigtuple.

{
    TriggerData *trigdata = (TriggerData *) fcinfo->context;
    const RI_ConstraintInfo *riinfo;
    Relation    fk_rel;
    Relation    pk_rel;
    HeapTuple   old_row;
    RI_QueryKey qkey;
    SPIPlanPtr  qplan;
    int         i;

    /*
     * Check that this is a valid trigger call on the right time and event.
     */
    ri_CheckTrigger(fcinfo, "RI_FKey_setnull_del", RI_TRIGTYPE_DELETE);

    /*
     * Get arguments.
     */
    riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
                                    trigdata->tg_relation, true);

    /*
     * Get the relation descriptors of the FK and PK tables and the old tuple.
     *
     * fk_rel is opened in RowExclusiveLock mode since that's what our
     * eventual UPDATE will get on it.
     */
    fk_rel = heap_open(riinfo->fk_relid, RowExclusiveLock);
    pk_rel = trigdata->tg_relation;
    old_row = trigdata->tg_trigtuple;

    switch (riinfo->confmatchtype)
    {
            /* ----------
             * SQL:2008 15.17 <Execution of referential actions>
             *  General rules 9) a) ii):
             *      MATCH SIMPLE/FULL
             *          ... ON DELETE SET NULL
             * ----------
             */
        case FKCONSTR_MATCH_SIMPLE:
        case FKCONSTR_MATCH_FULL:
            switch (ri_NullCheck(old_row, riinfo, true))
            {
                case RI_KEYS_ALL_NULL:
                case RI_KEYS_SOME_NULL:

                    /*
                     * No check needed - there cannot be any reference to old
                     * key if it contains a NULL
                     */
                    heap_close(fk_rel, RowExclusiveLock);
                    return PointerGetDatum(NULL);

                case RI_KEYS_NONE_NULL:

                    /*
                     * Have a full qualified key - continue below
                     */
                    break;
            }

            if (SPI_connect() != SPI_OK_CONNECT)
                elog(ERROR, "SPI_connect failed");

            /*
             * Fetch or prepare a saved plan for the set null delete operation
             */
            ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_SETNULL_DEL_DOUPDATE);

            if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
            {
                StringInfoData querybuf;
                StringInfoData qualbuf;
                char        fkrelname[MAX_QUOTED_REL_NAME_LEN];
                char        attname[MAX_QUOTED_NAME_LEN];
                char        paramname[16];
                const char *querysep;
                const char *qualsep;
                Oid         queryoids[RI_MAX_NUMKEYS];

                /* ----------
                 * The query string built is
                 *  UPDATE ONLY <fktable> SET fkatt1 = NULL [, ...]
                 *          WHERE $1 = fkatt1 [AND ...]
                 * The type id's for the $ parameters are those of the
                 * corresponding PK attributes.
                 * ----------
                 */
                initStringInfo(&querybuf);
                initStringInfo(&qualbuf);
                quoteRelationName(fkrelname, fk_rel);
                appendStringInfo(&querybuf, "UPDATE ONLY %s SET", fkrelname);
                querysep = "";
                qualsep = "WHERE";
                for (i = 0; i < riinfo->nkeys; i++)
                {
                    Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
                    Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);

                    quoteOneName(attname,
                                 RIAttName(fk_rel, riinfo->fk_attnums[i]));
                    appendStringInfo(&querybuf,
                                     "%s %s = NULL",
                                     querysep, attname);
                    sprintf(paramname, "$%d", i + 1);
                    ri_GenerateQual(&qualbuf, qualsep,
                                    paramname, pk_type,
                                    riinfo->pf_eq_oprs[i],
                                    attname, fk_type);
                    querysep = ",";
                    qualsep = "AND";
                    queryoids[i] = pk_type;
                }
                appendStringInfoString(&querybuf, qualbuf.data);

                /* Prepare and save the plan */
                qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
                                     &qkey, fk_rel, pk_rel, true);
            }

            /*
             * We have a plan now. Run it to check for existing references.
             */
            ri_PerformCheck(riinfo, &qkey, qplan,
                            fk_rel, pk_rel,
                            old_row, NULL,
                            true,       /* must detect new rows */
                            SPI_OK_UPDATE);

            if (SPI_finish() != SPI_OK_FINISH)
                elog(ERROR, "SPI_finish failed");

            heap_close(fk_rel, RowExclusiveLock);

            return PointerGetDatum(NULL);

            /*
             * Handle MATCH PARTIAL set null delete.
             */
        case FKCONSTR_MATCH_PARTIAL:
            ereport(ERROR,
                    (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                     errmsg("MATCH PARTIAL not yet implemented")));
            return PointerGetDatum(NULL);

        default:
            elog(ERROR, "unrecognized confmatchtype: %d",
                 riinfo->confmatchtype);
            break;
    }

    /* Never reached */
    return PointerGetDatum(NULL);
}

Datum RI_FKey_setnull_upd ( PG_FUNCTION_ARGS   ) 

Definition at line 1532 of file ri_triggers.c.

References appendStringInfo(), appendStringInfoString(), StringInfoData::data, elog, ereport, errcode(), errmsg(), ERROR, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, heap_close, heap_open(), i, initStringInfo(), NULL, PointerGetDatum, quoteOneName(), quoteRelationName(), ri_BuildQueryKey(), ri_CheckTrigger(), ri_FetchConstraintInfo(), ri_FetchPreparedPlan(), ri_GenerateQual(), RI_KEYS_ALL_NULL, RI_KEYS_NONE_NULL, RI_KEYS_SOME_NULL, ri_KeysEqual(), ri_NullCheck(), ri_PerformCheck(), RI_PLAN_SETNULL_UPD_DOUPDATE, ri_PlanCheck(), RI_TRIGTYPE_UPDATE, RIAttName, RIAttType, RowExclusiveLock, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_OK_UPDATE, TriggerData::tg_newtuple, TriggerData::tg_relation, TriggerData::tg_trigger, and TriggerData::tg_trigtuple.

{
    TriggerData *trigdata = (TriggerData *) fcinfo->context;
    const RI_ConstraintInfo *riinfo;
    Relation    fk_rel;
    Relation    pk_rel;
    HeapTuple   new_row;
    HeapTuple   old_row;
    RI_QueryKey qkey;
    SPIPlanPtr  qplan;
    int         i;

    /*
     * Check that this is a valid trigger call on the right time and event.
     */
    ri_CheckTrigger(fcinfo, "RI_FKey_setnull_upd", RI_TRIGTYPE_UPDATE);

    /*
     * Get arguments.
     */
    riinfo = ri_FetchConstraintInfo(trigdata->tg_trigger,
                                    trigdata->tg_relation, true);

    /*
     * Get the relation descriptors of the FK and PK tables and the old tuple.
     *
     * fk_rel is opened in RowExclusiveLock mode since that's what our
     * eventual UPDATE will get on it.
     */
    fk_rel = heap_open(riinfo->fk_relid, RowExclusiveLock);
    pk_rel = trigdata->tg_relation;
    new_row = trigdata->tg_newtuple;
    old_row = trigdata->tg_trigtuple;

    switch (riinfo->confmatchtype)
    {
            /* ----------
             * SQL:2008 15.17 <Execution of referential actions>
             *  General rules 10) a) ii):
             *      MATCH SIMPLE/FULL
             *          ... ON UPDATE SET NULL
             * ----------
             */
        case FKCONSTR_MATCH_SIMPLE:
        case FKCONSTR_MATCH_FULL:
            switch (ri_NullCheck(old_row, riinfo, true))
            {
                case RI_KEYS_ALL_NULL:
                case RI_KEYS_SOME_NULL:

                    /*
                     * No check needed - there cannot be any reference to old
                     * key if it contains a NULL
                     */
                    heap_close(fk_rel, RowExclusiveLock);
                    return PointerGetDatum(NULL);

                case RI_KEYS_NONE_NULL:

                    /*
                     * Have a full qualified key - continue below
                     */
                    break;
            }

            /*
             * No need to do anything if old and new keys are equal
             */
            if (ri_KeysEqual(pk_rel, old_row, new_row, riinfo, true))
            {
                heap_close(fk_rel, RowExclusiveLock);
                return PointerGetDatum(NULL);
            }

            if (SPI_connect() != SPI_OK_CONNECT)
                elog(ERROR, "SPI_connect failed");

            /*
             * Fetch or prepare a saved plan for the set null update operation
             */
            ri_BuildQueryKey(&qkey, riinfo, RI_PLAN_SETNULL_UPD_DOUPDATE);

            if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
            {
                StringInfoData querybuf;
                StringInfoData qualbuf;
                char        fkrelname[MAX_QUOTED_REL_NAME_LEN];
                char        attname[MAX_QUOTED_NAME_LEN];
                char        paramname[16];
                const char *querysep;
                const char *qualsep;
                Oid         queryoids[RI_MAX_NUMKEYS];

                /* ----------
                 * The query string built is
                 *  UPDATE ONLY <fktable> SET fkatt1 = NULL [, ...]
                 *          WHERE $1 = fkatt1 [AND ...]
                 * The type id's for the $ parameters are those of the
                 * corresponding PK attributes.
                 * ----------
                 */
                initStringInfo(&querybuf);
                initStringInfo(&qualbuf);
                quoteRelationName(fkrelname, fk_rel);
                appendStringInfo(&querybuf, "UPDATE ONLY %s SET", fkrelname);
                querysep = "";
                qualsep = "WHERE";
                for (i = 0; i < riinfo->nkeys; i++)
                {
                    Oid         pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
                    Oid         fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);

                    quoteOneName(attname,
                                 RIAttName(fk_rel, riinfo->fk_attnums[i]));
                    appendStringInfo(&querybuf,
                                     "%s %s = NULL",
                                     querysep, attname);
                    sprintf(paramname, "$%d", i + 1);
                    ri_GenerateQual(&qualbuf, qualsep,
                                    paramname, pk_type,
                                    riinfo->pf_eq_oprs[i],
                                    attname, fk_type);
                    querysep = ",";
                    qualsep = "AND";
                    queryoids[i] = pk_type;
                }
                appendStringInfoString(&querybuf, qualbuf.data);

                /* Prepare and save the plan */
                qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
                                     &qkey, fk_rel, pk_rel, true);
            }

            /*
             * We have a plan now. Run it to update the existing references.
             */
            ri_PerformCheck(riinfo, &qkey, qplan,
                            fk_rel, pk_rel,
                            old_row, NULL,
                            true,       /* must detect new rows */
                            SPI_OK_UPDATE);

            if (SPI_finish() != SPI_OK_FINISH)
                elog(ERROR, "SPI_finish failed");

            heap_close(fk_rel, RowExclusiveLock);

            return PointerGetDatum(NULL);

            /*
             * Handle MATCH PARTIAL set null update.
             */
        case FKCONSTR_MATCH_PARTIAL:
            ereport(ERROR,
                    (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                     errmsg("MATCH PARTIAL not yet implemented")));
            return PointerGetDatum(NULL);

        default:
            elog(ERROR, "unrecognized confmatchtype: %d",
                 riinfo->confmatchtype);
            break;
    }

    /* Never reached */
    return PointerGetDatum(NULL);
}

Datum rpad ( PG_FUNCTION_ARGS   ) 

Definition at line 239 of file oracle_compat.c.

References ereport, errcode(), errmsg(), ERROR, palloc(), pg_database_encoding_max_length(), PG_GETARG_INT32, PG_GETARG_TEXT_PP, pg_mblen(), pg_mbstrlen_with_len(), PG_RETURN_TEXT_P, SET_VARSIZE, VARDATA, VARDATA_ANY, VARHDRSZ, and VARSIZE_ANY_EXHDR.

{
    text       *string1 = PG_GETARG_TEXT_PP(0);
    int32       len = PG_GETARG_INT32(1);
    text       *string2 = PG_GETARG_TEXT_PP(2);
    text       *ret;
    char       *ptr1,
               *ptr2,
               *ptr2start,
               *ptr2end,
               *ptr_ret;
    int         m,
                s1len,
                s2len;

    int         bytelen;

    /* Negative len is silently taken as zero */
    if (len < 0)
        len = 0;

    s1len = VARSIZE_ANY_EXHDR(string1);
    if (s1len < 0)
        s1len = 0;              /* shouldn't happen */

    s2len = VARSIZE_ANY_EXHDR(string2);
    if (s2len < 0)
        s2len = 0;              /* shouldn't happen */

    s1len = pg_mbstrlen_with_len(VARDATA_ANY(string1), s1len);

    if (s1len > len)
        s1len = len;            /* truncate string1 to len chars */

    if (s2len <= 0)
        len = s1len;            /* nothing to pad with, so don't pad */

    bytelen = pg_database_encoding_max_length() * len;

    /* Check for integer overflow */
    if (len != 0 && bytelen / pg_database_encoding_max_length() != len)
        ereport(ERROR,
                (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                 errmsg("requested length too large")));

    ret = (text *) palloc(VARHDRSZ + bytelen);
    m = len - s1len;

    ptr1 = VARDATA_ANY(string1);
    ptr_ret = VARDATA(ret);

    while (s1len--)
    {
        int         mlen = pg_mblen(ptr1);

        memcpy(ptr_ret, ptr1, mlen);
        ptr_ret += mlen;
        ptr1 += mlen;
    }

    ptr2 = ptr2start = VARDATA_ANY(string2);
    ptr2end = ptr2 + s2len;

    while (m--)
    {
        int         mlen = pg_mblen(ptr2);

        memcpy(ptr_ret, ptr2, mlen);
        ptr_ret += mlen;
        ptr2 += mlen;
        if (ptr2 == ptr2end)    /* wrap around at end of s2 */
            ptr2 = ptr2start;
    }

    SET_VARSIZE(ret, ptr_ret - (char *) ret);

    PG_RETURN_TEXT_P(ret);
}

Datum rtrim ( PG_FUNCTION_ARGS   ) 

Definition at line 667 of file oracle_compat.c.

References dotrim(), PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    text       *string = PG_GETARG_TEXT_PP(0);
    text       *set = PG_GETARG_TEXT_PP(1);
    text       *ret;

    ret = dotrim(VARDATA_ANY(string), VARSIZE_ANY_EXHDR(string),
                 VARDATA_ANY(set), VARSIZE_ANY_EXHDR(set),
                 false, true);

    PG_RETURN_TEXT_P(ret);
}

Datum rtrim1 ( PG_FUNCTION_ARGS   ) 

Definition at line 687 of file oracle_compat.c.

References dotrim(), PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

Referenced by gbt_bpchar_compress(), and gbt_bpchar_consistent().

{
    text       *string = PG_GETARG_TEXT_PP(0);
    text       *ret;

    ret = dotrim(VARDATA_ANY(string), VARSIZE_ANY_EXHDR(string),
                 " ", 1,
                 false, true);

    PG_RETURN_TEXT_P(ret);
}

List* select_rtable_names_for_explain ( List rtable,
Bitmapset rels_used 
)

Definition at line 2422 of file ruleutils.c.

References deparse_namespace::ctes, NIL, deparse_namespace::rtable, deparse_namespace::rtable_names, and set_rtable_names().

Referenced by ExplainPrintPlan().

{
    deparse_namespace dpns;

    memset(&dpns, 0, sizeof(dpns));
    dpns.rtable = rtable;
    dpns.ctes = NIL;
    set_rtable_names(&dpns, NIL, rels_used);
    /* We needn't bother computing column aliases yet */

    return dpns.rtable_names;
}

Datum session_user ( PG_FUNCTION_ARGS   ) 
Datum set_config_by_name ( PG_FUNCTION_ARGS   ) 

Definition at line 6337 of file guc.c.

References cstring_to_text(), ereport, errcode(), errmsg(), ERROR, GetConfigOptionByName(), GUC_ACTION_LOCAL, name, NULL, PG_ARGISNULL, PG_GETARG_BOOL, PG_GETARG_DATUM, PG_RETURN_TEXT_P, PGC_SUSET, PGC_USERSET, set_config_option(), superuser(), TextDatumGetCString, and value.

{
    char       *name;
    char       *value;
    char       *new_value;
    bool        is_local;

    if (PG_ARGISNULL(0))
        ereport(ERROR,
                (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
                 errmsg("SET requires parameter name")));

    /* Get the GUC variable name */
    name = TextDatumGetCString(PG_GETARG_DATUM(0));

    /* Get the desired value or set to NULL for a reset request */
    if (PG_ARGISNULL(1))
        value = NULL;
    else
        value = TextDatumGetCString(PG_GETARG_DATUM(1));

    /*
     * Get the desired state of is_local. Default to false if provided value
     * is NULL
     */
    if (PG_ARGISNULL(2))
        is_local = false;
    else
        is_local = PG_GETARG_BOOL(2);

    /* Note SET DEFAULT (argstring == NULL) is equivalent to RESET */
    (void) set_config_option(name,
                             value,
                             (superuser() ? PGC_SUSET : PGC_USERSET),
                             PGC_S_SESSION,
                             is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET,
                             true,
                             0);

    /* get the new current value */
    new_value = GetConfigOptionByName(name, NULL);

    /* Convert return string to text */
    PG_RETURN_TEXT_P(cstring_to_text(new_value));
}

Datum setseed ( PG_FUNCTION_ARGS   ) 

Definition at line 1754 of file float.c.

References elog, ERROR, MAX_RANDOM_VALUE, PG_GETARG_FLOAT8, PG_RETURN_VOID, and srandom().

Referenced by assign_random_seed().

{
    float8      seed = PG_GETARG_FLOAT8(0);
    int         iseed;

    if (seed < -1 || seed > 1)
        elog(ERROR, "setseed parameter %f out of range [-1,1]", seed);

    iseed = (int) (seed * MAX_RANDOM_VALUE);
    srandom((unsigned int) iseed);

    PG_RETURN_VOID();
}

Datum shell_in ( PG_FUNCTION_ARGS   ) 

Definition at line 486 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot accept a value of a shell type")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum shell_out ( PG_FUNCTION_ARGS   ) 

Definition at line 499 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot display a value of a shell type")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum show_all_settings ( PG_FUNCTION_ARGS   ) 

Definition at line 7223 of file guc.c.

References FuncCallContext::attinmeta, BuildTupleFromCStrings(), FuncCallContext::call_cntr, CreateTemplateTupleDesc(), GetConfigOptionByNum(), GetNumConfigOptions(), HeapTupleGetDatum, INT4OID, FuncCallContext::max_calls, MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, NUM_PG_SETTINGS_ATTS, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, TEXTARRAYOID, TEXTOID, TupleDescGetAttInMetadata(), TupleDescInitEntry(), and values.

{
    FuncCallContext *funcctx;
    TupleDesc   tupdesc;
    int         call_cntr;
    int         max_calls;
    AttInMetadata *attinmeta;
    MemoryContext oldcontext;

    /* stuff done only on the first call of the function */
    if (SRF_IS_FIRSTCALL())
    {
        /* create a function context for cross-call persistence */
        funcctx = SRF_FIRSTCALL_INIT();

        /*
         * switch to memory context appropriate for multiple function calls
         */
        oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);

        /*
         * need a tuple descriptor representing NUM_PG_SETTINGS_ATTS columns
         * of the appropriate types
         */
        tupdesc = CreateTemplateTupleDesc(NUM_PG_SETTINGS_ATTS, false);
        TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
                           TEXTOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 2, "setting",
                           TEXTOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 3, "unit",
                           TEXTOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 4, "category",
                           TEXTOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 5, "short_desc",
                           TEXTOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 6, "extra_desc",
                           TEXTOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 7, "context",
                           TEXTOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 8, "vartype",
                           TEXTOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 9, "source",
                           TEXTOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 10, "min_val",
                           TEXTOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 11, "max_val",
                           TEXTOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 12, "enumvals",
                           TEXTARRAYOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 13, "boot_val",
                           TEXTOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 14, "reset_val",
                           TEXTOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 15, "sourcefile",
                           TEXTOID, -1, 0);
        TupleDescInitEntry(tupdesc, (AttrNumber) 16, "sourceline",
                           INT4OID, -1, 0);

        /*
         * Generate attribute metadata needed later to produce tuples from raw
         * C strings
         */
        attinmeta = TupleDescGetAttInMetadata(tupdesc);
        funcctx->attinmeta = attinmeta;

        /* total number of tuples to be returned */
        funcctx->max_calls = GetNumConfigOptions();

        MemoryContextSwitchTo(oldcontext);
    }

    /* stuff done on every call of the function */
    funcctx = SRF_PERCALL_SETUP();

    call_cntr = funcctx->call_cntr;
    max_calls = funcctx->max_calls;
    attinmeta = funcctx->attinmeta;

    if (call_cntr < max_calls)  /* do when there is more left to send */
    {
        char       *values[NUM_PG_SETTINGS_ATTS];
        bool        noshow;
        HeapTuple   tuple;
        Datum       result;

        /*
         * Get the next visible GUC variable name and value
         */
        do
        {
            GetConfigOptionByNum(call_cntr, (const char **) values, &noshow);
            if (noshow)
            {
                /* bump the counter and get the next config setting */
                call_cntr = ++funcctx->call_cntr;

                /* make sure we haven't gone too far now */
                if (call_cntr >= max_calls)
                    SRF_RETURN_DONE(funcctx);
            }
        } while (noshow);

        /* build a tuple */
        tuple = BuildTupleFromCStrings(attinmeta, values);

        /* make the tuple into a datum */
        result = HeapTupleGetDatum(tuple);

        SRF_RETURN_NEXT(funcctx, result);
    }
    else
    {
        /* do when there is no more left */
        SRF_RETURN_DONE(funcctx);
    }
}

Datum show_config_by_name ( PG_FUNCTION_ARGS   ) 

Definition at line 7201 of file guc.c.

References cstring_to_text(), GetConfigOptionByName(), NULL, PG_GETARG_DATUM, PG_RETURN_TEXT_P, and TextDatumGetCString.

{
    char       *varname;
    char       *varval;

    /* Get the GUC variable name */
    varname = TextDatumGetCString(PG_GETARG_DATUM(0));

    /* Get the value */
    varval = GetConfigOptionByName(varname, NULL);

    /* Convert to text */
    PG_RETURN_TEXT_P(cstring_to_text(varval));
}

Datum similar_escape ( PG_FUNCTION_ARGS   ) 

Definition at line 647 of file regexp.c.

References ereport, errcode(), errhint(), errmsg(), ERROR, palloc(), PG_ARGISNULL, PG_GETARG_TEXT_PP, PG_RETURN_NULL, PG_RETURN_TEXT_P, SET_VARSIZE, VARDATA, VARDATA_ANY, VARHDRSZ, and VARSIZE_ANY_EXHDR.

{
    text       *pat_text;
    text       *esc_text;
    text       *result;
    char       *p,
               *e,
               *r;
    int         plen,
                elen;
    bool        afterescape = false;
    bool        incharclass = false;
    int         nquotes = 0;

    /* This function is not strict, so must test explicitly */
    if (PG_ARGISNULL(0))
        PG_RETURN_NULL();
    pat_text = PG_GETARG_TEXT_PP(0);
    p = VARDATA_ANY(pat_text);
    plen = VARSIZE_ANY_EXHDR(pat_text);
    if (PG_ARGISNULL(1))
    {
        /* No ESCAPE clause provided; default to backslash as escape */
        e = "\\";
        elen = 1;
    }
    else
    {
        esc_text = PG_GETARG_TEXT_PP(1);
        e = VARDATA_ANY(esc_text);
        elen = VARSIZE_ANY_EXHDR(esc_text);
        if (elen == 0)
            e = NULL;           /* no escape character */
        else if (elen != 1)
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_ESCAPE_SEQUENCE),
                     errmsg("invalid escape string"),
                  errhint("Escape string must be empty or one character.")));
    }

    /*----------
     * We surround the transformed input string with
     *          ^(?: ... )$
     * which requires some explanation.  We need "^" and "$" to force
     * the pattern to match the entire input string as per SQL99 spec.
     * The "(?:" and ")" are a non-capturing set of parens; we have to have
     * parens in case the string contains "|", else the "^" and "$" will
     * be bound into the first and last alternatives which is not what we
     * want, and the parens must be non capturing because we don't want them
     * to count when selecting output for SUBSTRING.
     *----------
     */

    /*
     * We need room for the prefix/postfix plus as many as 3 output bytes per
     * input byte; since the input is at most 1GB this can't overflow
     */
    result = (text *) palloc(VARHDRSZ + 6 + 3 * plen);
    r = VARDATA(result);

    *r++ = '^';
    *r++ = '(';
    *r++ = '?';
    *r++ = ':';

    while (plen > 0)
    {
        char        pchar = *p;

        if (afterescape)
        {
            if (pchar == '"' && !incharclass)   /* for SUBSTRING patterns */
                *r++ = ((nquotes++ % 2) == 0) ? '(' : ')';
            else
            {
                *r++ = '\\';
                *r++ = pchar;
            }
            afterescape = false;
        }
        else if (e && pchar == *e)
        {
            /* SQL99 escape character; do not send to output */
            afterescape = true;
        }
        else if (incharclass)
        {
            if (pchar == '\\')
                *r++ = '\\';
            *r++ = pchar;
            if (pchar == ']')
                incharclass = false;
        }
        else if (pchar == '[')
        {
            *r++ = pchar;
            incharclass = true;
        }
        else if (pchar == '%')
        {
            *r++ = '.';
            *r++ = '*';
        }
        else if (pchar == '_')
            *r++ = '.';
        else if (pchar == '(')
        {
            /* convert to non-capturing parenthesis */
            *r++ = '(';
            *r++ = '?';
            *r++ = ':';
        }
        else if (pchar == '\\' || pchar == '.' ||
                 pchar == '^' || pchar == '$')
        {
            *r++ = '\\';
            *r++ = pchar;
        }
        else
            *r++ = pchar;
        p++, plen--;
    }

    *r++ = ')';
    *r++ = '$';

    SET_VARSIZE(result, r - ((char *) result));

    PG_RETURN_TEXT_P(result);
}

Datum spg_kd_choose ( PG_FUNCTION_ARGS   ) 

Definition at line 52 of file spgkdtreeproc.c.

References spgChooseIn::allTheSame, Assert, spgChooseIn::datum, DatumGetFloat8, DatumGetPointP, elog, ERROR, getSide(), spgChooseIn::hasPrefix, spgChooseIn::level, spgChooseOut::matchNode, spgChooseIn::nNodes, PG_GETARG_POINTER, PG_RETURN_VOID, PointPGetDatum, spgChooseIn::prefixDatum, spgChooseOut::result, and spgChooseOut::resultType.

{
    spgChooseIn *in = (spgChooseIn *) PG_GETARG_POINTER(0);
    spgChooseOut *out = (spgChooseOut *) PG_GETARG_POINTER(1);
    Point      *inPoint = DatumGetPointP(in->datum);
    double      coord;

    if (in->allTheSame)
        elog(ERROR, "allTheSame should not occur for k-d trees");

    Assert(in->hasPrefix);
    coord = DatumGetFloat8(in->prefixDatum);

    Assert(in->nNodes == 2);

    out->resultType = spgMatchNode;
    out->result.matchNode.nodeN =
        (getSide(coord, in->level % 2, inPoint) > 0) ? 0 : 1;
    out->result.matchNode.levelAdd = 1;
    out->result.matchNode.restDatum = PointPGetDatum(inPoint);

    PG_RETURN_VOID();
}

Datum spg_kd_config ( PG_FUNCTION_ARGS   ) 

Definition at line 26 of file spgkdtreeproc.c.

References spgConfigOut::canReturnData, spgConfigOut::labelType, spgConfigOut::longValuesOK, PG_GETARG_POINTER, PG_RETURN_VOID, and spgConfigOut::prefixType.

{
    /* spgConfigIn *cfgin = (spgConfigIn *) PG_GETARG_POINTER(0); */
    spgConfigOut *cfg = (spgConfigOut *) PG_GETARG_POINTER(1);

    cfg->prefixType = FLOAT8OID;
    cfg->labelType = VOIDOID;   /* we don't need node labels */
    cfg->canReturnData = true;
    cfg->longValuesOK = false;
    PG_RETURN_VOID();
}

Datum spg_kd_inner_consistent ( PG_FUNCTION_ARGS   ) 

Definition at line 158 of file spgkdtreeproc.c.

References spgInnerConsistentIn::allTheSame, Assert, DatumGetBoxP, DatumGetFloat8, DatumGetPointP, elog, ERROR, FPgt, FPlt, spgInnerConsistentIn::hasPrefix, BOX::high, i, spgInnerConsistentIn::level, spgInnerConsistentOut::levelAdds, BOX::low, spgInnerConsistentIn::nkeys, spgInnerConsistentOut::nNodes, spgInnerConsistentIn::nNodes, spgInnerConsistentOut::nodeNumbers, palloc(), PG_GETARG_POINTER, PG_RETURN_VOID, spgInnerConsistentIn::prefixDatum, RTAboveStrategyNumber, RTBelowStrategyNumber, RTContainedByStrategyNumber, RTLeftStrategyNumber, RTRightStrategyNumber, RTSameStrategyNumber, spgInnerConsistentIn::scankeys, ScanKeyData::sk_argument, ScanKeyData::sk_strategy, Point::x, and Point::y.

{
    spgInnerConsistentIn *in = (spgInnerConsistentIn *) PG_GETARG_POINTER(0);
    spgInnerConsistentOut *out = (spgInnerConsistentOut *) PG_GETARG_POINTER(1);
    double      coord;
    int         which;
    int         i;

    Assert(in->hasPrefix);
    coord = DatumGetFloat8(in->prefixDatum);

    if (in->allTheSame)
        elog(ERROR, "allTheSame should not occur for k-d trees");

    Assert(in->nNodes == 2);

    /* "which" is a bitmask of children that satisfy all constraints */
    which = (1 << 1) | (1 << 2);

    for (i = 0; i < in->nkeys; i++)
    {
        Point      *query = DatumGetPointP(in->scankeys[i].sk_argument);
        BOX        *boxQuery;

        switch (in->scankeys[i].sk_strategy)
        {
            case RTLeftStrategyNumber:
                if ((in->level % 2) != 0 && FPlt(query->x, coord))
                    which &= (1 << 1);
                break;
            case RTRightStrategyNumber:
                if ((in->level % 2) != 0 && FPgt(query->x, coord))
                    which &= (1 << 2);
                break;
            case RTSameStrategyNumber:
                if ((in->level % 2) != 0)
                {
                    if (FPlt(query->x, coord))
                        which &= (1 << 1);
                    else if (FPgt(query->x, coord))
                        which &= (1 << 2);
                }
                else
                {
                    if (FPlt(query->y, coord))
                        which &= (1 << 1);
                    else if (FPgt(query->y, coord))
                        which &= (1 << 2);
                }
                break;
            case RTBelowStrategyNumber:
                if ((in->level % 2) == 0 && FPlt(query->y, coord))
                    which &= (1 << 1);
                break;
            case RTAboveStrategyNumber:
                if ((in->level % 2) == 0 && FPgt(query->y, coord))
                    which &= (1 << 2);
                break;
            case RTContainedByStrategyNumber:

                /*
                 * For this operator, the query is a box not a point.  We
                 * cheat to the extent of assuming that DatumGetPointP won't
                 * do anything that would be bad for a pointer-to-box.
                 */
                boxQuery = DatumGetBoxP(in->scankeys[i].sk_argument);

                if ((in->level % 2) != 0)
                {
                    if (FPlt(boxQuery->high.x, coord))
                        which &= (1 << 1);
                    else if (FPgt(boxQuery->low.x, coord))
                        which &= (1 << 2);
                }
                else
                {
                    if (FPlt(boxQuery->high.y, coord))
                        which &= (1 << 1);
                    else if (FPgt(boxQuery->low.y, coord))
                        which &= (1 << 2);
                }
                break;
            default:
                elog(ERROR, "unrecognized strategy number: %d",
                     in->scankeys[i].sk_strategy);
                break;
        }

        if (which == 0)
            break;              /* no need to consider remaining conditions */
    }

    /* We must descend into the children identified by which */
    out->nodeNumbers = (int *) palloc(sizeof(int) * 2);
    out->nNodes = 0;
    for (i = 1; i <= 2; i++)
    {
        if (which & (1 << i))
            out->nodeNumbers[out->nNodes++] = i - 1;
    }

    /* Set up level increments, too */
    out->levelAdds = (int *) palloc(sizeof(int) * 2);
    out->levelAdds[0] = 1;
    out->levelAdds[1] = 1;

    PG_RETURN_VOID();
}

Datum spg_kd_picksplit ( PG_FUNCTION_ARGS   ) 

Definition at line 106 of file spgkdtreeproc.c.

References DatumGetPointP, spgPickSplitIn::datums, Float8GetDatum(), spgPickSplitOut::hasPrefix, SortedPoint::i, i, spgPickSplitOut::leafTupleDatums, spgPickSplitIn::level, spgPickSplitOut::mapTuplesToNodes, spgPickSplitOut::nNodes, spgPickSplitOut::nodeLabels, spgPickSplitIn::nTuples, SortedPoint::p, palloc(), PG_GETARG_POINTER, PG_RETURN_VOID, PointPGetDatum, spgPickSplitOut::prefixDatum, qsort, x_cmp(), Point::y, and y_cmp().

{
    spgPickSplitIn *in = (spgPickSplitIn *) PG_GETARG_POINTER(0);
    spgPickSplitOut *out = (spgPickSplitOut *) PG_GETARG_POINTER(1);
    int         i;
    int         middle;
    SortedPoint *sorted;
    double      coord;

    sorted = palloc(sizeof(*sorted) * in->nTuples);
    for (i = 0; i < in->nTuples; i++)
    {
        sorted[i].p = DatumGetPointP(in->datums[i]);
        sorted[i].i = i;
    }

    qsort(sorted, in->nTuples, sizeof(*sorted),
          (in->level % 2) ? x_cmp : y_cmp);
    middle = in->nTuples >> 1;
    coord = (in->level % 2) ? sorted[middle].p->x : sorted[middle].p->y;

    out->hasPrefix = true;
    out->prefixDatum = Float8GetDatum(coord);

    out->nNodes = 2;
    out->nodeLabels = NULL;     /* we don't need node labels */

    out->mapTuplesToNodes = palloc(sizeof(int) * in->nTuples);
    out->leafTupleDatums = palloc(sizeof(Datum) * in->nTuples);

    /*
     * Note: points that have coordinates exactly equal to coord may get
     * classified into either node, depending on where they happen to fall in
     * the sorted list.  This is okay as long as the inner_consistent function
     * descends into both sides for such cases.  This is better than the
     * alternative of trying to have an exact boundary, because it keeps the
     * tree balanced even when we have many instances of the same point value.
     * So we should never trigger the allTheSame logic.
     */
    for (i = 0; i < in->nTuples; i++)
    {
        Point      *p = sorted[i].p;
        int         n = sorted[i].i;

        out->mapTuplesToNodes[n] = (i < middle) ? 0 : 1;
        out->leafTupleDatums[n] = PointPGetDatum(p);
    }

    PG_RETURN_VOID();
}

Datum spg_quad_choose ( PG_FUNCTION_ARGS   ) 

Definition at line 82 of file spgquadtreeproc.c.

References spgChooseIn::allTheSame, Assert, spgChooseIn::datum, DatumGetPointP, getQuadrant(), spgChooseIn::hasPrefix, spgChooseOut::matchNode, spgChooseIn::nNodes, PG_GETARG_POINTER, PG_RETURN_VOID, PointPGetDatum, spgChooseIn::prefixDatum, spgChooseOut::result, and spgChooseOut::resultType.

{
    spgChooseIn *in = (spgChooseIn *) PG_GETARG_POINTER(0);
    spgChooseOut *out = (spgChooseOut *) PG_GETARG_POINTER(1);
    Point      *inPoint = DatumGetPointP(in->datum),
               *centroid;

    if (in->allTheSame)
    {
        out->resultType = spgMatchNode;
        /* nodeN will be set by core */
        out->result.matchNode.levelAdd = 0;
        out->result.matchNode.restDatum = PointPGetDatum(inPoint);
        PG_RETURN_VOID();
    }

    Assert(in->hasPrefix);
    centroid = DatumGetPointP(in->prefixDatum);

    Assert(in->nNodes == 4);

    out->resultType = spgMatchNode;
    out->result.matchNode.nodeN = getQuadrant(centroid, inPoint) - 1;
    out->result.matchNode.levelAdd = 0;
    out->result.matchNode.restDatum = PointPGetDatum(inPoint);

    PG_RETURN_VOID();
}

Datum spg_quad_config ( PG_FUNCTION_ARGS   ) 

Definition at line 26 of file spgquadtreeproc.c.

References spgConfigOut::canReturnData, spgConfigOut::labelType, spgConfigOut::longValuesOK, PG_GETARG_POINTER, PG_RETURN_VOID, and spgConfigOut::prefixType.

{
    /* spgConfigIn *cfgin = (spgConfigIn *) PG_GETARG_POINTER(0); */
    spgConfigOut *cfg = (spgConfigOut *) PG_GETARG_POINTER(1);

    cfg->prefixType = POINTOID;
    cfg->labelType = VOIDOID;   /* we don't need node labels */
    cfg->canReturnData = true;
    cfg->longValuesOK = false;
    PG_RETURN_VOID();
}

Datum spg_quad_inner_consistent ( PG_FUNCTION_ARGS   ) 

Definition at line 194 of file spgquadtreeproc.c.

References spgInnerConsistentIn::allTheSame, Assert, box_contain_pt(), DatumGetBool, DatumGetBoxP, DatumGetPointP, DirectFunctionCall2, elog, ERROR, getQuadrant(), spgInnerConsistentIn::hasPrefix, BOX::high, i, BOX::low, spgInnerConsistentIn::nkeys, spgInnerConsistentIn::nNodes, spgInnerConsistentOut::nNodes, spgInnerConsistentOut::nodeNumbers, palloc(), PG_GETARG_POINTER, PG_RETURN_VOID, point_above(), point_below(), point_left(), point_right(), PointerGetDatum, spgInnerConsistentIn::prefixDatum, RTAboveStrategyNumber, RTBelowStrategyNumber, RTContainedByStrategyNumber, RTLeftStrategyNumber, RTRightStrategyNumber, RTSameStrategyNumber, spgInnerConsistentIn::scankeys, ScanKeyData::sk_argument, ScanKeyData::sk_strategy, SPTEST, Point::x, and Point::y.

{
    spgInnerConsistentIn *in = (spgInnerConsistentIn *) PG_GETARG_POINTER(0);
    spgInnerConsistentOut *out = (spgInnerConsistentOut *) PG_GETARG_POINTER(1);
    Point      *centroid;
    int         which;
    int         i;

    Assert(in->hasPrefix);
    centroid = DatumGetPointP(in->prefixDatum);

    if (in->allTheSame)
    {
        /* Report that all nodes should be visited */
        out->nNodes = in->nNodes;
        out->nodeNumbers = (int *) palloc(sizeof(int) * in->nNodes);
        for (i = 0; i < in->nNodes; i++)
            out->nodeNumbers[i] = i;
        PG_RETURN_VOID();
    }

    Assert(in->nNodes == 4);

    /* "which" is a bitmask of quadrants that satisfy all constraints */
    which = (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4);

    for (i = 0; i < in->nkeys; i++)
    {
        Point      *query = DatumGetPointP(in->scankeys[i].sk_argument);
        BOX        *boxQuery;

        switch (in->scankeys[i].sk_strategy)
        {
            case RTLeftStrategyNumber:
                if (SPTEST(point_right, centroid, query))
                    which &= (1 << 3) | (1 << 4);
                break;
            case RTRightStrategyNumber:
                if (SPTEST(point_left, centroid, query))
                    which &= (1 << 1) | (1 << 2);
                break;
            case RTSameStrategyNumber:
                which &= (1 << getQuadrant(centroid, query));
                break;
            case RTBelowStrategyNumber:
                if (SPTEST(point_above, centroid, query))
                    which &= (1 << 2) | (1 << 3);
                break;
            case RTAboveStrategyNumber:
                if (SPTEST(point_below, centroid, query))
                    which &= (1 << 1) | (1 << 4);
                break;
            case RTContainedByStrategyNumber:

                /*
                 * For this operator, the query is a box not a point.  We
                 * cheat to the extent of assuming that DatumGetPointP won't
                 * do anything that would be bad for a pointer-to-box.
                 */
                boxQuery = DatumGetBoxP(in->scankeys[i].sk_argument);

                if (DatumGetBool(DirectFunctionCall2(box_contain_pt,
                                                   PointerGetDatum(boxQuery),
                                                 PointerGetDatum(centroid))))
                {
                    /* centroid is in box, so all quadrants are OK */
                }
                else
                {
                    /* identify quadrant(s) containing all corners of box */
                    Point       p;
                    int         r = 0;

                    p = boxQuery->low;
                    r |= 1 << getQuadrant(centroid, &p);
                    p.y = boxQuery->high.y;
                    r |= 1 << getQuadrant(centroid, &p);
                    p = boxQuery->high;
                    r |= 1 << getQuadrant(centroid, &p);
                    p.x = boxQuery->low.x;
                    r |= 1 << getQuadrant(centroid, &p);

                    which &= r;
                }
                break;
            default:
                elog(ERROR, "unrecognized strategy number: %d",
                     in->scankeys[i].sk_strategy);
                break;
        }

        if (which == 0)
            break;              /* no need to consider remaining conditions */
    }

    /* We must descend into the quadrant(s) identified by which */
    out->nodeNumbers = (int *) palloc(sizeof(int) * 4);
    out->nNodes = 0;
    for (i = 1; i <= 4; i++)
    {
        if (which & (1 << i))
            out->nodeNumbers[out->nNodes++] = i - 1;
    }

    PG_RETURN_VOID();
}

Datum spg_quad_leaf_consistent ( PG_FUNCTION_ARGS   ) 

Definition at line 303 of file spgquadtreeproc.c.

References box_contain_pt(), DatumGetPointP, elog, ERROR, i, spgLeafConsistentIn::leafDatum, spgLeafConsistentOut::leafValue, spgLeafConsistentIn::nkeys, PG_GETARG_POINTER, PG_RETURN_BOOL, point_above(), point_below(), point_eq(), point_left(), point_right(), spgLeafConsistentOut::recheck, RTAboveStrategyNumber, RTBelowStrategyNumber, RTContainedByStrategyNumber, RTLeftStrategyNumber, RTRightStrategyNumber, RTSameStrategyNumber, spgLeafConsistentIn::scankeys, ScanKeyData::sk_argument, ScanKeyData::sk_strategy, and SPTEST.

{
    spgLeafConsistentIn *in = (spgLeafConsistentIn *) PG_GETARG_POINTER(0);
    spgLeafConsistentOut *out = (spgLeafConsistentOut *) PG_GETARG_POINTER(1);
    Point      *datum = DatumGetPointP(in->leafDatum);
    bool        res;
    int         i;

    /* all tests are exact */
    out->recheck = false;

    /* leafDatum is what it is... */
    out->leafValue = in->leafDatum;

    /* Perform the required comparison(s) */
    res = true;
    for (i = 0; i < in->nkeys; i++)
    {
        Point      *query = DatumGetPointP(in->scankeys[i].sk_argument);

        switch (in->scankeys[i].sk_strategy)
        {
            case RTLeftStrategyNumber:
                res = SPTEST(point_left, datum, query);
                break;
            case RTRightStrategyNumber:
                res = SPTEST(point_right, datum, query);
                break;
            case RTSameStrategyNumber:
                res = SPTEST(point_eq, datum, query);
                break;
            case RTBelowStrategyNumber:
                res = SPTEST(point_below, datum, query);
                break;
            case RTAboveStrategyNumber:
                res = SPTEST(point_above, datum, query);
                break;
            case RTContainedByStrategyNumber:

                /*
                 * For this operator, the query is a box not a point.  We
                 * cheat to the extent of assuming that DatumGetPointP won't
                 * do anything that would be bad for a pointer-to-box.
                 */
                res = SPTEST(box_contain_pt, query, datum);
                break;
            default:
                elog(ERROR, "unrecognized strategy number: %d",
                     in->scankeys[i].sk_strategy);
                break;
        }

        if (!res)
            break;
    }

    PG_RETURN_BOOL(res);
}

Datum spg_quad_picksplit ( PG_FUNCTION_ARGS   ) 

Definition at line 136 of file spgquadtreeproc.c.

References DatumGetPointP, spgPickSplitIn::datums, getQuadrant(), spgPickSplitOut::hasPrefix, i, spgPickSplitOut::leafTupleDatums, spgPickSplitOut::mapTuplesToNodes, spgPickSplitOut::nNodes, spgPickSplitOut::nodeLabels, spgPickSplitIn::nTuples, palloc(), palloc0(), PG_GETARG_POINTER, PG_RETURN_VOID, PointPGetDatum, spgPickSplitOut::prefixDatum, qsort, Point::x, x_cmp(), Point::y, and y_cmp().

{
    spgPickSplitIn *in = (spgPickSplitIn *) PG_GETARG_POINTER(0);
    spgPickSplitOut *out = (spgPickSplitOut *) PG_GETARG_POINTER(1);
    int         i;
    Point      *centroid;

#ifdef USE_MEDIAN
    /* Use the median values of x and y as the centroid point */
    Point     **sorted;

    sorted = palloc(sizeof(*sorted) * in->nTuples);
    for (i = 0; i < in->nTuples; i++)
        sorted[i] = DatumGetPointP(in->datums[i]);

    centroid = palloc(sizeof(*centroid));

    qsort(sorted, in->nTuples, sizeof(*sorted), x_cmp);
    centroid->x = sorted[in->nTuples >> 1]->x;
    qsort(sorted, in->nTuples, sizeof(*sorted), y_cmp);
    centroid->y = sorted[in->nTuples >> 1]->y;
#else
    /* Use the average values of x and y as the centroid point */
    centroid = palloc0(sizeof(*centroid));

    for (i = 0; i < in->nTuples; i++)
    {
        centroid->x += DatumGetPointP(in->datums[i])->x;
        centroid->y += DatumGetPointP(in->datums[i])->y;
    }

    centroid->x /= in->nTuples;
    centroid->y /= in->nTuples;
#endif

    out->hasPrefix = true;
    out->prefixDatum = PointPGetDatum(centroid);

    out->nNodes = 4;
    out->nodeLabels = NULL;     /* we don't need node labels */

    out->mapTuplesToNodes = palloc(sizeof(int) * in->nTuples);
    out->leafTupleDatums = palloc(sizeof(Datum) * in->nTuples);

    for (i = 0; i < in->nTuples; i++)
    {
        Point      *p = DatumGetPointP(in->datums[i]);
        int         quadrant = getQuadrant(centroid, p) - 1;

        out->leafTupleDatums[i] = PointPGetDatum(p);
        out->mapTuplesToNodes[i] = quadrant;
    }

    PG_RETURN_VOID();
}

Datum spg_text_choose ( PG_FUNCTION_ARGS   ) 

Definition at line 141 of file spgtextproc.c.

References spgChooseOut::addNode, spgChooseIn::allTheSame, commonPrefix(), spgChooseIn::datum, DatumGetTextPP, formTextDatum(), spgChooseIn::hasPrefix, i, spgChooseIn::level, spgChooseOut::matchNode, spgChooseIn::nNodes, spgChooseIn::nodeLabels, NULL, PG_GETARG_POINTER, PG_RETURN_VOID, spgChooseIn::prefixDatum, spgChooseOut::result, spgChooseOut::resultType, searchChar(), spgChooseOut::splitTuple, UInt8GetDatum, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    spgChooseIn *in = (spgChooseIn *) PG_GETARG_POINTER(0);
    spgChooseOut *out = (spgChooseOut *) PG_GETARG_POINTER(1);
    text       *inText = DatumGetTextPP(in->datum);
    char       *inStr = VARDATA_ANY(inText);
    int         inSize = VARSIZE_ANY_EXHDR(inText);
    uint8       nodeChar = '\0';
    int         i = 0;
    int         commonLen = 0;

    /* Check for prefix match, set nodeChar to first byte after prefix */
    if (in->hasPrefix)
    {
        text       *prefixText = DatumGetTextPP(in->prefixDatum);
        char       *prefixStr = VARDATA_ANY(prefixText);
        int         prefixSize = VARSIZE_ANY_EXHDR(prefixText);

        commonLen = commonPrefix(inStr + in->level,
                                 prefixStr,
                                 inSize - in->level,
                                 prefixSize);

        if (commonLen == prefixSize)
        {
            if (inSize - in->level > commonLen)
                nodeChar = *(uint8 *) (inStr + in->level + commonLen);
            else
                nodeChar = '\0';
        }
        else
        {
            /* Must split tuple because incoming value doesn't match prefix */
            out->resultType = spgSplitTuple;

            if (commonLen == 0)
            {
                out->result.splitTuple.prefixHasPrefix = false;
            }
            else
            {
                out->result.splitTuple.prefixHasPrefix = true;
                out->result.splitTuple.prefixPrefixDatum =
                    formTextDatum(prefixStr, commonLen);
            }
            out->result.splitTuple.nodeLabel =
                UInt8GetDatum(*(prefixStr + commonLen));

            if (prefixSize - commonLen == 1)
            {
                out->result.splitTuple.postfixHasPrefix = false;
            }
            else
            {
                out->result.splitTuple.postfixHasPrefix = true;
                out->result.splitTuple.postfixPrefixDatum =
                    formTextDatum(prefixStr + commonLen + 1,
                                  prefixSize - commonLen - 1);
            }

            PG_RETURN_VOID();
        }
    }
    else if (inSize > in->level)
    {
        nodeChar = *(uint8 *) (inStr + in->level);
    }
    else
    {
        nodeChar = '\0';
    }

    /* Look up nodeChar in the node label array */
    if (searchChar(in->nodeLabels, in->nNodes, nodeChar, &i))
    {
        /*
         * Descend to existing node.  (If in->allTheSame, the core code will
         * ignore our nodeN specification here, but that's OK.  We still have
         * to provide the correct levelAdd and restDatum values, and those are
         * the same regardless of which node gets chosen by core.)
         */
        out->resultType = spgMatchNode;
        out->result.matchNode.nodeN = i;
        out->result.matchNode.levelAdd = commonLen + 1;
        if (inSize - in->level - commonLen - 1 > 0)
            out->result.matchNode.restDatum =
                formTextDatum(inStr + in->level + commonLen + 1,
                              inSize - in->level - commonLen - 1);
        else
            out->result.matchNode.restDatum =
                formTextDatum(NULL, 0);
    }
    else if (in->allTheSame)
    {
        /*
         * Can't use AddNode action, so split the tuple.  The upper tuple has
         * the same prefix as before and uses an empty node label for the
         * lower tuple.  The lower tuple has no prefix and the same node
         * labels as the original tuple.
         */
        out->resultType = spgSplitTuple;
        out->result.splitTuple.prefixHasPrefix = in->hasPrefix;
        out->result.splitTuple.prefixPrefixDatum = in->prefixDatum;
        out->result.splitTuple.nodeLabel = UInt8GetDatum('\0');
        out->result.splitTuple.postfixHasPrefix = false;
    }
    else
    {
        /* Add a node for the not-previously-seen nodeChar value */
        out->resultType = spgAddNode;
        out->result.addNode.nodeLabel = UInt8GetDatum(nodeChar);
        out->result.addNode.nodeN = i;
    }

    PG_RETURN_VOID();
}

Datum spg_text_config ( PG_FUNCTION_ARGS   ) 

Definition at line 53 of file spgtextproc.c.

References spgConfigOut::canReturnData, spgConfigOut::labelType, spgConfigOut::longValuesOK, PG_GETARG_POINTER, PG_RETURN_VOID, and spgConfigOut::prefixType.

{
    /* spgConfigIn *cfgin = (spgConfigIn *) PG_GETARG_POINTER(0); */
    spgConfigOut *cfg = (spgConfigOut *) PG_GETARG_POINTER(1);

    cfg->prefixType = TEXTOID;
    cfg->labelType = CHAROID;
    cfg->canReturnData = true;
    cfg->longValuesOK = true;   /* suffixing will shorten long values */
    PG_RETURN_VOID();
}

Datum spg_text_inner_consistent ( PG_FUNCTION_ARGS   ) 

Definition at line 367 of file spgtextproc.c.

References Assert, BTEqualStrategyNumber, BTGreaterEqualStrategyNumber, BTGreaterStrategyNumber, BTLessEqualStrategyNumber, BTLessStrategyNumber, datumCopy(), DatumGetPointer, DatumGetTextPP, DatumGetUInt8, elog, ERROR, spgInnerConsistentIn::hasPrefix, i, lc_collate_is_c(), spgInnerConsistentIn::level, spgInnerConsistentOut::levelAdds, memcmp(), Min, spgInnerConsistentIn::nkeys, spgInnerConsistentOut::nNodes, spgInnerConsistentIn::nNodes, spgInnerConsistentIn::nodeLabels, spgInnerConsistentOut::nodeNumbers, NULL, palloc(), PG_GET_COLLATION, PG_GETARG_POINTER, PG_RETURN_VOID, PointerGetDatum, spgInnerConsistentIn::prefixDatum, spgInnerConsistentIn::reconstructedValue, spgInnerConsistentOut::reconstructedValues, spgInnerConsistentIn::scankeys, SET_VARSIZE, ScanKeyData::sk_argument, ScanKeyData::sk_strategy, VARDATA, VARDATA_ANY, VARHDRSZ, and VARSIZE_ANY_EXHDR.

{
    spgInnerConsistentIn *in = (spgInnerConsistentIn *) PG_GETARG_POINTER(0);
    spgInnerConsistentOut *out = (spgInnerConsistentOut *) PG_GETARG_POINTER(1);
    bool        collate_is_c = lc_collate_is_c(PG_GET_COLLATION());
    text       *reconstrText = NULL;
    int         maxReconstrLen = 0;
    text       *prefixText = NULL;
    int         prefixSize = 0;
    int         i;

    /*
     * Reconstruct values represented at this tuple, including parent data,
     * prefix of this tuple if any, and the node label if any.  in->level
     * should be the length of the previously reconstructed value, and the
     * number of bytes added here is prefixSize or prefixSize + 1.
     *
     * Note: we assume that in->reconstructedValue isn't toasted and doesn't
     * have a short varlena header.  This is okay because it must have been
     * created by a previous invocation of this routine, and we always emit
     * long-format reconstructed values.
     */
    Assert(in->level == 0 ? DatumGetPointer(in->reconstructedValue) == NULL :
    VARSIZE_ANY_EXHDR(DatumGetPointer(in->reconstructedValue)) == in->level);

    maxReconstrLen = in->level + 1;
    if (in->hasPrefix)
    {
        prefixText = DatumGetTextPP(in->prefixDatum);
        prefixSize = VARSIZE_ANY_EXHDR(prefixText);
        maxReconstrLen += prefixSize;
    }

    reconstrText = palloc(VARHDRSZ + maxReconstrLen);
    SET_VARSIZE(reconstrText, VARHDRSZ + maxReconstrLen);

    if (in->level)
        memcpy(VARDATA(reconstrText),
               VARDATA(DatumGetPointer(in->reconstructedValue)),
               in->level);
    if (prefixSize)
        memcpy(((char *) VARDATA(reconstrText)) + in->level,
               VARDATA_ANY(prefixText),
               prefixSize);
    /* last byte of reconstrText will be filled in below */

    /*
     * Scan the child nodes.  For each one, complete the reconstructed value
     * and see if it's consistent with the query.  If so, emit an entry into
     * the output arrays.
     */
    out->nodeNumbers = (int *) palloc(sizeof(int) * in->nNodes);
    out->levelAdds = (int *) palloc(sizeof(int) * in->nNodes);
    out->reconstructedValues = (Datum *) palloc(sizeof(Datum) * in->nNodes);
    out->nNodes = 0;

    for (i = 0; i < in->nNodes; i++)
    {
        uint8       nodeChar = DatumGetUInt8(in->nodeLabels[i]);
        int         thisLen;
        bool        res = true;
        int         j;

        /* If nodeChar is zero, don't include it in data */
        if (nodeChar == '\0')
            thisLen = maxReconstrLen - 1;
        else
        {
            ((char *) VARDATA(reconstrText))[maxReconstrLen - 1] = nodeChar;
            thisLen = maxReconstrLen;
        }

        for (j = 0; j < in->nkeys; j++)
        {
            StrategyNumber strategy = in->scankeys[j].sk_strategy;
            text       *inText;
            int         inSize;
            int         r;

            /*
             * If it's a collation-aware operator, but the collation is C, we
             * can treat it as non-collation-aware.  With non-C collation we
             * need to traverse whole tree :-( so there's no point in making
             * any check here.
             */
            if (strategy > 10)
            {
                if (collate_is_c)
                    strategy -= 10;
                else
                    continue;
            }

            inText = DatumGetTextPP(in->scankeys[j].sk_argument);
            inSize = VARSIZE_ANY_EXHDR(inText);

            r = memcmp(VARDATA(reconstrText), VARDATA_ANY(inText),
                       Min(inSize, thisLen));

            switch (strategy)
            {
                case BTLessStrategyNumber:
                case BTLessEqualStrategyNumber:
                    if (r > 0)
                        res = false;
                    break;
                case BTEqualStrategyNumber:
                    if (r != 0 || inSize < thisLen)
                        res = false;
                    break;
                case BTGreaterEqualStrategyNumber:
                case BTGreaterStrategyNumber:
                    if (r < 0)
                        res = false;
                    break;
                default:
                    elog(ERROR, "unrecognized strategy number: %d",
                         in->scankeys[j].sk_strategy);
                    break;
            }

            if (!res)
                break;          /* no need to consider remaining conditions */
        }

        if (res)
        {
            out->nodeNumbers[out->nNodes] = i;
            out->levelAdds[out->nNodes] = thisLen - in->level;
            SET_VARSIZE(reconstrText, VARHDRSZ + thisLen);
            out->reconstructedValues[out->nNodes] =
                datumCopy(PointerGetDatum(reconstrText), false, -1);
            out->nNodes++;
        }
    }

    PG_RETURN_VOID();
}

Datum spg_text_leaf_consistent ( PG_FUNCTION_ARGS   ) 

Definition at line 507 of file spgtextproc.c.

References Assert, BTEqualStrategyNumber, BTGreaterEqualStrategyNumber, BTGreaterStrategyNumber, BTLessEqualStrategyNumber, BTLessStrategyNumber, DatumGetPointer, DatumGetTextP, DatumGetTextPP, elog, ERROR, spgLeafConsistentIn::leafDatum, spgLeafConsistentOut::leafValue, spgLeafConsistentIn::level, memcmp(), Min, spgLeafConsistentIn::nkeys, NULL, palloc(), PG_GET_COLLATION, PG_GETARG_POINTER, PG_RETURN_BOOL, pg_verifymbstr(), PointerGetDatum, spgLeafConsistentOut::recheck, spgLeafConsistentIn::reconstructedValue, spgLeafConsistentIn::scankeys, SET_VARSIZE, ScanKeyData::sk_argument, ScanKeyData::sk_strategy, VARDATA, VARDATA_ANY, VARHDRSZ, VARSIZE_ANY_EXHDR, and varstr_cmp().

{
    spgLeafConsistentIn *in = (spgLeafConsistentIn *) PG_GETARG_POINTER(0);
    spgLeafConsistentOut *out = (spgLeafConsistentOut *) PG_GETARG_POINTER(1);
    int         level = in->level;
    text       *leafValue,
               *reconstrValue = NULL;
    char       *fullValue;
    int         fullLen;
    bool        res;
    int         j;

    /* all tests are exact */
    out->recheck = false;

    leafValue = DatumGetTextPP(in->leafDatum);

    if (DatumGetPointer(in->reconstructedValue))
        reconstrValue = DatumGetTextP(in->reconstructedValue);

    Assert(level == 0 ? reconstrValue == NULL :
           VARSIZE_ANY_EXHDR(reconstrValue) == level);

    /* Reconstruct the full string represented by this leaf tuple */
    fullLen = level + VARSIZE_ANY_EXHDR(leafValue);
    if (VARSIZE_ANY_EXHDR(leafValue) == 0 && level > 0)
    {
        fullValue = VARDATA(reconstrValue);
        out->leafValue = PointerGetDatum(reconstrValue);
    }
    else
    {
        text       *fullText = palloc(VARHDRSZ + fullLen);

        SET_VARSIZE(fullText, VARHDRSZ + fullLen);
        fullValue = VARDATA(fullText);
        if (level)
            memcpy(fullValue, VARDATA(reconstrValue), level);
        if (VARSIZE_ANY_EXHDR(leafValue) > 0)
            memcpy(fullValue + level, VARDATA_ANY(leafValue),
                   VARSIZE_ANY_EXHDR(leafValue));
        out->leafValue = PointerGetDatum(fullText);
    }

    /* Perform the required comparison(s) */
    res = true;
    for (j = 0; j < in->nkeys; j++)
    {
        StrategyNumber strategy = in->scankeys[j].sk_strategy;
        text       *query = DatumGetTextPP(in->scankeys[j].sk_argument);
        int         queryLen = VARSIZE_ANY_EXHDR(query);
        int         r;

        if (strategy > 10)
        {
            /* Collation-aware comparison */
            strategy -= 10;

            /* If asserts enabled, verify encoding of reconstructed string */
            Assert(pg_verifymbstr(fullValue, fullLen, false));

            r = varstr_cmp(fullValue, Min(queryLen, fullLen),
                           VARDATA_ANY(query), Min(queryLen, fullLen),
                           PG_GET_COLLATION());
        }
        else
        {
            /* Non-collation-aware comparison */
            r = memcmp(fullValue, VARDATA_ANY(query), Min(queryLen, fullLen));
        }

        if (r == 0)
        {
            if (queryLen > fullLen)
                r = -1;
            else if (queryLen < fullLen)
                r = 1;
        }

        switch (strategy)
        {
            case BTLessStrategyNumber:
                res = (r < 0);
                break;
            case BTLessEqualStrategyNumber:
                res = (r <= 0);
                break;
            case BTEqualStrategyNumber:
                res = (r == 0);
                break;
            case BTGreaterEqualStrategyNumber:
                res = (r >= 0);
                break;
            case BTGreaterStrategyNumber:
                res = (r > 0);
                break;
            default:
                elog(ERROR, "unrecognized strategy number: %d",
                     in->scankeys[j].sk_strategy);
                res = false;
                break;
        }

        if (!res)
            break;              /* no need to consider remaining conditions */
    }

    PG_RETURN_BOOL(res);
}

Datum spg_text_picksplit ( PG_FUNCTION_ARGS   ) 

Definition at line 274 of file spgtextproc.c.

References spgNodePtr::c, cmpNodePtr(), commonPrefix(), spgNodePtr::d, DatumGetTextPP, spgPickSplitIn::datums, formTextDatum(), spgPickSplitOut::hasPrefix, spgNodePtr::i, i, spgPickSplitOut::leafTupleDatums, spgPickSplitOut::mapTuplesToNodes, Min, spgPickSplitOut::nNodes, spgPickSplitOut::nodeLabels, spgPickSplitIn::nTuples, NULL, palloc(), PG_GETARG_POINTER, PG_RETURN_VOID, spgPickSplitOut::prefixDatum, qsort, SPGIST_MAX_PREFIX_LENGTH, UInt8GetDatum, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    spgPickSplitIn *in = (spgPickSplitIn *) PG_GETARG_POINTER(0);
    spgPickSplitOut *out = (spgPickSplitOut *) PG_GETARG_POINTER(1);
    text       *text0 = DatumGetTextPP(in->datums[0]);
    int         i,
                commonLen;
    spgNodePtr *nodes;

    /* Identify longest common prefix, if any */
    commonLen = VARSIZE_ANY_EXHDR(text0);
    for (i = 1; i < in->nTuples && commonLen > 0; i++)
    {
        text       *texti = DatumGetTextPP(in->datums[i]);
        int         tmp = commonPrefix(VARDATA_ANY(text0),
                                       VARDATA_ANY(texti),
                                       VARSIZE_ANY_EXHDR(text0),
                                       VARSIZE_ANY_EXHDR(texti));

        if (tmp < commonLen)
            commonLen = tmp;
    }

    /*
     * Limit the prefix length, if necessary, to ensure that the resulting
     * inner tuple will fit on a page.
     */
    commonLen = Min(commonLen, SPGIST_MAX_PREFIX_LENGTH);

    /* Set node prefix to be that string, if it's not empty */
    if (commonLen == 0)
    {
        out->hasPrefix = false;
    }
    else
    {
        out->hasPrefix = true;
        out->prefixDatum = formTextDatum(VARDATA_ANY(text0), commonLen);
    }

    /* Extract the node label (first non-common byte) from each value */
    nodes = (spgNodePtr *) palloc(sizeof(spgNodePtr) * in->nTuples);

    for (i = 0; i < in->nTuples; i++)
    {
        text       *texti = DatumGetTextPP(in->datums[i]);

        if (commonLen < VARSIZE_ANY_EXHDR(texti))
            nodes[i].c = *(uint8 *) (VARDATA_ANY(texti) + commonLen);
        else
            nodes[i].c = '\0';  /* use \0 if string is all common */
        nodes[i].i = i;
        nodes[i].d = in->datums[i];
    }

    /*
     * Sort by label bytes so that we can group the values into nodes.  This
     * also ensures that the nodes are ordered by label value, allowing the
     * use of binary search in searchChar.
     */
    qsort(nodes, in->nTuples, sizeof(*nodes), cmpNodePtr);

    /* And emit results */
    out->nNodes = 0;
    out->nodeLabels = (Datum *) palloc(sizeof(Datum) * in->nTuples);
    out->mapTuplesToNodes = (int *) palloc(sizeof(int) * in->nTuples);
    out->leafTupleDatums = (Datum *) palloc(sizeof(Datum) * in->nTuples);

    for (i = 0; i < in->nTuples; i++)
    {
        text       *texti = DatumGetTextPP(nodes[i].d);
        Datum       leafD;

        if (i == 0 || nodes[i].c != nodes[i - 1].c)
        {
            out->nodeLabels[out->nNodes] = UInt8GetDatum(nodes[i].c);
            out->nNodes++;
        }

        if (commonLen < VARSIZE_ANY_EXHDR(texti))
            leafD = formTextDatum(VARDATA_ANY(texti) + commonLen + 1,
                                  VARSIZE_ANY_EXHDR(texti) - commonLen - 1);
        else
            leafD = formTextDatum(NULL, 0);

        out->leafTupleDatums[nodes[i].i] = leafD;
        out->mapTuplesToNodes[nodes[i].i] = out->nNodes - 1;
    }

    PG_RETURN_VOID();
}

Datum split_text ( PG_FUNCTION_ARGS   ) 

Definition at line 3118 of file varlena.c.

References cstring_to_text(), ereport, errcode(), errmsg(), ERROR, TextPositionState::len1, TextPositionState::len2, PG_GETARG_INT32, PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, PointerGetDatum, text_position_cleanup(), text_position_next(), text_position_setup(), and text_substring().

{
    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;
    int         start_posn;
    int         end_posn;
    text       *result_text;

    /* field number is 1 based */
    if (fldnum < 1)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("field position must be greater than zero")));

    text_position_setup(inputstring, fldsep, &state);

    /*
     * Note: we check the converted string length, not the original, because
     * they could be different if the input contained invalid encoding.
     */
    inputstring_len = state.len1;
    fldsep_len = state.len2;

    /* return empty string for empty input string */
    if (inputstring_len < 1)
    {
        text_position_cleanup(&state);
        PG_RETURN_TEXT_P(cstring_to_text(""));
    }

    /* empty field separator */
    if (fldsep_len < 1)
    {
        text_position_cleanup(&state);
        /* if first field, return input string, else empty string */
        if (fldnum == 1)
            PG_RETURN_TEXT_P(inputstring);
        else
            PG_RETURN_TEXT_P(cstring_to_text(""));
    }

    /* identify bounds of first field */
    start_posn = 1;
    end_posn = text_position_next(1, &state);

    /* special case if fldsep not found at all */
    if (end_posn == 0)
    {
        text_position_cleanup(&state);
        /* if field 1 requested, return input string, else empty string */
        if (fldnum == 1)
            PG_RETURN_TEXT_P(inputstring);
        else
            PG_RETURN_TEXT_P(cstring_to_text(""));
    }

    while (end_posn > 0 && --fldnum > 0)
    {
        /* identify bounds of next field */
        start_posn = end_posn + fldsep_len;
        end_posn = text_position_next(start_posn, &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)
            result_text = text_substring(PointerGetDatum(inputstring),
                                         start_posn,
                                         -1,
                                         true);
        else
            result_text = cstring_to_text("");
    }
    else
    {
        /* non-last field requested */
        result_text = text_substring(PointerGetDatum(inputstring),
                                     start_posn,
                                     end_posn - start_posn,
                                     false);
    }

    PG_RETURN_TEXT_P(result_text);
}

bool SplitDirectoriesString ( char *  rawstring,
char  separator,
List **  namelist 
)

Definition at line 2482 of file varlena.c.

References canonicalize_path(), lappend(), MAXPGPATH, memmove, NULL, and pstrdup().

Referenced by PostmasterMain().

{
    char       *nextp = rawstring;
    bool        done = false;

    *namelist = NIL;

    while (isspace((unsigned char) *nextp))
        nextp++;                /* skip leading whitespace */

    if (*nextp == '\0')
        return true;            /* 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)
                    return false;       /* 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 (!isspace((unsigned char) *nextp))
                    endp = nextp + 1;
                nextp++;
            }
            if (curname == endp)
                return false;   /* empty unquoted name not allowed */
        }

        while (isspace((unsigned char) *nextp))
            nextp++;            /* skip trailing whitespace */

        if (*nextp == separator)
        {
            nextp++;
            while (isspace((unsigned char) *nextp))
                nextp++;        /* skip leading whitespace for next */
            /* we expect another name, so done remains false */
        }
        else if (*nextp == '\0')
            done = true;
        else
            return false;       /* 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';

        /*
         * Finished isolating current name --- add it to list
         */
        curname = pstrdup(curname);
        canonicalize_path(curname);
        *namelist = lappend(*namelist, curname);

        /* Loop back if we didn't reach end of string */
    } while (!done);

    return true;
}

bool SplitIdentifierString ( char *  rawstring,
char  separator,
List **  namelist 
)

Definition at line 2357 of file varlena.c.

References Assert, downcase_truncate_identifier(), lappend(), memmove, NULL, pfree(), and truncate_identifier().

Referenced by check_datestyle(), check_log_destination(), check_search_path(), check_synchronous_standby_names(), check_temp_tablespaces(), load_libraries(), parse_extension_control_file(), PostmasterMain(), PrepareTempTablespaces(), recomputeNamespacePath(), stringToQualifiedNameList(), SyncRepGetStandbyPriority(), and textToQualifiedNameList().

{
    char       *nextp = rawstring;
    bool        done = false;

    *namelist = NIL;

    while (isspace((unsigned char) *nextp))
        nextp++;                /* skip leading whitespace */

    if (*nextp == '\0')
        return true;            /* 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)
                    return false;       /* 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 &&
                   !isspace((unsigned char) *nextp))
                nextp++;
            endp = nextp;
            if (curname == nextp)
                return false;   /* empty unquoted name not allowed */

            /*
             * Downcase the identifier, using same code as main lexer does.
             *
             * XXX because we want to overwrite the input in-place, we cannot
             * support a downcasing transformation that increases the string
             * length.  This is not a problem given the current implementation
             * of downcase_truncate_identifier, but we'll probably have to do
             * something about this someday.
             */
            len = endp - curname;
            downname = downcase_truncate_identifier(curname, len, false);
            Assert(strlen(downname) <= len);
            strncpy(curname, downname, len);
            pfree(downname);
        }

        while (isspace((unsigned char) *nextp))
            nextp++;            /* skip trailing whitespace */

        if (*nextp == separator)
        {
            nextp++;
            while (isspace((unsigned char) *nextp))
                nextp++;        /* skip leading whitespace for next */
            /* we expect another name, so done remains false */
        }
        else if (*nextp == '\0')
            done = true;
        else
            return false;       /* invalid syntax */

        /* Now safe to overwrite separator with a null */
        *endp = '\0';

        /* Truncate name if it's overlength */
        truncate_identifier(curname, strlen(curname), false);

        /*
         * Finished isolating current name --- add it to list
         */
        *namelist = lappend(*namelist, curname);

        /* Loop back if we didn't reach end of string */
    } while (!done);

    return true;
}

Datum string_agg_finalfn ( PG_FUNCTION_ARGS   ) 

Definition at line 3785 of file varlena.c.

References AggCheckCallContext(), Assert, cstring_to_text_with_len(), StringInfoData::data, StringInfoData::len, NULL, PG_ARGISNULL, PG_GETARG_POINTER, PG_RETURN_NULL, and PG_RETURN_TEXT_P.

{
    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)
        PG_RETURN_TEXT_P(cstring_to_text_with_len(state->data, state->len));
    else
        PG_RETURN_NULL();
}

Datum string_agg_transfn ( PG_FUNCTION_ARGS   ) 

Definition at line 3759 of file varlena.c.

References appendStringInfoText(), makeStringAggState(), NULL, PG_ARGISNULL, PG_GETARG_POINTER, PG_GETARG_TEXT_PP, and PG_RETURN_POINTER.

{
    StringInfo  state;

    state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);

    /* Append the value unless null. */
    if (!PG_ARGISNULL(1))
    {
        /* On the first time through, we ignore the delimiter. */
        if (state == NULL)
            state = makeStringAggState(fcinfo);
        else if (!PG_ARGISNULL(2))
            appendStringInfoText(state, PG_GETARG_TEXT_PP(2));  /* delimiter */

        appendStringInfoText(state, PG_GETARG_TEXT_PP(1));      /* value */
    }

    /*
     * The transition type for string_agg() is declared to be "internal",
     * which is a pass-by-value type the same size as a pointer.
     */
    PG_RETURN_POINTER(state);
}

List* stringToQualifiedNameList ( const char *  string  ) 

Definition at line 1352 of file regproc.c.

References ereport, errcode(), errmsg(), ERROR, lappend(), lfirst, list_free(), makeString(), NIL, pfree(), pstrdup(), and SplitIdentifierString().

Referenced by check_TSCurrentConfig(), GetCurrentParser(), getTSCurrentConfig(), parseNameAndArgTypes(), regclassin(), regconfigin(), regdictionaryin(), regoperin(), regprocin(), RelationNameGetTupleDesc(), thesaurus_init(), tsa_set_curdict_byname(), tsa_set_curprs_byname(), tsvector_update_trigger(), and unaccent_dict().

{
    char       *rawname;
    List       *result = NIL;
    List       *namelist;
    ListCell   *l;

    /* We need a modifiable copy of the input string. */
    rawname = pstrdup(string);

    if (!SplitIdentifierString(rawname, '.', &namelist))
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_NAME),
                 errmsg("invalid name syntax")));

    if (namelist == NIL)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_NAME),
                 errmsg("invalid name syntax")));

    foreach(l, namelist)
    {
        char       *curname = (char *) lfirst(l);

        result = lappend(result, makeString(pstrdup(curname)));
    }

    pfree(rawname);
    list_free(namelist);

    return result;
}

Datum suppress_redundant_updates_trigger ( PG_FUNCTION_ARGS   ) 

Definition at line 29 of file trigfuncs.c.

References CALLED_AS_TRIGGER, ereport, errcode(), errmsg(), ERROR, HEAP_XACT_MASK, HeapTupleHeaderGetNatts, HeapTupleHeaderGetOid, HeapTupleHeaderSetOid, memcmp(), offsetof, OidIsValid, PointerGetDatum, RelationData::rd_rel, HeapTupleData::t_data, HeapTupleData::t_len, TriggerData::tg_event, TriggerData::tg_newtuple, TriggerData::tg_relation, TriggerData::tg_trigtuple, TRIGGER_FIRED_BEFORE, TRIGGER_FIRED_BY_UPDATE, and TRIGGER_FIRED_FOR_ROW.

{
    TriggerData *trigdata = (TriggerData *) fcinfo->context;
    HeapTuple   newtuple,
                oldtuple,
                rettuple;
    HeapTupleHeader newheader,
                oldheader;

    /* make sure it's called as a trigger */
    if (!CALLED_AS_TRIGGER(fcinfo))
        ereport(ERROR,
                (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
                 errmsg("suppress_redundant_updates_trigger: must be called as trigger")));

    /* and that it's called on update */
    if (!TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
        ereport(ERROR,
                (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
                 errmsg("suppress_redundant_updates_trigger: must be called on update")));

    /* and that it's called before update */
    if (!TRIGGER_FIRED_BEFORE(trigdata->tg_event))
        ereport(ERROR,
                (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
                 errmsg("suppress_redundant_updates_trigger: must be called before update")));

    /* and that it's called for each row */
    if (!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
        ereport(ERROR,
                (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
                 errmsg("suppress_redundant_updates_trigger: must be called for each row")));

    /* get tuple data, set default result */
    rettuple = newtuple = trigdata->tg_newtuple;
    oldtuple = trigdata->tg_trigtuple;

    newheader = newtuple->t_data;
    oldheader = oldtuple->t_data;

    /*
     * We are called before the OID, if any, has been transcribed from the old
     * tuple to the new (in heap_update).  To avoid a bogus compare failure,
     * copy the OID now.  But check that someone didn't already put another
     * OID value into newtuple.  (That's not actually possible at present, but
     * maybe someday.)
     */
    if (trigdata->tg_relation->rd_rel->relhasoids &&
        !OidIsValid(HeapTupleHeaderGetOid(newheader)))
        HeapTupleHeaderSetOid(newheader, HeapTupleHeaderGetOid(oldheader));

    /* if the tuple payload is the same ... */
    if (newtuple->t_len == oldtuple->t_len &&
        newheader->t_hoff == oldheader->t_hoff &&
        (HeapTupleHeaderGetNatts(newheader) ==
         HeapTupleHeaderGetNatts(oldheader)) &&
        ((newheader->t_infomask & ~HEAP_XACT_MASK) ==
         (oldheader->t_infomask & ~HEAP_XACT_MASK)) &&
        memcmp(((char *) newheader) + offsetof(HeapTupleHeaderData, t_bits),
               ((char *) oldheader) + offsetof(HeapTupleHeaderData, t_bits),
               newtuple->t_len - offsetof(HeapTupleHeaderData, t_bits)) == 0)
    {
        /* ... then suppress the update */
        rettuple = NULL;
    }

    return PointerGetDatum(rettuple);
}

Datum text_char ( PG_FUNCTION_ARGS   ) 

Definition at line 176 of file char.c.

References PG_GETARG_TEXT_P, PG_RETURN_CHAR, VARDATA, VARHDRSZ, and VARSIZE.

{
    text       *arg1 = PG_GETARG_TEXT_P(0);
    char        result;

    /*
     * An empty input string is converted to \0 (for consistency with charin).
     * If the input is longer than one character, the excess data is silently
     * discarded.
     */
    if (VARSIZE(arg1) > VARHDRSZ)
        result = *(VARDATA(arg1));
    else
        result = '\0';

    PG_RETURN_CHAR(result);
}

Datum text_concat ( PG_FUNCTION_ARGS   ) 

Definition at line 3895 of file varlena.c.

References concat_internal(), NULL, PG_RETURN_NULL, and PG_RETURN_TEXT_P.

{
    text       *result;

    result = concat_internal("", 0, fcinfo);
    if (result == NULL)
        PG_RETURN_NULL();
    PG_RETURN_TEXT_P(result);
}

Datum text_concat_ws ( PG_FUNCTION_ARGS   ) 

Definition at line 3910 of file varlena.c.

References concat_internal(), NULL, PG_ARGISNULL, PG_GETARG_TEXT_PP, PG_RETURN_NULL, PG_RETURN_TEXT_P, and text_to_cstring().

{
    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);
}

Datum text_format ( PG_FUNCTION_ARGS   ) 

Definition at line 4026 of file varlena.c.

References ADVANCE_PARSE_POINTER, appendStringInfoCharMacro, arg, ARR_ELEMTYPE, Assert, cstring_to_text_with_len(), StringInfoData::data, DatumGetInt16, DatumGetInt32, deconstruct_array(), elog, ereport, errcode(), errmsg(), ERROR, fmgr_info(), get_element_type(), get_fn_expr_argtype(), get_fn_expr_variadic(), get_typlenbyvalalign(), getTypeOutputInfo(), initStringInfo(), INT2OID, INT4OID, StringInfoData::len, NULL, OidIsValid, OutputFunctionCall(), pfree(), PG_ARGISNULL, pg_atoi(), PG_GETARG_ARRAYTYPE_P, PG_GETARG_DATUM, PG_GETARG_TEXT_PP, PG_NARGS, PG_RETURN_NULL, PG_RETURN_TEXT_P, text_format_parse_format(), text_format_string_conversion(), value, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

Referenced by text_format_nv().

{
    text       *fmt;
    StringInfoData str;
    const char *cp;
    const char *start_ptr;
    const char *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))
    {
        Oid         arr_typid;
        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-null argument had better be an array.  The parser doesn't
             * enforce this for VARIADIC ANY functions (maybe it should?), so
             * that check uses ereport not just elog.
             */
            arr_typid = get_fn_expr_argtype(fcinfo->flinfo, 1);
            if (!OidIsValid(arr_typid))
                elog(ERROR, "could not determine data type of format() input");

            if (!OidIsValid(get_element_type(arr_typid)))
                ereport(ERROR,
                        (errcode(ERRCODE_DATATYPE_MISMATCH),
                         errmsg("VARIADIC argument must be an array")));

            /* 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);
        }

        nargs = nitems + 1;
        funcvariadic = true;
    }
    else
    {
        /* Non-variadic case, we'll process the arguments individually */
        nargs = PG_NARGS();
        funcvariadic = false;
    }

    /* 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;

        /*
         * If it's not the start of a conversion specifier, just copy it to
         * the output buffer.
         */
        if (*cp != '%')
        {
            appendStringInfoCharMacro(&str, *cp);
            continue;
        }

        ADVANCE_PARSE_POINTER(cp, end_ptr);

        /* 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);

        /*
         * Next we should see the main conversion specifier.  Whether or not
         * an argument position was present, it's known that at least one
         * character remains in the string at this point.  Experience suggests
         * that it's worth checking that that character is one of the expected
         * ones before we try to fetch arguments, so as to produce the least
         * confusing response to a mis-formatted specifier.
         */
        if (strchr("sIL", *cp) == NULL)
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                     errmsg("unrecognized conversion type specifier \"%c\"",
                            *cp)));

        /* 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;
            else if (typid == INT4OID)
                width = DatumGetInt32(value);
            else if (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;

                    getTypeOutputInfo(typid, &typoutputfunc, &typIsVarlena);
                    fmgr_info(typoutputfunc, &typoutputinfo_width);
                    prev_width_type = typid;
                }

                str = OutputFunctionCall(&typoutputinfo_width, value);

                /* pg_atoi will complain about bad data or overflow */
                width = pg_atoi(str, sizeof(int), '\0');

                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++;

        /*
         * Get the appropriate typOutput function, reusing previous one if
         * same type as previous argument.  That's particularly useful in the
         * variadic-array case, but often saves work even for ordinary calls.
         */
        if (typid != prev_type)
        {
            Oid         typoutputfunc;
            bool        typIsVarlena;

            getTypeOutputInfo(typid, &typoutputfunc, &typIsVarlena);
            fmgr_info(typoutputfunc, &typoutputfinfo);
            prev_type = typid;
        }

        /*
         * And now we can format the value.
         */
        switch (*cp)
        {
            case 's':
            case 'I':
            case 'L':
                text_format_string_conversion(&str, *cp, &typoutputfinfo,
                                              value, isNull,
                                              flags, width);
                break;
            default:
                /* should not get here, because of previous check */
                ereport(ERROR,
                        (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                         errmsg("unrecognized conversion type specifier \"%c\"",
                                *cp)));
                break;
        }
    }

    /* Don't need deconstruct_array results anymore. */
    if (elements != NULL)
        pfree(elements);
    if (nulls != NULL)
        pfree(nulls);

    /* Generate results. */
    result = cstring_to_text_with_len(str.data, str.len);
    pfree(str.data);

    PG_RETURN_TEXT_P(result);
}

Datum text_format_nv ( PG_FUNCTION_ARGS   ) 

Definition at line 4534 of file varlena.c.

References text_format().

{
    return text_format(fcinfo);
}

Datum text_ge ( PG_FUNCTION_ARGS   ) 

Definition at line 1657 of file varlena.c.

References PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, and text_cmp().

Referenced by gbt_textge().

{
    text       *arg1 = PG_GETARG_TEXT_PP(0);
    text       *arg2 = PG_GETARG_TEXT_PP(1);
    bool        result;

    result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) >= 0);

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_BOOL(result);
}

Datum text_gt ( PG_FUNCTION_ARGS   ) 

Definition at line 1642 of file varlena.c.

References PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, and text_cmp().

Referenced by gbt_textgt().

{
    text       *arg1 = PG_GETARG_TEXT_PP(0);
    text       *arg2 = PG_GETARG_TEXT_PP(1);
    bool        result;

    result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) > 0);

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_BOOL(result);
}

Datum text_larger ( PG_FUNCTION_ARGS   ) 

Definition at line 1688 of file varlena.c.

References PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, and text_cmp().

{
    text       *arg1 = PG_GETARG_TEXT_PP(0);
    text       *arg2 = PG_GETARG_TEXT_PP(1);
    text       *result;

    result = ((text_cmp(arg1, arg2, PG_GET_COLLATION()) > 0) ? arg1 : arg2);

    PG_RETURN_TEXT_P(result);
}

Datum text_le ( PG_FUNCTION_ARGS   ) 

Definition at line 1627 of file varlena.c.

References PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, and text_cmp().

Referenced by gbt_textle().

{
    text       *arg1 = PG_GETARG_TEXT_PP(0);
    text       *arg2 = PG_GETARG_TEXT_PP(1);
    bool        result;

    result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) <= 0);

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_BOOL(result);
}

Datum text_left ( PG_FUNCTION_ARGS   ) 

Definition at line 3931 of file varlena.c.

References cstring_to_text_with_len(), PG_GETARG_INT32, PG_GETARG_TEXT_PP, pg_mbcharcliplen(), pg_mbstrlen_with_len(), PG_RETURN_TEXT_P, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    text       *str = PG_GETARG_TEXT_PP(0);
    const char *p = VARDATA_ANY(str);
    int         len = VARSIZE_ANY_EXHDR(str);
    int         n = PG_GETARG_INT32(1);
    int         rlen;

    if (n < 0)
        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));
}

Datum text_lt ( PG_FUNCTION_ARGS   ) 

Definition at line 1612 of file varlena.c.

References PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, and text_cmp().

Referenced by gbt_textlt().

{
    text       *arg1 = PG_GETARG_TEXT_PP(0);
    text       *arg2 = PG_GETARG_TEXT_PP(1);
    bool        result;

    result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) < 0);

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_BOOL(result);
}

Datum text_name ( PG_FUNCTION_ARGS   ) 

Definition at line 2259 of file varlena.c.

References NAMEDATALEN, NameStr, palloc0(), PG_GETARG_TEXT_PP, pg_mbcliplen(), PG_RETURN_NAME, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    text       *s = PG_GETARG_TEXT_PP(0);
    Name        result;
    int         len;

    len = VARSIZE_ANY_EXHDR(s);

    /* Truncate oversize input */
    if (len >= NAMEDATALEN)
        len = pg_mbcliplen(VARDATA_ANY(s), len, NAMEDATALEN - 1);

    /* We use palloc0 here to ensure result is zero-padded */
    result = (Name) palloc0(NAMEDATALEN);
    memcpy(NameStr(*result), VARDATA_ANY(s), len);

    PG_RETURN_NAME(result);
}

Datum text_pattern_ge ( PG_FUNCTION_ARGS   ) 

Definition at line 1774 of file varlena.c.

References internal_text_pattern_compare(), PG_FREE_IF_COPY, PG_GETARG_TEXT_PP, and PG_RETURN_BOOL.

{
    text       *arg1 = PG_GETARG_TEXT_PP(0);
    text       *arg2 = PG_GETARG_TEXT_PP(1);
    int         result;

    result = internal_text_pattern_compare(arg1, arg2);

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_BOOL(result >= 0);
}

Datum text_pattern_gt ( PG_FUNCTION_ARGS   ) 

Definition at line 1790 of file varlena.c.

References internal_text_pattern_compare(), PG_FREE_IF_COPY, PG_GETARG_TEXT_PP, and PG_RETURN_BOOL.

{
    text       *arg1 = PG_GETARG_TEXT_PP(0);
    text       *arg2 = PG_GETARG_TEXT_PP(1);
    int         result;

    result = internal_text_pattern_compare(arg1, arg2);

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_BOOL(result > 0);
}

Datum text_pattern_le ( PG_FUNCTION_ARGS   ) 

Definition at line 1758 of file varlena.c.

References internal_text_pattern_compare(), PG_FREE_IF_COPY, PG_GETARG_TEXT_PP, and PG_RETURN_BOOL.

{
    text       *arg1 = PG_GETARG_TEXT_PP(0);
    text       *arg2 = PG_GETARG_TEXT_PP(1);
    int         result;

    result = internal_text_pattern_compare(arg1, arg2);

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_BOOL(result <= 0);
}

Datum text_pattern_lt ( PG_FUNCTION_ARGS   ) 

Definition at line 1742 of file varlena.c.

References internal_text_pattern_compare(), PG_FREE_IF_COPY, PG_GETARG_TEXT_PP, and PG_RETURN_BOOL.

{
    text       *arg1 = PG_GETARG_TEXT_PP(0);
    text       *arg2 = PG_GETARG_TEXT_PP(1);
    int         result;

    result = internal_text_pattern_compare(arg1, arg2);

    PG_FREE_IF_COPY(arg1, 0);
    PG_FREE_IF_COPY(arg2, 1);

    PG_RETURN_BOOL(result < 0);
}

Datum text_regclass ( PG_FUNCTION_ARGS   ) 

Definition at line 1333 of file regproc.c.

References makeRangeVarFromNameList(), NoLock, PG_GETARG_TEXT_P, PG_RETURN_OID, RangeVarGetRelid, and textToQualifiedNameList().

{
    text       *relname = PG_GETARG_TEXT_P(0);
    Oid         result;
    RangeVar   *rv;

    rv = makeRangeVarFromNameList(textToQualifiedNameList(relname));

    /* We might not even have permissions on this relation; don't lock it. */
    result = RangeVarGetRelid(rv, NoLock, false);

    PG_RETURN_OID(result);
}

Datum text_reverse ( PG_FUNCTION_ARGS   ) 

Definition at line 3972 of file varlena.c.

References palloc(), pg_database_encoding_max_length(), PG_GETARG_TEXT_PP, pg_mblen(), PG_RETURN_TEXT_P, SET_VARSIZE, VARDATA, VARDATA_ANY, VARHDRSZ, and VARSIZE_ANY_EXHDR.

{
    text       *str = PG_GETARG_TEXT_PP(0);
    const char *p = VARDATA_ANY(str);
    int         len = VARSIZE_ANY_EXHDR(str);
    const char *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(p);
            dst -= sz;
            memcpy(dst, p, sz);
            p += sz;
        }
    }
    else
    {
        /* single byte version */
        while (p < endp)
            *(--dst) = *p++;
    }

    PG_RETURN_TEXT_P(result);
}

Datum text_right ( PG_FUNCTION_ARGS   ) 

Definition at line 3951 of file varlena.c.

References cstring_to_text_with_len(), PG_GETARG_INT32, PG_GETARG_TEXT_PP, pg_mbcharcliplen(), pg_mbstrlen_with_len(), PG_RETURN_TEXT_P, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    text       *str = PG_GETARG_TEXT_PP(0);
    const char *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));
}

Datum text_smaller ( PG_FUNCTION_ARGS   ) 

Definition at line 1700 of file varlena.c.

References PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, and text_cmp().

{
    text       *arg1 = PG_GETARG_TEXT_PP(0);
    text       *arg2 = PG_GETARG_TEXT_PP(1);
    text       *result;

    result = ((text_cmp(arg1, arg2, PG_GET_COLLATION()) < 0) ? arg1 : arg2);

    PG_RETURN_TEXT_P(result);
}

Datum text_substr ( PG_FUNCTION_ARGS   ) 
Datum text_substr_no_len ( PG_FUNCTION_ARGS   ) 
Datum text_to_array ( PG_FUNCTION_ARGS   ) 

Definition at line 3228 of file varlena.c.

References text_to_array_internal().

{
    return text_to_array_internal(fcinfo);
}

Datum text_to_array_null ( PG_FUNCTION_ARGS   ) 

Definition at line 3242 of file varlena.c.

References text_to_array_internal().

{
    return text_to_array_internal(fcinfo);
}

char* text_to_cstring ( const text t  ) 

Definition at line 141 of file varlena.c.

References palloc(), pfree(), pg_detoast_datum_packed(), VARDATA_ANY, and VARSIZE_ANY_EXHDR.

Referenced by array_to_text(), array_to_text_null(), connectby_text(), connectby_text_serial(), convert_and_check_filename(), convert_any_priv_string(), convert_column_name(), convert_database_name(), convert_foreign_data_wrapper_name(), convert_function_name(), convert_language_name(), convert_priv_string(), convert_schema_name(), convert_server_name(), convert_tablespace_name(), convert_type_name(), create_empty_extension(), crosstab(), crosstab_hash(), cursor_to_xml(), cursor_to_xmlschema(), database_to_xml(), database_to_xml_and_xmlschema(), database_to_xmlschema(), datetime_to_char_body(), datum_to_json(), dblink_close(), dblink_connect(), dblink_disconnect(), dblink_exec(), dblink_fetch(), dblink_open(), dblink_record_internal(), dblink_send_query(), deserialize_deflist(), difference(), dmetaphone(), dmetaphone_alt(), do_to_timestamp(), ExecAlterExtensionStmt(), execute_extension_script(), get_raw_page_fork(), has_sequence_privilege_id_name(), has_sequence_privilege_name(), has_sequence_privilege_name_name(), json_object_field(), json_object_field_text(), ltree_addtext(), ltree_textadd(), NUM_cache(), pg_create_restore_point(), pg_crypt(), pg_get_expr_worker(), pg_get_serial_sequence(), pg_notify(), pg_relation_size(), pg_start_backup(), pg_stat_reset_shared(), pg_xlog_location_diff(), pg_xlogfile_name(), pg_xlogfile_name_offset(), pgxml_texttoxmlchar(), plainto_tsquery_byid(), query_to_xml(), query_to_xml_and_xmlschema(), query_to_xmlschema(), quote_ident(), quote_ident_cstr(), range_constructor3(), schema_to_xml(), schema_to_xml_and_xmlschema(), schema_to_xmlschema(), sepgsql_mcstrans_in(), sepgsql_mcstrans_out(), soundex(), table_to_xml(), table_to_xml_and_xmlschema(), table_to_xmlschema(), text2ltree(), text_concat_ws(), textToQualifiedNameList(), to_date(), to_tsquery_byid(), ts_stat_sql(), tsa_set_curcfg_byname(), tsa_set_curdict_byname(), tsa_set_curprs_byname(), tsquery_rewrite_query(), uuid_generate_v35_internal(), X509_NAME_field_to_text(), xml_out_internal(), xmlconcat(), xmlpi(), xmlroot(), and xpath_table().

{
    /* must cast away the const, unfortunately */
    text       *tunpacked = pg_detoast_datum_packed((struct varlena *) t);
    int         len = VARSIZE_ANY_EXHDR(tunpacked);
    char       *result;

    result = (char *) palloc(len + 1);
    memcpy(result, VARDATA_ANY(tunpacked), len);
    result[len] = '\0';

    if (tunpacked != t)
        pfree(tunpacked);

    return result;
}

void text_to_cstring_buffer ( const text src,
char *  dst,
size_t  dst_len 
)

Definition at line 172 of file varlena.c.

References pfree(), pg_detoast_datum_packed(), pg_mbcliplen(), VARDATA_ANY, and VARSIZE_ANY_EXHDR.

Referenced by chkpass_eq(), chkpass_ne(), lo_export(), lo_import_internal(), pg_gen_salt(), pg_gen_salt_rounds(), timestamp_zone(), timestamptz_zone(), and timetz_zone().

{
    /* must cast away the const, unfortunately */
    text       *srcunpacked = pg_detoast_datum_packed((struct varlena *) src);
    size_t      src_len = VARSIZE_ANY_EXHDR(srcunpacked);

    if (dst_len > 0)
    {
        dst_len--;
        if (dst_len >= src_len)
            dst_len = src_len;
        else    /* ensure truncation is encoding-safe */
            dst_len = pg_mbcliplen(VARDATA_ANY(srcunpacked), src_len, dst_len);
        memcpy(dst, VARDATA_ANY(srcunpacked), dst_len);
        dst[dst_len] = '\0';
    }

    if (srcunpacked != src)
        pfree(srcunpacked);
}

Datum textcat ( PG_FUNCTION_ARGS   ) 

Definition at line 638 of file varlena.c.

References PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, and text_catenate().

Datum texteq ( PG_FUNCTION_ARGS   ) 

Definition at line 1548 of file varlena.c.

References DatumGetTextPP, memcmp(), PG_FREE_IF_COPY, PG_GETARG_DATUM, PG_RETURN_BOOL, toast_raw_datum_size(), VARDATA_ANY, and VARHDRSZ.

Referenced by gbt_texteq(), and text_isequal().

{
    Datum       arg1 = PG_GETARG_DATUM(0);
    Datum       arg2 = PG_GETARG_DATUM(1);
    bool        result;
    Size        len1,
                len2;

    /*
     * Since we only care about equality or not-equality, we can avoid all the
     * expense of strcoll() here, and just do bitwise comparison.  In fact, we
     * don't even have to do a bitwise comparison if we can show the lengths
     * of the strings are unequal; which might save us from having to detoast
     * one or both values.
     */
    len1 = toast_raw_datum_size(arg1);
    len2 = toast_raw_datum_size(arg2);
    if (len1 != len2)
        result = false;
    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);
    }

    PG_RETURN_BOOL(result);
}

Datum texticlike ( PG_FUNCTION_ARGS   ) 

Definition at line 390 of file like.c.

References Generic_Text_IC_like(), PG_GET_COLLATION, PG_GETARG_TEXT_PP, and PG_RETURN_BOOL.

{
    text       *str = PG_GETARG_TEXT_PP(0);
    text       *pat = PG_GETARG_TEXT_PP(1);
    bool        result;

    result = (Generic_Text_IC_like(str, pat, PG_GET_COLLATION()) == LIKE_TRUE);

    PG_RETURN_BOOL(result);
}

Datum texticnlike ( PG_FUNCTION_ARGS   ) 

Definition at line 402 of file like.c.

References Generic_Text_IC_like(), PG_GET_COLLATION, PG_GETARG_TEXT_PP, and PG_RETURN_BOOL.

{
    text       *str = PG_GETARG_TEXT_PP(0);
    text       *pat = PG_GETARG_TEXT_PP(1);
    bool        result;

    result = (Generic_Text_IC_like(str, pat, PG_GET_COLLATION()) != LIKE_TRUE);

    PG_RETURN_BOOL(result);
}

Datum texticregexeq ( PG_FUNCTION_ARGS   ) 
Datum texticregexne ( PG_FUNCTION_ARGS   ) 
Datum textin ( PG_FUNCTION_ARGS   ) 

Definition at line 467 of file varlena.c.

References cstring_to_text(), PG_GETARG_CSTRING, and PG_RETURN_TEXT_P.

{
    char       *inputText = PG_GETARG_CSTRING(0);

    PG_RETURN_TEXT_P(cstring_to_text(inputText));
}

Datum textlen ( PG_FUNCTION_ARGS   ) 

Definition at line 581 of file varlena.c.

References PG_GETARG_DATUM, PG_RETURN_INT32, and text_length().

{
    Datum       str = PG_GETARG_DATUM(0);

    /* try to avoid decompressing argument */
    PG_RETURN_INT32(text_length(str));
}

Datum textlike ( PG_FUNCTION_ARGS   ) 

Definition at line 272 of file like.c.

References GenericMatchText(), PG_GETARG_TEXT_PP, PG_RETURN_BOOL, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    text       *str = PG_GETARG_TEXT_PP(0);
    text       *pat = PG_GETARG_TEXT_PP(1);
    bool        result;
    char       *s,
               *p;
    int         slen,
                plen;

    s = VARDATA_ANY(str);
    slen = VARSIZE_ANY_EXHDR(str);
    p = VARDATA_ANY(pat);
    plen = VARSIZE_ANY_EXHDR(pat);

    result = (GenericMatchText(s, slen, p, plen) == LIKE_TRUE);

    PG_RETURN_BOOL(result);
}

Datum textne ( PG_FUNCTION_ARGS   ) 

Definition at line 1583 of file varlena.c.

References DatumGetTextPP, memcmp(), PG_FREE_IF_COPY, PG_GETARG_DATUM, PG_RETURN_BOOL, toast_raw_datum_size(), VARDATA_ANY, and VARHDRSZ.

{
    Datum       arg1 = PG_GETARG_DATUM(0);
    Datum       arg2 = PG_GETARG_DATUM(1);
    bool        result;
    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);
    }

    PG_RETURN_BOOL(result);
}

Datum textnlike ( PG_FUNCTION_ARGS   ) 

Definition at line 293 of file like.c.

References GenericMatchText(), PG_GETARG_TEXT_PP, PG_RETURN_BOOL, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    text       *str = PG_GETARG_TEXT_PP(0);
    text       *pat = PG_GETARG_TEXT_PP(1);
    bool        result;
    char       *s,
               *p;
    int         slen,
                plen;

    s = VARDATA_ANY(str);
    slen = VARSIZE_ANY_EXHDR(str);
    p = VARDATA_ANY(pat);
    plen = VARSIZE_ANY_EXHDR(pat);

    result = (GenericMatchText(s, slen, p, plen) != LIKE_TRUE);

    PG_RETURN_BOOL(result);
}

Datum textoctetlen ( PG_FUNCTION_ARGS   ) 

Definition at line 619 of file varlena.c.

References PG_GETARG_DATUM, PG_RETURN_INT32, toast_raw_datum_size(), and VARHDRSZ.

{
    Datum       str = PG_GETARG_DATUM(0);

    /* We need not detoast the input at all */
    PG_RETURN_INT32(toast_raw_datum_size(str) - VARHDRSZ);
}

Datum textout ( PG_FUNCTION_ARGS   ) 

Definition at line 478 of file varlena.c.

References PG_GETARG_DATUM, PG_RETURN_CSTRING, and TextDatumGetCString.

Referenced by pg_node_tree_out().

Datum textoverlay ( PG_FUNCTION_ARGS   ) 

Definition at line 970 of file varlena.c.

References PG_GETARG_INT32, PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, and text_overlay().

{
    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   ) 

Definition at line 981 of file varlena.c.

References PG_GETARG_INT32, PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, PointerGetDatum, text_length(), and text_overlay().

{
    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;

    sl = text_length(PointerGetDatum(t2));      /* defaults to length(t2) */
    PG_RETURN_TEXT_P(text_overlay(t1, t2, sp, sl));
}

Datum textpos ( PG_FUNCTION_ARGS   ) 

Definition at line 1031 of file varlena.c.

References PG_GETARG_TEXT_PP, PG_RETURN_INT32, and text_position().

{
    text       *str = PG_GETARG_TEXT_PP(0);
    text       *search_str = PG_GETARG_TEXT_PP(1);

    PG_RETURN_INT32((int32) text_position(str, search_str));
}

Datum textrecv ( PG_FUNCTION_ARGS   ) 

Definition at line 489 of file varlena.c.

References buf, cstring_to_text_with_len(), StringInfoData::cursor, StringInfoData::len, pfree(), PG_GETARG_POINTER, PG_RETURN_TEXT_P, and pq_getmsgtext().

{
    StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
    text       *result;
    char       *str;
    int         nbytes;

    str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);

    result = cstring_to_text_with_len(str, nbytes);
    pfree(str);
    PG_RETURN_TEXT_P(result);
}

Datum textregexeq ( PG_FUNCTION_ARGS   ) 
Datum textregexne ( PG_FUNCTION_ARGS   ) 
Datum textregexreplace ( PG_FUNCTION_ARGS   ) 
Datum textregexreplace_noopt ( PG_FUNCTION_ARGS   ) 
Datum textregexsubstr ( PG_FUNCTION_ARGS   ) 

Definition at line 549 of file regexp.c.

References DirectFunctionCall3, Int32GetDatum, PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_NULL, PointerGetDatum, RE_compile_and_cache(), RE_execute(), regex_t::re_nsub, REG_ADVANCED, regmatch_t::rm_eo, regmatch_t::rm_so, text_substr(), VARDATA_ANY, and VARSIZE_ANY_EXHDR.

{
    text       *s = PG_GETARG_TEXT_PP(0);
    text       *p = PG_GETARG_TEXT_PP(1);
    regex_t    *re;
    regmatch_t  pmatch[2];
    int         so,
                eo;

    /* Compile RE */
    re = RE_compile_and_cache(p, REG_ADVANCED, PG_GET_COLLATION());

    /*
     * We pass two regmatch_t structs to get info about the overall match and
     * the match for the first parenthesized subexpression (if any). If there
     * is a parenthesized subexpression, we return what it matched; else
     * return what the whole regexp matched.
     */
    if (!RE_execute(re,
                    VARDATA_ANY(s), VARSIZE_ANY_EXHDR(s),
                    2, pmatch))
        PG_RETURN_NULL();       /* definitely no match */

    if (re->re_nsub > 0)
    {
        /* has parenthesized subexpressions, use the first one */
        so = pmatch[1].rm_so;
        eo = pmatch[1].rm_eo;
    }
    else
    {
        /* no parenthesized subexpression, use whole match */
        so = pmatch[0].rm_so;
        eo = pmatch[0].rm_eo;
    }

    /*
     * It is possible to have a match to the whole pattern but no match for a
     * subexpression; for example 'foo(bar)?' is considered to match 'foo' but
     * there is no subexpression match.  So this extra test for match failure
     * is not redundant.
     */
    if (so < 0 || eo < 0)
        PG_RETURN_NULL();

    return DirectFunctionCall3(text_substr,
                               PointerGetDatum(s),
                               Int32GetDatum(so + 1),
                               Int32GetDatum(eo - so));
}

Datum textsend ( PG_FUNCTION_ARGS   ) 
List* textToQualifiedNameList ( text textval  ) 

Definition at line 2299 of file varlena.c.

References ereport, errcode(), errmsg(), ERROR, lappend(), lfirst, list_free(), makeString(), NIL, pfree(), pstrdup(), SplitIdentifierString(), and text_to_cstring().

Referenced by bt_metap(), bt_page_items(), bt_page_stats(), convert_table_name(), currtid_byrelname(), get_raw_page_internal(), get_rel_from_relname(), nextval(), pg_get_serial_sequence(), pg_get_viewdef_name(), pg_get_viewdef_name_ext(), pg_relpages(), pgrowlocks(), pgstatindex(), pgstattuple(), text_regclass(), ts_parse_byname(), and ts_token_type_byname().

{
    char       *rawname;
    List       *result = NIL;
    List       *namelist;
    ListCell   *l;

    /* Convert to C string (handles possible detoasting). */
    /* Note we rely on being able to modify rawname below. */
    rawname = text_to_cstring(textval);

    if (!SplitIdentifierString(rawname, '.', &namelist))
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_NAME),
                 errmsg("invalid name syntax")));

    if (namelist == NIL)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_NAME),
                 errmsg("invalid name syntax")));

    foreach(l, namelist)
    {
        char       *curname = (char *) lfirst(l);

        result = lappend(result, makeString(pstrdup(curname)));
    }

    pfree(rawname);
    list_free(namelist);

    return result;
}

Datum tideq ( PG_FUNCTION_ARGS   ) 
Datum tidge ( PG_FUNCTION_ARGS   ) 
Datum tidgt ( PG_FUNCTION_ARGS   ) 
Datum tidin ( PG_FUNCTION_ARGS   ) 

Definition at line 51 of file tid.c.

References DELIM, ereport, errcode(), errmsg(), ERROR, i, ItemPointerSet, LDELIM, NTIDARGS, palloc(), PG_GETARG_CSTRING, PG_RETURN_ITEMPOINTER, and RDELIM.

Referenced by make_tuple_from_result_row().

{
    char       *str = PG_GETARG_CSTRING(0);
    char       *p,
               *coord[NTIDARGS];
    int         i;
    ItemPointer result;
    BlockNumber blockNumber;
    OffsetNumber offsetNumber;
    char       *badp;
    int         hold_offset;

    for (i = 0, p = str; *p && i < NTIDARGS && *p != RDELIM; p++)
        if (*p == DELIM || (*p == LDELIM && !i))
            coord[i++] = p + 1;

    if (i < NTIDARGS)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                 errmsg("invalid input syntax for type tid: \"%s\"",
                        str)));

    errno = 0;
    blockNumber = strtoul(coord[0], &badp, 10);
    if (errno || *badp != DELIM)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                 errmsg("invalid input syntax for type tid: \"%s\"",
                        str)));

    hold_offset = strtol(coord[1], &badp, 10);
    if (errno || *badp != RDELIM ||
        hold_offset > USHRT_MAX || hold_offset < 0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                 errmsg("invalid input syntax for type tid: \"%s\"",
                        str)));

    offsetNumber = hold_offset;

    result = (ItemPointer) palloc(sizeof(ItemPointerData));

    ItemPointerSet(result, blockNumber, offsetNumber);

    PG_RETURN_ITEMPOINTER(result);
}

Datum tidlarger ( PG_FUNCTION_ARGS   ) 

Definition at line 230 of file tid.c.

References ItemPointerCompare(), PG_GETARG_ITEMPOINTER, and PG_RETURN_ITEMPOINTER.

Datum tidle ( PG_FUNCTION_ARGS   ) 
Datum tidlt ( PG_FUNCTION_ARGS   ) 
Datum tidne ( PG_FUNCTION_ARGS   ) 
Datum tidout ( PG_FUNCTION_ARGS   ) 

Definition at line 103 of file tid.c.

References BlockIdGetBlockNumber, buf, ItemPointerData::ip_blkid, ItemPointerData::ip_posid, PG_GETARG_ITEMPOINTER, PG_RETURN_CSTRING, pstrdup(), and snprintf().

Referenced by pgrowlocks().

{
    ItemPointer itemPtr = PG_GETARG_ITEMPOINTER(0);
    BlockNumber blockNumber;
    OffsetNumber offsetNumber;
    char        buf[32];

    blockNumber = BlockIdGetBlockNumber(&(itemPtr->ip_blkid));
    offsetNumber = itemPtr->ip_posid;

    /* Perhaps someday we should output this as a record. */
    snprintf(buf, sizeof(buf), "(%u,%u)", blockNumber, offsetNumber);

    PG_RETURN_CSTRING(pstrdup(buf));
}

Datum tidrecv ( PG_FUNCTION_ARGS   ) 

Definition at line 123 of file tid.c.

References buf, ItemPointerSet, palloc(), PG_GETARG_POINTER, PG_RETURN_ITEMPOINTER, and pq_getmsgint().

{
    StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
    ItemPointer result;
    BlockNumber blockNumber;
    OffsetNumber offsetNumber;

    blockNumber = pq_getmsgint(buf, sizeof(blockNumber));
    offsetNumber = pq_getmsgint(buf, sizeof(offsetNumber));

    result = (ItemPointer) palloc(sizeof(ItemPointerData));

    ItemPointerSet(result, blockNumber, offsetNumber);

    PG_RETURN_ITEMPOINTER(result);
}

Datum tidsend ( PG_FUNCTION_ARGS   ) 

Definition at line 144 of file tid.c.

References BlockIdGetBlockNumber, buf, ItemPointerData::ip_blkid, ItemPointerData::ip_posid, PG_GETARG_ITEMPOINTER, PG_RETURN_BYTEA_P, pq_begintypsend(), pq_endtypsend(), and pq_sendint().

{
    ItemPointer itemPtr = PG_GETARG_ITEMPOINTER(0);
    BlockId     blockId;
    BlockNumber blockNumber;
    OffsetNumber offsetNumber;
    StringInfoData buf;

    blockId = &(itemPtr->ip_blkid);
    blockNumber = BlockIdGetBlockNumber(blockId);
    offsetNumber = itemPtr->ip_posid;

    pq_begintypsend(&buf);
    pq_sendint(&buf, blockNumber, sizeof(blockNumber));
    pq_sendint(&buf, offsetNumber, sizeof(offsetNumber));
    PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
}

Datum tidsmaller ( PG_FUNCTION_ARGS   ) 

Definition at line 239 of file tid.c.

References ItemPointerCompare(), PG_GETARG_ITEMPOINTER, and PG_RETURN_ITEMPOINTER.

Datum to_hex32 ( PG_FUNCTION_ARGS   ) 

Definition at line 3585 of file varlena.c.

References buf, cstring_to_text(), digits, PG_GETARG_INT32, PG_RETURN_TEXT_P, and value.

{
    uint32      value = (uint32) PG_GETARG_INT32(0);
    char       *ptr;
    const char *digits = "0123456789abcdef";
    char        buf[32];        /* bigger than needed, but reasonable */

    ptr = buf + sizeof(buf) - 1;
    *ptr = '\0';

    do
    {
        *--ptr = digits[value % HEXBASE];
        value /= HEXBASE;
    } while (ptr > buf && value);

    PG_RETURN_TEXT_P(cstring_to_text(ptr));
}

Datum to_hex64 ( PG_FUNCTION_ARGS   ) 

Definition at line 3609 of file varlena.c.

References buf, cstring_to_text(), digits, PG_GETARG_INT64, PG_RETURN_TEXT_P, and value.

{
    uint64      value = (uint64) PG_GETARG_INT64(0);
    char       *ptr;
    const char *digits = "0123456789abcdef";
    char        buf[32];        /* bigger than needed, but reasonable */

    ptr = buf + sizeof(buf) - 1;
    *ptr = '\0';

    do
    {
        *--ptr = digits[value % HEXBASE];
        value /= HEXBASE;
    } while (ptr > buf && value);

    PG_RETURN_TEXT_P(cstring_to_text(ptr));
}

Datum translate ( PG_FUNCTION_ARGS   ) 

Definition at line 718 of file oracle_compat.c.

References ereport, errcode(), errmsg(), ERROR, i, memcmp(), palloc(), pg_database_encoding_max_length(), PG_GETARG_TEXT_PP, pg_mblen(), PG_RETURN_TEXT_P, SET_VARSIZE, VARDATA, VARDATA_ANY, VARHDRSZ, and VARSIZE_ANY_EXHDR.

{
    text       *string = PG_GETARG_TEXT_PP(0);
    text       *from = PG_GETARG_TEXT_PP(1);
    text       *to = PG_GETARG_TEXT_PP(2);
    text       *result;
    char       *from_ptr,
               *to_ptr;
    char       *source,
               *target;
    int         m,
                fromlen,
                tolen,
                retlen,
                i;
    int         worst_len;
    int         len;
    int         source_len;
    int         from_index;

    m = VARSIZE_ANY_EXHDR(string);
    if (m <= 0)
        PG_RETURN_TEXT_P(string);
    source = VARDATA_ANY(string);

    fromlen = VARSIZE_ANY_EXHDR(from);
    from_ptr = VARDATA_ANY(from);
    tolen = VARSIZE_ANY_EXHDR(to);
    to_ptr = VARDATA_ANY(to);

    /*
     * The worst-case expansion is to substitute a max-length character for a
     * single-byte character at each position of the string.
     */
    worst_len = pg_database_encoding_max_length() * m;

    /* check for integer overflow */
    if (worst_len / pg_database_encoding_max_length() != m)
        ereport(ERROR,
                (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                 errmsg("requested length too large")));

    result = (text *) palloc(worst_len + VARHDRSZ);
    target = VARDATA(result);
    retlen = 0;

    while (m > 0)
    {
        source_len = pg_mblen(source);
        from_index = 0;

        for (i = 0; i < fromlen; i += len)
        {
            len = pg_mblen(&from_ptr[i]);
            if (len == source_len &&
                memcmp(source, &from_ptr[i], len) == 0)
                break;

            from_index++;
        }
        if (i < fromlen)
        {
            /* substitute */
            char       *p = to_ptr;

            for (i = 0; i < from_index; i++)
            {
                p += pg_mblen(p);
                if (p >= (to_ptr + tolen))
                    break;
            }
            if (p < (to_ptr + tolen))
            {
                len = pg_mblen(p);
                memcpy(target, p, len);
                target += len;
                retlen += len;
            }

        }
        else
        {
            /* no match, so copy */
            memcpy(target, source, source_len);
            target += source_len;
            retlen += source_len;
        }

        source += source_len;
        m -= source_len;
    }

    SET_VARSIZE(result, retlen + VARHDRSZ);

    /*
     * The function result is probably much bigger than needed, if we're using
     * a multibyte encoding, but it's not worth reallocating it; the result
     * probably won't live long anyway.
     */

    PG_RETURN_TEXT_P(result);
}

Datum trigger_in ( PG_FUNCTION_ARGS   ) 

Definition at line 272 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot accept a value of type trigger")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum trigger_out ( PG_FUNCTION_ARGS   ) 

Definition at line 285 of file pseudotypes.c.

References ereport, errcode(), errmsg(), ERROR, and PG_RETURN_VOID.

{
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("cannot display a value of type trigger")));

    PG_RETURN_VOID();           /* keep compiler quiet */
}

Datum txid_current ( PG_FUNCTION_ARGS   ) 

Definition at line 328 of file txid.c.

References convert_xid(), GetTopTransactionId(), load_xid_epoch(), PG_RETURN_INT64, PreventCommandDuringRecovery(), and val.

{
    txid        val;
    TxidEpoch   state;

    /*
     * Must prevent during recovery because if an xid is not assigned we try
     * to assign one, which would fail. Programs already rely on this function
     * to always return a valid current xid, so we should not change this to
     * return NULL or similar invalid xid.
     */
    PreventCommandDuringRecovery("txid_current()");

    load_xid_epoch(&state);

    val = convert_xid(GetTopTransactionId(), &state);

    PG_RETURN_INT64(val);
}

Datum txid_current_snapshot ( PG_FUNCTION_ARGS   ) 

Definition at line 356 of file txid.c.

References convert_xid(), cur, elog, ERROR, GetActiveSnapshot(), i, load_xid_epoch(), NULL, TxidSnapshot::nxip, palloc(), PG_RETURN_POINTER, SET_VARSIZE, sort_snapshot(), TXID_SNAPSHOT_SIZE, SnapshotData::xcnt, SnapshotData::xip, TxidSnapshot::xip, SnapshotData::xmax, TxidSnapshot::xmax, SnapshotData::xmin, and TxidSnapshot::xmin.

{
    TxidSnapshot *snap;
    uint32      nxip,
                i,
                size;
    TxidEpoch   state;
    Snapshot    cur;

    cur = GetActiveSnapshot();
    if (cur == NULL)
        elog(ERROR, "no active snapshot set");

    load_xid_epoch(&state);

    /* allocate */
    nxip = cur->xcnt;
    size = TXID_SNAPSHOT_SIZE(nxip);
    snap = palloc(size);
    SET_VARSIZE(snap, size);

    /* fill */
    snap->xmin = convert_xid(cur->xmin, &state);
    snap->xmax = convert_xid(cur->xmax, &state);
    snap->nxip = nxip;
    for (i = 0; i < nxip; i++)
        snap->xip[i] = convert_xid(cur->xip[i], &state);

    /* we want them guaranteed to be in ascending order */
    sort_snapshot(snap);

    PG_RETURN_POINTER(snap);
}

Datum txid_snapshot_in ( PG_FUNCTION_ARGS   ) 

Definition at line 396 of file txid.c.

References parse_snapshot(), PG_GETARG_CSTRING, and PG_RETURN_POINTER.

{
    char       *str = PG_GETARG_CSTRING(0);
    TxidSnapshot *snap;

    snap = parse_snapshot(str);

    PG_RETURN_POINTER(snap);
}

Datum txid_snapshot_out ( PG_FUNCTION_ARGS   ) 
Datum txid_snapshot_recv ( PG_FUNCTION_ARGS   ) 

Definition at line 441 of file txid.c.

References buf, cur, StringInfoData::cursor, elog, ERROR, i, StringInfoData::len, MAX_TXID, TxidSnapshot::nxip, palloc(), PG_GETARG_POINTER, PG_RETURN_POINTER, pq_getmsgint(), pq_getmsgint64(), SET_VARSIZE, TXID_SNAPSHOT_SIZE, TxidSnapshot::xip, TxidSnapshot::xmax, and TxidSnapshot::xmin.

{
    StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
    TxidSnapshot *snap;
    txid        last = 0;
    int         nxip;
    int         i;
    int         avail;
    int         expect;
    txid        xmin,
                xmax;

    /*
     * load nxip and check for nonsense.
     *
     * (nxip > avail) check is against int overflows in 'expect'.
     */
    nxip = pq_getmsgint(buf, 4);
    avail = buf->len - buf->cursor;
    expect = 8 + 8 + nxip * 8;
    if (nxip < 0 || nxip > avail || expect > avail)
        goto bad_format;

    xmin = pq_getmsgint64(buf);
    xmax = pq_getmsgint64(buf);
    if (xmin == 0 || xmax == 0 || xmin > xmax || xmax > MAX_TXID)
        goto bad_format;

    snap = palloc(TXID_SNAPSHOT_SIZE(nxip));
    snap->xmin = xmin;
    snap->xmax = xmax;
    snap->nxip = nxip;
    SET_VARSIZE(snap, TXID_SNAPSHOT_SIZE(nxip));

    for (i = 0; i < nxip; i++)
    {
        txid        cur = pq_getmsgint64(buf);

        if (cur <= last || cur < xmin || cur >= xmax)
            goto bad_format;
        snap->xip[i] = cur;
        last = cur;
    }
    PG_RETURN_POINTER(snap);

bad_format:
    elog(ERROR, "invalid snapshot data");
    return (Datum) NULL;
}

Datum txid_snapshot_send ( PG_FUNCTION_ARGS   ) 
Datum txid_snapshot_xip ( PG_FUNCTION_ARGS   ) 

Definition at line 560 of file txid.c.

References arg, FuncCallContext::call_cntr, Int64GetDatum(), MemoryContextAlloc(), FuncCallContext::multi_call_memory_ctx, TxidSnapshot::nxip, PG_GETARG_VARLENA_P, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, FuncCallContext::user_fctx, value, VARSIZE, and TxidSnapshot::xip.

{
    FuncCallContext *fctx;
    TxidSnapshot *snap;
    txid        value;

    /* on first call initialize snap_state and get copy of snapshot */
    if (SRF_IS_FIRSTCALL())
    {
        TxidSnapshot *arg = (TxidSnapshot *) PG_GETARG_VARLENA_P(0);

        fctx = SRF_FIRSTCALL_INIT();

        /* make a copy of user snapshot */
        snap = MemoryContextAlloc(fctx->multi_call_memory_ctx, VARSIZE(arg));
        memcpy(snap, arg, VARSIZE(arg));

        fctx->user_fctx = snap;
    }

    /* return values one-by-one */
    fctx = SRF_PERCALL_SETUP();
    snap = fctx->user_fctx;
    if (fctx->call_cntr < snap->nxip)
    {
        value = snap->xip[fctx->call_cntr];
        SRF_RETURN_NEXT(fctx, Int64GetDatum(value));
    }
    else
    {
        SRF_RETURN_DONE(fctx);
    }
}

Datum txid_snapshot_xmax ( PG_FUNCTION_ARGS   ) 

Definition at line 547 of file txid.c.

References PG_GETARG_VARLENA_P, PG_RETURN_INT64, and TxidSnapshot::xmax.

Datum txid_snapshot_xmin ( PG_FUNCTION_ARGS   ) 

Definition at line 534 of file txid.c.

References PG_GETARG_VARLENA_P, PG_RETURN_INT64, and TxidSnapshot::xmin.

Datum txid_visible_in_snapshot ( PG_FUNCTION_ARGS   ) 
int32 type_maximum_size ( Oid  type_oid,
int32  typemod 
)

Definition at line 378 of file format_type.c.

References BITOID, BITS_PER_BYTE, BPCHAROID, GetDatabaseEncoding(), numeric_maximum_size(), NUMERICOID, pg_encoding_max_length(), VARBITOID, VARCHAROID, and VARHDRSZ.

Referenced by get_typavgwidth(), and needs_toast_table().

{
    if (typemod < 0)
        return -1;

    switch (type_oid)
    {
        case BPCHAROID:
        case VARCHAROID:
            /* typemod includes varlena header */

            /* typemod is in characters not bytes */
            return (typemod - VARHDRSZ) *
                pg_encoding_max_length(GetDatabaseEncoding())
                + VARHDRSZ;

        case NUMERICOID:
            return numeric_maximum_size(typemod);

        case VARBITOID:
        case BITOID:
            /* typemod is the (max) number of bits */
            return (typemod + (BITS_PER_BYTE - 1)) / BITS_PER_BYTE
                + 2 * sizeof(int32);
    }

    /* Unknown type, or unlimited-width type such as 'text' */
    return -1;
}

Datum unique_key_recheck ( PG_FUNCTION_ARGS   ) 

Definition at line 38 of file constraint.c.

References CALLED_AS_TRIGGER, ereport, errcode(), errmsg(), ERROR, INDEX_MAX_KEYS, TriggerData::tg_event, TriggerData::tg_newtuple, TriggerData::tg_trigtuple, TRIGGER_FIRED_AFTER, TRIGGER_FIRED_BY_INSERT, TRIGGER_FIRED_BY_UPDATE, TRIGGER_FIRED_FOR_ROW, and values.

{
    TriggerData *trigdata = (TriggerData *) fcinfo->context;
    const char *funcname = "unique_key_recheck";
    HeapTuple   new_row;
    ItemPointerData tmptid;
    Relation    indexRel;
    IndexInfo  *indexInfo;
    EState     *estate;
    ExprContext *econtext;
    TupleTableSlot *slot;
    Datum       values[INDEX_MAX_KEYS];
    bool        isnull[INDEX_MAX_KEYS];

    /*
     * Make sure this is being called as an AFTER ROW trigger.  Note:
     * translatable error strings are shared with ri_triggers.c, so resist the
     * temptation to fold the function name into them.
     */
    if (!CALLED_AS_TRIGGER(fcinfo))
        ereport(ERROR,
                (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
                 errmsg("function \"%s\" was not called by trigger manager",
                        funcname)));

    if (!TRIGGER_FIRED_AFTER(trigdata->tg_event) ||
        !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
        ereport(ERROR,
                (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
                 errmsg("function \"%s\" must be fired AFTER ROW",
                        funcname)));

    /*
     * Get the new data that was inserted/updated.
     */
    if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
        new_row = trigdata->tg_trigtuple;
    else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
        new_row = trigdata->tg_newtuple;
    else
    {
        ereport(ERROR,
                (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
                 errmsg("function \"%s\" must be fired for INSERT or UPDATE",
                        funcname)));
        new_row = NULL;         /* keep compiler quiet */
    }

    /*
     * If the new_row is now dead (ie, inserted and then deleted within our
     * transaction), we can skip the check.  However, we have to be careful,
     * because this trigger gets queued only in response to index insertions;
     * which means it does not get queued for HOT updates.  The row we are
     * called for might now be dead, but have a live HOT child, in which case
     * we still need to make the check.  Therefore we have to use
     * heap_hot_search, not just HeapTupleSatisfiesVisibility as is done in
     * the comparable test in RI_FKey_check.
     *
     * This might look like just an optimization, because the index AM will
     * make this identical test before throwing an error.  But it's actually
     * needed for correctness, because the index AM will also throw an error
     * if it doesn't find the index entry for the row.  If the row's dead then
     * it's possible the index entry has also been marked dead, and even
     * removed.
     */
    tmptid = new_row->t_self;
    if (!heap_hot_search(&tmptid, trigdata->tg_relation, SnapshotSelf, NULL))
    {
        /*
         * All rows in the HOT chain are dead, so skip the check.
         */
        return PointerGetDatum(NULL);
    }

    /*
     * Open the index, acquiring a RowExclusiveLock, just as if we were going
     * to update it.  (This protects against possible changes of the index
     * schema, not against concurrent updates.)
     */
    indexRel = index_open(trigdata->tg_trigger->tgconstrindid,
                          RowExclusiveLock);
    indexInfo = BuildIndexInfo(indexRel);

    /*
     * The heap tuple must be put into a slot for FormIndexDatum.
     */
    slot = MakeSingleTupleTableSlot(RelationGetDescr(trigdata->tg_relation));

    ExecStoreTuple(new_row, slot, InvalidBuffer, false);

    /*
     * Typically the index won't have expressions, but if it does we need an
     * EState to evaluate them.  We need it for exclusion constraints too,
     * even if they are just on simple columns.
     */
    if (indexInfo->ii_Expressions != NIL ||
        indexInfo->ii_ExclusionOps != NULL)
    {
        estate = CreateExecutorState();
        econtext = GetPerTupleExprContext(estate);
        econtext->ecxt_scantuple = slot;
    }
    else
        estate = NULL;

    /*
     * Form the index values and isnull flags for the index entry that we need
     * to check.
     *
     * Note: if the index uses functions that are not as immutable as they are
     * supposed to be, this could produce an index tuple different from the
     * original.  The index AM can catch such errors by verifying that it
     * finds a matching index entry with the tuple's TID.  For exclusion
     * constraints we check this in check_exclusion_constraint().
     */
    FormIndexDatum(indexInfo, slot, estate, values, isnull);

    /*
     * Now do the appropriate check.
     */
    if (indexInfo->ii_ExclusionOps == NULL)
    {
        /*
         * Note: this is not a real insert; it is a check that the index entry
         * that has already been inserted is unique.
         */
        index_insert(indexRel, values, isnull, &(new_row->t_self),
                     trigdata->tg_relation, UNIQUE_CHECK_EXISTING);
    }
    else
    {
        /*
         * For exclusion constraints we just do the normal check, but now it's
         * okay to throw error.
         */
        check_exclusion_constraint(trigdata->tg_relation, indexRel, indexInfo,
                                   &(new_row->t_self), values, isnull,
                                   estate, false, false);
    }

    /*
     * If that worked, then this index entry is unique or non-excluded, and we
     * are done.
     */
    if (estate != NULL)
        FreeExecutorState(estate);

    ExecDropSingleTupleTableSlot(slot);

    index_close(indexRel, RowExclusiveLock);

    return PointerGetDatum(NULL);
}

Datum unknownin ( PG_FUNCTION_ARGS   ) 

Definition at line 522 of file varlena.c.

References PG_GETARG_CSTRING, PG_RETURN_CSTRING, and pstrdup().

{
    char       *str = PG_GETARG_CSTRING(0);

    /* representation is same as cstring */
    PG_RETURN_CSTRING(pstrdup(str));
}

Datum unknownout ( PG_FUNCTION_ARGS   ) 

Definition at line 534 of file varlena.c.

References PG_GETARG_CSTRING, PG_RETURN_CSTRING, and pstrdup().

{
    /* representation is same as cstring */
    char       *str = PG_GETARG_CSTRING(0);

    PG_RETURN_CSTRING(pstrdup(str));
}

Datum unknownrecv ( PG_FUNCTION_ARGS   ) 

Definition at line 546 of file varlena.c.

References buf, StringInfoData::cursor, StringInfoData::len, PG_GETARG_POINTER, PG_RETURN_CSTRING, and pq_getmsgtext().

{
    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);
}

Datum unknownsend ( PG_FUNCTION_ARGS   ) 

Definition at line 561 of file varlena.c.

References buf, PG_GETARG_CSTRING, PG_RETURN_BYTEA_P, pq_begintypsend(), pq_endtypsend(), and pq_sendtext().

{
    /* representation is same as cstring */
    char       *str = PG_GETARG_CSTRING(0);
    StringInfoData buf;

    pq_begintypsend(&buf);
    pq_sendtext(&buf, str, strlen(str));
    PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
}

Datum upper ( PG_FUNCTION_ARGS   ) 
Datum uuid_cmp ( PG_FUNCTION_ARGS   ) 

Definition at line 217 of file uuid.c.

References PG_GETARG_UUID_P, PG_RETURN_INT32, and uuid_internal_cmp().

Datum uuid_eq ( PG_FUNCTION_ARGS   ) 

Definition at line 180 of file uuid.c.

References PG_GETARG_UUID_P, PG_RETURN_BOOL, and uuid_internal_cmp().

Datum uuid_ge ( PG_FUNCTION_ARGS   ) 

Definition at line 189 of file uuid.c.

References PG_GETARG_UUID_P, PG_RETURN_BOOL, and uuid_internal_cmp().

Datum uuid_gt ( PG_FUNCTION_ARGS   ) 

Definition at line 198 of file uuid.c.

References PG_GETARG_UUID_P, PG_RETURN_BOOL, and uuid_internal_cmp().

Datum uuid_hash ( PG_FUNCTION_ARGS   ) 

Definition at line 227 of file uuid.c.

References pg_uuid_t::data, hash_any(), PG_GETARG_UUID_P, and UUID_LEN.

{
    pg_uuid_t  *key = PG_GETARG_UUID_P(0);

    return hash_any(key->data, UUID_LEN);
}

Datum uuid_in ( PG_FUNCTION_ARGS   ) 

Definition at line 34 of file uuid.c.

References palloc(), PG_GETARG_CSTRING, PG_RETURN_UUID_P, and string_to_uuid().

Referenced by special_uuid_value(), and uuid_generate_internal().

{
    char       *uuid_str = PG_GETARG_CSTRING(0);
    pg_uuid_t  *uuid;

    uuid = (pg_uuid_t *) palloc(sizeof(*uuid));
    string_to_uuid(uuid_str, uuid);
    PG_RETURN_UUID_P(uuid);
}

Datum uuid_le ( PG_FUNCTION_ARGS   ) 

Definition at line 171 of file uuid.c.

References PG_GETARG_UUID_P, PG_RETURN_BOOL, and uuid_internal_cmp().

Datum uuid_lt ( PG_FUNCTION_ARGS   ) 

Definition at line 162 of file uuid.c.

References PG_GETARG_UUID_P, PG_RETURN_BOOL, and uuid_internal_cmp().

Datum uuid_ne ( PG_FUNCTION_ARGS   ) 

Definition at line 207 of file uuid.c.

References PG_GETARG_UUID_P, PG_RETURN_BOOL, and uuid_internal_cmp().

Datum uuid_out ( PG_FUNCTION_ARGS   ) 

Definition at line 45 of file uuid.c.

References appendStringInfoChar(), buf, StringInfoData::data, pg_uuid_t::data, i, initStringInfo(), PG_GETARG_UUID_P, and PG_RETURN_CSTRING.

Referenced by uuid_generate_v35_internal().

{
    pg_uuid_t  *uuid = PG_GETARG_UUID_P(0);
    static const char hex_chars[] = "0123456789abcdef";
    StringInfoData buf;
    int         i;

    initStringInfo(&buf);
    for (i = 0; i < UUID_LEN; i++)
    {
        int         hi;
        int         lo;

        /*
         * We print uuid values as a string of 8, 4, 4, 4, and then 12
         * hexadecimal characters, with each group is separated by a hyphen
         * ("-"). Therefore, add the hyphens at the appropriate places here.
         */
        if (i == 4 || i == 6 || i == 8 || i == 10)
            appendStringInfoChar(&buf, '-');

        hi = uuid->data[i] >> 4;
        lo = uuid->data[i] & 0x0F;

        appendStringInfoChar(&buf, hex_chars[hi]);
        appendStringInfoChar(&buf, hex_chars[lo]);
    }

    PG_RETURN_CSTRING(buf.data);
}

Datum uuid_recv ( PG_FUNCTION_ARGS   ) 

Definition at line 133 of file uuid.c.

References pg_uuid_t::data, palloc(), PG_GETARG_POINTER, PG_RETURN_POINTER, pq_getmsgbytes(), and UUID_LEN.

{
    StringInfo  buffer = (StringInfo) PG_GETARG_POINTER(0);
    pg_uuid_t  *uuid;

    uuid = (pg_uuid_t *) palloc(UUID_LEN);
    memcpy(uuid->data, pq_getmsgbytes(buffer, UUID_LEN), UUID_LEN);
    PG_RETURN_POINTER(uuid);
}

Datum uuid_send ( PG_FUNCTION_ARGS   ) 
Datum varchar ( PG_FUNCTION_ARGS   ) 

Definition at line 592 of file varchar.c.

References cstring_to_text_with_len(), ereport, errcode(), errmsg(), ERROR, i, PG_GETARG_BOOL, PG_GETARG_INT32, PG_GETARG_VARCHAR_PP, pg_mbcharcliplen(), PG_RETURN_VARCHAR_P, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

Referenced by main().

{
    VarChar    *source = PG_GETARG_VARCHAR_PP(0);
    int32       typmod = PG_GETARG_INT32(1);
    bool        isExplicit = PG_GETARG_BOOL(2);
    int32       len,
                maxlen;
    size_t      maxmblen;
    int         i;
    char       *s_data;

    len = VARSIZE_ANY_EXHDR(source);
    s_data = VARDATA_ANY(source);
    maxlen = typmod - VARHDRSZ;

    /* No work if typmod is invalid or supplied data fits it already */
    if (maxlen < 0 || len <= maxlen)
        PG_RETURN_VARCHAR_P(source);

    /* only reach here if string is too long... */

    /* truncate multibyte string preserving multibyte boundary */
    maxmblen = pg_mbcharcliplen(s_data, len, maxlen);

    if (!isExplicit)
    {
        for (i = maxmblen; i < len; i++)
            if (s_data[i] != ' ')
                ereport(ERROR,
                        (errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION),
                      errmsg("value too long for type character varying(%d)",
                             maxlen)));
    }

    PG_RETURN_VARCHAR_P((VarChar *) cstring_to_text_with_len(s_data,
                                                             maxmblen));
}

Datum varchar_transform ( PG_FUNCTION_ARGS   ) 

Definition at line 553 of file varchar.c.

References FuncExpr::args, Assert, DatumGetInt32, exprTypmod(), IsA, linitial, list_length(), lsecond, PG_GETARG_POINTER, PG_RETURN_POINTER, and relabel_to_typmod().

{
    FuncExpr   *expr = (FuncExpr *) PG_GETARG_POINTER(0);
    Node       *ret = NULL;
    Node       *typmod;

    Assert(IsA(expr, FuncExpr));
    Assert(list_length(expr->args) >= 2);

    typmod = (Node *) lsecond(expr->args);

    if (IsA(typmod, Const) &&!((Const *) typmod)->constisnull)
    {
        Node       *source = (Node *) linitial(expr->args);
        int32       old_typmod = exprTypmod(source);
        int32       new_typmod = DatumGetInt32(((Const *) typmod)->constvalue);
        int32       old_max = old_typmod - VARHDRSZ;
        int32       new_max = new_typmod - VARHDRSZ;

        if (new_typmod < 0 || (old_typmod >= 0 && old_max <= new_max))
            ret = relabel_to_typmod(source, new_typmod);
    }

    PG_RETURN_POINTER(ret);
}

Datum varcharin ( PG_FUNCTION_ARGS   ) 

Definition at line 484 of file varchar.c.

References PG_GETARG_CSTRING, PG_GETARG_INT32, PG_GETARG_OID, PG_RETURN_VARCHAR_P, and varchar_input().

{
    char       *s = PG_GETARG_CSTRING(0);

#ifdef NOT_USED
    Oid         typelem = PG_GETARG_OID(1);
#endif
    int32       atttypmod = PG_GETARG_INT32(2);
    VarChar    *result;

    result = varchar_input(s, strlen(s), atttypmod);
    PG_RETURN_VARCHAR_P(result);
}

Datum varcharout ( PG_FUNCTION_ARGS   ) 
Datum varcharrecv ( PG_FUNCTION_ARGS   ) 

Definition at line 517 of file varchar.c.

References buf, StringInfoData::cursor, StringInfoData::len, pfree(), PG_GETARG_INT32, PG_GETARG_OID, PG_GETARG_POINTER, PG_RETURN_VARCHAR_P, pq_getmsgtext(), and varchar_input().

{
    StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);

#ifdef NOT_USED
    Oid         typelem = PG_GETARG_OID(1);
#endif
    int32       atttypmod = PG_GETARG_INT32(2);
    VarChar    *result;
    char       *str;
    int         nbytes;

    str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
    result = varchar_input(str, nbytes, atttypmod);
    pfree(str);
    PG_RETURN_VARCHAR_P(result);
}

Datum varcharsend ( PG_FUNCTION_ARGS   ) 

Definition at line 539 of file varchar.c.

References textsend().

{
    /* Exactly the same as textsend, so share code */
    return textsend(fcinfo);
}

Datum varchartypmodin ( PG_FUNCTION_ARGS   ) 

Definition at line 631 of file varchar.c.

References anychar_typmodin(), PG_GETARG_ARRAYTYPE_P, and PG_RETURN_INT32.

Datum varchartypmodout ( PG_FUNCTION_ARGS   ) 

Definition at line 639 of file varchar.c.

References anychar_typmodout(), PG_GETARG_INT32, and PG_RETURN_CSTRING.

int varstr_cmp ( char *  arg1,
int  len1,
char *  arg2,
int  len2,
Oid  collid 
)

Definition at line 1341 of file varlena.c.

References DEFAULT_COLLATION_OID, ereport, errcode(), errhint(), errmsg(), ERROR, GetDatabaseEncoding(), lc_collate_is_c(), memcmp(), Min, OidIsValid, palloc(), pfree(), pg_newlocale_from_collation(), PG_UTF8, STACKBUFLEN, strcoll_l, and wcscoll_l.

Referenced by bpchar_larger(), bpchar_smaller(), bpcharcmp(), bpcharge(), bpchargt(), bpcharle(), bpcharlt(), citextcmp(), make_greater_string(), spg_text_leaf_consistent(), and text_cmp().

{
    int         result;

    /*
     * Unfortunately, there is no strncoll(), so in the non-C locale case we
     * have to do some memory copying.  This turns out to be significantly
     * slower, so we optimize the case where LC_COLLATE is C.  We also try to
     * optimize relatively-short strings by avoiding palloc/pfree overhead.
     */
    if (lc_collate_is_c(collid))
    {
        result = memcmp(arg1, arg2, Min(len1, len2));
        if ((result == 0) && (len1 != len2))
            result = (len1 < len2) ? -1 : 1;
    }
    else
    {
#define STACKBUFLEN     1024

        char        a1buf[STACKBUFLEN];
        char        a2buf[STACKBUFLEN];
        char       *a1p,
                   *a2p;

#ifdef HAVE_LOCALE_T
        pg_locale_t mylocale = 0;
#endif

        if (collid != DEFAULT_COLLATION_OID)
        {
            if (!OidIsValid(collid))
            {
                /*
                 * This typically means that the parser could not resolve a
                 * conflict of implicit collations, so report it that way.
                 */
                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.")));
            }
#ifdef HAVE_LOCALE_T
            mylocale = pg_newlocale_from_collation(collid);
#endif
        }

#ifdef WIN32
        /* Win32 does not have UTF-8, so we need to map to UTF-16 */
        if (GetDatabaseEncoding() == PG_UTF8)
        {
            int         a1len;
            int         a2len;
            int         r;

            if (len1 >= STACKBUFLEN / 2)
            {
                a1len = len1 * 2 + 2;
                a1p = palloc(a1len);
            }
            else
            {
                a1len = STACKBUFLEN;
                a1p = a1buf;
            }
            if (len2 >= STACKBUFLEN / 2)
            {
                a2len = len2 * 2 + 2;
                a2p = palloc(a2len);
            }
            else
            {
                a2len = STACKBUFLEN;
                a2p = a2buf;
            }

            /* stupid Microsloth API does not work for zero-length input */
            if (len1 == 0)
                r = 0;
            else
            {
                r = MultiByteToWideChar(CP_UTF8, 0, arg1, len1,
                                        (LPWSTR) a1p, a1len / 2);
                if (!r)
                    ereport(ERROR,
                            (errmsg("could not convert string to UTF-16: error code %lu",
                                    GetLastError())));
            }
            ((LPWSTR) a1p)[r] = 0;

            if (len2 == 0)
                r = 0;
            else
            {
                r = MultiByteToWideChar(CP_UTF8, 0, arg2, len2,
                                        (LPWSTR) a2p, a2len / 2);
                if (!r)
                    ereport(ERROR,
                            (errmsg("could not convert string to UTF-16: error code %lu",
                                    GetLastError())));
            }
            ((LPWSTR) a2p)[r] = 0;

            errno = 0;
#ifdef HAVE_LOCALE_T
            if (mylocale)
                result = wcscoll_l((LPWSTR) a1p, (LPWSTR) a2p, mylocale);
            else
#endif
                result = wcscoll((LPWSTR) a1p, (LPWSTR) a2p);
            if (result == 2147483647)   /* _NLSCMPERROR; missing from mingw
                                         * headers */
                ereport(ERROR,
                        (errmsg("could not compare Unicode strings: %m")));

            /*
             * In some locales wcscoll() can claim that nonidentical strings
             * are equal.  Believing that would be bad news for a number of
             * reasons, so we follow Perl's lead and sort "equal" strings
             * according to strcmp (on the UTF-8 representation).
             */
            if (result == 0)
            {
                result = memcmp(arg1, arg2, Min(len1, len2));
                if ((result == 0) && (len1 != len2))
                    result = (len1 < len2) ? -1 : 1;
            }

            if (a1p != a1buf)
                pfree(a1p);
            if (a2p != a2buf)
                pfree(a2p);

            return result;
        }
#endif   /* WIN32 */

        if (len1 >= STACKBUFLEN)
            a1p = (char *) palloc(len1 + 1);
        else
            a1p = a1buf;
        if (len2 >= STACKBUFLEN)
            a2p = (char *) palloc(len2 + 1);
        else
            a2p = a2buf;

        memcpy(a1p, arg1, len1);
        a1p[len1] = '\0';
        memcpy(a2p, arg2, len2);
        a2p[len2] = '\0';

#ifdef HAVE_LOCALE_T
        if (mylocale)
            result = strcoll_l(a1p, a2p, mylocale);
        else
#endif
            result = strcoll(a1p, a2p);

        /*
         * In some locales strcoll() can claim that nonidentical strings are
         * equal.  Believing that would be bad news for a number of reasons,
         * so we follow Perl's lead and sort "equal" strings according to
         * strcmp().
         */
        if (result == 0)
            result = strcmp(a1p, a2p);

        if (a1p != a1buf)
            pfree(a1p);
        if (a2p != a2buf)
            pfree(a2p);
    }

    return result;
}

Datum void_in ( PG_FUNCTION_ARGS   ) 

Definition at line 223 of file pseudotypes.c.

References PG_RETURN_VOID.

{
    PG_RETURN_VOID();           /* you were expecting something different? */
}

Datum void_out ( PG_FUNCTION_ARGS   ) 

Definition at line 234 of file pseudotypes.c.

References PG_RETURN_CSTRING, and pstrdup().

Datum void_recv ( PG_FUNCTION_ARGS   ) 

Definition at line 246 of file pseudotypes.c.

References PG_RETURN_VOID.

Datum void_send ( PG_FUNCTION_ARGS   ) 

Definition at line 258 of file pseudotypes.c.

References buf, PG_RETURN_BYTEA_P, pq_begintypsend(), and pq_endtypsend().

{
    StringInfoData buf;

    /* send an empty string */
    pq_begintypsend(&buf);
    PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
}

Datum width_bucket_float8 ( PG_FUNCTION_ARGS   ) 

Definition at line 2737 of file float.c.

References ereport, errcode(), errmsg(), ERROR, isinf(), PG_GETARG_FLOAT8, PG_GETARG_INT32, and PG_RETURN_INT32.

{
    float8      operand = PG_GETARG_FLOAT8(0);
    float8      bound1 = PG_GETARG_FLOAT8(1);
    float8      bound2 = PG_GETARG_FLOAT8(2);
    int32       count = PG_GETARG_INT32(3);
    int32       result;

    if (count <= 0.0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
                 errmsg("count must be greater than zero")));

    if (isnan(operand) || isnan(bound1) || isnan(bound2))
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
             errmsg("operand, lower bound, and upper bound cannot be NaN")));

    /* Note that we allow "operand" to be infinite */
    if (isinf(bound1) || isinf(bound2))
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
                 errmsg("lower and upper bounds must be finite")));

    if (bound1 < bound2)
    {
        if (operand < bound1)
            result = 0;
        else if (operand >= bound2)
        {
            result = count + 1;
            /* check for overflow */
            if (result < count)
                ereport(ERROR,
                        (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                         errmsg("integer out of range")));
        }
        else
            result = ((float8) count * (operand - bound1) / (bound2 - bound1)) + 1;
    }
    else if (bound1 > bound2)
    {
        if (operand > bound1)
            result = 0;
        else if (operand <= bound2)
        {
            result = count + 1;
            /* check for overflow */
            if (result < count)
                ereport(ERROR,
                        (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
                         errmsg("integer out of range")));
        }
        else
            result = ((float8) count * (bound1 - operand) / (bound1 - bound2)) + 1;
    }
    else
    {
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
                 errmsg("lower bound cannot equal upper bound")));
        result = 0;             /* keep the compiler quiet */
    }

    PG_RETURN_INT32(result);
}

Datum width_bucket_numeric ( PG_FUNCTION_ARGS   ) 

Definition at line 1199 of file numeric.c.

References add_var(), cmp_numerics(), compute_bucket(), ereport, errcode(), errmsg(), ERROR, free_var(), init_var, int8_to_numericvar(), NUMERIC_IS_NAN, numericvar_to_int4(), PG_GETARG_INT32, PG_GETARG_NUMERIC, PG_RETURN_INT32, and set_var_from_var().

{
    Numeric     operand = PG_GETARG_NUMERIC(0);
    Numeric     bound1 = PG_GETARG_NUMERIC(1);
    Numeric     bound2 = PG_GETARG_NUMERIC(2);
    int32       count = PG_GETARG_INT32(3);
    NumericVar  count_var;
    NumericVar  result_var;
    int32       result;

    if (count <= 0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
                 errmsg("count must be greater than zero")));

    if (NUMERIC_IS_NAN(operand) ||
        NUMERIC_IS_NAN(bound1) ||
        NUMERIC_IS_NAN(bound2))
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
             errmsg("operand, lower bound, and upper bound cannot be NaN")));

    init_var(&result_var);
    init_var(&count_var);

    /* Convert 'count' to a numeric, for ease of use later */
    int8_to_numericvar((int64) count, &count_var);

    switch (cmp_numerics(bound1, bound2))
    {
        case 0:
            ereport(ERROR,
                (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
                 errmsg("lower bound cannot equal upper bound")));

            /* bound1 < bound2 */
        case -1:
            if (cmp_numerics(operand, bound1) < 0)
                set_var_from_var(&const_zero, &result_var);
            else if (cmp_numerics(operand, bound2) >= 0)
                add_var(&count_var, &const_one, &result_var);
            else
                compute_bucket(operand, bound1, bound2,
                               &count_var, &result_var);
            break;

            /* bound1 > bound2 */
        case 1:
            if (cmp_numerics(operand, bound1) > 0)
                set_var_from_var(&const_zero, &result_var);
            else if (cmp_numerics(operand, bound2) <= 0)
                add_var(&count_var, &const_one, &result_var);
            else
                compute_bucket(operand, bound1, bound2,
                               &count_var, &result_var);
            break;
    }

    /* if result exceeds the range of a legal int4, we ereport here */
    result = numericvar_to_int4(&result_var);

    free_var(&count_var);
    free_var(&result_var);

    PG_RETURN_INT32(result);
}

Datum window_cume_dist ( PG_FUNCTION_ARGS   ) 

Definition at line 169 of file windowfuncs.c.

References Assert, PG_RETURN_FLOAT8, PG_WINDOW_OBJECT, rank_context::rank, rank_up(), WinGetCurrentPosition(), WinGetPartitionLocalMemory(), WinGetPartitionRowCount(), and WinRowsArePeers().

{
    WindowObject winobj = PG_WINDOW_OBJECT();
    rank_context *context;
    bool        up;
    int64       totalrows = WinGetPartitionRowCount(winobj);

    Assert(totalrows > 0);

    up = rank_up(winobj);
    context = (rank_context *)
        WinGetPartitionLocalMemory(winobj, sizeof(rank_context));
    if (up || context->rank == 1)
    {
        /*
         * The current row is not peer to prior row or is just the first, so
         * count up the number of rows that are peer to the current.
         */
        int64       row;

        context->rank = WinGetCurrentPosition(winobj) + 1;

        /*
         * start from current + 1
         */
        for (row = context->rank; row < totalrows; row++)
        {
            if (!WinRowsArePeers(winobj, row - 1, row))
                break;
            context->rank++;
        }
    }

    PG_RETURN_FLOAT8((float8) context->rank / (float8) totalrows);
}

Datum window_dense_rank ( PG_FUNCTION_ARGS   ) 

Definition at line 118 of file windowfuncs.c.

References PG_RETURN_INT64, PG_WINDOW_OBJECT, rank_context::rank, rank_up(), and WinGetPartitionLocalMemory().

{
    WindowObject winobj = PG_WINDOW_OBJECT();
    rank_context *context;
    bool        up;

    up = rank_up(winobj);
    context = (rank_context *)
        WinGetPartitionLocalMemory(winobj, sizeof(rank_context));
    if (up)
        context->rank++;

    PG_RETURN_INT64(context->rank);
}

Datum window_first_value ( PG_FUNCTION_ARGS   ) 

Definition at line 407 of file windowfuncs.c.

References NULL, PG_RETURN_DATUM, PG_RETURN_NULL, PG_WINDOW_OBJECT, WINDOW_SEEK_HEAD, and WinGetFuncArgInFrame().

{
    WindowObject winobj = PG_WINDOW_OBJECT();
    Datum       result;
    bool        isnull;

    result = WinGetFuncArgInFrame(winobj, 0,
                                  0, WINDOW_SEEK_HEAD, true,
                                  &isnull, NULL);
    if (isnull)
        PG_RETURN_NULL();

    PG_RETURN_DATUM(result);
}

Datum window_lag ( PG_FUNCTION_ARGS   ) 

Definition at line 338 of file windowfuncs.c.

References leadlag_common().

{
    return leadlag_common(fcinfo, false, false, false);
}

Datum window_lag_with_offset ( PG_FUNCTION_ARGS   ) 

Definition at line 350 of file windowfuncs.c.

References leadlag_common().

{
    return leadlag_common(fcinfo, false, true, false);
}

Datum window_lag_with_offset_and_default ( PG_FUNCTION_ARGS   ) 

Definition at line 361 of file windowfuncs.c.

References leadlag_common().

{
    return leadlag_common(fcinfo, false, true, true);
}

Datum window_last_value ( PG_FUNCTION_ARGS   ) 

Definition at line 428 of file windowfuncs.c.

References NULL, PG_RETURN_DATUM, PG_RETURN_NULL, PG_WINDOW_OBJECT, WINDOW_SEEK_TAIL, and WinGetFuncArgInFrame().

{
    WindowObject winobj = PG_WINDOW_OBJECT();
    Datum       result;
    bool        isnull;

    result = WinGetFuncArgInFrame(winobj, 0,
                                  0, WINDOW_SEEK_TAIL, true,
                                  &isnull, NULL);
    if (isnull)
        PG_RETURN_NULL();

    PG_RETURN_DATUM(result);
}

Datum window_lead ( PG_FUNCTION_ARGS   ) 

Definition at line 373 of file windowfuncs.c.

References leadlag_common().

{
    return leadlag_common(fcinfo, true, false, false);
}

Datum window_lead_with_offset ( PG_FUNCTION_ARGS   ) 

Definition at line 385 of file windowfuncs.c.

References leadlag_common().

{
    return leadlag_common(fcinfo, true, true, false);
}

Datum window_lead_with_offset_and_default ( PG_FUNCTION_ARGS   ) 

Definition at line 396 of file windowfuncs.c.

References leadlag_common().

{
    return leadlag_common(fcinfo, true, true, true);
}

Datum window_nth_value ( PG_FUNCTION_ARGS   ) 

Definition at line 449 of file windowfuncs.c.

References DatumGetInt32, ereport, errcode(), errmsg(), ERROR, get_fn_expr_arg_stable(), NULL, PG_RETURN_DATUM, PG_RETURN_NULL, PG_WINDOW_OBJECT, WINDOW_SEEK_HEAD, WinGetFuncArgCurrent(), and WinGetFuncArgInFrame().

{
    WindowObject winobj = PG_WINDOW_OBJECT();
    bool        const_offset;
    Datum       result;
    bool        isnull;
    int32       nth;

    nth = DatumGetInt32(WinGetFuncArgCurrent(winobj, 1, &isnull));
    if (isnull)
        PG_RETURN_NULL();
    const_offset = get_fn_expr_arg_stable(fcinfo->flinfo, 1);

    if (nth <= 0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_ARGUMENT_FOR_NTH_VALUE),
                 errmsg("argument of nth_value must be greater than zero")));

    result = WinGetFuncArgInFrame(winobj, 0,
                                  nth - 1, WINDOW_SEEK_HEAD, const_offset,
                                  &isnull, NULL);
    if (isnull)
        PG_RETURN_NULL();

    PG_RETURN_DATUM(result);
}

Datum window_ntile ( PG_FUNCTION_ARGS   ) 

Definition at line 211 of file windowfuncs.c.

References ntile_context::boundary, DatumGetInt32, ereport, errcode(), errmsg(), ERROR, ntile_context::ntile, PG_RETURN_INT32, PG_RETURN_NULL, PG_WINDOW_OBJECT, ntile_context::remainder, ntile_context::rows_per_bucket, WinGetFuncArgCurrent(), WinGetPartitionLocalMemory(), and WinGetPartitionRowCount().

{
    WindowObject winobj = PG_WINDOW_OBJECT();
    ntile_context *context;

    context = (ntile_context *)
        WinGetPartitionLocalMemory(winobj, sizeof(ntile_context));

    if (context->ntile == 0)
    {
        /* first call */
        int64       total;
        int32       nbuckets;
        bool        isnull;

        total = WinGetPartitionRowCount(winobj);
        nbuckets = DatumGetInt32(WinGetFuncArgCurrent(winobj, 0, &isnull));

        /*
         * per spec: If NT is the null value, then the result is the null
         * value.
         */
        if (isnull)
            PG_RETURN_NULL();

        /*
         * per spec: If NT is less than or equal to 0 (zero), then an
         * exception condition is raised.
         */
        if (nbuckets <= 0)
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_ARGUMENT_FOR_NTILE),
                     errmsg("argument of ntile must be greater than zero")));

        context->ntile = 1;
        context->rows_per_bucket = 0;
        context->boundary = total / nbuckets;
        if (context->boundary <= 0)
            context->boundary = 1;
        else
        {
            /*
             * If the total number is not divisible, add 1 row to leading
             * buckets.
             */
            context->remainder = total % nbuckets;
            if (context->remainder != 0)
                context->boundary++;
        }
    }

    context->rows_per_bucket++;
    if (context->boundary < context->rows_per_bucket)
    {
        /* ntile up */
        if (context->remainder != 0 && context->ntile == context->remainder)
        {
            context->remainder = 0;
            context->boundary -= 1;
        }
        context->ntile += 1;
        context->rows_per_bucket = 1;
    }

    PG_RETURN_INT32(context->ntile);
}

Datum window_percent_rank ( PG_FUNCTION_ARGS   ) 

Definition at line 140 of file windowfuncs.c.

References Assert, PG_RETURN_FLOAT8, PG_WINDOW_OBJECT, rank_context::rank, rank_up(), WinGetCurrentPosition(), WinGetPartitionLocalMemory(), and WinGetPartitionRowCount().

{
    WindowObject winobj = PG_WINDOW_OBJECT();
    rank_context *context;
    bool        up;
    int64       totalrows = WinGetPartitionRowCount(winobj);

    Assert(totalrows > 0);

    up = rank_up(winobj);
    context = (rank_context *)
        WinGetPartitionLocalMemory(winobj, sizeof(rank_context));
    if (up)
        context->rank = WinGetCurrentPosition(winobj) + 1;

    /* return zero if there's only one row, per spec */
    if (totalrows <= 1)
        PG_RETURN_FLOAT8(0.0);

    PG_RETURN_FLOAT8((float8) (context->rank - 1) / (float8) (totalrows - 1));
}

Datum window_rank ( PG_FUNCTION_ARGS   ) 

Definition at line 98 of file windowfuncs.c.

References PG_RETURN_INT64, PG_WINDOW_OBJECT, rank_context::rank, rank_up(), WinGetCurrentPosition(), and WinGetPartitionLocalMemory().

{
    WindowObject winobj = PG_WINDOW_OBJECT();
    rank_context *context;
    bool        up;

    up = rank_up(winobj);
    context = (rank_context *)
        WinGetPartitionLocalMemory(winobj, sizeof(rank_context));
    if (up)
        context->rank = WinGetCurrentPosition(winobj) + 1;

    PG_RETURN_INT64(context->rank);
}

Datum window_row_number ( PG_FUNCTION_ARGS   ) 

Definition at line 82 of file windowfuncs.c.

References PG_RETURN_INT64, PG_WINDOW_OBJECT, WinGetCurrentPosition(), and WinSetMarkPosition().

{
    WindowObject winobj = PG_WINDOW_OBJECT();
    int64       curpos = WinGetCurrentPosition(winobj);

    WinSetMarkPosition(winobj, curpos);
    PG_RETURN_INT64(curpos + 1);
}

Datum xid_age ( PG_FUNCTION_ARGS   ) 

Definition at line 93 of file xid.c.

References GetStableLatestTransactionId(), now(), PG_GETARG_TRANSACTIONID, PG_RETURN_INT32, and TransactionIdIsNormal.

{
    TransactionId xid = PG_GETARG_TRANSACTIONID(0);
    TransactionId now = GetStableLatestTransactionId();

    /* Permanent XIDs are always infinitely old */
    if (!TransactionIdIsNormal(xid))
        PG_RETURN_INT32(INT_MAX);

    PG_RETURN_INT32((int32) (now - xid));
}

int xidComparator ( const void *  arg1,
const void *  arg2 
)

Definition at line 113 of file xid.c.

Referenced by ProcArrayApplyRecoveryInfo().

{
    TransactionId xid1 = *(const TransactionId *) arg1;
    TransactionId xid2 = *(const TransactionId *) arg2;

    if (xid1 > xid2)
        return 1;
    if (xid1 < xid2)
        return -1;
    return 0;
}

Datum xideq ( PG_FUNCTION_ARGS   ) 
Datum xidin ( PG_FUNCTION_ARGS   ) 

Definition at line 32 of file xid.c.

References NULL, PG_GETARG_CSTRING, and PG_RETURN_TRANSACTIONID.

{
    char       *str = PG_GETARG_CSTRING(0);

    PG_RETURN_TRANSACTIONID((TransactionId) strtoul(str, NULL, 0));
}

Datum xidout ( PG_FUNCTION_ARGS   ) 

Definition at line 40 of file xid.c.

References palloc(), PG_GETARG_TRANSACTIONID, PG_RETURN_CSTRING, and snprintf().

{
    TransactionId transactionId = PG_GETARG_TRANSACTIONID(0);

    /* maximum 32 bit unsigned integer representation takes 10 chars */
    char       *str = palloc(11);

    snprintf(str, 11, "%lu", (unsigned long) transactionId);

    PG_RETURN_CSTRING(str);
}

Datum xidrecv ( PG_FUNCTION_ARGS   ) 
Datum xidsend ( PG_FUNCTION_ARGS   ) 

Variable Documentation

PGDLLIMPORT int extra_float_digits

Definition at line 265 of file ruleutils.c.

Referenced by fmtId(), main(), quote_identifier(), and setup_connection().