如果为列提供的值不为空,则可选列更新

Optional column update if provided value for column is not null

我关注table:

CREATE TABLE IF NOT EXISTS categories
(
    id SERIAL PRIMARY KEY,
    title CHARACTER VARYING(100) NOT NULL,
    description CHARACTER VARYING(200) NULL,
    category_type CHARACTER VARYING(100) NOT NULL
);

我正在使用 pg-promise,我想提供可选的列更新:

categories.update = function (categoryTitle, toUpdateCategory) {
  return this.db.oneOrNone(sql.update, [
          categoryTitle,
          toUpdateCategory.title, toUpdateCategory.category_type, toUpdateCategory.description,
        ])
}

我想构建 UPDATE 查询以仅更新提供的列:

UPDATE categories
SET title=,
// ... SET category_type= if  is no NULL otherwise keep old category_type value
// ... SET description= if  is no NULL otherwise keep old description value
WHERE title = 
RETURNING *;

如何在 Postgres 中实现此可选列更新?

您可以 coalesce 介于旧值和新值之间:

UPDATE categories
SET title=,
    category_type = COALESCE(, category_type),
    description = COALESCE(, description) -- etc...
WHERE title = 

helpers syntax is best for any sort of dynamic logic with pg-promise:

/* logic for skipping columns: */
const skip = c => c.value === null || c.value === undefined;

/* reusable/static ColumnSet object: */
const cs = new pgp.helpers.ColumnSet(
    [
        'title',
        {name: 'category_type', skip},
        {name: 'description', skip}
    ],
    {table: 'categories'});

categories.update = function(title, category) {
   const condition = pgp.as.format(' WHERE title = ', title);
   const update = () => pgp.helpers.update(category, cs) + condition;
   return this.db.none(update);
}

如果您的可选列属性在未指定时甚至不存在于对象上,您可以将跳过逻辑简化为这样(参见 Column 逻辑):

const skip = c => !c.exists;

已用 API:ColumnSet, helpers.update

另见一个非常相似的问题: