[英]Insert UUID with pg-promise
I am developing a new server and I am trying to have a customer have a UUID identifier. 我正在开发新的服务器,并且试图让客户拥有UUID标识符。 I want to be able to push the customers name, parent company and internal id from a web interface but the uuid should be generated server side.
我希望能够从Web界面推送客户名称,母公司和内部ID,但是uuid应该在服务器端生成。 How can I insert the UUID into the database?
如何将UUID插入数据库? The uuid should be put into the ID in the table.
uuid应该放在表的ID中。
The current setup is so I can send the ID in with curl and have it all tested. 当前设置是这样,因此我可以通过curl发送ID并进行所有测试。 What the code was doing before was get every value from the terminal.
代码之前所做的是从终端获取每个值。 I am trying to modify this working code so that when I create a new customer I can put their name, parent, symID and have a uuid generated into the ID column.
我正在尝试修改此工作代码,以便在创建新客户时可以将其名称,父级,symID放入ID列中并生成一个uuid。
for the symID I also want to pull that from a database of ID's that I currently do not have access to. 对于symID,我也想从我目前无法访问的ID的数据库中提取该ID。 I do not know if this feature will be implemented so for right now it is just entered either manually or not at all.
我不知道是否会实现此功能,所以现在暂时只是手动输入还是根本不输入。
I am using pg-promise to write to a postgres database, also using express and bluebird. 我正在使用pg-promise来写到postgres数据库,也使用express和bluebird。
//Database setup
...
CREATE TABLE customer(
customer_name VARCHAR,
ID varchar PRIMARY KEY,
parent VARCHAR,
symID VARCHAR
);
...
//code to create new user
...
function createUser(req, res, next) {
const user_id = uuidv4();
//need to fix id. currently it is user entered and not a uuidv4
db.none('insert into customer values(${customer_name}, ${ID}, ${parent}, ${symID})',
req.body)
.then(function () {
res.status(200)
.json({
status: 'success',
message: 'Inserted one customer'
});
})
.catch(function (err) {
return next(err);
});
}
...
You can generate the UUID automatically with minor change to your table definition: 您只需对表定义进行少量更改即可自动生成UUID:
if not already installed then you need the extension pgcrypto. 如果尚未安装,则需要扩展pgcrypto。
CREATE EXTENSION pgcrypto; -- if needed
CREATE TABLE customer(
customer_name VARCHAR,
ID uuid default gen_random_uuid() PRIMARY KEY,
parent VARCHAR,
symID VARCHAR
);
That will generate a type4 uuid. 这将生成一个type4 uuid。 Getting it's value back would be similar to getting the PK created by sequence/serial ( at list I think so ).
取回它的价值将类似于获得序列/序列创建的PK(我认为是列表中的)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.