I.3. Сборка документации

Завершив все подготовительные действия, перейдите в каталог doc/src/sgml и запустите одну из команд сборки, описанных в следующих подразделах. (Помните, что для сборки нужно использовать GNU make.)

I.3.1. HTML

Чтобы собрать HTML-версию документации:

doc/src/sgml$ make html

Эта цель сборки также выбирается по умолчанию. Результат помещается в подкаталог html.

Чтобы был сформирован алфавитный указатель, во время сборки требуется выполнить несколько проходов. Если этот указатель вам не нужен, вы просто хотите проверить результат, используйте режим draft:

doc/src/sgml$ make draft

Чтобы получить документацию в виде одной HTML-страницы, выполните:

doc/src/sgml$ make postgres.html

I.3.2. Страницы man

Для преобразования страниц DocBook refentry в формат *roff, подходящий для страниц man, мы используем стили DocBook XSL. Страницы man распространяются в архиве tar, подобно HTML-версии. Чтобы создать страницы man, выполните:

cd doc/src/sgml
make man

I.3.3. Получение печатной версии с использованием JadeTeX

Если вы хотите получить печатную версию документации, используя JadeTex, вы можете воспользоваться одной из следующих команд:

  • Чтобы получить PostScript через DVI для формата A4, выполните:

    doc/src/sgml$ make postgres-A4.ps

    Для формата «U.S. Letter» выполните:

    doc/src/sgml$ make postgres-US.ps

  • Чтобы получить PDF:

    doc/src/sgml$ make postgres-A4.pdf

    или:

    doc/src/sgml$ make postgres-US.pdf

    (Разумеется, вы можете получить PDF и из PostScript, но если сгенерировать PDF напрямую, полученный файл будет содержать гиперссылки и другие расширенные особенности.)

Если вы намерены использовать JadeTeX для сборки документации PostgreSQL, вам, вероятно, потребуется увеличить некоторые внутренние параметры TeX. Их можно задать в файле texmf.cnf. На момент написания этого описания работали следующие параметры:

hash_extra.jadetex  = 200000
hash_extra.pdfjadetex  = 200000
pool_size.jadetex = 2000000
pool_size.pdfjadetex = 2000000
string_vacancies.jadetex = 150000
string_vacancies.pdfjadetex = 150000
max_strings.jadetex = 300000
max_strings.pdfjadetex = 300000
save_size.jadetex = 15000
save_size.pdfjadetex = 15000

I.3.4. Переполнение текста

В некоторых местах текст документации оказывается слишком широким для предопределённых границ, и, в особых случаях, не умещается на странице. В частности, это наблюдается с широкими таблицами или текстом, не допускающим переносы. Сталкиваясь с такой ситуацией, TeX выводит сообщения "Overfull hbox" (Переполнение горизонтальной рамки) в файл журнала, например, postgres-US.log или postgres-A4.log. С учётом того, что дюйм составляют 72 точки, всё, что выходит за границу больше чем на 72 точки, скорее всего не поместится на печатаемой странице (при размере поля один дюйм). Чтобы найти в SGML текст, выходящий за границы, определите номер страницы, указанный над сообщением о переполнении, например: [50 ###] (стр. 50), и посмотрите на следующую страницу (в данном случае, стр. 51) в PDF. Увидев, какой текст на ней выходит за границы, внесите требуемые коррективы в SGML.

I.3.5. Получение печатной версии из RTF

Вы также можете получить печатную версию документации PostgreSQL, преобразовав её в формат RTF, который позволяет откорректировать форматирование в офисном пакете. В зависимости от возможностей конкретного текстового редактора, затем документацию можно будет преобразовать в PostScript или PDF. Ниже описывается, как это можно проделать с применением Applixware.

Замечание: Судя по всему, текущие версии документации PostgreSQL провоцируют ошибку или превышают ограничения размера, существующие в OpenJade. Если у вас процесс сборки RTF «зависает» на долгое время, а размер выводимого файла остаётся нулевым, возможно, вы столкнулись именно с этой проблемой. (Но учтите, что обычная сборка занимает от 5 до 10 минут, так что не прерывайте процесс слишком быстро.)

Очистка RTF в Applixware

OpenJade опускает указание стиля по умолчанию для основного текста. В прошлом, пока это не было обнаружено, генерация оглавления документации выполнялась очень долго. Однако, благодаря помощи разработчиков Applixware, мы смогли диагностировать эту проблему и найти обходное решение.

  1. Получите RTF-версию документации, введя:

    doc/src/sgml$ make postgres.rtf

  2. Исправьте файл RTF, чтобы в нём корректно указывались все стили, в частности, стиль по умолчанию. Если документ содержит разделы refentry, нужно также заменить указания форматирования, связывающие предыдущий абзац с текущим, на указания, связывающие текущий абзац со следующим. Для внесения этих корректив предоставляется утилита fixrtf (она находится в doc/src/sgml):

    doc/src/sgml$ ./fixrtf --refentry postgres.rtf

    Этот скрипт добавляет в документ {\s0 Normal;} в качестве нулевого стиля. По утверждению разработчиков Applixware, стандарт RTF не должен допускать добавления неявного нулевого стиля, хотя Microsoft Word обрабатывает это указание. Для исправления разделов refentry этот скрипт заменяет теги \keepn на \keep.

  3. Создайте новый документ в Applixware Words, а затем импортируйте в него файл RTF.

  4. Создайте оглавление с помощью Applixware.

    1. Выделите строки существующего оглавления, от первого символа первой строки до последнего символа последней строки.

    2. Постройте новое оглавление, выбрав в меню Tools->Book Building->Create Table of Contents (Сервис->Сборка книги->Создать оглавление). Выберите первые три уровня заголовков для включения в оглавление. В результате строки оглавления, импортированные из RTF, будут заменены оглавлением, созданным в Applixware.

    3. Поправьте форматирование оглавления, выбрав пункт меню Format->Style (Формат->Стиль), и определив следующие значения отступов (First (Первый) и Left (Слева)) для каждого из трёх стилей оглавления:

      СтильПервый отступ (в дюймах)Отступ слева (в дюймах)
      TOC-Heading 10.40.4
      TOC-Heading 20.80.8
      TOC-Heading 31.21.2

  5. Проработайте форматирование документа:

    • Расставьте разрывы страниц.

    • Поправьте ширину колонок таблиц.

  6. Замените выравненные по правому краю номера страниц в части оглавления Примеры и Рисунки правильными значениями. Это должно занять всего несколько минут.

  7. Удалите из документа раздел алфавитного указателя, если он пуст.

  8. Сгенерируйте заново и скорректируйте оглавление.

    1. Выделите поле оглавления.

    2. Выберите в меню Tools->Book Building->Create Table of Contents (Сервис->Сборка книги->Создать оглавление).

    3. Отделите оглавление, выбрав в меню Tools->Field Editing->Unprotect (Сервис->Изменение полей->Снять защиту).

    4. Удалите первую строку в оглавлении, которая указывает на само оглавление.

  9. Сохраните документ в специальном формате Applixware Words, чтобы в него можно было легко внести последние правки.

  10. "Напечатайте" документ в файл формата PostScript.

I.3.6. Простые текстовые файлы

Инструкции по установке также распространяются в виде обычного текста, на случай, если они понадобятся в ситуации, когда под рукой не окажется средств просмотра более удобного формата. Файл INSTALL соответствует Главе 15, с небольшими изменениями, внесёнными с учётом другого контекста. Чтобы пересоздать этот файл, перейдите в каталог doc/src/sgml и введите make INSTALL.

В прошлом примечания к выпуску и инструкции по регрессионному тестированию также распространялись в виде простых текстовых файлов, но эта практика была прекращена.

I.3.7. Проверка синтаксиса

Сборка всей документации может занять много времени. Но если нужно проверить только синтаксис файлов документации, это можно сделать всего за несколько секунд:

doc/src/sgml$ make check

F.30. ltree — hierarchical tree-like data type #

This module implements a data type ltree for representing labels of data stored in a hierarchical tree-like structure. Extensive facilities for searching through label trees are provided.

This module is considered trusted, that is, it can be installed by non-superusers who have CREATE privilege on the current database.

F.30.1. Definitions #

A label is a sequence of alphanumeric characters, underscores, and hyphens. Valid alphanumeric character ranges are dependent on the database locale. For example, in C locale, the characters A-Za-z0-9_- are allowed. Labels must be no more than 1000 characters long.

Examples: 42, Personal_Services

A label path is a sequence of zero or more labels separated by dots, for example L1.L2.L3, representing a path from the root of a hierarchical tree to a particular node. The length of a label path cannot exceed 65535 labels.

Example: Top.Countries.Europe.Russia

The ltree module provides several data types:

  • ltree stores a label path.

  • lquery represents a regular-expression-like pattern for matching ltree values. A simple word matches that label within a path. A star symbol (*) matches zero or more labels. These can be joined with dots to form a pattern that must match the whole label path. For example:

    foo         Match the exact label path foo
    *.foo.*     Match any label path containing the label foo
    *.foo       Match any label path whose last label is foo
    

    Both star symbols and simple words can be quantified to restrict how many labels they can match:

    *{n}        Match exactly n labels
    *{n,}       Match at least n labels
    *{n,m}      Match at least n but not more than m labels
    *{,m}       Match at most m labels — same as *{0,m}
    foo{n,m}    Match at least n but not more than m occurrences of foo
    foo{,}      Match any number of occurrences of foo, including zero
    

    In the absence of any explicit quantifier, the default for a star symbol is to match any number of labels (that is, {,}) while the default for a non-star item is to match exactly once (that is, {1}).

    There are several modifiers that can be put at the end of a non-star lquery item to make it match more than just the exact match:

    @           Match case-insensitively, for example a@ matches A
    *           Match any label with this prefix, for example foo* matches foobar
    %           Match initial underscore-separated words
    

    The behavior of % is a bit complicated. It tries to match words rather than the entire label. For example foo_bar% matches foo_bar_baz but not foo_barbaz. If combined with *, prefix matching applies to each word separately, for example foo_bar%* matches foo1_bar2_baz but not foo1_br2_baz.

    Also, you can write several possibly-modified non-star items separated with | (OR) to match any of those items, and you can put ! (NOT) at the start of a non-star group to match any label that doesn't match any of the alternatives. A quantifier, if any, goes at the end of the group; it means some number of matches for the group as a whole (that is, some number of labels matching or not matching any of the alternatives).

    Here's an annotated example of lquery:

    Top.*{0,2}.sport*@.!football|tennis{1,}.Russ*|Spain
    a.  b.     c.      d.                   e.
    

    This query will match any label path that:

    1. begins with the label Top

    2. and next has zero to two labels before

    3. a label beginning with the case-insensitive prefix sport

    4. then has one or more labels, none of which match football nor tennis

    5. and then ends with a label beginning with Russ or exactly matching Spain.

  • ltxtquery represents a full-text-search-like pattern for matching ltree values. An ltxtquery value contains words, possibly with the modifiers @, *, % at the end; the modifiers have the same meanings as in lquery. Words can be combined with & (AND), | (OR), ! (NOT), and parentheses. The key difference from lquery is that ltxtquery matches words without regard to their position in the label path.

    Here's an example ltxtquery:

    Europe & Russia*@ & !Transportation
    

    This will match paths that contain the label Europe and any label beginning with Russia (case-insensitive), but not paths containing the label Transportation. The location of these words within the path is not important. Also, when % is used, the word can be matched to any underscore-separated word within a label, regardless of position.

Note: ltxtquery allows whitespace between symbols, but ltree and lquery do not.

F.30.2. Operators and Functions #

Type ltree has the usual comparison operators =, <>, <, >, <=, >=. Comparison sorts in the order of a tree traversal, with the children of a node sorted by label text. In addition, the specialized operators shown in Table F.17 are available.

Table F.17. ltree Operators

Operator

Description

ltree @> ltreeboolean

Is left argument an ancestor of right (or equal)?

ltree <@ ltreeboolean

Is left argument a descendant of right (or equal)?

ltree ~ lqueryboolean

lquery ~ ltreeboolean

Does ltree match lquery?

ltree ? lquery[]boolean

lquery[] ? ltreeboolean

Does ltree match any lquery in array?

ltree @ ltxtqueryboolean

ltxtquery @ ltreeboolean

Does ltree match ltxtquery?

ltree || ltreeltree

Concatenates ltree paths.

ltree || textltree

text || ltreeltree

Converts text to ltree and concatenates.

ltree[] @> ltreeboolean

ltree <@ ltree[]boolean

Does array contain an ancestor of ltree?

ltree[] <@ ltreeboolean

ltree @> ltree[]boolean

Does array contain a descendant of ltree?

ltree[] ~ lqueryboolean

lquery ~ ltree[]boolean

Does array contain any path matching lquery?

ltree[] ? lquery[]boolean

lquery[] ? ltree[]boolean

Does ltree array contain any path matching any lquery?

ltree[] @ ltxtqueryboolean

ltxtquery @ ltree[]boolean

Does array contain any path matching ltxtquery?

ltree[] ?@> ltreeltree

Returns first array entry that is an ancestor of ltree, or NULL if none.

ltree[] ?<@ ltreeltree

Returns first array entry that is a descendant of ltree, or NULL if none.

ltree[] ?~ lqueryltree

Returns first array entry that matches lquery, or NULL if none.

ltree[] ?@ ltxtqueryltree

Returns first array entry that matches ltxtquery, or NULL if none.


The operators <@, @>, @ and ~ have analogues ^<@, ^@>, ^@, ^~, which are the same except they do not use indexes. These are useful only for testing purposes.

The available functions are shown in Table F.18.

Table F.18. ltree Functions

Function

Description

Example(s)

subltree ( ltree, start integer, end integer ) → ltree

Returns subpath of ltree from position start to position end-1 (counting from 0).

subltree('Top.Child1.Child2', 1, 2)Child1

subpath ( ltree, offset integer, len integer ) → ltree

Returns subpath of ltree starting at position offset, with length len. If offset is negative, subpath starts that far from the end of the path. If len is negative, leaves that many labels off the end of the path.

subpath('Top.Child1.Child2', 0, 2)Top.Child1

subpath ( ltree, offset integer ) → ltree

Returns subpath of ltree starting at position offset, extending to end of path. If offset is negative, subpath starts that far from the end of the path.

subpath('Top.Child1.Child2', 1)Child1.Child2

nlevel ( ltree ) → integer

Returns number of labels in path.

nlevel('Top.Child1.Child2')3

index ( a ltree, b ltree ) → integer

Returns position of first occurrence of b in a, or -1 if not found.

index('0.1.2.3.5.4.5.6.8.5.6.8', '5.6')6

index ( a ltree, b ltree, offset integer ) → integer

Returns position of first occurrence of b in a, or -1 if not found. The search starts at position offset; negative offset means start -offset labels from the end of the path.

index('0.1.2.3.5.4.5.6.8.5.6.8', '5.6', -4)9

text2ltree ( text ) → ltree

Casts text to ltree.

ltree2text ( ltree ) → text

Casts ltree to text.

lca ( ltree [, ltree [, ... ]] ) → ltree

Computes longest common ancestor of paths (up to 8 arguments are supported).

lca('1.2.3', '1.2.3.4.5.6')1.2

lca ( ltree[] ) → ltree

Computes longest common ancestor of paths in array.

lca(array['1.2.3'::ltree,'1.2.3.4'])1.2


F.30.3. Indexes #

ltree supports several types of indexes that can speed up the indicated operators:

  • B-tree index over ltree: <, <=, =, >=, >

  • Hash index over ltree: =

  • GiST index over ltree (gist_ltree_ops opclass): <, <=, =, >=, >, @>, <@, @, ~, ?

    gist_ltree_ops GiST opclass approximates a set of path labels as a bitmap signature. Its optional integer parameter siglen determines the signature length in bytes. The default signature length is 8 bytes. The length must be a positive multiple of int alignment (4 bytes on most machines)) up to 2024. Longer signatures lead to a more precise search (scanning a smaller fraction of the index and fewer heap pages), at the cost of a larger index.

    Example of creating such an index with the default signature length of 8 bytes:

    CREATE INDEX path_gist_idx ON test USING GIST (path);
    

    Example of creating such an index with a signature length of 100 bytes:

    CREATE INDEX path_gist_idx ON test USING GIST (path gist_ltree_ops(siglen=100));
    
  • GiST index over ltree[] (gist__ltree_ops opclass): ltree[] <@ ltree, ltree @> ltree[], @, ~, ?

    gist__ltree_ops GiST opclass works similarly to gist_ltree_ops and also takes signature length as a parameter. The default value of siglen in gist__ltree_ops is 28 bytes.

    Example of creating such an index with the default signature length of 28 bytes:

    CREATE INDEX path_gist_idx ON test USING GIST (array_path);
    

    Example of creating such an index with a signature length of 100 bytes:

    CREATE INDEX path_gist_idx ON test USING GIST (array_path gist__ltree_ops(siglen=100));
    

    Note: This index type is lossy.

F.30.4. Example #

This example uses the following data (also available in file contrib/ltree/ltreetest.sql in the source distribution):

CREATE TABLE test (path ltree);
INSERT INTO test VALUES ('Top');
INSERT INTO test VALUES ('Top.Science');
INSERT INTO test VALUES ('Top.Science.Astronomy');
INSERT INTO test VALUES ('Top.Science.Astronomy.Astrophysics');
INSERT INTO test VALUES ('Top.Science.Astronomy.Cosmology');
INSERT INTO test VALUES ('Top.Hobbies');
INSERT INTO test VALUES ('Top.Hobbies.Amateurs_Astronomy');
INSERT INTO test VALUES ('Top.Collections');
INSERT INTO test VALUES ('Top.Collections.Pictures');
INSERT INTO test VALUES ('Top.Collections.Pictures.Astronomy');
INSERT INTO test VALUES ('Top.Collections.Pictures.Astronomy.Stars');
INSERT INTO test VALUES ('Top.Collections.Pictures.Astronomy.Galaxies');
INSERT INTO test VALUES ('Top.Collections.Pictures.Astronomy.Astronauts');
CREATE INDEX path_gist_idx ON test USING GIST (path);
CREATE INDEX path_idx ON test USING BTREE (path);
CREATE INDEX path_hash_idx ON test USING HASH (path);

Now, we have a table test populated with data describing the hierarchy shown below:

                        Top
                     /   |  \
             Science Hobbies Collections
                 /       |              \
        Astronomy   Amateurs_Astronomy Pictures
           /  \                            |
Astrophysics  Cosmology                Astronomy
                                        /  |    \
                                 Galaxies Stars Astronauts

We can do inheritance:

ltreetest=> SELECT path FROM test WHERE path <@ 'Top.Science';
                path
------------------------------------
 Top.Science
 Top.Science.Astronomy
 Top.Science.Astronomy.Astrophysics
 Top.Science.Astronomy.Cosmology
(4 rows)

Here are some examples of path matching:

ltreetest=> SELECT path FROM test WHERE path ~ '*.Astronomy.*';
                     path
-----------------------------------------------
 Top.Science.Astronomy
 Top.Science.Astronomy.Astrophysics
 Top.Science.Astronomy.Cosmology
 Top.Collections.Pictures.Astronomy
 Top.Collections.Pictures.Astronomy.Stars
 Top.Collections.Pictures.Astronomy.Galaxies
 Top.Collections.Pictures.Astronomy.Astronauts
(7 rows)

ltreetest=> SELECT path FROM test WHERE path ~ '*.!pictures@.Astronomy.*';
                path
------------------------------------
 Top.Science.Astronomy
 Top.Science.Astronomy.Astrophysics
 Top.Science.Astronomy.Cosmology
(3 rows)

Here are some examples of full text search:

ltreetest=> SELECT path FROM test WHERE path @ 'Astro*% & !pictures@';
                path
------------------------------------
 Top.Science.Astronomy
 Top.Science.Astronomy.Astrophysics
 Top.Science.Astronomy.Cosmology
 Top.Hobbies.Amateurs_Astronomy
(4 rows)

ltreetest=> SELECT path FROM test WHERE path @ 'Astro* & !pictures@';
                path
------------------------------------
 Top.Science.Astronomy
 Top.Science.Astronomy.Astrophysics
 Top.Science.Astronomy.Cosmology
(3 rows)

Path construction using functions:

ltreetest=> SELECT subpath(path,0,2)||'Space'||subpath(path,2) FROM test WHERE path <@ 'Top.Science.Astronomy';
                 ?column?
------------------------------------------
 Top.Science.Space.Astronomy
 Top.Science.Space.Astronomy.Astrophysics
 Top.Science.Space.Astronomy.Cosmology
(3 rows)

We could simplify this by creating an SQL function that inserts a label at a specified position in a path:

CREATE FUNCTION ins_label(ltree, int, text) RETURNS ltree
    AS 'select subpath($1,0,$2) || $3 || subpath($1,$2);'
    LANGUAGE SQL IMMUTABLE;

ltreetest=> SELECT ins_label(path,2,'Space') FROM test WHERE path <@ 'Top.Science.Astronomy';
                ins_label
------------------------------------------
 Top.Science.Space.Astronomy
 Top.Science.Space.Astronomy.Astrophysics
 Top.Science.Space.Astronomy.Cosmology
(3 rows)

F.30.5. Transforms #

The ltree_plpython3u extension implements transforms for the ltree type for PL/Python. If installed and specified when creating a function, ltree values are mapped to Python lists. (The reverse is currently not supported, however.)

Caution

It is strongly recommended that the transform extension be installed in the same schema as ltree. Otherwise there are installation-time security hazards if a transform extension's schema contains objects defined by a hostile user.

F.30.6. Authors #

All work was done by Teodor Sigaev () and Oleg Bartunov (). See http://www.sai.msu.su/~megera/postgres/gist/ for additional information. Authors would like to thank Eugeny Rodichev for helpful discussions. Comments and bug reports are welcome.