Меню Рубрики

Extension postgresql what package linux

Extension postgresql what package linux

CREATE EXTENSION загружает в текущую базу данных новое расширение. Расширение с таким именем не должно быть уже загружено.

Для загрузки расширения требуются те же права, что необходимы для создания составляющих его объектов. Для большинства расширений это означает, что необходимы права владельца базы данных или суперпользователя. Пользователь, запускающий CREATE EXTENSION , становится владельцем самого расширения (это требуется для последующих проверок доступа), а также владельцем всех объектов, созданных скриптом расширения.

Параметры

Не считать ошибкой, если расширение с таким именем уже существует. В этом случае будет выдано замечание. Заметьте, что нет никакой гарантии, что существующее расширение как-то соотносится с тем, которое могло бы быть создано из указанного скрипта. имя_расширения

Имя устанавливаемого расширения. PostgreSQL создаст расширение, используя инструкции из файла SHAREDIR/extension/ имя_расширения .control . имя_схемы

Имя схемы, в которую будут установлены объекты расширения (подразумевается, что расширение позволяет управлять размещением своих объектов). Указанная схема должна уже существовать. Если имя не указано и в управляющем файле расширения оно так же не задано, для создания объектов используется текущая схема.

Если в управляющем файле расширения задаётся параметр schema , заданную схему нельзя переопределить предложением SCHEMA . Обычно при указании предложения SCHEMA возникает ошибка, если эта схема конфликтует с параметром schema данного расширения. Однако, если также задаётся предложение CASCADE , в случае конфликта имя_схемы игнорируется. Заданное имя_схемы будет использоваться для установки всех необходимых расширений, в управляющих файлах которых не задаётся schema .

Помните, что само расширение не считается принадлежащим какой-либо схеме; имена расширений не дополняются схемой и потому должны быть уникальными во всей базе данных. Однако объекты, принадлежащие расширениям, могут относиться к схемам. версия

Версия устанавливаемого расширения. Её можно записать в виде идентификатора или строкового значения. По умолчанию версия считывается из управляющего файла расширения. старая_версия

Указание FROM старая_версия может быть добавлено тогда и только тогда, когда устанавливаемое расширение заменяет модуль « старого стиля » , представляющий собой просто набор объектов, не упакованный в расширение. С этим указанием CREATE EXTENSION запускает альтернативный установочный скрипт, собирающий все существующие объекты в расширение, а не создающий новые. Учтите, что SCHEMA при этом определяет схему, содержащую эти существующие объекты.

Значение, задаваемое в качестве старой_версии , определяется автором расширения и может меняться, если в расширение нужно преобразовать не одну версию модуля в старом стиле. Для стандартных дополнительных модулей, поставляемых в PostgreSQL до версии 9.1, при преобразовании модуля в расширение старая_версия должна содержать значение unpackaged . CASCADE

Автоматически устанавливать все расширения, от которого зависит данное, если они ещё не установлены. Их зависимости подобным образом рекурсивно устанавливаются автоматически. Предложение SCHEMA , если задано, применяется ко всем расширениям, устанавливаемым таким способом. Другие параметры оператора к автоматически устанавливаемым расширениям не применяются; в частности, всегда выбираются их версии по умолчанию.

Замечания

Прежде чем вы сможете выполнить CREATE EXTENSION и загрузить расширение в базу данных, необходимо правильно установить сопутствующие файлы расширения. Информацию об установке расширений, поставляемых в составе PostgreSQL , можно найти по ссылке Дополнительные поставляемые модули.

Расширения, доступные для установки в данный момент, можно найти в системном представлении pg_available_extensions или pg_available_extension_versions .

Внимание

Устанавливая расширение от имени суперпользователя, важно иметь уверенность в том, что автор расширения написал установочный скрипт безопасным образом. Для злонамеренного пользователя не составит большого труда создать объект типа троянского коня, который впоследствии скомпрометирует выполнение неаккуратно написанного скрипта расширения и позволит этому пользователю стать суперпользователем. Однако такие объекты опасны, только если они находятся в пути search_path во время выполнения скрипта, то есть, если они находятся в схеме, в которую устанавливается расширение, или в схеме, где располагается другое расширение, от которого зависит первое. Таким образом, имея дело с расширениями, скрипты которых не были тщательно проверены, рекомендуется устанавливать их только в те схемы, в которых недоверенные пользователи не имеют и не будут иметь права CREATE. То же самое касается их зависимостей, других расширений.

Расширения, поставляемые в составе PostgreSQL , можно считать защищёнными от подобного рода атак времени выполнения, за исключением некоторых, зависящих от других расширений. Как отмечается в документации таких расширений, их следует устанавливать в безопасные схемы и/или в те же схемы, в которые устанавливаются требующиеся им расширения.

За информацией для разработчиков расширений обратитесь к Разделу 36.15.

Примеры

Установка расширения hstore в текущую базу данных (при этом объекты расширения размещаются в схеме addons ):

Другой способ сделать то же самое:

Преобразование установленного до версии 9.1 модуля hstore в расширение:

Будьте внимательны — здесь нужно указать схему, в которую ранее были установлены существующие объекты hstore .

Совместимость

CREATE EXTENSION является расширением PostgreSQL .

Источник

How do I import modules or install extensions in PostgreSQL 9.1+?

Firstly, if you’re not using 9.1+, please refer to this question.

How do I install an extension to PostgreSQL 9.1?

7 Answers 7

Postgrseql 9.1 provides for a new command CREATE EXTENSION . You should use it to install modules.

If for instance you wanted to install earthdistance , simply use this command:

If you wanted to install an extension with a hyphen in its name, like uuid-ossp , you need to enclose the extension name in double quotes:

  • Read more about contrib, and the modules available in 9.1.
  • Read about the new extension infrastructure, and the SQL commands to manage it here You can now more easily uninstall a module, see DROP EXTENSION . You can also get an extension list, and there is basic support for version numbers.

While Evan Carrol’s answer is correct, please note that you need to install the postgresql contrib package in order for the CREATE EXTENSION command to work.

In Ubuntu 12.04 it would go like this:

Restart the postgresql server:

All available extension are in:

Now you can run the CREATE EXTENSION command.

In addition to the extensions which are maintained and provided by the core PostgreSQL development team, there are extensions available from third parties. Notably, there is a site dedicated to that purpose: http://www.pgxn.org/

For the postgrersql10

I have solved it with

Don’t forget to activate extensions in postgresql.conf

then of course restart

all of the needed extensions you can find here

The extensions available for each version of Postgresql vary. An easy way to check which extensions are available is, as has been already mentioned:

If the extension that you are looking for is available, you can install it using:

or if you want to drop it use:

With psql you can additionally check if the extension has been successfully installed using \dx , and find more details about the extension using \dx+ extensioName . It returns additional information about the extension, like which packages are used with it.

If the extension is not available in your Postgres version, then you need to download the necessary binary files and libraries and locate it them at /usr/share/conrib

Источник

Shining apples

Заметки о сетях, администрировании и вообще

PostgreSQL управление расширениями (extensions)

Расширения PostgreSQL предоставляют дополнительный функционал. Часть расширений входит в пакет contrib и доступны в
PostgreSQL сразу после его установки (пакет свой под каждую версию PG, например postgresql11-contrib).
Расширения ставятся индивидуально в каждую БД отдельно.
Так же, можно установить и использовать расширения не входящие в contrib-пакет. Для этого их необходимо скомпилировать
под конкретную мажорную версию PG и добавить необходимые файлы в директории PG.
PostgreSQL хранит файлы расширений в директориях (директория зависит от версии):

  • в /usr/pgsql-11/share/extension — sql-файлы и control-файлы
  • в /usr/pgsql-11/lib — so-файлы

Просмотр списка расширений
В бд выполнить запрос:

Установка расширений
Для установки расширения необходимо выполнить в бд запрос:

Обновление расширений
Для обновления расширения необходимо в бд выполнить запрос:

Или для обновления на конкретную версию:

Удаление расширений
Чтобы удалить расширение из бд, выполняем команду:

Источник

Extensions

Contents

Extensions

Extensions were implemented in PostgreSQL 9.1 to allow for easier packaging of additions to PostgreSQL. Extensions can package user-visible functions or use hooks in the PostgreSQL to modify how the database does certain processes.

Wish List for Future Features from Extension Builders

This list was originally compiled during an unconference session at PgCon 2018. Please feel free to add additional requests and/or clarify these.

Versioning

  • How to deal with multiple versions in different databases in the same PostgreSQL cluster?
  • How to deal with unloading old versions on upgrade?
    • Current system can’t really unload due to the way hooks are executed using pointers to other extensions.
    • Should the core code register hooks and manage their calling rather than relying on extensions being nice to one another and passing along hooks?
  • How to deal with extension defined GUCs defined in previous versions during an upgrade?

Documentation/Debugging Improvements

  • Currently hooks are relatively hard to find throughout the codebase ( ack _hook appears to be the way folks do that) how can we make it easier to find all hooks an extension might want to use and improve documentation around what they might be useful for/why they exist?
  • How can we give better error messages through PL/PGSQL at install/upgrade time? They are currently too terse to really understand easily what has failed.

Dependency Checking and Installation improvements

  • Currently we load extensions in the order specified in the shared_preload_libraries variable, should we instead check dependencies and order them based on dependencies?
  • Can we improve how dependencies for extensions are checked?
  • How should this interact with versioning?
    • Can we have some way of ordering extension versions either universally or extension defined so that dependencies can do >/ Installation/Uninstallation/Catalog Improvements
    • Should we allow an install of an extension automatically add something to shared_preload_libraries rather than having to specify in the configuration file?
    • Should there be a shared catalog for extensions and determining which versions are installed in which databases?

    New Hooks?

    • One major question to be considered: should we abandon the hook style integration of extensions for another model? What might that model look like?
    • List of possible new hooks please add new ones as needed.
      • Table file extension hook

    Notes on Original Extensions Patchset from 9.1

    A series of patches implements extensions support for dump and restore for PostgreSQL. In order to reach this goal, several things need to happen, and the patch is quite large by now. This is the diffstat of the cumulative branch:

    Overview

    The extension patch has to be considered with the dump and restore support in mind. About all that is done is to that end, there is very few extra in there. The goal is for pg_dump not to output the extension’s install script, that is maintained separately from the database objects. That allows for easier restores too, when the extension needs to be upgraded. What we want to see in the dump is:

    For schema support, see the discussion above.

    Some extension will install tables where users will be able to edit the data, or use commands and functions that will change the data for them. The line of though here is that the data will change and that we want to have them as part of the dump, because the maintenance of those data is not done in the extension’s SCM but in the database.

    User Interface

    There’s both \dx to list installed extensions and \dx+ to list installed and available extensions.

    The function pg_extension_objects() is useful both for end-users and extension authors who will want to find their objects oid easily to manage upgrades, e.g.

    catalog, system view, functions

    The calalog has minimal information here. All extension related operations are super-user only, and we only need a name, a version string and a custom_variable_classes setting, as detailed later.

    The pg_extensions system view will also list available extensions, and offers an «installed» column to sort that out:

    Some utility functions are available, intended for extension authoring. See later for details:

    commands

    Basically, you can CREATE and DROP an extension, and also ALTER it.

    user data and extensions

    The extension’s patches goal is for pg_dump *NOT* to care about extension’s objects, because they are maintained in some repository out there, not in the database. There’s an exception here, when the extension installs tables (or anything, really) that the user can edit, directly or through some facilities given by the extension. Now we need to dump those as well.

    Extension authors have a function they can call from their scripts to flag some objects are necessary to dump, and the documentation contains this example:

    Such flags will make it so that pg_dump will dump the objects separately. The idea is that the dependency between the object and its extension is changed from DEPENDENCY_INTERNAL (no dump) to DEPENDENCY_NORMAL (dump).

    schema and extensions

    The schema support has been asked for on the -hackers list and is a simple search and replace of the @extschema@ placeholder in the extension’s script, replacing it by the user entered schema in the CREATE EXTENSION command, which defaults to ‘public’.

    Another patch proposes the ALTER EXTENSION SET SCHEMA command: we are able to track all extension’s object, so we are able to run the SET SCHEMA command on all of them. That’s an optional sugar ish facility that is seen as a great value 🙂

    pg_dump support

    The pg_dump command has been patched so that it will not consider any object that has a direct DEPENDENDY_INTERNAL pg_depend entry to the extension’s oid. That’s about the only goal of all this work.

    Of course we have some special cases to care about or it wouldn’t be funny, such as the following:

    Usually it’s a lot more simple than that, as in the operator families example:

    Using the DEPENDENCY_INTERNAL implementation makes it quite simple to achieve pg_dump support.

    Authoring Extension

    As an extension author, you have very few new things to do compared to what you needed to do before the patch. You have to provide the meta-data that will end-up into the pg_extension catalog, that’s what the new .control file is for. There’s support for that in the pgxs makefile, too. All those changes in contrib are just about that.

    The control file

    Allows to register an extension into the catalogs. Minimal meta-data and syntax support (uses recovery.conf parser), fixed expected location alongside the SQL script, pgxs support

    Some more involved examples. First, a script which name is different from the extension name, second, some more variables.

    custom_variable_classes

    This GUC is clearly an extension author facility. Users will be able to edit their postgresql.conf file and set there the individual settings for the custom class, but it’s a bad idea to expose them the custom variable classes if we can have it managed automatically.

    After that, the custom_variable_classes is stored in the pg_extension catalog and will be dynamically set at backend creation time. The GUC management has been changed to be SUSET in the patch. To do that, we keep GUC placeholder in a secondary storage, and we are able to merge those into the main list when custom_variable_classes changes.

    Code design and patch series

    As usual, the patch growing, it has been asked to separate some parts of it in order to ease reviewing. We’re now at 5 patches, with some dependencies between them.

    The extension patch has been only produced with the cfparser and pg_execute_from_file() bits, to ease testing. The set schema has been produced separately and is independent, the alter_extension patch is an incremental patch atop both the extension and the set_schema patch, to ease discussion of APIs.

    tracking extension objects

    The backend/commands/extension.c file uses some new backend static variables in order to track the objects creation and add dependencies:

    cfparser

    This part of the patch allows to reuse the recovery.conf line parser function from elsewhere in the code.

    pg_execute_from_files()

    That function will load the file content in memory, then apply placeholders, then use SPI as if it were a single query string, which it is, somehow. That means the extension’s script can not embed BEGIN/COMMIT commands.

    extension, the main patch

    This main patch contains the bulk work for pg_dump support of extensions, and proposes a single placeholder for script files, @extschema@.

    set_schema

    Support patch for being able to move all extension’s object into another schema easily.

    So we have this supporting:

    alter extension

    Starting from the previous support, we now are able to have ALTER EXTENSION citext SET SCHEMA utils;

    Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

  • L110 epson mac os
  • L2tp mac os beeline
  • Kyocera m2135dn драйвер mac os
  • Kyocera fs 1060dn mac os
  • Kyocera fs 1040 драйвер mac os