postgresql 如何在创建数据库时安装 Postgres 扩展?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16611226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 00:55:23  来源:igfitidea点击:

How to install Postgres extensions at database creation?

ruby-on-railspostgresql

提问by Alive Developer

It would be lovely if the rake command db:createcould be followed by a postgresql installation script. This, for example. (It must be run as postgres user):

如果 rake 命令db:create后面可以跟一个 postgresql 安装脚本,那就太好了。这,例如。(它必须以 postgres 用户身份运行):

CREATE EXTENSION "fuzzystrmatch";

This because, in this moment, i'm doing it manually every time I create a database.

这是因为,在这一刻,我每次创建数据库时都手动进行。

Any hints?

任何提示?

回答by Dylan Markow

As of Rails 4, there is a enable_extensionmethod:

从 Rails 4 开始,有一个enable_extension方法:

class AddFuzzyStringMatching < ActiveRecord::Migration
  def change
    enable_extension "fuzzystrmatch"
  end
end

回答by Doon

I just do this in a migration

我只是在迁移中这样做

class AddCryptoToDb < ActiveRecord::Migration
  def up
    execute <<-SQL
      CREATE extension IF NOT EXISTS pgcrypto;
    SQL
  end
end

You can execute any sql want there. I also do it for functions

你可以在那里执行任何想要的 sql。我也为函数做

class BuildFnSetWebUsersUid < ActiveRecord::Migration
  def up
    say "building fn_set_web_users_uid function"
    execute <<-SQL
      CREATE OR REPLACE FUNCTION fn_set_web_users_uid()
        RETURNS trigger AS
      $BODY$
        BEGIN
          IF NEW.uid IS NULL THEN
            SELECT UID into NEW.uid
            FROM generate_series(10000, (SELECT last_value FROM web_users_uid_seq)) AS s(uid)
            EXCEPT
            SELECT uid FROM web_users
            ORDER BY uid;
            IF NEW.uid is NULL THEN
              SELECT nextval('web_users_uid_seq') INTO NEW.uid;
             END IF;
          END IF;
          RETURN NEW;
        END;
      $BODY$
        LANGUAGE 'plpgsql';
  SQL
  end

  def down
    execute "DROP FUNCTION IF EXISTS fn_set_web_users_uid;"
  end
end

Also it doesn't need to be postgres user, depending upon the extension it needs to be superuser or database owner. So on my dev boxes I give the user Super User Rights for ease of use.

此外,它不需要是 postgres 用户,具体取决于它需要是超级用户或数据库所有者的扩展名。所以在我的开发箱上,我授予用户超级用户权限以方便使用。

回答by Denis de Bernardy

You could create a rake task (it's fairly straightforward), or mess around with the template1 database (not recommended, but possible):

您可以创建一个 rake 任务(它相当简单),或者使用 template1 数据库(不推荐,但可能):

http://www.postgresql.org/docs/9.2/static/manage-ag-templatedbs.html

http://www.postgresql.org/docs/9.2/static/manage-ag-templatedbs.html