2012-07-20 51 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