避免将化合物类型转换为文本

时间:2017-01-21 22:00:50

标签: postgresql plpgsql

PLPGSQL函数返回时,我的复合类型将转换为文本:

dev=# select * from app.user_query_test(3);
   user_record   |   udata_record    
-----------------+-------------------
 (3,875227490,t) | (3,3,"Bob Smith")
(1 row)

dev=# 

我不想要这个,我希望在客户端接收它们作为数据的嵌套对象,如下所示:

{
   "user_record": {
         "user_id": 3,
         "identity_id": 875227490,
         "utype": t
    },
    "udata_record": {
          "udata_id": 3,
          "user_id": 3,
          "full_name": "Bob Smith"
    }
}

但是,我也不想要JSON,因为解码/编码为JSON格式需要处理时间并且会影响我的应用程序的性能。那我该怎么做呢?我的意思是如何在没有任何解码/编码过程的PLPGSQL函数返回的情况下将数据放在客户端的确切结构中?

我的源文件是:

DROP TYPE IF EXISTS app.user_reply_t CASCADE;
CREATE TYPE app.user_reply_t AS (
    user_id         integer,
    identity_id     integer,
    utype           boolean
);
DROP TYPE IF EXISTS app.udata_reply_t CASCADE;
CREATE TYPE app.udata_reply_t AS (
    udata_id        integer,
    user_id         integer,
    full_name       varchar(64)
);
DROP TYPE IF EXISTS app.user_info_t CASCADE;
CREATE TYPE app.user_info_t AS (
    user_record     app.user_reply_t,
    udata_record    app.udata_reply_t
);
CREATE OR REPLACE FUNCTION app.user_query_test(p_user_id integer) 
RETURNS app.user_info_t AS 
$$
DECLARE
    rec             app.user_info_t;
BEGIN
    SELECT user_id,identity_id,utype FROM "comp-158572724".users WHERE user_id=p_user_id INTO rec.user_record;
    SELECT udata_id,user_id,full_name FROM "comp-158572724".udata WHERE user_id=p_user_id INTO rec.udata_record;
    RETURN rec;
END;
$$ LANGUAGE plpgsql;

使用Node.js进行测试:

 src $ node usertest.js 
result={ command: 'SELECT',
  rowCount: 1,
  rows: 
   [ { user_record: '(3,875227490,t)',
       udata_record: '(3,3,"Bob Smith")' } ],
  fields: 
   [ { name: 'user_record', dataTypeID: 19862 },
     { name: 'udata_record', dataTypeID: 19865 } ] }
^C
 src $ 

客户代码来源:

src $ cat usertest.js 
const util = require('util');
pg = require('pg').native
var Pool = pg.Pool
var Client = pg.Client
var pool=new Pool({
    user:     'dev_user',
    password: 'dev',
    host:     'localhost',
    database: 'dev'
});

pool.query('select * from app.user_query_test(3)',function(err, result) {
        console.log('result=' + util.inspect(result));
    }
);
function wait() {
    console.log('wating...');
    setTimeout(wait,3000);
}
setTimeout(wait,3000);
 src $ 

0 个答案:

没有答案