PostgreSQL Source Code  git master
regexp.c File Reference
#include "postgres.h"
#include "catalog/pg_type.h"
#include "funcapi.h"
#include "regex/regex.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/memutils.h"
#include "utils/varlena.h"
Include dependency graph for regexp.c:

Go to the source code of this file.

Data Structures

struct  pg_re_flags
 
struct  regexp_matches_ctx
 
struct  cached_re_str
 

Macros

#define PG_GETARG_TEXT_PP_IF_EXISTS(_n)    (PG_NARGS() > (_n) ? PG_GETARG_TEXT_PP(_n) : NULL)
 
#define MAX_CACHED_RES   32
 

Typedefs

typedef struct pg_re_flags pg_re_flags
 
typedef struct regexp_matches_ctx regexp_matches_ctx
 
typedef struct cached_re_str cached_re_str
 

Functions

static regexp_matches_ctxsetup_regexp_matches (text *orig_str, text *pattern, pg_re_flags *re_flags, int start_search, Oid collation, bool use_subpatterns, bool ignore_degenerate, bool fetching_unmatched)
 
static ArrayTypebuild_regexp_match_result (regexp_matches_ctx *matchctx)
 
static Datum build_regexp_split_result (regexp_matches_ctx *splitctx)
 
regex_tRE_compile_and_cache (text *text_re, int cflags, Oid collation)
 
static bool RE_wchar_execute (regex_t *re, pg_wchar *data, int data_len, int start_search, int nmatch, regmatch_t *pmatch)
 
static bool RE_execute (regex_t *re, char *dat, int dat_len, int nmatch, regmatch_t *pmatch)
 
bool RE_compile_and_execute (text *text_re, char *dat, int dat_len, int cflags, Oid collation, int nmatch, regmatch_t *pmatch)
 
static void parse_re_flags (pg_re_flags *flags, text *opts)
 
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 textregexreplace_extended (PG_FUNCTION_ARGS)
 
Datum textregexreplace_extended_no_n (PG_FUNCTION_ARGS)
 
Datum textregexreplace_extended_no_flags (PG_FUNCTION_ARGS)
 
static textsimilar_escape_internal (text *pat_text, text *esc_text)
 
Datum similar_to_escape_2 (PG_FUNCTION_ARGS)
 
Datum similar_to_escape_1 (PG_FUNCTION_ARGS)
 
Datum similar_escape (PG_FUNCTION_ARGS)
 
Datum regexp_count (PG_FUNCTION_ARGS)
 
Datum regexp_count_no_start (PG_FUNCTION_ARGS)
 
Datum regexp_count_no_flags (PG_FUNCTION_ARGS)
 
Datum regexp_instr (PG_FUNCTION_ARGS)
 
Datum regexp_instr_no_start (PG_FUNCTION_ARGS)
 
Datum regexp_instr_no_n (PG_FUNCTION_ARGS)
 
Datum regexp_instr_no_endoption (PG_FUNCTION_ARGS)
 
Datum regexp_instr_no_flags (PG_FUNCTION_ARGS)
 
Datum regexp_instr_no_subexpr (PG_FUNCTION_ARGS)
 
Datum regexp_like (PG_FUNCTION_ARGS)
 
Datum regexp_like_no_flags (PG_FUNCTION_ARGS)
 
Datum regexp_match (PG_FUNCTION_ARGS)
 
Datum regexp_match_no_flags (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)
 
Datum regexp_substr (PG_FUNCTION_ARGS)
 
Datum regexp_substr_no_start (PG_FUNCTION_ARGS)
 
Datum regexp_substr_no_n (PG_FUNCTION_ARGS)
 
Datum regexp_substr_no_flags (PG_FUNCTION_ARGS)
 
Datum regexp_substr_no_subexpr (PG_FUNCTION_ARGS)
 
char * regexp_fixed_prefix (text *text_re, bool case_insensitive, Oid collation, bool *exact)
 

Variables

static MemoryContext RegexpCacheMemoryContext
 
static int num_res = 0
 
static cached_re_str re_array [MAX_CACHED_RES]
 

Macro Definition Documentation

◆ MAX_CACHED_RES

#define MAX_CACHED_RES   32

Definition at line 95 of file regexp.c.

◆ PG_GETARG_TEXT_PP_IF_EXISTS

#define PG_GETARG_TEXT_PP_IF_EXISTS (   _n)     (PG_NARGS() > (_n) ? PG_GETARG_TEXT_PP(_n) : NULL)

Definition at line 40 of file regexp.c.

Typedef Documentation

◆ cached_re_str

typedef struct cached_re_str cached_re_str

◆ pg_re_flags

typedef struct pg_re_flags pg_re_flags

◆ regexp_matches_ctx

Function Documentation

◆ build_regexp_match_result()

static ArrayType * build_regexp_match_result ( regexp_matches_ctx matchctx)
static

Definition at line 1620 of file regexp.c.

1621 {
1622  char *buf = matchctx->conv_buf;
1623  Datum *elems = matchctx->elems;
1624  bool *nulls = matchctx->nulls;
1625  int dims[1];
1626  int lbs[1];
1627  int loc;
1628  int i;
1629 
1630  /* Extract matching substrings from the original string */
1631  loc = matchctx->next_match * matchctx->npatterns * 2;
1632  for (i = 0; i < matchctx->npatterns; i++)
1633  {
1634  int so = matchctx->match_locs[loc++];
1635  int eo = matchctx->match_locs[loc++];
1636 
1637  if (so < 0 || eo < 0)
1638  {
1639  elems[i] = (Datum) 0;
1640  nulls[i] = true;
1641  }
1642  else if (buf)
1643  {
1644  int len = pg_wchar2mb_with_len(matchctx->wide_str + so,
1645  buf,
1646  eo - so);
1647 
1648  Assert(len < matchctx->conv_bufsiz);
1650  nulls[i] = false;
1651  }
1652  else
1653  {
1655  PointerGetDatum(matchctx->orig_str),
1656  Int32GetDatum(so + 1),
1657  Int32GetDatum(eo - so));
1658  nulls[i] = false;
1659  }
1660  }
1661 
1662  /* And form an array */
1663  dims[0] = matchctx->npatterns;
1664  lbs[0] = 1;
1665  /* XXX: this hardcodes assumptions about the text type */
1666  return construct_md_array(elems, nulls, 1, dims, lbs,
1667  TEXTOID, -1, false, TYPALIGN_INT);
1668 }
ArrayType * construct_md_array(Datum *elems, bool *nulls, int ndims, int *dims, int *lbs, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3475
#define Assert(condition)
Definition: c.h:858
#define DirectFunctionCall3(func, arg1, arg2, arg3)
Definition: fmgr.h:646
int i
Definition: isn.c:73
int pg_wchar2mb_with_len(const pg_wchar *from, char *to, int len)
Definition: mbutils.c:1008
const void size_t len
static char * buf
Definition: pg_test_fsync.c:73
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
uintptr_t Datum
Definition: postgres.h:64
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:212
Datum * elems
Definition: regexp.c:62
text * orig_str
Definition: regexp.c:54
char * conv_buf
Definition: regexp.c:65
int * match_locs
Definition: regexp.c:59
pg_wchar * wide_str
Definition: regexp.c:64
bool * nulls
Definition: regexp.c:63
Datum text_substr(PG_FUNCTION_ARGS)
Definition: varlena.c:852
text * cstring_to_text_with_len(const char *s, int len)
Definition: varlena.c:196

References Assert, buf, construct_md_array(), regexp_matches_ctx::conv_buf, cstring_to_text_with_len(), DirectFunctionCall3, regexp_matches_ctx::elems, i, Int32GetDatum(), len, regexp_matches_ctx::match_locs, regexp_matches_ctx::next_match, regexp_matches_ctx::npatterns, regexp_matches_ctx::nulls, regexp_matches_ctx::orig_str, pg_wchar2mb_with_len(), PointerGetDatum(), text_substr(), and regexp_matches_ctx::wide_str.

Referenced by regexp_match(), and regexp_matches().

◆ build_regexp_split_result()

static Datum build_regexp_split_result ( regexp_matches_ctx splitctx)
static

Definition at line 1791 of file regexp.c.

1792 {
1793  char *buf = splitctx->conv_buf;
1794  int startpos;
1795  int endpos;
1796 
1797  if (splitctx->next_match > 0)
1798  startpos = splitctx->match_locs[splitctx->next_match * 2 - 1];
1799  else
1800  startpos = 0;
1801  if (startpos < 0)
1802  elog(ERROR, "invalid match ending position");
1803 
1804  endpos = splitctx->match_locs[splitctx->next_match * 2];
1805  if (endpos < startpos)
1806  elog(ERROR, "invalid match starting position");
1807 
1808  if (buf)
1809  {
1810  int len;
1811 
1812  len = pg_wchar2mb_with_len(splitctx->wide_str + startpos,
1813  buf,
1814  endpos - startpos);
1815  Assert(len < splitctx->conv_bufsiz);
1817  }
1818  else
1819  {
1821  PointerGetDatum(splitctx->orig_str),
1822  Int32GetDatum(startpos + 1),
1824  }
1825 }
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
static XLogRecPtr endpos
Definition: pg_receivewal.c:56
static XLogRecPtr startpos

References Assert, buf, regexp_matches_ctx::conv_buf, cstring_to_text_with_len(), DirectFunctionCall3, elog, endpos, ERROR, Int32GetDatum(), len, regexp_matches_ctx::match_locs, regexp_matches_ctx::next_match, regexp_matches_ctx::orig_str, pg_wchar2mb_with_len(), PointerGetDatum(), startpos, text_substr(), and regexp_matches_ctx::wide_str.

Referenced by regexp_split_to_array(), and regexp_split_to_table().

◆ nameicregexeq()

Datum nameicregexeq ( PG_FUNCTION_ARGS  )

Definition at line 522 of file regexp.c.

523 {
524  Name n = PG_GETARG_NAME(0);
525  text *p = PG_GETARG_TEXT_PP(1);
526 
528  NameStr(*n),
529  strlen(NameStr(*n)),
532  0, NULL));
533 }
#define NameStr(name)
Definition: c.h:746
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
#define PG_GETARG_NAME(n)
Definition: fmgr.h:278
#define PG_GET_COLLATION()
Definition: fmgr.h:198
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:359
#define REG_ICASE
Definition: regex.h:106
#define REG_ADVANCED
Definition: regex.h:103
bool RE_compile_and_execute(text *text_re, char *dat, int dat_len, int cflags, Oid collation, int nmatch, regmatch_t *pmatch)
Definition: regexp.c:358
Definition: c.h:741
Definition: c.h:687

References NameStr, PG_GET_COLLATION, PG_GETARG_NAME, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, RE_compile_and_execute(), REG_ADVANCED, and REG_ICASE.

◆ nameicregexne()

Datum nameicregexne ( PG_FUNCTION_ARGS  )

Definition at line 536 of file regexp.c.

537 {
538  Name n = PG_GETARG_NAME(0);
539  text *p = PG_GETARG_TEXT_PP(1);
540 
542  NameStr(*n),
543  strlen(NameStr(*n)),
546  0, NULL));
547 }

References NameStr, PG_GET_COLLATION, PG_GETARG_NAME, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, RE_compile_and_execute(), REG_ADVANCED, and REG_ICASE.

◆ nameregexeq()

Datum nameregexeq ( PG_FUNCTION_ARGS  )

Definition at line 459 of file regexp.c.

460 {
461  Name n = PG_GETARG_NAME(0);
462  text *p = PG_GETARG_TEXT_PP(1);
463 
465  NameStr(*n),
466  strlen(NameStr(*n)),
467  REG_ADVANCED,
469  0, NULL));
470 }

References NameStr, PG_GET_COLLATION, PG_GETARG_NAME, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, RE_compile_and_execute(), and REG_ADVANCED.

◆ nameregexne()

Datum nameregexne ( PG_FUNCTION_ARGS  )

Definition at line 473 of file regexp.c.

474 {
475  Name n = PG_GETARG_NAME(0);
476  text *p = PG_GETARG_TEXT_PP(1);
477 
479  NameStr(*n),
480  strlen(NameStr(*n)),
481  REG_ADVANCED,
483  0, NULL));
484 }

References NameStr, PG_GET_COLLATION, PG_GETARG_NAME, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, RE_compile_and_execute(), and REG_ADVANCED.

◆ parse_re_flags()

static void parse_re_flags ( pg_re_flags flags,
text opts 
)
static

Definition at line 385 of file regexp.c.

386 {
387  /* regex flavor is always folded into the compile flags */
388  flags->cflags = REG_ADVANCED;
389  flags->glob = false;
390 
391  if (opts)
392  {
393  char *opt_p = VARDATA_ANY(opts);
394  int opt_len = VARSIZE_ANY_EXHDR(opts);
395  int i;
396 
397  for (i = 0; i < opt_len; i++)
398  {
399  switch (opt_p[i])
400  {
401  case 'g':
402  flags->glob = true;
403  break;
404  case 'b': /* BREs (but why???) */
405  flags->cflags &= ~(REG_ADVANCED | REG_EXTENDED | REG_QUOTE);
406  break;
407  case 'c': /* case sensitive */
408  flags->cflags &= ~REG_ICASE;
409  break;
410  case 'e': /* plain EREs */
411  flags->cflags |= REG_EXTENDED;
412  flags->cflags &= ~(REG_ADVANCED | REG_QUOTE);
413  break;
414  case 'i': /* case insensitive */
415  flags->cflags |= REG_ICASE;
416  break;
417  case 'm': /* Perloid synonym for n */
418  case 'n': /* \n affects ^ $ . [^ */
419  flags->cflags |= REG_NEWLINE;
420  break;
421  case 'p': /* ~Perl, \n affects . [^ */
422  flags->cflags |= REG_NLSTOP;
423  flags->cflags &= ~REG_NLANCH;
424  break;
425  case 'q': /* literal string */
426  flags->cflags |= REG_QUOTE;
427  flags->cflags &= ~(REG_ADVANCED | REG_EXTENDED);
428  break;
429  case 's': /* single line, \n ordinary */
430  flags->cflags &= ~REG_NEWLINE;
431  break;
432  case 't': /* tight syntax */
433  flags->cflags &= ~REG_EXPANDED;
434  break;
435  case 'w': /* weird, \n affects ^ $ only */
436  flags->cflags &= ~REG_NLSTOP;
437  flags->cflags |= REG_NLANCH;
438  break;
439  case 'x': /* expanded syntax */
440  flags->cflags |= REG_EXPANDED;
441  break;
442  default:
443  ereport(ERROR,
444  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
445  errmsg("invalid regular expression option: \"%.*s\"",
446  pg_mblen(opt_p + i), opt_p + i)));
447  break;
448  }
449  }
450  }
451 }
int errcode(int sqlerrcode)
Definition: elog.c:857
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ereport(elevel,...)
Definition: elog.h:149
int pg_mblen(const char *mbstr)
Definition: mbutils.c:1023
static AmcheckOptions opts
Definition: pg_amcheck.c:111
#define REG_EXPANDED
Definition: regex.h:108
#define REG_NLANCH
Definition: regex.h:110
#define REG_EXTENDED
Definition: regex.h:101
#define REG_NLSTOP
Definition: regex.h:109
#define REG_NEWLINE
Definition: regex.h:111
#define REG_QUOTE
Definition: regex.h:104
bool glob
Definition: regexp.c:48
int cflags
Definition: regexp.c:47
#define VARDATA_ANY(PTR)
Definition: varatt.h:324
#define VARSIZE_ANY_EXHDR(PTR)
Definition: varatt.h:317

References pg_re_flags::cflags, ereport, errcode(), errmsg(), ERROR, pg_re_flags::glob, i, opts, pg_mblen(), REG_ADVANCED, REG_EXPANDED, REG_EXTENDED, REG_ICASE, REG_NEWLINE, REG_NLANCH, REG_NLSTOP, REG_QUOTE, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

Referenced by regexp_count(), regexp_instr(), regexp_like(), regexp_match(), regexp_matches(), regexp_split_to_array(), regexp_split_to_table(), regexp_substr(), textregexreplace(), and textregexreplace_extended().

◆ RE_compile_and_cache()

regex_t* RE_compile_and_cache ( text text_re,
int  cflags,
Oid  collation 
)

Definition at line 141 of file regexp.c.

142 {
143  int text_re_len = VARSIZE_ANY_EXHDR(text_re);
144  char *text_re_val = VARDATA_ANY(text_re);
145  pg_wchar *pattern;
146  int pattern_len;
147  int i;
148  int regcomp_result;
149  cached_re_str re_temp;
150  char errMsg[100];
151  MemoryContext oldcontext;
152 
153  /*
154  * Look for a match among previously compiled REs. Since the data
155  * structure is self-organizing with most-used entries at the front, our
156  * search strategy can just be to scan from the front.
157  */
158  for (i = 0; i < num_res; i++)
159  {
160  if (re_array[i].cre_pat_len == text_re_len &&
161  re_array[i].cre_flags == cflags &&
162  re_array[i].cre_collation == collation &&
163  memcmp(re_array[i].cre_pat, text_re_val, text_re_len) == 0)
164  {
165  /*
166  * Found a match; move it to front if not there already.
167  */
168  if (i > 0)
169  {
170  re_temp = re_array[i];
171  memmove(&re_array[1], &re_array[0], i * sizeof(cached_re_str));
172  re_array[0] = re_temp;
173  }
174 
175  return &re_array[0].cre_re;
176  }
177  }
178 
179  /* Set up the cache memory on first go through. */
180  if (unlikely(RegexpCacheMemoryContext == NULL))
183  "RegexpCacheMemoryContext",
185 
186  /*
187  * Couldn't find it, so try to compile the new RE. To avoid leaking
188  * resources on failure, we build into the re_temp local.
189  */
190 
191  /* Convert pattern string to wide characters */
192  pattern = (pg_wchar *) palloc((text_re_len + 1) * sizeof(pg_wchar));
193  pattern_len = pg_mb2wchar_with_len(text_re_val,
194  pattern,
195  text_re_len);
196 
197  /*
198  * Make a memory context for this compiled regexp. This is initially a
199  * child of the current memory context, so it will be cleaned up
200  * automatically if compilation is interrupted and throws an ERROR. We'll
201  * re-parent it under the longer lived cache context if we make it to the
202  * bottom of this function.
203  */
205  "RegexpMemoryContext",
207  oldcontext = MemoryContextSwitchTo(re_temp.cre_context);
208 
209  regcomp_result = pg_regcomp(&re_temp.cre_re,
210  pattern,
211  pattern_len,
212  cflags,
213  collation);
214 
215  pfree(pattern);
216 
217  if (regcomp_result != REG_OKAY)
218  {
219  /* re didn't compile (no need for pg_regfree, if so) */
220  pg_regerror(regcomp_result, &re_temp.cre_re, errMsg, sizeof(errMsg));
221  ereport(ERROR,
222  (errcode(ERRCODE_INVALID_REGULAR_EXPRESSION),
223  errmsg("invalid regular expression: %s", errMsg)));
224  }
225 
226  /* Copy the pattern into the per-regexp memory context. */
227  re_temp.cre_pat = palloc(text_re_len + 1);
228  memcpy(re_temp.cre_pat, text_re_val, text_re_len);
229 
230  /*
231  * NUL-terminate it only for the benefit of the identifier used for the
232  * memory context, visible in the pg_backend_memory_contexts view.
233  */
234  re_temp.cre_pat[text_re_len] = 0;
236 
237  re_temp.cre_pat_len = text_re_len;
238  re_temp.cre_flags = cflags;
239  re_temp.cre_collation = collation;
240 
241  /*
242  * Okay, we have a valid new item in re_temp; insert it into the storage
243  * array. Discard last entry if needed.
244  */
245  if (num_res >= MAX_CACHED_RES)
246  {
247  --num_res;
249  /* Delete the memory context holding the regexp and pattern. */
250  MemoryContextDelete(re_array[num_res].cre_context);
251  }
252 
253  /* Re-parent the memory context to our long-lived cache context. */
255 
256  if (num_res > 0)
257  memmove(&re_array[1], &re_array[0], num_res * sizeof(cached_re_str));
258 
259  re_array[0] = re_temp;
260  num_res++;
261 
262  MemoryContextSwitchTo(oldcontext);
263 
264  return &re_array[0].cre_re;
265 }
#define unlikely(x)
Definition: c.h:311
unsigned int pg_wchar
Definition: mbprint.c:31
int pg_mb2wchar_with_len(const char *from, pg_wchar *to, int len)
Definition: mbutils.c:986
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:637
void pfree(void *pointer)
Definition: mcxt.c:1520
MemoryContext TopMemoryContext
Definition: mcxt.c:149
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
void * palloc(Size size)
Definition: mcxt.c:1316
void MemoryContextSetIdentifier(MemoryContext context, const char *id)
Definition: mcxt.c:612
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:170
MemoryContextSwitchTo(old_ctx)
int pg_regcomp(regex_t *re, const chr *string, size_t len, int flags, Oid collation)
Definition: regcomp.c:370
size_t pg_regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
Definition: regerror.c:60
#define REG_OKAY
Definition: regex.h:137
static MemoryContext RegexpCacheMemoryContext
Definition: regexp.c:99
#define MAX_CACHED_RES
Definition: regexp.c:95
static int num_res
Definition: regexp.c:112
static cached_re_str re_array[MAX_CACHED_RES]
Definition: regexp.c:113
char * cre_pat
Definition: regexp.c:105
int cre_pat_len
Definition: regexp.c:106
regex_t cre_re
Definition: regexp.c:109
Oid cre_collation
Definition: regexp.c:108
int cre_flags
Definition: regexp.c:107
MemoryContext cre_context
Definition: regexp.c:104

References ALLOCSET_SMALL_SIZES, AllocSetContextCreate, Assert, cached_re_str::cre_collation, cached_re_str::cre_context, cached_re_str::cre_flags, cached_re_str::cre_pat, cached_re_str::cre_pat_len, cached_re_str::cre_re, CurrentMemoryContext, ereport, errcode(), errmsg(), ERROR, i, MAX_CACHED_RES, MemoryContextDelete(), MemoryContextSetIdentifier(), MemoryContextSetParent(), MemoryContextSwitchTo(), num_res, palloc(), pfree(), pg_mb2wchar_with_len(), pg_regcomp(), pg_regerror(), re_array, REG_OKAY, RegexpCacheMemoryContext, TopMemoryContext, unlikely, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

Referenced by RE_compile_and_execute(), regexp_fixed_prefix(), replace_text_regexp(), setup_regexp_matches(), and textregexsubstr().

◆ RE_compile_and_execute()

bool RE_compile_and_execute ( text text_re,
char *  dat,
int  dat_len,
int  cflags,
Oid  collation,
int  nmatch,
regmatch_t pmatch 
)

Definition at line 358 of file regexp.c.

361 {
362  regex_t *re;
363 
364  /* Use REG_NOSUB if caller does not want sub-match details */
365  if (nmatch < 2)
366  cflags |= REG_NOSUB;
367 
368  /* Compile RE */
369  re = RE_compile_and_cache(text_re, cflags, collation);
370 
371  return RE_execute(re, dat, dat_len, nmatch, pmatch);
372 }
#define REG_NOSUB
Definition: regex.h:107
regex_t * RE_compile_and_cache(text *text_re, int cflags, Oid collation)
Definition: regexp.c:141
static bool RE_execute(regex_t *re, char *dat, int dat_len, int nmatch, regmatch_t *pmatch)
Definition: regexp.c:324
Definition: regex.h:56

References RE_compile_and_cache(), RE_execute(), and REG_NOSUB.

Referenced by executeLikeRegex(), nameicregexeq(), nameicregexne(), nameregexeq(), nameregexne(), regexp_like(), texticregexeq(), texticregexne(), textregexeq(), and textregexne().

◆ RE_execute()

static bool RE_execute ( regex_t re,
char *  dat,
int  dat_len,
int  nmatch,
regmatch_t pmatch 
)
static

Definition at line 324 of file regexp.c.

326 {
327  pg_wchar *data;
328  int data_len;
329  bool match;
330 
331  /* Convert data string to wide characters */
332  data = (pg_wchar *) palloc((dat_len + 1) * sizeof(pg_wchar));
333  data_len = pg_mb2wchar_with_len(dat, data, dat_len);
334 
335  /* Perform RE match and return result */
336  match = RE_wchar_execute(re, data, data_len, 0, nmatch, pmatch);
337 
338  pfree(data);
339  return match;
340 }
const void * data
static bool RE_wchar_execute(regex_t *re, pg_wchar *data, int data_len, int start_search, int nmatch, regmatch_t *pmatch)
Definition: regexp.c:282

References data, palloc(), pfree(), pg_mb2wchar_with_len(), and RE_wchar_execute().

Referenced by RE_compile_and_execute(), and textregexsubstr().

◆ RE_wchar_execute()

static bool RE_wchar_execute ( regex_t re,
pg_wchar data,
int  data_len,
int  start_search,
int  nmatch,
regmatch_t pmatch 
)
static

Definition at line 282 of file regexp.c.

284 {
285  int regexec_result;
286  char errMsg[100];
287 
288  /* Perform RE match and return result */
289  regexec_result = pg_regexec(re,
290  data,
291  data_len,
292  start_search,
293  NULL, /* no details */
294  nmatch,
295  pmatch,
296  0);
297 
298  if (regexec_result != REG_OKAY && regexec_result != REG_NOMATCH)
299  {
300  /* re failed??? */
301  pg_regerror(regexec_result, re, errMsg, sizeof(errMsg));
302  ereport(ERROR,
303  (errcode(ERRCODE_INVALID_REGULAR_EXPRESSION),
304  errmsg("regular expression failed: %s", errMsg)));
305  }
306 
307  return (regexec_result == REG_OKAY);
308 }
#define REG_NOMATCH
Definition: regex.h:138
int pg_regexec(regex_t *re, const chr *string, size_t len, size_t search_start, rm_detail_t *details, size_t nmatch, regmatch_t pmatch[], int flags)
Definition: regexec.c:185

References data, ereport, errcode(), errmsg(), ERROR, pg_regerror(), pg_regexec(), REG_NOMATCH, and REG_OKAY.

Referenced by RE_execute(), and setup_regexp_matches().

◆ regexp_count()

Datum regexp_count ( PG_FUNCTION_ARGS  )

Definition at line 1066 of file regexp.c.

1067 {
1068  text *str = PG_GETARG_TEXT_PP(0);
1069  text *pattern = PG_GETARG_TEXT_PP(1);
1070  int start = 1;
1071  text *flags = PG_GETARG_TEXT_PP_IF_EXISTS(3);
1072  pg_re_flags re_flags;
1073  regexp_matches_ctx *matchctx;
1074 
1075  /* Collect optional parameters */
1076  if (PG_NARGS() > 2)
1077  {
1078  start = PG_GETARG_INT32(2);
1079  if (start <= 0)
1080  ereport(ERROR,
1081  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1082  errmsg("invalid value for parameter \"%s\": %d",
1083  "start", start)));
1084  }
1085 
1086  /* Determine options */
1087  parse_re_flags(&re_flags, flags);
1088  /* User mustn't specify 'g' */
1089  if (re_flags.glob)
1090  ereport(ERROR,
1091  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1092  /* translator: %s is a SQL function name */
1093  errmsg("%s does not support the \"global\" option",
1094  "regexp_count()")));
1095  /* But we find all the matches anyway */
1096  re_flags.glob = true;
1097 
1098  /* Do the matching */
1099  matchctx = setup_regexp_matches(str, pattern, &re_flags, start - 1,
1100  PG_GET_COLLATION(),
1101  false, /* can ignore subexprs */
1102  false, false);
1103 
1104  PG_RETURN_INT32(matchctx->nmatches);
1105 }
#define PG_NARGS()
Definition: fmgr.h:203
#define PG_RETURN_INT32(x)
Definition: fmgr.h:354
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269
return str start
const char * str
static regexp_matches_ctx * setup_regexp_matches(text *orig_str, text *pattern, pg_re_flags *re_flags, int start_search, Oid collation, bool use_subpatterns, bool ignore_degenerate, bool fetching_unmatched)
Definition: regexp.c:1416
#define PG_GETARG_TEXT_PP_IF_EXISTS(_n)
Definition: regexp.c:40
static void parse_re_flags(pg_re_flags *flags, text *opts)
Definition: regexp.c:385

References ereport, errcode(), errmsg(), ERROR, pg_re_flags::glob, regexp_matches_ctx::nmatches, parse_re_flags(), PG_GET_COLLATION, PG_GETARG_INT32, PG_GETARG_TEXT_PP, PG_GETARG_TEXT_PP_IF_EXISTS, PG_NARGS, PG_RETURN_INT32, setup_regexp_matches(), start, and str.

Referenced by regexp_count_no_flags(), and regexp_count_no_start().

◆ regexp_count_no_flags()

Datum regexp_count_no_flags ( PG_FUNCTION_ARGS  )

Definition at line 1116 of file regexp.c.

1117 {
1118  return regexp_count(fcinfo);
1119 }
Datum regexp_count(PG_FUNCTION_ARGS)
Definition: regexp.c:1066

References regexp_count().

◆ regexp_count_no_start()

Datum regexp_count_no_start ( PG_FUNCTION_ARGS  )

Definition at line 1109 of file regexp.c.

1110 {
1111  return regexp_count(fcinfo);
1112 }

References regexp_count().

◆ regexp_fixed_prefix()

char* regexp_fixed_prefix ( text text_re,
bool  case_insensitive,
Oid  collation,
bool exact 
)

Definition at line 1953 of file regexp.c.

1955 {
1956  char *result;
1957  regex_t *re;
1958  int cflags;
1959  int re_result;
1960  pg_wchar *str;
1961  size_t slen;
1962  size_t maxlen;
1963  char errMsg[100];
1964 
1965  *exact = false; /* default result */
1966 
1967  /* Compile RE */
1968  cflags = REG_ADVANCED;
1969  if (case_insensitive)
1970  cflags |= REG_ICASE;
1971 
1972  re = RE_compile_and_cache(text_re, cflags | REG_NOSUB, collation);
1973 
1974  /* Examine it to see if there's a fixed prefix */
1975  re_result = pg_regprefix(re, &str, &slen);
1976 
1977  switch (re_result)
1978  {
1979  case REG_NOMATCH:
1980  return NULL;
1981 
1982  case REG_PREFIX:
1983  /* continue with wchar conversion */
1984  break;
1985 
1986  case REG_EXACT:
1987  *exact = true;
1988  /* continue with wchar conversion */
1989  break;
1990 
1991  default:
1992  /* re failed??? */
1993  pg_regerror(re_result, re, errMsg, sizeof(errMsg));
1994  ereport(ERROR,
1995  (errcode(ERRCODE_INVALID_REGULAR_EXPRESSION),
1996  errmsg("regular expression failed: %s", errMsg)));
1997  break;
1998  }
1999 
2000  /* Convert pg_wchar result back to database encoding */
2001  maxlen = pg_database_encoding_max_length() * slen + 1;
2002  result = (char *) palloc(maxlen);
2003  slen = pg_wchar2mb_with_len(str, result, slen);
2004  Assert(slen < maxlen);
2005 
2006  pfree(str);
2007 
2008  return result;
2009 }
int pg_database_encoding_max_length(void)
Definition: mbutils.c:1546
#define REG_EXACT
Definition: regex.h:162
#define REG_PREFIX
Definition: regex.h:161
int pg_regprefix(regex_t *re, chr **string, size_t *slength)
Definition: regprefix.c:46

References Assert, ereport, errcode(), errmsg(), ERROR, palloc(), pfree(), pg_database_encoding_max_length(), pg_regerror(), pg_regprefix(), pg_wchar2mb_with_len(), RE_compile_and_cache(), REG_ADVANCED, REG_EXACT, REG_ICASE, REG_NOMATCH, REG_NOSUB, REG_PREFIX, and str.

Referenced by regex_fixed_prefix().

◆ regexp_instr()

Datum regexp_instr ( PG_FUNCTION_ARGS  )

Definition at line 1126 of file regexp.c.

1127 {
1128  text *str = PG_GETARG_TEXT_PP(0);
1129  text *pattern = PG_GETARG_TEXT_PP(1);
1130  int start = 1;
1131  int n = 1;
1132  int endoption = 0;
1133  text *flags = PG_GETARG_TEXT_PP_IF_EXISTS(5);
1134  int subexpr = 0;
1135  int pos;
1136  pg_re_flags re_flags;
1137  regexp_matches_ctx *matchctx;
1138 
1139  /* Collect optional parameters */
1140  if (PG_NARGS() > 2)
1141  {
1142  start = PG_GETARG_INT32(2);
1143  if (start <= 0)
1144  ereport(ERROR,
1145  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1146  errmsg("invalid value for parameter \"%s\": %d",
1147  "start", start)));
1148  }
1149  if (PG_NARGS() > 3)
1150  {
1151  n = PG_GETARG_INT32(3);
1152  if (n <= 0)
1153  ereport(ERROR,
1154  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1155  errmsg("invalid value for parameter \"%s\": %d",
1156  "n", n)));
1157  }
1158  if (PG_NARGS() > 4)
1159  {
1160  endoption = PG_GETARG_INT32(4);
1161  if (endoption != 0 && endoption != 1)
1162  ereport(ERROR,
1163  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1164  errmsg("invalid value for parameter \"%s\": %d",
1165  "endoption", endoption)));
1166  }
1167  if (PG_NARGS() > 6)
1168  {
1169  subexpr = PG_GETARG_INT32(6);
1170  if (subexpr < 0)
1171  ereport(ERROR,
1172  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1173  errmsg("invalid value for parameter \"%s\": %d",
1174  "subexpr", subexpr)));
1175  }
1176 
1177  /* Determine options */
1178  parse_re_flags(&re_flags, flags);
1179  /* User mustn't specify 'g' */
1180  if (re_flags.glob)
1181  ereport(ERROR,
1182  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1183  /* translator: %s is a SQL function name */
1184  errmsg("%s does not support the \"global\" option",
1185  "regexp_instr()")));
1186  /* But we find all the matches anyway */
1187  re_flags.glob = true;
1188 
1189  /* Do the matching */
1190  matchctx = setup_regexp_matches(str, pattern, &re_flags, start - 1,
1191  PG_GET_COLLATION(),
1192  (subexpr > 0), /* need submatches? */
1193  false, false);
1194 
1195  /* When n exceeds matches return 0 (includes case of no matches) */
1196  if (n > matchctx->nmatches)
1197  PG_RETURN_INT32(0);
1198 
1199  /* When subexpr exceeds number of subexpressions return 0 */
1200  if (subexpr > matchctx->npatterns)
1201  PG_RETURN_INT32(0);
1202 
1203  /* Select the appropriate match position to return */
1204  pos = (n - 1) * matchctx->npatterns;
1205  if (subexpr > 0)
1206  pos += subexpr - 1;
1207  pos *= 2;
1208  if (endoption == 1)
1209  pos += 1;
1210 
1211  if (matchctx->match_locs[pos] >= 0)
1212  PG_RETURN_INT32(matchctx->match_locs[pos] + 1);
1213  else
1214  PG_RETURN_INT32(0); /* position not identifiable */
1215 }
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77

References ereport, errcode(), errmsg(), ERROR, pg_re_flags::glob, if(), regexp_matches_ctx::match_locs, regexp_matches_ctx::nmatches, regexp_matches_ctx::npatterns, parse_re_flags(), PG_GET_COLLATION, PG_GETARG_INT32, PG_GETARG_TEXT_PP, PG_GETARG_TEXT_PP_IF_EXISTS, PG_NARGS, PG_RETURN_INT32, setup_regexp_matches(), start, and str.

Referenced by regexp_instr_no_endoption(), regexp_instr_no_flags(), regexp_instr_no_n(), regexp_instr_no_start(), and regexp_instr_no_subexpr().

◆ regexp_instr_no_endoption()

Datum regexp_instr_no_endoption ( PG_FUNCTION_ARGS  )

Definition at line 1233 of file regexp.c.

1234 {
1235  return regexp_instr(fcinfo);
1236 }
Datum regexp_instr(PG_FUNCTION_ARGS)
Definition: regexp.c:1126

References regexp_instr().

◆ regexp_instr_no_flags()

Datum regexp_instr_no_flags ( PG_FUNCTION_ARGS  )

Definition at line 1240 of file regexp.c.

1241 {
1242  return regexp_instr(fcinfo);
1243 }

References regexp_instr().

◆ regexp_instr_no_n()

Datum regexp_instr_no_n ( PG_FUNCTION_ARGS  )

Definition at line 1226 of file regexp.c.

1227 {
1228  return regexp_instr(fcinfo);
1229 }

References regexp_instr().

◆ regexp_instr_no_start()

Datum regexp_instr_no_start ( PG_FUNCTION_ARGS  )

Definition at line 1219 of file regexp.c.

1220 {
1221  return regexp_instr(fcinfo);
1222 }

References regexp_instr().

◆ regexp_instr_no_subexpr()

Datum regexp_instr_no_subexpr ( PG_FUNCTION_ARGS  )

Definition at line 1247 of file regexp.c.

1248 {
1249  return regexp_instr(fcinfo);
1250 }

References regexp_instr().

◆ regexp_like()

Datum regexp_like ( PG_FUNCTION_ARGS  )

Definition at line 1257 of file regexp.c.

1258 {
1259  text *str = PG_GETARG_TEXT_PP(0);
1260  text *pattern = PG_GETARG_TEXT_PP(1);
1261  text *flags = PG_GETARG_TEXT_PP_IF_EXISTS(2);
1262  pg_re_flags re_flags;
1263 
1264  /* Determine options */
1265  parse_re_flags(&re_flags, flags);
1266  /* User mustn't specify 'g' */
1267  if (re_flags.glob)
1268  ereport(ERROR,
1269  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1270  /* translator: %s is a SQL function name */
1271  errmsg("%s does not support the \"global\" option",
1272  "regexp_like()")));
1273 
1274  /* Otherwise it's like textregexeq/texticregexeq */
1276  VARDATA_ANY(str),
1278  re_flags.cflags,
1279  PG_GET_COLLATION(),
1280  0, NULL));
1281 }

References pg_re_flags::cflags, ereport, errcode(), errmsg(), ERROR, pg_re_flags::glob, parse_re_flags(), PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_GETARG_TEXT_PP_IF_EXISTS, PG_RETURN_BOOL, RE_compile_and_execute(), str, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

Referenced by regexp_like_no_flags().

◆ regexp_like_no_flags()

Datum regexp_like_no_flags ( PG_FUNCTION_ARGS  )

Definition at line 1285 of file regexp.c.

1286 {
1287  return regexp_like(fcinfo);
1288 }
Datum regexp_like(PG_FUNCTION_ARGS)
Definition: regexp.c:1257

References regexp_like().

◆ regexp_match()

Datum regexp_match ( PG_FUNCTION_ARGS  )

Definition at line 1295 of file regexp.c.

1296 {
1297  text *orig_str = PG_GETARG_TEXT_PP(0);
1298  text *pattern = PG_GETARG_TEXT_PP(1);
1299  text *flags = PG_GETARG_TEXT_PP_IF_EXISTS(2);
1300  pg_re_flags re_flags;
1301  regexp_matches_ctx *matchctx;
1302 
1303  /* Determine options */
1304  parse_re_flags(&re_flags, flags);
1305  /* User mustn't specify 'g' */
1306  if (re_flags.glob)
1307  ereport(ERROR,
1308  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1309  /* translator: %s is a SQL function name */
1310  errmsg("%s does not support the \"global\" option",
1311  "regexp_match()"),
1312  errhint("Use the regexp_matches function instead.")));
1313 
1314  matchctx = setup_regexp_matches(orig_str, pattern, &re_flags, 0,
1315  PG_GET_COLLATION(), true, false, false);
1316 
1317  if (matchctx->nmatches == 0)
1318  PG_RETURN_NULL();
1319 
1320  Assert(matchctx->nmatches == 1);
1321 
1322  /* Create workspace that build_regexp_match_result needs */
1323  matchctx->elems = (Datum *) palloc(sizeof(Datum) * matchctx->npatterns);
1324  matchctx->nulls = (bool *) palloc(sizeof(bool) * matchctx->npatterns);
1325 
1327 }
int errhint(const char *fmt,...)
Definition: elog.c:1317
#define PG_RETURN_NULL()
Definition: fmgr.h:345
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:353
static ArrayType * build_regexp_match_result(regexp_matches_ctx *matchctx)
Definition: regexp.c:1620

References Assert, build_regexp_match_result(), regexp_matches_ctx::elems, ereport, errcode(), errhint(), errmsg(), ERROR, pg_re_flags::glob, regexp_matches_ctx::nmatches, regexp_matches_ctx::npatterns, regexp_matches_ctx::nulls, palloc(), parse_re_flags(), PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_GETARG_TEXT_PP_IF_EXISTS, PG_RETURN_DATUM, PG_RETURN_NULL, PointerGetDatum(), and setup_regexp_matches().

Referenced by regexp_match_no_flags().

◆ regexp_match_no_flags()

Datum regexp_match_no_flags ( PG_FUNCTION_ARGS  )

Definition at line 1331 of file regexp.c.

1332 {
1333  return regexp_match(fcinfo);
1334 }
Datum regexp_match(PG_FUNCTION_ARGS)
Definition: regexp.c:1295

References regexp_match().

◆ regexp_matches()

Datum regexp_matches ( PG_FUNCTION_ARGS  )

Definition at line 1341 of file regexp.c.

1342 {
1343  FuncCallContext *funcctx;
1344  regexp_matches_ctx *matchctx;
1345 
1346  if (SRF_IS_FIRSTCALL())
1347  {
1348  text *pattern = PG_GETARG_TEXT_PP(1);
1349  text *flags = PG_GETARG_TEXT_PP_IF_EXISTS(2);
1350  pg_re_flags re_flags;
1351  MemoryContext oldcontext;
1352 
1353  funcctx = SRF_FIRSTCALL_INIT();
1354  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1355 
1356  /* Determine options */
1357  parse_re_flags(&re_flags, flags);
1358 
1359  /* be sure to copy the input string into the multi-call ctx */
1360  matchctx = setup_regexp_matches(PG_GETARG_TEXT_P_COPY(0), pattern,
1361  &re_flags, 0,
1362  PG_GET_COLLATION(),
1363  true, false, false);
1364 
1365  /* Pre-create workspace that build_regexp_match_result needs */
1366  matchctx->elems = (Datum *) palloc(sizeof(Datum) * matchctx->npatterns);
1367  matchctx->nulls = (bool *) palloc(sizeof(bool) * matchctx->npatterns);
1368 
1369  MemoryContextSwitchTo(oldcontext);
1370  funcctx->user_fctx = (void *) matchctx;
1371  }
1372 
1373  funcctx = SRF_PERCALL_SETUP();
1374  matchctx = (regexp_matches_ctx *) funcctx->user_fctx;
1375 
1376  if (matchctx->next_match < matchctx->nmatches)
1377  {
1378  ArrayType *result_ary;
1379 
1380  result_ary = build_regexp_match_result(matchctx);
1381  matchctx->next_match++;
1382  SRF_RETURN_NEXT(funcctx, PointerGetDatum(result_ary));
1383  }
1384 
1385  SRF_RETURN_DONE(funcctx);
1386 }
#define PG_GETARG_TEXT_P_COPY(n)
Definition: fmgr.h:315
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:304
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:308
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:310
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:306
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:328
void * user_fctx
Definition: funcapi.h:82
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:101

References build_regexp_match_result(), regexp_matches_ctx::elems, if(), MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, regexp_matches_ctx::next_match, regexp_matches_ctx::nmatches, regexp_matches_ctx::npatterns, regexp_matches_ctx::nulls, palloc(), parse_re_flags(), 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().

◆ regexp_matches_no_flags()

Datum regexp_matches_no_flags ( PG_FUNCTION_ARGS  )

Definition at line 1390 of file regexp.c.

1391 {
1392  return regexp_matches(fcinfo);
1393 }
Datum regexp_matches(PG_FUNCTION_ARGS)
Definition: regexp.c:1341

References regexp_matches().

◆ regexp_split_to_array()

Datum regexp_split_to_array ( PG_FUNCTION_ARGS  )

Definition at line 1740 of file regexp.c.

1741 {
1742  ArrayBuildState *astate = NULL;
1743  pg_re_flags re_flags;
1744  regexp_matches_ctx *splitctx;
1745 
1746  /* Determine options */
1748  /* User mustn't specify 'g' */
1749  if (re_flags.glob)
1750  ereport(ERROR,
1751  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1752  /* translator: %s is a SQL function name */
1753  errmsg("%s does not support the \"global\" option",
1754  "regexp_split_to_array()")));
1755  /* But we find all the matches anyway */
1756  re_flags.glob = true;
1757 
1759  PG_GETARG_TEXT_PP(1),
1760  &re_flags, 0,
1761  PG_GET_COLLATION(),
1762  false, true, true);
1763 
1764  while (splitctx->next_match <= splitctx->nmatches)
1765  {
1766  astate = accumArrayResult(astate,
1767  build_regexp_split_result(splitctx),
1768  false,
1769  TEXTOID,
1771  splitctx->next_match++;
1772  }
1773 
1775 }
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5331
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5401
static Datum build_regexp_split_result(regexp_matches_ctx *splitctx)
Definition: regexp.c:1791

References accumArrayResult(), build_regexp_split_result(), CurrentMemoryContext, ereport, errcode(), errmsg(), ERROR, pg_re_flags::glob, makeArrayResult(), regexp_matches_ctx::next_match, regexp_matches_ctx::nmatches, parse_re_flags(), PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_GETARG_TEXT_PP_IF_EXISTS, PG_RETURN_DATUM, and setup_regexp_matches().

Referenced by regexp_split_to_array_no_flags().

◆ regexp_split_to_array_no_flags()

Datum regexp_split_to_array_no_flags ( PG_FUNCTION_ARGS  )

Definition at line 1779 of file regexp.c.

1780 {
1781  return regexp_split_to_array(fcinfo);
1782 }
Datum regexp_split_to_array(PG_FUNCTION_ARGS)
Definition: regexp.c:1740

References regexp_split_to_array().

◆ regexp_split_to_table()

Datum regexp_split_to_table ( PG_FUNCTION_ARGS  )

Definition at line 1676 of file regexp.c.

1677 {
1678  FuncCallContext *funcctx;
1679  regexp_matches_ctx *splitctx;
1680 
1681  if (SRF_IS_FIRSTCALL())
1682  {
1683  text *pattern = PG_GETARG_TEXT_PP(1);
1684  text *flags = PG_GETARG_TEXT_PP_IF_EXISTS(2);
1685  pg_re_flags re_flags;
1686  MemoryContext oldcontext;
1687 
1688  funcctx = SRF_FIRSTCALL_INIT();
1689  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1690 
1691  /* Determine options */
1692  parse_re_flags(&re_flags, flags);
1693  /* User mustn't specify 'g' */
1694  if (re_flags.glob)
1695  ereport(ERROR,
1696  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1697  /* translator: %s is a SQL function name */
1698  errmsg("%s does not support the \"global\" option",
1699  "regexp_split_to_table()")));
1700  /* But we find all the matches anyway */
1701  re_flags.glob = true;
1702 
1703  /* be sure to copy the input string into the multi-call ctx */
1704  splitctx = setup_regexp_matches(PG_GETARG_TEXT_P_COPY(0), pattern,
1705  &re_flags, 0,
1706  PG_GET_COLLATION(),
1707  false, true, true);
1708 
1709  MemoryContextSwitchTo(oldcontext);
1710  funcctx->user_fctx = (void *) splitctx;
1711  }
1712 
1713  funcctx = SRF_PERCALL_SETUP();
1714  splitctx = (regexp_matches_ctx *) funcctx->user_fctx;
1715 
1716  if (splitctx->next_match <= splitctx->nmatches)
1717  {
1718  Datum result = build_regexp_split_result(splitctx);
1719 
1720  splitctx->next_match++;
1721  SRF_RETURN_NEXT(funcctx, result);
1722  }
1723 
1724  SRF_RETURN_DONE(funcctx);
1725 }

References build_regexp_split_result(), ereport, errcode(), errmsg(), ERROR, pg_re_flags::glob, if(), MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, regexp_matches_ctx::next_match, regexp_matches_ctx::nmatches, parse_re_flags(), 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().

◆ regexp_split_to_table_no_flags()

Datum regexp_split_to_table_no_flags ( PG_FUNCTION_ARGS  )

Definition at line 1729 of file regexp.c.

1730 {
1731  return regexp_split_to_table(fcinfo);
1732 }
Datum regexp_split_to_table(PG_FUNCTION_ARGS)
Definition: regexp.c:1676

References regexp_split_to_table().

◆ regexp_substr()

Datum regexp_substr ( PG_FUNCTION_ARGS  )

Definition at line 1832 of file regexp.c.

1833 {
1834  text *str = PG_GETARG_TEXT_PP(0);
1835  text *pattern = PG_GETARG_TEXT_PP(1);
1836  int start = 1;
1837  int n = 1;
1838  text *flags = PG_GETARG_TEXT_PP_IF_EXISTS(4);
1839  int subexpr = 0;
1840  int so,
1841  eo,
1842  pos;
1843  pg_re_flags re_flags;
1844  regexp_matches_ctx *matchctx;
1845 
1846  /* Collect optional parameters */
1847  if (PG_NARGS() > 2)
1848  {
1849  start = PG_GETARG_INT32(2);
1850  if (start <= 0)
1851  ereport(ERROR,
1852  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1853  errmsg("invalid value for parameter \"%s\": %d",
1854  "start", start)));
1855  }
1856  if (PG_NARGS() > 3)
1857  {
1858  n = PG_GETARG_INT32(3);
1859  if (n <= 0)
1860  ereport(ERROR,
1861  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1862  errmsg("invalid value for parameter \"%s\": %d",
1863  "n", n)));
1864  }
1865  if (PG_NARGS() > 5)
1866  {
1867  subexpr = PG_GETARG_INT32(5);
1868  if (subexpr < 0)
1869  ereport(ERROR,
1870  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1871  errmsg("invalid value for parameter \"%s\": %d",
1872  "subexpr", subexpr)));
1873  }
1874 
1875  /* Determine options */
1876  parse_re_flags(&re_flags, flags);
1877  /* User mustn't specify 'g' */
1878  if (re_flags.glob)
1879  ereport(ERROR,
1880  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1881  /* translator: %s is a SQL function name */
1882  errmsg("%s does not support the \"global\" option",
1883  "regexp_substr()")));
1884  /* But we find all the matches anyway */
1885  re_flags.glob = true;
1886 
1887  /* Do the matching */
1888  matchctx = setup_regexp_matches(str, pattern, &re_flags, start - 1,
1889  PG_GET_COLLATION(),
1890  (subexpr > 0), /* need submatches? */
1891  false, false);
1892 
1893  /* When n exceeds matches return NULL (includes case of no matches) */
1894  if (n > matchctx->nmatches)
1895  PG_RETURN_NULL();
1896 
1897  /* When subexpr exceeds number of subexpressions return NULL */
1898  if (subexpr > matchctx->npatterns)
1899  PG_RETURN_NULL();
1900 
1901  /* Select the appropriate match position to return */
1902  pos = (n - 1) * matchctx->npatterns;
1903  if (subexpr > 0)
1904  pos += subexpr - 1;
1905  pos *= 2;
1906  so = matchctx->match_locs[pos];
1907  eo = matchctx->match_locs[pos + 1];
1908 
1909  if (so < 0 || eo < 0)
1910  PG_RETURN_NULL(); /* unidentifiable location */
1911 
1913  PointerGetDatum(matchctx->orig_str),
1914  Int32GetDatum(so + 1),
1915  Int32GetDatum(eo - so)));
1916 }

References DirectFunctionCall3, ereport, errcode(), errmsg(), ERROR, pg_re_flags::glob, if(), Int32GetDatum(), regexp_matches_ctx::match_locs, regexp_matches_ctx::nmatches, regexp_matches_ctx::npatterns, regexp_matches_ctx::orig_str, parse_re_flags(), PG_GET_COLLATION, PG_GETARG_INT32, PG_GETARG_TEXT_PP, PG_GETARG_TEXT_PP_IF_EXISTS, PG_NARGS, PG_RETURN_DATUM, PG_RETURN_NULL, PointerGetDatum(), setup_regexp_matches(), start, str, and text_substr().

Referenced by regexp_substr_no_flags(), regexp_substr_no_n(), regexp_substr_no_start(), and regexp_substr_no_subexpr().

◆ regexp_substr_no_flags()

Datum regexp_substr_no_flags ( PG_FUNCTION_ARGS  )

Definition at line 1934 of file regexp.c.

1935 {
1936  return regexp_substr(fcinfo);
1937 }
Datum regexp_substr(PG_FUNCTION_ARGS)
Definition: regexp.c:1832

References regexp_substr().

◆ regexp_substr_no_n()

Datum regexp_substr_no_n ( PG_FUNCTION_ARGS  )

Definition at line 1927 of file regexp.c.

1928 {
1929  return regexp_substr(fcinfo);
1930 }

References regexp_substr().

◆ regexp_substr_no_start()

Datum regexp_substr_no_start ( PG_FUNCTION_ARGS  )

Definition at line 1920 of file regexp.c.

1921 {
1922  return regexp_substr(fcinfo);
1923 }

References regexp_substr().

◆ regexp_substr_no_subexpr()

Datum regexp_substr_no_subexpr ( PG_FUNCTION_ARGS  )

Definition at line 1941 of file regexp.c.

1942 {
1943  return regexp_substr(fcinfo);
1944 }

References regexp_substr().

◆ setup_regexp_matches()

static regexp_matches_ctx * setup_regexp_matches ( text orig_str,
text pattern,
pg_re_flags re_flags,
int  start_search,
Oid  collation,
bool  use_subpatterns,
bool  ignore_degenerate,
bool  fetching_unmatched 
)
static

Definition at line 1416 of file regexp.c.

1422 {
1423  regexp_matches_ctx *matchctx = palloc0(sizeof(regexp_matches_ctx));
1424  int eml = pg_database_encoding_max_length();
1425  int orig_len;
1426  pg_wchar *wide_str;
1427  int wide_len;
1428  int cflags;
1429  regex_t *cpattern;
1430  regmatch_t *pmatch;
1431  int pmatch_len;
1432  int array_len;
1433  int array_idx;
1434  int prev_match_end;
1435  int prev_valid_match_end;
1436  int maxlen = 0; /* largest fetch length in characters */
1437 
1438  /* save original string --- we'll extract result substrings from it */
1439  matchctx->orig_str = orig_str;
1440 
1441  /* convert string to pg_wchar form for matching */
1442  orig_len = VARSIZE_ANY_EXHDR(orig_str);
1443  wide_str = (pg_wchar *) palloc(sizeof(pg_wchar) * (orig_len + 1));
1444  wide_len = pg_mb2wchar_with_len(VARDATA_ANY(orig_str), wide_str, orig_len);
1445 
1446  /* set up the compiled pattern */
1447  cflags = re_flags->cflags;
1448  if (!use_subpatterns)
1449  cflags |= REG_NOSUB;
1450  cpattern = RE_compile_and_cache(pattern, cflags, collation);
1451 
1452  /* do we want to remember subpatterns? */
1453  if (use_subpatterns && cpattern->re_nsub > 0)
1454  {
1455  matchctx->npatterns = cpattern->re_nsub;
1456  pmatch_len = cpattern->re_nsub + 1;
1457  }
1458  else
1459  {
1460  use_subpatterns = false;
1461  matchctx->npatterns = 1;
1462  pmatch_len = 1;
1463  }
1464 
1465  /* temporary output space for RE package */
1466  pmatch = palloc(sizeof(regmatch_t) * pmatch_len);
1467 
1468  /*
1469  * the real output space (grown dynamically if needed)
1470  *
1471  * use values 2^n-1, not 2^n, so that we hit the limit at 2^28-1 rather
1472  * than at 2^27
1473  */
1474  array_len = re_flags->glob ? 255 : 31;
1475  matchctx->match_locs = (int *) palloc(sizeof(int) * array_len);
1476  array_idx = 0;
1477 
1478  /* search for the pattern, perhaps repeatedly */
1479  prev_match_end = 0;
1480  prev_valid_match_end = 0;
1481  while (RE_wchar_execute(cpattern, wide_str, wide_len, start_search,
1482  pmatch_len, pmatch))
1483  {
1484  /*
1485  * If requested, ignore degenerate matches, which are zero-length
1486  * matches occurring at the start or end of a string or just after a
1487  * previous match.
1488  */
1489  if (!ignore_degenerate ||
1490  (pmatch[0].rm_so < wide_len &&
1491  pmatch[0].rm_eo > prev_match_end))
1492  {
1493  /* enlarge output space if needed */
1494  while (array_idx + matchctx->npatterns * 2 + 1 > array_len)
1495  {
1496  array_len += array_len + 1; /* 2^n-1 => 2^(n+1)-1 */
1497  if (array_len > MaxAllocSize / sizeof(int))
1498  ereport(ERROR,
1499  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1500  errmsg("too many regular expression matches")));
1501  matchctx->match_locs = (int *) repalloc(matchctx->match_locs,
1502  sizeof(int) * array_len);
1503  }
1504 
1505  /* save this match's locations */
1506  if (use_subpatterns)
1507  {
1508  int i;
1509 
1510  for (i = 1; i <= matchctx->npatterns; i++)
1511  {
1512  int so = pmatch[i].rm_so;
1513  int eo = pmatch[i].rm_eo;
1514 
1515  matchctx->match_locs[array_idx++] = so;
1516  matchctx->match_locs[array_idx++] = eo;
1517  if (so >= 0 && eo >= 0 && (eo - so) > maxlen)
1518  maxlen = (eo - so);
1519  }
1520  }
1521  else
1522  {
1523  int so = pmatch[0].rm_so;
1524  int eo = pmatch[0].rm_eo;
1525 
1526  matchctx->match_locs[array_idx++] = so;
1527  matchctx->match_locs[array_idx++] = eo;
1528  if (so >= 0 && eo >= 0 && (eo - so) > maxlen)
1529  maxlen = (eo - so);
1530  }
1531  matchctx->nmatches++;
1532 
1533  /*
1534  * check length of unmatched portion between end of previous valid
1535  * (nondegenerate, or degenerate but not ignored) match and start
1536  * of current one
1537  */
1538  if (fetching_unmatched &&
1539  pmatch[0].rm_so >= 0 &&
1540  (pmatch[0].rm_so - prev_valid_match_end) > maxlen)
1541  maxlen = (pmatch[0].rm_so - prev_valid_match_end);
1542  prev_valid_match_end = pmatch[0].rm_eo;
1543  }
1544  prev_match_end = pmatch[0].rm_eo;
1545 
1546  /* if not glob, stop after one match */
1547  if (!re_flags->glob)
1548  break;
1549 
1550  /*
1551  * Advance search position. Normally we start the next search at the
1552  * end of the previous match; but if the match was of zero length, we
1553  * have to advance by one character, or we'd just find the same match
1554  * again.
1555  */
1556  start_search = prev_match_end;
1557  if (pmatch[0].rm_so == pmatch[0].rm_eo)
1558  start_search++;
1559  if (start_search > wide_len)
1560  break;
1561  }
1562 
1563  /*
1564  * check length of unmatched portion between end of last match and end of
1565  * input string
1566  */
1567  if (fetching_unmatched &&
1568  (wide_len - prev_valid_match_end) > maxlen)
1569  maxlen = (wide_len - prev_valid_match_end);
1570 
1571  /*
1572  * Keep a note of the end position of the string for the benefit of
1573  * splitting code.
1574  */
1575  matchctx->match_locs[array_idx] = wide_len;
1576 
1577  if (eml > 1)
1578  {
1579  int64 maxsiz = eml * (int64) maxlen;
1580  int conv_bufsiz;
1581 
1582  /*
1583  * Make the conversion buffer large enough for any substring of
1584  * interest.
1585  *
1586  * Worst case: assume we need the maximum size (maxlen*eml), but take
1587  * advantage of the fact that the original string length in bytes is
1588  * an upper bound on the byte length of any fetched substring (and we
1589  * know that len+1 is safe to allocate because the varlena header is
1590  * longer than 1 byte).
1591  */
1592  if (maxsiz > orig_len)
1593  conv_bufsiz = orig_len + 1;
1594  else
1595  conv_bufsiz = maxsiz + 1; /* safe since maxsiz < 2^30 */
1596 
1597  matchctx->conv_buf = palloc(conv_bufsiz);
1598  matchctx->conv_bufsiz = conv_bufsiz;
1599  matchctx->wide_str = wide_str;
1600  }
1601  else
1602  {
1603  /* No need to keep the wide string if we're in a single-byte charset. */
1604  pfree(wide_str);
1605  matchctx->wide_str = NULL;
1606  matchctx->conv_buf = NULL;
1607  matchctx->conv_bufsiz = 0;
1608  }
1609 
1610  /* Clean up temp storage */
1611  pfree(pmatch);
1612 
1613  return matchctx;
1614 }
void * palloc0(Size size)
Definition: mcxt.c:1346
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1540
#define MaxAllocSize
Definition: memutils.h:40
size_t re_nsub
Definition: regex.h:58
regoff_t rm_eo
Definition: regex.h:86
regoff_t rm_so
Definition: regex.h:85

References pg_re_flags::cflags, regexp_matches_ctx::conv_buf, regexp_matches_ctx::conv_bufsiz, ereport, errcode(), errmsg(), ERROR, pg_re_flags::glob, i, regexp_matches_ctx::match_locs, MaxAllocSize, regexp_matches_ctx::nmatches, regexp_matches_ctx::npatterns, regexp_matches_ctx::orig_str, palloc(), palloc0(), pfree(), pg_database_encoding_max_length(), pg_mb2wchar_with_len(), RE_compile_and_cache(), regex_t::re_nsub, RE_wchar_execute(), REG_NOSUB, repalloc(), regmatch_t::rm_eo, regmatch_t::rm_so, VARDATA_ANY, VARSIZE_ANY_EXHDR, and regexp_matches_ctx::wide_str.

Referenced by regexp_count(), regexp_instr(), regexp_match(), regexp_matches(), regexp_split_to_array(), regexp_split_to_table(), and regexp_substr().

◆ similar_escape()

Datum similar_escape ( PG_FUNCTION_ARGS  )

Definition at line 1040 of file regexp.c.

1041 {
1042  text *pat_text;
1043  text *esc_text;
1044  text *result;
1045 
1046  /* This function is not strict, so must test explicitly */
1047  if (PG_ARGISNULL(0))
1048  PG_RETURN_NULL();
1049  pat_text = PG_GETARG_TEXT_PP(0);
1050 
1051  if (PG_ARGISNULL(1))
1052  esc_text = NULL; /* use default escape character */
1053  else
1054  esc_text = PG_GETARG_TEXT_PP(1);
1055 
1056  result = similar_escape_internal(pat_text, esc_text);
1057 
1058  PG_RETURN_TEXT_P(result);
1059 }
#define PG_ARGISNULL(n)
Definition: fmgr.h:209
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
static text * similar_escape_internal(text *pat_text, text *esc_text)
Definition: regexp.c:767

References PG_ARGISNULL, PG_GETARG_TEXT_PP, PG_RETURN_NULL, PG_RETURN_TEXT_P, and similar_escape_internal().

◆ similar_escape_internal()

static text* similar_escape_internal ( text pat_text,
text esc_text 
)
static

Definition at line 767 of file regexp.c.

768 {
769  text *result;
770  char *p,
771  *e,
772  *r;
773  int plen,
774  elen;
775  bool afterescape = false;
776  bool incharclass = false;
777  int nquotes = 0;
778 
779  p = VARDATA_ANY(pat_text);
780  plen = VARSIZE_ANY_EXHDR(pat_text);
781  if (esc_text == NULL)
782  {
783  /* No ESCAPE clause provided; default to backslash as escape */
784  e = "\\";
785  elen = 1;
786  }
787  else
788  {
789  e = VARDATA_ANY(esc_text);
790  elen = VARSIZE_ANY_EXHDR(esc_text);
791  if (elen == 0)
792  e = NULL; /* no escape character */
793  else if (elen > 1)
794  {
795  int escape_mblen = pg_mbstrlen_with_len(e, elen);
796 
797  if (escape_mblen > 1)
798  ereport(ERROR,
799  (errcode(ERRCODE_INVALID_ESCAPE_SEQUENCE),
800  errmsg("invalid escape string"),
801  errhint("Escape string must be empty or one character.")));
802  }
803  }
804 
805  /*----------
806  * We surround the transformed input string with
807  * ^(?: ... )$
808  * which requires some explanation. We need "^" and "$" to force
809  * the pattern to match the entire input string as per the SQL spec.
810  * The "(?:" and ")" are a non-capturing set of parens; we have to have
811  * parens in case the string contains "|", else the "^" and "$" will
812  * be bound into the first and last alternatives which is not what we
813  * want, and the parens must be non capturing because we don't want them
814  * to count when selecting output for SUBSTRING.
815  *
816  * When the pattern is divided into three parts by escape-double-quotes,
817  * what we emit is
818  * ^(?:part1){1,1}?(part2){1,1}(?:part3)$
819  * which requires even more explanation. The "{1,1}?" on part1 makes it
820  * non-greedy so that it will match the smallest possible amount of text
821  * not the largest, as required by SQL. The plain parens around part2
822  * are capturing parens so that that part is what controls the result of
823  * SUBSTRING. The "{1,1}" forces part2 to be greedy, so that it matches
824  * the largest possible amount of text; hence part3 must match the
825  * smallest amount of text, as required by SQL. We don't need an explicit
826  * greediness marker on part3. Note that this also confines the effects
827  * of any "|" characters to the respective part, which is what we want.
828  *
829  * The SQL spec says that SUBSTRING's pattern must contain exactly two
830  * escape-double-quotes, but we only complain if there's more than two.
831  * With none, we act as though part1 and part3 are empty; with one, we
832  * act as though part3 is empty. Both behaviors fall out of omitting
833  * the relevant part separators in the above expansion. If the result
834  * of this function is used in a plain regexp match (SIMILAR TO), the
835  * escape-double-quotes have no effect on the match behavior.
836  *----------
837  */
838 
839  /*
840  * We need room for the prefix/postfix and part separators, plus as many
841  * as 3 output bytes per input byte; since the input is at most 1GB this
842  * can't overflow size_t.
843  */
844  result = (text *) palloc(VARHDRSZ + 23 + 3 * (size_t) plen);
845  r = VARDATA(result);
846 
847  *r++ = '^';
848  *r++ = '(';
849  *r++ = '?';
850  *r++ = ':';
851 
852  while (plen > 0)
853  {
854  char pchar = *p;
855 
856  /*
857  * If both the escape character and the current character from the
858  * pattern are multi-byte, we need to take the slow path.
859  *
860  * But if one of them is single-byte, we can process the pattern one
861  * byte at a time, ignoring multi-byte characters. (This works
862  * because all server-encodings have the property that a valid
863  * multi-byte character representation cannot contain the
864  * representation of a valid single-byte character.)
865  */
866 
867  if (elen > 1)
868  {
869  int mblen = pg_mblen(p);
870 
871  if (mblen > 1)
872  {
873  /* slow, multi-byte path */
874  if (afterescape)
875  {
876  *r++ = '\\';
877  memcpy(r, p, mblen);
878  r += mblen;
879  afterescape = false;
880  }
881  else if (e && elen == mblen && memcmp(e, p, mblen) == 0)
882  {
883  /* SQL escape character; do not send to output */
884  afterescape = true;
885  }
886  else
887  {
888  /*
889  * We know it's a multi-byte character, so we don't need
890  * to do all the comparisons to single-byte characters
891  * that we do below.
892  */
893  memcpy(r, p, mblen);
894  r += mblen;
895  }
896 
897  p += mblen;
898  plen -= mblen;
899 
900  continue;
901  }
902  }
903 
904  /* fast path */
905  if (afterescape)
906  {
907  if (pchar == '"' && !incharclass) /* escape-double-quote? */
908  {
909  /* emit appropriate part separator, per notes above */
910  if (nquotes == 0)
911  {
912  *r++ = ')';
913  *r++ = '{';
914  *r++ = '1';
915  *r++ = ',';
916  *r++ = '1';
917  *r++ = '}';
918  *r++ = '?';
919  *r++ = '(';
920  }
921  else if (nquotes == 1)
922  {
923  *r++ = ')';
924  *r++ = '{';
925  *r++ = '1';
926  *r++ = ',';
927  *r++ = '1';
928  *r++ = '}';
929  *r++ = '(';
930  *r++ = '?';
931  *r++ = ':';
932  }
933  else
934  ereport(ERROR,
935  (errcode(ERRCODE_INVALID_USE_OF_ESCAPE_CHARACTER),
936  errmsg("SQL regular expression may not contain more than two escape-double-quote separators")));
937  nquotes++;
938  }
939  else
940  {
941  /*
942  * We allow any character at all to be escaped; notably, this
943  * allows access to POSIX character-class escapes such as
944  * "\d". The SQL spec is considerably more restrictive.
945  */
946  *r++ = '\\';
947  *r++ = pchar;
948  }
949  afterescape = false;
950  }
951  else if (e && pchar == *e)
952  {
953  /* SQL escape character; do not send to output */
954  afterescape = true;
955  }
956  else if (incharclass)
957  {
958  if (pchar == '\\')
959  *r++ = '\\';
960  *r++ = pchar;
961  if (pchar == ']')
962  incharclass = false;
963  }
964  else if (pchar == '[')
965  {
966  *r++ = pchar;
967  incharclass = true;
968  }
969  else if (pchar == '%')
970  {
971  *r++ = '.';
972  *r++ = '*';
973  }
974  else if (pchar == '_')
975  *r++ = '.';
976  else if (pchar == '(')
977  {
978  /* convert to non-capturing parenthesis */
979  *r++ = '(';
980  *r++ = '?';
981  *r++ = ':';
982  }
983  else if (pchar == '\\' || pchar == '.' ||
984  pchar == '^' || pchar == '$')
985  {
986  *r++ = '\\';
987  *r++ = pchar;
988  }
989  else
990  *r++ = pchar;
991  p++, plen--;
992  }
993 
994  *r++ = ')';
995  *r++ = '$';
996 
997  SET_VARSIZE(result, r - ((char *) result));
998 
999  return result;
1000 }
#define VARHDRSZ
Definition: c.h:692
int pg_mbstrlen_with_len(const char *mbstr, int limit)
Definition: mbutils.c:1057
e
Definition: preproc-init.c:82
#define VARDATA(PTR)
Definition: varatt.h:278
#define SET_VARSIZE(PTR, len)
Definition: varatt.h:305

References ereport, errcode(), errhint(), errmsg(), ERROR, palloc(), pg_mblen(), pg_mbstrlen_with_len(), SET_VARSIZE, VARDATA, VARDATA_ANY, VARHDRSZ, and VARSIZE_ANY_EXHDR.

Referenced by similar_escape(), similar_to_escape_1(), and similar_to_escape_2().

◆ similar_to_escape_1()

Datum similar_to_escape_1 ( PG_FUNCTION_ARGS  )

Definition at line 1022 of file regexp.c.

1023 {
1024  text *pat_text = PG_GETARG_TEXT_PP(0);
1025  text *result;
1026 
1027  result = similar_escape_internal(pat_text, NULL);
1028 
1029  PG_RETURN_TEXT_P(result);
1030 }

References PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, and similar_escape_internal().

◆ similar_to_escape_2()

Datum similar_to_escape_2 ( PG_FUNCTION_ARGS  )

Definition at line 1006 of file regexp.c.

1007 {
1008  text *pat_text = PG_GETARG_TEXT_PP(0);
1009  text *esc_text = PG_GETARG_TEXT_PP(1);
1010  text *result;
1011 
1012  result = similar_escape_internal(pat_text, esc_text);
1013 
1014  PG_RETURN_TEXT_P(result);
1015 }

References PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, and similar_escape_internal().

◆ texticregexeq()

Datum texticregexeq ( PG_FUNCTION_ARGS  )

Definition at line 550 of file regexp.c.

551 {
552  text *s = PG_GETARG_TEXT_PP(0);
553  text *p = PG_GETARG_TEXT_PP(1);
554 
556  VARDATA_ANY(s),
560  0, NULL));
561 }

References PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, RE_compile_and_execute(), REG_ADVANCED, REG_ICASE, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

◆ texticregexne()

Datum texticregexne ( PG_FUNCTION_ARGS  )

Definition at line 564 of file regexp.c.

565 {
566  text *s = PG_GETARG_TEXT_PP(0);
567  text *p = PG_GETARG_TEXT_PP(1);
568 
570  VARDATA_ANY(s),
574  0, NULL));
575 }

References PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, RE_compile_and_execute(), REG_ADVANCED, REG_ICASE, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

◆ textregexeq()

Datum textregexeq ( PG_FUNCTION_ARGS  )

Definition at line 487 of file regexp.c.

488 {
489  text *s = PG_GETARG_TEXT_PP(0);
490  text *p = PG_GETARG_TEXT_PP(1);
491 
493  VARDATA_ANY(s),
495  REG_ADVANCED,
497  0, NULL));
498 }

References PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, RE_compile_and_execute(), REG_ADVANCED, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

◆ textregexne()

Datum textregexne ( PG_FUNCTION_ARGS  )

Definition at line 501 of file regexp.c.

502 {
503  text *s = PG_GETARG_TEXT_PP(0);
504  text *p = PG_GETARG_TEXT_PP(1);
505 
507  VARDATA_ANY(s),
509  REG_ADVANCED,
511  0, NULL));
512 }

References PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, RE_compile_and_execute(), REG_ADVANCED, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

◆ textregexreplace()

Datum textregexreplace ( PG_FUNCTION_ARGS  )

Definition at line 658 of file regexp.c.

659 {
660  text *s = PG_GETARG_TEXT_PP(0);
661  text *p = PG_GETARG_TEXT_PP(1);
662  text *r = PG_GETARG_TEXT_PP(2);
663  text *opt = PG_GETARG_TEXT_PP(3);
664  pg_re_flags flags;
665 
666  /*
667  * regexp_replace() with four arguments will be preferentially resolved as
668  * this form when the fourth argument is of type UNKNOWN. However, the
669  * user might have intended to call textregexreplace_extended_no_n. If we
670  * see flags that look like an integer, emit the same error that
671  * parse_re_flags would, but add a HINT about how to fix it.
672  */
673  if (VARSIZE_ANY_EXHDR(opt) > 0)
674  {
675  char *opt_p = VARDATA_ANY(opt);
676 
677  if (*opt_p >= '0' && *opt_p <= '9')
678  ereport(ERROR,
679  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
680  errmsg("invalid regular expression option: \"%.*s\"",
681  pg_mblen(opt_p), opt_p),
682  errhint("If you meant to use regexp_replace() with a start parameter, cast the fourth argument to integer explicitly.")));
683  }
684 
685  parse_re_flags(&flags, opt);
686 
688  flags.cflags, PG_GET_COLLATION(),
689  0, flags.glob ? 0 : 1));
690 }
text * replace_text_regexp(text *src_text, text *pattern_text, text *replace_text, int cflags, Oid collation, int search_start, int n)
Definition: varlena.c:4206

References pg_re_flags::cflags, ereport, errcode(), errhint(), errmsg(), ERROR, pg_re_flags::glob, parse_re_flags(), PG_GET_COLLATION, PG_GETARG_TEXT_PP, pg_mblen(), PG_RETURN_TEXT_P, replace_text_regexp(), VARDATA_ANY, and VARSIZE_ANY_EXHDR.

Referenced by execute_extension_script().

◆ textregexreplace_extended()

Datum textregexreplace_extended ( PG_FUNCTION_ARGS  )

Definition at line 699 of file regexp.c.

700 {
701  text *s = PG_GETARG_TEXT_PP(0);
702  text *p = PG_GETARG_TEXT_PP(1);
703  text *r = PG_GETARG_TEXT_PP(2);
704  int start = 1;
705  int n = 1;
706  text *flags = PG_GETARG_TEXT_PP_IF_EXISTS(5);
707  pg_re_flags re_flags;
708 
709  /* Collect optional parameters */
710  if (PG_NARGS() > 3)
711  {
712  start = PG_GETARG_INT32(3);
713  if (start <= 0)
714  ereport(ERROR,
715  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
716  errmsg("invalid value for parameter \"%s\": %d",
717  "start", start)));
718  }
719  if (PG_NARGS() > 4)
720  {
721  n = PG_GETARG_INT32(4);
722  if (n < 0)
723  ereport(ERROR,
724  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
725  errmsg("invalid value for parameter \"%s\": %d",
726  "n", n)));
727  }
728 
729  /* Determine options */
730  parse_re_flags(&re_flags, flags);
731 
732  /* If N was not specified, deduce it from the 'g' flag */
733  if (PG_NARGS() <= 4)
734  n = re_flags.glob ? 0 : 1;
735 
736  /* Do the replacement(s) */
738  re_flags.cflags, PG_GET_COLLATION(),
739  start - 1, n));
740 }

References pg_re_flags::cflags, ereport, errcode(), errmsg(), ERROR, pg_re_flags::glob, parse_re_flags(), PG_GET_COLLATION, PG_GETARG_INT32, PG_GETARG_TEXT_PP, PG_GETARG_TEXT_PP_IF_EXISTS, PG_NARGS, PG_RETURN_TEXT_P, replace_text_regexp(), and start.

Referenced by textregexreplace_extended_no_flags(), and textregexreplace_extended_no_n().

◆ textregexreplace_extended_no_flags()

Datum textregexreplace_extended_no_flags ( PG_FUNCTION_ARGS  )

Definition at line 751 of file regexp.c.

752 {
753  return textregexreplace_extended(fcinfo);
754 }
Datum textregexreplace_extended(PG_FUNCTION_ARGS)
Definition: regexp.c:699

References textregexreplace_extended().

◆ textregexreplace_extended_no_n()

Datum textregexreplace_extended_no_n ( PG_FUNCTION_ARGS  )

Definition at line 744 of file regexp.c.

745 {
746  return textregexreplace_extended(fcinfo);
747 }

References textregexreplace_extended().

◆ textregexreplace_noopt()

Datum textregexreplace_noopt ( PG_FUNCTION_ARGS  )

Definition at line 642 of file regexp.c.

643 {
644  text *s = PG_GETARG_TEXT_PP(0);
645  text *p = PG_GETARG_TEXT_PP(1);
646  text *r = PG_GETARG_TEXT_PP(2);
647 
650  0, 1));
651 }

References PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, REG_ADVANCED, and replace_text_regexp().

◆ textregexsubstr()

Datum textregexsubstr ( PG_FUNCTION_ARGS  )

Definition at line 583 of file regexp.c.

584 {
585  text *s = PG_GETARG_TEXT_PP(0);
586  text *p = PG_GETARG_TEXT_PP(1);
587  regex_t *re;
588  regmatch_t pmatch[2];
589  int so,
590  eo;
591 
592  /* Compile RE */
594 
595  /*
596  * We pass two regmatch_t structs to get info about the overall match and
597  * the match for the first parenthesized subexpression (if any). If there
598  * is a parenthesized subexpression, we return what it matched; else
599  * return what the whole regexp matched.
600  */
601  if (!RE_execute(re,
603  2, pmatch))
604  PG_RETURN_NULL(); /* definitely no match */
605 
606  if (re->re_nsub > 0)
607  {
608  /* has parenthesized subexpressions, use the first one */
609  so = pmatch[1].rm_so;
610  eo = pmatch[1].rm_eo;
611  }
612  else
613  {
614  /* no parenthesized subexpression, use whole match */
615  so = pmatch[0].rm_so;
616  eo = pmatch[0].rm_eo;
617  }
618 
619  /*
620  * It is possible to have a match to the whole pattern but no match for a
621  * subexpression; for example 'foo(bar)?' is considered to match 'foo' but
622  * there is no subexpression match. So this extra test for match failure
623  * is not redundant.
624  */
625  if (so < 0 || eo < 0)
626  PG_RETURN_NULL();
627 
629  PointerGetDatum(s),
630  Int32GetDatum(so + 1),
631  Int32GetDatum(eo - so));
632 }

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.

Variable Documentation

◆ num_res

int num_res = 0
static

Definition at line 112 of file regexp.c.

Referenced by RE_compile_and_cache().

◆ re_array

cached_re_str re_array[MAX_CACHED_RES]
static

Definition at line 113 of file regexp.c.

Referenced by RE_compile_and_cache().

◆ RegexpCacheMemoryContext

MemoryContext RegexpCacheMemoryContext
static

Definition at line 99 of file regexp.c.

Referenced by RE_compile_and_cache().