Postgreql: ERROR: 类型“ citext”不存在

我在搜索的时候也读过其他的帖子,这是对这个问题的回答。

我使用 PostgreSQL 9.1,并使用 CREATE EXTENSION citext创建了扩展名“ citext”,但是当我尝试创建任何类型为“ citext”的列时,它会抛出这个错误

错误: 类型“ citext”不存在

我研究了,但没有找到任何具体的答案? 知道为什么吗?

44161 次浏览

Ok figured it out. I have several databases and CREATE EXTENSION citext has to be run for each db to install the extension in that DB. You must do on psql prompt:

psql =# \c db_1
CREATE EXTENSION citext;


psql =# \c db_2
CREATE EXTENSION citext;

Hope it helps others. Thank you.

@NullException is correct that the extension needs to be created in each database. If you want to automatically have an extension created, you can create it in the template1 database which (by default, at least) is the database used as a model for "create database", so with appropriate permissions, in psql:

\c template1
create extension citext;

Then new databases will include citext by default.

To use citext, use the CITextExtension operation to setup the citext extension in PostgreSQL before the first CreateModel migration operation.

https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/fields/#citext-fields

from django.contrib.postgres.operations import CITextExtension


class Migration(migrations.Migration):
...


operations = [
CITextExtension(),
...
]

similarly to HStoreField as https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/operations/#create-postgresql-extensions

If you use Docker, and want to add this extension to your database,

I have done the following,

# Dockerfile
FROM postgres:11.3


# Adds the CIText Extension to our database
COPY ./compose/production/postgres/initdb_citext.sh /docker-entrypoint-initdb.d/citext.sh

And my initdb_citext.sh:

#!/bin/sh


# Adds the citext extension to database and test database
"${psql[@]}" <<- 'EOSQL'
CREATE EXTENSION IF NOT EXISTS citext;
\c template1
CREATE EXTENSION IF NOT EXISTS citext;
EOSQL

This applies the extension to test databases that django generates too.