【问题标题】:substring by C language function of PostgreSQLPostgreSQL 的 C 语言函数的子串
【发布时间】:2021-10-06 07:47:58
【问题描述】:

我正在尝试为 postgresql 创建一个 c 语言函数,它返回给定字符串的子字符串

 Datum pg_string_slice(PG_FUNCTION_ARGS)
{
    text* original_text = PG_GETARG_TEXT_P(0);
    int64 start = PG_ARGISNULL(1) ? 0 : PG_GETARG_INT64(1);
    if (VARDATA(original_text) == nullptr)
    {
        PG_RETURN_NULL();
    }
    // Length = buffer size (format [valena type]) - header size (VARHDRSZ)
    // The size of the buffer is saved in the header (start of the buffer [4 bytes]).
    const int64 string_length = VARSIZE(original_text) - VARHDRSZ;
    int64 stop = PG_ARGISNULL(2) ? string_length : PG_GETARG_INT64(2);
    text* result = (text*)palloc(string_length + VARHDRSZ);
    uint64 new_length;
.
.
.
    //using here memcpy for transfering the substring to the palloced memory
.
.
.
    SET_VARSIZE(result, new_length + VARHDRSZ);
    PG_RETURN_TEXT_P(result);
} 

有没有一种方法可以返回子字符串,而不必分配缓冲区,只需如何操作给定的字符串?

【问题讨论】:

    标签: postgresql user-defined-functions


    【解决方案1】:

    您将不得不分配空间。 text 参数是不可变的——例如,它可能是对 TOAST 表中的值的引用。 text 以包含值大小的标头开头,因此如果不更改它,您将无法将相同的内存用于您的目的。

    不要忘记取消 TOAST 值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-10
      • 2020-07-25
      • 2016-06-30
      • 1970-01-01
      • 2021-03-29
      • 2011-10-12
      • 2016-08-19
      • 2015-09-15
      相关资源
      最近更新 更多