2012-07-20 52 views
49

最近I went into trouble试图与Django一起使用hstore。我这样安装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在新创建的数据库?

回答

96

长话短说:

在template1数据库安装hstore:

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

步骤一步的解释:

如前所述通过the PostgreSQL documentation

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数据库中。根据the doc

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

+1是正确的,并将其全部置于有用的格式中。有人可能会考虑使用与“template1”不同的数据库。任何数据库都可以作为模板:'CREATE DATABASE foo TEMPLATE mytemplate'。或者,一旦你在'template1'中有了额外的东西,你可以使用(默认为空)'template0'。 – 2012-07-20 19:48:07