2016-11-08 106 views
1

我想与NOT_NULL约束添加列,以便列将包含随机默认值下面是我的代码我怎样才能做到这一点添加列随机值Sequelize PostgreSQL的

up: function (queryInterface, Sequelize, done) { 
queryInterface.addColumn(
    { 
     tableName: 'someTable', 
     schema: 'sometemplate' 
    }, 
    'someColumn', //column name 
    { //column date type and constraint 
     type: Sequelize.STRING, 
     allowNull: false, 
     defaultValue: // I want this to random value 
    }) 
    .then(function() { done() }) 
    .catch(done); 
} 

回答

-1

PostgreSQL的例子:

CREATE OR REPLACE FUNCTION f_random_text(
    length integer 
) 
RETURNS text AS 
$body$ 
WITH chars AS (
    SELECT unnest(string_to_array('A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9', ' ')) AS _char 
), 
charlist AS 
(
    SELECT _char FROM chars ORDER BY random() LIMIT $1 
) 
SELECT string_agg(_char, '') 
FROM charlist 
; 
$body$ 
LANGUAGE sql; 


DROP TABLE IF EXISTS tmp_test; 


CREATE TEMPORARY TABLE tmp_test (
    id serial, 
    data text default f_random_text(12) 
); 


INSERT INTO tmp_test 
VALUES 
    (DEFAULT, DEFAULT), 
    (DEFAULT, DEFAULT) 
; 


SELECT * FROM tmp_test; 

id |  data 
----+-------------- 
    1 | RYMUJH4E0NIQ 
    2 | 7U4029BOKAEJ 
(2 rows) 

显然你可以做到这一点。 (当然,您也可以添加其他字符,或者使用其他随机字符串生成器 - 例如,像这样)。 ref:https://dba.stackexchange.com/questions/19632/how-to-create-column-in-db-with-default-value-random-string