创建自己的postgresql日期数据类型

研究了一下postgresql的日期数据类型的二进制存贮方式。发现是存贮是自2000年1月1号以来的天数。这样直接传入二进制参数会比较麻烦。因些参考了一些postgresql扩展的项目如:https://github.com/pgstuff/base32_4b

增加了一个date1的数据类型,存贮格式为 (year << 16) | ((month - 1) << 8) | (mday - 1)

select current_date1(),current_date;
 current_date1 | current_date
---------------+--------------
 2022-01-07    | 2022-01-07
(1 row)

用如下代码打印二进制内容:

  static const char cmd[] = "select '2000-01-01'::date,CURRENT_DATE,"
    "'2000-01-01'::date1,current_date1()";
  PGconn     *conn;
  PGresult   *res;

  conn = PQconnectdb(conninfo);
  res = PQexecParams(conn, cmd,
                     0,           /* one param */
                     NULL,        /* let the backend deduce param type */
                     NULL,
                     NULL,        /* don't need param lengths since text */
                     NULL,        /* default to all text params */
                     1);          /* ask for binary results */

  show_binary_results(res);

static void
show_binary_results(PGresult *res)
{
  int i, j;
  /* first, print out the attribute names */
  int nFields = PQnfields(res);

  for (i = 0; i < PQntuples(res); i++)
    {
      for(j=0; j< nFields; ++j)
        if(0 == PQgetisnull(res, i, j))
        {
          int len = PQgetlength(res, i, j);
          char* vp = PQgetvalue(res, i, j);
          if(4 == len || 8 == len)
            {
              printf("%-15s=", PQfname(res, j));
              for(int k=0; k<len; ++k, ++vp)
                printf("%02x ", *(uint8_t*)vp);
              printf("\n");
            }
          else
            {
              printf("%-15s=%.*s\n", PQfname(res, j), len, vp);
            }
        }
    }
}

date           =00 00 00 00
current_date   =00 00 1f 6a
date1          =07 d0 00 00
current_date1  =07 e6 00 06

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值