研究了一下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