【问题标题】:How to create a new database with the hstore extension already installed?如何创建一个已经安装了 hstore 扩展的新数据库?
【发布时间】:2012-07-20 01:10:28
【问题描述】:

最近I went into trouble 尝试在 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 ?

【问题讨论】:

    标签: sql postgresql postgresql-9.1 hstore


    【解决方案1】:

    长话短说:

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

    完成!

    【讨论】:

    • +1 表示正确并将其全部置于有用的格式中。有人可能会考虑使用与template1 不同的数据库。任何数据库都可以作为模板:CREATE DATABASE foo TEMPLATE mytemplate。或者,一旦您在 template1 中有其他内容,您可以使用(默认为空)template0
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多