如何创建已安装hstore扩展的新数据库?

Max*_* R. 54 sql postgresql postgresql-9.1 hstore

最近我在尝试使用Djang与Django时遇到了麻烦.我用这种方式安装了hstore:

$ sudo -u postgres psql
postgres=# CREATE EXTENSION hstore;
WARNING:  => is deprecated as an operator name
DETAIL:  This name may be disallowed altogether in future versions of PostgreSQL.
CREATE EXTENSION
postgres=# \dx
                           List of installed extensions
  Name   | Version |   Schema   |                   Description                    
---------+---------+------------+--------------------------------------------------
 hstore  | 1.0     | public     | data type for storing sets of (key, value) pairs
 plpgsql | 1.0     | pg_catalog | PL/pgSQL procedural language
(2 rows)
Run Code Online (Sandbox Code Playgroud)

并天真地认为我的新数据库将包括hstore.情况并非如此:

$ createdb dbtest
$ psql -d dbtest -c '\dx'
                 List of installed extensions
  Name   | Version |   Schema   |         Description          
---------+---------+------------+------------------------------
 plpgsql | 1.0     | pg_catalog | PL/pgSQL procedural language
(1 row)
Run Code Online (Sandbox Code Playgroud)

有没有办法在新创建的数据库中自动拥有hstore?

Max*_* R. 107

长话短说:

在template1数据库中安装hstore:

psql -d template1 -c 'create extension hstore;'
Run Code Online (Sandbox Code Playgroud)

分步说明:

正如PostgreSQL文档所述:

CREATE EXTENSION将新扩展加载到当前数据库中.

安装扩展是特定于数据库的.以下内容返回当前数据库名称:

$ psql -c 'select current_database()'
 current_database 
------------------
 username
(1 row)
Run Code Online (Sandbox Code Playgroud)

如果您有一个以您的用户名命名的数据库.现在dbtest:

$ psql -d dbtest -c 'select current_database()'
 current_database 
------------------
 dbtest
(1 row)
Run Code Online (Sandbox Code Playgroud)

好的,你明白了.现在,要创建安装了hstore的新数据库,您必须将其安装在template1数据库中.根据文件:

CREATE DATABASE实际上通过复制现有数据库来工作.默认情况下,它复制名为template1的标准系统数据库.

我们开工吧:

$ psql -d template1 -c 'create extension hstore;'
Run Code Online (Sandbox Code Playgroud)

并检查它是否有效:

$ createdb dbtest
$ psql -d dbtest -c '\dx'
                 List of installed extensions
  Name   | Version |   Schema   |                   Description                    
---------+---------+------------+--------------------------------------------------
 hstore  | 1.0     | public     | data type for storing sets of (key, value) pairs
 plpgsql | 1.0     | pg_catalog | PL/pgSQL procedural language
(2 rows)
Run Code Online (Sandbox Code Playgroud)

完成!

  • +1是正确的,并将其全部放在有用的格式中.有人可能会考虑使用与`template1`不同的数据库.任何数据库都可以作为模板:`CREATE DATABASE foo TEMPLATE mytemplate`.或者,一旦你在`template1`中有了额外的东西,就可以使用(默认为空)`template0`. (10认同)