sql – 用随机数替换序列

前端之家收集整理的这篇文章主要介绍了sql – 用随机数替换序列前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想用我自己的自定义id生成器替换我在 postgresql数据库中的id的一些序列.发生器将产生一个随机数,最后有一个checkdigit.所以这:
SELECT nextval('customers')

将被这样的东西所取代:

SELECT get_new_rand_id('customer')

函数然后返回一个数值,例如:[1-9] [0-9] {9}其中最后一个数字是校验和.

我所关心的是:

>我该如何使事情成为原子
>如何避免返回相同的ID两次(这将通过尝试将其插入到具有唯一约束的列,但后来我想)
这是一个好主意吗?

注1:我不想使用uuid,因为它是与客户沟通,10位数字比36个字符uuid简单得多.

Note2:该函数很少使用SELECT get_new_rand_id()调用,但将被分配为id-column而不是nextval()的默认值.

编辑:好的,下面很好的讨论!这里有一些解释为什么:

那么为什么我会以这种方式过分的改变呢? purpouse是隐藏客户的主键.

@H_404_24@

I give each new customer a unique
customerId (generated serial number in
the db). Since I communicate that
number with the customer it is a
fairly simple task for my competitors
to monitor my business (there are
other numbers such as invoice nr and
order nr that have the same
properties). It is this monitoring I
would like to make a little bit
harder (note: not impossible but
harder).

>为什么是校验位?

@H_404_24@

Before there was any talk of hiding the serial nr I added a checkdigit to ordernr since there were klumbsy fingers at some points in the production,and my thought was that this would be a good practice to keep in the future.

阅读讨论后,我可以肯定地看到,我的方法不是解决问题的最佳方法,但是我没有其他的好方法解决问题,所以请帮忙我.

>我应该添加一个额外的列,我把我公开的id给客户,并将序列作为主键吗?
>如何生成id以公开和有效的方式公开?
>需要checkdigit吗?

解决方法

为了从序列生成唯一且随机的标识符,使用密码可能是一个好主意.由于它们的输出是双射的(输入和输出值之间存在一对一的映射) – 与散列不同,您不会有任何冲突.这意味着您的标识符不必与散列一样长.

大多数加密密码适用于64位或更大的块,但Postgresql维基有一个example PL/pgSQL procedure for a “non-cryptographic” cipher功能,适用于(32位)int类型.免责声明:我没有尝试使用这个功能.

要将其用于主键,请从Wiki页面运行CREATE FUNCTION调用,然后在空表上执行:

ALTER TABLE foo ALTER COLUMN foo_id SET DEFAULT pseudo_encrypt(nextval('foo_foo_id_seq')::int);

和瞧!

pg=> insert into foo (foo_id) values(default);
pg=> insert into foo (foo_id) values(default);
pg=> insert into foo (foo_id) values(default);
pg=> select * from foo;
  foo_id   
------------
 1241588087
 1500453386
 1755259484
(4 rows)
原文链接:https://www.f2er.com/mssql/75118.html

猜你在找的MsSQL相关文章