8.10. Битовые строки
Битовые строки представляют собой последовательности из 1 и 0. Их можно использовать для хранения или отображения битовых масок. В SQL есть два битовых типа: bit(
и n
)bit varying(
, где n
)n
— положительное целое число.
Длина значения типа bit
должна в точности равняться n
; при попытке сохранить данные длиннее или короче произойдёт ошибка. Данные типа bit varying
могут иметь переменную длину, но не превышающую n
; строки большей длины не будут приняты. Запись bit
без указания длины равнозначна записи bit(1)
, тогда как bit varying
без указания длины подразумевает строку неограниченной длины.
Примечание
При попытке привести значение битовой строки к типу bit(
, оно будет усечено или дополнено нулями справа до длины ровно n
)n
бит, ошибки при этом не будет. Подобным образом, если явно привести значение битовой строки к типу bit varying(
, она будет усечена справа, если её длина превышает n
)n
бит.
Синтаксис констант битовых строк описан в Подразделе 4.1.2.5, а все доступные битовые операторы и функции перечислены в Разделе 9.6.
Пример 8.3. Использование битовых строк
CREATE TABLE test (a BIT(3), b BIT VARYING(5)); INSERT INTO test VALUES (B'101', B'00'); INSERT INTO test VALUES (B'10', B'101');ОШИБКА: длина битовой строки (2) не соответствует типу bit(3)
INSERT INTO test VALUES (B'10'::bit(3), B'101'); SELECT * FROM test;a | b -----+----- 101 | 00 100 | 101
Для хранения битовой строки используется по 1 байту для каждой группы из 8 бит, плюс 5 или 8 байт дополнительно в зависимости от длины строки (но длинные строки могут быть сжаты или вынесены отдельно, как описано в Разделе 8.3 применительно к символьным строкам).
3.3. Foreign Keys
Recall the weather
and cities
tables from Chapter 2. Consider the following problem: You want to make sure that no one can insert rows in the weather
table that do not have a matching entry in the cities
table. This is called maintaining the referential integrity of your data. In simplistic database systems this would be implemented (if at all) by first looking at the cities
table to check if a matching record exists, and then inserting or rejecting the new weather
records. This approach has a number of problems and is very inconvenient, so Postgres Pro can do this for you.
The new declaration of the tables would look like this:
CREATE TABLE cities ( name varchar(80) primary key, location point ); CREATE TABLE weather ( city varchar(80) references cities(name), temp_lo int, temp_hi int, prcp real, date date );
Now try inserting an invalid record:
INSERT INTO weather VALUES ('Berkeley', 45, 53, 0.0, '1994-11-28');
ERROR: insert or update on table "weather" violates foreign key constraint "weather_city_fkey" DETAIL: Key (city)=(Berkeley) is not present in table "cities".
The behavior of foreign keys can be finely tuned to your application. We will not go beyond this simple example in this tutorial, but just refer you to Chapter 5 for more information. Making correct use of foreign keys will definitely improve the quality of your database applications, so you are strongly encouraged to learn about them.