PostgreSQL Source Code  git master
stringinfo.c File Reference
#include "postgres.h"
#include "lib/stringinfo.h"
#include "utils/memutils.h"
Include dependency graph for stringinfo.c:

Go to the source code of this file.

Functions

StringInfo makeStringInfo (void)
 
void initStringInfo (StringInfo str)
 
void resetStringInfo (StringInfo str)
 
void appendStringInfo (StringInfo str, const char *fmt,...)
 
int appendStringInfoVA (StringInfo str, const char *fmt, va_list args)
 
void appendStringInfoString (StringInfo str, const char *s)
 
void appendStringInfoChar (StringInfo str, char ch)
 
void appendStringInfoSpaces (StringInfo str, int count)
 
void appendBinaryStringInfo (StringInfo str, const char *data, int datalen)
 
void appendBinaryStringInfoNT (StringInfo str, const char *data, int datalen)
 
void enlargeStringInfo (StringInfo str, int needed)
 

Function Documentation

◆ appendBinaryStringInfo()

void appendBinaryStringInfo ( StringInfo  str,
const char *  data,
int  datalen 
)

Definition at line 214 of file stringinfo.c.

References Assert, StringInfoData::data, enlargeStringInfo(), and StringInfoData::len.

Referenced by add_indent(), appendStringInfoRegexpSubstr(), appendStringInfoString(), appendStringInfoText(), buf_add_txid(), buf_init(), bytea_string_agg_transfn(), config_enum_get_options(), CopyReadLine(), CopyReadLineText(), CopySendData(), CopySendString(), database_to_xml_internal(), DeadLockReport(), deparseFromExprForRel(), ExecBuildSlotPartitionKeyDescription(), ExecBuildSlotValueDescription(), flattenJsonPathParseItem(), get_from_clause(), get_target_list(), GetOldFunctionMessage(), HandleParallelMessages(), hstore_to_json(), hstore_to_json_loose(), hstore_to_jsonb_loose(), ident_inet(), int8_avg_deserialize(), json_lex_string(), jsonb_put_escaped_value(), JsonbToCStringWorker(), jsonPathToCstring(), log_line_prefix(), map_sql_identifier_to_xml_name(), map_xml_name_to_sql_identifier(), numeric_avg_deserialize(), numeric_deserialize(), numeric_poly_deserialize(), parse_fcall_arguments(), parse_fcall_arguments_20(), pg_decode_message(), pg_get_functiondef(), plpgsql_append_source_text(), pq_getstring(), pq_sendbytes(), pq_sendtext(), print_function_rettype(), printJsonPathItem(), process_pipe_input(), range_recv(), replace_text(), replace_text_regexp(), reserveSpaceForItemPointer(), RI_FKey_cascade_upd(), ri_set(), schema_to_xml_internal(), unaccent_lexize(), write_csvlog(), XLogInsertRecord(), XLogWalRcvProcessMsg(), xml_is_document(), xml_send(), and xmlconcat().

215 {
216  Assert(str != NULL);
217 
218  /* Make more room if needed */
219  enlargeStringInfo(str, datalen);
220 
221  /* OK, append the data */
222  memcpy(str->data + str->len, data, datalen);
223  str->len += datalen;
224 
225  /*
226  * Keep a trailing null in place, even though it's probably useless for
227  * binary data. (Some callers are dealing with text but call this because
228  * their input isn't null-terminated.)
229  */
230  str->data[str->len] = '\0';
231 }
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:270
#define Assert(condition)
Definition: c.h:732

◆ appendBinaryStringInfoNT()

void appendBinaryStringInfoNT ( StringInfo  str,
const char *  data,
int  datalen 
)

Definition at line 240 of file stringinfo.c.

References Assert, StringInfoData::data, enlargeStringInfo(), and StringInfoData::len.

Referenced by pq_sendcountedtext(), and pq_sendstring().

241 {
242  Assert(str != NULL);
243 
244  /* Make more room if needed */
245  enlargeStringInfo(str, datalen);
246 
247  /* OK, append the data */
248  memcpy(str->data + str->len, data, datalen);
249  str->len += datalen;
250 }
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:270
#define Assert(condition)
Definition: c.h:732

◆ appendStringInfo()

void appendStringInfo ( StringInfo  str,
const char *  fmt,
  ... 
)

Definition at line 78 of file stringinfo.c.

References appendStringInfoVA(), generate_unaccent_rules::args, and enlargeStringInfo().

Referenced by _outConstraint(), _outForeignKeyOptInfo(), _outList(), _outPathTarget(), _outValue(), add_cast_to(), appendFunctionName(), array_to_text_internal(), bqarr_in(), brin_desc(), btree_desc(), build_tuplestore_recursively(), BuildIndexValueDescription(), checkSharedDependencies(), clog_desc(), commit_ts_desc(), ConvertTriggerToFK(), copy_table(), create_cursor(), database_to_xml_internal(), datum_to_json(), dbase_desc(), dblink_close(), dblink_fdw_validator(), dblink_fetch(), dblink_open(), DeadLockReport(), decompile_column_index_array(), deparseAnalyzeSizeSql(), deparseArrayExpr(), deparseBoolExpr(), deparseColumnRef(), deparseConst(), deparseDirectDeleteSql(), deparseDirectUpdateSql(), deparseFromExprForRel(), deparseFuncExpr(), deparseInsertSql(), deparseLockingClause(), deparseOperatorName(), deparseRangeTblRef(), deparseRelabelType(), deparseRelation(), deparseScalarArrayOpExpr(), deparseSortGroupClause(), deparseUpdateSql(), deparseVar(), desc_recompress_leaf(), DescribeLockTag(), do_pg_start_backup(), DropSubscription(), errdetail_params(), escape_json(), ExecBuildSlotPartitionKeyDescription(), ExecEvalXmlExpr(), execute_extension_script(), ExplainIndexScanDetails(), ExplainNode(), ExplainOpenGroup(), ExplainPrintJIT(), ExplainPrintSettings(), ExplainProperty(), ExplainPropertyList(), ExplainTargetRel(), ExportSnapshot(), fetch_remote_table_info(), file_fdw_validator(), flatten_reloptions(), flatten_set_variable_args(), foreign_grouping_ok(), foreign_join_ok(), format_expr_params(), format_node_dump(), format_operator_internal(), format_preparedparamsdata(), format_procedure_internal(), FreePageManagerDump(), FreePageManagerDumpBtree(), FreePageManagerDumpSpans(), fsm_page_contents(), funcname_signature_string(), generate_operator_clause(), generate_operator_name(), generic_desc(), get_agg_expr(), get_coercion_expr(), get_connect_string(), get_const_collation(), get_const_expr(), get_delete_query_def(), get_from_clause_coldeflist(), get_from_clause_item(), get_func_expr(), get_insert_query_def(), get_opclass_name(), get_oper_expr(), get_parameter(), get_rule_expr(), get_rule_expr_funccall(), get_rule_orderby(), get_rule_sortgroupclause(), get_rule_windowclause(), get_select_query_def(), get_sql_delete(), get_sql_insert(), get_sql_update(), get_sublink_expr(), get_tablefunc(), get_tablesample_def(), get_target_list(), get_tuple_of_interest(), get_update_query_def(), get_utility_query_def(), get_variable(), get_windowfunc_expr(), getObjectDescription(), getObjectIdentityParts(), getOpFamilyDescription(), getOpFamilyIdentity(), getRelationDescription(), gin_desc(), hash_desc(), heap2_desc(), heap_desc(), heap_vacuum_rel(), ident_inet(), incompatible_module_error(), initialize_worker_spi(), KnownAssignedXidsDisplay(), lazy_scan_heap(), libpqrcv_create_slot(), libpqrcv_startstreaming(), log_line_prefix(), logicalmsg_desc(), make_ruledef(), make_temptable_name_n(), map_multipart_sql_identifier_to_xml_name(), map_sql_catalog_to_xmlschema_types(), map_sql_identifier_to_xml_name(), map_sql_schema_to_xmlschema_types(), map_sql_table_to_xmlschema(), map_sql_type_to_xml_name(), map_sql_type_to_xmlschema_type(), map_sql_typecoll_to_xmlschema_types(), multixact_desc(), mxid_to_string(), op_signature_string(), out_gistxlogDelete(), out_gistxlogPageDelete(), out_gistxlogPageReuse(), out_gistxlogPageSplit(), out_member(), outBitmapset(), outDatum(), packArcInfoCmp(), pair_encode(), pg_decode_commit_txn(), pg_decode_message(), pg_dependencies_out(), pg_get_constraintdef_worker(), pg_get_functiondef(), pg_get_indexdef_worker(), pg_get_partkeydef_worker(), pg_get_statisticsobj_worker(), pg_get_triggerdef_worker(), pg_ndistinct_out(), pg_output_begin(), pgp_armor_encode(), PLy_traceback(), populate_array_report_expected_array(), postgres_fdw_validator(), postgresAcquireSampleRowsFunc(), postgresGetForeignRelSize(), postgresImportForeignSchema(), postgresql_fdw_validator(), pretty_format_node_dump(), print_function_arguments(), print_function_trftypes(), print_literal(), printJsonPathItem(), printRemoteParam(), printRemotePlaceholder(), processIndirection(), ProcSleep(), query_to_xml_internal(), quote_object_name(), quote_qualified_identifier(), refresh_by_match_merge(), relmap_desc(), replorigin_desc(), report_triggers(), reportDependentObjects(), ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), ri_GenerateQual(), ri_GenerateQualCollation(), RI_Initial_Check(), RI_PartitionRemove_Check(), ri_restrict(), ri_set(), schema_get_xml_visible_tables(), schema_to_xml_internal(), send_message_to_frontend(), send_message_to_server_log(), sepgsql_attribute_post_create(), sepgsql_audit_log(), sepgsql_proc_post_create(), sepgsql_relation_post_create(), sepgsql_schema_post_create(), seq_desc(), serialize_deflist(), show_buffer_usage(), show_hash_info(), show_sort_info(), show_sortorder_options(), show_tablesample(), show_tidbitmap_info(), ShowTransactionStateRec(), ShowUsage(), smgr_desc(), spg_desc(), SPI_sql_row_to_xmlelement(), standby_desc(), standby_desc_invalidations(), standby_desc_running_xacts(), StartupXLOG(), storeObjectDescription(), table_to_xml_internal(), tblspc_desc(), txid_snapshot_out(), typeStringToTypeName(), write_csvlog(), xact_desc(), xact_desc_abort(), xact_desc_assignment(), xact_desc_commit(), xlog_desc(), xlog_outdesc(), xlog_redo(), XLogInsertRecord(), xml_is_document(), xmldata_root_element_end(), xmldata_root_element_start(), xmlpi(), xpath_table(), and xsd_schema_element_start().

79 {
80  int save_errno = errno;
81 
82  for (;;)
83  {
84  va_list args;
85  int needed;
86 
87  /* Try to format the data. */
88  errno = save_errno;
89  va_start(args, fmt);
90  needed = appendStringInfoVA(str, fmt, args);
91  va_end(args);
92 
93  if (needed == 0)
94  break; /* success */
95 
96  /* Increase the buffer size and try again. */
97  enlargeStringInfo(str, needed);
98  }
99 }
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:270
int appendStringInfoVA(StringInfo str, const char *fmt, va_list args)
Definition: stringinfo.c:120

◆ appendStringInfoChar()

void appendStringInfoChar ( StringInfo  str,
char  ch 
)

Definition at line 175 of file stringinfo.c.

Referenced by _outAExpr(), _outList(), _outValue(), appendConditions(), appendContextKeyword(), appendStringInfoRegexpSubstr(), appendTypeNameToBuffer(), array_dim_to_json(), brin_page_items(), BuildIndexValueDescription(), CheckSCRAMAuth(), circle_out(), composite_to_json(), ConvertTriggerToFK(), cube_out(), cursor_to_xml(), database_to_xml_internal(), DeadLockReport(), deparseAggref(), deparseArrayExpr(), deparseBoolExpr(), deparseColumnRef(), deparseDistinctExpr(), deparseFromExprForRel(), deparseFuncExpr(), deparseInsertSql(), deparseNullTest(), deparseOpExpr(), deparseRangeTblRef(), deparseScalarArrayOpExpr(), deparseSortGroupClause(), deparseStringLiteral(), deparseSubscriptingRef(), do_pg_start_backup(), escape_param_str(), exec_stmt_raise(), ExecBuildSlotPartitionKeyDescription(), ExecBuildSlotValueDescription(), ExplainBeginOutput(), ExplainCloseGroup(), ExplainJSONLineEnding(), ExplainNode(), ExplainOpenGroup(), ExplainProperty(), ExplainPropertyList(), ExplainPropertyListNested(), ExplainSeparatePlans(), ExplainXMLTag(), ExplainYAMLLineStarting(), fetch_table_list(), flattenJsonPathParseItem(), format_procedure_internal(), FreePageManagerDumpBtree(), FreePageManagerDumpSpans(), funcname_signature_string(), generate_operator_name(), get_agg_expr(), get_basic_select_query(), get_coercion_expr(), get_column_alias_list(), get_delete_query_def(), get_from_clause_coldeflist(), get_from_clause_item(), get_func_expr(), get_insert_query_def(), get_oper_expr(), get_parameter(), get_range_partbound_string(), get_rule_expr(), get_rule_expr_paren(), get_rule_groupingset(), get_rule_sortgroupclause(), get_rule_windowspec(), get_setop_query(), get_special_variable(), get_sql_insert(), get_sublink_expr(), get_tablefunc(), get_tablesample_def(), get_update_query_def(), get_update_query_targetlist_def(), get_values_def(), get_variable(), get_windowfunc_expr(), get_with_clause(), hstore_to_json(), hstore_to_json_loose(), ident_inet(), incompatible_module_error(), InteractiveBackend(), json_agg_transfn(), json_build_array(), json_build_object(), json_lex_string(), json_object(), json_object_two_arg(), libpqrcv_startstreaming(), log_line_prefix(), make_ruledef(), make_viewdef(), merge_children(), mxid_to_string(), NameListToQuotedString(), NameListToString(), outBitmapset(), outDatum(), outNode(), outToken(), packArcInfoCmp(), path_encode(), pg_be_scram_get_mechanisms(), pg_decode_change(), pg_dependencies_out(), pg_get_constraintdef_worker(), pg_get_functiondef(), pg_get_indexdef_worker(), pg_get_partkeydef_worker(), pg_get_statisticsobj_worker(), pg_get_triggerdef_worker(), pg_ndistinct_out(), pg_split_opts(), pgp_armor_encode(), postgresImportForeignSchema(), pq_send_ascii_string(), print_function_arguments(), print_function_rettype(), print_literal(), printJsonPathItem(), printSubscripts(), query_to_xml_internal(), range_bound_escape(), range_deparse(), range_parse_bound(), record_in(), record_out(), reportDependentObjects(), RI_Initial_Check(), RI_PartitionRemove_Check(), run_ssl_passphrase_command(), schema_to_xml_internal(), send_message_to_frontend(), send_message_to_server_log(), sepgsql_proc_post_create(), serialize_deflist(), show_buffer_usage(), show_modifytable_info(), show_tablesample(), show_tidbitmap_info(), simple_quote_literal(), SPI_sql_row_to_xmlelement(), storeObjectDescription(), stringlist_to_identifierstr(), tuple_to_stringinfo(), txid_snapshot_out(), TypeNameListToString(), uuid_out(), write_csvlog(), xlog_outdesc(), xml_is_document(), and xmlpi().

176 {
177  /* Make more room if needed */
178  if (str->len + 1 >= str->maxlen)
179  enlargeStringInfo(str, 1);
180 
181  /* OK, append the character */
182  str->data[str->len] = ch;
183  str->len++;
184  str->data[str->len] = '\0';
185 }
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:270

◆ appendStringInfoSpaces()

void appendStringInfoSpaces ( StringInfo  str,
int  count 
)

Definition at line 193 of file stringinfo.c.

References StringInfoData::data, enlargeStringInfo(), and StringInfoData::len.

Referenced by appendContextKeyword(), ExplainCloseGroup(), ExplainDummyGroup(), ExplainNode(), ExplainOpenGroup(), ExplainPrintJIT(), ExplainProperty(), ExplainPropertyList(), ExplainPropertyListNested(), ExplainXMLTag(), ExplainYAMLLineStarting(), flattenJsonPathParseItem(), jsonPathFromCstring(), log_line_prefix(), merge_children(), show_buffer_usage(), show_hash_info(), show_modifytable_info(), show_sort_info(), show_tablesample(), show_tidbitmap_info(), and text_format_append_string().

194 {
195  if (count > 0)
196  {
197  /* Make more room if needed */
198  enlargeStringInfo(str, count);
199 
200  /* OK, append the spaces */
201  while (--count >= 0)
202  str->data[str->len++] = ' ';
203  str->data[str->len] = '\0';
204  }
205 }
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:270

◆ appendStringInfoString()

void appendStringInfoString ( StringInfo  str,
const char *  s 
)

Definition at line 163 of file stringinfo.c.

Referenced by _outAConst(), _outAExpr(), _outBoolExpr(), _outConst(), _outConstraint(), _outCustomPath(), _outCustomScan(), _outForeignKeyOptInfo(), _outPathInfo(), _outPathTarget(), _outQuery(), _outValue(), appendAggOrderBy(), appendConditions(), appendContextKeyword(), appendFunctionName(), appendGroupByClause(), appendLimitClause(), appendOrderByClause(), appendTypeNameToBuffer(), array_dim_to_json(), array_to_json_internal(), array_to_text_internal(), brin_page_items(), build_tuplestore_recursively(), BuildIndexValueDescription(), composite_to_json(), concat_internal(), config_enum_get_options(), ConvertTriggerToFK(), cube_out(), database_to_xmlschema_internal(), datum_to_json(), decompile_column_index_array(), deparseAggref(), deparseAnalyzeSizeSql(), deparseAnalyzeSql(), deparseArrayExpr(), deparseBoolExpr(), deparseColumnRef(), deparseConst(), deparseDeleteSql(), deparseDirectDeleteSql(), deparseDirectUpdateSql(), deparseDistinctExpr(), deparseExplicitTargetList(), deparseFromExpr(), deparseFromExprForRel(), deparseFuncExpr(), deparseInsertSql(), deparseLockingClause(), deparseNullTest(), deparseOperatorName(), deparseRangeTblRef(), deparseSelectSql(), deparseSelectStmtForRel(), deparseSubqueryTargetList(), deparseTargetList(), deparseUpdateSql(), errdetail_params(), escape_json(), escape_xml(), estimate_path_cost_size(), exec_stmt_raise(), ExecBuildSlotPartitionKeyDescription(), ExecBuildSlotValueDescription(), execute_extension_script(), ExplainBeginOutput(), ExplainDummyGroup(), ExplainEndOutput(), ExplainIndexScanDetails(), ExplainNode(), ExplainOneUtility(), ExplainOpenGroup(), ExplainPrintJIT(), ExplainPrintSettings(), ExplainProperty(), ExplainPropertyList(), ExplainPropertyListNested(), ExplainQuery(), ExplainTargetRel(), ExplainXMLTag(), ExportSnapshot(), fetch_table_list(), flatten_reloptions(), flatten_set_variable_args(), format_expr_params(), format_operator_internal(), format_preparedparamsdata(), format_procedure_internal(), FreePageManagerDump(), funcname_signature_string(), generate_operator_clause(), generate_operator_name(), get_agg_expr(), get_basic_select_query(), get_column_alias_list(), get_const_expr(), get_from_clause(), get_from_clause_coldeflist(), get_from_clause_item(), get_func_expr(), get_insert_query_def(), get_query_def(), get_range_partbound_string(), get_rule_expr(), get_rule_expr_funccall(), get_rule_groupingset(), get_rule_orderby(), get_rule_windowclause(), get_rule_windowspec(), get_select_query_def(), get_setop_query(), get_sql_delete(), get_sql_insert(), get_sql_update(), get_sublink_expr(), get_tablefunc(), get_tablesample_def(), get_target_list(), get_tuple_of_interest(), get_update_query_def(), get_update_query_targetlist_def(), get_utility_query_def(), get_values_def(), get_variable(), get_windowfunc_expr(), get_with_clause(), getConstraintTypeDescription(), getObjectIdentityParts(), getObjectTypeDescription(), getProcedureTypeDescription(), getRelationIdentity(), getRelationTypeDescription(), gin_desc(), heap_desc(), hstore_to_json(), hstore_to_json_loose(), ident_inet(), incompatible_module_error(), json_agg_transfn(), json_build_array(), json_build_object(), json_object(), json_object_agg_transfn(), json_object_two_arg(), jsonb_put_escaped_value(), libpqrcv_create_slot(), libpqrcv_startstreaming(), log_line_prefix(), make_ruledef(), make_temptable_name_n(), map_multipart_sql_identifier_to_xml_name(), map_sql_catalog_to_xmlschema_types(), map_sql_identifier_to_xml_name(), map_sql_schema_to_xmlschema_types(), map_sql_table_to_xmlschema(), map_sql_type_to_xml_name(), map_sql_type_to_xmlschema_type(), map_sql_value_to_xml_value(), map_xml_name_to_sql_identifier(), NameListToQuotedString(), NameListToString(), op_signature_string(), out_infobits(), out_member(), outDatum(), outNode(), outToken(), packArcInfoCmp(), pg_be_scram_get_mechanisms(), pg_decode_change(), pg_decode_commit_txn(), pg_decode_truncate(), pg_dependencies_out(), pg_extension_update_paths(), pg_get_constraintdef_worker(), pg_get_functiondef(), pg_get_indexdef_worker(), pg_get_partkeydef_worker(), pg_get_statisticsobj_worker(), pg_get_triggerdef_worker(), pg_ndistinct_out(), pg_output_begin(), pgp_armor_encode(), PLy_traceback(), postgresImportForeignSchema(), print_function_arguments(), print_function_rettype(), print_function_trftypes(), print_literal(), printJsonPathItem(), quote_object_name(), quote_qualified_identifier(), range_deparse(), refresh_by_match_merge(), report_triggers(), ri_Check_Pk_Match(), RI_FKey_check(), RI_Initial_Check(), RI_PartitionRemove_Check(), ri_ReportViolation(), ri_restrict(), run_ssl_passphrase_command(), schema_to_xmlschema_internal(), send_message_to_frontend(), send_message_to_server_log(), sepgsql_audit_log(), sepgsql_database_post_create(), sepgsql_proc_post_create(), serialize_deflist(), show_buffer_usage(), show_modifytable_info(), show_sort_group_keys(), show_sortorder_options(), show_tablesample(), show_tidbitmap_info(), ShowUsage(), single_encode(), smgr_desc(), sn_scalar(), spg_desc(), SPI_sql_row_to_xmlelement(), standby_desc_invalidations(), standby_desc_running_xacts(), StartupXLOG(), stringlist_to_identifierstr(), text_format_append_string(), transform_string_values_scalar(), tuple_to_stringinfo(), write_auto_conf_file(), write_csvlog(), xact_desc_abort(), xact_desc_assignment(), xact_desc_commit(), xlog_desc(), xlog_outdesc(), xlog_redo(), XLogInsertRecord(), xml_is_document(), xml_out_internal(), xmlcomment(), xmlconcat(), xmldata_root_element_start(), xmlpi(), xmlroot(), xsd_schema_element_end(), and xsd_schema_element_start().

164 {
165  appendBinaryStringInfo(str, s, strlen(s));
166 }
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:214

◆ appendStringInfoVA()

int appendStringInfoVA ( StringInfo  str,
const char *  fmt,
va_list  args 
)

Definition at line 120 of file stringinfo.c.

References Assert, StringInfoData::data, StringInfoData::len, StringInfoData::maxlen, and pvsnprintf().

Referenced by appendStringInfo(), and PLy_elog_impl().

121 {
122  int avail;
123  size_t nprinted;
124 
125  Assert(str != NULL);
126 
127  /*
128  * If there's hardly any space, don't bother trying, just fail to make the
129  * caller enlarge the buffer first. We have to guess at how much to
130  * enlarge, since we're skipping the formatting work.
131  */
132  avail = str->maxlen - str->len;
133  if (avail < 16)
134  return 32;
135 
136  nprinted = pvsnprintf(str->data + str->len, (size_t) avail, fmt, args);
137 
138  if (nprinted < (size_t) avail)
139  {
140  /* Success. Note nprinted does not include trailing null. */
141  str->len += (int) nprinted;
142  return 0;
143  }
144 
145  /* Restore the trailing null so that str is unmodified. */
146  str->data[str->len] = '\0';
147 
148  /*
149  * Return pvsnprintf's estimate of the space needed. (Although this is
150  * given as a size_t, we know it will fit in int because it's not more
151  * than MaxAllocSize.)
152  */
153  return (int) nprinted;
154 }
size_t pvsnprintf(char *buf, size_t len, const char *fmt, va_list args)
Definition: psprintf.c:106
#define Assert(condition)
Definition: c.h:732

◆ enlargeStringInfo()

void enlargeStringInfo ( StringInfo  str,
int  needed 
)

Definition at line 270 of file stringinfo.c.

References StringInfoData::data, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, StringInfoData::len, MaxAllocSize, StringInfoData::maxlen, and repalloc().

Referenced by appendBinaryStringInfo(), appendBinaryStringInfoNT(), appendStringInfo(), appendStringInfoChar(), appendStringInfoSpaces(), CopyReadAttributesCSV(), CopyReadAttributesText(), CopyReadBinaryAttribute(), GetOldFunctionMessage(), JsonbToCStringWorker(), jsonPathFromCstring(), jsonPathToCstring(), logicalrep_write_tuple(), pgp_armor_decode(), pgp_armor_encode(), PLy_elog_impl(), pq_getmessage(), pq_sendint16(), pq_sendint32(), pq_sendint64(), pq_sendint8(), reserveFromBuffer(), SendRowDescriptionCols_3(), and XLogSendPhysical().

271 {
272  int newlen;
273 
274  /*
275  * Guard against out-of-range "needed" values. Without this, we can get
276  * an overflow or infinite loop in the following.
277  */
278  if (needed < 0) /* should not happen */
279  elog(ERROR, "invalid string enlargement request size: %d", needed);
280  if (((Size) needed) >= (MaxAllocSize - (Size) str->len))
281  ereport(ERROR,
282  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
283  errmsg("out of memory"),
284  errdetail("Cannot enlarge string buffer containing %d bytes by %d more bytes.",
285  str->len, needed)));
286 
287  needed += str->len + 1; /* total space required now */
288 
289  /* Because of the above test, we now have needed <= MaxAllocSize */
290 
291  if (needed <= str->maxlen)
292  return; /* got enough space already */
293 
294  /*
295  * We don't want to allocate just a little more space with each append;
296  * for efficiency, double the buffer size each time it overflows.
297  * Actually, we might need to more than double it if 'needed' is big...
298  */
299  newlen = 2 * str->maxlen;
300  while (needed > newlen)
301  newlen = 2 * newlen;
302 
303  /*
304  * Clamp to MaxAllocSize in case we went past it. Note we are assuming
305  * here that MaxAllocSize <= INT_MAX/2, else the above loop could
306  * overflow. We will still have newlen >= needed.
307  */
308  if (newlen > (int) MaxAllocSize)
309  newlen = (int) MaxAllocSize;
310 
311  str->data = (char *) repalloc(str->data, newlen);
312 
313  str->maxlen = newlen;
314 }
int errcode(int sqlerrcode)
Definition: elog.c:570
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define ereport(elevel, rest)
Definition: elog.h:141
#define MaxAllocSize
Definition: memutils.h:40
size_t Size
Definition: c.h:466
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1044
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226

◆ initStringInfo()

void initStringInfo ( StringInfo  str)

Definition at line 46 of file stringinfo.c.

References StringInfoData::data, StringInfoData::maxlen, palloc(), and resetStringInfo().

Referenced by array_to_text_internal(), BeginCopyFrom(), bmsToString(), bqarr_in(), brin_page_items(), build_tuplestore_recursively(), BuildIndexValueDescription(), CheckSCRAMAuth(), checkSharedDependencies(), circle_out(), concat_internal(), config_enum_get_options(), convertToJsonb(), ConvertTriggerToFK(), copy_table(), create_cursor(), cube_out(), cursor_to_xml(), dblink_close(), dblink_fdw_validator(), dblink_fetch(), dblink_open(), DeadLockReport(), deparse_expression_pretty(), deparseAnalyzeSizeSql(), deparseFromExprForRel(), do_pg_start_backup(), DropSubscription(), errdetail_params(), escape_param_str(), escape_xml(), estimate_path_cost_size(), exec_replication_command(), exec_stmt_raise(), ExecBuildSlotPartitionKeyDescription(), ExecBuildSlotValueDescription(), ExecEvalXmlExpr(), execute_extension_script(), ExplainPrintSettings(), ExportSnapshot(), fetch_remote_table_info(), fetch_table_list(), file_fdw_validator(), flatten_reloptions(), flatten_set_variable_args(), format_expr_params(), format_node_dump(), format_operator_internal(), format_preparedparamsdata(), format_procedure_internal(), FreePageManagerDump(), fsm_page_contents(), funcname_signature_string(), generate_operator_name(), get_connect_string(), get_from_clause(), get_sql_delete(), get_sql_insert(), get_sql_update(), get_target_list(), get_tuple_of_interest(), getObjectDescription(), getObjectIdentityParts(), getObjectTypeDescription(), HandleParallelMessages(), heap_vacuum_rel(), hstore_to_json(), hstore_to_json_loose(), hstore_to_jsonb_loose(), ident_inet(), incompatible_module_error(), initialize_worker_spi(), int8_avg_deserialize(), json_object(), json_object_two_arg(), jsonpath_send(), jsonPathFromCstring(), jsonPathToCstring(), KnownAssignedXidsDisplay(), lazy_scan_heap(), libpqrcv_create_slot(), libpqrcv_startstreaming(), make_temptable_name_n(), makeStringInfo(), map_multipart_sql_identifier_to_xml_name(), map_sql_catalog_to_xmlschema_types(), map_sql_identifier_to_xml_name(), map_sql_schema_to_xmlschema_types(), map_sql_table_to_xmlschema(), map_sql_type_to_xml_name(), map_sql_type_to_xmlschema_type(), map_sql_typecoll_to_xmlschema_types(), map_sql_value_to_xml_value(), map_xml_name_to_sql_identifier(), merge_children(), mxid_to_string(), NameListToQuotedString(), NameListToString(), nodeToString(), numeric_avg_deserialize(), numeric_deserialize(), numeric_poly_deserialize(), op_signature_string(), packArcInfoCmp(), parse_fcall_arguments(), parse_fcall_arguments_20(), path_encode(), pg_armor(), pg_dearmor(), pg_dependencies_out(), pg_extension_update_paths(), pg_get_constraintdef_worker(), pg_get_function_arguments(), pg_get_function_identity_arguments(), pg_get_function_result(), pg_get_functiondef(), pg_get_indexdef_worker(), pg_get_partkeydef_worker(), pg_get_ruledef_worker(), pg_get_statisticsobj_worker(), pg_get_triggerdef_worker(), pg_get_viewdef_worker(), pg_ndistinct_out(), pg_split_opts(), PLy_elog_impl(), PLy_traceback(), populate_array_report_expected_array(), populate_scalar(), postgres_fdw_validator(), postgresAcquireSampleRowsFunc(), postgresAnalyzeForeignTable(), postgresBeginForeignInsert(), postgresGetForeignPlan(), postgresImportForeignSchema(), PostgresMain(), postgresPlanDirectModify(), postgresPlanForeignModify(), postgresql_fdw_validator(), pq_beginmessage(), pq_begintypsend(), pretty_format_node_dump(), print_function_rettype(), printtup_startup(), process_pipe_input(), ProcSleep(), quote_object_name(), quote_qualified_identifier(), range_bound_escape(), range_deparse(), range_parse_bound(), range_recv(), record_in(), record_out(), recv_password_packet(), refresh_by_match_merge(), replace_text(), replace_text_regexp(), reportDependentObjects(), ri_Check_Pk_Match(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), RI_Initial_Check(), RI_PartitionRemove_Check(), ri_ReportViolation(), ri_restrict(), ri_set(), rm_redo_error_callback(), run_ssl_passphrase_command(), schema_get_xml_visible_tables(), send_message_to_frontend(), send_message_to_server_log(), sepgsql_attribute_post_create(), sepgsql_audit_log(), sepgsql_database_post_create(), sepgsql_proc_post_create(), sepgsql_relation_post_create(), sepgsql_schema_post_create(), serialize_deflist(), show_sort_group_keys(), ShowTransactionStateRec(), ShowUsage(), StartupXLOG(), stringlist_to_identifierstr(), table_to_xml_internal(), text_format(), txid_snapshot_out(), TypeNameListToString(), TypeNameToString(), typeStringToTypeName(), unaccent_lexize(), uuid_out(), WalReceiverMain(), write_auto_conf_file(), write_csvlog(), XLogInsertRecord(), xml_is_document(), xml_out_internal(), xmlcomment(), xmlconcat(), xmlpi(), xmlroot(), XmlTableGetValue(), and xpath_table().

47 {
48  int size = 1024; /* initial default buffer size */
49 
50  str->data = (char *) palloc(size);
51  str->maxlen = size;
52  resetStringInfo(str);
53 }
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:62
void * palloc(Size size)
Definition: mcxt.c:924

◆ makeStringInfo()

◆ resetStringInfo()