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

62

最近,我在尝试使用Django的hstore时遇到了麻烦。我是这样安装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)

我天真地以为我的新数据库将包括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)

有没有一种自动在新创建的数据库中使用hstore的方法?

2个回答

118

长话短说:

在template1数据库中安装hstore:

psql -d template1 -c 'create extension hstore;'
步骤说明:

根据PostgreSQL文档的说明:

 

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

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

$ psql -c 'select current_database()'
 current_database 
------------------
 username
(1 row)

如果您有一个以您的用户名命名的数据库,现在可以使用 dbtest

$ psql -d dbtest -c 'select current_database()'
 current_database 
------------------
 dbtest
(1 row)

好的,你明白了。现在,如果要创建安装了hstore的新数据库,你需要在template1数据库中安装它。根据文档

CREATE DATABASE实际上是通过复制现有的数据库来完成的。默认情况下,它会复制名为template1的标准系统数据库。

我们来做吧:

$ psql -d template1 -c 'create extension hstore;'

并检查它是否有效:

$ 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)

完成!


10
使用不同的数据库作为模板,而非template1。任何数据库都可以作为模板:CREATE DATABASE foo TEMPLATE mytemplate。或者,一旦您在template1中添加了其他内容,您可以使用(默认为空的)template0 - Erwin Brandstetter

0

还要记住,hstore在Public模式中,如果您使用其他模式,则应该使用格式public.hstore(record)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接