100% нашли этот документ полезным (1 голос)
681 просмотров

Postgresql Osnovy PDF

Загружено:

Alexandr Casapciuc
Авторское право
© © All Rights Reserved
Мы серьезно относимся к защите прав на контент. Если вы подозреваете, что это ваш контент, заявите об этом здесь.
Доступные форматы
Скачать в формате PDF, TXT или читать онлайн в Scribd
100% нашли этот документ полезным (1 голос)
681 просмотров

Postgresql Osnovy PDF

Загружено:

Alexandr Casapciuc
Авторское право
© © All Rights Reserved
Мы серьезно относимся к защите прав на контент. Если вы подозреваете, что это ваш контент, заявите об этом здесь.
Доступные форматы
Скачать в формате PDF, TXT или читать онлайн в Scribd
Вы находитесь на странице: 1/ 639

PostgreSQL.

qxd

16.07.02

PROGRAMMER

13:39

Page 1

TO PROGRAMMER

PROGRAMMER

TM

TO PROGRAMMER

TM

PostgreSQL

PostgreSQL "
.
, "
, "
, . "

PostgreSQL, "
.


,
. "
, , , ,
, C.

SQL,
PHP, Perl Java.
PostgreSQL Windows"
UNIX".

?
,
, "
. "

:
:

PostgreSQL
"
UNIX Windows

, "
,
, ,

,

SQL""
(libpq) SQL
PHP, Perl Java

www.symbol.ru


(812) 3245353
(095) 9458100

PostgreSQL

PostgreSQL
,

Beginning
Databases with
PostgreSQL
Richard Stones and Neil Matthew

PostgreSQL


2002

PostgreSQL.
.

.
.

.
.
.
.
.
.

., .
PostgreSQL. . . . : , 2002. 640 ., .
ISBN 593286043X
PostgreSQL
. .
, , 
, .

PostgreSQL, .

, , 
. , , , 
SQL, PHP, Perl Java.

UNIX Windows, , 
, , , , 
, . , 
, ,
SQL (libpq) SQL, 
PHP, Perl Java.
ISBN 593286043X
ISBN 1861005156 ()
, 2002
Authorized translation of the English edition 2001 Wrox Press Ltd. This translation
is published and sold by permission of Wrox Press Ltd, the owner of all rights to pub
lish and sell the same.
, 
. 
, , .

. 193148, , . , 4,
. (812) 3245353, [email protected]. N 000054 25.12.98.

00593, 2; 953000 .
16.08.2002. 701001/16 . .
40 . . 2000 . N

199034, , 9 , 12.


. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1. PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
, . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
PostgreSQL? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Open Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
NULL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

3. PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
PostgreSQL Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
PostgreSQL Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Cygwin UNIX= Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
IPC Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
PostgreSQL Cygwin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
PostgreSQL Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
PostgreSQL Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
psql . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
SELECT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
. . . . . . . . . . . . . . . . . . . . . . . . . . 121
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
NULL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141

5. PostgreSQL . . . . . . . . . . . 142
psql . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
psql . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
psql . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
psql . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
. . . . . . . . . . . . . . . . 147
. . . . . . . . . . . . . . . . . . . . . . . 148
ODBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
pgAdmin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
Kpsql . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
PgAccess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Microsoft Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Microsoft Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
INSERT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
SERIAL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
NULL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
\copy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
. . . . . . . . . . . . . . . . . . . 189
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
7. . . . . . . . . . . . . . . . 200
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
COUNT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
MIN() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
MAX() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
SUM() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
AVG() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
UNION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229

8. . . . . . . . . . . . . . . 230
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
OID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
. . . . . . . . . . . . . . . . . . . . . . . . . 260
. . . . . . . . . . . . . . . . . . . . . . . . 261
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
9. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
. . . . . . . . . . . . . . . . . . . . . . . . . 274
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
. . . . . . . . . . . . . . . . . . . . . . . . 278
ANSI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
ANSI/ISO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
(Auto Commit) . . . . . . . . . . . . . . . . . 285
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291

10. . . . . . . . . . . . . . . . . . . . . . . . . . . 293
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
PL/pgSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327

? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334

11. PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335


. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
bin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
include lib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
doc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
man . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
share . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
. . . . . . . . . . . . . . . . . . . . . 351

10

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
. . . . . . . . . . . . . . . . . . . . . . . . 360
. . . . . . . . . . . . . . . . . . . . . . . . 362
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
VACUUM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369

12. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
. . . . . . . . . . . . . . . . . . . . . . . . . . 381
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
== . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
13. PostgreSQL C libpq . . . . . . . . . . . . . . . . . 403
libpq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
Makefile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
SQL libpq . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437

11

14. PostgreSQL C SQL . . . . . 438


SQL . . . . . . . . . . . . . . . . . . . . 439
ecpg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
ecpg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
ecpg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
15. PostgreSQL PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
PostgreSQL PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
PHP API PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
. . . . . . . . . . . . . . . . . . . . . . . . . . . 477
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
PEAR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
16. PostgreSQL Perl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
pgsql_perl5 Pg. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
pgsql_perl5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
pgsql_perl5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
Perl DBI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500
DBI PostgreSQL DBD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
DBI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
DBI? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
DBIx::Easy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
DBI XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
17. PostgreSQL Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
JDBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
JDBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519

12

JDBC PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519


DriverManager Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
java.sql.DriverManager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
java.sql.Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
JDBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
. . . . . . . . 530
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
. . . . . . . . . . . . . . . . . . . . . . . . 534
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
. . . . . . . . . . . . . . . . . . . . . . . . . . . 535
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
JDBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
PreparedStatements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
SQL . . . . . . . . . . . . . . . . . . . . . . 546
JDBC . . . . . . . . . . . . . 547
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565

18. . . . . . . . . . . . . . . . . . . . . 566
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566
OLTP, OLAP . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
A. PostgreSQL . . . . . . . . . . . . . . 574
B. PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
C. SQL PostgreSQL. . . . . . . . . . . . . . . . . . . . . . . . . . 582
D. psql . . . . . . . . . . . . . . . . . . . . 594
E. . . . . . . . . . . . . . . . . . . . . . . 597
F. PostgreSQL . . . . . . . . . . 600
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608


, , :
, , , ,
, . =
, =
, .
, ,
, , , ,
, .
,
.
, ,
Beginning Linux Programming ( Linux)
Professional Linux Programming ( Linux
). , =
.
Wrox
, . (Dan M.), =
. =
, (=
), . (Dilip T), (Manju), . (Indu B),
(Nilesh) . (Vijay T), , =
.
, =
; !
,
. ,
, .
. =
, , , .
, GEHE,
.

14

, =
, PostgreSQL =
; =
.
(Linus) Linux,
RMS GNU GPL,
,
, ,
Open Source
GPL= .

PostgreSQL
 
, .
PostgreSQL ( 
), .
()
Postgres. SQL,
Postgres , 
SQL.
() ( 
() ).


18 , ,
PostgreSQL, ,
;
PostgreSQL, 
.
1 , ,
. PostgreSQL 
.
2 
, 1
( PostgreSQL). ,
,
.
3 PostgreSQL
UNIX, 
Windows.
.

16

4 SQL 
SELECT. ,
PostgreSQL , 
.
5 psql ( 
PostgreSQL), pgAdmin pgAccess. 
, Microsoft Office (Microsoft Excel
Microsoft Access) .
6 
INSERT 
TRUNCATE.
7 4 
SQL: SELECT
, . .
8
, .
9 ,
ACID, ANSI .
10, , 
PostgreSQL, 
PL/pgSQL.
11 
. , , 
, . .
12 . 
, .
13
C.
14 , 
, PostgreSQL C
SQL , 
ecpg , 
.
15 PostgreSQL
PHP, PostgreSQL
PHP. PEAR
.
16 PostgreSQL Perl. 
,
Perl, Perl DBI DBIx,
.

17

17 Java, JDBC
PostgreSQL.
, 3.0 JDBC
API.
18 ,
PostgreSQL.
, .



. , 
. :


.

, .
, , 
, . !

 test.sql, , ,
.
, Control Panel,
.

. 
, psql, 
. , 
,
:
SELECT * FROM item;

, :
for(n = 0; n < nfields; n++) {
if(PQgetisnull(result, r, n))
printf(" %s is NULL,", PQfname(result, n));
else
printf(" %s = %s(%d),",
PQfname(result, n),
PQgetvalue(result, r, n),
PQgetlength(result, r, n));
}

18

, 
,
( ).
,
, :
# SELECT * FROM item;

, :
item_id | description | cost_price | sell_price
+++
1 | Wood Puzzle |
15.23 |
21.95
2 | Rubic Cube
|
7.45 |
11.49
3 | Linux CD
|
1.99 |
2.49
4 | Tissues
|
2.11 |
3.99
5 | Picture Frame |
7.54 |
9.95
6 | Fan Small
|
9.23 |
15.75
7 | Fan Large
|
13.36 |
19.95
8 | Toothbrush
|
0.75 |
1.45
9 | Roman Coin
|
2.34 |
2.45
10 | Carrier Bag |
0.01 |
0.00
11 | Speakers
|
19.73 |
25.32
(11 rows)


, 
.
, 
.
, , , 
http://www.wrox.com.
, , 
. 
, . 
.

,
. ,
,
.

19


http://www.wrox.com. , 
, , .
,
, ,
,
.



, , 
[email protected], Subject
ISBN.
, 
. , ,
. , 
.
, 
. 
,
.
, 
,
.
,
. .
,
. ,
, .
Wrox . 

, .

P2P
Wrox , 
. , ,
, ,
,
P2P (http://p2p.wrox.com/).
P2P ,
. 
. ,

20

, 
 .
,
, 
. , 
,
, 
. (
), , 
( ).


,
. , 

,
, .
, ( )
. 
feed
[email protected]. .

1
PostgreSQL


(Open Source)
PostgreSQL. , 
Open Source PostgreSQL .
,
, PostgreSQL 
(),
,
.
PostgreSQL 
, C, C++, Perl, Python, Java, Tcl
PHP. 
, SQL92. 2000 Linux Journal
Editors Choice Award ( Linux Journal)
.
. , , ,
PostgreSQL .

, 
, ,
PostgreSQL.



, 

22

1. PostgreSQL

, ,
.
, 80% 
, 
, 
. 
.
, .
:

Linux (Beginning Linux Pro


gramming), , Wrox Press (ISBN
8173661561) DBM.

Linux (Professional
Linux Programming), , Wrox Press
(ISBN 1861003013) 
PostgreSQL MySQL.

, 
.
 , ,
, .

. 
, .

. 
, 
(),
.
 
,
, 
. .
. 
, 
.
, ,
.
.
, , 
, , 
.
,
.

23

 
; , 
, .
,
(flat). . 1.1:
1.1.
France

FRF

6.559570

Germany

DEM

1.955830

Italy

ITL

1936.270020

Belgium

BEF

40.339901

,

. ,
, .
, UNIX,

. UNIX.
, , 
,
, . ,
,
. ,
,
.
,
, , 
. 
,
. 
, 
,
, . 
, ,  ,

.
,
. 
,
. 
.

24

1. PostgreSQL

. 
: () 
, 
(), .
, , 
. 

, .
,

. , 
, .
,
. .
, DVD, 
, , .
,
.ini Windows:
[2001: A Space Odyssey]
year=1968
director=Stanley Kubrick
genre=science fiction
starring=Keir Dullea
starring=Leonard Rossiter
...
[Toy Story]
...

, 
.

,
.
. ,
? ,
,
?

,
. DVD,
,
, , 
,
,
 .

25

, . ,
, 
,

, , , 
. , 
, 
,
1968 ?.
,
, , 
, ,
.
.

?
MerriamWebster (http://www.mw. com)
,

(, ).
(), , 
, ,
, 
. 
.

.


196070 ,
.
. 
, , 
, IBM.

.
, , ,
( ).
. , 
 , ,

C. 

26

1. PostgreSQL

, 
.


, 
. , 
. 
. , 
. 
,
. 
, ,
, (. 1.1):

. 1.1.

( 
) (. 1.2):

. 1.2.

, , 
, .
, ,
. ,
, (
),
.
.

27

.
, 
(, , 
), , 
, .
, , . , 
, 
, 
. , 
,
, , 
, , 
.
, ,
, ,

.


1960 IBM IMS
.

.
, 
. ,
() , , 
.
. ,
.  
; , 
.
. 
,
,
, 
.



1970 , . . 
(E. F. Codd) 
(A Relational Model of Data for Large Shared Data
Banks), . http://www.acm.org/classics/nov95/toc.html. 

28

1. PostgreSQL


, , 
, 
, .
, ,

, , . 
, 
.

. , , 
PostgreSQL.
( ),
.
, 
. :
{"France", "FRF", 6.56}
{"Belgium", "BEF", 40.1}

:
( ), ( ) (
). , 
( ), ,
, , :
{"Germany", "DEM"}

{"Switzerland", "CHF", "French", "German", "Italian", "Romansch"}

{1936.27, "ITL", "Italy"}
( )

, .

.
, 
, , , 
, , 
. ,
, .
, 
, 
. ,
, . 
,
.

29

, , 
,  , 
.
, , , 
.
.

( ), ,

(, , ), 
. (
) , ,
.
, 
, . ,

. , 
, , , 
. ,
. CUSTOMER,
ORDERS. 
, .

.
, 
, ,
.


, , 
, ,
, 

. , 
, 
, ,

, .
,
,
. , 
, ,
.

30

1. PostgreSQL


.
QUEL, 
1970 Ingres.
, , QBE
(Query By Example ). 
, IBM, 
SQL (Structured Query
Language), .
SQL , 
ISO/IEC 9075:1992, Information Techno
logy Database Languages SQL (, , SQL92)
ANSI X3.1351992,
. 
SQL89. 
, SQL99, , 
SQL.
SQL92: Entry SQL, Intermediate
SQL Full SQL. Entry,
PostgreSQL , 
. 
, PostgreSQL
.
SQL :

Data Manipulation Language (DML) 

SQL, 90% .
, , , ,
.

Data Definition Language (DDL)



, ,
.

Data Control Language (DCL)


, . 

, , 
( ),
,
.

SQL ,
, , 
, , .

31

SQL
SQL
, , 
. 
SQL. , . . , 
SQL ,
,

.

. 
SQL, , ,
, 
, 

. SQL,
() Oracle, SQL Server PostgreSQL.
SQL ,
, , . 
, SQL,
.
SQL . 
, , 
:
CREATE TABLE item
(
item_id
description
cost_price
sell_price
);

serial,
char(64)
numeric(7,2),
numeric(7,2)

not null,

, , 
, 
. 
serial, ,
item , 
item_id. (description) , 
64 . (cost_price)
(sell_price) , 
.
SQL 
. :
INSERT INTO item(description, cost_price, sell_price)
values('Fan Small', 9.23, 15.75);

32

1. PostgreSQL
INSERT INTO item(description, cost_price, sell_price)
values('Fan Large', 13.36, 19.95);
INSERT INTO item(description, cost_price, sell_price)
values('Toothbrush', 0.75, 1.45);

SQL SELECT. 
( ),
.
. 
, 
UPDATE, , DELETE.
SELECT:
SELECT * FROM customer, orderinfo
WHERE orderinfo.customer_id = customer.customer_id GROUP BY customer_id
SELECT customer.title, customer.fname, customer.lname,
COUNT(orderinfo.orderinfo_id) AS "Number of orders" FROM customer, orderinfo
WHERE customer.customer_id = orderinfo.customer_id
GROUP BY customer.title, customer.fname, customer.lname

SELECT
, 
. 2,
SELECT 4.
PostgreSQL ,
:


SQL

SQL

API (Application Programming In


terfaces, ) 
SQL,

PostgreSQL
ODBC (Open Database Connection 
) JDBC (Java Database
Connectivity Java 
) , DBI Perl


, , ,
.
:

33



, 

.

, . . 
.


, 
,
, , 
. SQL 
, 
.


,
, 
.
, 
, ( )
 .
. , 

.
9.



. 
, ( , )
, 
.
, . .

.


,

, , (
, ). 
,
, ,
, 

34

1. PostgreSQL

, , .
,
, ,
.


, 
, . ,
,
.

PostgreSQL?
, PostgreSQL. ,

SQL.
PostgreSQL , 

. UNIX,
UNIX , FreeBSD Linux.
Windows NT Server Windows 2000 Server,
Microsoft 
, ME. , PostgreSQL
.
PostgreSQL .
, 
( Open Source), 
.
PostgreSQL (
PostgreSQL):

.
6.5 PostgreSQL 
, 

PostgreSQL?

35

, . 7.x Post
greSQL SQL92, 
.
PostgreSQL
. , 
. 

.
,
,
. , 
, Post
greSQL , .
,
.

PostgreSQL
PostgreSQL 1977 
. Ingres 
197785 . Ingres
,
.
Ingres Relational Technologies/In
gres Corporation, 
. In
gres CAINGRES II, Computer Associates.

( Postgres), 1986
1994 . , 
. 
Informix Illustra.  1994
Postgres SQL,
Postgres95.
1996 Postgres 
, 
, 
,
Postgres. , 
95 SQL, 
SQL Postgres. Post
greSQL.
PostgreSQL ,
, 
Open Source: Perl, Apache PHP. 

36

1. PostgreSQL

, , 
, . 
PostgreSQL http://www.postgresql.org.
GreatBridge ,
PostgreSQL. (
.)

PostgreSQL
PostgreSQL .
, PostgreSQL
, ,
.
PostgreSQL . 
. ( 
,
,
, 
.)

. 
,
, .

.
,
. , UNIX
,
Microsoft Windows.
(. 1.3) 
PostgreSQL:

. 1.3. PostgreSQL

PostgreSQL?

37

. PostgreSQL
TCP/IP
.
( Postmaster), 

.

, 
, ,
PostgreSQL 
.

PostgreSQL. 
,
, ODBC
JDBC. ODBC PostgreSQL
,
Microsoft Office, Excel Access. 
PostgreSQL
.
 . 

,
. 
. 
,

,
. 
.

Open Source*
XXI

. PostgreSQL. 
?
Open Source 
, . 
.
, .
 , 
.
Open Source ,


38

1. PostgreSQL

. PostgreSQL ,
.
Open Source ,
(
),  
.
Open Source, , ,
.
Open Source, 
,
. 

.
Berkeley Software Distribu
tion (BSD),
, . 
PostgreSQL BSD,
, 
: , 
, 
,
,
,
, .

.

PostgreSQL 
, , 
.

Tech Talk (David Frick) http://www.frick
cpa.com.
PostgreSQL http://www.postgresql.org,
, Post
greSQL, ,
, 
PostgreSQL.
PostgreSQL Great Bridge
http://www.greatbridge.com. Great Bridge 
Open Source http://www.greatbridge.org,
, PostgreSQL,

PostgreSQL?

39

, 
. .
Red Hat Database PostgreSQL.
Red Hat Database : http://www.redhat.com/pro
ducts/software/database/.
PostgreSQL Post
greSQL Inc. http://www.pgsql.com.
,
(Open Source
), :

http://www.gnu.org

http://www.opensource.org

, , , 
, PostgreSQL, 
. ,
, 
.
(
PostgreSQL) 
, 
PostgreSQL.
SQL.
, , :

NULL

41


, , Mic
rosoft Excel, 
. , 
. 
, 
, , , ,
.
, , 
,
. .

, 
, 
StarOffice,
(. 2.1):

. 2.1. StarOffice

, 
. , ,
, , 
.

42

2.

, 
. ,
,
, .


, 
.
, (. 2.2):

. 2.2.

.
StarOffice, , 52 The Willow
.



? , , , 
. 
, , ,

. 
.
,
. ,
( 
) , 
.
,
.
, , .
,
, ,

43

, ,
.
, ,
, . ,
, 
.
, 
.
, 
. , 
,
(. 2.3):

. 2.3.

, , . 
, ,
, .
.
, 
.
, 
. ,
. 
, 
, , , 
. ,

. (

44

2.

), 
. :

, , 

,


. ,
,  
.
,
,
.

?
, ,
PostgreSQL, , 
. 

,
, .
, ,
, , 
. 
, PostgreSQL 
.
, , 
, .
. 
,
. :
, 
.
, 
:

,
?

45

()?

, ?



.
: , , . .
.


,
.
,
. ,
 . 
,
, , 
, . 
PostgreSQL ,
8. ,
.
,
.
, ,
(+), 
. . ,
, 
, .
,
( 
), , , 
, .
. , (Mr,
Mrs, Dr) . , 
.
,
,
, , .

,
.
.

46

2.


, , 
, , 

, . , 

.
, ?
,
, . .
, 
.
, , ,
, . ,
.
,
, .

.
, , 
, (
, ) 
. 
? , 
, . . 
, , , , 
, .

. 
. 
, , , 
.
; 
,
,
. 
, PostgreSQL , se
rial, . 
.


, 
, 

47

,
. ,
,
 .


, , 
. 
, .
. 2.4 PostgreSQL (
psql 
Linux):

. 2.4. psql PostgreSQL

, , custo
mer_id, . 
.
.

48

2.

PostgreSQL
.
pgAccess (. 2.5):

. 2.5. PostgreSQL pgAccess


, 
, ,
, , 
.
PostgreSQL , , 
, 
. ,
, , 
. Microsoft Windows
ODBC. 
Windows,
ODBC, , .
4.

49

. 2.6 MS Access, 
( ODBC) Post
greSQL, Linux:

. 2.6. MS Access

, 
.

, 
, 
. , PostgreSQL 

. , 
, PostgreSQL 
.


.  
, , ,
, 
.

.
 ,
, . 
,
, ,
, ,
.

50

2.

, PostgreSQL, 
, 
. 
, ,
, . 9 
.


, ,
, , , .

.
, 
, .

, ,
.
. , 
, (Bing
ham). psql, Post
greSQL, , SQL 
.
SQL, , :
SELECT * FROM customer WHERE town = 'Bingham';

psql  
, ,
(. . 
, ). ,
, ,
, ,
.
PostgreSQL 
, , , Bingham
(. 2.7):

. 2.7.

51

, . 
SQL, 5.
customer_id, ,
.
, , 
. , , , 
, .

customer. fname lname. 
:
SELECT fname, lname FROM customer;

, PostgreSQL
(. 2.8):

. 2.8. ()

, 
, 
. SQL 
. , , 
(Bingham). 
SQL :
SELECT fname, lname FROM customer WHERE town = 'Bingham';

PostgreSQL (. 2.9):

. 2.9.

52

2.

, . 
, C Java,

,
. 
,
. , C, Java 
. , 
. SQL,
, , , 
PostgreSQL .
, , 
,
, , , 
, , , .
, .


,
,
. ,
, PostgreSQL,
.


, , 
( 
 ,
).
, ,
?
, , ,

, .
customer, ,
, 
.
, ,
, , .
customer, , 
( ,
, ). 
, ,

53

. ,
customer, , customer_id.
, , ,
,
, ! 
, . , 
, , 
,
( , , ).
, , !
, ,
(. 2.10) pgAccess, ,
, 
PostgreSQL . 4
:

. 2.10.

, . . 
.


,
, , 
.

54

2.

, ,
. , 
.
. 
( ), 
SQL.
, 
. , 
C, ,
, , customer, 
. 
, , 
. , SQL
. 
:

?
?
?


SQL. , , 
:
SELECT * FROM customers, orderinfo WHERE customer.customer_id =
orderinfo.customer_id;

,
, SQL, custo
mer_id customer ( . 
, )
, customer_id orderinfo.
, , 
, PostgreSQL (. 2.11):

. 2.11.

55

, 
, ,
, PostgreSQL (, 
,
). * , 
(, 
).

, ,
SQL. , 
. SQL,
:
SELECT customer.title, customer.fname, customer.lname,
count(orderinfo.orderinfo_id) AS "Number of orders" FROM customer, orderinfo
WHERE customer.customer_id = orderinfo.customer_id group by customer.title,
customer.fname, customer.lname;

, , ,
, , , , , ,
, SQL.
. PostgreSQL (. 2.12):

. 2.12.


SQL (
), ,
. ,  
Windows, , 

ODBC, . (. 2.13)
, StarOffice 
Windows NT (StarOffice Base
Microsoft Access Windows).
Linux,
.
, SQL

56

2.

. 2.13. , StarOffice

, ,
SQL,

. ,
SQL , ,
.


,
, , 
; , 
. (
, , 
, ) . 
, , ,
12.

57

,
, . ,
, , 
.


, ( 
) , , 
, .
, 
, ,
, , .

, , ,
. 12
.
.
( , ),
, , , 
, , 
, 12.
,
, 
SQL PostgreSQL.


, 
(). 
. 
, , ,
.

, . 
, 
. ? 
, ,
29 35 , . .
.
, , ,
. 
,
.

58

2.



,
, ,
. .

, ,
.
 , ,
, : X
, ,
.
, 
, ,
.
customer customer_id, 
.

customer,
 .

, . , 
, . 
. 
, ,
, , 
 . 
.
, ,
cus
tomer_id , 
.
, 
, ,
.

, .
? , 
,  .

59


, ,
, . , ,
 
, ( ,
). 
, , tablename_id, 
.
, . 
(. 12), ,
.

,
. 
, , , 
, 
.


() ,
.
. 2.14:

. 2.14.

, ,
, , customer_id ,
.
orderinfo customer. ,

60

2.

orderinfo customer,
.
, 
, . ,
, ,
customer_id. 
, foo
bar, .
(
, customer_id, customer_ident, cust_id cust_no)
.
,
.


, , 
, , , 
. ,
, 
. .
, , 
( , ,
). 
, . 
, ,
. ,
. 2.15:

. 2.15.

61

customer orderinfo,
, .
.

, , or
derinfo ,
( 
). 
(. 2.16):

. 2.16.


,
. 
. , ,

.
,
item ,

, ( 
!).
12, 
, . 
,
. , 
, , 
, orderline, .
, 
(. 2.17). , 
, orderinfo_id, , 
, item_id.
orderli
ne, . 

.

62

2.

. 2.17. orderline

, 
. , orderin
fo_id item_id . 
. ,
?
orderline , 
orderinfo_id item_id . 

, ? ,
. . 
(quantity) orderline, .


,
.
 , 
, .
,
, 
, .
, +20% 
, () ,

. ,

63

, , . : 
 .
 (. 2.18):

. 2.18. BARCODE

, BARCODE 
ITEM,  
. , barcode_ean 
, . . 
(
) 
.
, ,
, .
. 
, 
, , 
, item.

64

2.

, , 
 , 
, ,
, . , 
, .
500 000 , 1000,
.
.
, 
(, ),
,
. .
, 
. 
, , . 2.19:

. 2.19. stock

, stock
item_id, 
, 

65

item item_id. 
item, ,
.
, 
.
, , , ,
, 
(, ). ,
, , 
.
, 
, ,
(, orderinfo) . 
.


.
, ( 
PostgreSQL) ,
,
PostgreSQL .
,
,
, customer_id item_id. , , ,

, ,
, 
, . 
, , 
, 
.

, 
, SERIAL. 
, 

. 
, SERIAL, 
, 
.

.
. ,

66

2.


, SERIAL INTEGER, 
.
, , . 2.1.
2.1.

INTEGER

SERIAL

, 
. 
,
_id.

CHAR

, 
.
PostgreSQL
. CHAR(256) ,
256 , 
.

VARCHAR

, ( ) 
, , ,

. VARCHAR 
, . 
. 
, ,
VARCHAR? 
. 
, . 
, , ,
,
,
, . . ,
.

DATE

, . ,
,
( ).
.

NUMERIC


( ) 
( ). , NUMERIC(7,2) 
, .

PostgreSQL,
,  
, NUMERIC, ,
NUMERIC ,
PostgreSQL.

67

NULL
, NULL.
NULL , 
( 
).
orderinfo, ,
, DATE. 
, , ?
? , 
(sentinel value), ,
. UNIX 
1 1970 , . . UNIX
. 
, , , 
.
, .
, ,
. ,
, 
, , 

, ( 

).
, 
NULL, 
. , , 
, 
. 0 .
,
, 
. orderinfo NULL (
, ), 
.
NULL ( 
, ) (not relevant) .
, , ,
. ,
, , , .
NULL ,
, 
.

68

2.

NULL
NULL : 
NULL . ,
, NULL , ,
, .
SQL
NULL, , 
'IS NULL'.
NULL ,
,
NULL. ,
'NOT NULL', ,
NULL (, ,
). 
NULL,
. , , 
NULL 
, .


( ) 
, ,
. 
SQL 
PostgreSQL. 
, 
.
, 
,
, . , 
, ,
, , .
.
, ,
, .
, 
,
. 
.
PostgreSQL, 
.

69

,
, :

,
. 
, ,
(
).
, 
,
, .
, ,

(), .
,
PostgreSQL .

3
PostgreSQL

, Post
greSQL . 
Linux , , , PostgreSQL
. , 
UNIX,
UNIX.
, PostgreSQL Windows,
PostgreSQL 
, UNIX.
:

PostgreSQL Linux

PostgreSQL

PostgreSQL PostgreSQL

PostgreSQL

PostgreSQL Windows

Cygwin UNIX Windows

IPC Windows

PostgreSQL Windows

PostgreSQL Windows

71

PostgreSQL
Solaris. ,
. PostgreSQL Sola
ris . PostgreSQL,
Solaris, http://
www.greatbridge.org .

?
Linux,
PostgreSQL. 
. Postgre
SQL7.1.2. http://www.post
gresql.org ftp.
Linux,
, PostgreSQL. 
Linux ,
7.1.x, PostgreSQL , 
, Post
greSQL. ,
PostgreSQL, ,
.
Linux,
,
PostgreSQL.
PostgreSQL UNIX
, Linux Microsoft Windows.
Linux.
PostgreSQL:

PostgreSQL Linux;

PostgreSQL .

PostgreSQL Linux.

PostgreSQL Linux
, PostgreSQL Linux

, RedHat (Red
Hat Package Manager, RPM) . 
RPM :

RedHat 6.x 7.x

SuSe 6.4 7.x

72

3. PostgreSQL

TurboLinux 6.x

Caldera OpenLinux eServer 2.3

Mandrake 7.x

LinuxPPC 2000


. 
. 3.1:
3.1. ,

postgresql

postgresqlserver

postgresqldevel

postgresqljdbc

JDBC PostgreSQL Java

postgresqlodbc

ODBC PostgreSQL

postgresqlperl

Perl PostgreSQL

postgresqlpython

Python PostgreSQL

postgresqltcl

Tcl PostgreSQL

postgresqltest

PostgreSQL

postgresqltk

Tk

.

. ,
x 7.1.x.
RPM Package Mana
ger. , , 
(superuser/root). RPM
,
GnoRPM Kpackage. RPM
(superuser/root)
:
$ rpm i *.rpm


.
PostgreSQL , 
Linux, RedHat SuSe. ,
SuSe 7.x PostgreSQL YaST
(. 3.1) , . 3.1.

PostgreSQL Linux

73

. 3.1. YaST

CD 
( 
) PostgreSQL, 
.
http://www.greatbridge.com Great Bridge.
PostgreSQL , , ,
. 
RPM , 
, . 
, 
, , i u:
$ rpm u *.rpm

.
PostgreSQL.


11.

PostgreSQL
,
PostgreSQL . 
, 
.
PostgreSQL ,
. (postmaster postgres)

74

3. PostgreSQL

,
. , pg_ctl, 
, 
, . data
, . 
, .
PostgreSQL, 
. 3.2, . 
( 
) /usr/local/pgsql.
PostgreSQL 
:
3.2. PostgreSQL

bin

, pg_ctl postmaster

data

doc

HTML

include

PostgreSQL

lib

PostgreSQL

man

PostgreSQL

share

,
,
.
, PostgreSQL, 
.
. , , 

. , 
. , 
.

. Post
greSQL ,
, Linux
.
, SuSE 7.0 PostgreSQL
/usr/bin, 
/var/log/postgresql, /var/lib/pgsql/data.


. .

PostgreSQL Linux

75


. , 
, RPM, 
:
$ rpm q l postgres
/usr/bin/createdb
...
/usr/share/man/manl/vacuum.1.gz
$

, rpm
, PostgreSQL:
$ rpm q l pg_serv
/sbin/conf.d/SuSEconfig.Postgres
...
/var/lib/pgsql/data/pg_options
$

,
pg_serv. rpm 
, kpackage
(. 3.2), KDE:

. 3.2. kpackage

76

3. PostgreSQL

Linux ,
, . , 
, , 
.
PostgreSQL . ,
,
PostgreSQL.

PostgreSQL
RPM PostgreSQL
Linux, 
PostgreSQL UNIX .
, 
PostgreSQL http://www.postgresql.org.
,
. CD
. 
CD
PostgreSQL.
. 

postgresql7.1.2.tar.gz

7,5 .
,
:
postgresql7.1.2.base.tar.gz
postgresql7.1.2.docs.tar.gz
postgresql7.1.2.opt.tar.gz
postgresql7.1.2.test.tar.gz

, 
.
PostgreSQL . 
,
. , ,
. 
Linux UNIX
, 
C GNU make, .
Linux ,
GNU 

PostgreSQL

77

FSF. GNU C
(gcc), Linux. GNU
UNIX,
PostgreSQL. 
http://www.gnu.org.

PostgreSQL.
 
. , 
PostgreSQL, .
, 
,
. :
$ tar zxvf postgres7.1.2.tar.gz


/usr/src, 
,
( 50 ).
,
PostgreSQL. :
$ cd postgres7.1.2

INSTALL,
, 
.
configure, 

. configure
:
$ ./configure
creating cache ./config.cache
checking host system type... i686pclinuxgnu
checking which template to use... linux
...
$

configure ,
PostgreSQL, , 
. . configure
.
man.
configure .
PostgreSQL /usr/
local/pgsql, .

78

3. PostgreSQL

configure c 
. , . 3.3:
3.3. configure

prefix=PREFIX PREFIX. /usr/local/


psql
bindir=DIR

DIR. PREFIX/bin

withtcl

Tcl,
pgAccess

withperl

Perl

withpython

Python

help
:
$ ./configure help
Usage: configure [options] [host]
Options: [defaults in brackets after descriptions]
Configuration:
cachefile=FILE
cache test results in FILE
...
$


. 
, .
,
make.
PostgreSQL make, 
. GNUmake. Linux
, UNIX
GNUmake. gmake,
gmake, 
. make GNUmake.

:
$ make
...
All of PostgreSQL successfully made. Ready to install.

,

.

PostgreSQL

79

make 
. make,
:
$ su
# make install
...
Thank you for choosing PostgreSQL, the most advanced open source database
engine.
# exit
$

, , . ,
PostgreSQL, .
RPM.
, PostgreSQL.

PostgreSQL
PostgreSQL postmaster 
. 
.
,
.
,

, , .
PostgreSQL 
. postgres 
.

. postmaster 
.
,
PostgreSQL postgres.

. Linux (
root) useradd:
# useradd postgres

UNIX
, 
.
.

postmaster.

80

3. PostgreSQL

initdb ,
, .
( root) 
postgres :
# mkdir /usr/local/pgsql/data
# chown postgres /usr/local/pgsql/data

. 
, .
,
PostgreSQL post
gres, .
postgres,
(root), su:
$ su
# su postgres
pg$

post
gres PostgreSQL. 
, postgres,
pg$.
,
root. , 
, .

. postmaster
root.

initdb:
pg$ /usr/local/pgsql/bin/initdb D /usr/local/pgsql/data
This database system will be initialized with the user name "Postgres".
This user will own all the data files and must also own the server process.
...
Success.
pg$

, , 
, , D.
. 
D, postmaster,
.
, i, 
:
pg$ /usr/local/pgsql/bin/postmaster i D /usr/local/pgsql/data >logfile 2>&1 &

81

PostgreSQL

PostgreSQL .
,
pg_hba.conf. ,
( /usr/local/pgsql/data), 
, 
. ,
, PostgreSQL, 
, . 
,
.
,
.
, 
.
pg_hba.conf :
host

all

192.168.0.0

255.255.0.0

trust

, , IP
192.168, .
(logfile
postgres)
, 2>&1. 
, , 
.
, 
, . 
, , ,
psql. 
. 
. , 
postmaster :
pg$ /usr/local/pgsql/bin/psql
psql: FATAL 1: Database "postgres" does not exist in the system catalog.

: psql 

, , 
. , . .
postgres. , postmaster
.
psql, 
, d. 
PostgreSQL , 
. 

82

3. PostgreSQL

template1.

.
, 
, PostgreSQL.
h ( IP)
(
):
remote$ psql h 192.168.0.66 d template1
Welcome to psql, the PostgreSQL interactive terminal.
Type:

\copyright for distribution terms


\h for help with SQL commands
\? For help on internal slash commands
\g or terminate with semicolon to execute query
\q to quit
template1=# \q
remote$

,
postmaster .
, postmaster
. , ,
Linux UNIX. 
.
PostgreSQL Linux, ,
, RPM.
SuSE Linux PostgreSQL
/etc/rc.d/
init.d, postgres.

, , postmaster
, , 
/etc/rc.d. , postmaster 
postgres.
, PostgreSQL, 
, :
#!/bin/sh
# Script to start and stop PostgreSQL
SERVER=/usr/local/pgsql/bin/postmaster
PGCTL=/usr/local/pgsql/bin/pg_ctl
PGDATA=/usr/local/pgsql/data

PostgreSQL

83

OPTIONS=i
LOGFILE=/usr/local/pgsql/data/postmaster.log
case "$1" in
start)
echo n "Starting PostgreSQL..."
su l postgres c "nohup $SERVER $OPTIONS D $PGDATA >$LOGFILE 2>&1 &"
;;
stop)
echo n "Stopping PostgreSQL..."
su l postgres c "$PGCTL D $PGDATA stop"
;;
*)
echo "Usage: $0 {start|stop}"
exit 1
;;
esac
exit 0
Debian Linux su l su  .


, , MyPostgreSQL. chmod, 
:
# chmod a+rx MyPostgreSQL

, , PostgreSQL
:
MyPostgreSQL start
MyPostgreSQL stop

, System V
( Linux), 
. , SuSE Linux 
/etc/rc.d/init.d/MyPostgreSQL 
PostgreSQL 

:
/etc/rc.d/rc2.d/S25MyPostgreSQL
/etc/rc.d/rc2.d/K25MyPostgreSQL
/etc/rc.d/rc3.d/S25MyPostgreSQL
/etc/rc.d/rc3.d/K25MyPostgreSQL


.
.

84

3. PostgreSQL



, ,
, . 
, bpsimple, 
. , Post
greSQL, .
, , PostgreSQL , 
postmaster :
$ ps el | grep post

postmaster (
), , PostgreSQL .
PostgreSQL
.
,
PostgreSQL. createuser.
su ( root)
postgres. createuser, 
.
PostgreSQL. neil
( UNIX/Linux):
$ su
# su postgres
pg$ /usr/local/pgsql/bin/createuser neil
Shall the new user be able to create databases? (y/n) y
Shall the new user be able to create new users (y/n) n
CREATE USER
pg$

neil
, .
, PostgreSQL 
, .
( root) :
$ /usr/local/pgsql/bin/createdb bpsimple
CREATE DATABASE
$

() , 
psql:
$ /usr/local/pgsql/bin/psql d bpsimple
Welcome to psql, the PostgreSQL interactive terminal.
...
bpsimple=#

PostgreSQL

85

PostgreSQL
. /q.


bpsimple ,
psql,
Wrox, 
\i <>, ,
. ,
:
bpsimple=# \i create_tables.sql
CREATE TABLE
...
bpsimple=#


( , , ). 

. .
create_tables.sql, , SQL
:
create table customer
(
customer_id
title
fname
lname
addressline
town
zipcode
phone
CONSTRAINT
);
create table item
(
item_id
description
cost_price
sell_price
CONSTRAINT
);
create table orderinfo
(

serial
,
char(4)
,
varchar(32)
,
varchar(32)
not null,
varchar(64)
,
varchar(32)
,
char(10)
not null,
varchar(16)
,
customer_pk PRIMARY KEY(customer_id)

serial
,
varchar(64)
not null,
numeric(7,2)
,
numeric(7,2)
,
item_pk PRIMARY KEY(item_id)

86

3. PostgreSQL

orderinfo_id
customer_id
date_placed
date_shipped
shipping
CONSTRAINT

serial
,
integer
not null,
date
not null,
date
,
numeric(7,2)
,
orderinfo_pk PRIMARY KEY(orderinfo_id)

);
create table stock
(
item_id
quantity
CONSTRAINT
);
create table orderline
(
orderinfo_id
item_id
quantity
CONSTRAINT
);
create table barcode
(
barcode_ean
item_id
CONSTRAINT
);

integer
not null,
integer
not null,
stock_pk PRIMARY KEY(item_id)

integer
integer
integer
orderline_pk PRIMARY

not null,
not null,
not null,
KEY(orderinfo_id, item_id)

char(13)
not null,
integer
not null,
barcode_pk PRIMARY KEY(barcode_ean)



, . 
drop_tables.sql:
drop table barcode;
drop table orderline;
drop table stock;
drop table orderinfo;
drop table item;
drop table customer;

PostgreSQL

87

drop sequence customer_customer_id_seq;


drop sequence item_item_id_seq;
drop sequence orderinfo_orderinfo_id_seq;
: ,
!

,
create_tables.sql , .


, ,
.
pop_tablename.sql.
, , ,
. ,
, ,
.

, . 
, psql,
SQL.

customer
insert into customer(title, fname, lname, addressline, town, zipcode, phone)
values('Miss','Jenny','Stones','27 Rowan Avenue','Hightown','NT2 1AQ','023
9876');
insert into customer(title, fname, lname, addressline, town, zipcode, phone)
values('Mr','Andrew','Stones','52 The Willows','Lowtown','LT5 7RA','876
3527');
insert into customer(title, fname, lname, addressline, town, zipcode, phone)
values('Miss','Alex','Matthew','4 The Street','Nicetown','NT2 2TX','010
4567');
insert into customer(title, fname, lname, addressline, town, zipcode, phone)
values('Mr','Adrian','Matthew','The Barn','Yuleville','YV67 2WR','487
3871');
insert into customer(title, fname, lname, addressline, town, zipcode, phone)
values('Mr','Simon','Cozens','7 Shady Lane','Oahenham','OA3 6QW','514
5926');
insert into customer(title, fname, lname, addressline, town, zipcode, phone)
values('Mr','Neil','Matthew','5 Pasture Lane','Nicetown','NT3 7RT','267
1232');

88

3. PostgreSQL

insert into customer(title, fname, lname, addressline, town, zipcode, phone)


values('Mr','Richard','Stones','34 Holly Way','Bingham','BG4 2WE','342 5982');
insert into customer(title, fname, lname, addressline, town, zipcode, phone)
values('Mrs','Ann','Stones','34 Holly Way','Bingham','BG4 2WE','342 5982');
insert into customer(title, fname, lname, addressline, town, zipcode, phone)
values('Mrs','Christine','Hickman','36 Queen Street','Histon','HT3 5EM','342
5432');
insert into customer(title, fname, lname, addressline, town, zipcode, phone)
values('Mr','Mike','Howard','86 Dysart Street','Tibsville','TB3 7FG','505
5482');
insert into customer(title, fname, lname, addressline, town, zipcode, phone)
values('Mr','Dave','Jones','54 Vale Rise','Bingham','BG3 8GD','342 8264');
insert into customer(title, fname, lname, addressline, town, zipcode, phone)
values('Mr','Richard','Neill','42 Thached way','Winersby','WB3 6GQ','505
6482');
insert into customer(title, fname, lname, addressline, town, zipcode, phone)
values('Mrs','Laura','Hendy','73 Margeritta Way','Oxbridge','OX2 3HX','821
2335');
insert into customer(title, fname, lname, addressline, town, zipcode, phone)
values('Mr','Bill','O\'Neill','2 Beamer Street','Welltown','WT3 8GM','435
1234');
insert into customer(title, fname, lname, addressline, town, zipcode, phone)
values('Mr','David','Hudson','4 The Square','Milltown','MT2 6RT','961 4526');

item
insert into item, (description, cost_price, sell_price) values('Wood Puzzle',
15.23, 21.95);
insert into item(description, cost_price, sell_price) values('Rubic Cube',
7.45, 11.49);
insert into item(description, cost_price, sell_price) values('Linux CD',
1.99, 2.49);
insert into item(description, cost_price, sell_price) values('Tissues',
2.11, 3.99);
insert into item(description, cost_price, sell_price) values('Picture
Frame', 7.54, 9.95);
insert into item(description, cost_price, sell_price) values('Fan Small',
9.23, 15.75);
insert into item(description, cost_price, sell_price) values('Fan Large',
13.36, 19.95);
insert into item(description, cost_price, sell_price) values('Toothbrush',
0.75, 1.45);
insert into item(description, cost_price, sell_price) values('Roman Coin',
2.34, 2.45);
insert into item(description, cost_price, sell_price) values('Carrier Bag',
0.01, 0.0);
insert into item(description, cost_price, sell_price) values('Speakers',
19.73, 25.32);

89

PostgreSQL

barcode
insert
insert
insert
insert
insert
insert
insert
insert
insert
insert
insert
insert
insert
insert

into
into
into
into
into
into
into
into
into
into
into
into
into
into

barcode(barcode_ean,
barcode(barcode_ean,
barcode(barcode_ean,
barcode(barcode_ean,
barcode(barcode_ean,
barcode(barcode_ean,
barcode(barcode_ean,
barcode(barcode_ean,
barcode(barcode_ean,
barcode(barcode_ean,
barcode(barcode_ean,
barcode(barcode_ean,
barcode(barcode_ean,
barcode(barcode_ean,

item_id)
item_id)
item_id)
item_id)
item_id)
item_id)
item_id)
item_id)
item_id)
item_id)
item_id)
item_id)
item_id)
item_id)

values('6241527836173',
values('6241574635234',
values('6264537836173',
values('6241527746363',
values('7465743843764',
values('3453458677628',
values('6434564564544',
values('8476736836876',
values('6241234586487',
values('9473625532534',
values('9473627464543',
values('4587263646878',
values('9879879837489',
values('2239872376872',

1);
2);
3);
3);
4);
5);
6);
7);
8);
8);
8);
9);
11);
11);

orderinfo
insert into orderinfo(customer_id, date_placed,
values(3,'03132000','03172000', 2.99);
insert into orderinfo(customer_id, date_placed,
values(8,'06232000','06242000', 0.00);
insert into orderinfo(customer_id, date_placed,
values(15,'09022000','09122000', 3.99);
insert into orderinfo(customer_id, date_placed,
values(13,'09032000','09102000', 2.99);
insert into orderinfo(customer_id, date_placed,
values(8,'07212000','07242000', 0.00);

date_shipped, shipping)
date_shipped, shipping)
date_shipped, shipping)
date_shipped, shipping)
date_shipped, shipping)

orderline
insert
insert
insert
insert
insert
insert
insert
insert
insert
insert
insert
insert

into
into
into
into
into
into
into
into
into
into
into
into

orderline(orderinfo_id,
orderline(orderinfo_id,
orderline(orderinfo_id,
orderline(orderinfo_id,
orderline(orderinfo_id,
orderline(orderinfo_id,
orderline(orderinfo_id,
orderline(orderinfo_id,
orderline(orderinfo_id,
orderline(orderinfo_id,
orderline(orderinfo_id,
orderline(orderinfo_id,

item_id,
item_id,
item_id,
item_id,
item_id,
item_id,
item_id,
item_id,
item_id,
item_id,
item_id,
item_id,

quantity)
quantity)
quantity)
quantity)
quantity)
quantity)
quantity)
quantity)
quantity)
quantity)
quantity)
quantity)

stock
insert into stock(item_id, quantity) values(1,12);
insert into stock(item_id, quantity) values(2,2);
insert into stock(item_id, quantity) values(4,8);

values(1,
values(1,
values(1,
values(2,
values(2,
values(2,
values(2,
values(3,
values(3,
values(4,
values(5,
values(5,

4, 1);
7, 1);
9, 1);
1, 1);
10, 1);
7, 2);
4, 2);
2, 1);
1, 1);
5, 2);
1, 1);
3, 1);

90

3. PostgreSQL

insert
insert
insert
insert

into
into
into
into

stock(item_id,
stock(item_id,
stock(item_id,
stock(item_id,

quantity)
quantity)
quantity)
quantity)

values(5,3);
values(7,8);
values(8,18);
values(10,1);

, , 
, PostgreSQL.

PostgreSQL
, PostgreSQL
.
.
,
postgres root pg_ctl:
# /usr/local/pgsql/bin/pg_ctl D /usr/local/pgsql/data stop

, ,
:
# /etc/rc.d/init.d/MyPostgreSQL stop

psql, createuser createdb


,
man, , PostgreSQL.
PostgreSQL 
. 
UNIX 
(.profile .bashrc):
PATH=$PATH:/usr/local/pgsql/bin
MANPATH=$MANPATH:/usr/local/pgsql/man
export PATH MANPATH

, 
PostgreSQL http://www.post
gresql.org. PostgreSQL
18.

PostgreSQL Windows
Windows.
PostgreSQL UNIX ,

91

PostgreSQL Windows

. 
PostgreSQL
Windows, 7.1 PostgreSQL 
, Microsoft Windows NT4
Windows 2000. 
, UNIX
Windows.
,
Linux UNIX . 
, UNIX
Windows ,
postmaster .
. ,

Post
greSQL, psql, , 
,
Windows.

Cygwin UNIX! Windows


, Microsoft Win
dows, Cygnus Solutions ( Red Hat)
, UNIX API
Windows NT 2000. DLL , 
UNIX Linux, Windows. 
, 
, ,
, , 
.
Cygwin
http://www.cygwin.com. ,
Cygwin Windows 
PostgreSQL.
, http://www.cyg
win.com Install Cygwin
now (. 3.3).
,

, .
Windows

.

. 3.3.
Cgwin

Cygwin 40 .

92

3. PostgreSQL

setup.exe, (. 3.4).

, Cygwin.
. 
.
, (. 3.5). 
,
.

. 3.4.

. 3.5.


setup.exe Install from Local Directory,
.

(. 3.6). Internet Explorer 5 
, setup.exe .

. 3.6.

, .
, (. 3.7), 
Cygwin, 
. ,
.

93

PostgreSQL Windows

. 3.7.


Cygwin (. 3.8).
, 
. PostgreSQL 
.

. 3.8.

,  , 
, skip. 

94

3. PostgreSQL

, . ,
. setup.exe
(. 3.9):

. 3.9.

setup.exe
,
(. 3.10):

. 3.10.

Cygwin. 
Cygwin , 
UNIX Linux.
bin, lib, usr . .
NT/2000 (. 3.11):

. 3.11.

UNIX
(Default Text File Type), 

PostgreSQL Windows

95

, Cygwin,
.
Cygwin
Windows , 

.
(Programmers File Editor, PFE), 
. PFE 
http://www.lancs.ac.uk/people/cpaap/pfe.
UNIX vi emacs Cygwin.
Install For All ( ),
Cygwin Windows,
.
, postgres Cygwin.
, , ;
.

Cygnus (. 3.12), UNIX
Windows:

. 3.12.

96

3. PostgreSQL

Cygwin GNU C,
Bash
PostgreSQL.

IPC Windows
,
PostgreSQL Windows, IPC, 
. 
, Cygwin,
CygIPC http://www.neuro.gatech.edu/users/cwil
son/cygutils/V1.1/cygipc.
CygIPC . 
Cygwin:
$ cd /
$ tar zxvf cygipc1.092.tar.gz

PostgreSQL Cygwin
2.29 Cygwin
PostgreSQL, 
Cygwin. PostgreSQL 
/usr/bin, /usr/lib,
/usr/share.

PostgreSQL Windows
PostgreSQL Windows NT/
2000 , Linux UNIX,
.
(postgresql7.1.2.tar.gz)
Cygwin, /usr/src.
Cygwin Windows Explorer 
, Cygwin.

configure make, 
UNIX:
$
$
$
$
$

tar zxvf postgresql7.1.2.tar.gz


cd postgres7.1.2
./configure
make
make install

PostgreSQL /usr/local/pgsql.

97

PostgreSQL Windows

PostgreSQL Windows
UNIX Linux, PostgreSQL postmaster
. 
, postgres.
,
postgres 
. . 
Windows, 
.
postgres 
Cygwin bash.
postmaster,
, IPC UNIX.
$ /usr/local/bin/ipcdaemon.exe &

,
UNIX Linux:
pg$ /usr/local/pgsql/bin/initdb D /usr/local/pgsql/data

, 
postmaster pg_hba.conf,
:
host

all

192.168.0.0

255.255.0.0

trust

, , IP
192.168, .
, :
pg$ /usr/local/pgsql/bin/postmaster i D /usr/local/pgsql/data
>logfile 2>&1 &

, :
$ /usr/local/pgsql/bin/createuser neil
$ /usr/local/pgsql/bin/createdb test

psql , ,
. , Post
greSQL Windows 2000, Li
nux (. 3.13 3.14).
Windows, Cygwin 
bash
$ /usr/local/pgsql/bin/psql d test

98

3. PostgreSQL

. 3.13. PostgreSQL Windows

. 3.14. PostgreSQL Linux

PostgreSQL Windows

99

PostgreSQL
PostgreSQL . , 
Windows NT 2000, 
PostgreSQL, 
postgres (ipcdaemon postmaster)
, .

, , .
, Windows 
. Windows.

, , ,
Windows .
, PostgreSQL 
, . ,
, .

: INSTSRV SRVANY. Windows NT4 Resource Kit 
.
Windows 2000. SRVANY 
ftp://ftp.microsoft.com/bussys/winnt/winntpublic/reskit/nt40/.
.
Windows , . . 
. , 
.
instsrv.exe srvany.exe . 
srvany.exe
PostgreSQL. , 
C:\NTRESKIT.
Windows, 
srvany.exe, , , 
, .
IPC.

IPC, INSTSRV
SRVANY. cygipc 1.09, 
README .

, ,
instsrv.exe:
C:\NTRESKIT> instsrv "IPC Daemon"
c:\ntreskit\srvany.exe

100

3. PostgreSQL
The service was successfully added!
Make sure that you go into the Control Panel and use
the Services applet to change the Account Name and
Password that this newly installed service will use
for its Security Context.
C:\NTRESKIT>

,
, ,
postgres. (Services)
(MMC).1 
postgres , 
(. 3.15). 
, ,
.\postgres, . 3.15:

. 3.15. PostgreSQL
1

 .
. .

PostgreSQL Windows

101

regedit.exe,
IPC. 
srvany.exe, ipcda
emon.exe .
regedit.exe
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services

IPC Daemon.
Parameters, , Applica
tion AppDirectory. ipcda
emon.exe /bin, Cygwin.
, F:\cygwin\usr\local\bin\ipcdaemon.exe
F:\cygwin\bin .
(. 3.16):

. 3.16.

(Services) 
(Administrative Tools) (Con
trol Panel) Windows 2000.

102

3. PostgreSQL

ipcdaemon.exe , 
Windows (Windows ask Manager) (. 3.17):

. 3.17. Windows

postmas
ter. SRVANY.
C:\NTRESKIT> instsrv "PostgreSQL" c:\ntreskit\srvany.exe

,
, IPC, 
postgres. , ,
.\postgres .
postmaster UNIX
Cygwin, 
. srvany.exe , cmd.exe 
Windows. ,
. 
Cygwin, , , 
.  postmaster.
, .
bash Cygwin /usr/local/bin 
startpg. ( UNIX) 
:

103

#!/bin/bash
# Start PostgreSQL
PGDATA=/usr/local/pgsql/data
PATH=/bin:/usr/bin:/usr/local/bin:/usr/local/pgsql/bin
export PGDATA PATH
postmaster i >/usr/local/pgsql/postmaster.log 2>&1 </dev/null

PostgreSQL.
regedit.exe
. , HKEY_LOCAL_MAC
HINE\SYSTEM\CurrentControlSet\Services. 
PostgreSQL.
Parameters, 
, . 3.4:
3.4. Parameters

Application

cmd.exe

AppDirectory

f:\cygwin\bin

AppParameters

/c "f:\cygwin\bin\bash.exe /usr/local/bin/startpg"

PostgreSQL.
, ,
. , postmaster 
postgres.exe, . .
postmaster.
:
,
PostgreSQL , postgres.
, .

Post
greSQL. 
. PostgreSQL 
, 
UNIX .
,
Linux, 
UNIX Windows NT/2000 Cygwin.

SQL
.
, 
.
PostgreSQL.

, 
psql.
SQL
SELECT.
SELECT. ,
, , SELECT 
SQL. 
, , ,
SQL .
, SELECT 

. SQL
. SQL , 
. ,
, ,
'Newtown' 'newtown'.
psql, 
, 
, PostgreSQL SQL.

psql

105

psql

SELECT

, 
2 3.

psql
, 3,
bpsimple, .
PostgreSQL postgres, 
, .
Linux, root,
.

bpsimple psql,
:
$ psql d bpsimple

:
Welcome to psql, the PostgreSQL interactive terminal.
Type: \copyright for distribution terms
\h for help with SQL commands
\? for help on internal slash commands
\g or terminate with semicolon to execute query
\q to quit
bpsimple=#

. psql pg_sha
dow, ,
. su postgres,

106

4.

createuser < > 'y'. 


, 
createdb, bpsimple. ,
psql, bpsimple=#.
,
, ,
.
, , \dt
<Enter>:
bpsimple=# \dt
List of relations
Name
| Type | Owner
++
barcode
| table
| rick
customer
| table
| rick
item
| table
| rick
orderinfo
| table
| rick
orderline
| table
| rick
stock
| table
| rick
bpsimple=#

rick owner .
psql
( 5), . 4.1, 
<Enter>:
4.1. psql

\?

\do

\dt

\dT

\h <>

SQL

\i < >

\r

( )

\g

psql

Linux 
.
psql GNU readline,
.
SQL PostgreSQL. 


SELECT

107

, PostgreSQL, 
psql. , , 
5,
psql.

SELECT
, Post
greSQL SELECT. ,
SQL,
.
SELECT : 
, . 
, FROM :
SELECT < > FROM <>


, '*' .

.
item:
SELECT * FROM item;

, ';' psql , 
. , 
SQL. \g, 
psql .
SQL , , .
<Enter> :
bpsimple=# SELECT * FROM item;
item_id | description | cost_price | sell_price
+++
1 | Wood Puzzle |
15.23 |
21.95
2 | Rubic Cube
|
7.45 |
11.49
3 | Linux CD
|
1.99 |
2.49
4 | Tissues
|
2.11 |
3.99
5 | Picture Frame |
7.54 |
9.95
6 | Fan Small
|
9.23 |
15.75
7 | Fan Large
|
13.36 |
19.95
8 | Toothbrush
|
0.75 |
1.45
9 | Roman Coin
|
2.34 |
2.45
10 | Carrier Bag |
0.01 |
0.00
11 | Speakers
|
19.73 |
25.32
(11 rows)
bpsimple=#

108

4.


PostgreSQL 
item, '*' , 
PostgreSQL , 
'|'.
, .
, ? 
, PostgreSQL, ,
, . 

. .
SQL 
(. 14), , 
. ,
'*', , 
, , .
, SQL
, . .
, 
, .
, , , 

.
.
, ,
. ,
, ,
.

.

, , . 
PostgreSQL:
bpsimple=# SELECT town, lname FROM customer;
town
| lname
+
Hightown | Stones
Lowtown | Stones
Nicetown | Matthew
Yuleville | Matthew
Oahenham | Cozens
Nicetown | Matthew
Bingham | Stones
Bingham | Stones

SELECT
Histon
Tibsville
Bingham
Winersby
Oxbridge
Welltown
Milltown
(15 rows)

|
|
|
|
|
|
|

109

Hickman
Howard
Jones
Neill
Hendy
O'Neill
Hudson

bpsimple=#


PostrgreSQL ,
. ,
SELECT.


, , , 
.
, ( 7)
, ,
. ,
AS < >
SELECT. 
, . , , 
.
, lname Last Na
me,
SELECT town, lname AS "Last Name" FROM customer;


,
, . 
, 
, , , 
.
2 , , 
, . 
, 
. , 
.
,
.

110

4.

, , 
, 
. SQL , PostgreSQL,
 ,
.
, SELECT, 
ORDER BY, 
. :
SELECT < > FROM <> ORDER BY
<> [ASC | DESC]

ASC ( ascending 
) DESC ( descending ). 
. 
.

.

lname, ,
.
, , 
, ASC, . . 
. PostgreSQL:
bpsimple=# SELECT town, lname AS "Last Name" FROM customer ORDER BY town;
town
| Last Name
+
Bingham | Stones
Bingham | Stones
Bingham | Jones
Hightown | Stones
Histon
| Hickman
Lowtown | Stones
Milltown | Hudson
Nicetown | Matthew
Nicetown | Matthew
Oahenham | Cozens
Oxbridge | Hendy
Tibsville | Howard
Welltown | O'Neill
Winersby | Neill
Yuleville | Matthew
(15 rows)
bpsimple=#

, 
.

SELECT

111


. 
AS Last Na
me, , ORDER BY, 
, PosgteSQL .

. ,
town, Last Name .
, , Bingham Jo
nes Stones.
ORDER BY, 
. 
.

. ASC DESC
SELECT ,
, 
. .
PostgreSQL :
bpsimple=# SELECT town, lname FROM customer ORDER BY town DESC, lname ASC;
town
| lname
+
Yuleville | Matthew
Winersby | Neill
Welltown | O'Neill
Tibsville | Howard
Oxbridge | Hendy
Oahenham | Cozens
Nicetown | Matthew
Nicetown | Matthew
Milltown | Hudson
Lowtown | Stones
Histon
| Hickman
Hightown | Stones
Bingham | Jones
Bingham | Stones
Bingham | Stones
(15 rows)
bpsimple=#


,
town, ORDER BY. 
, ,

112

4.

. , Bingham 
, 
.
, , 
, , 
. PostgreSQL, , ,
, ORDER BY 
, .
SQL, 
.


, 
, :
Nicetown | Matthew
Bingham | Stones

? 
2 3, , Nicetown 
Matthew, Bingham 
Stones. 
:
Nicetown
Nicetown
Bingham
Bingham

|
|
|
|

Matthew
Matthew
Stones
Stones

|
|
|
|

Alex
Neil
Richard
Ann

PostgreSQL Nicetown Matthew


Bingham Stones, .
.
, ,
. ,
, .
, ,
, , , ,
. ,
:
bpsimple=# SELECT town FROM customer ORDER BY town;
town

Bingham
Bingham
Bingham
Hightown

SELECT

113

Histon
Lowtown
Milltown
Nicetown
Nicetown
Oahenham
Oxbridge
Tibsville
Welltown
Winersby
Yuleville
(15 rows)
bpsimple=#

, , , , 
.
customer PostgreSQL 
. , .
, ,
.
SQL 
DISTINCT SELECT. :
SELECT DISTINCT < > FROM <>

SELECT,
,
.

. DUISTINCT
, customer,
. :
bpsimple=# SELECT DISTINCT town FROM customer;
town

Bingham
Hightown
Histon
Lowtown
Milltown
Nicetown
Oahenham
Oxbridge
Tibsville
Welltown
Winersby

114

4.
Yuleville
(12 rows)
bpsimple=#


DISTINCT PostgreSQL 
. , 
. , PostgreSQL 
. , 
.
 , 
ORDER BY.
, DISTINCT  
. ,
,  
. :
SELECT DISTINCT town, fname FROM customer;

15 , . . 15 
.
. ,
SELECT,
. , DISTINCT
PostgreSQL
. DISTINCT,
, .
. DISTINCT
SQL,
. ,
DISTINCT , .


, , 
.
, 
item. SELECT:
bpsimple=# SELECT description, cost_price FROM item;
description | cost_price
+
Wood Puzzle |
15.23
Rubic Cube
|
7.45
Linux CD
|
1.99
Tissues
|
2.11

115


Picture Frame
Fan Small
Fan Large
Toothbrush
Roman Coin
Carrier Bag
Speakers
(11 rows)
bpsimple=#

|
|
|
|
|
|
|

7.54
9.23
13.36
0.75
2.34
0.01
19.73

, ,
. , SQL , 
:
bpsimple=# SELECT description, cost_price *100 FROM item;
description | cost_price
+
Wood Puzzle | 1523.00
Rubic Cube
| 745.00
Linux CD
| 199.00
Tissues
| 211.00
Picture Frame | 754.00
Fan Small
| 923.00
Fan Large
| 1336.00
Toothbrush
|
75.00
Roman Coin
| 234.00
Carrier Bag |
1.00
Speakers
| 1973.00
(11 rows)
bpsimple=#

, 
, .
CAST :
bpsimple=# SELECT description, CAST(cost_price *100 AS INT) FROM item;
description | cost_price
+
Wood Puzzle |
1523
Rubic Cube
|
745
Linux CD
|
199
Tissues
|
211
Picture Frame |
754
Fan Small
|
923
Fan Large
|
1336
Toothbrush
|
75
Roman Coin
|
234
Carrier Bag |
1
Speakers
|
1973
(11 rows)
bpsimple=#

116

4.

.
, , , ,
7. , 
.



, . , , 
, . , ,
, 
SELECT.
WHERE,
:
SELECT < > FROM <> WHERE <>

, 
AND, OR NOT.
. 4.2:
4.2.

<

<=

>=

>

<>

,
, , 
.
,
Bingham. :
bpsimple=# SELECT town, lname, fname FROM customer WHERE town = 'Bingham';
town | lname | fname
++
Bingham | Stones | Richard
Bingham | Stones | Ann
Bingham | Jones | Dave
(3 rows)
bpsimple=#

117

, ? 
, Bingham 
, .
, , Bingham ,
. town = 'bingham',
, . . 
.
, AND, OR,
NOT . , 
OR
DER BY, .

.
. ,
, Bingham Nice
town, .
:
bpsimple=# SELECT title, fname, lname, town FROM customer WHERE title <> 'Mr'
bpsimple# AND (town = 'Bingham' OR town = 'Nicetown');
title | fname | lname | town
+++
Miss | Alex | Matthew | Nicetown
Mrs | Ann | Stones | Bingham
(2 rows)
bpsimple=#


,
. SELECT 
. WHERE
, (Mr),
, , AND. 
, Bingham Nicetown.
,
.
, PostgreSQL,
, ,
SQL. ,
SQL.
, 
, , 
. , 
, ,

118

4.

. ,
, , .
, PostgreSQL SQL,
SQL explain (). PostgreSQL
, ,
.



. , ,
.
SQL ,
, .
IN,

OR. :
SELECT title, fname, lname, town FROM customer WHERE title <> 'Mr' AND (town =
'Bingham' OR town = 'Nicetown');

:
SELECT title, fname, lname, town FROM customer WHERE title <> 'Mr' AND town IN
('Bingham', 'Nicetown');

, , , ,
ORDER BY.
IN , 
. , , 
IN, .
BETWEEN. 
, .
, , cus
tomer_id 5 9. OR
IN 
:
bpsimple=# SELECT customer_id, town, lname FROM customer WHERE customer_id
bpsimple# BETWEEN 5 AND 9;
customer_id | town | lname
++
5 | Oahenham | Cozens
6 | Nicetown | Matthew
7 | Bingham | Stones
8 | Bingham | Stones
9 | Histon | Hickman
(5 rows)
bpsimple=#

119

BETWEEN , 
, 
, , , , 
.

.
BETWEEN . ,
, ,
B N. ,
, 
:
bpsimple=# SELECT DISTINCT town FROM customer
bpsimple# WHERE town BETWEEN 'B' AND 'N';
town

Bingham
Hightown
Histon
Lowtown
Milltown
(5 rows)
bpsimple=#

,
. Newtown?
N, .

, , ,
PostgreSQL, SQL92, 
,
. ,
Newtown, PostgreSQL N (
) Newtown, ASCII 
, ,
Newtown N .

.
,
z, BETWEEN
O. ,
O, ,
. z ASCII

120

4.

Z, .
, :
SELECT DISTINCT town FROM customer WHERE town BETWEEN 'B' AND 'Nz';

, Z B, . . B,
, , 
B. , 
Nzz, , Nz Nzz 
, Nzz Nz Nz 
, , z
, .
, 
SQL. 
BETWEEN .



, 
. SQL LIKE.
, LIKE 
,
. , 
. LIKE
(%) , 
(_) .
, ,
B, :
WHERE town LIKE 'B%'

, e, :
WHERE fname LIKE '%e';

, , 
:
WHERE fname LIKE '_ _ _ _';

.
,
a.

121

:
bpsimple=# SELECT fname, lname FROM customer WHERE fname LIKE '_a%';
fname | lname
+
Dave | Jones
Laura | Hendy
David | Hudson
(3 rows)
bpsimple=#


_a , 
, a 
. , %, .
%, 
.


,
, , . . 
, . 
, 
, , SQL
, , ,
.
.
PostgreSQL SELECT 
LIMIT, SQL,
, 
.
LIMIT
. SELECT LIMIT ,
.
LIMIT 
, . LIMIT M, N, N
, M .
, . 
:
bpsimple=# SELECT customer_id, town FROM customer LIMIT 5;
customer_id | town
+
1 | Hightown
2 | Lowtown

122

4.
3 | Nicetown
4 | Yuleville
5 | Oahenham
(5 rows)
bpsimple=#

, :
bpsimple=# SELECT customer_id, town FROM customer LIMIT 5,2;
customer_id | town
+
3 | Nicetown
4 | Yuleville
5 | Oahenham
6 | Nicetown
7 | Bingham
(5 rows)
bpsimple=#

LIMIT SELECT
, .


, 
. 2 NULL, 
. 
, . . NULL,
, 
.
, 
, PostgreSQL
.

NULL
, , 
NULL. ,
, . ,
testtab tryint, ,
0, 1, NULL. :
SELECT * FROM testtab WHERE tryint = 0;

:
SELECT * FROM testtab WHERE tryint = 1;

123

NULL, .
SQL
NULL, PostgreSQL .
, IS NULL:
SELECT * FROM testtab WHERE tryint IS NULL;

, IS, 
. , NULL,
NOT :
SELECT * FROM testtab WHERE tryint IS NOT NULL;


? , 
, , 
, ,
.
, NULL
.
, tryint
NULL:
SELECT * FROM testtab WHERE tryint = 1;

tryint = 1,
NULL? 
, . . 
, . , ,
NULL, .
tryint = 0, 
, .
, 
.
NULL .
, 
, , ,
NULL .


PostgreSQL,

.
PostgreSQL : TIMES
TAMP, , DATE ,
. PostgreSQL

124

4.

, 
.
( PostgreSQL),
.
, 
, . 
?
, 1/2/1997?
1997 , .
, DD/MM/YYYY,
MM/DD/YYYY. , 
, .
,
PostgreSQL .
PostgreSQL 
, ,
, , 
.


, , PostgreSQL
,
.
, :

: 

, PostgreSQL
, , 
, .
, , PostgreSQL 
ISO8601
: YYYYMMDD hh:mm:ss.sTZD. , 
19970201 05:23:43.23+5,
1 1997 , 5 23 43,23 .
TZD
(Time Zone Designator), .
NN/NN/NNNN PostgreSQL
, , 2/1/97 
1 .
February 1, 1997 ISO 19970201. 
, , ,
PostgreSQL , 

125

, 
.
,
PostgreSQL , .
, , 
. , 
DATESTYLE. ,
.
PostgreSQL , 
, .
psql :
SET DATESTYLE TO '';

, SQL, .

US European (. 4.3):
4.3.

US

02/01/1997

European

01/02/1997

DATESTYLE,
(. 4.4):
4.4.

ISO

ISO8601, '' 19970201


SQL

02/01/1997

Postgres

Sat Feb 01

German

01.02.1997

Postgres
DATE SQL, TIMESTAMP ,
.

DATESTYLE , 
. , SQL 
( ), :
SET DATESTYLE TO 'European, SQL';

126

4.

,

.
,
PGDATESTYLE
postmaster.
UNIX, Linux Cygwin :
PGDATESTYLE="European, SQL"
export PGDATESTYLE

postmaster,
, .

, ,
psql. 
.
, ,
CAST, .
PostgreSQL , 
, ,
.
DATE:
CAST('string' TO DATE)

, :
CAST('string' TO TIMESTAMP)

. , 
.
SELECT
, . , :
bpsimple=# SELECT 'Fred';
?column?

Fred
(1 row)
bpsimple=#

PostgreSQL ,
, SELECT 
, .
CAST,
, PostgreSQL ,
.

127

.
, PGDATES
TYLE, . 
, , 
. ISO, . . 
, PostgreSQL . 
:
bpsimple=# SELECT CAST('1997021' AS DATE);
?column?

19970201
(1 row)
bpsimple=#

US SQL : ( 1 
) ISO, . 
( ), 
MM/DD/YYYY:
bpsimple=# SET DateStyle TO 'US, SQL';
SET VARIABLE
bpsimple=# SELECT CAST('1997021' AS DATE);
?column?

02/01/1997
(1 row)
bpsimple=#

, datestyle psql:
bpsimple=# SHOW datestyle;
NOTICE: DateStyle is SQL with US (NonEuropean) conventions
SHOW VARIABLE
bpsimple=#

. ,
DD/MM/YYYY:
bpsimple=# SET DateStyle TO 'European, SQL';
SET VARIABLE
bpsimple=# SELECT CAST('1997021' AS DATE);
?column?

01/02/1997
(1 row)
bpsimple=#

128

4.

ISO . European
, ISO:
bpsimple=# SET DateStyle TO 'European, ISO';
SET VARIABLE
bpsimple=# SELECT CAST('1997021' AS DATE);
?column?

19970201
(1 row)
bpsimple=#

TIMESTAMP, .
, :
bpsimple=# SELECT CAST('1997021' AS TIMESTAMP);
?column?

19970201 00:00:00+00
(1 row)
bpsimple=#

PostgreSQL:
bpsimple=# SET DateStyle TO 'European, Postgres';
SET VARIABLE
bpsimple=# SELECT CAST('1997021' AS TIMESTAMP);
?column?

Sat 01 Feb 00:00:00 1997 GMT


(1 row)
bpsimple=#


, , 
,
'01/02/1997'.
.
TZ, PostgreSQL 
.


, , , 
, :
date_part(units required, value to use);
now()

, date_part(),
, .

129

, orderinfo ,
. , 
, :
bpsimple=# SELECT * FROM orderinfo WHERE date_part('month',date_placed)=9;
orderinfo_id | customer_id | date_placed | date_shipped | shipping
++++
3 |
15 | 20000902 | 20000912 |
3.99
4 |
13 | 20000903 | 20000910 |
2.99
(2 rows)
bpsimple=#

. ,
ISO. , DATE
TIMESTAMP, :

year
month
day
hour
minute
second

<>, <=, <, >, >=, =,


. :
bpsimple=# SELECT * FROM orderinfo WHERE date_placed >= CAST('20000721' AS
bpsimple# DATE);
orderinfo_id | customer_id | date_placed | date_shipped | shipping
++++
3 |
15 | 20000902 | 20000912 |
3.99
4 |
13 | 20000903 | 20000910 |
2.99
5 |
8 | 20000721 | 20000724 |
0.00
(3 rows)
bpsimple=#

,
CAST ISO.
, now(), .
, , , 

. now(),
:
bpsimple=# SELECT now();
now

20010203 17:06:20+00
(1 row)
bpsimple=#

130

4.

. ,
,
, :
bpsimple=# SELECT date_shipped date_placed FROM orderinfo;
?column?

4
1
10
7
3
(5 rows)
bpsimple=#

, 
.


, , 
, , 
. ,
.
SQL

. , 
SELECT
.


SQL , 
2 .
, customer, 
, orderinfo, 
. 
, 
.
customer_id, .
customer, 
customer_id , 
orderinfo, 
customer_id (. 4.1):

131

. 4.1. customer orderinfo

, 8 customer_id cus
tomer orderinfo,
customer_id. ,
, , 
, .
, ,
Ann Stones.
customer:
bpsimple=# SELECT customer_id FROM customer WHERE fname = 'Ann' AND lname =
bpsimple# 'Stones';
customer_id

8
(1 row)
bpsimple=#

customer_id , :
bpsimple=# SELECT * FROM orderinfo WHERE customer_id = 8;
orderinfo_id | customer_id | date_placed | date_shipped | shipping
++++
2 |
8 | 20000623 | 20000624 |
0.00
5 |
8 | 20000721 | 20000724 |
0.00
(2 rows)
bpsimple=#

, , 
customer_id. 2 ,
SQL . , 
, , 
. 
. 

132

4.

, .
.
, SQL , ,
, 'Ann Stones', 
, customer orderin
fo, customer_id,
.
, , 
WHERE:
SELECT < > FROM < > WHERE < > AND
< >

, . 
, , 
(8), .
, ( 
), ,
customer_id, ,
, customer_id = 8.
, . SQL, 
customer_id , custo
mer, , orderinfo? 
, ; , 
, ? 
:
tablename.columname


. , PostgreSQL ,
SELECT ,
. customer.fname, 
fname, 
SQL. , 
:
SELECT customer.fname, orderinfo.date_placed FROM customer, orderinfo;

PostgreSQL, 
.
. : ,
customer_id 8, , ,
(joined), customer_id. 
, AND,
:
WHERE customer.customer_id = 8 AND customer.customer_id = orderinfo.customer_id;

133

, , customer_id,
tablename.columname ,
, 8, . . 
, .
, :
bpsimple=# SELECT customer.fname, orderinfo.date_placed FROM customer,
bpsimple# orderinfo WHERE customer.customer_id = 8 AND customer.customer_id
bpsimple# =orderinfo.customer_id;
fname | date_placed
+
Ann | 06/23/2000
Ann | 07/21/2000
(2 rows)
bpsimple=#

, , ? 
, , ,
PostgreSQL .
, :
, Ann Stones,
customer_id.

.
, ,
SQL .
:
bpsimple=# SELECT customer.fname, orderinfo.date_placed FROM customer,
bpsimple# orderinfo WHERE customer.fname = 'Ann' AND customer.lname =
bpsimple# 'Stones' AND customer.customer_id = orderinfo.customer_id;
fname | date_placed
+
Ann | 20000623
Ann | 20000721
(2 rows)
bpsimple=#


,
(customer.fname, orderinfo.date_placed), (custo
mer, orderinfo), (customer.fname = 'Ann' AND custo
mer.lname = 'Stones') (customer.custo
mer_id = orderinfo.customer_id).
SQL . ,
, 

134

4.

, . SQL
, ,
.
. ,
. 
items, barcodes.
item_id,
. , , ,
, 
.
,
, , 
.
.
SQL :
bpsimple=# SELECT description, cost_price, barcode_ean FROM item, barcode
bpsimple# WHERE barcode.item_id = item.item_id ORDER BY cost_price;
description | cost_price | barcode_ean
++
Toothbrush
|
0.75 | 6241234586487
Toothbrush
|
0.75 | 9473625532534
Toothbrush
|
0.75 | 9473627464543
Linux CD
|
1.99 | 6264537836173
Linux CD
|
1.99 | 6241527746363
Tissues
|
2.11 | 7465743843764
Roman Coin
|
2.34 | 4587263646878
Rubic Cube
|
7.45 | 6241574635234
Picture Frame |
7.54 | 3453458677628
Fan Small
|
9.23 | 6434564564544
Fan Large
|
13.36 | 8476736836876
Wood Puzzle |
15.23 | 6241527836173
Speakers
|
19.73 | 9879879837489
Speakers
|
19.73 | 2239872376872
(14 rows)
bpsimple=#

, 
, (speakers) 
. , .
?
SQL
:
bpsimple=# SELECT * FROM item;

11 .

135

11 ,
14 .  ? , , ,
(Toothbrush), 
. PostgreSQL 
, . . 
.
, :
bpsimple=# SELECT item.item_id, description, cost_price, barcode_ean FROM
bpsimple# item, barcode WHERE barcode.item_id = item.item_id ORDER BY
bpsimple# cost_price;
item_id | description | cost_price | barcode_ean
+++
8 | Toothbrush
|
0.75 | 6241234586487
8 | Toothbrush
|
0.75 | 9473625532534
8 | Toothbrush
|
0.75 | 9473627464543
3 | Linux CD
|
1.99 | 6264537836173
3 | Linux CD
|
1.99 | 6241527746363
4 | Tissues
|
2.11 | 7465743843764
9 | Roman Coin
|
2.34 | 4587263646878
2 | Rubic Cube
|
7.45 | 6241574635234
5 | Picture Frame |
7.54 | 3453458677628
6 | Fan Small
|
9.23 | 6434564564544
7 | Fan Large
|
13.36 | 8476736836876
1 | Wood Puzzle |
15.23 | 6241527836173
11 | Speakers
|
19.73 | 9879879837489
11 | Speakers
|
19.73 | 2239872376872
(14 rows)
bpsimple=#

, ,
item_id, . . item
barcode.
, . , 
SELECT, ,
, ,
.


, ,
AS.
.
, ,
. ,

SQL.

136

4.

, 
FROM. 
SQL.
. ,
SQL:
SELECT lname FROM customer;

, 
:
SELECT customer.lname FROM customer;

cu, 
cu:
SELECT cu.lname FROM customer cu;

cu
.
.

.
:
SELECT customer.fname, orderinfo.date_placed FROM customer, orderinfo WHERE
customer.fname = 'Ann' AND customer.lname = 'Stones' AND customer.customer_id =
orderinfo.customer_id;

:
SELECT c.fname, o.date_placed FROM customer c, orderinfo o WHERE c.fname =
'Ann' AND c.lname = 'Stones' AND c.customer_id = o.customer_id;


,
? , . SQL 
, N ,
N+1 . ,
,
PostgreSQL,
,
.
, 
.
,
. customer, orde
rinfo orderline (. 4.2):

137

. 4.2.

, 
, . 4.3:

. 4.3. customer, orderinfo orderline

138

4.

, '123' 
orderinfo, orderinfo_id '579', '426', '723'
'114', , , 
orderline.
, customer orderline .
orderinfo, . . 
, .

.
, ,
Ann Stones.
:
SELECT customer.fname, customer.lname, orderinfo.date_placed,
orderline.item_id, orderline.quantity

:
FROM customer, orderinfo, orderline

orderinfo customer:
WHERE customer.customer_id = orderinfo.customer_id

orderinfo
orderline:
orderinfo.orderinfo_id = orderline.orderinfo_id

, :
customer.fname = 'Ann' AND customer.lname = 'Stones';

, :
bpsimple=# SELECT customer.fname, customer.lname, orderinfo.date_placed,
bpsimple# orderline.item_id,orderline.quantity
bpsimple# FROM customer, orderinfo, orderline
bpsimple# WHERE
bpsimple# customer.customer_id = orderinfo.customer_id AND
bpsimple# orderinfo.orderinfo_id = orderline.orderinfo_id AND
bpsimple# customer.fname = 'Ann' AND
bpsimple# customer.lname = 'Stones';
fname | lname | date_placed | item_id | quantity
++++
Ann | Stones | 20000623 |
1 |
1
Ann | Stones | 20000623 |
4 |
2
Ann | Stones | 20000623 |
7 |
2
Ann | Stones | 20000623 |
10 |
1
Ann | Stones | 20000721 |
1 |
1

139


Ann | Stones | 20000721 |
(6 rows)

3 |

bpsimple =#

, 
, SQL .
;, psql 
.

.
, ,
, Ann Sto
nes. , item, 
. :
bpsimple=# SELECT customer.fname, customer.lname, orderinfo.date_placed,
bpsimple# item.description, quantity
bpsimple# FROM customer, orderinfo, orderline, item
bpsimple# WHERE
bpsimple# customer.customer_id = orderinfo.customer_id AND
bpsimple# orderinfo.orderinfo_id = orderline.orderinfo_id AND
bpsimple# orderline.item_id = item.item_id AND
bpsimple# customer.fname = 'Ann' AND
bpsimple# customer.lname = 'Stones';
fname | lname | date_placed | description | quantity
++++
Ann | Stones | 20000623 | Wood Puzzle |
1
Ann | Stones | 20000721 | Wood Puzzle |
1
Ann | Stones | 20000721 | Linux CD
|
1
Ann | Stones | 20000623 | Tissues
|
2
Ann | Stones | 20000623 | Fan Large |
2
Ann | Stones | 20000623 | Carrier Bag |
1
(6 rows)
bpsimple= #


, , , 
. 
, item 
item
, orderline.item_id = item.item_id.
, Wood Puzzle , . .
.
SELECT
. :
,
.

140

4.


, , :
SELECT customer.fname, customer.lname, item.description
FROM customer, orderinfo, orderline, item
WHERE
customer.customer_id = orderinfo.customer_id AND
orderinfo.orderinfo_id = orderline.orderinfo_id AND
orderline.item_id = item.item_id AND
customer.fname = 'Ann' AND
customer.lname = 'Stones';

,
: ,
DISTINCT.

.
, , Ann
Stones. 
. ,
( ). 
item.description DISTINCT, 
, 
.
bpsimple=# SELECT DISTINCT item.description
bpsimple# FROM customer, orderinfo, orderline, item
bpsimple# WHERE
bpsimple# customer.customer_id = orderinfo.customer_id AND
bpsimple# orderinfo.orderinfo_id = orderline.orderinfo_id AND
bpsimple# orderline.item_id = item.item_id AND
bpsimple# customer.fname = 'Ann' AND
bpsimple# customer.lname = 'Stones'
bpsimple# ORDER BY item.description;
description

Carrier Bag
Fan Large
Linux CD
Tissues
Wood Puzzle
(5 rows)
bpsimple=#


SQL, ,
DISTINCT SELECT, 
, ORDER BY WHERE.

141

SQL:  ,
. , ORDER BY
, .

, .
SELECT. ,
, 
. , 
.
SQL 
. 
, 
. 

.
, 
SELECT, 
, SELECT, SQL
. SELECT 7,
,
, , 
.

5

PostgreSQL

PostgreSQL
psql, 
. , 
psql,
. , SQL*Plus, Oracle.

, , 
, . , 
: 
, . .
psql
PostgreSQL.
. , 
,
, , ,
. PostgreSQL 
11. , 
.
psql, 
:

psql

ODBC

pgAdmin

Kpsql

143

psql

PgAccess

Microsoft Access

Microsoft Excel

psql
psql ,
: 
, , , 
SQL.

psql
psql :
psql [] [ [ ]]

, psql ,
.
, .

, .
, 
psql:
$ psql d bpsimple

, ,

PGDATABASE, PGUSER, PGHOST PGPORT .
d, U, h p psql 
.
psql
.
: 
. 
postgres,
( 3). PostgreSQL
template1. , 
psql, \c
.

psql :
$ psql help

144

5. PostgreSQL

psql
psql .psqlrc,

. 
psql, 
, .
, psql
X.
, psql ,
, ,
=#. =>.
: SQL.
SQL, PostgreSQL, psql .
SQL 
\h : \h < SQL>.
\? .

psql ,
# >, , 
:
$ psql d bpsimple
...
bpsimple=#SELECT *
bpsimple#FROM customer
bpsimple#;
...
$

psql, SQL 
, .
, ,
SQL. 
, , WHERE .
psql S, 
, 
. psql
^>, , 
.
psql ,
SQL,
.

.

145

psql


, psql, 
, 
. 
.
, n
( ). 
\s : \s <>.
. 
\p, \r 
. \e
. vi (
, Linux UNIX), 
, EDITOR 
psql.

psql
psql ( SQL,
) .
\i psql .
,
bpsimple.
create_tables:
create table customer
(
customer_id
title
fname
lname
addressline
town
zipcode
phone
CONSTRAINT
);
create table item
(
item_id
description
cost_price
sell_price
CONSTRAINT
);

serial
,
char(4)
,
varchar(32)
,
varchar(32)
not null,
varchar(64)
,
varchar(64)
,
char(10)
not null,
varchar(16)
,
customer_pk PRIMARY KEY(customer_id)

serial
,
varchar(64)
not null,
numeric(7,2)
,
numeric(7,2)
,
item_pk PRIMARY KEY(item_id)

146

5. PostgreSQL

.sql 
\i:
bpsimple=#\i create_tables.sql
CREATE TABLE
CREATE TABLE

bpsimple=#


. ,

. 
, report.sql,
psql:
select count(*) from customer;
select count(*) from orderinfo;

psql f, 
:
$ psql f report.sql bpsimple
count

15
(1 row)
count

5
(1 row)
$

, 
o , 
\o .



psql.
\d ( , 
, ) .
\dt .
, 
\d :
bpsimple=# \d customer
Table "customer"
Attribute |
Type
|
Modifier
++

147

psql
customer_id | integer
title
| character(4)
fname
| character varying(32)
lname
| character varying(32)
addressline | character varying(64)
town
| character varying(32)
zipcode
| character(10)
phone
| character varying(16)
Index: customer_pk

| not null default nextval(...)


|
|
| not null
|
|
| not null
|

bpsimple=#

psql
,
PostgreSQL.



psql . 5.1:
5.1. psql

a

A


( P format=unaligned).

c <query>

( )
.

d <dbname>

( $PGDATABASE
).

e

, .

E

, .

f <filename> .
F <string>

( |)
( P fieldsep=<string>).

h <host>

( $PGHOST 
).

H

HTML
( P format=html).

l

n

o <filename> . |pipe 
.

148

5. PostgreSQL

5.1. ()

p <port>

( $PGPORT
, 5432).

P var[=arg]

var arg
(. \pset).

q

( 
).

R <string>

(
) ( P recordsep=<>).

s

( ).

S

(
, ).

t

( P tuples_only).

T <text>

(width, border) HTML


( P tableattr=<>).

U <username> ( $PGUSER
).
v name=val

psql name val.

V

W

( ,
).

x

( P expanded).

X

(~/.psqlrc).


, psql, . 5.2:
5.2. psql

\a


.

\c[onnect]
[dbname|
[user]]

.  ()
, 
.

\C <title>


( \pset title).

\copy ...

SQL COPY .

\copyright


PostgreSQL.

149

psql

\d <table>

( , , 
).

\d{t|i|s|v}

///.

\d{p|S|l}

/ /

\da

\dd [object]

, , , .

\df

\do

\dT

\e [file]

\echo <text>

(stdout).

\encoding
<encoding>
\f <sep>

\g [file]

( file
|pipe).

\h [cmd]

SQL, * 
.

\H

HTML.

\i <file>

\l

\lo_export,
\lo_import,
\lo_list,
\lo_unlink
\o [file]

\p

\pset <opt>

; :
format, border, expanded, fieldsep, null, recordsep, tuples_on
ly, title, tableattr, pager.

\q

psql.

file |pipe (
).

\qecho <text> (. \o).


\r

\s [file]

[file] .

\set <var>
<value>

150

5. PostgreSQL

5.2. ()

\t

( ).

\T <tags>

HTML.

\unset <var>

\w <file>

<file>.

\x

\z

\! [cmd]

ODBC

ODBC PostgreSQL. ODBC

X/Open ISO/IEC. ODBC 
(Open
DataBase Connectivity) ( )
Microsoft Windows.
ODBC  , 
, ODBC, 
.
PostgreSQL ODBC psqlodbc, 
, 
. 
,
. 
ODBC . 
, UNIX Linux, 
Windows.
, Microsoft Windows,
ODBC Great
Bridge.

psqlodbcregistry.zip

psqlodbc07_01_0003.zip

http:/
/www.greatbridge.org/project/pgadmin.
Microsoft Windows ODBC
(. 5.1):

151

ODBC

. 5.1. Windows


ODBC (. 5.2):

. 5.2. ODBC

152

5. PostgreSQL

ODBC PostgreSQL
. , (
DLL Windows) . , 
, ODBC
.
DLL psqlodbc.dll
psqlodbc07_01_0003.zip. 
SYSTEM , ,
C:\WINDOWS\SYSTEM Windows 9x/ME C:\WINNT\SYSTEM32
Windows NT/2000.
,
psqlodbc.reg,
psqlodbcregistry.zip.
.
ODBC PostgreSQL 
postdrv.exe.
, , Post
greSQL 6.4. , Great Bridge 
, 
.

, ,
, Drivers ODBC Data Source Administrator
( ODBC). PostgreSQL
(. 5.3):

. 5.3. PostgreSQL

153

ODBC

ODBC Post
greSQL. , 
(data source).
User DSN ODBC Data Source Administrator
, .
System DSN, ,
. Add,
(. 5.4):

. 5.4.

Finish.
PostgreSQL,
. PostgreSQL Driver Setup 
(. 5.5):

. 5.5.

154

5. PostgreSQL

Data Source , Description 


. IP
Linux. , DNS
WINS, .
,
.
Driver Data Source, 
.
ODBC, , Read
Only ( ).
PostgreSQL ODBC
. .
, ,
PostgreSQL, Microsoft Access,
pgAdmin.

pgAdmin
pgAdmin 
PostgreSQL.
Great Bridge
GNU GPL.
Great Bridge, pgAdmin 
, 
PostgreSQL. Windows 95/98/
ME NT/2000.
:

SQL Wizard

(plugin) , 
SQL

, , , 
, , ,

(Database Migration Wizard)

() , , 
, ,

(
Seagate Crystal Reports)

155

pgAdmin


pgAdmin, 
.
ODBC psqlodbc
PostgreSQL , 
pgAdmin. 
ODBC .
pgAdmin Microsoft Data Ac
cess Components 2.6 Runtime. 2.6
. mdac_type.exe
http://www.microsoft.com/data/downlo$
ad.htm.
pgAdmin Great Bridge
http://www.greatbridge.org/project/pgadmin/.
pgadmin710.zip .
Windows 9x NT (
Windows Me 2000), Microsoft Windows Installer
(instmsia.exe Windows 9x instmsiw.exe Windows NT), 
http://msdn.microsoft.com/downloads/ (
Windows Installer Redistributable).
pgAdmin:

OBDC psqlodbc PostgreSQL

MDAC 2.6
mdac_typ.exe

Windows Installer Windows 9x NT (instm


sia.exe instmsiw.exe)

pgAdmin.zip pgAdmin.msi 

pgAdmin.msi


(pgAdmin).
pgAdmin, ,
, . ,
pgAdmin .
, , ODBC 
, , 
. ODBC Data
Sources.
PostgreSQL
ReadOnly (. 5.6).

156

5. PostgreSQL

. 5.6.

Advanced Options
(. 5.7):

. 5.7.

, PostgreSQL,
( Show System Tables).
pgAdmin 
. pgAdmin
ODBC, (. 5.8):

157

pgAdmin

. 5.8.

, pgAdmin, , ,
, 
, , superuser.
, 
, (. 5.9):

. 5.9.

11.
PostgreSQL , 
postgres,
.
pgAdmin,
bpsimple lname customer (. 5.10):

. 5.10. pgAdmin

158

5. PostgreSQL

pgAdmin, ,
. 
, PostgreSQL, pgAd
min .

, (Comma Separated Variables,
CSV). , Microsoft Excel,
.
.
numbers test Excel.
CSV . ,
, 
. :
111,Nelson
0,Duck
22,Two Ducks

pgAdmin Tools | Im


port (. 5.11):

. 5.11.

, ,
, . 
.

(. 5.12).
Import Data,
.

159

Kpsql

. 5.12.

Kpsql
Linux psql
Kpsql Mutiny Bay Software. 
, Kpsql . 
KDE.
(1.0) http://www.mutinybaysoftware.com.
, Kpsql SQL.
, 
, SQL 
, . 

(. 5.13):

. 5.13. SQL$ Kpsql

160

5. PostgreSQL

, , 
.
.
Kpsql ,
SQL Post
greSQL.

PgAccess
PostgreSQL 
PgAccess,
PostgreSQL. :

, ,

PgAccess Tcl/Tk , 
Tcl/Tk 8.0 . 

, Linux Microsoft Windows.
Linux, Windows.
, PgAccess .
PostgreSQL, , ,
src/bin .
http://www.flex.ro/pgaccess.

PgAccess 
PgAccess, PATH_TO_WISH
( wish Tcl/Tk) PGACCESS_HOME (, 
PgAccess).
PgAccess
:
pgaccess [dbname]

, PgAccess
, .
,
.pgaccessrc .

161

PgAccess



PgAccess 

(. 5.14):

. 5.14. PgAccess
pgAdmin,
, pgAdmin 
. PgAccess
.

PgAccess :
, .

Open (. 5.15):

. 5.15. customer PgAccess

162

5. PostgreSQL

,
. 
Sort Field,
Filter conditions. item, 
description, , 
cost_price (. 5.16):

. 5.16.


, PgAccess 
.
PgAccess 


Tcl/Tk.
PgAc
cess. 
,
PgAccess formde
mo.sql, 
. 


(. 5.17):

. 5.17.

163

Microsoft Access

Tcl, 
, ,
PgAccess.
PgAccess
SQL.
,
. 

Drag and Drop, , 
, . 
SQL .
(. 5.18) , 
, :

. 5.18.

Microsoft Access
, Microsoft Access
PostgreSQL. Access 
, PostgreSQL?
PostgreSQL , PgAccess,
Microsoft Access?
,
, , 
, , . 
PostgreSQL 
, .

164

5. PostgreSQL

, PostgreSQL, UNIX
Linux, , 
.

, Access,
. PostgreSQL
ODBC, , .
Access,
PostgreSQL
. , 
Access.
Access PostgreSQL ,
Access
, PostgreSQL.


Access 
, 
. ,
Access . , 
. 

Access.
Access ,
bpsimple.
item, 
, , .
Access (. 5.19):

. 5.19. Access

165

Microsoft Access

Tables
Database
New, 
,
Link Table (. 5.20):

. 5.20.

Link ODBC Databases (. 5.21):

. 5.21.


ODBC. Machine DSN
PostgreSQL (. 5.22):

. 5.22. ODBC

166

5. PostgreSQL

,
,
(. 5.23):

. 5.23.


. item, 
item Access (. 5.24):

. 5.24. Access

Access , 
, 
. ,
? item_id, 
.
(. 5.25):

. 5.25.

167

Microsoft Access

, Access ,
item, ,
Access (. 5.26):

. 5.26. Access

, .

Access Windows.
oid, 
PostgreSQL. object_id , 
OID ODBC.


Access
PostgreSQL, .
Access 
PostgreSQL, , NUMERIC(7,2), 
float8. 
. Access Post
greSQL, .

Access
, item. 
Access 
, 

168

5. PostgreSQL

, 
(. 5.27):

. 5.27. Access

. Access
, PostgreSQL,
, Access.

. , 
( sell_price cost_price) 
item (. 5.28):

. 5.28. Access

169

Microsoft Excel

Microsoft Access PostgreSQL 


. 
PostgreSQL
Microsoft Access
, .

Microsoft Excel
Microsoft Access,
Microsoft Excel PostgreSQL.
, Access:
, (, , 
). 
, .
PostgreSQL, 
Excel, 
.
product Access , 
(markup) item
.
Access, Excel,

. ,
(. 5.29):

. 5.29.

170

5. PostgreSQL

ODBC
(. 5.30):

. 5.30.

, ,
. 
, item (. 5.31):

. 5.31.

, 
, 
. (. 5.32):

. 5.32.

171

Microsoft Excel

,
(. 5.33):

. 5.33.

Excel, ,
. ,
PostgreSQL .
,
. 
.


(. 5.34):

. 5.34. Excel

(. 5.35):

. 5.35. Excel

172

5. PostgreSQL


. , , 
.

Excel.
, ,
Data | Refresh Data (. 5.36):

. 5.36.

,
Excel.
, 
. Excel, 
, PostgreSQL (. 5.37):

. 5.37.

173

PostgreSQL
, .
Excel 
Microsoft Query PostgreSQL. 
Excel 2000.

PostgreSQL
Great Bridge: http://www.greatbridge.org.
Zeos database explorer, http://www.ze$
os.dn.ua/eng/,
PostgreSQL.
PostgreSQL pgmonitor
http://www.gre$
atbridge.org/project/pgmonitor/projdisplay.php.
Tcl/Tk, .
, 
, X Win
dow System Unix Unix .


PostgreSQL. 
psql, 
.
Tcl/Tk
PgAccess.
Microsoft
Windows pgAdmin.
, ,
PostgreSQL, , 
Microsoft Office, Microsoft Excel Access. 
Post
greSQL UNIX Linux 
.

, 

, PostgreSQL. 
, psql, pgAdmin, Kpsql PgAccess, 
PostgreSQL.
, Microsoft Access PostgreSQL,
Microsoft Excel. ,
,
.
PostgreSQL (INSERT),
(UPDATE) (DELETE).
:

INSERT

SERIAL

NULL

\copy

175


SELECT, 4,
PostgreSQL .
INSERT.

.

INSERT
SQL INSERT :
INSERT INTO tablename VALUES (list of column values);

(list of column values) 


, 
.
,
. 
, ( 
, ). 
, , 
.

. \d
customer . 
. , 
SQL , , 
, CREATE TABLE.
(, , ) 
,
psql ,
\d. , custo
mer ( 3).
, \d. :
bpsimple=# \d customer
Table "customer"
Attribute |
Type
|
Modifier
++
customer_id | integer
| not null default nextval('"
customer_customer_id_seq"'::text)
title
| character(4)
|
fname
| character varying(32) |
lname
| character varying(32) | not null
addressline | character varying(64) |
town
| character varying(32) |

176

6.
zipcode
| character(10)
| not null
phone
| character varying(16) |
Index: customer_pk
bpsimple=#

 ,
, 
customer . , customer_id
, CREATE TABLE.
, PostgreSQL
SERIAL, customer_id.
, . Post
greSQL SERIAL 8 
.

(').
, 
(\). ( 
). 
, NULL (, INSERT,
,
).
, 
INSERT:
INSERT INTO customer VALUES(16, 'Mr', 'Gavin', 'Smyth', '23 Harlestone',
'Milltown', 'MT7 7HI', '746 3725');

:
bpsimple=# INSERT INTO customer VALUES(16, 'Mr', 'Gavin', 'Smyth', '23
bpsimple# Harlestone', 'Milltown', 'MT7 7HI', '746 3725');
INSERT 18944 1
bpsimple=#

, INSERT,
. , PostgreSQL 
.
PostgreSQL, OID;
.
(Object IDentification number, OID) 
, , PostgreSQL .
,
. IN
SERT, 18944. 1
. SQL OID
, 
, 
, ().

177

, ( , 
SELECT ):
bpsimple=# SELECT * FROM customer WHERE customer_id > 15;
customer_id | title | fname | lname | addressline | town | zipcode | phone
+++++++
16 | Mr
| Gavin | Smyth |23 Harlestone|Milltown| MT7 7HI |746 3725
(1 row)
bpsimple=#

 , , 
 , , 
.
,
O'Rourke. 
?
:
INSERT INTO customer VALUES(17, 'Mr', 'Shaun', 'O\'Rourke', '32 Sheepy Lane',
'Milltown', 'MT9 8NQ', '746 3956');

, :
bpsimple=# SELECT * FROM customer WHERE customer_id > 15;
customer_id|title| fname | lname | addressline | town | zipcode |phone
+++++++
16 | Mr | Gavin |Smyth |23 Harlestone |Milltown| MT7 7HI |746 3725
17 | Mr | Shaun |O'Rourke|32 Sheepy Lane|Milltown| MT9 8NQ |746 3956
(2 rows)
bpsimple=#


customer 
INSERT,
, .
, , 
. 
, (\).
, 
\\.

. INSERT
, ,
: Midtown Street A\33.

178

6.

, ? 
, 
:
INSERT INTO customer VALUES(18, 'Mr', 'Jeff', 'Baggott', 'Midtown Street
A\\33', 'Milltown', 'MT9 8NQ', '746 3956');

:
bpsimple=# SELECT * FROM customer WHERE addressline='Midtown Street A\\33';
customer_id|title|fname| lname |
addressline | town |zipcode| phone
+++++++
18 |Mr |Jeff |Baggott|Midtown Street A\33|Milltown|MT9 8NQ|746 3956
(1 row)
bpsimple=#

INSERT
INSERT, 
,
,
. ,
,
. , ,

fname lname. , 
, PostgreSQL 
.
, Smyth ( ), Gavin.

( ) , 
, 
, .

, , 
, ( , , 
) .
, 
INSERT, , :
INSERT INTO tablename(list of column names) VALUES (list of column values
corresponding to the column names);

INSERT 
, 
, 
. , 
.

179

,
. .

.
, 
:
INSERT INTO customer(customer_id, title, fname, lname, addressline, town,
zipcode, phone) VALUES(19, 'Mrs', 'Sarah', 'Harvey', '84 Willow Way',
'Lincoln', 'LC3 7RD', '527 3739');

,

.
, ( ) 
:
bpsimple=# INSERT INTO
bpsimple# customer(customer_id, title, lname, fname, addressline, town,
bpsimple# zipcode, phone)
bpsimple# VALUES(19, 'Mrs', 'Harvey', 'Sarah', '84 Willow Way', 'Lincoln',
bpsimple# 'LC3 7RD', '527 3739');
INSERT 22592 1
bpsimple=#

,
.
fname lname, , 
. . 
, , ,
.
, psql
,
( ).
IN
SERT , 
.

SERIAL
, 
customer_id. , 
, 
. , INSERT,
, ( ,
, 
SERIAL).

180

6.

2 (
) , SERIAL ,
, 
unique_id . (
), customer_id, 
SERIAL.
, customer
:
bpsimple=# SELECT customer_id, fname, lname, addressline FROM customer;
customer_id | fname | lname |
addressline
+++
1 | Jenny
| Stones | 27 Rowan Avenue
2 | Andrew
| Stones | 52 The Willows
3 | Alex
| Matthew | 4 The Street
4 | Adrian
| Matthew | The Barn
5 | Simon
| Cozens | 7 Shady Lane
6 | Neil
| Matthew | 5 Pasture Lane
7 | Richard | Stones | 34 Holly Way
8 | Ann
| Stones | 34 Holly Way
9 | Christine | Hickman | 36 Queen Street
10 | Mike
| Howard | 86 Dysart Street
11 | Dave
| Jones
| 54 Vale Rise
12 | Richard | Neill
| 42 Thatched way
13 | Laura
| Hendy
| 73 Margeritta Way
14 | Bill
| O'Neill | 2 Beamer Street
15 | David
| Hudson | 4 The Square
16 | Gavin
| Smyth
| 23 Harlestone
17 | Shaun
| O'Rourke | 32 Sheepy Lane
18 | Jeff
| Baggott | Midtown Street A\33
19 | Sarah
| Harvey | 84 Willow Way
(19 rows)
bpsimple=#

, , . 
customer_id,
SERIAL,
PostgreSQL.
, SERI
AL 
customer_id:
bpsimple=# INSERT INTO customer(title, fname, lname, addressline, town,
bpsimple# zipcode, phone)
bpsimple# VALUES('Mr', 'Steve', 'Clarke', '14 Satview way', 'Lincoln',
bpsimple# 'LC4 3ED', '527 7254');
ERROR: Cannot insert a duplicate key into unique index customer_pk
bpsimple=#

181

,  , 
. , ,
customer_id, 
PostgreSQL
SERIAL, , 

.
SERIAL .

?
PostgreSQL , 
.


customer customer_id
SERIAL. , Post
greSQL , ,
customer_customer_id_seq. ,
PostgreSQL , \d,
, :
customer_id integer not null default nextval('customer_customer_id_seq'::text)

PostgreSQL
, 
. , 
(sequence) : <tablena
me>_<column name>_seq. PostgreSQL ,

nextval('customer_customer_id_seq'). INSERT
, PostgreSQL
.
,
( , ).
, 
, PostgreSQL 
.
cur
rval:
currval('sequence name');

PostgreSQL .
:
bpsimple=# SELECT currval('customer_customer_id_seq');
currval

182

6.
17
(1 row)
bpsimple=#

, PostgreSQL ,
17, 19.
customer
customer_id PostgreSQL
, nextval():
nextval('sequence number');


, . , :
bpsimple=# SELECT nextval('customer_customer_id_seq');
nextval

18
(1 row)
bpsimple=#

, 
, nextval(),
, , ,
. setval():
setval('sequence number', new value);

, 
. ,
.
MAX(column name) ( 7), 
, 
:
bpsimple=# SELECT MAX(customer_id) FROM customer;
max

19
bpsimple=#

, PostgreSQL ,
customer_id customer. 
setval(sequence, value),

. 19,
, 
,

183

, 
:
bpsimple=# SELECT setval('customer_customer_id_seq', 19);
setval

19
(1 row)
bpsimple=#

,
, PostgreSQL 
customer_id SERIAL:
bpsimple=# INSERT INTO customer(title, fname, lname, addressline, town,
bpsimple# zipcode, phone) VALUES('Mr', 'Steve', 'Clarke', '14 Satview
bpsimple# way', 'Lincoln', 'LC4 3ED', '527 7254');
INSERT 21459 1
bpsimple=#

! PostgreSQL 
, SERIAL  .
, , 
, . 
:

,
.


PostgreSQL SERIAL,
.

NULL
2 , NULL
INSERT. .
INSERT ( 
, ) 
NULL . 
, . . NULL . , NULL
SQL ,
, .
, :
INSERT INTO customer VALUES(16, 'Mr', 'Gavin', 'Smyth', '23 Harlestone',
'Milltown', 'MT7 7HI', '746 3725');

184

6.

.
NULL fname, 
, . :
INSERT INTO customer VALUES(16, 'Mr', '', 'Smyth', '23 Harlestone',
'Milltown', 'MT7 7HI', '746 3725');

, ;
, , , , 
(Mr. Smyth) , 
NULL, .
INSERT
:
INSERT INTO customer VALUES(16, 'Mr', NULL, 'Smyth', '23 Harlestone',
'Milltown', 'MT7 7HI', '746 3725');

, NULL .
, fname NULL, 
NULL.
( ) INSERT ( 
) NULL ,
, :
INSERT INTO customer(title, lname, addressline, town, zipcode, phone)
VALUES('Mr', 'Smyth', '23 Harlestone', 'Milltown', 'MT7 7HI', '746
3725');

, fname ,
. 
NULL .
NULL , ,
NULL, . 
, , lname
():
bpsimple=# INSERT INTO customer(title, fname, addressline, town, zipcode,
bpsimple# phone) VALUES('Ms', 'Gill', '27 Chase Avenue', 'Lowtown', 'LT5
bpsimple# 8TQ', '876 1962');
ERROR: ExecAppend: Fail to add null value in not null attribute lname
bpsimple=#

lname, INSERT , 
customer 
NULL .

185

:
bpsimple=# \d customer
Table "customer"
Attribute |
Type
|
Modifier
++
customer_id | integer
| not null default
nextval('customer_customer_id_seq'::text)
title
| char(4)
|
fname
| varchar(32) |
lname
| varchar(32) | not null
addressline | varchar(64) |
town
| varchar(32) |
zipcode
| char(10)
| not null
phone
| varchar(16) |
Index: customer_pk
bpsimple=#

8 , 
,
, (
).

\copy

SQL INSERT,
.
, 
, , , 
.
Export, , 
,
, .
, EMACS (  , 
), INSERT.
:
Miss,Jenny,Stones,27 Rowan Avenue,Hightown,NT2 1AQ,023 9876
Mr,Andrew,Stones,52 The Willows,Lowtown,LT5 7RA,876 3527
Miss,Alex,Matthew,4 The Street,Nicetown,NT2 2TX,010 4567

INSERT,
:
INSERT INTO customer(title, fname, lname, addressline, town, zipcode, phone)
VALUES('Miss','Jenny','Stones','27 Rowan Avenue','Hightown','NT2 1AQ','023
9876');

186

6.

INSERT INTO customer(title, fname, lname, addressline, town, zipcode, phone)


VALUES('Mr','Andrew','Stones','52 The Willows','Lowtown','LT5 7RA','876
3527');
INSERT INTO customer(title, fname, lname, addressline, town, zipcode, phone)
VALUES('Miss','Alex','Matthew','4 The Street','Nicetown','NT2 2TX','010
4567');

.sql.
\i psql.
pop_customer.sql ( 3
). , 
customer_id PostgreSQL.
, .
, 
. PostgreSQL
. copy
( ). PostgreSQL
SQL, COPY,
, 
, 
. \copy, 
COPY, 
, .
, SQL COPY ,
.
COPY . 
,
, \copy 
, . 
.
, .
\copy
:
\copy tablename FROM 'filename' [USING DELIMITERS 'a single character to use
as a delimiter'] [WITH NULL AS 'a string that means NULL']

, . 
, [], , 
. , 
.
USING DELIMITERS 'a single character...' ,
(
) . ,
. 
, 
, ,

187

. 
, (, )
,
. , 
. , 
, 
, ,
. , |,
. . .
WITH NULL AS 'a string...' ,
(NULL).
\N. , \copy
, PostgreSQL
, ,
. NULL
NOTHING, 
WITH NULL AS 'NOTHING', (, , 
Mr. Hudson) :
15,Mr,NOTHING,Hudson,4 The Square, Milltown,MT2 6RT,961 4526


, . 
, , 
, ,
,
. . PostgreSQL o
,
, , ,
. 
,
\copy.

. \copy
,
cust.txt, :
21,Miss,Emma,Neill,21 Sheepy Lane,Hightown,NT2 1YQ,023 4245
22,Mr,Gavin,Neill,21 Sheepy Lane,Hightown,NT2 1YQ,023 4245
23,Mr,Duncan,Neill,21 Sheepy Lane,Hightown,NT2 1YQ,023 4245

, (
), 
. :
\copy customer from 'cust.txt' using delimiters ','

188

6.

(;). ,
psql, SQL. psql
\., , .

SELECT * FROM customer;

, .
. , 
? 
, \copy 
, . 
, :
bpsimple=# SELECT MAX(customer_id) FROM customer;
max

23
(1 row)
bpsimple=# SELECT currval('customer_customer_id_seq');
currval

20
(1 row)
bpsimple=#

! , customer_id, 
22, ID 23,

21. , :
bpsimple=# SELECT setval('customer_customer_id_seq', 23);
setval

23
(1 row)
bpsimple=#


, 
,
, customer, \copy. 
, 
customer_id SERIAL, 
, , 
,
, INSERT.

189


Microsoft Access,
PostgreSQL. 
PostgreSQL Access ODBC
PostgreSQL.
, ,
, ,
. ,

, ,
. 

, ,
. 
, 
, ,
.

(. 10 ) 
. 
,
INSERT,
, 
. ,
INSERT . 
INSERT INTO.

:
INSERT INTO tablename(list of column names) SELECT normal select statement

, , tcust, 
, 
customer.
:
create table tcust
(
title
fname
lname
addressline
town
zipcode
phone
);

char(4)
varchar(32)
varchar(32)
varchar(64)
varchar(32)
char(10)
varchar(16)

,
,
,
,
,
,

190

6.

, , 
. 
. , 
. 
. , 
, customer_id,
PostgreSQL .
,  tcust (
: ODBC, \copy  ), 
, SELECT 
:
bpsimple=# SELECT * FROM tcust;
title | fname | lname | addressline | town | zipcode | phone
++++++
Mr
| Peter | Bradley | 72 Milton Rise | Keynes | MK41 2HQ |
Mr
| Kevin | Carney | 43 Glen Way
| Lincoln | LI2 7RD
| 786 3454
Mr
| Brian | Waters | 21 Troon Rise | Lincoln | LI7 6GT
| 786 7243
(3 rows)
bpsimple=#

.
, Mr. Bradley 
. , .
,
. ( ) 
, 
, ,
,
.
INSERT .
, 
. :
INSERT INTO customer(title, fname, lname, addressline, town, zipcode, phone);

, customer_id .
, PostgreSQL
, 
SERIAL.
SELECT,
INSERT. ,
Mr. Bradley, NULL,
.
Mr. Bradley, 

191

NULL. 
, , 
. 
SELECT :
SELECT title, fname, lname, addressline, town, zipcode, phone FROM tcust
WHERE phone IS NOT NULL;

, .
:
bpsimple=# SELECT title, fname, lname, addressline, town, zipcode, phone
bpsimple# FROM tcust WHERE phone IS NOT NULL;
title | fname | lname | addressline | town | zipcode | phone
++++++
Mr
| Kevin | Carney | 43 Glen Way | Lincoln | LI2 7RD | 786 3454
Mr
| Brian | Waters | 21 Troon Rise | Lincoln | LI7 6GT | 786 7243
(2 rows)
bpsimple=#

, . SELECT ,
, , INSERT. 
:
bpsimple=# INSERT INTO customer(title, fname, lname, addressline, town,
bpsimple# zipcode, phone) SELECT title, fname, lname, addressline, town,
bpsimple# zipcode, phone FROM tcust WHERE phone IS NOT NULL;
INSERT 0 2
bpsimple=#

, psql , . , 
,
customer, , 
, :
bpsimple=# SELECT customer_id, fname, lname, addressline FROM customer WHERE
bpsimple# town = 'Lincoln';
customer_id | fname | lname | addressline
+++
18 | Sarah | Harvey | 84 Willow Way
24 | Kevin | Carney | 43 Glen Way
25 | Brian | Waters | 21 Troon Rise
(3 rows)
bpsimple=#

, Lin
coln. , 
customer_id. tcust 
customer, 

192

6.

tcust. 
, .

, custo
mer,
tcust. PostgreSQL
customer_id, customer_id
. PostgreSQL
, 
.
(
, ). 
,
isvalid Boolean. 
, isvalid FALSE 
UPDATE ( ):
UPDATE tcust SET isvalid = 'FALSE';

WHERE , ,
isvalid FALSE. :
, , isvalid 
TRUE,
, isvalid
TRUE:
bpsimple=#
bpsimple#
bpsimple#
bpsimple#

INSERT INTO customer(title, fname, lname, addressline, town,


zipcode, phone)
SELECT title, fname, lname, addressline, town, zipcode, phone
FROM tcust WHERE isvalid = TRUE;

, ( 
DELETE )
tcust; :
DELETE FROM tcust WHERE isvalid = TRUE;


tcust.


, 
INSERT SELECT. 
, . , 
. . 
.

193

PostgreSQL, , SQL, 
UPDATE.
UPDATE . :
UPDATE tablename SET columnname = value WHERE condition

, 
, :
UPDATE customer SET town = 'Leicester', zipcode = 'LE4 2WQ' WHERE some condition


, .
, , 
SQL. ,
, , 
UPDATE.
(. 9 )
, ,
.

. UPDATE
,
Mr. Bradley tcust, 
customer. UPDATE :
UPDATE tcust SET phone = '352 3442'

, :
WHERE fname = 'Peter' and lname = 'Bradley';

UPDATE,
WHERE. :
bpsimple=# SELECT fname, lname, phone FROM tcust WHERE fname = 'Peter' AND
bpsimple# lname = 'Bradley';
fname | lname | phone
++
Peter | Bradley |
(1 row)
bpsimple=#

, ,
. 
:
bpsimple=# UPDATE tcust SET phone = '352 3442' WHERE fname = 'Peter' AND
bpsimple# lname = 'Bradley';

194

6.
UPDATE 1
bpsimple=#

PostgreSQL , . , ,
SELECT, , 
.

UPDATE . 
UPDATE, , 
WHERE, , 
. WHERE UPDATE, 
.


WHERE, UPDATE? , 
UPDATE , 
WHERE. UPDATE 
, .
tcust , 
, UPDATE WHERE:
bpsimple=# UPDATE tcust SET phone = '999 9999';
UPDATE 3
bpsimple=#

, psql , .
, :
bpsimple=# SELECT fname, lname, phone FROM tcust;
fname | lname | phone
++
Kevin | Carney | 999 9999
Brian | Waters | 999 9999
Peter | Bradley | 999 9999
(3 rows)
bpsimple=#

, !
UPDATE WHERE.

, 
, , 
WHERE, COUNT(*), 
7

195

. ,
SELECT COUNT(*),
, (
). , 
COUNT(*), .
SELECT ,
WHERE:
bpsimple=# SELECT count(*) from tcust WHERE fname = 'Peter' AND lname =
bpsimple# 'Bradley';
count

1
(1 row)
bpsimple=#

, WHERE , 
. , ,
fname lname 
.
PostgreSQL , 
, :
UPDATE tablename FROM tablename WHERE condition

SQL.

. UPDATE FROM
custphone, 
. 
:
create table custphone
(
customer_id
fname
lname
phone_num

serial,
varchar(32),
varchar(32) not null,
varchar(16)

);

:
bpsimple=# INSERT INTO custphone(fname, lname, phone_num) VALUES('Peter',
bpsimple# 'Bradley', '352 3442');
INSERT 22593 1
bpsimple=#

196

6.

tcust ,
:
bpsimple=# UPDATE tcust SET phone = custphone.phone_num FROM custphone WHERE
bpsimple# fname = 'Peter' AND lname = 'Bradley';
UPDATE 1
bpsimple=#


. 
. UPDATE,
.
UPDATE 
, FROM
SET. FROM . Post
greSQL , 
.


, ,
. 
, . .
.

DELETE. UPDATE:
DELETE FROM tablename WHERE condition

, , 
DELETE .
UPDATE, NULL 
 .

tcust customer, 
tcust.

. DELETE
, 
WHERE , .
,
WHERE SELECT:
bpsimple=# SELECT fname, lname FROM tcust WHERE town = 'Lincoln';
fname | lname
+

197

Kevin | Carney
Brian | Waters
(2 rows)
bpsimple=#

, .
DELETE , 
, :
bpsimple=# DELETE FROM tcust WHERE town = 'Lincoln';
DELETE 2
bpsimple=#
, !


WHERE 
. DE
LETE, .
UPDATE, DELETE 
. ,
(. 9 ).

TRUNCATE. , 
, 
. .
TRUNCATE :
TRUNCATE TABLE name of table

,
, .

,
.

. TRUNCATE
, tcust
. drop
, , , 
. TRUNCATE
:
bpsimple=# TRUNCATE TABLE tcust;
TRUNCATE
bpsimple=# SELECT COUNT(*) FROM tcust;

198

6.
count

0
(1 row)
bpsimple=#

.

TRUNCATE .
DELETE
WHERE TRUNCATE. , SQL92, 
SQL
.

(, )
, PostgreSQL

. , 
, 
.

. TRUNCATE 
,
.
, DELETE. , 
ROLLBACK, 
, , 
TRUNCATE.
DELETE, . .
. , , 
, 
TRUNCATE.

SELECT 
: IN
SERT, UPDATE , , 
DELETE.
INSERT.
, , 
SELECT . ,
INSERT, ,
. 
INSERT, PostgreSQL 

199

\copy,
.

SERIAL, ,
.
, PostgreSQL
, 
SERIAL.
UPDATE DELETE, 
WHERE ( SELECT). ,
UPDATE DELETE, WHERE,
SELECT, . . 
.
, TRUNCATE, 
.
, . . ,
.

4 SELECT , 
. , 
. SELECT
.
, ,
, SQL.
, ,
, , (
) , 
, 
. , 
, 
.
,
.
, 
, 
. , 
, , ,
. 
, ,
SELECT. ,
,
, .

201

UNION



: MAX(< >), 
, COUNT(*),
. SQL
, .
:

COUNT(*)

COUNT(< >)

MIN(< >)

MAX(< >)

SUM(< >)

AVG(< >)

, .
psql \da , 
PostgreSQL.

COUNT
COUNT, , 
, . COUNT(*) 
. 
SELECT. SELECT, 
,
, GROUP BY HAVING.
:
SELECT COUNT(*) < > FROM <> WHERE <> [GROUP BY
<> [HAVING < >]]

GROUP BY 
, SELECT. 
. GROUP BY 
ORDER BY, 

202

7.

. HAVING GROUP
BY , COUNT(*) 
.
,
. ,
COUNT(*). GROUP BY
.

. COUNT(*)
, , customer 
, . , ,
, SQL:
SELECT * FROM customer WHERE town = 'Bingham';

, , :
SELECT customer_id FROM customer WHERE town = 'Bingham';

, . 
. , , cus
tomer ,
, 
. COUNT(*),
, .
SELECT ,
COUNT(*):
bpsimple=# SELECT COUNT(*) FROM customer WHERE town = 'Bingham';
count

3
(1 row)
bpsimple=#

, 
WHERE:
bpsimple=# SELECT COUNT(*) FROM customer;
count

15
(1 row)
bpsimple=#

, , 
. , COUNT(*) custo
mer_id, .

203


COUNT(*) 
. , ,
:

,
, .

COUNT(*)
, ,
.
,
.

GROUP BY COUNT(*)
, , 
, . , ,
. , 
,
. 
.
SQL? , :
SELECT COUNT(*), town FROM customer;

, ,
, PostgreSQL ,
. . . ,
GROUP BY.
GROUP BY PostgreSQL,
, 
( ).
. GROUP BY <
> SELECT, COUNT(*). PostgreSQL
, 
.

. GROUP BY
,
?
, SELECT, COUNT(*)
, :
SELECT COUNT(*), town FROM customer;

204

7.

GROUP BY, PostgreSQL


,
, SQL :
SELECT COUNT(*), town FROM customer GROUP BY town;

:
bpsimple=# SELECT COUNT(*), town FROM customer GROUP BY town;
count | town
+
3 | Bingham
1 | Hightown
1 | Histon
1 | Lowtown
1 | Milltown
2 | Nicetown
1 | Oahenham
1 | Oxbridge
1 | Tibsville
1 | Welltown
1 | Winersby
1 | Yuleville
(12 rows)
bpsimple=#

,
.

PostgreSQL , 
GROUP BY. ,
, , ,
. , , 
, .

, GROUP BY.
, . ,
; , 
. lname SELECT GROUP BY
:
bpsimple=# SELECT count(*), lname, town FROM customer GROUP BY town, lname;
count | lname | town
++
1 | Jones | Bingham
2 | Stones | Bingham
1 | Stones | Hightown
1 | Hickman | Histon
1 | Stones | Lowtown

205


1 | Hudson
2 | Matthew
1 | Cozens
1 | Hendy
1 | Howard
1 | O'Neill
1 | Neill
1 | Matthew
(13 rows)
bpsimple=#

|
|
|
|
|
|
|
|

Milltown
Nicetown
Oahenham
Oxbridge
Tibsville
Welltown
Winersby
Yuleville

, town,
lname, 
ORDER BY, Bingham
, Jones Stones, 
.

HAVING COUNT(*)
HA
VING. , SQL,
. , HA
VING WHERE . HAVING
, 
, COUNT(*)>1. 
WHERE
.
WHERE; 
HAVING.

, . ,
, . 
COUNT(*), 
. 
, , 
. HAVING ,
COUNT(*) :
bpsimple=# SELECT COUNT(*), town FROM customer
bpsimple# GROUP BY town HAVING COUNT(*) > 1;
count | town
+
3 | Bingham
2 | Nicetown
(2 rows)
bpsimple=#

,  GROUP BY,
HAVING. , 

206

7.

COUNT(*), GROUP BY HAVING 


.

. HAVING
, .
, 
Lincoln ( , 
) ,
.
, , 
. SQL.
,
, , ,
. , ,
.
:
bpsimple=# SELECT lname, town FROM customer WHERE town <> 'Lincoln';
lname | town
+
Stones | Hightown
Stones | Lowtown
Matthew | Nicetown
Matthew | Yuleville
Cozens | Oahenham
Matthew | Nicetown
Stones | Bingham
Stones | Bingham
Hickman | Histon
Howard | Tibsville
Jones | Bingham
Neill | Winersby
Hendy | Oxbridge
O'Neill | Welltown
Hudson | Milltown
Smyth | Milltown
Garrett | Lowtown
(17 rows)

bpsimple=#
, ?
, COUNT(*) , 
lname town:
bpsimple=# SELECT COUNT(*), lname, town FROM customer WHERE town <>
bpsimple# 'Lincoln' GROUP BY lname, town;

207

count | lname | town


++
1 | Cozens | Oahenham
1 | Garrett | Lowtown
1 | Hendy | Oxbridge
1 | Hickman | Histon
1 | Howard | Tibsville
1 | Hudson | Milltown
1 | Jones | Bingham
2 | Matthew | Nicetown
1 | Matthew | Yuleville
1 | Neill | Winersby
1 | O'Neill | Welltown
1 | Smyth | Milltown
2 | Stones | Bingham
1 | Stones | Hightown
1 | Stones | Lowtown
(15 rows)
bpsimple=#

, , 

HAVING, COUNT(*),
:
bpsimple=# SELECT COUNT(*), lname, town FROM customer WHERE town <>
bpsimple# 'Lincoln' GROUP BY lname, town HAVING COUNT(*) > 1;
count | lname | town
++
2 | Matthew | Nicetown
2 | Stones | Bingham
(2 rows)
bpsimple=#

, .

:

SELECT,
.

COUNT(*) GROUP BY 
lname town.

, HAVING,
, COUNT(*) .

, , .
, , 

208

7.

.
,
. , 

. WHERE custo
mer_id < 50, 
.
, WHERE,
. , 
, 
, 
.

COUNT(< >)
COUNT(*) '*'
. , COUNT(< >)
, 
, NULL.
, customer 
, NULL :
INSERT INTO customer(title, fname, lname, addressline, town, zipcode)
VALUES('Mr','Gavin','Smyth','23 Harlestone','Milltown','MT7 7HI');
INSERT INTO customer(title, fname, lname, addressline, town, zipcode, phone)
VALUES('Mrs','Sarah','Harvey','84 Willow Way','Lincoln','LC3 7RD','527 3739');
INSERT INTO customer(title, fname, lname, addressline, town, zipcode)
VALUES('Mr','Steve','Harvey','84 Willow Way','Lincoln','LC3 7RD');
INSERT INTO customer(title, fname, lname, addressline, town, zipcode)
VALUES('Mr','Paul','Garrett','27 Chase Avenue','Lowtown','LT5 8TQ');

, 
:
bpsimple=# SELECT customer_id FROM customer WHERE phone IS NULL;
customer_id

16
18
19
(3 rows)
bpsimple=#

, . 
, :
bpsimple=# SELECT COUNT(*) FROM customer;
count

209

19
(1 row)
bpsimple=#

19 . ,
phone NULL, ,
, 16:
bpsimple=# SELECT COUNT(phone) FROM customer;
count

16
(1 row)
bpsimple=#


COUNT(*) COUNT(column name).
, 
NULL, '*'
. , GROUP BY HA
VING, COUNT(*).

MIN()
, COUNT(*)
. 
.
, MIN()
,
. . 
( ) , 
, .
;
. 
MIN() MAX() VARCHAR ,
.
.
, :
bpsimple=# SELECT MIN(shipping) FROM orderinfo;
min

0.00
(1 row)
bpsimple=#

210

7.

. , , 
, , 
, NULL:
bpsimple=# SELECT MIN(phone) FROM customer;
min

010 4567
(1 row)
bpsimple=#

, NULL
. , , NULL 
, MIN()
. NULL
COUNT(*). 
.

MAX()
, MAX() MIN(),
.
, MAX() 
, .
.
, :
bpsimple=# SELECT MAX(shipping) FROM orderinfo;
max

3.99
(1 row)
bpsimple=#

MIN(), NULL :
bpsimple=# SELECT MAX(phone) FROM customer;
max

961 4526
(1 row)
bpsimple=#

, , MAX()
, GROUP BY HAVING
COUNT(*).

211

SUM()
SUM() 
. MIN() MAX(), NULL
:
bpsimple=# SELECT SUM(shipping) FROM orderinfo;
sum

9.97
(1 row)
bpsimple=#

, , SUM().
,
, ,
:
bpsimple=# SELECT SUM(DISTINCT shipping) FROM orderinfo;
sum

6.98
(1 row)
bpsimple=#

,
.

AVG()
AVG().
. SUM(), 
NULL DISTINCT
:
bpsimple=# SELECT AVG(shipping) FROM orderinfo;
avg

1.9940000000
(1 row)
bpsimple=#

DISTINCT:
bpsimple=# SELECT AVG(DISTINCT shipping) FROM orderinfo;
avg

2.3266666667
(1 row)
bpsimple=#

212

7.

, SQL,
PostgreSQL MODE MEDIAN, 

.

UNION
, SELECT
.
, tcust
, 
customer. , 
tcust 
customer
, , .
, 
,
, ,
, . , 
. , 
, .
, town
customer, , town tcust, 
, . 
, 
.
 ? 
, 
UNION. , 
, , 
, .
tcust , :
bpsimple=# SELECT * FROM tcust;
title| fname | lname | addressline | town | zipcode | phone
++++++
Mr | Peter | Bradley | 72 Milton Rise | Keynes | MK41 2HQ |
Mr | Kevin | Carney | 43 Glen Way
| Lincoln | LI2 7RD
| 786 3454
Mr | Brian | Waters | 21 Troon Rise | Lincoln | LI7 6GT
| 786 7245
Mr | Malcolm | Whalley | 3 Craddock Way | Welltown | WT3 4GQ
| 435 6543
(4 rows)
bpsimple=#

customer.

UNION

213

, town .
SELECT:
SELECT town FROM tcust;
SELECT town FROM customer;

. , 
UNION,
SELECT:
SELECT town FROM tcust UNION SELECT town FROM customer;

. UNION
SQL, 
. , psql =#
#, ,
, , . . 
:
bpsimple=# SELECT town FROM tcust
bpsimple# UNION
bpsimple# SELECT town FROM customer;
town

Bingham
Hightown
Histon
Keynes
Lincoln
Lowtown
Milltown
Nicetown
Oahenham
Oxbridge
Tibsville
Welltown
Winersby
Yuleville
(14 rows)
bpsimple=#


PostgreSQL
. , . 
, ,
UNION ALL, UNION.

214

7.

SELECT
, :
SELECT town, zipcode FROM tcust UNION SELECT town, zipcode FROM customer;

, . 
,
, , .
 UNION .
, , 
, 
. :
bpsimple=# SELECT title FROM customer
bpsimple# UNION
bpsimple# SELECT town FROM tcust;
title

Keynes
Lincoln
Miss
Mr
Mrs
Welltown
(6 rows)
bpsimple=#

, , , . .
PostgreSQL , , title
, town
, , 
. , , cus
tomer_id town, PostgreSQL , 
, .
, UNION, 

.

SQL,
SELECT,
,
SELECT. 
, SELECT UNION,

.

215

, ( ) 
WHERE SELECT SELECT.
, item , 
(cost price) 10 . SE
LECT , 
, NUMERIC(7,2),
cost_price item,
:
bpsimple=# SELECT * FROM item WHERE cost_price > CAST(10.0 AS NUMERIC(7,2));
item_id | description | cost_price | sell_price
+++
1 | Wood Puzzle |
15.23 |
21.95
7 | Fan Large |
13.36 |
19.95
11 | Speakers
|
19.73 |
25.32
(3 rows)
bpsimple=#

, , 
. 
:
bpsimple=# SELECT AVG(cost_price) FROM item;
avg

7.2490909091
(1 row)
bpsimple=# SELECT * FROM item WHERE cost_price > CAST(7.249 AS
bpsimple# NUMERIC(7,2));
item_id | description | cost_price | sell_price
+++
1 | Wood Puzzle |
15.23 |
21.95
2 | Rubic Cube
|
7.45 |
11.49
5 | Picture Frame |
7.54 |
9.95
6 | Fan Small
|
9.23 |
15.75
7 | Fan Large
|
13.36 |
19.95
11 | Speakers
|
19.73 |
25.32
(6 rows)
bpsimple=#

. 
, 
, .
. 
WHERE 
:

216

7.
bpsimple=# SELECT * FROM item WHERE cost_price > (SELECT AVG(cost_price)
bpsimple# FROM item);
item_id | description | cost_price | sell_price
+++
1 | Wood Puzzle |
15.23 |
21.95
2 | Rubic Cube
|
7.45 |
11.49
5 | Picture Frame |
7.54 |
9.95
6 | Fan Small
|
9.23 |
15.75
7 | Fan Large
|
13.36 |
19.95
11 | Speakers
|
19.73 |
25.32
(6 rows)
bpsimple=#

, ,
, , . . 
.
PostgreSQL , . 
,
. 
, WHERE. 
, 
SELECT .

.
. 
, , 
. ,
, ,
, 
.
, : SELECT
AVG(cost_price) FROM item. 
: SELECT AVG(sell_price) FROM item.
:
SELECT * FROM item WHERE cost_price > average cost price AND sell_price <
average selling price

, :
bpsimple=# SELECT * FROM item WHERE cost_price > (SELECT AVG(cost_price)
bpsimple# FROM item) AND sell_price < (SELECT AVG(sell_price) FROM item);
item_id | description | cost_price | sell_price
+++
5 | Picture Frame |
7.54 |
9.95
(1 row)
bpsimple=#

217

,  
!

PostgreSQL
, . . .
,
WHERE ,
.
WHERE
ORDER BY. WHERE, ,
.


, 
, . . . 
:

( )


. , ,
, , 10,0.
SELECT:
bpsimple=# SELECT s.item_id, s.quantity FROM stock s, item i WHERE
bpsimple# i.cost_price > CAST(10.0 AS NUMERIC(7,2)) AND s.item_id =
bpsimple# i.item_id;
item_id | quantity
+
1 |
12
7 |
8
(2 rows)
bpsimple=#

, , 
(stock s, item i).
(s.item_id = i.item_id),
item (i.cost_price > CAST(10.0 AS NUMERIC(7,2))).
, IN
. ,
(item_id) , 
10,0:
SELECT item_id FROM item WHERE cost_price > CAST(10.0 AS NUMERIC(7,2));

218

7.

, stock:
SELECT * FROM stock WHERE item_id IN list of values

:
bpsimple=# SELECT * FROM stock WHERE item_id IN (SELECT item_id FROM item
bpsimple# WHERE cost_price > CAST(10.0 AS NUMERIC(7,2)));
item_id | quantity
+
1 |
12
7 |
8
(2 rows)
bpsimple=#

. ,
, 
, . 
, , NOT IN,
WHERE ORDER BY.
,
? :
.
, 
, .
, 
,
. , 

, .
SQL, , 
,
.

, 
, ,
.

. , , ,
, .


, 
, 
. 

219

(uncorrelated subqueries).
.
, 
SELECT, 
, WHERE
.
, 
(correlated subqueries), 
.
SELECT
SELECT, . 
,
SELECT .
:
SELECT columnA FROM table1 T1 WHERE T1.columnB = (SELECT T2.columnB FROM
table2 T2 WHERE T2.columnC = T1.columnC)

, SQL. 
, T1
SELECT SELECT. 
, .
, 
. , ,
, ,
.

, . . .



. 
T1 
SELECT,
T1.columnB 
, 
T2

. 
, 
WHE
RE, 
.
. 7.1:

1.columnB


2




WHERE

1.columnB

, ,

. 7.1.

220

7.

, . 
.
.
, ,
.

.
, , , 
. ,
, 
.

Bingham. ,
:
bpsimple=# SELECT oi.date_placed FROM orderinfo oi WHERE oi.customer_id =
bpsimple# (SELECT c.customer_id from customer c WHERE c.customer_id =
bpsimple# oi.customer_id and town = 'Bingham');
date_placed

20000623
20000721
(2 rows)
bpsimple=#


order
info. customer
customer_id.
customer , customer_id 
Bingham. , 
customer_id , 
WHERE , , date_placed. 
,
.
. 
, . ,
.
, ,
. . 
:
SELECT fname, lname FROM customer c;

221

, customer c 
. 
, customer_id orderinfo:
SELECT 1 FROM orderinfo oi WHERE oi.customer_id = c.customer_id;

. ,
.
, ,
'1'.  ,
1.
. , 
:
bpsimple=# SELECT 1 FROM customer WHERE town = 'Bingham';
?column?

1
1
1
(3 rows)
bpsimple=#

, .
COUNT(*), 
, , 
, 
Bingham.

customer, . 
. , 
. .
,
.
EXISTS WHERE,
, .
EXISTS 
SELECT, . . ,
. EXISTS
, IN. 
, 
, .
bpsimple=# SELECT fname, lname FROM customer c WHERE EXISTS ( SELECT 1 FROM
bpsimple# orderinfo oi WHERE oi.customer_id = c.customer_id);

222

7.
fname | lname
+
Alex | Matthew
Ann | Stones
Laura | Hendy
David | Hudson
(4 rows)
bpsimple=#

, , . 
, 
, .

,
(self join), , 
. ,  
,
.
, ,
, . , ,
, .
,
. 
(parts explosion),
12.
, 
, :
CREATE TABLE part (part_id INT, description VARCHAR(32), parent_part_id INT);

parent_part_id , 
. ,
(item_id 1), (item_id 2)
(item_id 3). INSERT :
bpsimple=# INSERT INTO part(part_id, description, parent_part_id) VALUES(1,
bpsimple# 'table and chairs', NULL);
INSERT 21579 1
bpsimple=# INSERT INTO part(part_id, description, parent_part_id) VALUES(2,
bpsimple# 'chair', 1);
INSERT 21580 1
bpsimple=# INSERT INTO part(part_id, description, parent_part_id) VALUES(3,

223

bpsimple# 'table', 1);


INSERT 21581 1
bpsimple=#

, , 
? 
.
. 
WHERE, ,
:
bpsimple=# SELECT p1.description, p2.description FROM part p1, part p2 WHERE
bpsimple# p1.part_id = p2.parent_part_id;
description
| description
+
table and chairs | chair
table and chairs | table
(2 rows)
bpsimple=#

. ,
. ,
AS:
bpsimple=# SELECT p1.description AS "Combined", p2.description AS "Parts"
bpsimple# FROM part p1, part p2 WHERE p1.part_id = p2.parent_part_id;
Combined
| Parts
+
table and chairs | chair
table and chairs | table
(2 rows)
bpsimple=#

12, 

.


, , 
(outer joins).
, , 
.

224

7.

item stock (. 7.2):

. 7.2. item stock

, , , 
item, stock ,
.
, 
, .
, , ( 
) SQL. 
, ,
SQL.
SELECT, :
bpsimple=# SELECT i.item_id, s.quantity FROM item i, stock s WHERE i.item_id
bpsimple# = s.item_id;
item_id | quantity
+
1 |
12
2 |
2
4 |
8
5 |
3
7 |
8
8 |
18
10 |
1
(7 rows)
bpsimple=#

(. . ,
item_id item 
, ), item_id .
, , , 
item stock ,
stock item_id.
, 
IN:
bpsimple=# SELECT i.item_id FROM item i WHERE i.item_id NOT IN (SELECT
bpsimple# i.item_id FROM item i, stock s WHERE i.item_id = s.item_id);

225

item_id

3
6
9
11
(4 rows)
bpsimple=#

:
item item_id, , stock.
SELECT , 
item_id 
SELECT. SELECT item_id,
WHERE NOT IN 
, .
item_id , , 
item_id, , 
. ,
UNION. .
: item_id quantity, SELECT
, item_id, . . . 
SELECT,
, SE
LECT. NULL,
0 (). ,
.
:
SELECT i.item_id, s.quantity FROM item i, stock s WHERE i.item_id = s.item_id
UNION
SELECT i.item_id, NULL FROM item i WHERE i.item_id NOT IN
(SELECT i.item_id FROM item i, stock s WHERE i.item_id = s.item_id);

, :
bpsimple=# SELECT i.item_id, s.quantity FROM item i, stock s WHERE i.item_id
bpsimple# = s.item_id
bpsimple# UNION
bpsimple# SELECT i.item_id, NULL FROM item i WHERE i.item_id NOT IN (select
bpsimple# i.item_id FROM item i, stock s WHERE i.item_id = s.item_id);
item_id | quantity
+
1 |
12
2 |
2
3 |
4 |
8
5 |
3

226

7.
6 |
7 |
8 |
9 |
10 |
11 |
(11 rows)

8
18
1

bpsimple=#

SQL 
, SQL89 NULL,
SELECT. , 
NULL,
. NULL,
0, NULL , . . 0 
, NULL .

, ,
. ,
,
, .
Oracle DB2 : '+'
WHERE , ,
. Sybase '*=' 
WHERE .
, , , ,
 SQL.
SQL92
, 
. 
. Sybase 11, Oracle 8,
. PostgreSQL 
7.1 . ,
, ,
. , 
, , 7.1, . .
7.1 
.
SQL92 WHERE
ON
LEFT OUTER JOIN.
:
SELECT columns FROM table1 LEFT OUTER JOIN table2 ON table1.column =
table2.column

227

, LEFT OUTER JOIN,


, .
, 
:
SELECT i.item_id, s.quantity FROM item i LEFT OUTER JOIN stock s ON i.item_id =
s.item_id;

, ? 
:
bpsimple=# SELECT i.item_id, s.quantity FROM item i LEFT OUTER JOIN stock s
bpsimple# ON i.item_id = s.item_id;
item_id | quantity
+
1 |
12
2 |
2
3 |
4 |
8
5 |
3
6 |
7 |
8
8 |
18
9 |
10 |
1
11 |
(11 rows)
bpsimple=#

, . , o 
, 
, , SQL89.
RIGHT OUTER JOIN, 
, , , ,
, 
,
.

.
, 
, , ?
, stock,
, 2 
, , ,
5,0. , 
item ( > 5.0),

228

7.

stock ( > 2),


item,
,
.
ON, ,
, WHERE,
.
stock 
, , 
, , ON:
ON i.item_id = s.item_id AND s.quantity > 2

item ,
WHERE:
WHERE i.cost_price > CAST(5.0 AS NUMERIC(7,2));

, :
bpsimple=# SELECT i.item_id, i.cost_price, s.quantity FROM item i LEFT OUTER
bpsimple# JOIN stock s ON i.item_id = s.item_id AND s.quantity > 2 WHERE
bpsimple# i.cost_price > CAST(5.0 AS NUMERIC(7,2));
item_id | cost_price | quantity
++
1 |
15.23 |
12
2 |
7.45 |
5 |
7.54 |
3
6 |
9.23 |
7 |
13.36 |
8
11 |
19.73 |
(6 rows)
bpsimple=#


LEFT OUTER JOIN
item, stock ,
quantity, 
2. ,
item, quantity ( stock) 
NULL, 
2. WHERE, 
, (
item) 5.0.

229

,
SQL . 
, COUNT(*), 
.
GROUP BY, 
, HAVING,
,
. 
UNION, 
. ,
.
, 
. ;
,
.

,
, ,
.
SQL. 
,  . 
 SQL ,
. PostgreSQL,
, .
SELECT , 
. 
, SQL,
,  SQL 
, , .
8 ,
, 
.


PostgreSQL .
,
, PostgreSQL, 
. , 
, 
Null.
,
Post
greSQL , , ,
(casting) .

,
, 
,
.
, 
,
. ,
, 
. .
:

PostgreSQL

231


PostgreSQL SQL,
, ,
, . .
.
PostgreSQL
:

PostgreSQL

Binary Large Object (BLOB)

, Binary Large Ob


jects, 
.


, , .
True (), False () 
, Null, .
: bool.
PostgreSQL 
, .
SQL, 
(. 8.1):
8.1.
True

False

TRUE
'1'
'yes'
'y'
'true'
't'

FALSE
'0'
'no'
'n'
'false'
'f'

232

8.

( NULL) .
PostgreSQL 
t, f, NULL , 
. ,
, PostgreSQL : True,
False Null, (true, y, t . .), 
, , 
. , . . 
, , 
.

.
bool 
. , , 
, , , .
testtype :
. ,
PostgreSQL. bpsimple, 
, test, 
. , 
3, , , .
, :
bpsimple=# CREATE DATABASE test;
CREATE DATABASE
bpsimple=# \c test
You are now connected to database test.
test=#

:
test=#
test#
test#
test#
CREATE
test=#
INSERT
test=#
INSERT
test=#
INSERT
test=#
INSERT
test=#
INSERT

CREATE TABLE testtype (


valused VARCHAR(10),
boolres BOOL
);
INSERT INTO
19132 1
INSERT INTO
19133 1
INSERT INTO
19134 1
INSERT INTO
19135 1
INSERT INTO
19136 1

testtype VALUES('TRUE', TRUE);


testtype VALUES('1', '1');
testtype VALUES('t', 't');
testtype VALUES('no', 'no');
testtype VALUES('f', 'f');

233


test=#
INSERT
test=#
INSERT
test=#

INSERT INTO testtype VALUES('Null', NULL);


19137 1
INSERT INTO testtype VALUES('FALSE', FALSE);
19138 1

, :
test=# SELECT * FROM testtype;
valused | boolres
+
TRUE
| t
1
| t
t
| t
no
| f
f
| f
Null
|
FALSE | f
(7 rows)
test=#


testtype, , 
, . 
,
( , ), 
,
. NULL, ,
PostgreSQL ( 
) NULL .
,
PostgreSQL TRUE, FALSE
NULL.


, , 
, :

SQL. , PostgreSQL 
TEXT, , 
. TEXT 
SQL. . 
CHAR, CHAR(N) VARCHAR(N)(. 8.2).

234

8.

8.2.

CHAR

CHAR(N)

N , .

.

VARCHAR(N)

N,
.

TEXT


, VARCHAR,
.


7.1 . PostgreSQL 7.1
1
, 
.

, ?
, .
, Post
greSQL, TEXT,
.
, PostgreSQL.
7.1, 
8 ,
. 7.1 .
!
TEXT ,
, 
, TEXT.
TEXT ,
SQL.
VARCHAR(N) , ,
, . CHAR(N),

. , 
, , ,
CHAR(N).
,
VARCHAR(N). , VARCHAR(N).
, NULL
.

235

.
testtype, 
:
test=#
DROP
test=#
test#
test#
test#
test#
CREATE
test=#
test#
INSERT
test=#
INSERT
test=#
INSERT
test=#
INSERT
test=#

DROP TABLE testtype;


CREATE TABLE testtype (
singlechar
CHAR,
fixedchar
CHAR(13),
variablechar
VARCHAR(128)
);
INSERT INTO testtype VALUES('F', '0349101779', 'The Wasp
Factory');
19164 1
INSERT INTO testtype VALUES('S', '185723457X', 'Excession');
19165 1
INSERT INTO testtype VALUES('F', '0349107688', 'Whit');
19166 1
INSERT INTO testtype VALUES(NULL, '', 'T.B.D.');
19167 1
SELECT * FROM testtype;

singlechar | fixedchar | variablechar


++
F
| 0349101779 | The Wasp Factory
S
| 185723457X | Excession
F
| 0349107688 | Whit
|
| T.B.D.
(4 rows)
test=#


, ,
SQL. singlechar 
, fixedchar 13 , variablechar
128 . ,
, , PostgreSQL
, psql 
.


PostgreSQL , , 
, . 
, :
. , 
, SERIAL,

236

8.

,
. 

, PostgreSQL MONEY.
,
. 8.3:
8.3.

small
integer

SMALLINT

,
32768 32767.

integer

INT

,
2147483648 +2147483647.

serial

SERIAL

INT, ,

PostgreSQL (. 6).

float

FLOAT(N)


N,
8 .

float8

REAL


(8 ).

numeric

NUMERIC(P,S)

P ,
S 
. FLOAT, 
,
, 
.

money

NUMERIC(9,2)

PostgreSQL,
. Post
greSQL MONEY 
NUMERIC(9,2).


, NUMERIC .

. NUMERIC 
,
. 
.
!
, NUMERIC(5,2)
, 12345,12. .
, NUMERIC(5,2) 
999,99 ( ).

237

PostgreSQL 
, , 
.

.
testtype, 
:
test=# DROP TABLE testtype;
DROP
test=# CREATE TABLE testtype (
test#
asmallint
SMALLINT,
test#
anint
INT,
test#
afloat
FLOAT(2),
test#
areal
REAL,
test#
anumeric
NUMERIC(5,2)
test# );
CREATE
test=# INSERT INTO testtype VALUES(2, 2, 2.0, 2.0, 2.0);
INSERT 19244 1
test=# INSERT INTO testtype VALUES(100, 100, 123.456789, 123.456789,
test# 123.456789);
INSERT 19245 1
test=# INSERT INTO testtype VALUES(32768, 123456789, 1.23456789,
test# 1.23456789, 1.23456789);
INSERT 19246 1
test=# INSERT INTO testtype VALUES(32768, 123456789, 123456789.123456789,
test# 123456789.123456789, 123456789.123456789);
ERROR: overflow on numeric ABS(value) >= 10^8 for field with precision 5
scale 2
test=# INSERT INTO testtype VALUES(32768, 123456789, 123456789.123456789,
test# 123456789.123456789, 123.123456789);
INSERT 19247 1
test=# SELECT * FROM testtype;
asmallint | anint
| afloat
|
areal
| anumeric
++++
2 |
2 |
2 |
2 |
2.00
100 |
100 |
123.457 |
123.457 | 123.46
32768 | 123456789 |
1.23457 |
1.23457 |
1.23
32768 | 123456789 | 1.23457e+08 | 1.23457e+08 | 123.12
(4 rows)
test=#


: ,
, , 
.

238

8.

, FLOAT REAL ,
NUMERIC . 
, 
.
, INSERT . 
, FLOAT, REAL , 123.456789
123.457.


(, , 
) .
PostgreSQL ,
, SQL92
(. 8.4):
8.4.

DATE

TIME

TIMESTAMP

INTERVAL

4,
.

PostgreSQL
, PostgreSQL
. 
(. 8.5), . 
PostgreSQL, 
:
8.5. PostgreSQL

Box

cidr inet

 Ipv4, 196.192.12.45

Line

Point

Lseg

polygon

PostgreSQL

239


PostgreSQL , 
, SQL CREATE TYPE.
, , 
, PostgreSQL.
. 
, ,
PostgreSQL, . . , 
, .

PostgreSQL (
SQL) .
, 
, ,
, PostgreSQL.
, 
[] , 
. , 
, , . 

. PostgreSQL
:
test=#
test#
test#
test#
CREATE

CREATE TABLE empworkday (


refcode CHAR(5),
workdays INT[]
);

test=#

empworkday, . 
, work
days. , 
, , {}:
test=#
INSERT
test=#
INSERT

INSERT INTO empworkday VALUES('val01', '{0,1,0,1,1,1,1}');


19290 1
INSERT INTO empworkday VALUES('val02', '{0,1,1,1,1,0,1}');
19291 1

test=#


:
test=# SELECT * FROM empworkday;
refcode |
workdays
+

240

8.
val01 | {0,1,0,1,1,1,1}
val02 | {0,1,1,1,1,0,1}
(2 rows)
test=#

, :
test=# SELECT workdays[2] FROM empworkday WHERE refcode = 'val02';
workdays

1
(1 row)
test=#

1 ( ).
NULL.
 
, 
PostgreSQL.



.
, 
. 
( 4) 
, , .

. PostgreSQL CAST
. :
CAST(columnname AS typedefinitiontoconvertto)

columnname::typedefinitiontoconvertto

SELECT.
, orderinfo
char(10). bpsimple :
SELECT CAST(date_placed AS CHAR(10)) FROM orderinfo;

bpsimple, :
bpsimple=# SELECT CAST(date_placed AS CHAR(10)) FROM orderinfo;
?column?

20000313

PostgreSQL

241

20000623
20000902
20000903
20000721
(5 rows)
bpsimple=#

, .
CAST ( ::) , 
, , 
.

.
, 
, , 5 .
:
bpsimple=# SELECT sell_price::int FROM item WHERE sell_price > 5.0;

PostgreSQL :
ERROR: Unable to identify an operator '>' for types 'numeric' and 'float8'
You will have to retype this query using an explicit cast

sell_price ,
, , numeric, . .
sell_price, .
. !
bpsimple=# SELECT item_id, sell_price::int AS "Guide Price" FROM item WHERE
bpsimple# sell_price > 5.0::NUMERIC(7,2);
item_id | Guide Price
+
1 |
22
2 |
11
5 |
10
6 |
16
7 |
20
11 |
25
(6 rows)
bpsimple=#

!

sell_price (sell_price::int)
(AS "Guide Price"). 
. 

242

8.

WHERE, CAST 
5.0 NUMERIC(7,2), sell_price.
CAST(::);
. ,
. ,
.


PostgreSQL ,
. ,
, 
.
,
(. 8.6):
8.6.

length(columnname)

trim(columnname)

strpos(columnname, string) .
substr(columnname,
position, length)

length , 
, .
1.

round(columnname, length) 
.
Abs(number)

, CAST:
bpsimple=# SELECT substr(description, 3, 5), round(sell_price, 1) FROM item;
substr | round
+
od Pu | 22.0
bik C | 11.5
nux C | 2.5
ssues | 4.0
cture | 10.0
n Sma | 15.8
n Lar | 20.0
othbr | 1.5
man C | 2.5
rrier | 0.0
eaker | 25.3
(11 rows)
bpsimple=#

PostgreSQL

243


,

, .
PostgreSQL 
:

CURRENT_DATE
CURRENT_TIME
CURRENT_TIMESTAMP
CURRENT_USER

, 
( SELECT), :
bpsimple=# SELECT item_id, quantity, CURRENT_TIMESTAMP FROM stock;
item_id | quantity |
timestamp
++
1 |
12 | 20010325 09:22:11+01
2 |
2 | 20010325 09:22:11+01
4 |
8 | 20010325 09:22:11+01
5 |
3 | 20010325 09:22:11+01
7 |
8 | 20010325 09:22:11+01
8 |
18 | 20010325 09:22:11+01
10 |
1 | 20010325 09:22:11+01
(7 rows)
bpsimple=# SELECT CURRENT_USER, CURRENT_TIME;
current_user | time
+
rick
| 09:22:20
(1 row)
bpsimple=#


INSERT UPDATE:
INSERT INTO orderinfo(orderinfo_id, customer_id, date_placed, date_shipped,
shipping) VALUES (5, 8, CURRENT_DATE, NULL, 0.0);

OID
,
PostgreSQL
( ). , 
PostgreSQL ,
oid.
,
. PostgreSQL,

244

8.

,
, :
bpsimple=# SELECT oid, fname, lname FROM customer;
oid | fname | lname
++
19888 | Jenny
| Stones
19889 | Andrew
| Stones
19890 | Alex
| Matthew
19891 | Adrian
| Matthew
19892 | Simon
| Cozens
19893 | Neil
| Matthew
19894 | Richard | Stones
19895 | Ann
| Stones
19896 | Christine | Hickman
19897 | Mike
| Howard
19898 | Dave
| Jones
19899 | Richard | Neill
19900 | Laura
| Hendy
19901 | Bill
| O'Neill
19902 | David
| Hudson
(15 rows)
bpsimple=#

oid
. OID ODBC
. , .

OID .
, 
.


PostgreSQL,
. SQL CREATE TABLE (
), 
. ,
, ,
, , , 
.


, , :
CREATE [TEMPORARY] TABLE tablename (
{ columnname type [ columnconstraint ] [,] }
[ CONSTRAINT tableconstraint ]
) [ INHERITS (existingtablename) ]

245

, ,
. ,
CREATE TABLE, ,
. TEMPORARY 
. , 
. ,
, 
.
, , 
NOT NULL .

, ,
, .
PostgreSQL, INHERITS, 
. 
.

, , 
INHERITS. INHERITS 
.
, 
, 
.
, ,
, ,
( ) . 
, , 
.



, 
,
.  
, .
, 
, NULL. 
. 
,
,
, . 
(constraints) 
.

, , 

246

8.

, 
, . , 
,
.
,
(. 8.7). , 
,
:
8.7.

NOT NULL

NULL.

UNIQUE

, ,
. NULL
. .

PRIMARY KEY

NOT NULL UNIQUE.


PRIMARY KEY (
, NOT NULL UNQIUE,
). 
, 
( , 
) 
, ,
.

DEFAULT value


.

CHECK (condition)
.
REFERENCES

.
.

, REFERENCES, 
, .
( 
PRIMARY KEY). ,
.
, 
NULL UNIQUE. PostgreSQL 
NULL , ,
UNIQUE, NULL.
SQL NULL,
. ,
SQL , (NULL),
, ;
PostgreSQL , NULL,
.

247

.
, 
, . 
test :
bpsimple=# \c test
You are now connected to database test
test=# CREATE TABLE testcolcons (
test#
colnotnull INT NOT NULL,
test#
colunique INT UNIQUE,
test#
colprikey INT PRIMARY KEY,
test#
coldefault INT DEFAULT 42,
test#
colcheck INT CHECK( colcheck < 42)
test# );
NOTICE: CREATE TABLE/PRIMARY KEY will create implicit index
'testcolcons_pkey' for table 'testcolcons'
NOTICE: CREATE TABLE/UNIQUE will create implicit index
'testcolcons_colunique_key' for table 'testcolcons'
CREATE
test=#

, PostgreSQL ,
PRIMARY KEY UNIQUE.
,
, , 
, :
test=#
test#
INSERT
test=#
test#
INSERT
test=#
test#
ERROR:

INSERT INTO testcolcons(colnotnull,


colcheck) VALUES(1,1,1,1,1);
19341 1
INSERT INTO testcolcons(colnotnull,
colcheck) VALUES(2,2,2,2,2);
19342 1
INSERT INTO testcolcons(colnotnull,
colcheck) VALUES(2,2,2,2,2);
Cannot insert a duplicate key into

colunique, colprikey, coldefault,

colunique, colprikey, coldefault,

colunique, colprikey, coldefault,


unique index testcolcons_pkey

test=#

INSERT , . . testcol
cons_pkey .
, , testcol
cons_pkey testcolcons.
!
, ,
tablename_pkey, .

248

8.
test=# INSERT INTO testcolcons(colnotnull, colunique, colprikey, coldefault,
test# colcheck) VALUES(2,2,9,2,2);
ERROR: Cannot insert a duplicate key into unique index
testcolcons_colunique_key
test=#

INSERT ,
testcolcons_colunique_key .
UNIQUE, 
PostgreSQL tablename_columnname_key, 
, :
test=#
test#
INSERT
test=#
test#
ERROR:

INSERT INTO testcolcons(colnotnull, colunique, colprikey, coldefault,


colcheck) VALUES(2,9,9,2,2);
19345 1
INSERT INTO testcolcons(colnotnull, colunique, colprikey, coldefault,
colcheck) VALUES(3,3,3,3,100);
ExecAppend: rejected due to CHECK constraint testcolcons_colcheck

test=#

INSERT , 
CHECK. , tablena
me_columnname, :
test=# UPDATE testcolcons SET colunique = 1 WHERE colnotnull = 2;
ERROR: Cannot insert a duplicate key into unique index
testcolcons_colunique_key
test=#

colunique,
, :
test=# INSERT INTO testcolcons(colnotnull, colunique, colprikey, colcheck)
VALUES(3,3,3,41);
INSERT 19346 1
test=# SELECT * FROM testcolcons ;
colnotnull | colunique | colprikey | coldefault | colcheck
++++
1 |
1 |
1 |
1 |
1
2 |
2 |
2 |
2 |
2
2 |
9 |
9 |
2 |
2
3 |
3 |
3 |
42 |
41
(4 rows)`
test=#

, coldefault (,
), 
.

249

,
psql, \d tablename:
test=# \d testcolcons
Table "testcolcons"
Attribute | Type | Modifier
++
colnotnull | integer | not null
colunique | integer |
colprikey | integer | not null
coldefault | integer | default 42
colcheck | integer |
Indices: testcolcons_colunique_key,
testcolcons_pkey
Constraint: (colcheck < 42)
test=#


PostgreSQL . 
.
,
PostgreSQL. ,
, .
( 9 
), ,
, .


,
( ) 
, . ,
, , . ,
, orderline
, orderinfo_id item_id,
, . . .
(. 8.8):
8.8.

UNIQUE(column list)

, ,
.

PRIMARY KEY(column list) NOT NULL UNIQUE.


PRIMARY KEY 
,
.

250

8.

8.8 ()

CHECK (condition)

REFERENCES

.
.

, 
.
:

(
), 

.
:
test=# CREATE TABLE ttconst (
test# mykey1 int,
test# mykey2 int,
test# mystring varchar(15),
test# CONSTRAINT cs1 CHECK (mystring <> ''),
test# CONSTRAINT cs2 PRIMARY KEY(mykey1, mykey2)
test# );
NOTICE: CREATE TABLE/PRIMARY KEY will create implicit index 'cs2' for table
'ttconst'
CREATE
test=#

, , , Post
greSQL :
test=#
INSERT
test=#
INSERT

INSERT INTO ttconst VALUES(1,1,'Hello');


19381 1
INSERT INTO ttconst VALUES(1,2,'Bye');
19382 1

test=#

, mykey1 1 , . .
mykey2 , :
test=# INSERT INTO ttconst VALUES(1,2,'');
ERROR: ExecAppend: rejected due to CHECK constraint cs1
test=#

251

CHECK 
,  
:
test=#
INSERT
test=#
ERROR:

INSERT INTO ttconst VALUES(2,2,'Chow');


19383 1
INSERT INTO ttconst VALUES(2,2,'Hi');
Cannot insert a duplicate key into unique index cs2

test=#

mykey, , . .
.
, 
. , ( )
.
( bpsimple), 

.


,

, , .
6
INSERT INTO, , 
. :

INSERT INTO , 

, 

INSERT INTO,

, ( 
). , ,
. SQL 

in situ ( ). .
PostgreSQL 
, .

252

8.

, , 
.
:
ALTER TABLE tablename ADD COLUMN columnname columntype
ALTER TABLE tablename RENAME COLUMN oldcolumnname TO newcolumnname
ALTER TABLE oldtablename RENAME TO newtablename

, ,
NULL .
:
test=# \d ttconst
Table "ttconst"
Attribute |
Type
| Modifier
++
mykey1
| integer
| not null
mykey2
| integer
| not null
mystring | character varying(15) |
Index: cs2
Constraint: (mystring <> ''::"varchar")
test=#

:
test=# ALTER TABLE ttconst ADD COLUMN mydate DATE;
ALTER
test=# \d ttconst
Table "ttconst"
Attribute |
Type
| Modifier
++
mykey1
| integer
| not null
mykey2
| integer
| not null
mystring | character varying(15) |
mydate
| date
|
Index: cs2
Constraint: (mystring <> ''::"varchar")
test=#

:
test=# ALTER TABLE ttconst RENAME COLUMN mydate TO birthdate;
ALTER
test=# \d ttconst
Table "ttconst"
Attribute |
Type
| Modifier
++
mykey1
| integer
| not null
mykey2
| integer
| not null
mystring | character varying(15) |

253

birthdate | date
|
Index: cs2
Constraint: (mystring <> ''::"varchar")
test=#

:
test=# ALTER TABLE ttconst RENAME TO ttconst2;
ALTER
test=#

, ALTER TABLE .

. 
, 
.
, customer
title (, . .), . 
,  customer 
, 
.

:

, 

INSERT INTO ... SELECT ... 


, 
(. 10 
).


:
DROP TABLE tablename

!1 
. , !

praestus . . .

254

8.


SQL, , 
, 
, SELECT.
. ( ,
SQL .) ,
, SQL .
( ) 
SELECT 
.
, 
. ,
, ,
,
 ,  
. ,
, . ,
, 
, , , 
.
SQL , 
.
CREATE TEMPORARY TABLE ( CREATE TEMP TABLE, ), CREATE
TABLE. , , 
, 
.
, \dt .


(. 11 
PostgreSQL),
. .
, 
 .
item barcode .
,
, ,
 (. 5).
,
, &
(view).

255

, , :
CREATE VIEW nameofview AS selectstatement;

,
. PostgreSQL 
. ,
, , 
. ( SELECT) 
, , , 
WHERE.

, ( 
, ).
, , 
item. , 
item_id, description sell_price. SELECT 
:
SELECT item_id, description, sell_price FROM item;

()
item_price, :
CREATE VIEW item_price AS SELECT item_id, description, sell_price FROM item;

, 5 , 
item. ,
NUMERIC(7,2).
, ( 
CAST SELECT).

.
item,
, . , 
cost_price ( item 

11 PostgreSQL). ,
sell_price , NUMERIC.
:
bpsimple=# CREATE VIEW item_price AS SELECT item_id, description,
bpsimple# CAST(sell_price AS FLOAT) AS price FROM item;
CREATE
bpsimple=#

256

8.


SELECT,
:
bpsimple=# SELECT * FROM item_price;
item_id | description | price
++
1 | Wood Puzzle | 21.95
2 | Rubik Cube
| 11.49
3 | Linux CD
| 2.49
4 | Tissues
| 3.99
5 | Picture Frame | 9.95
6 | Fan Small
| 15.75
7 | Fan Large
| 19.95
8 | Toothbrush
| 1.45
9 | Roman Coin
| 2.45
10 | Carrier Bag |
0
11 | Speakers
| 25.32
(11 rows)
bpsimple=#


, , 
.
sell_price ,
CAST. , ( AS
price) .
, 
. 
SQL .

.
, 
item barcode ,
.
CREATE VIEW all_items:
bpsimple=# CREATE VIEW all_items AS SELECT i.item_id, i.description,
bpsimple# b.barcode_ean FROM item i, barcode b WHERE i.item_id =
b.item_id;
CREATE
bpsimple=#

257

,
:
bpsimple=# SELECT * FROM all_items;
item_id | description | barcode_ean
++
1 | Wood Puzzle | 6241527836173
2 | Rubik Cube
| 6241574635234
3 | Linux CD
| 6264537836173
3 | Linux CD
| 6241527746363
4 | Tissues
| 7465743843764
5 | Picture Frame | 3453458677628
6 | Fan Small
| 6434564564544
7 | Fan Large
| 8476736836876
8 | Toothbrush
| 6241234586487
8 | Toothbrush
| 9473625532534
8 | Toothbrush
| 9473627464543
9 | Roman Coin
| 4587263646878
11 | Speakers
| 9879879837489
11 | Speakers
| 2239872376872
(14 rows)
bpsimple=#

, , :
SELECT i.item_id, i.description, b.barcode_ean FROM item i, barcode b WHERE
i.item_id = b.item_id;


.
, ,
psql \dv. \d #

:
bpsimple=# \dv
List of relations
Name
| Type | Owner
++
all_items | view | rick
(1 row)
bpsimple=# \d all_items
View "all_items"
Attribute |
Type
| Modifier
++
item_id
| integer
|
description | character varying(64) |
barcode_ean | character(13)
|

258

8.
View definition: SELECT i.item_id, i.description, b.barcode_ean FROM item i,
barcode b WHERE (i.item_id = b.item_id);
bpsimple=#


( all_items), 
, ,
SQL.
, 
, . 

, , 
, 
SQL,
. 
, , 
SQL (, 
, 
). 
, ,
SQL ( 
), .
, !
:
DROP VIEW viewname

, , 
, .



.
bpsimple ,
.
2
(. 8.1).
,
. ,
customer_id orderinfo customer_id customer.
, orderinfo_id, customer_id 
, ,
. , customer_id
customer,

259

customer. 
. orderinfo customer_id
. ? customer_id
orderinfo, 
customer, , . ,
: 
customer  
. , , customer &
. Post
greSQL , ,
. 
, , , 
.

. 8.1. bpsimple

( customer), 
. , orderline 
orderinfo_id, orderinfo_id
orderinfo.
item_id, item_id item
.
item item_id , 
, , 

260

8.

stock. ,
, 
, ( ) 
 .
, , 
, ( or
derinfo_id item_id), (orderline).
.
orderinfo , customer_id
customer_id customer, . ,
, . ,
, 
( 
, ),
.
, ,
( ),
, , 
. ,
CREATE TABLE REFERENCES, 
.
bpsimple bpfinal

.



:
[CONSTRAINT arbitraryname] existingcolumnname type REFERENCES foreign
tablename(columninforeigntable)

, ,
, .
,
. (
)
. 
.
custo
mer_id orderinfo, customer,
REFERENCES
, :
create table orderinfo
(

261


orderinfo_id
customer_id
date_placed
date_shipped
shipping
CONSTRAINT

serial,
integer not null REFERENCES customer(customer_id),
date not null,
date,
numeric(7,2) ,
orderinfo_pk PRIMARY KEY(orderinfo_id)

);

, orderinfo_pk.
REFERENCES .


, 
, 
, PRIMARY KEY. , 
, 
.
, 
, 
.


, :
[CONSTRAINT arbitraryname] FOREIGN KEY (columnlist) REFERENCES foreign
tablename(columnlistinforeigntable)

orderinfo, 
: customer_id , . .
customer_id, 
customer.
create table orderinfo
(
orderinfo_id
serial ,
customer_id
integer not null,
date_placed
date not null,
date_shipped
date ,
shipping
numeric(7,2) ,
CONSTRAINT
orderinfo_pk PRIMARY KEY(orderinfo_id),
CONSTRAINT orderinfo_customer_id_fk FOREIGN KEY(customer_id) REFERENCES
customer(customer_id)
);

orderinfo ( 
),
, :

262

8.
bpfinal=# DROP SEQUENCE orderinfo_orderinfo_id_seq;
DROP
bpfinal=# DROP TABLE orderinfo;
DROP
bpfinal=# CREATE TABLE orderinfo
bpfinal# (
bpfinal#
orderinfo_id
serial,
bpfinal#
customer_id
integer not null,
bpfinal#
date_placed
date not null,
bpfinal#
date_shipped
date,
bpfinal#
shipping
numeric(7,2),
bpfinal#
CONSTRAINT
orderinfo_pk PRIMARY
bpfinal#
KEY(orderinfo_id),
bpfinal#
CONSTRAINT orderinfo_customer_id_fk FOREIGN KEY(customer_id)
bpfinal#
REFERENCES customer(customer_id)
bpfinal# );
NOTICE: CREATE TABLE will create implicit sequence
'orderinfo_orderinfo_id_seq' for SERIAL column 'orderinfo.orderinfo_id'
NOTICE: CREATE TABLE/PRIMARY KEY will create implicit index 'orderinfo_pk'
for
table 'orderinfo'
NOTICE: CREATE TABLE will create implicit trigger(s) for FOREIGN KEY
check(s)
CREATE
bpfinal=#

,
NOTICE CREATE, :
CREATE TABLE will create implicit trigger(s) for FOREIGN KEY check(s)

, ( 
) .
orderinfo 
SQL:
bpfinal=# \i
INSERT 20325
INSERT 20326
INSERT 20327
INSERT 20328
INSERT 20329

pop_orderinfo.sql
1
1
1
1
1

bpfinal=#

, , (
) , orderinfo 
, ,
orderinfo customer_id customer_id

263

customer. ,
customer, orderinfo.

.
, customer_id 
orderinfo:
bpsimple=# select orderinfo_id, customer_id from orderinfo;
orderinfo_id | customer_id
+
1 |
3
2 |
8
3 |
15
4 |
13
5 |
8
6 |
8
(6 rows)
bpsimple=#

, orderinfo customer_id 
customer ,
, 3, 8, 13 15.
, ( orderinfo_id, 2, 5 6)
.
customer customer_id, 3:
bpfinal=# DELETE FROM customer WHERE customer_id = 3;
ERROR: orderinfo_customer_id_fk referential integrity violation  key in
customer still referenced from orderinfo
bpfinal=#

PostgreSQL . , 
(orderinfo_customer_id_fk),
.
, PostgreSQL <unnamed>. Post
greSQL customer,
orderinfo:
bpfinal=# DELETE FROM customer WHERE customer_id = 4;
DELETE 1
bpfinal=#


PostgreSQL , 
, , customer,

264

8.

, ,
( orderinfo).

, . 
, , 
, .
PostgreSQL ( INSERT)
orderinfo ,
:
bpfinal=# INSERT INTO orderinfo(customer_id, date_placed, shipping)
VALUEFS(250, '07252000', 0.00);
ERROR: orderinfo_customer_id_fk referential integrity violation  key
referenced from orderinfo not found in customer
bpfinal=#

, 
. , 
. 
orderinfo , 
.
create_tables.sql,
, ,
orderinfo, orderline, stock barcode.
orderline, 
orderinfo_id orderinfo, item_id
item. , 
, , 
:
create table orderline
(
orderinfo_id
integer
not null,
item_id
integer
not null,
quantity
integer
not null,
CONSTRAINT
orderline_pk PRIMARY KEY(orderinfo_id,
item_id),
CONSTRAINT orderline_orderinfo_id_fk FOREIGN KEY(orderinfo_id) REFERENCES
orderinfo(orderinfo_id),
CONSTRAINT orderline_item_id_fk FOREIGN KEY(item_id) REFERENCES
item(item_id)
);


,  .
, ,
, 

265

,
orderinfo , custo
mer, , ,
.
:

customer

item

orderinfo

orderline

stock

barcode



( 
, ).

SQL .
, orderinfo , 
customer, 
customer_id. , . .
customer_id ( ,
SERIAL!) orderinfo ,
, customer_id,
orderinfo, customer_id 
customer.
customer_id orderinfo,
customer , customer 
, orderinfo.


SQL 
. DEFERRABLE
, :
create table orderinfo
(
orderinfo_id
customer_id
date_placed
date_shipped
shipping

serial ,
integer not null,
date not null,
date ,
numeric(7,2) ,

266

8.
CONSTRAINT
orderinfo_pk PRIMARY KEY(orderinfo_id),
CONSTRAINT orderinfo_customer_id_fk FOREIGN KEY(customer_id) REFERENCES
customer(customer_id)DEFERRABLE
);

. Post
greSQL , 
. 
( 9) DEFER
RABLE, PostgreSQL ,
. ,
SQL, ,
, .
, , customer_id 
customer, customer_id
orderinfo, , PostgreSQL 
.
.

ON UPDATE ON DELETE

, 
(UPDATE) (DELETE). . 
, (CASCADE) 
, , NULL (SET
NULL), . . .
:
create table orderinfo
(
orderinfo_id
serial ,
customer_id
integer not null,
date_placed
date not null,
date_shipped
date ,
shipping
numeric(7,2) ,
CONSTRAINT
orderinfo_pk PRIMARY KEY(orderinfo_id),
CONSTRAINT orderinfo_customer_id_fk FOREIGN KEY(customer_id) REFERENCES
customer(customer_id) ON DELETE CASCADE
);

PostgreSQL,
customer, customer_id, order
info, PostgreSQL
orderinfo. , , , 
. 
, 
, ,
.

267

SET NULL (UPDATE); 


:
create table orderinfo
(
orderinfo_id
serial ,
customer_id
integer not null,
date_placed
date not null,
date_shipped
date ,
shipping
numeric(7,2) ,
CONSTRAINT
orderinfo_pk PRIMARY KEY(orderinfo_id),
CONSTRAINT orderinfo_customer_id_fk FOREIGN KEY(customer_id) REFERENCES
customer(customer_id) ON UPDATE SET NULL
);

, customer ,
customer_id, orderinfo 
NULL. ,
. customer_id
NOT NULL, NULL.
, , orderinfo
customer_id.
? , .
, :
ON UPDATE SET NULL ON DELETE CASCADE

(ON UPDATE ON DELETE)


. .

UPDATE DELETE
, CASCADE DELETE
NULL  , 
.
10 ,

, 
.

, 
PostgreSQL,
SQL, PostgreSQL, 
.
, 
, , 
, , CURRENT_USER.

268

8.

, . 
:
. , 

.

,
. ,
, 
, , ,
, 
.


PostgreSQL, 
, , ( 
) PostgreSQL 
. 
, , 
, ,
.
,
, 
. , PostgreSQL,
,  .
.

, , 
.
,
PostgreSQL , 
. ,

,
. , PostgreSQL

. 
, 
.

270

9.

ACID

ANSI

?
,
. , (, ) 
,
, 
,
SQL.  , 
, ( 
).
:
, 
, 
. ,
,
,
. , 
!
, ANSI SQL, PostgreSQL,

.
, 
.

?
,
, . 
. PostgreSQL 
:

BEGIN WORK, .

271

COMMIT WORK, ,

.

ROLLBACK WORK, , 
, , 
, .
, BEGIN WORK 
.

ANSI/ISO SQL BEGIN WORK, 


( 
),
.
ROLLBACK WORK, COMMIT WORK WORK .

,
, 
.
, 
. , 
, 
, 
.
, .
, 
. , .
,
. , 
, ,
. ,
, , 
.
, ,
, ,
.
, 
, , ,
. , .
.
, , 
:
.
, .
, .
.

272

9.
.
.
.

,

. .
(. 9.1):
9.1.
1

1
?

1
1

, 1

, 

,  1


1
1

( 1
)

 0





1

, 

. , 
,
.

273

, 

,
. .


. , ,
, 
. 
, 
, ,
.
,
, , 
. ,
,
.
: ,
, 

;
.


(ACID) ,
, :

(Atomicity)
,
. 
, .

.
, ,
,
SQL.

(Consistency)

. 8,
, 
(deferrable). , 
.
.

274

9.

(Isolation)
,
, 
.
, 
, , 
. , , 
(
). ,

.
.

(Durability)
,
.

, .
PostgreSQL, ,
.
. 
, . 
, 
, 
, 
.

, 
(
, , 
). , ,
,
.
, ,
.



, ,
.

. , 

275

SQL, ,
, ,
. , 

, , , .
, 
.
. 9.1:

BEGIN WORK

2
3
4

SQL
SQL
SQL
ROLLBACK WORK

. 9.1.
( )

5 ,
, , 
ROLLBACK WORK COMMIT WORK (. 9.2):

BEGIN WORK

SQL
SQL
SQL
COMMIT WORK

2
3
4

. 9.2.
( )

5 
, , 
.
, PostgreSQL,
, , .
,
. PostgreSQL COMMIT

276

9.

WORK , ,
, . .
, , .
, 
.

.
, 
, David Dave,
ROLLBACK :
bpfinal=#
BEGIN
bpfinal=#
fname

David
(1 row)
bpfinal=#
UPDATE 1
bpfinal=#
fname

Dave
(1 row)
bpfinal=#
ROLLBACK
bpfinal=#
fname

David
(1 row)
bpfinal=#

BEGIN WORK;
SELECT fname FROM customer WHERE customer_id = 15;

UPDATE customer SET fname = 'Dave' WHERE customer_id = 15;


SELECT fname FROM customer WHERE customer_id = 15;

ROLLBACK WORK;
SELECT fname FROM customer WHERE customer_id = 15;


BEGIN WORK.
, fname custo"
mer_id, 15. SELECT ,
. ROLLBACK WORK. PostgreSQL

, , BEGIN WORK,
( SELECT)
customer_id = 15 , .
PostgreSQL WORK BEGIN WORK, COMMIT WORK ROLLBACK
WORK , PostgreSQL 
BEGIN, COMMIT ROLLBACK. 
.

277


. , 
UPDATE INSERT,
:
bpfinal=# BEGIN WORK;
BEGIN
bpfinal=# INSERT INTO customer(title, fname, lname, addressline, town,
bpfinal"# zipcode, phone) VALUES('Mr', 'Steven', 'Harvey', '23 Millbank
bpfinal"# Road', 'Nicetown', 'NT1 1EE', '267 4323');
INSERT 21099 1
bpfinal=# UPDATE item SET sell_price = 99.99 WHERE item_id = 2;
UPDATE 1
bpfinal=# ROLLBACK WORK;
ROLLBACK
bpfinal=# SELECT fname, lname FROM customer WHERE lname = 'Harvey';
fname | lname
+
(0 rows)
bpfinal=# SELECT * FROM item WHERE item_id = 2;
item_id | description | cost_price | sell_price
+++
2 | Rubik Cube |
7.45 |
11.49
(1 row)
bpfinal=#

, INSERT, 
, ( UPDATE)
item .


,
.
, PostgreSQL 
. PostgreSQL 
BEGIN WORK 
, 
. 
, SQL. ,
,
, .

BEGIN WORK, . COMMIT WORK
ROLLBACK WORK 
BEGIN WORK, ,
, BEGIN
WORK .

278

9.

PostgreSQL ,

BEGIN WORK .
PostgreSQL
, .
, .
, PostgreSQL (
) ,
.
, , 
( ).
PostgreSQL ,

, , 
. , 
, .
, 
. ,
,
. 


.

. ,
, 
.
COMMIT WORK, , 
, .

, , .
, , ( ,
SQL) 5 ,
ROLLBACK WORK, ,
.
5 .

, 
, ,
,
.

279

ANSI
, 
, 
. ,
. 
,
. 
,
, 
.
, 
, ANSI/
ISO SQL 
, . 

, 
.
, 
. 
PostgreSQL , 
, .


ANSI/ISO SQL 
,
.

(dirty reads), 
 SQL, , , 
, ,
, .
, ( )
, .
, , .
, ,
ROLLBACK WORK. 

COMMIT.
(. 9.2) ,
fname
customer_id, 15. , 
( ) ,
PostgreSQL , .

280

9.

9.2.

, ,

1

,
, 


David

David

David

Dave

Dave

David

Dave

Dave

Dave

BEGIN WORK
UPDATE customer SET
fname='Dave'
WHERE customer_id = 15;
COMMIT WORK
BEGIN WORK
UPDATE customer SET
fname = 'David' WHERE
customer_id = 15;

Dave

David

David

Dave

Dave

Dave

Dave

ROLLBACK WORK

, 
, .
, ,
ROLLBACK WORK.
PostgreSQL 
.


, 
. (unrepeatable reads)
, , 
, .
, , 
. , ,
. 9.3:
9.3.

BEGIN WORK
David

,



BEGIN WORK
David

,
,


BEGIN WORK
David

281

,



,
,


Dave

David

David

Dave

Dave
COMMIT WORK
BEGIN WORK

David
COMMIT WORK
BEGIN WORK

Dave

Dave

UPDATE customer SET


fname = 'Dave' WHERE
customer_id = 15;
COMMIT WORK

SELECT fname FROM


customer WHERE cus"
tomer_id = 15;

,
, ,
.
, 
, ,
.
PostgreSQL ,
,
.
(phantom reads)

, 
, ,
, .
, item.
1 ,
(. 9.4):
9.4.
1
BEGIN WORK
UPDATE item SET sell_price = sell_price + 1;

2
BEGIN WORK
INSERT INTO item(.) VALUES();

COMMIT WORK
COMMIT WORK

282

9.

( sell_price)
, 2? INSERT
, UPDATE , ,
. 
, , ,
1 , 
UPDATE, .

, 
, PostgreSQL
.


, , ,
, 
. , ,
, 
.
, 
, item (. 9.5):
9.5. :
item
1

2
,



21.95
15.23
22.55
16.00
BEGIN WORK
BEGIN WORK
SELECT cost_price,
15.23, 21.95 SELECT cost_price,
15.23, 21.95
sell_price from item WHERE
sell_price from item
item_id = 1;
WHERE item_id = 1;
UPDATE item SET cost_price
= 15.23, sell_price =
22.55 WHERE item_id = 1;
15.23, 22.55
COMMIT WORK
15.23, 22.55
UPDATE item SET
cost_price = 16.00,
sell_price = 21.95
WHERE item_id = 1;
15.23, 22.55
16.00, 21.95

283

2
,

COMMIT WORK
16.00, 21.95

16.00, 21.95

sell_price, 1, ,
 ,  , 2 
sell_price, , 
, , 1.
, ,
, .
, 
. 
, 
, 
, . , 
, .
, 
, .
, , 
sell_price, . 

, , UPDATE (. 9.6):
9.6. : UPDATE
1

2
,


21.95 22.55


21.95 22.99

BEGIN WORK
Read sell_price where
21.95
item_id = 1
UPDATE item SET cost_price
= 15.23, sell_price = 22.55
WHERE item_id = 1 and
sell_price = 21.95;
22.55
COMMIT WORK

BEGIN WORK
Read sell_price where
item_id = 1

21.95

21.95
22.55

284

9.

9.6 ()
1

2
,


UPDATE item SET cost_price =
16.00, sell_price = 21.95
WHERE item_id = 1 and
sell_price = 21.95;

, . . 
,
sell_price

, . . ,
( COMMIT) , 
UPDATE,
.

ANSI/ISO
, , ,
ANSI/ISO , 
. ANSI/ISO

, (. 9.7):
9.7. ANSI/ISO

ANSI/ISO

Read uncommitted

( )

Read committed
( )

Repeatable read
( )

Serializable (
)

, Read uncommit
ted Read committed Repeatable read 
Serializable 
.

285

SET TRANSAC"
TION ISOLATION LEVEL, :
SET TRANSACTION ISOLATION LEVEL { READ COMMITTED | SERIALIZABLE }

READ COMMITTED.
, PostgreSQL 
l Repeatable read,
Read uncommitted. , Read uncom
mitted 
, , 
, 
( ), .
Repeatable read
, ,
, , 
.
, 
Read commit
ted Serializable.

(Auto Commit)

BEGIN WORK COMMIT ( ROLLBACK) WORK.
, ,
BEGIN WORK.
PostgreSQL 
(auto commit mode),
(chained mode) (implicit transaction
mode), SQL, 
, ,
.
, ,
SQL,
, 
COMMIT ROLLBACK.
SQL, , 
, SET CHAINED
Sybase, SET IMPLICIT_TRANSACTIONS Microsoft SQL Server.
PostgreSQL BEGIN WORK, 
, 
,
COMMIT ROLLBACK.

286

9.

SQL SQL
,
SQL , 
COMMIT WORK ROLLBACK WORK. SQL 
BEGIN WORK. ,
PostgreSQL, BEGIN WORK, 
.

, 
, 

. :

(shared lock), 
,
.

,
(exclusive lock),
.

, , ,
, .
, 
, .

, 
. PostgreSQL
. PostgreSQL 
, 
(multiversion) , , 
, 
( ).
, , , 
, 
( )
.


, 
? , 
psql
(. 9.8):

287

9.8.
1
UPDATE row 14

2
UPDATE row 15

UPDATE row 15
UPDATE row 14

, ,
.

serializable

repeatable
read

read
commited

read
uncommited

, PostgreSQL 
Read committed.
,
, , 
(. 9.3):

. 9.3.

,
, 

. , .
, , 2 
1,
, 2 .
,
.

.
psql 
(. 9.9).

288

9.

9.9. :
1
BEGIN WORK

2
BEGIN WORK

UPDATE customer SET fname = 'D'


WHERE customer_id = 15;
UPDATE customer SET fname = 'B'
WHERE customer_id = 14;
UPDATE customer SET fname = 'Bill'
WHERE customer_id = 14;
UPDATE customer SET fname = 'Dave'
WHERE customer_id = 15;

, 
:
ERROR: Deadlock detected.
See the lock(l) manual page for a possible cause.

. , 
, , 
. , 
COMMIT WORK, .
PostgreSQL , 
, , , 
.

1 15, 2 
14. 1 14,
, . . 2, 
2 15, ,
1.
PostgreSQL 
, , 
.
,
PostgreSQL. , , ,
, .
, , 
.
: 
.
,
.

289

, : ,

. ,
, ,
1 
. 2
1. , 
,
,
, 
.


, , 
PostgreSQL, 
, .
. SQL 
, Post
greSQL.
.
COMMIT ROLLBACK,
, , 
.
: ,
,
, ROLLBACK, 
.


,
. , 
. , 
, , 
.
, SE"
LECT, FOR UPDATE:
SELECT 1 FROM item WHERE sell_price > 5.0 FOR UPDATE;

, , 
item, sell_price
5. ,

1.

290

9.

.
, custo"
mer, , Nicetown, 
, , .
, 
,
(, , 
, ):
bpfinal=# BEGIN WORK;
BEGIN
bpfinal=# SELECT customer_id FROM customer WHERE town = 'Nicetown' FOR
bpfinal=# UPDATE;
customer_id

3
6
(2 rows)
bpfinal=#

custo"
mer_id, 3 6, ,
UPDATE psql:
bpfinal=# BEGIN;
BEGIN
bpfinal=# UPDATE customer SET phone = '023 3376' WHERE customer_id = 2;
UPDATE 1
bpfinal=# UPDATE customer SET phone = '023 3267' WHERE customer_id = 3;
UPDATE 1
bpfinal=#


<Ctrl>+<C>
, ( COMMIT) 
( ROLLBACK) .

SELECT FOR UPDATE
, 3 6.
customer, 3 6
( , ).


PostgreSQL , , 
, ,
.

291

:
LOCK [ TABLE ] name
LOCK [ TABLE ] name IN [ ROW | ACCESS ] { SHARE | EXCLUSIVE } MODE
LOCK [ TABLE ] name IN SHARE ROW EXCLUSIVE MODE


, 
.
.
, ,
:
LOCK TABLE tablename

:
LOCK TABLE tablename ACCESS EXCLUSIVE MODE.


. ,
, ,
, .

. ,

, SQL
, , .
.
, 
(atomicity), (consistency),
(isolation) (durability) 
.


. 



.
, 
, ( )

.

292

9.

,

.
,
, 
.
, 
, 

PostgreSQL.

10

Post
greSQL, . ,
, PostgreSQL,
, Oracle, .
, PostgreSQL 
SELECT,
,
WHERE. ,
PostgreSQL , 
, SELECT.
PostgreSQL

C .
,
, 
. ,
, Postgr
eSQL.
, C.
, PL/pgSQL,
. , PL/Tcl PL/Perl, 
PostgreSQL
Tcl Perl .
, , ,
.
.

294

10.

,
PL/pgSQL, PostgreSQL,
. , Oracle
PL/SQL, Sybase TransactSQL.
( ) 
PostgreSQL 
. ,
, 
(
), .
,
.
:



PL/pgSQL

SQL

8 SELECT 
. ,
, 
( ,
4 ):
bpfinal=# SELECT * FROM item WHERE cost_price > 4;
item_id | description | cost_price | sell_price
+++
1 | Wood Puzzle |
15.23 |
21.95
2 | Rubik Cube
|
7.45 |
11.49
5 | Picture Frame |
7.54 |
9.95
6 | Fan Small
|
9.23 |
15.75
7 | Fan Large
|
13.36 |
19.95
11 | Speakers
|
19.73 |
25.32
(6 rows)
bpfinal=#

> cost_price
.

295

, 
:
bpfinal=# SELECT * FROM item WHERE (sell_price*100)%100 = 99;
item_id | description | cost_price | sell_price
+++
4 | Tissues
|
2.11 |
3.99
(1 row)
bpfinal=#


, , 
99 .
. 
, ,
, p r
e:
bpfinal=# SELECT * FROM item WHERE description ~* '^[PR].*E$';
item_id | description | cost_price | sell_price
+++
2 | Rubik Cube
|
7.45 |
11.49
5 | Picture Frame |
7.54 |
9.95
(2 rows)
bpfinal=#

, PostgreSQL . 
, 
(
), , 
600 .


PostgreSQL 
, 
.
, 
.
, .
, PostgreSQL
(, , ) WHERE 
SELECT:
bpfinal=# SELECT 1+2*3;
?column?

296

10.
7
(1 row)
bpfinal=# SELECT (1+2)*3 AS answer;
answer

9
(1 row)
bpfinal=#

, 1+2*3 7,
,
?column?. , 
answer.
,
, C
, , 
. C,
, ,

. , 
, .
PostgreSQL
,
. , 
, , 1+23
, (1+2)3. 
, , ,
x = y = z x = (y = z).
PostgreSQL,
, . 10.1:
10.1. PostgreSQL

UNION

SQL SELECT
( CAST)

::
[]

()

( )

* / %

+ 

IS

( TRUE, FALSE NULL)

297

ISNULL

( NULL)

NOTNULL

( NULL)

OR

IN

BETWEEN

LIKE

<>

NOT

AND


,
,

PostgreSQL
(: ;), 
PostgreSQL.
ln() exp().


PostgreSQL . 
. 10.2.
:
10.2.

2+3 5

32 1

2*3 6

3/2 1
3/2.0 1.5
3/2::float8 1.5

22 % 7 1

( )

4^3 64

&

14 & 23 6

14 | 23 31

14 # 23 25

>>

128 >> 4 8

<<

1 << 4 16

298

10.

, 
. 10.3:
10.3.

%2.3 2

4! 24

!!

!!4 24

@2 2

|/

|/64 8

||/

||/64 4

~15 16

. Post
greSQL , 
. , 
.
. 
,
,
.


PostgreSQL
(. 10.4), . 
,
PostgreSQL,
, 
.
TRUE, FALSE. psql
t f:
10.4.

<

2 < 3
'axy' < 'azz'

<=

2 <= 3

<>
!=

2 <> 3
2 != 3

3 = 1+2

>

3 > 2

299

>=

3 >= 2

IN

3 in (1,2,3)

!!=

4 !!= (2,3)

( NOT IN)

PostgreSQL 
. (
)
(. 10.5):
10.5.

||

'abc' || 'def' 'abcdef'

~~

'xyzzy' ~~ '%zz%'

LIKE

!~~

'xyzzy' !~~ '%aa%'

NOT LIKE

'xyzzy' ~ 'y.*y'


. 
^ 

, 
$ ,

~*

'xyzzy' ~* '^X.*Y$'

!~

'xyzzy' !~ 'aa'


( ~)

!~*

'xyzzy' !~* 'AA'


(
~*)


, , UNIX
grep Perl.


PostgreSQL
PostgreSQL ,
, , IP.
PostgreSQL.
PostgreSQL HTML, 
. file://usr/local/pgsql/
doc/html.

300

10.

pg_operator ,
psql
\do \df.

PostgreSQL ,
SELECT.
:

PostgreSQL,

IP

(
) PostgreSQL,
pg_proc. PostgreSQL 7.1
1100 .
\df psql 
. 
\dd.
, 
, , , 
. 
7 8.
PostgreSQL.
, PostgreSQL.

.
int4shl float8mul, (<<) 
(*) , 
.

. 10.6. 
,
.

301

10.6.

abs(x)

degrees(r)
radians(d)
exp(x)

, e

ln(x)

log(x)

10

log(b,x)

, b

mod(x,y)

x y ( )

pi()

pow(x,y)

x y

random()

0.0 1.0

round(x)

round(x,d) 
, d
trunc(x)

Trunc(x,d) , d
ceil(x)

, 

floor(x)

, 

sqrt(x)

cbrt(x)

float8(i)


float8

float4(i)


float4

int4(x)

PostgreSQL
(. 10.7, ):
10.7.

sin

cos

tan

cot

302

10.

10.7. ()

asin

acos

atan

atan2

. a, b, 
atan(b/a)

PostgreSQL SQL
(. 10.8) .
char, varchar text:
10.8. SQL

char_length(s)
character_length(s)

octet_length(s)

, ,

lower(s)

upper(s)

position(s1, s2)

, s1 s2

substring(s from n for m)

m,
n

trim([leading | trailing | s1 s2 ,
both] [s1] from s2)
, . 
, s1

PostgreSQL
.
.
, to_char.
PostgreSQL , printf C,

. ,

, . 
.


, PostgreSQL 
,
. ,

PL/pgSQL

303

 
.
SQL CREATE
FUNCTION, :
CREATE FUNCTION name ( [ ftype [, ...] ] )
RETURNS rtype
AS definition
LANGUAGE 'langname'
CREATE FUNCTION, 
PostgreSQL 
, , C.
C 
.

, 
, :
CREATE FUNCTION add_one(int4) RETURNS int4 AS '
BEGIN
RETURN $1 + 1;
END;
' LANGUAGE 'plpgsql';

, 

, PostgreSQL 
. PL/pgSQL,
plpgsql, LANGUAGE.
, 
PostgreSQL 
, C. PL/pgSQL
(shared) .
, .

.
, .

, , PostgreSQL 
. .

PL/pgSQL

PL/pgSQL.
PostgreSQL PL/pgSQL

304

10.

plpgsql.so, /usr/
local/pgsql/lib UNIX Linux, plpgsql.dll 
/usr/lib, Cygwin Microsoft Windows.
PostgreSQL
, .
, 
CPU, , .
.
PostgreSQL 
. PL/pgSQL, 
.
template1,
.

PL/pgSQL bpsimple, 
psql CREATE LANGUAGE 
, . ,
,
PostgreSQL.
createlang:
createlang [options] [langname] dbname

. 10.9:
10.9. createlang

h, host=HOSTNAME

p, port=PORT

U, username=USERNAME
W, password

d, dbname=DBNAME

L, pglib=DIRECTORY

DIRECTORY

l, list

, 

langname ,
. dbname .
, 

postgres:
$ createlang U postgres plpgsql bpsimple L/usr/local/pgsql/lib

PL/pgSQL

305

, ,
createlang
pg_language psql pgAdmin:
$ createlang l bpsimple
Procedural languages
Name | Trusted? | Compiler
++
plpgsql | t
| PL/pgSQL
(1 row)
$ psql d bpsimple
bpfinal=# SELECT * FROM pg_language;
lanname | lanispl | lanpltrusted | lanplcallfoid | lancompiler
++++
internal | f
| f
|
0 | n/a
C
| f
| f
|
0 | /bin/cc
sql
| f
| f
|
0 | postgres
plpgsql | t
| t
|
21571 | PL/pgSQL
(4 rows)
bpfinal=#

,
DROP LANGUAGE psql:
bpfinal=# DROP language 'plpgsql';
DROP
bpfinal=#

.
PL/
pgSQL, . 
, , add_one, :
bpfinal=# CREATE function add_one (int4) RETURNS int4 as '
bpfinal'# BEGIN return $1 + 1; end;' language 'plpgsql';
CREATE
bpfinal=# SELECT add_one(2) AS answer;
answer

3
(1 row)
bpfinal=#

306

10.


CREATE FUNCTION add_one, 
PL/pgSQL, .
SELECT. , PL/pgSQL 
, BEGIN, .
:
bpfinal=#
bpfinal#
bpfinal#
bpfinal'#
bpfinal'#
bpfinal'#
bpfinal'#
bpfinal#
CREATE

CREATE function
add_one(int4) RETURNS int4
AS '
BEGIN
RETURN $1 + 1;
END;
'
LANGUAGE 'plpgsql';

bpfinal=#


PostgreSQL ,
,
.
add_one, . 
, , 
add_one :
bpfinal=# SELECT add_one(3.1);
add_one

4
(1 row)
bpfinal=#

, PostgreSQL add_one, ,
(int4), . 
(3.1) , 
3, .

, add_one:
bpfinal=#
bpfinal#
bpfinal#
bpfinal'#
bpfinal'#
bpfinal'#
bpfinal'#

CREATE function
add_one(float8) RETURNS float8
AS '
BEGIN
RETURN $1 + 1;
END;
'

307

PL/pgSQL
bpfinal# LANGUAGE 'plpgsql';
CREATE
bpfinal=# SELECT add_one(3.1);
add_one

4.1
(1 row)
bpfinal=#

, . . PostgreSQL
add_one. ,
, , 
. , ,
. , 
add_one(int4) add_one(float8).

, , psql \i
.



, ,
. pg_proc:
bpfinal=# SELECT prosrc FROM pg_proc WHERE proname = 'add_one';
prosrc

begin
return $1 + 1;
end;
begin
return $1 + 1;
end;
(2 rows)
bpfinal=#


DROP FUNCTION.
,
,
:
bpfinal=# DROP function add_one(int4);
DROP

308

10.
bpfinal=# DROP function add_one(float8);
DROP
bpfinal=#


PL/pgSQL
, . 
CREATE FUNCTION 
, . , 
, 
.
. , , 
.


, , ,

PL/pgSQL.
PL/pgSQL , , C,
. 
,
,
BEGIN END. 
:
[<<label>>]
[DECLARE declarations]
BEGIN
statements
END;
PL/pgSQL .
.

PL/pgSQL CREATE
FUNCTION, ,
:
CREATE FUNCTION name ( [ ftype [, ...] ] )
RETURNS rtype
AS 'block definition'
LANGUAGE 'plpgsql';

309


PL/pgSQL ,
.
PostgreSQL, int4 float8.
, 
RETURNS .
$1, $2 . ., 
, . ,
ALIAS.
, 
( ) :
 geom_avg
 get a geometric average of two integers
create function geom_avg(int4, int4) returns float8 as '
begin
return sqrt($1 * $2::float8);
end;
' language 'plpgsql';


, sqrt
. , 
, , sqrt(int4)
.

( ), PL/pgSQL
. 
: .
SQL 
(). , 
, :

create 
function 



. C C++, 
/* */:
/*
,

310

10.
*/
create function blah() returns integer as '
begin
/*
func();
*/
return 1;
end;
' language 'plpgsql';

, 

 
.

PL/pgSQL , 
. 
, PostgreSQL, , 
, ,
.
DECLARE
DECLARE .
C C++, ,
, , 
. ,
, , 
:
DECLARE
n1 integer;
n2 integer;
BEGIN
 n1 n2
n2 := 1;
DECLARE
n2 integer;  n2
n3 integer;
BEGIN
 n1, n2 n3
n2 := 2;
END;
 n3
 n2 1
END;

311

, ,
. 
, . 
PL/pgSQL (. 10.10):
10.10. PL/pgSQL
alias

begin

bpchar

Char

constant

debug

declare

Default

diagnostics

else

end

Exception

execute

exit

for

From

Get

if

in

Into

loop

not

notice

Null

perform

processed

raise

Record

rename

result

return

Reverse

select

then

to

Type

varchar

when

while

, 
, 
.

ALIAS
, . 

.
ALIAS :
name ALIAS FOR $n;

name,
. ,
geom_avg :
create function geom_avg(integer, integer) returns float8 as '
declare
first alias for $1;
second alias for $2;
begin
return sqrt(first * second::float8);
end;
' language 'plpgsql';

312

10.

RENAME
RENAME.
, ,
,
, . . .
RENAME :
RENAME original TO new;


, 
() . :
name [CONSTANT] type [NOT NULL] [:= value];

CONSTANT , 
. , 
.
NOT NULL PostgreSQL 
, 
NULL.
, 
. , 
now timestamp, 

, .
(type) PostgreSQL. 
,
, . 
,

. :
builtintype
variable%TYPE
table.column%TYPE

:
n integer := 1;
mypi constant float8 := pi();
pizza_pi mypi%TYPE;
mydesc item.description%type := ''extra large size pizza'';

mydesc, 
item .
, , char(64), char(80), ,

313

mydesc, Postgre
SQL . ,
, 
,
( ).



. .

ROWTYPE

ROWTYPE:
name table%ROWTYPE;

, 
, , 
. :
contact customer%ROWTYPE;

contact,
customer. 
variable.field. :
DECLARE
contact customer%ROWTYPE;
address text;
BEGIN
contact.zipcode := ''XY1 6ZZ'';
contact.fname := NULL;
address := contact.addressline || contact.town;
END;

RECORD
RECORD. 
ROWTYPE, 
. , 
, 
. ,
, 
.
SELECT. :
name RECORD;

314

10.

PL/pgSQL 
. :
reference := expression;

reference , 
rowtype record. (expression)
,
, , 
. :
n1: = 23;
long_variable_names_are_OK := (n1 + 45)/2;
f2 := add_one(n1)::float8 * sqrt(2.0);
/*
: */
contact.zipcode := ''AB12 3CD'';

SELECT INTO

SELECT. SELECT INTO
, , .
SQL SELECT:
SELECT expressions INTO target [FROM ...];

SELECT 
:
SELECT
SELECT
SELECT
SELECT

sqrt(2.0) INTO sqrt2;


add_one(n1) INTO n1;
1,2,3,4 INTO n1, n2, n3, n4;
''Mole'', ''Adrian'' INTO contact.lname, contact.fname;

ROWTYPE (
),
:
DECLARE
product item%ROWTYPE;
BEGIN
select NULL, ''Widget'', ''1.45'', ''1.99'' into product;
END;


, PostgreSQL 

315

.
NUMERIC(7,2), 
, .
PostgreSQL SE
LECT, :=. SELECT
. 
FROM () WHERE. 
:
SELECT * INTO product FROM item WHERE item_id = 9;

, SELECT
, . . ,
, , 
. ,
, SELECT, 
.
, SELECT ,
. PostgreSQL 
FOUND, 
SELECT INTO.
, :
SELECT * INTO product FROM item WHERE description ~~ ''%Cube%'';
IF NOT FOUND THEN
 take some recovery action
END IF;

PERFORM
, 
SELECT, ,
, .

PERFORM:
PERFORM <>;

PERFORM SELECT
SPI .


PL/pgSQL , 
: , ,
.

316

10.



RETURN:
RETURN <>;


. ,
, . 
,
, .
PL/pgSQL , 
, RETURN 
, .


,
 , .
,
.
PostgreSQL
:
RAISE level 'format' [, variable ...];

RAISE ,
.
PostgreSQL (. 10.11):
10.11.

DEBUG ()

( )

NOTICE ()

EXCEPTION () 

DEBUG 
. NOTICE 
.

NOTIFY. EXCEPTION ,
. 

PostgreSQL.

317

format .
% 
. printf C, RAISE 
, .
:
RAISE DEBUG '' The value of n is %'', n;

PostgreSQL, /usr/local/pgsql/data/postmaster.log,
, :
DEBUG: The value of n is 4

:
create function scope() returns integer AS '
BEGIN
DECLARE
n integer := 4;
BEGIN
RAISE DEBUG ''n is %'', n;
return n;
END;
' language 'plpgsql';

psql,
:
bpfinal=# SELECT scope();
scope

4
(1 row)
bpfinal=#

RAISE NOTICE,
psql, , :
bpfinal=# SELECT scope();
NOTICE: n is 4
scope

4
(1 row)
bpfinal=#

, EXCEPTION
:
bpfinal=# SELECT scope();
ERROR: n is 4
bpfinal=#

318

10.


PL/pgSQL ,
,

. ,
PL/pgSQL. 
, ,
, , IF.
IF,THEN,ELSE
IF expression
THEN
statements
[ELSE
statements]
END IF;

expression TRUE, 
THEN IF. ,
ELSE, .
, 
IF, IF
THEN ELSE.
NULLIF CASE
SQL, 
.
NULLIF CASE, PostgreSQL 
SQL.
NULLIF NULL, input 
value, input
:
NULLIF(input, value)

NULL, input = value


TRUE, input.
CASE
. :
CASE
WHEN expression
THEN expression
...
ELSE expression
END;

319

WHEN/THEN , . 
THEN,
WHEN, TRUE. 
WHEN, 
ELSE. , , 
, res 5, 6 7 , 
n2 1, 2  :
res := CASE
WHEN
THEN
WHEN
THEN
ELSE
END;

n2 = 1
5
n2 = 2
6
7

PL/pgSQL
(
).
,
, EXIT:
[<<label>>]
LOOP
statements
END LOOP;

LOOP PL/pgSQL , BE


GIN ... END. EXIT,
. , 
C, break ,
C:
The EXIT statement
EXIT [label] [WHEN expression];

LOOP, label, , 
, 
. LOOP
LOOP. , 
. WHEN, EXIT
, expression TRUE.
:
<<infinite>>
LOOP

320

10.
n := n + 1;
EXIT infinite WHEN n >= 10;
END LOOP;

WHILE, 
, .
WHILE
[<<label>>]
WHILE expression
LOOP
statements
END LOOP;

, 
, FOR:
FOR name IN [REVERSE] from .. to
LOOP
statements
END LOOP;


, from to.
name.
,
. REVERSE 
, name
.
FOR
FOR:
FOR cid IN 1 .. 15
LOOP
SELECT * INTO row FROM customer
WHERE customer_id = cid;

END LOOP;

15 , cid 
1 15, row.

, customer,
15 :
SELECT COUNT(*) INTO ncustomers FROM customer;
FOR cid IN 1 .. ncustomers
...

321


FOR,
, 
, SELECT:
FOR row IN SELECT ...
LOOP
statements
END LOOP;

, SELECT, row 
statements. row,
, 
ROWTYPE RECORD. 
,
EXIT.
, psql,
:
DECLARE
row record;
BEGIN
FOR row IN SELECT * FROM customer
LOOP
RAISE NOTICE ''Family Name is %'', row.lname;
END LOOP;
END:

, PL/pgSQL ,
.

.
, ,
, 
. 
stock, ,
. 
.
, 

. reorders stock , 
.
reorders.
( )
reorders:

322

10.


drop table reorders;
create table reorders
(
item_id
integer,
message text
);
 reorders
 stock, ,

create function reorders(int4) returns integer as '
declare
min_stock alias for $1;
reorder_item integer;
reorder_count integer;
stock_row stock%rowtype;
msg text;
begin
select count(*) into reorder_count from stock
where quantity <= min_stock;
for stock_row in select * from stock
where quantity <= min_stock
loop
declare
item_row item%rowtype;
begin
select * into item_row from item
where item_id = stock_row.item_id;
msg = ''order more '' ||
item_row.description || ''s at '' ||
to_char(item_row.cost_price,''99.99'');
insert into reorders
values (stock_row.item_id, msg);
end;
end loop;
return reorder_count;
end;
' language 'plpgsql';

sproc.sql (
Wrox, http://www.wrox.com).
( 
3), 3, 
, 3 :
bpfinal=# \i sproc.sql
DROP
CREATE

323

CREATE
bpfinal=# SELECT reorders(3);
reorders

3
(1 row)
bpfinal=#

reorders ,
:
bpfinal=# SELECT * SELECT reorders;
item_id |
message
+
2 | order more Rubik Cubes at 7.45
5 | order more Picture Frames at 7.54
10 | order more Carrier Bags at
.01
(3 rows)
bpfinal=#

reorders CREATE
TEMPORARY TABLE,
. CREATE TABLE,
reorders . , 
, , ,
.
,
stock:
bpfinal=# SELECT * FROM stock;
item_id | quantity
+
1 |
12
2 |
2
4 |
8
5 |
3
7 |
8
8 |
18
10 |
1
(7 rows)
bpfinal=#


reorders SELECT 
stock, . 
, SELECT. ,
INSERT reorders,
. 

324

10.

reorders SELECT,
stock.
,
.
,
item. ,
, , , 
, ,  
.



. 
, 
, ,
. 
SELECT UPDATE :
INSERT INTO reorders VALUES (stock_row.item_id, msg);



. PostgreSQL ,
,
.
PL/pgSQL EXECUTE,
SQL, 
:
EXECUTE querystring


, .

. 
: 
quote_ident,
, ,
quote_value.
, , 
:
EXECUTE ''UPDATE ''
|| quote_ident(tablename)
|| '' SET ''
|| quote_ident(columnname)

325

SQL
|| '' = ''
|| quote_literal(columnvalue)
|| '' WHERE ''
...;

, 
, . .
.
FOR
SELECT .
:
FOR row IN EXECUTE querystring
LOOP
statements
END LOOP;

SQL
PL/pgSQL
, ,
SQL.
'sql' SQL PostgreSQL
PL/pgSQL.
PL/pgSQL, SQL ,
$1, $2 . . 
$1 
. . ,
SQL PostgreSQL. , PL/pgSQL 
, ,
, SQL
. , SQL, , 
SQL,
SELECT.
SQL
,
PL/pgSQL.
SQL ,
. setof,
SELECT,
. , ,
:
CREATE function sqlf(text) RETURNS setof customer AS '
SELECT * FROM customer WHERE town = $1;
' language 'sql';

326

10.

psql, , 
:
bpfinal=# SELECT sqlf('Bingham');
?column?

136842856
136842856
136842856
(3 rows)
bpfinal=#

, psql 
, .
, : co
lumn(function()). ,
Bingham, :
bpfinal=# SELECT lname(sqlf('Bingham')) AS customer;
customer

Stones
Stones
Jones
(3 rows)
bpfinal=#

,
, . 
 reorders.
, 
, ,
. , 
reorders, 
, .
8 , 
, . , 
, 
. ,
PostgreSQL .
:
, , 
, 
, .

327

8 ,

, , , . 
, ,
, 
(, 
, 
). , 
, .
.
, PostgreSQL 
 , 
INSERT, DELETE UPDATE.

 .
,  
.

, , ,
.


CREATE
:

TRIGGER,

CREATE TRIGGER name { BEFORE | AFTER }


{ event [OR ...] }
ON table FOR EACH { ROW | STATEMENT }
EXECUTE PROCEDURE func ( arguments )

event INSERT, DELETE UPDATE.


:
,   .
, , 
:
DROP TRIGGER name ON table;

, DELETE,
INSERT UPDATE. ,
, ,
( ),
( ). ,
. 
.

328

10.
, OR.

, SQL 
.
, : 
. ROW,
, , STATEMENT
.
, , 
, 
.
reorders
reorder_trigger
, stock:
CREATE TRIGGER trig_reorder
AFTER INSERT OR UPDATE ON stock
FOR EACH ROW EXECUTE PROCEDURE reorder_trigger(3);

, (trig_reorder 
) , .

, 3.


, , 
, .
,
, .
, 
OPAQUE. OPAQUE 
, , Postgre
SQL .
PostgreSQL , 
.
NULL, , ,
.
AFTER, UPDATE, 
, NULL.
BEFORE
.
NULL, UPDATE , 
, , 
,
.

329

.
, 
reorders :
Create function reorder_trigger() returns opaque AS '
declare
mq integer;
item_record record;
begin
mq := tg_argv[0];
raise notice ''in trigger, mq is %'', mq;
if new.quantity <= mq
then
select * into item_record from item
where item_id = new.item_id;
insert into reorders
values (new.item_id, item_record.description);
end if;
return NULL;
end;
' language 'plpgsql';

, , ,
( psql).
:
bpfinal=# \i sproc.sql
...
CREATE
CREATE
bpfinal=#

,
3 :
bpfinal=# UPDATE stock SET quantity = 3 WHERE item_id = 1;
NOTICE: in trigger, mq is 3
UPDATE 1
bpfinal=#

, , . 
stock , 
reorders, :
bpfinal=# SELECT * FROM reorders;
item_id | message
+
1 | Wood Puzzle

330

10.
(1 row)
bpfinal=#


, stock
INSERT UPDATE. 
,
, reorders.
, 
. , 
$1, $2 . . 
, 
. 
tg_argv tg_argv[0].
, 
, OLD NEW. ROW 
, , . 
, OLD , NEW
( BEFORE).

(. 10.12):
10.12.

NEW

OLD

TG_NAME

,
,

TG_WHEN

, 'BEFORE' 'AFTER',

TG_LEVEL

, 'ROW' 'STATEMENT', 

TG_OP

, 'INSERT', 'DELETE' 'UP


DATE', ,

TG_RELID

, , 

TG_RELNAME

TG_NARGS

, , 

TG_ARGV

, 
, .
NULL

331

, 
, . 
, date_shipped orderinfo 
NULL  , ,
, . 
, ,
, 
, , .

.
create function customer_trigger() returns opaque AS
declare order_record record;
begin

 ,
select * into order_record from orderinfo
where customer_id = old.customer_id
and date_shipped = NULL;
if not found
then
 OK,
raise notice '' '';



for order_record in select * from orderinfo
where customer_id = old.customer_id
loop
delete from orderline
where orderinfo_id = order_record.orderinfo_id;
end loop;

delete from orderinfo
where customer_id = old.customer_id;

return old;
else
 , NULL
raise notice '' '';
return NULL;
end if;
end;
' language 'plpgsql';
create trigger trig_customer before delete on customer
for each row execute procedure customer_trigger();

332

10.

, .
, NULL 
. , :
bpfinal=# UPDATE orderinfo SET date_shipped = NULL WHERE orderinfo_id = 3;
UPDATE 1
bpfinal=# SELECT * FROM orderinfo;
orderinfo_id | customer_id | date_placed | date_shipped | shipping
++++
1 |
3 | 20000313 | 20000317 |
2.99
2 |
8 | 20000623 | 20000624 |
0.00
4 |
5 |
3 |

13 | 20000903 | 20000910
8 | 20000721 | 20000724
15 | 20000902 |

|
|
|

2.99
0.00
3.99

(5 rows)
bpfinal=#

, 15, 
3 , 
, , 
:
bpfinal=# DELETE FROM customer WHERE customer_id = 15;
NOTICE:
DELETE 0
bpfinal=#

, , 
,
orderinfo. ,
, . 
,
.
3 , ,
:
bpfinal=# DELETE FROM customer WHERE customer_id = 3;
NOTICE:
DELETE 1
bpfinal=#

,
:
bpfinal=# SELECT * FROM orderinfo;
orderinfo_id | customer_id | date_placed | date_shipped | shipping
++++
2 |
8 | 20000623 | 20000624 |
0.00
4 |
13 | 20000903 | 20000910 |
2.99

333

?
5 |
3 |

8 | 20000721 | 20000724
15 | 20000902 |

|
|

0.00
3.99

(4 rows)
bpfinal=# SELECT * FROM orderline;
orderinfo_id | item_id | quantity
++
2 |
1 |
1
2 |
10 |
1
2 |
7 |
2
2 |
4 |
2
3 |
2 |
1
3 |
1 |
1
4 |
5 |
2
5 |
1 |
1
5 |
3 |
1
(9 rows)
bpfinal=#
bpfinal=# SELECT customer_id, fname, lname FROM customer;
customer_id | fname | lname
++
1 | Jenny
| Stones
2 | Andrew
| Stones
4 | Adrian
| Matthew
5 | Simon
| Cozens
6 | Neil
| Matthew
7 | Richard | Stones
8 | Ann
| Stones
9 | Christine | Hickman
10 | Mike
| Howard
11 | Dave
| Jones
12 | Richard | Neill
13 | Laura
| Hendy
14 | Bill
| O'Neill
15 | David
| Hudson
(14 rows)
bpfinal=#


?

, , . 
:


, . 
.

334

10.


, 
,
, ,
,
.


PostgreSQL current_user, 
.


, 
, ,
.



, , 
. ,
Microsoft Excel.
, (
) .


PostgreSQL. , PostgreSQL 
,
.
, PostgreSQL, 

PL/pgSQL, SQL . 

.
. 
, , 
. 
, .

, . . ,
. 
, 
, 
.

11
PostgreSQL

, Post
greSQL. , 3 4, 
PostgreSQL, . 
, ,
.

. pgAdmin, 

Microsoft Windows. 5
pgAdmin.

, 
:

, 

( )

336

11. PostgreSQL

PostgreSQL


PostgreSQL ,
, , 
/usr/local/pgsql .
, ,
, /var/lib/pgsql,
,
,
/usr/bin.
,
, , PostgreSQL ,
, .
:
bin
include
lib
doc
man
share
data

bin
bin (. 11.1),
PostgreSQL:
11.1. , bin

postgres

postmaster

, (
, postgres)

337


psql

PostgreSQL

initdb

pg_ctl

PostgreSQL ,

createuser

dropuser

createdb

dropdb

initlocation
pg_dump

pg_dumpall

pg_restore

pg_upgrade

, PostgreSQL

pg_passwd

vacuumdb

, (.
)

ipcclean

pg_config

PostgreSQL

createlang

(. 10)

droplang

ecpg

SQL (. 14)

pg_id

, 

include lib
include lib 
, PostgreSQL.
, libpq 
C, SQL.
libpq ecpg 13 14.

doc
doc PostgreSQL. , 
doc/html/index.html
, .

338

11. PostgreSQL

man
man ,
UNIX. MANPATH, 
man
:
$ MANPATH=$MANPATH:/usr/local/pgsql/man
$ export MANPATH
$ man psql
...

share
share PostgreSQL
, initdb
.

data
data PostgreSQL.
, , (postmaster)
TCP/IP, 
PostgreSQL. , ,
. 11.2:
11.2. , data

PG_VERSION

, PostgreSQL 
(, 7.1)

pg_hba.conf

, 
PostgreSQL

pg_ident.conf

, 
PostgreSQL

postgresql.conf PostgreSQL
postmaster.log

(log file) PostgreSQL ( 


)

postmaster.opts , ,
postmaster
postmaster.pid

, post
master . , 

global base. 
, 
, . . 
data.

339


PostgreSQL
. 3 initdb.
PostgreSQL initdb,
.

PostgreSQL, . . 

. 
, ,
. PostgreSQL
. 
,
:

, .
postgres

(data),

post
gres

initdb  postgres,  root,


initdb . 
. 11.3:
11.3. initdb

D dir

pgdata=dir
i id
sysid=id


. , 
, initdb

W
pwprompt

initdb
. 

, initdb , 
( 
postgres) , ,
template1 .
PostgreSQL 

. createdb,

340

11. PostgreSQL

.
. 
, 
, .
, 
.


PostgreSQL UNIX Linux
, (a listener process), Windows
.
3, postmaster
, 
.
postmaster . 
, 
, 
, , 
$PGDATA.
,
, . 
postmaster 
, postgres, 
.

. 
postgres, , 
postgres , 
postmaster. postmaster
, . 
. 11.4:
11.4. postmaster

B nbufs

nbufs.
8 K. 64 
. 
(. N).

d level

, 
. , 0 ( 
), , 
4.

341

D dir

(/data) dir.
. D , 
PGDATA.

I

TCP/IP .
, ,
, . 
, 
,
.

l


(Secure Sockets
Layer, SSL). i ( ).
SSL.

N cons

,
. 32.
, B.

o "opts"

, 
, 
(postgres). 
PostgreSQL.

p port

TCP,
.
$PGPORT
( 5432).

c name=value . .
.

postmaster , 
.
:
/usr/local/pgsql/data/postmaster.pid



:
postmaster >postmaster.log 2>&1

, postmaster 
, root, 
. (postgres) 3.

342

11. PostgreSQL


PostgreSQL pg_ctl, 
postmaster. ,
, :
pg_ctl start [ w ] [ D datadir ] [ p path ]
[ o options ]
pg_ctl stop [ w ] [ D datadir ]
[ m [ s[mart] ] [ f[ast] ] [ i[mmediate] ] ]
pg_ctl restart [ w ] [ D datadir ]
[ m [ s[mart] ] [ f[ast] ] [ i[mmediate] ] ]
[ o options ]
pg_ctl status [ D datadir ]

pg_ctl,
, (root)
postgres.
pg_ctl . 11.5:
11.5. pg_ctl

D datadir

. $PGDATA.

w

, ,
. pid (process id
) .
60 .

o "options" ,
postmaster .
m mode

(smart, fast immediate).


, :

pg_ctl stop ( restart)


smart ( s), , 
.

fast (f) , 
. , 
, .

immediate (i) , 
. 
. 
.

343

, PostgreSQL, pg_ctl status.


postmaster, 
, , :
# pg_ctl status
pg_ctl: postmaster is running (pid: 486)
Command line was:
/usr/local/pgsql/bin/postmaster 'i' 'D' '/usr/local/pgsql/data'
#

PostgreSQL
. , 
. 
, .
, ,
PostgreSQL, 
, pg_user. 
, pg_user psql:
bpfinal=# SELECT usename, usesysid, usecreatedb FROM pg_user;
usename | usesysid | usecreatedb
++
postgres |
26 | t
neil
|
28 | t
(2 rows)
bpfinal=#


(usesysid) , , 
usecreatedb.
, PostgreSQL
UNIX, Windows Linux.
PostgreSQL 
, 
, .
PostgreSQL
, , 
, PostgreSQL.

PostgreSQL. neil, rick, steve
gavin PostgreSQL author reviewer, 
, neil rick
PostgreSQL author, gavin steve

344

11. PostgreSQL

PostgreSQL reviewer. ,
.

CREATE USER
PostgreSQL createuser, 
PostgreSQL:
createuser [options...] username

createuser (. 11.6) 
, ,
, :
11.6. createuser

h host
.
host host .
p port
. ,
port port postmaster PostgreSQL, 5432.
q
quiet

d
createdb

a
adduser


.

P
pwprompt

.
.

I
sysid id

usesysid 
.

e
echo

, .

createuser, , psql
PostgreSQL .
, e echo createuser:
$ createuser e pwprompt rick
Enter password for user "rick":
Enter it again:
Shall the new user be allowed to create databases? (y/n) n
Shall the new user be allowed to create more new users? (y/n) n
CREATE USER "rick" WITH PASSWORD 'xxx' NOCREATEDB NOCREATEUSER
$

345

SQL ( DDL) CREATE


USER,
:
CREATE USER username
[ WITH
[ SYSID uid ]
[ PASSWORD 'password' ] ]
[ CREATEDB | NOCREATEDB ]
[ CREATEUSER | NOCREATEUSER ]
[ IN GROUP groupname [, ...] ]
[ VALID UNTIL 'abstime' ]

, 
,
CREATE USER ( psql SQL).

DROP USER
PostgreSQL 
SQL DROP USER name psql, 
dropuser:
dropuser [options...] username

dropuser
, createuser,
(. 11.7):
11.7. dropuser

i
interactive

ALTER USER

ALTER USER psql:
ALTER USER username
[ WITH PASSWORD 'password' ]
[ CREATEDB | NOCREATEDB ] [ CREATEUSER | NOCREATEUSER ]
[ VALID UNTIL 'abstime' ]

,
,
, 
, , .

346

11. PostgreSQL

SQL CREATE
GROUP:
CREATE GROUP name
[ WITH
[ SYSID gid ]
[ USER username [, ...] ] ]

, authors, neil rick,


:
bpfinal=# CREATE GROUP authors WITH USER neil, rick;
CREATE GROUP
bpfinal=#
pgAdmin
, 
Microsoft Windows (. 11.1):

. 11.1. Microsoft Windows


pg_group, . 11.8:
11.8. pg_group

groname

.  
, .

grosysid .
grolist

347


ALTER GROUP:
ALTER GROUP name ADD USER username [, ... ]
ALTER GROUP name DROP USER username [, ... ]

DROP
GROUP:
DROP GROUP name

PostgreSQL
, GRANT.

, .
GRANT :
GRANT privilege [, ...] ON object [, ...]
TO { PUBLIC | GROUP group | username }

.11.9:
11.9.

SELECT

INSERT

DELETE

UPDATE

RULE

ALL

PUBLIC , 
; object , 
.
authors customer
, :
bpfinal=# GRANT SELECT,INSERT ON customer TO GROUP authors;
CHANGE
bpfinal=#

REVOKE, GRANT:
REVOKE privilege [, ...]
ON object [, ...]
FROM { PUBLIC | GROUP groupname | username }

348

11. PostgreSQL

rick customer:
bpfinal=# REVOKE ALL ON customer FROM rick;
CHANGE
bpfinal=#

. ,
, authors customer,
rick , . 
, 
rick , .
pgAdmin 
(. 11.2):

. 11.2.

, 
,
. , 
, 
, ,
. , 
, (. 8),
, 
.

349

PostgreSQL 
pg_user. ,
, pg_shadow. 
(SELECT) :
bpfinal=# SELECT * FROM pg_shadow;
ERROR: pg_shadow: Permission denied.
bpfinal=#


pg_user:
bpfinal=# SELECT usename,passwd FROM pg_user;
usename | passwd
+
postgres | ********
neil
| ********
rick
| ********
(3 rows)
bpfinal=#

passwd .
.
pg_user
psql, \d:
bpfinal=# \d pg_user
View "pg_user"
Attribute | Type | Modifier
++
usename
| name
|
usesysid
| integer |
usecreatedb | boolean |
usetrace
| boolean |
usesuper
| boolean |
usecatupd | boolean |
passwd
| text
|
valuntil
| abstime |
View definition: SELECT pg_shadow.usename, pg_shadow.usesysid,
pg_shadow.usecreatedb, pg_shadow.usetrace, pg_shadow.usesuper,
pg_shadow.usecatupd, '********'::text AS passwd, pg_shadow.valuntil FROM
pg_shadow;
bpfinal=#

pg_user
pg_shadow, 
.

350

11. PostgreSQL


. :

PostgreSQL


PostgreSQL psql CREATE
DATABASE, :
CREATE DATABASE name
[ WITH [ LOCATION = 'dbpath' ]
[ TEMPLATE = template ]
[ ENCODING = encoding ] ]


PostgreSQL. 
LOCATION. 
PostgreSQL, initlocation. TEMPLATE EN
CODING . 
( 
PostgreSQL).
psql, ,

template1.

DROP DATABASE:
DROP DATABASE name

, psql.
, ,
template1.
PostgreSQL : createdb dropdb,

UNIX Linux:
createdb [ ... ] dbname [ ]
dropdb [ ... ] dbname

createuser dro
puser, (. 11.10):

351

11.10. createdb dropdb

h host
host host

.
.

p port
port port

. Postgr
eSQL, 5432.

q
quiet

e
echo

, 
.

U name
.
username name .
W
password

D dir
( createdb).
location dir .
E type
( crea
encoding type tedb). 
PostgreSQL.
I
interactive

(
dropdb).

[] createdb 
.


PostgreSQL 
.  
.

, .
, 
, ,
,
, 
. , 

,
. (
) .
PostgreSQL 
,

352

11. PostgreSQL

.
PostgreSQL ,
. 

, . PostgreSQL
:
pg_dump, pg_dumpall pg_restore.
, pg_dump 
( pg_dump
):
$ pg_dump bpfinal > bpfinal.backup

, 
() SQL (
PostgreSQL), 
. pg_dump , ,
, 
, .
:
CREATE SEQUENCE "customer_customer_id_seq" start 1 increment 1 maxvalue
2147483647 minvalue 1 cache 1 ;

 TOC Entry ID 18 (OID 24462)

 Name: customer Type: TABLE Owner: neil

CREATE TABLE "customer" (
"customer_id" integer DEFAULT nextval('"customer_customer_id_seq"'::text)
NOT NULL,
"title" character(4),
"fname" character varying(32),
"lname" character varying(32) NOT NULL,
"addressline" character varying(64),
"town" character varying(32),
"zipcode" character(10) NOT NULL,
"phone" character varying(16),
Constraint "customer_pk" Primary Key ("customer_id")
);

 TOC Entry ID 19 (OID 24462)

 Name: customer Type: ACL Owner:

REVOKE ALL on "customer" from PUBLIC;
GRANT ALL on "customer" to "neil";

353

GRANT INSERT,SELECT on "customer" to GROUP "authors";



 Data for TOC Entry ID 44 (OID 24502) TABLE DATA item

 Disable triggers
UPDATE "pg_class" SET "reltriggers" = 0 WHERE "relname" ~* 'item';
COPY "item" FROM stdin;
1
Wood Puzzle
15.23 21.95
2
Rubik Cube
7.45
11.49
3
Linux CD
1.99
2.49
4
Tissues 2.11
3.99
5
Picture Frame 7.54
9.95
6
Fan Small
9.23
15.75
7
Fan Large
13.36 19.95
8
Toothbrush
0.75
1.45
9
Roman Coin
2.34
2.45
10
Carrier Bag
0.01
0.00
11
Speakers
19.73 25.32
\.


.
,
. , 
, 
.
. ,
, newbpfinal, 
, psql :
$ createdb newbpfinal
$ psql f bpfinal.backup newbpfinal

f , psql ,
.
PostgreSQL
pgAdmin, . 
, , 
, 
pgAdmin
.


( , PostgreSQL),
pg_dumpall (post
gres):
$ su postgres
$ pg_dumpall >all.backup

354

11. PostgreSQL

, 
(, ).
.
, , 
template1.
, pg_dumpall,
SQL . 
, 
:
$ psql f all.backup template1

,
, SQL,
. 
gzip:
$ pg_dump bpfinal | gzip >bpfinal.backup.gz
$ gunzip c bpfinal.backup.gz | psql newbpfinal

pg_dump /, 
, 
.
. 11.11.
pg_dump [dbname] [options]

11.11. pg_dump

h host

, .
.

p port

TCP/IP, .
PostgreSQL 5432.

t table

,  
, .

u

.
.

v

S user

c

. 
.

C

. SQL 
. .

a

, .

355


(), .

s
x

( GRANT REVOKE).

b

(BLOB).

O


.

f file

. 
.

F format

. :
p SQL ( ).
t tar.
c .

Z 0..9

,
0 () 9 ().

(F t F c) 
.
pg_restore:
pg_restore [archive] [options...]

pg_restore
. 11.12:
11.12. pg_restore

h host

, . 
.

p port

TCP/IP, .
5432.

d dbname

dbname,
psql. (BLOBs) 
.

t table

, ,
. .

P proc

( ), 
.

T trig

, .

I index

, 
.

u

.
.

356

11. PostgreSQL

11.12 ()

.

v
l

. U.

U file

,
. .
.

S user


.

c

a

, .

s

(), .

x

( GRANT RE
VOKE).

O


.

f file

.
, .


:
$ pg_dump F c bpsimple >bpsimple.bak
$ createdb bpsimple2
CREATE DATABASE
$ pg_restore d bpsimple2 bpsimple.bak
NOTICE: CREATE TABLE/PRIMARY KEY will create implicit index 'customer_pk'
for table 'customer'
NOTICE: CREATE TABLE/PRIMARY KEY will create implicit index 'item_pk' for
table 'item'
NOTICE: CREATE TABLE/PRIMARY KEY will create implicit index 'orderinfo_pk'
for table 'orderinfo'
NOTICE: CREATE TABLE/PRIMARY KEY will create implicit index 'stock_pk' for
table 'stock'
NOTICE: CREATE TABLE/PRIMARY KEY will create implicit index 'orderline_pk'
for table 'orderline'
NOTICE: CREATE TABLE/PRIMARY KEY will create implicit index 'barcode_pk' for
table 'barcode'
$

bpsimple ,
, bpsimple.bak.

pg_restore.

357


PostgreSQL, 
, 
.
PostgreSQL, . 
, , 
, .
PostgreSQL 
.
,
.
, PostgreSQL
pg_upgrade, .

.



. ,
, . 
, .
, PostgreSQL 
GRANT REVOKE 
. . ,
.
, 
, .
PostgreSQL . 
, , PostgreSQL , 
PostgreSQL postgres. 
.
, 
, , 
. ,
PostgreSQL, postmaster i. 
, 
. , , 
, , 
. , 
PostgreSQL, , 
, , .
, Post
greSQL ,

358

11. PostgreSQL

.
(. 11.13) :
11.13.


trust

password

, 
pg_shadow

Crypt

, 
,

Ident

ident (RFC 1413)

Krb4

Kerberos 
4

Krb5

Kerberos 
5

reject

PostgreSQL, ,
pg_hba.conf Post
greSQL. 
. 
.
pg_hba.conf . 
, , # ( 
).
 . , 

.
:
local database method [argument]

( UNIX,
) 
. 
. 
trust, password, crypt reject.

:
#
local test trust
#

359

local bpfinal crypt


#
local all reject

, PostgreSQL 
. , 
, . 
all , .
password crypt
. , 
PostgreSQL, 
, 
pg_shadow.
,
, .
, 
( 
postmaster i). 
:
host database address netmask method [argument]

IP . 
, 
, .
:
#
host 127.0.0.1 255.255.255.255 trust
#
host 192.168.0.0 255.255.255.0 password
#
host 192.168.1.66 255.255.255.255 reject
# ,
host 192.168.1.0 255.255.255.0 password mypasswords
#

, 192.168.1.0, 
. 
, 
, .
pg_passwd:
pg_passwd password_file

, pg_passwd
. mypasswords, 

360

11. PostgreSQL

, ( ) 
neil, :
$ pg_passwd /usr/local/pgsql/data/mypasswords
File "/usr/local/pgsql/data/mypasswords" does not exist. Create? (y/n): y
Username: neil
New password:
Reenter new password:
$

(
ident Kerberos) Post
greSQL .


PostgreSQL .
, PostgreSQL
, 
,
.
, PostgreSQL
, 
 . 
, TCP,
(postmaster) , 
, with
pgport=number configure.
, p
number postmaster.


PostgreSQL 
configure (
3). , con
figure help:
$ ./configure help
Usage: configure [options] [host]
Options: [defaults in brackets after descriptions]
Configuration:
cachefile=FILE
cache test results in FILE
help
print this message
nocreate
do not create output files
quiet, silent
do not print `checking...' messages
version
print the version of autoconf that created configure
Directory and file names:

361


prefix=PREFIX
[/usr/local/pgsql]
execprefix=EPREFIX
[same as prefix]
bindir=DIR
...
$

install architectureindependent files in PREFIX


install architecturedependent files in EPREFIX
user executables in DIR [EPREFIX/bin]

, 
, 

(. 11.14):
11.14.

prefix

,
/usr/local/pgsql

withpgport=port

TCP , 

withmaxbackends=n

withtcl

Tcl

withperl

Perl

withodbc

ODBC

Post
greSQL pg_config:
pg_config
bindir | includedir | libdir |
configure | version

pg_config , Post
greSQL (bindir), C (in
cludedir) (libdir), Post
greSQL (version):
# pg_config version
PostgreSQL 7.1
#

, 
, pg_config configure.
,
configure, PostgreSQL 
.

362

11. PostgreSQL


PostgreSQL 
, , 
. 
, .
PostgreSQL 
postgresql.conf data. 
,
, . 
, 
.
c,
postmaster.
, 
SQL SET 
.
, 
, .
0,
debug_level 1, postgresql.conf ,
:
debug_level=1

postmaster:
postmaster c debug_level=1

psql set 
, psql:
set debug_level=1;

. 11.15:
11.15.

tcpip_socket

Max_connections 
. 32.
Port

TCP .

Sort_mem

, .

shared_buffers (
2 * Max_connections).
debug_level

,
.

363

PostgreSQL 
.


PostgreSQL,
( ), .
,
, 
. , Post
greSQL , .
.
, 

. PostgreSQL ,

, .
, Post
greSQL, , 
PostgreSQL 
, :

VACUUM

VACUUM
PostgreSQL SQL VACUUM :

:
vacuum [verbose] analyse [table [ (column [, ... ] ) ] ]

PostgreSQL 
, , 
, . 
.
, 9 , , 
, 

. PostgreSQL 
, 
. .

364

11. PostgreSQL

,
, . VACUUM 
, .
VACUUM. 
, . 
customer. VACUUM
:
bpfinal=# vacuum verbose customer;
NOTICE: Relation customer
NOTICE: Pages 1: Changed 1, reaped 1, Empty 0, New 0; Tup 14: Vac 1, Keep/
VTL
0/0, Crash 0, UnUsed 0, MinLen 120, MaxLen 132; Reusing: Free/Avail. Space
6348/0; EndEmpty/Avail. Pages 0/0. CPU 0.00s/0.00u sec.
NOTICE: Index customer_pk: Pages 2; Tuples 14: Deleted 1. CPU 0.00s/0.00u
sec.
VACUUM
bpfinal=#

ANALYZE VACUUM 
, PostgreSQL 
.
, SQL .
PostgreSQL, (
, Newtown, CD
Linux ), ,
. , ,
customer,
, item , 
Linux CD, , , 
.
, 
,
. PostgreSQL , 
. 
. , 
, , 
, ( )
.

SQL EXPLAIN:
explain [verbose] query

:
bpfinal=# EXPLAIN SELECT customer_id customer WHERE zipcode='BG3 8GD';
NOTICE: QUERY PLAN:

365

Seq Scan on customer (cost=0.00..1.18 rows=1 width=4)


EXPLAIN
bpfinal=#


. PostgreSQL 

.
, , PostgreSQL (cost)
customer 0 1.18.
PostgreSQL ,
, zipcode.
, PostgreSQL, 
, .

, .
, VACUUM ANALYZE:
bpfinal=# vacuum analyze;
VACUUM
bpfinal=#

PostgreSQL vacuumdb 
. :
vacuumdb [options] database

vacuumdb . 11.16:
11.16. vacuumdb

h host
host host

.
.

p port
port port

. Post
greSQL, , 5432.

q
quiet

U name
.
username name
W
password

d name
dbname name

,
.

a
all

366

11. PostgreSQL

11.16 ()

z
analyze

v
verbose

, 
.

t object
, 
table object . : , 
, .
PostgreSQL 
VACUUM vacuumdb , 
. , , 
, , ,
, .

, PostgreSQL , 
. 

. 
, ,
(. . 
, ).
PostgreSQL
, . ,
, customer_id ,
(zipcode) 
.

SQL CREATE INDEX:
CREATE [unique] INDEX indexname ON table(column)

unique ,
,
.
,
, ( ). 
, 
.
, 
,
, .

367

, UNIX.
40 000 .
\copy psql, :
bpfinal=# CREATE TABLE words ( word text );
CREATE
bpfinal=# \copy words FROM '/usr/dict/words'
\.
bpfinal=# SELECT count(*) FROM words;
count

45407
(1 row)
bpfinal=#

. PostgreSQL,
, Zulu:
bpfinal=# EXPLAIN SELECT * FROM words WHERE word='Zulu';
NOTICE: QUERY PLAN:
Seq Scan on words (cost=0.00..22.50 rows=10 width=12)
EXPLAIN
bpfinal=#

45 000 PostgreSQL 
22,5. 
, . PostgreSQL
, VACUUM ANALYZE 
:
bpfinal=# VACUUM ANALYZE words;
VACUUM
bpfinal=# EXPLAIN SELECT * FROM words WHERE word='Zulu';
NOTICE: QUERY PLAN:
Seq Scan on words (cost=0.00..843.59 rows=1 width=12)
EXPLAIN
bpfinal=#

PostgreSQL , 
843. 
VACUUM, ,
, 
.

368

11. PostgreSQL

Zulu, 
( , 
, ):
bpfinal=# SELECT * FROM words WHERE word='Zulu';
word

Zulu
(1 row)
bpfinal=#

words , :
bpfinal=# CREATE INDEX words_idx ON words(word);
CREATE
bpfinal=#

, .
(
2 843), :
bpfinal=# EXPLAIN SELECT * FROM words WHERE word='Zulu';
NOTICE: QUERY PLAN:
Index Scan using words_idx on words (cost=0.00..2.09 rows=1 width=12)
EXPLAIN
bpfinal=# SELECT * FROM words WHERE word='Zulu';
word

Zulu
(1 row)
bpfinal=#

, 
, , PostgreSQL , 
. 
. , Zu,
PostgreSQL . 
,
.
,
EXPLAIN:
bpfinal=# EXPLAIN SELECT * FROM words WHERE word LIKE 'Zu%';
NOTICE: QUERY PLAN:
Index Scan using words_idx on words (cost=0.00..16.25 rows=14 width=12)
bpfinal=#


, , ,

369

,
, . 
,
. 
, .
, .
,
, 

. ,
? 
, , , .
,
.
:

, ,

, 

, 
PostgreSQL
PostgreSQL




pg_dump pg_restore,
PostgreSQL ( )

, PostgreSQL, 
, ,
.

, pgAdmin

,
.

12

,
, , 
. ,
,
(,
, ).
, 
, 
, .
: . , 
,
. ,
. ,
, 
.

:

371



. 
, , 
.

? , , 
, 
.
: 
. 
, ,
.
, 
, :

. 
 .

, ;
, .

, ,
, 
.


. 
,  , ,
, .

,
,
(  )
.

.
, 
. ?,
?. , 
, , 
, , .

, . 
,

.

372

12.


, , 
. .
,
, , 
, .

.
,
.


, . .
. ,
, 
. ,
, ,
,
, , .
, 
,

. , ,
, , 
. 

, 
, , 
, .

25% ,
, . 

. ,
.


. 
, 
,
. , 
, 

373

, ,
(

).

,
, 
. 
.
,
.

. ,
. , 
,
, ,
. IT 
, .
( )
. , 
. ,
.

, .
, 
.
: , 

. 
.
,
, 
.
, ,
, . 
, , 
, .


: 
. , ( 
, ) .

374

12.

, 

.
 , 
. ,
,
, .

VARCHAR CHAR. 
, , 
.
( , 
), , 
. (
, ,
)
.

, , 
, 
.
, ,
.
, 
, , 
.
, ,
,
. (Alan Perlis)
:
(. http://www.cs.yale.edu/homes/perlisalan/quotes.html).


, , 
. ,
. 
,
.

, 
.

375



, . 
?
( ,
). , , ,
.
, 
, . 
, 
, , ,
, .
, ,
.
,
:
, ,
, .
, . 
, , , ,

, . ,
, 
. , .
, , , . . 
. 
, 
.
, 
. 
, 
, , , 
, , .
, ,
,
,
, ,
. . .



,
( , ).

376

12.

.
, .
,
.
,
, ,

.
, ,
() . ,
, 
:

Name ()
, . PostgreSQL 
,
, .
, 

Name.
, , , 
, 
. ,
Address () Shipping information ( ).


377

, ,
 .

. , 
, ,

, .

. 12.1:
12.1.

( 75 ), 

, ,

, ,

 EAN13

, 
, , , 
 .


, 
, . 
.
, 
, 
. 

, customer () order ().
item ().
, 
, 
.
,
. , 
,
.

378

12.

customer:
Customer ()
Name ()
Address ()
Phone number ( )

Name .
(title): Mr, Miss Dr, 
. .
, ,
, 
, , . 
. !
, Rose Martin,
von Neumann. 
, Jennifer Ann Sto
nes. :
Title

Name

Miss

Jennifer Ann Stones

Dr

John von Neumann

Mr

Andrew Stones

Mr

Adrian Alan Matthew

Mr

Robert Rose Martin


.
:
Title

Fname ()

Lname ()

Miss

Jennifer

Stones

Dr

John

von Neumann

Mr

Andrew

Stones

Mr

Adrian

Matthew

Mr

Robert

Rose Martin

,
(middle names), ( )
.

. , Dr John von Neumann ( Dr
Neumann), Dear John, Dear

379

John von. 
.
(Address). 
, . . 
, .
, :
20 James Road,
Great Barr,
Birmingham
M11 2BA

:
Arden House,
Warwick Road,
Acocks Green,
Birmingham
B27 6BH

:
29 S. La Salle St,
Suite 520
Chicago
Illinois
60603

 (. 12.1).
Getreidegasse 9
A5020 Salzburg

. 12.1. Getreidegasse ;
9

, 
. , 
, ( ),
.
, , ( ) , 
, .
,
, : 
, State ()
.
,
. (, )
,

380

12.

, 
.
, 
, ,
, , .
, 
.
, .
, 
. 

.
,
:
Customer ()
Title ()
Fname ()
Lname ()
Addressline ( )
Town ()
Zip code ( )
Phone ()

Item ( )
:
Item ()
Description ()
Buy price ( )
Sell price ( )
Barcodes (may be several) (
, )
Stock Quantity ( )

, 
. .
orders .
(, 

). , 
:

381


Orders ()
Items ordered ( )
Quantity of each item ( )
Date placed ( )
Date delivered ( )
Shipping information ( )


, 
( , )
.
,
,
. .
, 
. , 
,
. , ,
, , .



. 

. ,
, .

. , 
. 
,
, . 
, , . 12.2:

Table
Table

Table
Table

. 12.2. ,

382

12.

, 
.
.
, , A B,
. 12.3:

Table A

Table B

. 12.3.

A B

B ,
A

, , A orders, B customer,
,
, , 
.


, 
, . customer 
, .
item, .
, item,
, . 
, 
( PostgreSQL 
, 
). ,
, , , , 
, item
, barcode1, barcode2, barcode3?
, ,
, . 
, , ? 
,
? ?
2,
.

383


, , , 
, .
, . . 
. ,
, ,
.
, ,
. 
. barcode
item barcode.
:
, .
: 
.  
, ,
,
.
. 12.4:
ITEM
Description ()
Buy price ( )
Sell price ( )
Stock quantity ( )

BARCODE
Barcode ()

. 12.4. item barcode

, , 
,  .
, 
. . 
, , SQL.
orders, 
. , , 
. 
, ,
. , ,
. orderinfo (
), , 
, orderline ( ), . . ,
, 
.
.
, , 

384

12.

, orderinfo order
line .
orderline, ,
, or
derline orderinfo.
. 12.5:
ORDERLINE
Item ordered ( )

ORDERINFO
Date ordered ( )
Date shipped ( )
Shipping cost ( )

. 12.5. orderline orderinfo

, .
,  :
I'd like a coffee please
I'd like a coffee please
I'd like a donut please
I'd like a coffee please
I'd like a donut please
:
I'd like three coffees and two donuts please

, , 
.
, , 
, 
, ,
.
, , , 
, .
(. 12.6):
ORDERLINE
Item ordered ( )
Quantity ()

ORDERINFO
Date ordered ( )
Date shipped ( )
Shipping cost ( )

. 12.6. orderline

385

, 
, ,
.
, ,
. , ,
. 12.7:

ITEM
Description
Buy Price
Sell Price
Stock quantity

ORDERLINE
Item ordered
Quantity

ORDERINFO
Date ordered
Date shipped
Shipping cost

CUSTOMER
Title ()
Fname ()
Lname ()
Address ()
own ()
Zipcode ()
Phonenumber ()

BARCODE
Barcode ()

. 12.7.

, . 
, cus
tomer orderinfo. 
, , 
item orderinfo, orderline.
? ,
, 
, ?
, , 
, ,
.
item orderline. 
orderline ,
. 
, item orderline, 
, 
, . ,
, ,
. 12.8.

386

12.

ITEM
Description
Buy Price
Sell Price
Stock quantity

ORDERLINE
Item ordered
Quantity

ORDERINFO
Date ordered
Date shipped
Shipping cost

CUSTOMER
Title
Fname
Lname
Address
Town
Zipcode
Phonenumber

BARCODE
Barcode

. 12.8.

, ,
,
, 
, ,
. 
!

. , ,
. 
: , 
. ,

10 .
. ,
,
. ,
, , . . 


.
, 
. , 
, , ,
.
, ,
.
, , , .
, , 
.

387




.



. , 
, ,
.
, 
, , , 
, 
. 

, ,
,
.
, ,
, . 
, .
, 
, . 
,

(NULL). ,
. SQL ,
PostgreSQL, , 
NULL , 
.
, 
, , , 

. ,
. : 

. 
, 
, 
. , ,
200 , ,
.
, 
, , 

388

12.

, .
,
,
(, ). 

.
Barcode
barcode, .
, ,
barcode.  , 
, 
.
Customer
, 
, 
, . 
:

. ,
,
.

. ,
, ,
() .

, . , 
,  . 
. 
, .

, , 
,
. , 
: <_>_id, 
customer_id.
Orderinfo
customer.
,  
, orderinfo_id.
Item
,
, 
, ,
. item_id.

389

Orderline
orderline orderinfo item. 
,
(. . , 
, ),

item. , , . .
,
orderline.
 orderline 
orderinfo, . .
, , 
.
orderline .


, , 
,
.
, ,
, 
.
,
, ,
, .

(
, ),
, . 12.9:
ORDERINFO

ORDERLINE
ORDERINFO ID
ITEM ID
QUANTITY

INTEGER
INTEGER
INTEGER

ORDERINGINFO_ID
ORDERINGINFO_ID

ITEM_ID  ITEM_ID

INTEGER
INTEGER
DATE
DATE
NUMERIC(7,2)

ORDERINFO ID
CUSTOMER_ID
DATE_PLACED
DATE_SHIPPED
SHIPPING

ITEM
CUSTOMER_ID  CUSTOMER _ID

ITEM ID
DESCRIPTION
COST_PRICE
SELL_PRICE
QUANTITY_IN_STOCK

INTEGER
VARCHAR(64)
NUMERIC(7,2)
NUMERIC(7,2)
INTEGER

ITEM_ID  ITEM_ID
BARCODE
BARCODE EAN
ITEM_ID

CHAR(13)
INTEGER

CUSTOMER
CUSTOMER ID
TITLE
FNAME
LNAME
ADDRESSLINE
TO WN
ZIPCODE
PHONE

INTEGER
CHAR(4)
VARCHAR(32)
VARCHAR(32)
VARCHAR(64)
VARCHAR(32)
CHAR(10)
VARCHAR(16)

. 12.9.

390

12.

, 
. 
, ,
. , , 
.
,
.
CHAR(10). .
, .
,
, . 
customer_id orderinfo, orderinfo_id orderline,
item_id barcode.
orderline (. 12.10):
ORDERLINE
ORDERINFO ID
ITEM ID
QUANTITY

CHAR(10)
CHAR(10)
INTEGER

. 12.10. orderline

item_id orderinfo_id . 
, 
, .
. ,
 
,
. item quanti
ty_in_stock .
, , 
, , 
. ,
, ,
. 

.


, . 12.11.
,
. . cus
tomer_ident orderinfo
customer_id customer. , 
, , (

391

)
, , .
ORDERINFO
ORDERLINE
ORDERINFO ID
ITEM ID
QUANTITY

INTEGER
INTEGER
INTEGER

ORDERINGINFO_ID ORDERINGINFO_ID

ORDERINFO ID
CUSTOMER_ID
DATE_PLACED
DATE_SHIPPED
SHIPPING

INTEGER
INTEGER
DATE
DATE
NUMERIC(7,2)

ITEM_ID  ITEM_ID
CUSTOMER_ID  CUSTOMER_ID
ITEM
ITEM ID
DESCRIPTION
COST_PRICE
SELL_PRICE

INTEGER
VARCHAR(64)
NUMERIC(7,2)
NUMERIC(7,2)

ITEM_ID
 ITEM_ID

ITEM_ID  ITEM_ID

STOCK
ITEM ID
INTEGER
QUANTITY
INTEGER

CUSTOMER
CUSTOMER ID
TITLE
FNAME
LNAME
ADDRESSLINE
TOWN
ZIPCODE
PHONE

INTEGER
CHAR(4)
VARCHAR(32)
VARCHAR(32)
VARCHAR(64)
VARCHAR(32)
CHAR(10)
VARCHAR(16)

BARCODE
BARCODE EAN
ITEM_ID

CHAR(13)
INTEGER

. 12.11. stock

, . 

ident, ,
< >_<>. ,
: id, ident, key pk, , 
.


, 
,
. , 
NULL,
NOT NULL. , ,
NOT NULL, .
, , NULL
, . . ( ) 
,
.
, , 
, , 
(, integer).
PostgreSQL ,
NULL.

392

12.


. MONEY,
. PostgreSQL MONEY, 
, .
,
float(P).
(numeric(P,S)) 
, . . .
,
. ,
, CHAR(N), N
(, EAN13,
,
). 
, 
CHAR(4) . 
, .
PostgreSQL 
text, .
, , , 
, 
ISO/ANSI VARCHAR(N), N
. , 
VARCHAR(N).
. , 
MONEY .
, , 
, , 
(, , ) . 
, . 
customer.
customer_id.
( , ),
, INTEGER.
TITLE (Mr, Mrs Dr)
, CHAR(4).
VARCHAR,
.
, , VARCHAR .
,
NULL.
, fname lname. 
, 32 , ,
, VAR

393

CHAR(32). fname NULL, lname .


.
,
. ,
,
,
.
.
, 
.
, . .
, 
+44 (0)116, 44
, , 
0.
, , 
.

. 12.12:

ORDERINFO
ORDERINFO ID
CUSTOMER_ID
DATE_PLACED
DATE_SHIPPED
SHIPPING

INTEGER
INTEGER
DATE
DATE
NUMERIC(7,2)

CUSTOMER_ID  CUSTOMER_ID

ORDERLINE
ORDERINFO ID
ITEM ID
QUANTITY

INTEGER
INTEGER
INTEGER

CUSTOMER
ORDERINGINFO_ID ORDERINGINFO_ID

ITEM_ID  ITEM_ID

CUSTOMER ID
TITLE
FNAME
LNAME
ADDRESSLINE
TOWN
ZIPCODE
PHONE

INTEGER
CHAR(4)
VARCHAR(32)
VARCHAR(32)
VARCHAR(64)
VARCHAR(32)
CHAR(10)
VARCHAR(16)

ITEM
ITEM ID
DESCRIPTION
COST_PRICE
SELL_PRICE

INTEGER
VARCHAR(64)
NUMERIC(7,2)
NUMERIC(7,2)

ITEM_ID  ITEM_ID

STOCK
ITEM ID
INTEGER
QUANTITY
INTEGER

ITEM_ID  ITEM_ID

BARCODE
BARCODE EAN
ITEM_ID

CHAR(13)
INTEGER

. 12.12.

394

12.


,
, .
,
.

( ), 
. ,

, 
. , 
,
(
) 
. ,
.

-
SQL ( 
), . ,
8 10,  
. , 
(. 8) 
, 10. , 
. ,
,
10.



(, , ) 
. 
, . 
,
, .
 , ,
, .
. , 
NULL , , 
. ,
. ,
.

395

SQL , ,
, .
,
, . , 
, , 
, ,
. 
. 
, , 
, ,
. . . 
.
, 
, , 
. , ,
, 
.


,

. , 

, ,
,
.
,
(E. F. Codd), 1969
Communications of the ACM, vol. 13, 6 1970 . 
. 

.
: ,
, 
. : 
, .
, 
, , 
.
, 
.

396

12.


,

. ,
, . , 
, 
.
, ,
2,
.
, , 

.

fname customer,
, . . fname ,
. 
(
, 
), 
. , 
( )
.
,
,
, , , 
. , 13 , 411
12 . , 
.
, 
,
.


,


. , or
derline (. 12.13) 
.

ORDERLINE
ORDERINFO ID
ITEM ID
QUANTITY

INTEGER
INTEGER
INTEGER

. 12.13. orderline

397

, orderline
orderinfo_id item_id.
orderinfo, ,
. 
, ,
.
. ,
, ,
. , order
line , . 
,
orderline , .



,
. , 
, 
,
, .

:
,
,
. ,
customer (. 12.14)
.

CUSTOMER
CUSTOMER ID
TITLE
FNAME
LNAME
ADDRESSLINE
TOWN
ZIPCODE
PHONE

INTEGER
CHAR(4)
VARCHAR(32)
VARCHAR(32)
VARCHAR(64)
VARCHAR(32)
CHAR(10)
VARCHAR(16)

. 12.14. customer

, . . 
, , 
, customer_id,
. . .

(. . ,
), ,
. 
, .

, (
, ).



, , . . 
. 

398

12.

, , 
.

--
, .

, .

,  
() . author ()
book (). ,
(, , , ) 
. ?

, . 
bookauthor, 
, 
:

AUTHOR_ID  AUTHOR_ID

BOOKAUTHOR
AUTHOR_ID
ISBN

ISBN  ISBN

INTEGER
INTEGER

AUTHOR
AUTHOR ID
NAME

INTEGER
CHAR(10)

BOOK
ISBN
TITLE

INTEGER
CHAR(10)

. 12.15. bookauthor

author ,
bookauthor , 
.
book, bookauthor,
.
bookauthor ,
, .

.
. , 
,  
, , ,
, . ,

399

, . 12.16, . .
, :
REGION

AREA
AREA ID
AREA_NAME

REGION ID
REGION_NAME

INTEGER
CHAR(10)

INTEGER
CHAR(10)

SHOP
AREA_ID  AREA_ID

SHOP ID
AREA_ID
REGION_ID

INTEGER
INTEGER
INTEGER

REGION_ID  REGION_ID

. 12.16.

, 
, . . , ,
shop 
: , shop,
,
REGION
. 
INTEGER
REGION ID
, 
CHAR(10)
REGION_NAME
( ), 
. 12.17.
,


region_id
shop.
, ,
region_id, shop,

, 
area.



.

REGION_ID  REGION_ID

AREA
INTEGER
INTEGER
CHAR(10)

AREA ID
REGION_ID
AREA_NAME

AREA_ID  AREA_ID

SHOP
SHOP_ID
AREA_ID

INTEGER
INTEGER

. 12.17. 


, 
, :

(parts explosion), item 
, , , .

400

12.

. , 
,
, , , ,
, 
. 
, 
?
,
person manager_id 
. , 
person,
. 
, manager_id ,
emp_id.
(. 12.18):
EMP_ID  MANAGER_ID
PERSON
EMP ID
NAME
MANA GER_ID

INTEGER
CHAR(10)
INTEGER

. 12.18.

, ,
. 12.19:
Mr MD

Manager 1

Fred

Manager 2

Barney

Tom

Jerry

. 12.19.

:
test=#
test=#
test=#
test=#
test=#
test=#
test=#

INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT

INTO
INTO
INTO
INTO
INTO
INTO
INTO

person(emp_id,
person(emp_id,
person(emp_id,
person(emp_id,
person(emp_id,
person(emp_id,
person(emp_id,

name, manager_id) VALUES(1, 'Mr MD', NULL);


name, manager_id) VALUES(2, 'Manager1', 1);
name, manager_id) VALUES(3, 'Manager2', 1);
name, manager_id) VALUES(4, 'Fred', 2);
name, manager_id) VALUES(5, 'Barney', 2);
name, manager_id) VALUES(6, 'Tom', 3);
name, manager_id) VALUES(7, 'Jerry', 6);

401

, emp_id 
, emp_id
. , Tom emp_id,
6, manager_id 3, emp_id Mana
ger2, . . Manager2 Tom.
,
.
, . 
( ) SQL:
test=# SELECT n1.name AS "Manager", n2.name AS "Subordinate" FROM person n1,
test# person n2 WHERE n1.emp_id = n2.manager_id;

person: n1 n2,
emp_id manager_id. ,
AS, ,
.

person:
Manager | Subordinate
+
Mr MD
| Manager1
Mr MD
| Manager2
Manager1 | Fred
Manager1 | Barney
Manager2 | Tom
Tom
| Jerry
(6 rows)

,
:

Database Design for Mere Mortals (


) . (Michael J. Hernan
dez), AddisonWesley (ISBN 0201694719). 
, , 
, 
,
.

The Practical SQL Handbook ( SQL)


. (Judith S. Bowman), . (Sandra
L. Emerson) (Marcy Darnovsky), AddisonWesley
(ISBN 0201447878). , 
.

402

12.


, ,

. 
,
.

.
, 
. 

.

13
PostgreSQL C
libpq


PostgreSQL.
, psql, 
PostgreSQL, (
pgAdmin), PostgreSQL. 
, Microsoft Access Sun StarOffice,
ODBC
.
,
.  libpq.
, PostgreSQL . 
, psql pgAdmin, 
, Windows,
PostgreSQL UNIX Linux. 
. 
, SELECT SQL, 
psql. , 
.
, 
PostgreSQL, 
.  ( 
, frontend/backend
) , 
, .
( ) 

404

13. PostgreSQL C libpq

. , 
PostgreSQL 6.4 , 
.

libpq. , 
.
, 
C.
, libpq, 
:

SQL

, 
, libpq 
. 
, ,
, .

libpq
PostgreSQL,
libpq, ,
, libpq,
, 
.
, frontend
(fe), libpqfe.h. 
libpq
PostgreSQL,
. libpqint.h,
PostgreSQL,
, libpq, 
.
libpqfe.h , 
libpq. 
include PostgreSQL (
/usr/local/pgsql/include). 
C, , 
I.
libpq lib 
PostgreSQL ( /usr/local/pgsql/lib).
libpq , 

405

. , , 
lpq, Postgre
SQL ( L).
libpq :
#include <libpqfe.h>
main()
{
/* PostgreSQL */
LOOP:
/* SQL */
/* */
/* */
}


, :
$ gcc o program program.c I/usr/local/pgsql/include L/usr/local/pgsql/lib
lpq

Red Hat Linux libpq 


, ,
, 
:
$ gcc o program program.c I/usr/local/pgsql/include lpq

Linux
. Microsoft Windows 
Cygwin /usr/
include/postgresql, /usr/lib.
, 
PostgreSQL Makefile.


, PostgreSQL 
.

, 
. libpq 
.
PostgreSQL libpq 
. 
, PGconn,

406

13. PostgreSQL C libpq

.
libpq PGconn 
, ( , 
/ C FILE).
PQconnectdb:
PGconn *PQconnectdb(const char *conninfo);

Pqconnnectdb()
. 
, , , 
NULL. NULL, ,
.
PQconnectdb , 
, .
,
. conninfo 
, 
=.
. 13.1:
13.1. PQconnnectdb

dbname

, $PGDATABASE

user

,  $PGUSER

password

host

, $PGHOST localhost

hostaddr

IP

port

TCP/IP $PGPORT 5432

$PGPASSWORD

$PGHOSTADDR

bpsimple
, conninfo :
"dbname=bpsimple"


, () :
"host=monster password='' user=rick"

host , . 
PQconnectdb IP
, . 
(Domain Naming Service, DNS), 

407

. IP
, hostaddr ,
, . hostaddr
, (
dotted quad), IP:
"hostaddr=192.168.0.22 dbname=neil"

host, hostaddr, PQconnectdb 


.
PostgreSQL TCP 5432 
. 
, , 
port.

(. . 13.1). , conninfo 
host, PQconnectdb , ,
PGHOST. , $PGHOST 
. 
, PQcon
nectdb , 
:
#include <libpqfe.h>
int main()
{
PGconn *conn = PQconnectdb("");

}
$ PGHOST=monster PGUSER=neil ./program

, PQconnectdb
, NULL, 
.

, PQstatus:
ConnStatusType PQstatus(const PGconn *conn);

ConnStatusType , 
:
CONNECTION_OK
CONNECTION_BAD

, , 
, PQconnectdb, 

408

13. PostgreSQL C libpq

. ConnStatusType , 
.
, (
). , 
PQfinish:
void PQfinish(PGconn *conn);

PQfinish libpq , 
.
, , 
PostgreSQL (connect.c), , 
. PQconnectdb 
(

, 
):
#include <stdlib.h>
#include <libpqfe.h>
int main()
{
PGconn *myconnection = PQconnectdb("");
if(PQstatus(myconnection) == CONNECTION_OK)
printf("connection made\n");
else
printf("connection failed\n");
PQfinish(myconnection);
return EXIT_SUCCESS;
}
$ gcc o connect connect.c lpq
$ ./connect
connection failed
$ PGDATABASE=bpsimple PGUSER=neil ./connect
connection made
$

Makefile
L I 
, . ,

libpq. Makefile,
CFLAGS LDLIBS .
Makefile,
,

409

. 
Wrox (http://www.wrox.com):
# Makefile 
# PostgreSQL.
#
# PostgreSQL
INC=/usr/local/pgsql/include
LIB=/usr/local/pgsql/lib
CFLAGS=I$(INC)
LDLIBS=L$(LIB) lpq
ALL: async1 connect create cursor cursor2 print select1 select2
$(ALL)

all:

clean :
@rm f *.o *~ $(ALL)

:
$ make program


, PQstatus PQfinish
NULL , 
, PQconnectdb.
, 
, PQerrorMessage:
char *PQerrorMessage(const PGconn *conn);

.
libpq, 
PqerrorMessage,
libpq. , 

:
printf("connection failed: %s", PQerrorMessage(myconnection));

,
,  
PGconn ( libpq
fe.h), . , ,
 libpq, 
PGconn.

410

13. PostgreSQL C libpq

, 
libpq ,
:
char
char
char
char
char
char

*PQdb(const PGconn *conn);


*PQuser(const PGconn *conn);
*PQpass(const PGconn *conn);
*PQhost(const PGconn *conn);
*PQport(const PGconn *conn);
*PQoptions(const PGconn *conn);

, 
, , , 
. 
.
, 
. PQreset.
, 
, :
void PQreset(PGconn *conn);

SQL libpq
,
C, SQL. 
. PQexec:
PGresult *PQexec(PGconn *conn, const char *sql_string);

, : SQL 
PQexec, , NULL
conn, . 
PGresult. PQexec
NULL, ,
, . ,
, PQexec
,
.
SQL, 
PQresultStatus,
, ExecStatusType:
ExecStatusType PQresultStatus(const PGresult *result);

SQL libpq

411

. 13.2:
13.2. SQL

PGRES_EMPTY_QUERY

. 
.

PGRES_COMMAND_OK

. .

PGRES_TUPLES_OK

.
.

PGRES_BAD_RESPONSE

, .

PGRES_NONFATAL_ERROR , .
PGRES_FATAL_ERROR

, .


,
.
PGRES_EMPTY_QUERY 
, , .
PGRES_COMMAND_OK ,
, (
CREATE TABLE.)
PGRES_TUPLES_OK ,
, ( SELECT).
, .
, , 
.
: PGRES_BAD_RESPONSE, PGRES_NONFATAL_ERROR PGRES_FA
TAL_ERROR , .
,
PQexec PQresultStatus:
PGresult *result;
result = PQexec(myconnection,
"SELECT customer_id FROM customer");
switch(PQresultStatus(result)) {
case PGRES_TUPLES_OK:
/* , */
if(PQntuples(result)) {
/* */
break;
}
/* , */
case PGRES_COMMAND_OK:
/* OK, */
break;

412

13. PostgreSQL C libpq


case PGRES_EMPTY_QUERY:
/* , , ? */
break;
case PGRES_NONFATAL_ERROR:
/* , */
break;
case PGRES_BAD_RESPONSE:
case PGRES_FATAL_ERROR:
default:
/* , */
}

PQntuples ,
PGRES_TUPLES_OK SELECT.

PQresStatus. :
const char *PQresStatus(ExecStatusType status);

,
PQresultErrorMessage,
:
const char *PQresultErrorMessage(const PGresult *result);

, , 
. 
PQclear, NULL. 
, ,
, :
void PQclear(PGresult *result);


SQL. test 
.
customer, .
number.
.
:
value |
name
+
42 | The Answer
29 | My Age
66 | ClicketyClick

,
PQexec , SQL,

SQL libpq

413

.
:
PGconn *myconnection;
...
PQexec(myconnection,"CREATE TABLE number ( value INTEGER, name VARCHAR)");
PQexec(myconnection,"INSERT INTO number VALUES (42, 'The Answer')");

, ,
,
. number ,
, PQresultErrorMessage :
ERROR: Relation 'number' already exists

, 
, SQL,
.
. .
SQL 
, psql. cre
ate.c:
#include<stdlib.h>
#include<libpqfe.h>
void doSQL(PGconn *conn, char *command)
{
PGresult *result;
printf("%s\n", command);
result = PQexec(conn, command);
printf("status is %s\n", PQresStatus(PQresultStatus(result)));
printf("result message: %s\n", PQresultErrorMessage(result));
PQclear(result);
}
int main()
{
PGresult *result;
PGconn *conn;
conn = PQconnectdb("");
if(PQstatus(conn) == CONNECTION_OK) {
printf("connection made\n");
/* doSQL(conn, "DROP TABLE number"); */

414

13. PostgreSQL C libpq

doSQL(conn, "CREATE TABLE number (


value INTEGER,
name VARCHAR
)");
doSQL(conn, "INSERT INTO number values(42,
doSQL(conn, "INSERT INTO number values(29,
doSQL(conn, "INSERT INTO number values(29,
doSQL(conn, "INSERT INTO number values(66,

'The Answer')");
'My Age')");
'Anniversary')");
'ClicketyClick')");

}
else
printf("connection failed %s\n", PQerrorMessage(conn));
PQfinish(conn);
return EXIT_SUCCESS;
}

number .
, 
, . 
DROP TABLE 
.
,
. doSQL (
), , 
.
, 
:
$ make create
$ PGDATABASE=bpsimple ./create
connection made
...
INSERT INTO number VALUES(66, 'ClicketyClick')
status is PGRES_COMMAND_OK
result message:
$

SQL 
, ,
PQexec. 
, :
for(n = 0; n < 10; n++) {
sprintf(buffer,
"INSERT INTO number VALUES(%d, 'single digit')", n);
PQexec(buffer);
}

415


UPDATE DELETE:
UPDATE number SET name = 'Zaphod' WHERE value = 42
DELETE FROM number WHERE value = 29

PQexec (
doSQL): 42 ( Zaphod), 
29.
psql:
$ psql d bpsimple
bpsimple=# SELECT * FROM number;
value |
name
+
66 | ClicketyClick
42 | Zaphod
bpsimple=#

DELETE UPDATE (
, PostgreSQL ), 
, . 
, PQcmdTuples:
const char *PQcmdTuples(const PGresult *result);

 , PQcmdTuples (
), , .
doSQL , 
:
printf("#rows affected %s\n", PQcmdTuples(result));

PQcmdTuples ,
( CREATE TABLE ),
"1" "2" , ( INSERT DELETE).
, ,
, ,
 . 
, , .

SQL
, , 
, ( 
).

416

13. PostgreSQL C libpq

SQL, libpq, 
. PQexec 
SQL, BEGIN, COMMIT ROLLBACK:
PQexec(conn, "BEGIN WORK");
/* make changes */
if(we changed our minds) {
PQexec(conn, "ROLLBACK WORK");
}
else {
PQexec(conn, "COMMIT WORK");
}

9. 
libpq,
SQL PQexec.


SQL, 
. ,
, PQexec 
SELECT.
SELECT PQexec, 
, 
.

, . . , . 
SELECT ,
, . SE
LECT (*), ,
.
, , , 
. , 
, , , ,
, , 
.
(,
SQL,
) ,
libpq . 
.
PQexec SELECT,
PGRES_TUPLES_OK. 

417

,
. PQntuples:
int PQntuples(const PGresult *result);

, ,
, .
( ) ,
PQnfields:
int PQnfields(const PGresult *result);

,
, PQfname:
char *PQfname(const PGresult *result, int index);

PQfsize:
int PQfsize(const PGresult *result, int index);

PQfsize ,
. 
PQfsize 1.
,
, PQfnumber:
int PQfnumber(const PGresult *result, const char *field);

doSQL ,
, SELECT.
:
void doSQL(PGconn *conn, char *command);
{
PGresult *result;
printf("%s\n", command);
result = PQexec(conn, command);
printf("status is %s\n", PQresStatus(PQresultStatus(result)));
printf("#rows affected %s\n", PQcmdTuples(result));
printf("result message: %s\n", PQresultErrorMessage(result));
switch(PQresultStatus(result)) {
case PGRES_TUPLES_OK:
{
int n = 0;
int nrows = PQntuples(result);
int nfields = PQnfields(result);
printf("number of rows returned = %d\n", nrows);

418

13. PostgreSQL C libpq

printf("number of fields returned = %d\n", nfields);


/* Print the field names */
for(n = 0; n < nfields; n++) {
printf(" %s:%d",
PQfname(result, n), PQfsize(result, n));
}
printf("\n");
}
}
PQclear(result);
}

SELECT 
:
doSQL(conn, "SELECT * FROM number WHERE value = 29");

:
status is PGRES_TUPLES_OK
#rows affected
result message:
number of rows returned = 2
number of fields returned = 2
value:4 name:1

, PQcmdTuples
, , PQresultErrorMessage
, .
,
. .
.
,
PQgetvalue:
char *PQgetvalue(const PGresult *result, int tuple, int field);

, PQgetvalue,
PQgetlength:
int PQgetlength(const PGresult *result, int tuple, int field);

, () ()
.
doSQL :
void doSQL(PGconn *conn, char *command)
{
PGresult *result;
printf("%s\n", command);

419

result = PQexec(conn, command);


printf("status is %s\n", PQresStatus(PQresultStatus(result)));
printf("#rows affected %s\n", PQcmdTuples(result));
printf("result message: %s\n", PQresultErrorMessage(result));
switch(PQresultStatus(result)) {
case PGRES_TUPLES_OK:
{
int r, n;
int nrows = PQntuples(result);
int nfields = PQnfields(result);
printf("number of rows returned = %d\n", nrows);
printf("number of fields returned = %d\n", nfields);
for(r = 0; r < nrows; r++) {
for(n = 0; n < nfields; n++)
printf(" %s = %s(%d),",
PQfname(result, n),
PQgetvalue(result, r, n),
PQgetlength(result, r, n));
printf("\n");
}
}
}
PQclear(result);
}

SELECT, ,
:
SELECT * FROM number WHERE value = 29
Status is PGRES_TUPLES_OK
#rows affected
result message:
number of rows returned = 2
number of fields returned = 2
value = 29(2), name = My Age(6),
value = 29(2), name = Anniversary(11),

, 
, , PQget
value.
, ,
CHAR(n), . 

. Zaphod , 
CHAR(8), "Zaphod<><>",
,
"Zaphod" ( C strcmp). 
, 
.

420

13. PostgreSQL C libpq

, 
. , 
, ,
NULL SQL.
, libpq , ,
, 
NULL:
int PQgetisnull(const PGresult *result, int tuple, int field);

PQgetisnull, , 
(NULL). 1,
NULL, 0 .
:
for(n = 0; n < nfields; n++) {
if(PQgetisnull(result, r, n))
printf(" %s is NULL,", PQfname(result, n));
else
printf(" %s = %s(%d),",
PQfname(result, n),
PQgetvalue(result, r, n),
PQgetlength(result, r, n));
}


,
PostgreSQL. 
, , 
libpq, 
.
PQprint , 
psql, .
:
void PQprint(FILE *output, const PGresult *result, const PQprintOpt *options);

PQprint Postgre
SQL, 
. , : 
(output) , 
(result) ,
, (options). :
struct {
pqbool header;
pqbool align;

/* */
/* */

421

pqbool html3;
pqbool expanded;
pqbool pager;
char *fieldSep;
char *tableOpt;
char *caption;
char **fieldName;
} PQprintOpt;

/* HTML */
/* */
/*
*/
/* */
/* HTML <TABLE > */
/* HTML <> */
/* */

PQprintOpt . hea
der, , ,
,
fieldName.
, 
fieldSep
( ), align 0.
:
++++
| customer_id | title | fname
| town
++++
|
1 | Miss | Jenny
| Hightown
++++
|
3 | Miss | Alex
| Nicetown
++++

| zipcode |

phone |

| NT2 1AQ | 023 9876 |


| NT2 2TX | 010 4567 |

, 
pager, ,
, ,
.
expanded, : 
.
HTML, 
, html3 . 
, tableOpt caption.
(print.c),
PQprint HTML:
#include <stdlib.h>
#include <libpqfe.h>
int main()
{
PGresult *result;
PGconn *conn;
conn = PQconnectdb("");

422

13. PostgreSQL C libpq

if(PQstatus(conn) == CONNECTION_OK) {
printf("connection made\n");
result = PQexec(conn, "SELECT * FROM customer
WHERE town = 'Bingham'");
{
PQprintOpt pqp;
pqp.header = 1;
pqp.align = 1;
pqp.html3 = 1;
pqp.expanded = 0;
pqp.pager = 0;
pqp.fieldSep = "";
pqp.tableOpt = "align=center";
pqp.caption = "Bingham Customer List";
pqp.fieldName = NULL;
printf("<HTML><HEAD><TITLE>Customers</TITLE></HEAD><BODY>\n");
PQprint(stdout, result, &pqp);
printf("</BODY></HTML>\n");
}
}
PQfinish(conn);
return EXIT_SUCCESS;
}

, ,
HTML, (stdout). 
:
$ PGDATABASE=bpsimple ./print
<HTML><HEAD></HEAD><BODY>
<table align=center><caption align=high>Bingham Customer List</caption>
<tr><th align=right>customer_id</th><th align=left>title</th><th
align=left>fnam
e</th><th align=left>lname</th><th align=left>addressline</th><th
align=left>tow
n</th><th align=left>zipcode</th><th align=right>phone</th></tr>
<tr><td align=right>7</td><td align=left>Mr </td><td align=left>Richard</
td><td
align=left>Stones</td><td align=left>34 Holly Way</td><td
align=left>Bingham</t
d><td align=left>BG4 2WE </td><td align=right>342 5982</td></tr>
<tr><td align=right>8</td><td align=left>Mrs </td><td align=left>Ann</td><td
ali
gn=left>Stones</td><td align=left>34 Holly Way</td><td align=left>Bingham</
td><t
d align=left>BG4 2WE </td><td align=right>342 5982</td></tr>

423

<tr><td align=right>11</td><td align=left>Mr </td><td align=left>Dave</


td><td a
lign=left>Jones</td><td align=left>54 Vale Rise</td><td align=left>Bingham</
td><
td align=left>BG3 8GD </td><td align=right>342 8264</td></tr>
</table>
</BODY></HTML>

, 
( list.html),
. 
:
$ PGDATABASE=bpsimple ./print > list.html

HTML (. 13.1):

. 13.1. ,
HTML


. 
PostgreSQL , 
.
, 
,
. 
, , 

SELECT.
,
, ,
.

424

13. PostgreSQL C libpq


. , 
, .
, , 25 
, .
libpq , . 

. , 
, , : , 
.
, , 
, SELECT , ,
,
SELECT COUNT(*) FROM, SELECT 
, ,
. ,
.
, , 
( )
FETCH,
, SELECT,
.
,
. ,
, .
, , 
.
PostgreSQL, :
PQexec(conn, "BEGIN work");
PQexec(conn, "DECLARE mycursor CURSOR FOR SELECT ..."

. , 
FETCH
( ):
result = PQexec(conn, "FETCH 1 IN mycursor");
result = PQexec(conn, "FETCH 4 IN mycursor");
result = PQexec(conn, "FETCH ALL IN mycursor");

,
, .
, :
PQexec(conn, "COMMIT work");
PQexec(conn, "CLOSE mycursor");

425

, 
bpsimple, 
.
, 
:
#include <libpqfe.h>
main()
{
/* PostgreSQL */
/* SQL SELECT */
DO
/* */
/* */
UNTIL no more results
/* */
/* */
}


PGresult, ,
. ( cursor.c),
, 
SQL:
#include <stdlib.h>
#include <libpqfe.h>
void doSQL(PGconn *conn, char *command)
{
PGresult *result;
printf("%s\n", command);
result = PQexec(conn, command);
printf("status is %s\n", PQresStatus(PQresultStatus(result)));
printf("#rows affected %s\n", PQcmdTuples(result));
printf("result message: %s\n", PQresultErrorMessage(result));
switch(PQresultStatus(result)) {
case PGRES_TUPLES_OK:
{
int r, n;
int nrows = PQntuples(result);
int nfields = PQnfields(result);
printf("number of rows returned = %d\n", nrows);
printf("number of fields returned = %d\n", nfields);
for(r = 0; r < nrows; r++) {

426

13. PostgreSQL C libpq

for(n = 0; n < nfields; n++)


printf(" %s = %s(%d),",
PQfname(result, n),
PQgetvalue(result, r, n),
PQgetlength(result, r, n));
printf("\n");
}
}
}
PQclear(result);
}
int main()
{
PGresult *result;
PGconn *conn;
conn = PQconnectdb("");
if(PQstatus(conn) == CONNECTION_OK) {
printf("connection made\n");
doSQL(conn, "BEGIN work");
doSQL(conn, "DECLARE mycursor CURSOR FOR "
"SELECT fname, lname FROM customer");
doSQL(conn, "FETCH ALL IN mycursor");
doSQL(conn, "COMMIT work");
doSQL(conn, "CLOSE mycursor");
}
else
printf("connection failed\n");
PQfinish(conn);
return EXIT_SUCCESS;
}

, ,
:
connection made
DECLARE mycursor CURSOR FOR SELECT fname, lname FROM customer
status is PGRES_COMMAND_OK
#rows affected
result message:
BEGIN work
status is PGRES_COMMAND_OK
#rows affected
result message:

427

FETCH ALL IN mycursor


status is PGRES_TUPLES_OK
#rows affected
result message:
number of rows returned = 15
number of fields returned = 2
fname = Jenny(5), lname = Stones(6),
fname = Andrew(6), lname = Stones(6),
fname = Adrian(6), lname = Matthew(7),
fname = Simon(5), lname = Cozens(6),
fname = Neil(4), lname = Matthew(7),
fname = Richard(7), lname = Stones(6),
fname = Ann(3), lname = Stones(6),
fname = Christine(9), lname = Hickman(7),
fname = Mike(4), lname = Howard(6),
fname = Dave(4), lname = Jones(5),
fname = Richard(7), lname = Neill(5),
fname = Laura(5), lname = Hendy(5),
fname = Bill(4), lname = O'Neill(7),
fname = David(5), lname = Hudson(6),
fname = Alex(4), lname = Matthew(7),
COMMIT work
status is PGRES_COMMAND_OK
#rows affected
result message:
CLOSE mycursor
status is PGRES_COMMAND_OK
#rows affected
result message:

, , ,
.
, . 
, , . . PQntuples ,
.
, PQntuples 4 , 
, , 
, . ( cursor2.c).
doSQL , 
PQexec:
#include <stdlib.h>
#include <libpqfe.h>
void printTuples(PGresult *result)
{
int r, n;
int nrows = PQntuples(result);
int nfields = PQnfields(result);
printf("number of rows returned = %d\n", nrows);
printf("number of fields returned = %d\n", nfields);

428

13. PostgreSQL C libpq

for(r = 0; r < nrows; r++) {


for(n = 0; n < nfields; n++)
printf(" %s = %s(%d),",
PQfname(result, n),
PQgetvalue(result, r, n),
PQgetlength(result, r, n));
printf("\n");
}
}
void doSQL(PGconn *conn, char *command)
{
PGresult *result;
printf("%s\n", command);
result = PQexec(conn, command);
printf("status is %s\n", PQresStatus(PQresultStatus(result)));
printf("#rows affected %s\n", PQcmdTuples(result));
printf("result message: %s\n", PQresultErrorMessage(result));
switch(PQresultStatus(result)) {
case PGRES_TUPLES_OK:
printTuples(result);
break;
}
PQclear(result);
}
int main()
{
PGresult *result;
PGconn *conn;
int ntuples = 0;
conn = PQconnectdb("");
if(PQstatus(conn) == CONNECTION_OK) {
printf("connection made\n");
doSQL(conn, "BEGIN work");
doSQL(conn, "DECLARE mycursor CURSOR FOR "
"SELECT fname, lname FROM customer");
do {
result = PQexec(conn, "FETCH 4 IN mycursor");
if(PQresultStatus(result) == PGRES_TUPLES_OK) {
ntuples = PQntuples(result);
printTuples(result);

429

PQclear(result);
}
else ntuples = 0;
} while(ntuples);
doSQL(conn, "CLOSE mycursor");
doSQL(conn, "COMMIT work");
}
else
printf("connection failed\n");
PQfinish(conn);
return EXIT_SUCCESS;
}


, , 
, :
connection made
...
DECLARE mycursor CURSOR FOR SELECT fname, lname FROM customer
status is PGRES_COMMAND_OK
#rows affected
result message:
number of rows returned = 4
number of fields returned = 2
fname = Jenny(5), lname = Stones(6),
fname = Andrew(6), lname = Stones(6),
fname = Adrian(6), lname = Matthew(7),
fname = Simon(5), lname = Cozens(6),
number of rows returned = 4
number of fields returned = 2
fname = Neil(4), lname = Matthew(7),
fname = Richard(7), lname = Stones(6),
fname = Ann(3), lname = Stones(6),
fname = Christine(9), lname = Hickman(7),
number of rows returned = 4
number of fields returned = 2
fname = Mike(4), lname = Howard(6),
fname = Dave(4), lname = Jones(5),
fname = Richard(7), lname = Neill(5),
fname = Laura(5), lname = Hendy(5),
number of rows returned = 3
number of fields returned = 2
fname = Bill(4), lname = O'Neill(7),
fname = David(5), lname = Hudson(6),
fname = Alex(4), lname = Matthew(7),
number of rows returned = 0

430

13. PostgreSQL C libpq


number of fields returned = 2
COMMIT work
status is PGRES_COMMAND_OK
#rows affected
result message:
...
$

FETCH, , 
( NEXT), ( 
) ( ALL).


, ,
. INSERT 
,
SELECT.
, 
.
, 
,
C double?
: , . PostgreSQL ( libpq) 
,
. 
,
BINARY:
DECLARE mycursor BINARY CURSOR FOR...

PQbinaryTuples , 
, FETCH ,
:
int PQbinaryTuples(const PGresult *result);

, PQgetvalue
, ,
, .

( ) 
.
libpq. ecpg
,
SQL.

431

libpq 
. , libpq 
, . , 
, 
. () ,
PQexec, ,
PQexec. . ,
.
, .
,
. 
,
.
, 
, 
. , 
, ,
. , , ,
,
, . .

:
main()
{
LOOP:
/* , */
/* , */
switch(event type) {
/* */
}
}

, , , 
 .  , ,
, .
, ,
, , 
, 
. ,
, , 
, . , ,
Visual Basic.

432

13. PostgreSQL C libpq

libpq PostgreSQL
. 
, , ,
, 
, .
PostgreSQL, , 
.
, .
, PQexec 
, PQsendQuery PQgetResult. , PQsendQue
ry , .
, 
. , 
, 
. , PQgetResult
,
:
int PQsendQuery(PGconn *conn, const char *query);

PQsendQuery , , 
, 
PqerrorMessage. 1,
:
PGresult *PQgetResult(PGconn *conn);

PQgetResult
, 
.
, ,
, . 
, PQgetResult NULL.

, PQclear.
, PQsendQuery, PQgetResult 
.
PQsendQuery, 
, PQsetnonblocking:
int PQsetnonblocking(PGconn *conn, int arg);

PQsendQuery,
PQsetnonblocking . PQsendQuery
, ,
.

433

PQsetnonblocking 1,
. 
, PQisnonblocking:
int PQisnonblocking(const PGconn *conn);

, 
.
, 
 (async1.c):
#include <stdlib.h>
#include <libpqfe.h>
void printTuples(PGresult *result)
{
int r, n;
int nrows = PQntuples(result);
int nfields = PQnfields(result);
printf("number of rows returned = %d\n", nrows);
printf("number of fields returned = %d\n", nfields);
for(r = 0; r < nrows; r++) {
for(n = 0; n < nfields; n++)
printf(" %s = %s(%d),",
PQfname(result, n),
PQgetvalue(result, r, n),
PQgetlength(result, r, n));
printf("\n");
}
}
int main()
{
PGresult *result;
PGconn *conn;
conn = PQconnectdb("");
if(PQstatus(conn) == CONNECTION_OK &&
PQsetnonblocking(conn,1) == 0) {
printf("connection made\n");
PQsendQuery(conn, "SELECT * FROM customer");
while(result = PQgetResult(conn)) {
printTuples(result);
PQclear(result);
}
}

434

13. PostgreSQL C libpq

else
printf("connection failed\n");
PQfinish(conn);
return EXIT_SUCCESS;
}

, , 
. (
), , 
, .
, 
PQgetResult , , 
. 
libpq. 
, , 
,
PQisBusy, PQconsumeInput PQflush Post
greSQL, :
int PQisBusy(PGconn *conn);

PQisBusy 1, , PQgetResult
, :
int PQflush(PGconn *conn);

PQflush , 
. , 
:
int PQconsumeInput(PGconn *conn);

PQconsumeInput libpq, , 
,
libpq. ,
PQexec, ,
, .
SELECT 

, SELECT PostgreSQL.
, , 
. PQsocket:
int PQsocket(const PGconn *conn);


, , 

435

. ,
, . 
PQflush , . 
, PQcon
sumeInput , PQgetResult.
, 
, PQcancelRequest 
:
int PQcancelRequest(PGconn *conn);

PQcancelRequest 1, 
, 0 . , , 
. 
. PQcancelReq
uest 
.
PQcancelRequest 
,
. 

, PQconnectStart PQconnectPoll:
PGconn *PQconnectStart(const char *conninfo);
PostgresPollingStatusType *PQconnectPoll(PGconn *conn);

PQconnectStart PQconnectdb, ,
, 
, conninfo.
DNS, PQcon
nectStart .
, ,
. PQstatus,
, PQconnectStart, 
CONNECTION_BAD. 
PQconnectPoll,
. PQconnectPoll 
:
PGRES_POLLING_FAILED
PGRES_POLLING_OK

/* */
/* */

, PGRES_POLLING_FAILED,
, PGRES_POLLING_OK, 

.

436

13. PostgreSQL C libpq

(async2.c),
:
#include <stdlib.h>
#include <libpqfe.h>
int main()
{
PGresult *result;
PGconn *conn;
/* */
conn = PQconnectStart("");
if(PQstatus(conn) == CONNECTION_BAD) {
printf(" cannot start connect: %s\n", PQerrorMessage(conn));
}
else {
/*  , PQconnectPoll */
PostgresPollingStatusType status;
do {
printf("polling\n");
status = PQconnectPoll(conn);
}
while(status != PGRES_POLLING_FAILED &&
status != PGRES_POLLING_OK);
if(status == PGRES_POLLING_OK)
printf("connection made!\n");
else
printf("connection failed: %s\n", PQerrorMessage(conn));
}
PQfinish(conn);
return EXIT_SUCCESS;
}

, 
, 
:
$ PGDATABASE=bpsimple ./async2
polling
polling
...
connection made!
$

437

PostgreSQL 
C. , Post
greSQL .
, libpq
PostgreSQL, 
, (
). , 
, 
SQL ,
.


.
,
.
PostgreSQL C
SQL, .

14
PostgreSQL C
SQL


PostgreSQL C 
, . 
libpq, PostgreSQL,

. 
SQL, ,
.
libpq
PostgreSQL, , 
, , .
, PostgreSQL.
SQL, . . 

SQL.
. , ,
SQL. SQL92 
SQL , C,
FORTRAN, ADA . 1998
ANSI SQL, Java, SQLJ.
PostgreSQL , SQL,
C, libpq.
, SQL
C libpq. Oracle Infor
mix PRO*C ESQL/C 

SQL

439

, . PostgreSQL,
ecpg, ANSI.
, , , ,
C. (
pgc PostgreSQL)
C, .
SQL ecpg,
libpq.
SQL 
C SQL , 
.
. ,
SQL ,
.


SQL
PostgreSQL SQL, ecpg, 
ANSI.
, ( psql) test
number, 
, . ,
test,
, DROP
DATABASE:
bpsimple=# DROP database test;
DROP DATABASE
bpsimple=# CREATE database test;
CREATE DATABASE
bpsimple=# \c test
You are now connected to database
test=# create table number (
test(# intval integer,
test(# name varchar
test(# );
CREATE
test=# INSERT INTO number(intval,
INSERT 19107 1
test=# INSERT INTO number(intval,
INSERT 19231 1
test=# INSERT INTO number(intval,
INSERT 19253 1
test=#

test.

name) VALUES(42, 'six times seven');


name) VALUES(1, 'Numero Uno');
name) VALUES(111, 'Nelson ');

440

14. PostgreSQL C SQL

. SQL
esqlc, 
update.pgc:
int main()
{
EXEC SQL connect to test;
EXEC SQL UPDATE number
SET name = 'The Answer to the Ultimate Question'
WHERE intval = 42;
EXEC SQL commit work;
EXEC SQL disconnect all;
return 0;
}


(,
)
number.
. , 2.1.0, 
ecpg , 
. 
ecpg,
, PostgreSQL ,
'test' .

, SQL 
. SQL : 
SQL, , 
exec sql :
EXEC SQL < SQL>;

SQL (
EXEC SQL), ,
. 
, . . SQL C,
. , 
 .
SQL , . .
, . SQL 
.

C, . 

SQL

441

, ecpg
:
$ ecpg t update.pgc
$

ecpg, 
, I<
>.
C, update.c,
. , 
,
update.pgc:
#include <ecpgtype.h>
#include <ecpglib.h>
#include <ecpgerrno.h>
main()
{
{ ECPGconnect(__LINE__, "test" , NULL, NULL , NULL, 1); }
{ ECPGdo(__LINE__, NULL, "UPDATE number SET name = 'The Answer to the
Ultimate Question' WHERE intval = 42", ECPGt_EOIT, ECPGt_EORT);}
{ ECPGtrans(__LINE__, NULL, "commit");}
{ ECPGdisconnect(__LINE__, "ALL");}
}

, SQL .
ecpg , ecpg, 
libpq, . ecpg 
libpq.
upda
te.c (ecpg libpq). 
, PostgreSQL, , 
L, :
$ cc o update update.c L/usr/local/pgsql/lib lecpg lpq
$

I<
> ECPG.
,
:
$ ./update
$

442

14. PostgreSQL C SQL

, . . .
, , 
psql.
,
, libecpg.so.<
> , LD_LIBRA
RY_PATH , ,
. :
$ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/pgsql/lib
$ export LD_LIBRARY_PATH
$
$ psql d test
test=# SELECT * FROM number;
intval |
name
+
1 | Numero Uno
111 | Nelson
42 | The Answer to the Ultimate Question
(3 rows)
test=# \q
$

ecpg , 
, 
. 
, COMMIT, 
. ,
.

SQL, make,
. make, 
ecpg:
# Make 
# PostgreSQL
#
# PostgreSQL
INC=/usr/local/pgsql/include
LIB=/usr/local/pgsql/lib
CFLAGS=I$(INC)
LDLIBS=L$(LIB) lecpg lpq
ECPGFLAGS=t I$(INC)

SQL

443

.SUFFIXES: .pgc
.pgc.c:
ecpg $(ECPGFLAGS) $<
ALL= cursor insert insert2 select select2 select3 update update2

make , .c 
.pgc ecpg .pgc. 
ECPGFLAGS 
. t
. , 
, , 
ecpg LDLIBS.
make
Beginning Linux Programming ( Linux)
(Neil Matthew) (Richard Stones)
(Wrox Press, ISBN 1861002971), GNU 
make,  http://www.gnu.org.
make, , 
:
$ rm f update.c update
$ make update
ecpg t I/usr/local/pgsql/include update.pgc
cc I/usr/local/pgsql/include c o update.o update.c
cc update.o L/usr/local/pgsql/lib lecpg lpqo update
rm update.o update.c
$

update.c update ,
make 
. , ( , GNU)
make ,
. update.pgc, 
SQL , update.

ecpg
ecpg 
. 
:
ecpg [v] [t] [I includedir] [o outputfile] file1 [file2 ]

. 14.1.

444

14. PostgreSQL C SQL

14.1. ecpg

v

stderr.

t

, 

. COMMIT.

o


. , , 
.pgc. .c.

I

,
, .

t . 
( t) ecpg ,
, BEGIN
WORK. PostgreSQL ,
. 
, COMMIT.
. SQL 
.
(
), t ecpg 
SQL BEGIN WORK COMMIT WORK.
,
ecpg t 
Makefile.

make
( 
libpq) 
.

SQL
ecpg
. 
SQL
SQL. 
ECPGdebug:
void ECPGdebug(int logging, FILE *logstream);

logging, 
, , 
. ,
logstream.

SQL

445

main update.pgc
:
ECPGdebug(1,stderr);

:
$ make update
$ ./update
[1597]: ECPGdebug: set to 1
[1597]: ECPGconnect: opening database test
[1597]: ECPGexecute line 15: QUERY: update number set name = 'The Answer to
the Ultimate Question' where intval = 42 on connection test
[1597]: ECPGexecute line 15 Ok: UPDATE 1
[1597]: ECPGtrans line 16 action = commit connection = test
[1597]: ecpg_finish: finishing test.

, , 

. 
, .
ECPGdebug ( ECPG) 
PostgreSQL, , 
, ,
SQL. , 
,

C.


update.pgc
SQL
. ,
libpq,
.

test, , 
:
EXEC SQL connect to test;

connect,
: ,
, :
EXEC SQL CONNECT database_url
AS connection_name
USER login_name
USING password;

446

14. PostgreSQL C SQL


database_url ( , URL
), 
, . 14.2:
14.2. database_url

database_name

database_name@server

database_name@server:port
tcp:postgresql://server

,
TCP

tcp:postgresql://
server:port
tcp:postgresql://server/
database_name
unix:postgresql://server

default

, 
PGDATABASE

:host_variable


, UNIX

SQL 
connection_name.
login_name.
( ).
, password . identifi
edby connect using
.
.
SQL 
.
, 
,
SQL. 
, exec sql:
EXEC SQL AT connection_name <sql statement>;

, SQL
( ), SET:
EXEC SQL SET CONNECTION TO connection_name;

SQL

447

DISCONNECT:
EXEC SQL DISCONNECT connection;

connection ,
. 14.3:
14.3. DISCONNECT

Default

Current

All

connection_name

ECPGstatus,
ecpg, 
(TRUE), (. . 
), FALSE :
bool ECPGstatus(int lineno, char *connection_name);

ECPGstatus ECPG, 
( __LI
NE__ C). ,
. 
,
SQL connect .
,
, :
if(!ECPGstatus(__LINE__,"test")) {
/* failed to connect */
}

, ECPGstatus
PostgreSQL. , 
,
.



. , 
,
SQL. , 
, , 
, .

448

14. PostgreSQL C SQL

,
.
SQL 
, PostgreSQL . 
( SQL) sqlca. C
:
struct
{
char
long
long
struct
{
int
char
} sqlerrm;
char
long
char
char
} sqlca;

sqlcaid[8];
sqlabc;
sqlcode;

sqlerrml;
sqlerrmc[70];
sqlerrp[8];
sqlerrd[6];
sqlwarn[8];
sqlext[8];

sqlca 
SQL
, . 
, PostgreSQL , 
sqlca. , Orac
le, ,
.
, PostgreSQL.
sqlca
SQL, ,
 , 
. ,
, sqlcode.
sqlca.sqlcode ,
, .
. ,
, sqlca.sqlcode 402. 
. 
100, ,
SELECT , .
, sqlca.sqlerrm.sqlerrmc 
, . (
) sqlca.sqlerrm.sqlerrml.
PostgreSQL 

SQL

449

, . . 
"error #203". 
. 14.4:
14.4. SQL

12

201

. , , PostgreSQL
, 
SELECT.

202

. , , PostgreSQL
, .

203

. , 
, , .

208

. PGRES_EMPTY_QUERY, 
libpq, , , , . .
.

220

. ,
.

221

. ,
.

400

PostgreSQL.
.

401

. ,
.

402

. .

100

. .

INSERT, UPDATE DELETE 


, , sql
ca.sqlerrd[2]. 
SELECT .
, , 
, . 

. 
SQL, SELECT, , 
C (
). , 
.
sqlca.sqlwarn 
: sqlca.sqlwarn[0] W, 
, sqlca.sqlwarn[1] W,

450

14. PostgreSQL C SQL

C, sqlca.sqlwarn[2] 
W, .
sqlca . 
ecpg, .
:
EXEC SQL INCLUDE sqlca;

.
, 
. (update2.pgc) 
, bpsimple:
#include <stdio.h>
EXEC SQL include sqlca;
main()
{
ECPGdebug(1,stderr);
EXEC SQL connect to bpsimple;
EXEC SQL UPDATE item
SET cost_price = 1.75, sell_price = 2.99
WHERE description = 'Linux CD';
if(sqlca.sqlcode == 0)
printf("rows affected: %d\n", sqlca.sqlerrd[2]);
EXEC SQL disconnect all;
}


, UPDA
TE, . sqlca.sqlcode ,
UPDATE . 
sqlca.sqlerrd[2].


, ecpg 
, 
. , 
, ( ) 
100.

SQL

451

whenever:
EXEC SQL whenever condition action;

(condition) . 14.5:
14.5. whenever

Sqlerror

Sqlwarning

Not found

(action), 
, . 14.6:
14.6. whenever

Sqlprint

stderr

do c_code


,
:
EXEC SQL whenever sqlwarning sqlprint;
EXEC SQL whenever sqlerror do GiveUp();
void GiveUp()
{
fprintf(stderr, "Fatal error\n");
sqlprint();
exit(1);
}

PostgreSQL ecpg whenever, 


sqlca.sqlcode sqlca.sqlwarn[0] 
SQL , 
. sqlprint do sql
print(), ,
.
whenever PostgreSQL 
SQL.  
,
, .


 
SQL, , 

452

14. PostgreSQL C SQL

. libpq, SQL
( sprintf) 
, , .
SQL 
, , 
, libpq.
SQL, , 
. item 
:
EXEC SQL INSERT INTO item VALUES(:description, :cost_price, :sell_price);

, item_id , . .
item.
(description, cost_price sell_price)
, . . ,
, .
C (
), ecpg. , 
, SQL,
:
EXEC SQL BEGIN declare section;

. . . .
EXEC SQL END declare section;

, 
C, 
. ,
C, ecpg 
.
, 
, ,
C.

.
(insert.pgc), 
 .
 :
#include <stdio.h>
#include <string.h>
EXEC SQL include sqlca;
EXEC SQL whenever sqlwarning sqlprint;

SQL

453

EXEC SQL whenever sqlerror do GiveUp();


void GiveUp()
{
fprintf(stderr, "Fatal Error\n");
sqlprint();
}
main(int argc, char *argv[])
{
EXEC SQL begin declare section;
int item_id;
char barcode[13];
EXEC SQL end declare section;
if(argc != 3) {
printf("usage: INSERT item barcode\n");
exit(1);
}
item_id = atoi(argv[1]);
strncpy(barcode, argv[2], sizeof(barcode));
EXEC SQL connect to bpsimple;
EXEC SQL insert into barcode values(:barcode, :item_id);
EXEC SQL disconnect all;
}


, item_id barcode,
( 
) . 
C, C.
SQL, . .
ecpg . SQL,
.
,
.
 ,
sql whenever:
$ make insert
$ ./insert 2 1234567890123
$ ./insert 2 1234567890123
Fatal Error
sql error 'ERROR: Cannot insert a duplicate key into unique index
barcode_pk'
$

454

14. PostgreSQL C SQL

,
. 
, NUMERIC(7,2), C
double. .
,
VARCHAR.
,
C. 
VARCHAR C, , 
: 
, 
.
, ecpg.
VARCHAR char 
, ecpg , arr
len, .

.
(insert2.pgc) ,
item .
(VARCHAR(64)) , 
, 
:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
EXEC SQL include sqlca;
EXEC SQL whenever sqlwarning sqlprint;
EXEC SQL whenever sqlerror do GiveUp();
void GiveUp()
{
fprintf(stderr, "Fatal Error\n");
sqlprint();
}
main(int argc, char *argv[])
{
EXEC SQL begin declare section;
char dbname[] = "bpsimple";
double cost_price, sell_price;
VARCHAR description[64];
EXEC SQL end declare section;
if(argc != 4) {
printf("usage: insert description cost_price sell_price\n");

SQL

455

exit(1);
}
strncpy(description.arr, argv[1], sizeof(description.arr));
description.len = strlen(description.arr);
cost_price = atof(argv[2]);
sell_price = atof(argv[3]);
EXEC SQL connect to :dbname as bpsimple;
EXEC SQL at bpsimple insert into
item(description, cost_price, sell_price)
values(:description, :cost_price, :sell_price);
EXEC SQL disconnect bpsimple;
}

:
$ ./insert2 "Widget" 1.87 2.93
$

, item, psql:
bpsimple=# SELECT * FROM item;
item_id | description | cost_price | sell_price
+++
...
12 | Widget
|
1.87 |
2.93
bpsimple=#




, SQL 
.
item item_id serial,
( ) item_id 
. , 
, INSERT.
NULL ,
null values INSERT.

, , , 
, 
, .

ecpg

, . .

456

14. PostgreSQL C SQL

(), 
SELECT. . 
:
EXEC SQL begin declare section;
int count;
EXEC SQL end declare section;
EXEC SQL SELECT count(*) INTO :count FROM customer;

SELECT INTO, 
, 
. count, 
SQL 
, .
, 
INTO ,
. 
customer_id, :
EXEC SQL SELECT addressline, zipcode INTO :addr, :zip
FROM customer
WHERE customer_id = 15;

"*",
SELECT .
, ,
 , . .
, , , 
.

SELECT. customer_id 
, :
WHERE customer_id = :id;

customer_id customer 
serial, , ,
.

.
customer_id
:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

SQL

457

EXEC SQL include sqlca;


EXEC SQL whenever sqlwarning sqlprint;
EXEC SQL whenever sqlerror do GiveUp();
void GiveUp()
{
fprintf(stderr, "Fatal Error\n");
sqlprint();
}
main(int argc, char *argv[])
{
EXEC SQL begin declare section;
int id;
char zip[10];
VARCHAR address[64];
int address_ind;
EXEC SQL end declare section;
EXEC SQL connect to bpsimple;
EXEC SQL SELECT max(customer_id) INTO :id FROM customer;
printf("We have %d customers\n", id);
EXEC SQL SELECT addressline, zipcode
INTO :address:address_ind, :zip
FROM customer
WHERE customer_id = :id;
printf("The address is%sNULL\n", address_ind ? " " : " not ");
printf("customer id: %d\n", id);
printf("%.*s <%.*s>\n", sizeof(zip), zip, address.len, address.arr);
EXEC SQL disconnect all;
}
select.pgc

, 
:
$ ./select
We have 15 customers
The address is not NULL
customer id: 15
MT2 6RT <4 The Square>


, SELECT, 
, , 
. 

458

14. PostgreSQL C SQL

, 
.
, 
, C. C 
,
. , , printf 
,
.
, . . strcpy , 
.

, , SE
LECT, . printf, 
, . . printf
, ,
. strcpy 
, , 
, 
, .


: 
.
printf
. %s
.
10
, , 64 
:
printf("%.10s %.64s\n", zip, address.arr);


, .

, printf, 
.
printf, :
printf("%.*s %.*s\n", sizeof(zip), zip, address.len, address.arr);

, , 
.
,
NULL.

SQL

459


NULL
NULL.
. libpq PQgetisnull, , 
NULL. SQL
, , NULL, 
.
, 
, ,
NULL. 
, . 
, :
SELECT addressline
INTO :address:address_ind FROM customer
WHERE ...

address_ind, 
, ,
address, NULL.
( , . .), 
, NULL.
, 
, . 
, ,
_ind ().

ecpg . libpq
SQL,
. :
EXEC SQL BEGIN WORK;
EXEC SQL COMMIT WORK;
EXEC SQL ROLLBACK;

, ( t) ecpg 
, SQL
( autocommit ). 
,
COMMIT.
,
pgc, , t ecpg.


, 
, 

460

14. PostgreSQL C SQL


.
select,
, 
, .

.
, (se
lect2.pgc), , SELECT :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
EXEC SQL include sqlca;
EXEC SQL whenever sqlwarning sqlprint;
EXEC SQL whenever sqlerror do GiveUp();
void GiveUp()
{
fprintf(stderr, "Fatal Error\n");
sqlprint();
exit(1);
}
main(int argc, char *argv[])
{
EXEC SQL begin declare section;
int id;
char title[4];
int title_ind;
char zip[10];
VARCHAR lname[32];
VARCHAR town[64];
int town_ind;
EXEC SQL end declare section;
if(argc != 2) {
printf("Usage: select2 zipcode\n");
exit(1);
}
strncpy(zip, argv[1], sizeof(zip));
EXEC SQL connect to bpsimple;
EXEC SQL SELECT customer_id, title, lname, town
INTO :id, :title:title_ind, :lname, :town:town_ind
FROM customer

SQL

461

WHERE zipcode = :zip;


if(sqlca.sqlerrd[2] == 0) {
printf("no customer found\n");
}
else {
printf("title is%sNULL\n", title_ind ? " " : " not ");
printf("town is%sNULL\n", town_ind ? " " : " not ");
printf("customer id: %d\n", id);
printf("%.*s %.*s <%.*s>\n",
sizeof(title), title,
lname.len, lname.arr,
town.len, town.arr);
}
EXEC SQL disconnect all;
}


,
SQL
sqlca.sqlerrd[2]. , , 
. .
:
customer_id | title | lname | town
| zipcode
++++
1 | Miss | Stones | Hightown | NT2 1AQ
2 | Mr
| Stones | Lowtown | LT5 7RA
4 | Mr
| Matthew | Yuleville | YV67 2WR
5 | Mr
| Cozens | Oahenham | OA3 6QW
6 | Mr
| Matthew | Nicetown | NT3 7RT
7 | Mr
| Stones | Bingham | BG4 2WE
8 | Mrs | Stones | Bingham | BG4 2WE
9 | Mrs | Hickman | Histon
| HT3 5EM
10 | Mr
| Howard | Tibsville | TB3 7FG
11 | Mr
| Jones | Bingham | BG3 8GD
12 | Mr
| Neill | Winersby | WB3 6GQ
13 | Mrs | Hendy | Oxbridge | OX2 3HX
14 | Mr
| O'Neill | Welltown | WT3 8GM
15 | Mr
| Hudson | Milltown | MT2 6RT
3 | Miss | Matthew | Nicetown | NT2 2TX
$ make select2
$ ./select2 "NT2 2TX"
title is not NULL
town is not NULL
customer id: 3
Miss Matthew <Nicetown>
$ ./select2 "BG4 2XE"
no customer found

462

14. PostgreSQL C SQL


$ ./select2 "BG4 2WE"
Fatal Error
sql error SQL error #203 in line 39.
$

(zipcode) 
, . 
.
zipcode , .
, . . 
.
zipcode. 
,
. , 
, .
.
, exec sql whe
never: ,
. :
EXEC SQL whenever not found do break;
do {
EXEC SQL SELECT customer_id, title, lname, town
INTO :id, :title:title_ind, :lname, :town:town_ind
FROM customer
WHERE zipcode = :zip;
printf("title is%sNULL\n", title_ind ? " ": " not ");
printf("town is%sNULL\n", town_ind ? " ": " not ");
printf("customer id: %d\n", id);
printf("%.*s %.*s <%.*s>\n",
sizeof(title), title,
lname.len, lname.arr,
town.len, town.arr);
} while(0);

, , 
C break. break , 
, ( C 
do{} while(0)), , do
, . . .
, ,
, .
, , ,
ecpg sql whene
ver. :
exec sql whenever not found < >;
exec sql < >;

SQL

463

:
ECPGdo( < > );
if(sqlca.sqlcode == ECPG_NOT_FOUND) < >;

, sql whenever,
, . 
break, 
, .
sql whe
never , ,
, ,
.
sql whenever
, , 
, , goto. 
, sql whenever
, 
.
,
, .


SQL.

.
, 13, .
, , 
, SELECT 
; 
, SELECT COUNT(*) FROM SELECT
, ,
. , .
, , 
, FETCH, 
, 
. libpq, , 

. , 
, .

. 
PostgreSQL, 

464

14. PostgreSQL C SQL

ecpg, 
:
EXEC SQL begin work
EXEC SQL declare mycursor cursor for SELECT ... ;

SELECT, ,
WHERE . ., 
INTO, . . 
.
. 
:
EXEC SQL open mycursor;

: FETCH INTO:
EXEC SQL fetch next from mycursor into :var1, :var2, ... ;

, sqlca.sql
errd[2] , sqlca.sqlcode 100,
, sql whenever not found.

:
EXEC SQL close mycursor;
EXEC SQL commit work;

.
(cursor.pgc),
, 7:
, 
:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
EXEC SQL include sqlca;
EXEC SQL whenever sqlwarning sqlprint;
EXEC SQL whenever sqlerror do GiveUp();
void GiveUp()
{
fprintf(stderr, "Fatal Error\n");
sqlprint();
exit(1);
}

SQL

465

main(int argc, char *argv[])


{
EXEC SQL begin declare section;
char town[32];
double shipping;
char date[15];
EXEC SQL end declare section;
if(argc != 2) {
printf("Usage: cursor town\n");
exit(1);
}
strncpy(town, argv[1], sizeof(town));
EXEC SQL connect to bpsimple;
EXEC SQL begin work;
EXEC SQL declare mycursor cursor for
SELECT oi.date_placed, oi.shipping
FROM orderinfo oi, customer c
WHERE oi.customer_id = c.customer_id
AND town = :town;
EXEC SQL open mycursor;
EXEC SQL fetch next from mycursor into :date, :shipping;
while(sqlca.sqlcode == 0) {
printf("%.*s <%.2f>\n", sizeof(date), date, shipping);
EXEC SQL fetch next from mycursor into :date, :shipping;
}
EXEC SQL close mycursor;
EXEC SQL commit work;
EXEC SQL disconnect all;
return EXIT_SUCCESS;
}



, , 
:
$ make cursor
$ ./cursor Erewhon
$ ./cursor Milltown
20000902 <3.99>

466

14. PostgreSQL C SQL


$ ./cursor Bingham
20000623 <0.00>
20000721 <5.55>

ecpg
ecpg C pgc, 
. 
C, , ecpg  .
C, ecpg.
, ecpg
#line, 
.pgc,
.c.
:
ecpg .c .pgc
grep #line


C

, , cursor.pgc:
$ ecpg t I/usr/local/pgsql/include cursor.pgc
$ grep v '^#line' cursor.c > _1.c
$ mv _1.c cursor.c
$ make
cc I/usr/local/pgsql/include L/usr/local/pgsql/lib lecpg lpq cursor.c
o cursor

, SQL 
, C, SQL
. ecpg C, 
.
.

INSERT UPDATE.
SELECT, 

WHERE. ,

. , , 
, .

467

, ,
PostgreSQL C.
, libpq

, .
, SQL
, . . ecpg ,
SQL , SQL
. , 
.

15
PostgreSQL PHP


 . ,
:

 

 


 HTML 

Post
greSQL PHP. PHP 
,  
. 
HTML ,
. PHP , 
PostgreSQL.
, 
PHP. , , , 
:

PHP: http://www.php.net

PHP4 (Beginning PHP4), (Wankyu Choi),


(Allan Kent), (Ganesh Prasad)
(Chris Ullman), (Jon Blank)
(Sean Cazzell), Wrox Press (ISBN 1861003730)

469

PostgreSQL PHP


PHP. , 
. 
PHP, 
PostgreSQL.
, PHP 4. 

PHP, 
. , ,
PHP (
<?php ?>), .

PostgreSQL PHP
PHP, 
PostgreSQL, PHP
PostgreSQL.
, Post
greSQL PHP, 
phpinfo.php ( 
), :
<?php
phpinfo();
?>

.
PostgreSQL , 
:
pgsql
PostgreSQL

Enabled

Active Persistent Links

Active Links

Directive

Local Value

Master Value

Pgsql.allow_persistent

On

On

Pgsql.max_links

Unlimited

Pgsql.max_persistent

Unlimited

Unlimited
Unlimited

PHP PostgreSQL, 
.

470

15. PostgreSQL PHP

PHP PostgreSQL
. withpgsql
:
$ ./configure withpgsql

, 
PostgreSQL, :
$ ./configure withpgsql=/var/lib/pgsql

, , , configure
. 
, PHP PostgreSQL, LDAP XML 
:
$ ./configure withpgsql withldap enablexml


PHP ( , 
INSTALL, ) http://
www.php.net/manual/en/html/installation.html.

PHP API PostgreSQL


PostgreSQL 
PostgreSQL, 
PHP. 
http://www.php.net/
manual/ref.pgsql.php.
PHP, Postgre
SQL, , 
, :
<?php
$db_handle = pg_connect("dbname=bpsimple");
$query = "SELECT * FROM item";
$result = pg_exec($db_handle, $query);
echo "Number of rows: " . pg_numrows($result);
pg_freeresult($result);
pg_close($db_handle);
?>

, PHP . 

PostgreSQL PHP.

471

PHP API PostgreSQL


,
. 
( ). PHP
, 
.
pg_connect()

pg_connect(). 

. :
$db_handle = pg_connect("dbname=bpsimple user=jon");


user=<username>.
PHP,
, :
$db_handle = pg_connect("dbname=$dbname user=$dbuser");


PostgreSQL. 
. 15.1:
15.1.


Dbname
,  $PGDATABASE

User

, $PGUSER

password

Host

,  $PGHOST

localhost

hostaddr

IP ,  $PGHOSTADDR

Port

TCP/IP,  $PGPORT

or 5432

$PGPASSWORD

, pg_con
nect() . , 
, , :
<?php
$db_handle = pg_connect("dbname=bpsimple");
if ($db_handle) {

472

15. PostgreSQL PHP


echo 'Connection attempt succeeded.';
} else {
echo 'Connection attempt failed.';
}
pg_close($db_handle);
?>

, PHP 
:
$db_handle1 = pg_connect("dbname=database1");
$db_handle2 = pg_connect("dbname=database2");


PHP . 
,
, , 
. PHP 
,
, 
 , 
. , 
,
.
pg_pconnect()
PostgreSQL
pg_pconnect().
pg_connect() , 
.
, 
. 

. ,

( ).

.


pg_close()

pg_close():
pg_close($db_handle);

PHP API PostgreSQL

473

. ,
. 
. ,
PHP 
.
, pg_close()
, 
, , 
.
,
pg_close() , 
.


PHP 
. 
. 15.2:
15.2. ,

pg_dbname()
pg_host()

pg_options()
pg_port()

pg_tty()

TTY


, ( ) , 
. :
<?php
$db_handle = pg_connect("dbname=bpsimple");
echo "<h1>Connection Information</h1>";
echo "Database name: ' . pg_dbname($db_handle) . "<br>\n";
echo "Hostname: " . pg_host($db_handle) . "<br>\n";
echo "Options: " . pg_options($db_handle) . "<br>\n";
echo "Port: " . pg_port($db_handle) . "<br>\n";
echo "TTY name: " . pg_tty($db_handle) . "<br>\n";
pg_close($db_handle);
?>


PHP .
.

474

15. PostgreSQL PHP

SQL , 
PHP.
PHP:
$lastname = strtolower($lastname);
$query = "SELECT * FROM customer WHERE lname = '$lastname'";

$lastname
, , 
PHP.
, $lastname
.
$query = "SELECT * FROM customer WHERE lname = '" .strtolower($lastname) . "'";

strtolower().
( , 
),
( ),
.
, strtolower()
$lastname ,
PHP.
$query = sprintf("SELECT * FROM customer WHERE lname = '%s'",
strtolower($lastname));


sprintf(). sprintf() 
(, %s , )
.
sprintf() http://www.php.net/manual/en/
function.sprintf.php.
.
, , 
. , ,
, 
, 
. 

. ,
.
, 
:
$query = "UPDATE table $tablename SET " . strtolower($column) . " = '" .
strtoupper($value) . "'";

PHP API PostgreSQL

475

PHP sprintf() :
$query = sprintf("UPDATE table %s SET %s = '%s'", $tablename,
strtolower($column), strtoupper($value));

, , 
, 
, 
. , , 
, , 
.


, 
,
. PHP
, .
, , , 
. SQL
:
DELETE FROM items WHERE item_id = 4 OR item_id = 6

,
, item_id WHERE?
,
where , 
.
, , ,
 HTML,
,  
( , 
).
$item_ids. , 
:
<?php
$db_handle = pg_connect("dbname=bpsimple");
$query = "DELETE FROM items WHERE ";
$query .= "item_id = " . $item_ids[0];
if (count($item_ids) > 1) {
array_shift($item_ids);
$query .= " or item_id = " .
implode(" or item_id =", $item_ids);
pg_close($db_handle);
?>

476

15. PostgreSQL PHP

SQL 
. 
, :
<?php
$db_handle = pg_connect("dbname=bpsimple");
function sqlDelete($tablename, $column, $ids)
{
$query = '';
if (is_array($ids)) {
$query = "DELETE FROM $tablename WHERE ";
$query .= "$column = " . $ids[0];
if (count($ids) > 1) {
array_shift($ids);
$query .= " or $column = " .
implode(" or $column =", $ids);
}
}
return $query;
}
pg_close($db_handle);
?>


, . 
pg_exec().
pg_exec()
pg_exec() Post
greSQL .
, pg_exec():
<?php
$db_handle = pg_connect("dbname=bpsimple");
$query = 'SELECT * FROM customer';
$result = pg_exec($db_handle, $query);
pg_close($db_handle);
?>

, pg_exec() : 
( 
). pg_exec()
. 
.

, pg_exec() .

PHP API PostgreSQL

477

, pg_exec(),
.
:
<?php
$db_handle = pg_connect("dbname=bpsimple");
$query = "SELECT * FROM customer";
$result = pg_exec($db_handle, $query);
if ($result) {
echo "The query executed successfully.<br>\n";
} else {
echo "The query failed with the following error:<br>\n";
echo pg_errormessage($db_handle);
}
pg_close($db_handle);
?>

, pg_exec().
FALSE ( , ), $result 
. ($re
sult ) , .
pg_errormessage()
.
.


pg_exec() 
,
. 
, . ,
, 
.
PHP 
. 
,
. ,
, .
pg_numrows() pg_numfields()
: pg_numrows()
pg_numfields(). 
. :
<?php
$db_handle = pg_connect("dbname=bpsimple");
$query = "SELECT * FROM customer";
$result = pg_exec($db_handle, $query);

478

15. PostgreSQL PHP


if ($result) {
echo "The query executed successfully.<br>\n";
echo "Number of rows in result: " . pg_numrows($result) . "<br>\n";
echo "Number of fields in result: " . pg_numfields($result);
} else {
echo "The query failed with the following error:<br>\n";
echo pg_errormessage($db_handle);
}
pg_close($db_handle);
?>

, 1.
pg_cmdtuples()
pg_cmdtuples(),
, . ,
, 
, 
.
, pg_cmdtuples() 
, ( 
, ):
<?php
$db_handle = pg_connect("dbname=bpsimple");
$query = "DELETE FROM item WHERE cost_price > 10.00";
$result = pg_exec($db_handle, $query);
if ($result) {
echo "The query executed successfully.<br>\n";
echo "Number of rows deleted: " . pg_cmdtuples($result);
} else {
echo "The query failed with the following error:<br>\n";
echo pg_errormessage($db_handle);
}
pg_close($db_handle);
?>

(
), pg_cmdtuples() 0.



. pg_result().
pg_result()
pg_result() , 
. 
,
. ,

PHP API PostgreSQL

479

, .
.
pg_result():
<?php
$db_handle = pg_connect("dbname=bpsimple");
$query = "SELECT title, fname, lname FROM customer";
$result = pg_exec($db_handle, $query);
if ($result) {
echo "The query executed successfully.<br>\n";
for ($row = 0; $row < pg_numrows($result); $row++) {
$fullname = pg_result($result, $row, 'title') . " ";
$fullname .= pg_result($result, $row, 'fname') . " ";
$fullname .= pg_result($result, $row, 'lname');
echo "Customer: $fullname<br>\n";
}
} else {
echo "The query failed with the following error:<br>\n";
echo pg_errormessage($db_handle);
}
pg_close($db_handle);
?>


:
<?php
$db_handle = pg_connect("dbname=bpsimple");
$query = "SELECT title, fname, lname FROM customer";
$result = pg_exec($db_handle, $query);
if ($result) {
echo "The query executed successfully.<br>\n";
for ($row = 0; $row < pg_numrows($result); $row++) {
for ($col = 0; $col < pg_numfields($result); $col++) {
$fullname = pg_result($result, $row, $col) . " ";
$fullname .= pg_result($result, $row, $col) . " ";
$fullname .= pg_result($result, $row, $col);
echo "Customer: $fullname<br>\n";
}
}
} else {
echo "The query failed with the following error:<br>\n";
echo pg_errormessage($db_handle);
}
pg_close($db_handle);
?>


. PHP 
, . .
.

480

15. PostgreSQL PHP

pg_fetch_row()
PHP , pg_fetch_row() pg_fetch_array(),
.
.
pg_fetch_row() ,
.
. ,
pg_fetch_row():
<?php
$db_handle = pg_connect("dbname=bpsimple");
$query = "SELECT title, fname, lname FROM customer";
$result = pg_exec($db_handle, $query);
if ($result) {
echo "The query executed successfully.<br>\n";
for ($row = 0; $row < pg_numrows($result); $row++) {
$values = pg_fetch_row($result, $row);
for ($col = 0; $col < count($values); $col++) {
$fullname = $values[$col] . " ";
$fullname .= $values[$col] . " ";
$fullname .= $values[$col];
echo "Customer: $fullname<br>\n";
}
}
} else {
echo "The query failed with the following error:<br>\n";
echo pg_errormessage($db_handle);
}
pg_close($db_handle);
?>

, pg_fetch_row() 
pg_result(). ,
,
PHP .

.
. ,
pg_fetch_array().
pg_fetch_array()
pg_fetch_array() ,

( ). 
,
. 15.3:

PHP API PostgreSQL

481

15.3.

PGSQL_ASSOC

PGSQL_NUM

PGSQL_BOTH

,
PGSQL_BOTH. , 
, , , 
. , 
, ,
.
,
pg_fetch_array():
<?php
$db_handle = pg_connect("dbname=bpsimple");
$query = "SELECT title, fname, lname FROM customer";
$result = pg_exec($db_handle, $query);
if ($result) {
echo "The query executed successfully.<br>\n";
for ($row = 0; $row < pg_numrows($result); $row++) {
$values = pg_fetch_array($result, $row, PGSQL_ASSOC);
$fullname = $values['title'] . " ";
$fullname .= $values['fname'] . " ";
$fullname .= $values['lname'];
echo "Customer: $fullname<br>\n";
}
} else {
echo "The query failed with the following error:<br>\n";
echo pg_errormessage($db_handle);
}
pg_close($db_handle);
?>

pg_fetch_object()
PHP
pg_fetch_object().
. 
. pg_fetch_ob
ject() :
<?php
$db_handle = pg_connect("dbname=bpsimple");
$query = "SELECT title, fname, lname FROM customer";
$result = pg_exec($db_handle, $query);
if ($result) {

482

15. PostgreSQL PHP


echo "The query executed successfully.<br>\n";
for ($row = 0; $row < pg_numrows($result); $row++) {
$values = pg_fetch_object($result, $row, PGSQL_ASSOC);
$fullname = $values>title . " ";
$fullname .= $values>fname . " ";
$fullname .= $values>lname;
echo "Customer: $fullname<br>\n";
}
} else {
echo "The query failed with the following error:<br>\n";
echo pg_errormessage($db_handle);
}
pg_close($db_handle);
?>


PHP 
.
, 
.
pg_fieldisnull()
PostgreSQL
(NULL). PHP NULL , PostgreSQL.
PHP pg_fieldisnull(), ,
NULL PostgreSQL:
<?php
$db_handle = pg_connect("dbname=bpsimple");
$query = "SELECT title, fname, lname FROM customer";
$result = pg_exec($db_handle, $query);
if (pg_fieldisnull($result, $row, $field)) {
echo "$field is NULL.";
} else {
echo "$field is " . pg_result($result, $row, $field);
}
pg_close($db_handle);
?>

pg_fieldname() pg_fieldnum()
. 
:
<?php
$db_handle = pg_connect("dbname=bpsimple");
$query = "SELECT title, fname, lname FROM customer";
$result = pg_exec($db_handle, $query);
if (pg_fieldisnull($result, $row, $field)) {

PHP API PostgreSQL

483

echo "$field is NULL.";


echo "Field 1 is named: " . pg_fieldname($result, 1);
echo "Field item_id is number: " . pg_fieldnum($result, "item_id");
} else {
echo "$field is " . pg_result($result, $row, $field);
}
pg_close($db_handle);
?>

, pg_fieldname() ,
SELECT.
pg_fieldsize(), pg_fieldprtlen() pg_fieldtype()
,
:
<?php
$db_handle = pg_connect("dbname=bpsimple");
$query = "SELECT title, fname, lname FROM customer";
$result = pg_exec($db_handle, $query);
if (pg_fieldisnull($result, $row, $field)) {
echo "$field is NULL.";
echo "Field 1 is named: " . pg_fieldname($result, 1);
echo "Field 1 is named: " . pg_fieldname($result, 1);
echo "Field item_id is number: " . pg_fieldnum($result, "item_id");
echo "Size of field 2:" . pg_fieldsize($result, 2);
echo "Length of field 2: " . pg_fieldprtlen($result, $row, 2);
echo "Type of field 2: " . pg_fieldtype($result, 2);
} else {
echo "$field is " . pg_result($result, $row, $field);
}
pg_close($db_handle);
?>

, 0.
,
.
, pg_fieldsize() 1,
, . pg_fieldprtlen()
1 .


pg_freeresult()
pg_freeresult() , 
:
pg_freeresult($result);

484

15. PostgreSQL PHP

PHP , 
, ,
,
, 
.


, PHP 
, 

PHP.
( ),
, :

, OID ( ) 

double

( . .)


,
.
PostgreSQL 
 ( false 1).

,
. :
$db_handle = pg_connect('dbname=bpsimple');
if (!$db_handle) {
header("Location: http://www.example.com/error.php");
exit;
}

, , 
, .
pg_errormessage()
pg_errormessage() 
,
. ,
, , 
.

PHP API PostgreSQL

485

PHP 
, 
.
.
@

PHP ( er
ror_reporting php.ini).
PHP 
. PHP ,
, @. ,
:
$db_handle = pg_connect("host=nonexistent_host");
$result = @pg_exec($db_handle, "SELECT * FROM item");

@,
,
(, , 
, 
).
, $re
sult,
. , 
,
pg_errormessage().
(!result ....) , , SQL .
(!pg_cmdTuples($result)) , ,
SQL .


PostgreSQL, PHP 

. SQL ASCII.
: SQL_ASCII, EUC_JP, EUC_CN,
EUC_KR, EUC_TW, UNICODE, MULE_INTERNAL, LATINX (X=1...9), KOI8, WIN, ALT, SJIS,
BIG5, WIN1250.
pg_client_encoding()
pg_client_encoding() 
:
$encoding = pg_client_encoding($db_handle);

486

15. PostgreSQL PHP

pg_set_client_encoding()

pg_set_client_encoding():
pg_set_client_encoding($db_handle, 'UNICODE');

PEAR
PEAR (The PHP Extension and Application Repository 
PHP) 
CPAN Perl PHP. PEAR:

,

,

PHP
,

PEAR PHP, 
 
PHP. , 
PHP PHP. 
PHP http://
www.php.net/manual/en/language.oop.php.
PEAR :

http://pear.php.net
http://php.weblogs.com/php_pear_tutorials/

PEAR
PEAR (DB),
PHP. 
DB

. 
.
, .
DB PEAR 
, 
. 
DB. 
Perl DBI.

.

PHP API PostgreSQL

487


.
DB-

: , , PEAR DB
include_
path. PHP4 :
<?php
/* PEAR . */
require_once "DB.php";
/* . */
$username = "jon";
$password = "secret";
$hostname = "localhost";
$dbname = "bpsimple";
/* DSN . */
$dsn = "pgsql://$username:$password@$hostname/$dbname";
/* . */
$db = DB::connect($dsn);
/* . */
if (DB::isError($db)) {
die ($db>getMessage());
}
/* . */
$query = "SELECT title, fname, lname FROM customer";
$result = $db>query($query);
/* . */
if (DB::isError($result)) {
die ($result>getMessage());
}
/* . */
while ($row = $result>fetchRow(DB_FETCHMODE_ASSOC)) {
$fullname = $row['title'] . " ";
$fullname .= $row['fname'] . " ";
$fullname .= $row['lname'];
echo "Customer: $fullname<br>\n";
}

488

15. PostgreSQL PHP

/* . */
$db>disconnect();
?>

,
PostgreSQL, , 
. ,
(, Oracle MySQL).

PEAR
PEAR DB
. , PEAR 
. , 
:
<?php
/* PEAR . */
require_once 'DB.php';
/* DSN */
$dsn = "pgsql://jon:secret@localhost/bpsimple";
/* . */
$db = DB::connect($dsn);
/* . */
if (DB::isError($db)) {
die ($db>getMessage());
}

PEAR: DB::isEr
ror().  DB::connect() 
, PEAR_Error,
.
DB::isError(), .
, , , ,
.
( , Postgre
SQL), getMessage() PEAR_Error.
.
:
/* . */
$db>setErrorHandling(PEAR_ERROR_DIE);
/* . */
$query = "SELECT title, fname, lname FROM customer";

PHP API PostgreSQL

489

$result = $db>query($query);
/* . */
if (DB::isError($result)) {
die ($result>getMessage());
}
while ($row = $result>fetchRow(DB_FETCHMODE_ASSOC)) {
$fullname = $row['title'] . " ";
$fullname .= $row['fname'] . " ";
$fullname .= $row['lname'];
echo "Customer: $fullname<br>\n";
}
/* . */
$db>disconnect();
?>

, PEAR
setErrorHandling(). 
PEAR_ERROR_DIE ,
PHP .

. 15.4:
15.4.

PEAR_ERROR_RETURN

( )

PEAR_ERROR_PRINT

PEAR_ERROR_TRIGGER PHP trigger_error() 



PEAR_ERROR_DIE

PEAR_ERROR_CALLBACK

PEAR_Error
PEAR http://php.net/manual/ class.pe"
ar"error.php.


PEAR 
. ,
prepare() execute() DB. ,
(
DB::connect()):
/* $items. */
$items = array(

490

15. PostgreSQL PHP

'6241527836190' => 20,


'7241427238373' => 21,
'7093454306788' => 22
);
/* SQL. */
$statement = $db>prepare("INSERT INTO barcode VALUES(?,?)");
/* $items. */
while (list($barcode, $item_id) = each($items)) {
$db>execute($statement, array($barcode, $item_id));
}

, SQL, ,
.
prepare() SQL, 
.
, . ,
execute(), .
, $items,  
,
. , 
$items, 
, SQL.
, execute() 
,
. ar
ray($barcode, $item_id).  
, ,
.
, PEAR DB 
.

Post
greSQL PHP.
, 
, 
. 
PEAR.
, , 
, 
 .

16
PostgreSQL Perl

, Post
greSQL, ,
. , 
, Perl. 
Perl PostgreSQL.
13 , libpq 
, , , 
C, . 
NULL, , 
, .
13 , ,
. Perl 
, , , 
,
.
Perl ,

. ,
, PHP, 
.
Perl.
, , 
, :

http://www.perl.org http://www.cpan.org

Perl (Beginning Perl), (Simon Cozens),


Wrox Press (ISBN 1861003145)

492

16. PostgreSQL Perl

Perl (Learning Perl), . (Randal L.


Schwartz) (Tom Christiansen), OReilly (ISBN
1565922840)

, , Perl,
C.
:

( , Perl 
) $

( ) @

( ) %

, @ % 
, 
$.
, Perl, ,

. , Perl 
, 
.
PostgreSQL Perl,
.
, PostgreSQL Perl:

Perl C libpq (pqsql_perl5)

Perl ( SQL, 
14)

,
C, 13.
, . . .
. PL/Perl 
, , , ecpg C, Perl 
, C. , PL/Perl , . . 
Perl, (lib
perl.so libperl.a), 
(. Perl
).

pgsql_perl5 Pg
Perl, (
, Perl ) 
libpq,
(Edmund Mergl) pgsql_per15, Pg. 

pgsql_perl5 Pg

493

, , , , 
, PostgreSQL.

pgsql_perl5
 PostgreSQL
, ,
. ,
RedHat Linux, :
postgresqlperlversionrelease.architecture.rpm

RPM
:
$ rpm i$ rpm i postgresqlperl7.1.21.i386.rpm

, (
) .
PostgreSQL 
Perl , 
. ,
withperl configure ( Post
greSQL, . 3), Post
greSQL, .
Perl , 
, ( 1.8.0 Post
greSQL 7.1.2, CPAN 
1.9.0), :
$ tar xfz pgsql_perl51.9.0.tar.gz

, POSTGRES_INCLUDE ,
libpq ( /usr/local/pgsql/
include Red Hat), POSTGRES_LIB 
(, /usr/local/pgsql/lib). 
, 1.9.0: 
1.8.0 POST
GRES_HOME, , 
PostgreSQL (, PostgreSQL
$POSTGRES_HOME/include, $POSTGRES_HOME/lib).
:
$ perl Makefile.PL
$ make
$ make test

, 
:
# make install

494

16. PostgreSQL Perl

CPAN
CPAN (Comprehensive Perl Archive Network) 
Perl,
http://www.cpan.org.
Perl.
, ,
CPAN: , 
make, . ,
, , .

.
,
.  CPAN
( ), 
, CPAN,
, :
perl MCPAN e 'install DBI'

, ActiveState Perl (http://www.activestate.com),


ppm. 
, ppm h.
, CPAN 
, , 
perldoc 
:
perldoc DBI

pgsql_perl5
pgsql_perl5 C,
. 
Perl C, 
select2.c 13:
select_c.pl
#!/usr/bin/perl w
use Pg;
use strict;
sub doSQL
{
my ($conn, $command) = @_;

pgsql_perl5

495

print $command, "\n";


my $result = $conn>exec($command);
print "status is ", $result>resultStatus, "\n";
print "#rows affected ", $result>cmdTuples, "\n";
print "result message: ", $conn>errorMessage, "\n";
if($result>resultStatus eq PGRES_TUPLES_OK) {
print "number of rows returned = ", $result>ntuples, "\n";
print "number of fields returned = ", $result>nfields, "\n";
for(my $r = 0; $r < $result>ntuples; ++$r) {
for(my $n = 0; $n < $result>nfields; ++$n) {
print " ", $result>fname($n), " = ",
$result>getvalue($r, $n), "(",
$result>getlength($r, $n), "),";
}
print "\n";
}
}
}
my $conn = Pg::connectdb("");
if($conn>status eq PGRES_CONNECTION_OK) {
print "connection made\n";
doSQL($conn, "DROP TABLE number");
doSQL($conn, "CREATE TABLE number ( value INTEGER, name VARCHAR )");
doSQL($conn, "INSERT INTO number values(42, 'The Answer')");
doSQL($conn, "INSERT INTO number values(29, 'My Age')");
doSQL($conn, "INSERT INTO number values(29, 'Anniversary')");
doSQL($conn, "INSERT INTO number values(66, 'ClicketyClick')");
doSQL($conn, "SELECT * FROM number WHERE value = 29");
doSQL($conn, "UPDATE number SET name = 'Zaphod' WHERE value = 42");
doSQL($conn, "DELETE FROM number WHERE value = 29");
} else {
print "connection failed\n";
}

. ,
libpq. , $conn>exec($com
mand) PQexec($conn, $command). 
Perl. 
.
:
$ perl select_c.pl

496

16. PostgreSQL Perl

, C, ,
PG* 
.
:
( chmod 750 select_c.pl), :
$ ./select_c.pl

,
C:
connection made
DROP TABLE number
status is 1
#rows affected is
error message:
CREATE TABLE number ( value INTEGER, name VARCHAR )
status is 1
#rows affected is
error message:
INSERT INTO number values(42, 'The Answer')
status is 1
#rows affected is 1
error message:
INSERT INTO number values(29, 'My Age')
status is 1
#rows affected is 1
error message:
INSERT INTO number values(29, 'Anniversary')
status is 1
#rows affected is 1
error message:
INSERT INTO number values(66, 'ClicketyClick')
status is 1
#rows affected is 1
error message:
SELECT * FROM number WHERE value = 29
status is 2
#rows affected is
error message:
number of rows returned = 2
number of fields returned = 2
value = 29(2), name = My Age(6),
value = 29(2), name = Anniversary(11),
UPDATE number SET name = 'Zaphod' WHERE value = 42
status is 1
#rows affected is 1
error message:
DELETE FROM number WHERE value = 29
status is 1
#rows affected is 2
error message:

497

pgsql_perl5

, PostgreSQL.

#include <libpqfe.h> C,
:
use Pg;

doSQL .
:
$conn = Pg::connectdb("");

PQconnectdb(), 
, dbname=bpsimple user=rick,
, (. 16.1):
16.1.

PGHOST

"localhost"

PGPORT

5432

PGOPTIONS

PGDATABASE

template1

PGUSER

PGPASSWORD

$conn , 
Pgconn C. Perl
, C, ,
eq, ==. pgsql_perl5
, PGRES_EMPTY_QUERY, PGRES_COMMAND_OK PGRES_TUPLES_OK.
, doSQL
, .
Perl ,
PQfinish() , ,
, $conn 
, undef. , 
, 
.
doSQL :
$result = $conn>exec($command);

$result , PGresult* C.

, resultStatus, cmdStatus, ntuples nfields. ,
pgsql_perl5 , 

498

16. PostgreSQL Perl

($conn>errorMes
sage).
Perl PostgreSQL.
:
$fname
$fnumber
$ftype
$fsize

=
=
=
=

$result>fname($fieldNum);
$result>fnumber($fieldName);
$result>ftype($fieldNum);
$result>fsize($fieldNum);

libpq: $fieldNum
( ), $fieldName .
:
$value = $result>getvalue($tupleNum, $fieldNum);
$length = $result>getlength($tupleNum, $fieldNum);
$isNull = $result>getisnull($tupleNum, $fieldNum);

libpq, ,
$tupleNum ( 
).
PQclear().
: Perl , 
.
, C
13. C Perl, 
Perl. , for 
C,
Perl. , 
fetchrow pgsql_perl5,
( NULL ):
while(my @row = $result>fetchrow) {
print " ", join(" ", @row), "\n";
}

join
, . 
, Perl, 
:
($number, $value) = $result>fetchrow

$number $value , 
.
, , 
Perl. 
Perl, ,

pgsql_perl5

499

, 

:
select.pl
#!/usr/bin/perl w
use Pg;
use strict;
# 
sub doSQL
{
my ($conn, $command) = @_;
print $command, "\n";
my $result = $conn>exec($command);
print "status is ", $result>resultStatus, "\n";
print "#rows affected ", $result>cmdTuples, "\n";
print "result message: ", $conn>errorMessage, "\n";
}
#
sub doSQLquery
{
my ($conn, $command) = @_;
print $command, "\n";
my $result = $conn>exec($command);
print "status is ", $result>resultStatus, "\n";
return if($result>resultStatus ne PGRES_TUPLES_OK);
print "number of rows returned = ", $result>ntuples, "\n";
print "number of fields returned = ", $result>nfields, "\n";
print "fields: ";
for(my $n = 0; $n < $result>nfields; ++$n) {
print " ", $result>fname($n);
}
print "\n";
while(my @row = $result>fetchrow) {
print " ", join(" ", @row), "\n";
}
}

500

16. PostgreSQL Perl

my $conn = Pg::connectdb("") or die "connection failed";


doSQL($conn, "DROP TABLE number");
doSQL($conn, "CREATE TABLE number ( value INTEGER, name VARCHAR )");
doSQL($conn, "INSERT INTO number values(42, 'The Answer')");
doSQL($conn, "INSERT INTO number values(29, 'My Age')");
doSQL($conn, "INSERT INTO number values(29, 'Anniversary')");
doSQL($conn, "INSERT INTO number values(66, 'ClicketyClick')");
doSQLquery($conn, "SELECT * FROM number WHERE value = 29");
doSQL($conn, "UPDATE number SET name = 'Zaphod' WHERE value = 42");
doSQL($conn, "DELETE FROM number WHERE value = 29");


Perl die, 
, ,
Perl . 
, SQL
, ,
, ( ,
).
pgsql_perl5, , Perl 
PQprint() , 
13 ( libpq),
C,
13 pgsql_perl5.

Perl DBI
, Windows, 
ODBC (Open Database Connectivity 
) API,
ADO OLE DB. , Java ,
JDBC (. ).


, . 
, , ,
.
(Database Interface, DBI) Perl
. API, , DBI
API 
(DBD). 
, ,
, Perl (. 16.1):

501

Perl DBI

Perl

DBI

DBI :: Pg

PostgreSQL

DBI :: Oracle

Oracle

. 16.1. Perl

, DBD ODBC 
, . ODBC, 
Win32::ODBC,
PostgreSQL, .
DBI
http://www.symbolstone.org/technology/perl/DBI/ 
Perl DBI (Programming the Perl DBI) 
(Alligator Descartes) (Tim Bunce), OReilly (ISBN
1565926994).1

DBI PostgreSQL DBD


, DBI 
DBD. CPAN, 
( , ). 
, 
. , .
DBI DBD (ADO, Multiplex,
Proxy ExampleP, ,
DBD),
PostgreSQL, . 
(Edmund Mergl)
DBD::Pg. CPAN,
POSTGRES_INCLUDE , libpq,
POSTGRES_LIB ,
.
1

. , . , Perl DBI, 
, 2000 .

502

16. PostgreSQL Perl

PostgreSQL 
, DBD::CSV. , 
, (Comma Sepa
rated Values, CSV). 
, . . .

DBI
,
,
API PostgreSQL. , 
DBI , 
, , 
,
PostgreSQL, pgsql_perl5.
DBI ,
, , 
DBI; :
select_dbi.pl
#!/usr/bin/perl w
use DBI;
use strict;
#
sub doSQL
{
my ($conn, $command) = @_;
print $command, "\n";
my $sth = $conn>prepare($command);
my $nrows = $sth>execute;
print "status is ", $DBI::err, "\n" if $DBI::err;
print "#rows affected is ", $nrows, "\n";
print "error message: ", $DBI::errstr, "\n" if $DBI::err;
}
#
sub doSQLquery
{
my ($conn, $command) = @_;
print $command, "\n";
my $sth = $conn>prepare($command);
my $nrows = $sth>execute;
print "status is ", $DBI::err, "\n" if $DBI::err;
print "number of rows returned (unreliable) = ", $sth>rows, "\n";
print "number of fields returned = ", $sth>{NUM_OF_FIELDS}, "\n";

503

Perl DBI

print "fields: ", join(" ", @{$sth>{NAME}}), "\n";


while(my @row = $sth>fetchrow_array) {
print " ", join(" ", @row), "\n";
}
}
my $conn = DBI>connect("DBI:Pg:") or die $DBI::errstr;
doSQL($conn, "DROP TABLE number");
doSQL($conn, "CREATE TABLE number ( value INTEGER, name VARCHAR )");
doSQL($conn, "INSERT INTO number values(42, 'The Answer')");
doSQL($conn, "INSERT INTO number values(29, 'My Age')");
doSQL($conn, "INSERT INTO number values(29, 'Anniversary')");
doSQL($conn, "INSERT INTO number values(66, 'ClicketyClick')");
doSQLquery($conn, "SELECT * FROM number WHERE value = 29");
doSQL($conn, "UPDATE number SET name = 'Zaphod' WHERE value = 42");
doSQL($conn, "DELETE FROM number WHERE value = 29");
$conn>disconnect;

, , 
DBI.
, :
use DBI;

(. ),
DBI DBD
( ) .
:
$conn = DBI>connect("DBI:Pg:");

,
DBI, . 
DBD, 
:
DBI: :

DBI , 
, .
PostgreSQL ,
PQconnectdb(), dbname=bpsimple; , 
( 
pgsql_perl5).
DBI ; 
(
, DBI::dbname=bpsimple), DBI DBD 
DBI_DRIVER. , 

504

16. PostgreSQL Perl

, DBI 
DBI_DSN. 
connect, 

DBI_USER DBI_PASS, . :
$dbh = DBI>connect($dsn, $uname, $pwd, \%attrs);


, , 
, , ,
DBI.
, AutoCommit, 1 
, DBI
, 0,
.
:
$dbh = DBI>connect("DBI:Pg:dbname=bpsimple",
"rick", "",
{ AutoCommit => 0 });

,
$dbh>com
mit ( $dbh>rollback).
, 
$DBI_USER $PGUSER.
.
, , 
?
connect
undef . , 
$DBI::err $DBI::errstr.
, 
Perl die.
, :
$conn>disconnect;


( ), 
,
. ,
DBI>disconnect_all.
doSQL. DBI
( ): (

505

Perl DBI

). ,
,
,
:
my $sth = $conn>prepare($command);
my $nrows = $sth>execute;

, 
, 
undef, . 
, ,
, ,
, :
my $nrows = $conn>do($command);

, , , 
, do
, .
, :
pgsql_perl5 
, SQL, , DBI 
, 
. 
doSQL : . 
,
, ,
, . , , 
execute, , PostgreSQL 
.
.
, 
fetchrow_array.
:

fetchrow_arrayref
( 
), 
, fetchrow_array ,
.

fetchrow_hashref

.

fetchall_arrayref
.
, 

506

16. PostgreSQL Perl

, ,
.
do , , 
. , 
, , ,
: selectrow_array selectall_arrayref
, (
) . 
, DBI,
.

, undef, 
. :
$sth>finish;

, 
, ,
. 
.
, DBI : 
, .
?
,
?
DBI 
.
SQL
, 
, (
ecpg,
14). 
, 
. 14 15:
my $sth = $conn>prepare("SELECT * FROM number WHERE value = ?");
$sth>execute(14);
# ...
$sth>execute(15);
# ...

() SQL 
execute. $sth>execute(14)
:
$sth>bind_param(1, 14); # : 1
$sth>execute;

507

Perl DBI

, 
. ,
, 
. DBI , ,

, :
my $num;
my $sth = $conn>prepare("SELECT * FROM number WHERE value = ?");
$sth>bind_param_inout(1,\$num, 10);
$num = 14;
$sth>execute;
# ...
$num = 15;
$sth>execute;
# ...

, 
DBI.
, 
; 
, , , .
. 
doSQLquery:
sub doSQLquery
{
my ($conn, $command) = @_;
print $command, "\n";
my $sth = $conn>prepare($command);
my $nrows = $sth>execute;
print "status is ", $DBI::err, "\n" if $DBI::err;
print "number of rows returned (unreliable) = ", $sth>rows, "\n";
my( $name, $value );
$sth>bind_col(1, \$value); # 1st column mapped on to $value
$sth>bind_col(2, \$name); # 2nd column mapped on to $name
while($sth>fetch) {
print " name = ", $name, ", value = ", $value, "\n";
}
}

(
), 
.

508

16. PostgreSQL Perl

DBI?
DBI
PostgreSQL,
, .
, 
, , :
dbi_sources.pl
#!/usr/bin/perl w
use DBI;
use strict;
foreach my $driver (DBI>available_drivers())
{
print "Driver ", $driver;
eval { print "\n", join("\n ", DBI>data_sources($driver)), "\n\n" };
print " error ", $@, "\n\n" if ($@);
}

DBI>available_drivers DBD
, , , 
. DBD , 
, DBI>data_sources 
,  ,
eval. eval
, . 
$@, 
NULL. 
:
Driver ADO
Driver ExampleP
dbi:ExampleP:dir=.
Driver Multiplex
Driver Pg
dbi:Pg:dbname=bpsimple
dbi:Pg:dbname=pgperltest
dbi:Pg:dbname=template1
Driver Proxy

, eval, 
:
install_driver(Proxy) failed: Can't locate RPC/PlClient.pm in @INC (@INC
contains: /usr/lib/perl5/5.6.0/i386linux /usr/lib/perl5/5.6.0 /usr/lib/
perl5/site_perl/5.6.0/i386linux /usr/lib/perl5/site_perl/5.6.0

509

Perl DBI

/usr/lib/perl5/site_perl .) at /usr/lib/perl5/site_perl/5.6.0/i386linux/
DBD/Proxy.pm line 28.
BEGIN failedcompilation aborted at /usr/lib/perl5/site_perl/5.6.0/
i386linux/DBD/Proxy.pm line 28.
Compilation failed in require at (eval 5) line 3.
Perhaps a module that DBD::Proxy requires hasn't been fully installed
at dbi_sources.pl line 10

, DBD proxy .
AutoCommit, 
:

PrintError
$DBI::errstr,
stderr

RaiseError
, 
(die), eval

Name
, ,


, , ,
. ,
, DBI
PostgreSQL DBD.
,
,
. , DBD 
, . 

:
$oldState = $conn>{ AutoCommit };
$conn>{ AutoCommit } = 0;

,
. :
print "number of fields returned = ", $sth>{NUM_OF_FIELDS}, "\n";

. 16.2:
16.2.

NUM_OF_FIELDS

NUM_OF_PARAMS

510

16. PostgreSQL Perl

16.2 ()

NAME

NAME_lc

NAME,

NAME_uc

NAME,

NULLABLE

, , ,
NULL

Statement

TYPE

, , 

,
.
DBI,
. 
DBI dbish. psql, , DBI,
.

PostgreSQL Perl: DBI pgsql_perl5. DBI

. ,
pgsql_perl5 , , , 
. ,
libpq, pgsql_perl5 .
, 
(. F). pgsql_perl5 
, DBI 
. 
, 
, DBI;
pgsql_perl5.

DBIx::Easy
, CPAN, ,
DBIx.
, .
, DBIx::Easy ( 
http://www.linuxia.de/DBIx/Easy/, , ,
CPAN), DBI. DBIx::Easy
DBD. ,
PostgreSQL .

511

Perl DBI


. , . , 
( , ).
: ,
,
.
Perl,
DBIx::Easy, :
select_easy.pl
#!/usr/bin/perl w
use DBIx::Easy;
use strict;
sub myErrorHandler
{
my( $statement, $err, $msg ) = @_;
die"Oops, \"$statement\" failed ($err) $msg";
}
# :
my $conn = new DBIx::Easy("Pg", "bpsimple");
$conn>install_handler(\&myErrorHandler);
$conn>process("DROP TABLE number");
$conn>process("CREATE TABLE number ( value INTEGER, name
$conn>insert("number", name => "The Answer",
value =>
$conn>insert("number", name => "My Age",
value =>
$conn>insert("number", name => "Anniversary",
value =>
$conn>insert("number", name => "ClicketyClick", value =>

VARCHAR )");
42);
29);
29);
66);

my $numbers = $conn>makemap("number", "name", "value", "value = 29");


foreach my $name (keys(%$numbers)) {
print $name, " has value ", $$numbers{$name}, "\n";
}
$conn>update("number", "value = 42", name => "Zaphod");
$conn>process("DELETE FROM number WHERE value = 29");
$conn>disconnect;

. ,
DBIx::Easy process, insert, update makemap (),

doSQL.
, 
: 
( , , 
), 

512

16. PostgreSQL Perl

, .
, 
.
process, insert update , makemap 
. , 
where:
$conn>makemap($table, $keycol, $valuecol, $where)

:
SELECT $keycol, $valuecol FROM $table WHERE $where

, 
:
while(my ($key, $value) = $sth>fetchrow_array) {
$map{$key} = $value;
}

,
. 
, : (A, B) (A, C),
, . . , 
, .
:
, , 
. ,
, fetchrow_hashref DBI.
, 
, .

DBI XML
DBIx, 
(Matt Sergeant) DBIx::XML_RDB, 
(wellformed) XML DBI.
Perl, 
XML ( select_dbi.pl ):
select_xml.pl
#!/usr/bin/perl w
use DBI;
use DBIx::XML_RDB;
use strict;
# 
sub doSQL
{
my ($conn, $command) = @_;

513

Perl DBI
print $command, "\n";
my $sth = $conn>prepare($command);
my $nrows = $sth>execute;
print "status is ", $DBI::err, "\n" if $DBI::err;
print "#rows affected is ", $nrows, "\n";
print "error message: ", $DBI::errstr, "\n" if $DBI::err;
}
#
sub doSQLquery
{
my ($conn, $command) = @_;
print $command, "\n";
$conn>DoSql($command);
print $conn>GetData;
}
my $connXml = DBIx::XML_RDB>new("", "Pg") or die $DBI::errstr;
my $conn = $connXml>{dbh}
doSQL($conn, "DROP TABLE number");
doSQL($conn, "CREATE TABLE number ( value INTEGER, name VARCHAR )");
doSQL($conn, "INSERT INTO number values(42, 'The Answer')");
doSQL($conn, "INSERT INTO number values(29, 'My Age')");
doSQL($conn, "INSERT INTO number values(29, 'Anniversary')");
doSQL($conn, "INSERT INTO number values(66, 'ClicketyClick')");
doSQLquery($connXml, "SELECT * FROM number WHERE value = 29");
doSQL($conn, "UPDATE number SET name = 'Zaphod' WHERE value = 42");
doSQL($conn, "DELETE FROM number WHERE value = 29");

:
my $connXml = DBIx::XML_RDB>new("", "Pg") or die $DBI::errstr;
my $conn = $connXml>{dbh};

DBIx::XML_RDB>new XML_
RDB, DBI.
, , , 
,
(, , ,
XML_RDB ).
, , DoSql, XML 
, GetData, 
doSQLquery. :
<?xml version="1.0"?>
<DBI driver="dbname=book">
<RESULTSET statement="SELECT * FROM number WHERE value = 29">
<ROW>

514

16. PostgreSQL Perl

<value>29</value>
<name>My Age</name>
</ROW>
<ROW>
<value>29</value>
<name>Anniversary</name>
</ROW>
</RESULTSET>
</DBI>

DBIx::XML_RDB XML 
, 
XML : sql2xml.pl 
XML , xml2sql.pl
.
. 16.3:
16.3. sql2xml.pl

sn servername

driver dbi_driver

, DBI ( ODBC)

uid username

pwd password

()

table tablename

output outputfile

, XML

,
, sql2xls.pl,
Excel, ,  
.
,
Perl, ( ):
$ /usr/lib/perl5/site_perl/5.6.0/DBIx/sql2xml.pl
sn dbname=bpsimple driver Pg
table number otput xml.txt uid rick

, ,
, (
Perl).
xml.txt :
<?xml version="1.0"?>
<DBI driver="dbname=bpsimple">
<RESULTSET statement="SELECT * FROM number ORDER BY 1">
<ROW>
<value>42</value>

515

<name>Zaphod</name>
</ROW>
<ROW>
<value>66</value>
<name>ClicketyClick</name>
</ROW>
</RESULTSET>
</DBI>

, , 
, , 
DBIx::XML_RDB.
, xml2sql.pl,
(. 16.4):
16.4. xml2sql.pl

sn servername

driver dbi_driver

, DBI ( ODBC)

uid username

pwd password

()

table tablename

input inputfile

, XML

x

XML::Parser, 
CPAN.
, XMLDBMS (Ron Bour
ret), ,
.
http://www.rpbourret.com/xmldbms/.

Post
greSQL Perl, Perl 
C, .

Perl, , ,
PostgreSQL: ,
C, DBI.
DBI
.
, DBI DBIx.

17
PostgreSQL Java

,
Java, ,
JDBC. JDBC API
Java , 
PostgreSQL.
, :

JDBC

JDBC

JDBC PostgreSQL

JDBC

JDBC DDL
DML

PostgreSQL

JDBC
SQL

JDBC

API JDBC 3.0,


Java, 

PostgreSQL.

JDBC

517

JDBC
JDBC API, Java
,
,
. Java,
JDBC, 

, SQL,
ANSI. JDBC API JDBC API
API.
API :

java.sql 
Java 2 (Java 2 Platform, Standard Edition).
API 
XA, ,
. XA 

(twophase commit), 
.
javax.sql Java 2 Platform, Enterprise Edition.
JDBC.

JDBC
JDBC API , 
, : 
, SQL 
. 
. Ja
va ,
.
 
, , .
JDBC 

. JDBC.
JDBC JDBC
API, .

518

17. PostgreSQL Java

(. 17.1) , 
, Java,
JDBC :

Java

JDBC API

,
JDBC API

J2SE/J2EE

JDBC

. 17.1. , Java,

JDBC
.

1
JDBC 1 JDBC API
, ODBC. , 
, .
JDBC ODBC, ODBC
, 
. JDBCODBC, J2SE,
.

2
2 Java .
API 
.
JDBC ,
. (
1), .

3
3
. 
.

JDBC PostgreSQL

519


.
Java.

4
4 Java, 
JDBC JDBC
 .

.
.

JDBC PostgreSQL
PostgreSQL 
JDBC . , 
JDBC PostgreSQL . 
JDBC PostgreSQL :
1. Ant
http://jakarta.apache.org/builds/jakartaant/release/v1.3/bin/
http://jakarta.apache.org/builds/
jakartaant/release/v1.3/src/ .
2. PostgreSQL 
.
3. /src/in
terfaces/jdbc.
4. , build.xml.
5. Ant, ant ,
3.
6. , Ant
: Ant, 
Ant JAXP
XML. JAXP 
XML Xerces Apache,
http://xml.apache.org. Xerces, 
xerces.jar .
,
build.xml, . , postgresql.jar, 
JDBC, , postgresqlexamples.jar, . 
Ant Java, 
Linux, Cygwin.

520

17. PostgreSQL Java

: 
JDBC PostgreSQL http://jdbc.postgresql.org/
download/.

DriverManager Driver
java.sql java.sql.Driver,
JDBC, java.sql.DriverMana
ger,
, 
.
JDBC DriverManager 
,
, JDBC
, . 
, java.sql.DriverMana
ger java.sql.Driver JDBC API.

java.sql.DriverManager
DriverManager
JDBC. ,
java.sql.Driver, , JDBC
DriverManager. 
:

JDBC


,
DriverManager :
public static void registerDriver(Driver driver) throws SQLException

ja
va.sql.Driver, JDBC,
DriverManager. ja
va.sql.SQLException . DriverManager 

.
public static void deregisterDriver(Driver driver) throws SQLException

DriverManager Driver

521


DriverManager .
public static Enumeration getDrivers()


DriverManager.
public static Driver getDriver(String url) throws SQLException

DriverMana
ger , JDBC URL.
SQLException . JD
BC URL 
. , JDBC
,
JDBC URL, URL,
,
.
JDBC JDBC URL
. DriverManager , 
URL,
, . 
JDBC URL :
<protocol>:<subprotocol>:<resource>

jdbc, 
. URL PostgreSQL :
jdbc:postgres://<host>:<port>/<database>

host , postmaster, data


base , 
.


DriverManager, 
.
public static Connection getConnection(String url) throws SQLException

, JDBC
URL. java.sql.Connection 
. SQLException 
.
public static Connection getConnection(String url,String user,String
password) throws SQLException

522

17. PostgreSQL Java

, JDBC
URL, . 
SQLException .
public static Connection getConnection(String url,Properties info) throws
SQLException

, JDBC
URL. java.util.Properties 
. 
user, password.
SQLException .

JDBC
, Dri
verManager JDBC:
public static PrintWriter getLogWriter()

java.io.Print
Writer,
. SQLException 
:
public static void setLogWriter(PrintWriter writer)

PrintWriter, DriverManager 

:
public static void println(String message) throws SQLException


.


, Driver
Manager :
public static int getLoginTimeout()

( ),
DriverManager :
public static void setLogWriter(PrintWriter writer)1

, . setLogTimeout (int time


out). . . .

DriverManager Driver

523

( ), 
DriverManager .

java.sql.Driver
,
JDBC.
DriverMana
ger,

JDBC URL.
org.postgresql.Driver, 
PostgreSQL, ( 
interfaces/jdbc/org/postgresql 
PostgreSQL). :
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException e) {
e.printStackTrace();
}
}

, org.post
gresql.Driver, DriverManager. , 
JDBC 
, , DriverManager 
. 

forName() java.lang.Class, :
try {
Class.forName("org.postgresql.Driver");
}catch(ClassNotFoundException e) {
//
}

org.postgresql.Driver classpath, 
ClassNotFoundException. 
, postgres.jar, , 
.
(. 17.2)
JDBC, 
PostgreSQL bpsimple,
. meeraj
waheeda.

524

17. PostgreSQL Java

jdbcClient

java.sql.DriverManager

java.lang.Class

Class.for Name(org.postgresql.Driver)
prop

setProperty("user", "meeraj")
setProperty("password", "waheeda")
getConnection("jdbc:postgresquel:test",prop):java.sql.Connection

. 17.2. JDBC PostgreSQL


, , :
try {
// JDBC
Class.forName("org.postgresql.Driver");
// properties
Properties prop = new Properties();
prop.setProperty("user","meeraj");
prop.setProperty("password","waheeda");
// JDBC URL
String url = "jdbc:postgresql:test";
//
Connection con = DriverManager.getConnection(url,prop);
}catch(ClassNotFoundException e) {
//
}catch(SQLException e) {
//
}

, java.sql.Dri
ver:
public boolean acceptsURL(String url) throws SQLException

525

,
URL. 
, 
, JDBC URL.
SQLException.
public Connection connect(String url,Properties info) throws SQLException

URL,
, info. DriverManager 
, 
JDBC.
SQLException.
public int getMajorVersion()

.
public int getMinorVersion()

.
public boolean jdbcCompliant()

, 
JDBC. JDBC
JDBC API SQL92 Entry Level.
, SQL,
http://www.opengroup.org.
.

java.sql.Connection , 
. JDBC
. 

, . 
:

,
SQL 
JDBC .
.
(autocommit).
.
.

, 
java.sql.Connection.

526

17. PostgreSQL Java

Statement
java.sql.Connection
, SQL 
:
public Statement createStatement() throws SQLException

ja
va.sql.Statement.
SQL . java.sql.Statement 
SQL,
. 
SQLException:
public Statement createStatement(int resType, int resConcurrency) throws
SQLException

,
JDBC
.

. .
,

.
public PreparedStatement prepareStatement(String sql) throws SQLException

ja
va.sql.PreparedStatement. java.sql.PreparedStatement
SQL, 
. (prepared statements) 
SQL. 
SQLException. 
SQL, , 
? (IN)
.
public Statement prepareStatement (String sql,int resType, int
resConcurrency) throws SQLException

,
JDBC
:
public CallableStatement prepareCall(String sql) throws SQLException

java.sql.
CallableStatement. java.sql.CallableStatement 

527

,
IN OUT. 
SQLException. , 
, ? 
(IN), (OUT) 
.
public Statement prepareCall (String sql,int resType, int resConcurrency)
throws SQLException

,
JDBC
.



.
public void setAutoCommit(boolean autoCommit) throws SQLException

.
, (commit) SQL
, 
.
SQLException.
public boolean getAutoCommit() throws SQLException

(autocommit).

SQLException.
public void commit() throws SQLException

, 
. 
SQLException.
public void rollback() throws SQLException

, 
.
SQLException.
public int getTransactionIsolation() throws SQLException

.
, 9, , 
, 

528

17. PostgreSQL Java

.
SQLException.
public void getTransactionIsolation(int level) throws SQLException

.
SQLException.



:
public DatabaseMetaData getMetaData() throws SQLException

,
java.sql.DatabaseMetaData.
SQLException. java.sql.Data
baseMetaData 149
. Ja
vadocs JDBC API.

PostgreSQL
,
PostgreSQL. 
JDBC PostgreSQL
bpsimple, localhost. 

:

JDBC URL

, PostgreSQL

. PostgreSQL
MetaData.java:
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;

529

public class PostgreSQLMetaData {


public static void main(String args[]) throws Exception {
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql:bpsimple";
Connection con =
DriverManager.getConnection(url,"meeraj","password");
DatabaseMetaData dbmd = con.getMetaData();
System.out.print("Database Product Name : ");
System.out.println(dbmd.getDatabaseProductName());
System.out.print("Database Product Version : ");
System.out.println(dbmd.getDatabaseProductVersion());
System.out.print("Driver Major Version : ");
System.out.println(dbmd.getDriverMajorVersion());
System.out.print("Driver Minor Version : ");
System.out.println(dbmd.getDriverMinorVersion());
System.out.print("Driver Name : ");
System.out.println(dbmd.getDriverName());
System.out.print("Driver Version : ");
System.out.println(dbmd.getDriverVersion());
System.out.print("JDBC URL : ");
System.out.println(dbmd.getURL());
System.out.print("Supports Transactions : ");
System.out.println(dbmd.supportsTransactions());
System.out.print("Uses Local Files : ");
System.out.println(dbmd.usesLocalFiles());
con.close();
}
}

:
$ javac PostgreSQLMetaData.java

Java postgresql.jar 
(classpath):
$ java PostgreSQLMetaData

530

17. PostgreSQL Java

PostgreSQL
. JVM , post
gresql.jar :
Database Product Name : PostgreSQL
Database Product Version : 7.1
Driver Major Version : 7
Driver Minor Version : 1
Driver Name : PostgreSQL Native Driver
Driver Version : PostgreSQL 7.1 JDBC2
JDBC URL : jdbc:postgresql:test
Supports Transactions : true
Uses Local Files : false


,
SQL. 
Javadoc.

JDBC
JDBC ,
SQL SELECT 
JDBC. JDBC
. JDBC 
java.sql.ResultSet. JDBC 
.



Statement 
java.sql.ResultSet. , 
, , 

, 
.
.

TYPE_FORWARD_ONLY
.
. ,
N, 
N1 .

JDBC

531

TYPE_SCROLL_INSENSITIVE
ResultSet
, .

TYPE_SCROLL_SENSITIVE
ResultSet
, .


. 
 ( 
):
public int getType() throws SQLException



:

CONCUR_READ_ONLY
,
.

CONCUR _UPDATEABLE
,
.

ResultSet 
.

( ):
public int getConcurrency() throws SQLException


ResultSet 
,
. .



.
public boolean next() throws SQLException


, , 

532

17. PostgreSQL Java

.
SQLException.
public boolean first() throws SQLException


, 
, . 
, 
. 
SQLException.
public boolean last() throws SQLException


, 
, .
,
. 
SQLException.
public boolean absolute(int rows) throws SQLException


, 
. , 
rows , , rows
.
SQLException.
public boolean relative(int row) throws SQLException


, . 
, rows , ,
rows .
SQLException.
public boolean previous() throws SQLException


. ,
.
SQLException.


.
public boolean next() throws SQLException

JDBC

533


, , 
.
SQLException.
public boolean isBeforeFirst() throws SQLException

,
. 
SQLException.
public boolean isAfterLast() throws SQLException

,
. 
SQLException.
public boolean isFirst() throws SQLException

,
. 
SQLException.
public void isLast() throws SQLException

,
. 
SQLException.
public void beforeFirst() throws SQLException

,
. 
SQLException.
public boolean afterLast() throws SQLException

,
. 
SQLException.



. ,
, 
.
public int getFetchDirection() throws SQLException

534

17. PostgreSQL Java

.
SQLException. JDBC API 
:

FETCH_FORWARD

FETCH_REVERSE

FETCH_UNKNOWN
public void setFetchDirection(int direction) throws SQLException

. 
, FETCH_FORWARD
,
, SQLException.
public int getFetchSize() throws SQLException

.
SQLException.
public void setFetchDirection(int direction) throws SQLException

. 
SQLException.



.
. 
: getXXX(int col), XXX 
int, short, string, col , 
. 1.
. 
.
SQLException 
.
. 17.1, 

Javadoc:
17.1.

public boolean getBoolean(int i)



public boolean getBoolean(String col)
public int getInt(int i)
public inr getInt(String col)

535

JDBC

public String getString(int i)
public String getString(String col)


Java 
PostgreSQL JDBC.
Java PostgreSQL JDBC 
. 17.2. JDBC ja
va.sql.Types:
17.2. Java, JDBC PostgreSQL
Java

JDBC

PostgreSQL

java.lang.Boolean
java.lang.Byte
java.lang.Short
java.lang.Integer
java.lang.Long
java.lang.Float
java.lang.Double
java.lang.Character
java.lang.String
java.sql.Date
java.sql.Time
java.sql.Timestamp
java.lang.Object

TINYINT
TINYINT
SMALLINT
INTEGER
BIGINT
FLOAT
DOUBLE
CHAR
VARCHAR
DATE
TIME
TIMESTAMP
JAVA_OBJECT

INT2
INT2
INT2
INT4
INT8
FLOAT(7)
FLOAT8
CHAR(1)
TEXT
DATE
TIME
TIMESTAMP
OID



, 
CONCUR_UPDATEABLE. 
, .

.



, .
public void deleteRow() throws SQLException


. ,

536

17. PostgreSQL Java

INSERT. INSERT ,
.
SQLException.
public boolean rowDeleted() throws SQLException

, .
SQLException.


upda
teXXX() .

. . 17.3, 
Javadoc.
17.3.


public void updateBoolean(String col, boolean x) 

public void updateBoolean(int i, boolean x)

public void updateInt(int i, int x)


public void updateInt(String col, int x)


public void updateString(String col, String x) 

public void updateString(int i, String x)

public void updateRow() throws SQLException

,
, , 
updateXXX().
SQLException.
public void refreshRow() throws SQLException


. 
SQLException.
public void cancelRowUpdates() throws SQLException

, .

SQLException.
public boolean rowUpdated() throws SQLException

JDBC

537

, .
SQLException.


INSERT 
.
INSERT .
public boolean moveToInsertRow() throws SQLException

INSERT
:
public boolean moveToCurrentRow() throws SQLException


,
SQLException.
, 
updateXXX() .

:
public boolean insertRow() throws SQLException


INSERT, SQLException.


ja
va.sql.ResultSet:
public void close() throws SQLException

JDBC.
SQLException.
public ResultSetMetaData getMetaData() throws SQLException


java.sql.ResultSetMetaData. 

, :

538

17. PostgreSQL Java

Javadoc.
SQLException.

JDBC
JDBC API SQL
:

(statements) 
SQL . 
Statement java.sql.Statement. 
JDBC 
.


(prepared statements) 
SQL,
(IN). Prepa
redStatement java.sql.PreparedStatement.
java.sql.Statement.



(IN), 
(OUT) . , 
, java.sql.Callab
leStatement. java.sql.Prepa
redStatement.

JDBC PostgreSQL.

Statement
java.sql.Statement 
SQL .
JDBC 
. , JDBC, 
,
:

SQL

JDBC

SQL

539

java.sql.Statement 
SQL, SELECT, UPDATE, INSERT, DELETE CREATE.
public ResultSet executeQuery(String sql) throws SQLException


SELECT . SQLExcep
tion .
:
try {
Connection con = DriverManager.getConnection(url,prop);
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM MyTable");
}catch(SQLException e) {
//
}

,
MyTable.
public boolean execute(String sql) throws SQLException


SQL,
. , 
ResultSet.
SQLException.
public int executeUpdate(String sql) throws SQLException

SQL,
( 
, INSERT, UPDATE DELETE), DDL. 
, .
SQLException.


Statement 
SQL:
public ResultSet getResultSet() throws SQLException

SQL 
,

Statement. 

540

17. PostgreSQL Java

, Statement.
NULL,
,
UPDATE, INSERT DELETE.
SQLException.
public int getUpdateCount() throws SQLException


UPDATE, INSERT DELETE. 1 ,

, 
SELECT.
SQLException.
public boolean getMoreResults() throws SQLException


Statement. , 

. 
SQLException.
get ()
set () :

, 

SQL

SQL:
public void addBatch(String sql) throws SQLException

sql .
SQL UPDATE, INSERT DELETE. SQLException
.
public void clearBatch() throws SQLException

.
SQLException.
public int[] executeBatch() throws SQLException

541

JDBC

.
. 
SQLException.

escape

SQL

JDBC
JDBC.
JDBC, 
:

Statement

:
import
import
import
import

java.sql.Connection;
java.sql.Statement;
java.sql.ResultSet;
java.sql.DriverManager;

public class StatementClient {


public static void main(String args[]) throws Exception {

JDBC .
Statement, :
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql:bpfinal";
Connection con =
DriverManager.getConnection(url,"meeraj","password");
Statement stmt = con.createStatement();

542

17. PostgreSQL Java

SQL ( customer)
:
System.out.println("Inserting records");
stmt.addBatch("INSERT INTO customer(title,fname," +
"lname,addressline,town,zipcode,phone) values " +
"('Mr','Fred','Flintstone','31 Bramble Avenue'," +
"'London','NT2 1AQ','023 9876')");
stmt.addBatch("INSERT INTO customer(title,fname," +
"lname,addressline,town,zipcode,phone) values " +
"('Mr','Barney','Rubble','22 Ramsons Avenue'," +
"'London','PWD LS1','111 2313')");

:
stmt.executeBatch();
System.out.println("Records Inserted");
System.out.println();

customer 
:
System.out.println("Selecting records");
String selectSQL = "SELECT * FROM customer";
ResultSet res = stmt.executeQuery(selectSQL);
while(res.next()) {
for(int i = 1;i <= res.getMetaData().getColumnCount();i++) {
System.out.print(res.getString(i) + "\t");
}
System.out.println();
}
System.out.println();

customer
:
System.out.println("Deleting records");
String deleteSQL = "DELETE FROM customer";
System.out.println("Records deleted: " +
stmt.executeUpdate(deleteSQL));

,
:
res.close();
stmt.close();
con.close();
}
}

JDBC

543

StatementClient.java,
JVM (
postgresql.jar):
# java cp ./postgresql.jar StatementClient

customer , 
. JVM , 
classpath postgresql.jar:
Inserting records
Records Inserted
Selecting records
81 Mr Fred Flinstone 31 Bramble Avenue London NT2 1AQ 023 9876
82 Mr Barney Rubble 22 Ramsons Avenue London PWD LS1 111 2313
Deleting records
Records deleted: 2

PreparedStatements
(prepared statements)
SQL 
JDBC API java.sql.PreparedState
ment. java.sql.Statement.

JDBC.
, .
SQL , 
?. 
SQL
IN.
, java.sql.PreparedStatement, 
(
):

SQL

SQL

(IN) SQL,
SQL

SQL
java.sql.PreparedStatement 
SQL, SELECT, UPDATE, INSERT, DELETE
CREATE. , 
, SQL

544

17. PostgreSQL Java

. SQL , 
:
public ResultSet executeQuery() throws SQLException

,
, 
.
SQLException. :
try {
String sql = "SELECT * FROM customer WHERE fname = ? ";
Connection con = DriverManager.getConnection(url,prop);
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, "Fred");
ResultSet res = stmt.executeQuery();
}catch(SQLException e) {
//Handle exception
}
public boolean execute() throws SQLException

SQL, 
. 
, ResultSet.
SQLException.
public int executeUpdate() throws SQLException

SQL, 
, 
, , . .
,
SQL. 
SQLException.



setXXX() IN
SQL, ?. 
1. setXXX()
SQL. 
. 17.4, 
Javadoc:
17.4.

(IN) , 
public void
setBoolean(int index, boolean x) index, 
, x

545

JDBC

Public void setInt(int index,


int x)

(IN) , 
index, , 
x

public void setString(int index, (IN) , 


index ,
string x)
x


:
public void clearParameters() throws SQLException


,
, , INSERT 
:
import
import
import
import

java.sql.Connection;
java.sql.PreparedStatement;
java.sql.ResultSet;
java.sql.DriverManager;

public class PreparedStatementClient {


public static void main(String args[]) throws Exception {
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql:bpfinal";
Connection con =
DriverManager.getConnection(url,"meeraj","password");
PreparedStatement stmt;
String insertSQL = "INSERT INTO customer(title,fname," +
"lname,addressline,town,zipcode,phone) VALUES " +
"(?,?,?,?,?,?,?)";
stmt = con.prepareStatement(insertSQL);
System.out.println("Inserting records");
stmt.setString(1,"Mr");
stmt.setString(2,"Fred");
stmt.setString(3,"Flinstone");
stmt.setString(4,"31 Bramble Avenue");
stmt.setString(5,"London");
stmt.setString(6,"NT2 1AQ");
stmt.setString(7,"023 9876");
stmt.executeUpdate();

546

17. PostgreSQL Java

stmt.clearParameters();
stmt.setString(1,"Mr");
stmt.setString(2,"Barney");
stmt.setString(3,"Rubble");
stmt.setString(4,"22 Ramsons Avenue");
stmt.setString(5,"London");
stmt.setString(6,"PWD LS1");
stmt.setString(7,"111 2313");
stmt.executeUpdate();
System.out.println("Records Inserted");
System.out.println();
System.out.println("Selecting records");
String selectSQL = "SELECT * FROM customer";
stmt = con.prepareStatement(selectSQL);
ResultSet res = stmt.executeQuery();
while(res.next()) {
for(int i = 1;i <= res.getMetaData().getColumnCount();i++) {
System.out.print(res.getString(i) + "\t");
}
System.out.println();
}
System.out.println();
System.out.println("Deleting records");
String deleteSQL = "DELETE FROM customer";
stmt = con.prepareStatement(deleteSQL);
System.out.println("Records deleted: " +
stmt.executeUpdate());
res.close();
stmt.close();
con.close();
}
}


SQL
JDBC API 
:

BatchUpdateException
, 
SQL.

JDBC

547

, 
, .

DataTruncation
, 
.
:

SQLException
SQL. 

SQL , .

SQLWarning
SQLException,
.

JDBC


JDBC c
customer. ,
,
. 17.3:

. 17.3.

548

17. PostgreSQL Java

Java 
Swing.

, , JTable,
JPanel 
.



:

, TableModel, 
,

Customer
:

(private) , 
customer

(accessors) (mutators) 

CustomerTableModel
JTable, 
. ja
vax.swing.table.TableModel, javax.swing.table.Abstract
TableModel:

Customer, 
,

JDBC

549

,
. , JTable TableMo
del MVC

CustomerApp
, 
:

, 
(), , ,

, Customer,
,

CustomerPanel
:


CustomerPanel CustomerTableModel

javax.swing.JFrame


, customer 
CustomerTableModel

JTable, 

CustomerPanel

, ,
, , .


. 
, .

550

17. PostgreSQL Java

. 17.4:
JFrame
ActionListener

CustomerPanel
$title:JTextField=new JTextField(15)
$fname:JTextField=newJTextField(15)
$lname:JTextField=newJTextField(15)
$addressLine:JTextField(15)
$town:JTextField=newJTextField(15)
$zipCode:JTextField=new JTextField(15)
$phone:JTextField=newJTextField(15)
+getCustomer():Customer
+CustomerPanel()
+reset():void

CustomerApp
$model:CustomerTableModel
$table:JTable
$con:Connection
$customerPanel:CustomerPanel
+CustomerApp(arg:String )
+main(args:String ):void
+actionPerformed(e:ActionEvent):void
$getConnection(url:String,user:String,passwd:String):void
$refreshData():void
$addCustomer()void
$removeCustomer():void

Customer

AbstractTableModel
CustomerTableModel
$customerList:ArrayList=newArrayList()
+setCustomerList(customerList:ArrayList):void
+removeCustomer(index:int):void
+removeCustomer(index:int):Customer
+getRowCount():int
+getColumnCount():int
+getValueAT(row:int,co:int):Object
+getColumnName():String

1..

$Customerld:int=$1
$title:String=
$fname:String=
lname:String=
addressLine:String=
town:String=
zipCode:String=
$phone:String
+Customer()
+Customer(customer:int,title:String,fnar
+getCustomerld():int
+setCustomerld(customerld;int):void
+getTitle():Stringld
+setTitle(title:String):void
+setFname():String
+getLname():String
+getLname(lname:String):void
+getAddressLine():String
+setAddressLine(addressLine:String):void
+getTown():String
+setTown(town:String):void
+getZipCode:()String
+setZipCode(zipCode:String):void
+getPhone():String
+setPhone(phone:String):void
+getPhone():String
+setPhone(phone:String):void

. 17.4.


, 
, .


(. 17.5) 
, :

CustomerTableModel

(private) refreshData

Statement

Statement SQL 
customer

551

JDBC

con
Connection

customerApp
customerApp

rs
ResultSet

stmt
Statement

model
CustomerTableModel

getConnection

/refreshData():void
/createStatement():java.sqlStatement
/executeQuery(java.lang.String):java.sql.ResultSet

list
ArrayList

While(rs.next())

cust
Customer

Customer

. 17.5.


Customer,

, , 
JTable


, 
, . 17.6:
customerApp
CustomerApp

customerPanel
CustomerPanel

cust
Customer

con
Connection

stmt
PreparedStatement

addCustomer

getCustomer
SQL

refreshData

. 17.6.

, ,
CustomerPanel, Customer

552

17. PostgreSQL Java

(IN) SQL
, Customer

,
,


, (. 17.7), 
,
:
customerApp
CustomerApp

model
CustomerTableModel

cust
Customer

con
Connection

stmt
PreparedStatement

Customer
getCustomer
$

SQL


Customer

. 17.7.

Customer, , 

SQL 
, Customer

Custo
mer

Customer

:
public class Customer {
private int customerId = 1;
private String title = "";

JDBC

private String fname = "";


private String lname = "";
private String addressLine = "";
private String town = "";
private String zipCode = "";
private String phone = "";
public Customer() {
}

:
public Customer(int customerId,String title,
String fname,String lname,
String addressLine,String town,
String zipCode,String phone) {
this.customerId = customerId;
this.title = title;
this.fname = fname;
this.lname = lname;
this.addressLine = addressLine;
this.town = town;
this.zipCode = zipCode;
this.phone = phone;
}

:
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}

:
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}

:
public String getFname() {
return fname;

553

554

17. PostgreSQL Java

}
public void setFname(String fname) {
this.fname = fname;
}

:
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}

:
public String getAddressLine() {
return addressLine;
}
public void setAddressLine(String addressLine) {
this.addressLine = addressLine;
}

:
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}

:
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}

:
public String getPhone() {
return phone;
}

JDBC

555

public void setPhone(String phone) {


this.phone = phone;
}
}

CustomerTableModel
:
import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
public class CustomerTableModel extends AbstractTableModel {

:
private ArrayList customerList = new ArrayList();

. ,
(listeners) . ,
:
public void setCustomerList(ArrayList customerList) {
this.customerList = customerList;
fireTableDataChanged();
}

. , 
:
public void removeCustomer(int index) {
customerList.remove(index);
fireTableDataChanged();
}

:
public Customer getCustomer(int index) {
if(index >= customerList.size()) {
return null;
}
return (Customer)customerList.get(index);
}

,
:
public int getRowCount() {
return customerList.size();
}

556

17. PostgreSQL Java

,
:
public int getColumnCount() {
return 7;
}

,
:
public Object getValueAt(int row,int col) {
if(row >= customerList.size()) {
throw new IllegalArgumentException("Invalid row");
}
Customer customer = (Customer)customerList.get(row);
switch(col) {
case 0:
return customer.getTitle();
case 1:
return customer.getFname();
case 2:
return customer.getLname();
case 3:
return customer.getAddressLine();
case 4:
return customer.getTown();
case 5:
return customer.getZipCode();
case 6:
return customer.getPhone();
default:
throw new IllegalArgumentException("Invalid column");
}
}
}

CustomerPanel
:
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;

JDBC

557

import java.awt.GridLayout;
import java.awt.FlowLayout;
public class CustomerPanel extends JPanel {

:
private
private
private
private
private
private
private

JTextField
JTextField
JTextField
JTextField
JTextField
JTextField
JTextField

title = new JTextField(15);


fname = new JTextField(15);
lname = new JTextField(15);
addressLine = new JTextField(15);
town = new JTextField(15);
zipCode = new JTextField(15);
phone = new JTextField(15);

Customer , 
:
public Customer getCustomer() {
return new Customer(1,title.getText(),
fname.getText(),lname.getText(),
addressLine.getText(),town.getText(),
zipCode.getText(),phone.getText());
}

:
public CustomerPanel() {

(grid) 71:
setLayout(new GridLayout(7,1));

:
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout(FlowLayout.RIGHT));
panel1.add(new JLabel("Title:"));
panel1.add(title);
add(panel1);

:
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout(FlowLayout.RIGHT));
panel2.add(new JLabel("First Name:"));
panel2.add(fname);
add(panel2);

558

17. PostgreSQL Java

:
JPanel panel3 = new JPanel();
panel3.setLayout(new FlowLayout(FlowLayout.RIGHT));
panel3.add(new JLabel("Last Name:"));
panel3.add(lname);
add(panel3);

:
JPanel panel4 = new JPanel();
panel4.setLayout(new FlowLayout(FlowLayout.RIGHT));
panel4.add(new JLabel("Address:"));
panel4.add(addressLine);
add(panel4);

:
JPanel panel5 = new JPanel();
panel5.setLayout(new FlowLayout(FlowLayout.RIGHT));
panel5.add(new JLabel("Town:"));
panel5.add(town);
add(panel5);

:
JPanel panel6 = new JPanel();
panel6.setLayout(new FlowLayout(FlowLayout.RIGHT));
panel6.add(new JLabel("Zip Code:"));
panel6.add(zipCode);
add(panel6);

:
JPanel panel7 = new JPanel();
panel7.setLayout(new FlowLayout(FlowLayout.RIGHT));
panel7.add(new JLabel("Phone:"));
panel7.add(phone);
add(panel7);
setBorder(new TitledBorder(new EtchedBorder(),"Add Customer"));
}

:
public void reset() {
title.setText("");
fname.setText("");
lname.setText("");

JDBC

addressLine.setText("");
town.setText("");
zipCode.setText("");
phone.setText("");
}
}

CustomerApp
:
import
import
import
import
import

javax.swing.JTable;
javax.swing.JFrame;
javax.swing.JScrollPane;
javax.swing.JPanel;
javax.swing.JButton;

import java.awt.BorderLayout;
import
import
import
import

java.awt.event.ActionEvent;
java.awt.event.ActionListener;
java.awt.event.WindowEvent;
java.awt.event.WindowAdapter;

import java.util.ArrayList;
import
import
import
import
import
import

java.sql.DriverManager;
java.sql.Connection;
java.sql.Statement;
java.sql.PreparedStatement;
java.sql.ResultSet;
java.sql.SQLException;

public class CustomerApp extends JFrame implements ActionListener {

, :
private CustomerTableModel model;

, :
private JTable table;

PostgreSQL:
private Connection con;

559

560

17. PostgreSQL Java

, :
private CustomerPanel customerPanel;
public CustomerApp(String[] arg) throws Exception {
super("Customer Management System");

:
getConnection(arg[0],arg[1],arg[2]);

:
model = new CustomerTableModel();
refreshData();


. :
table = new JTable(model);
table.setAutoCreateColumnsFromModel(true);
JScrollPane pane = new JScrollPane(table);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(pane,BorderLayout.CENTER);

: , 
. 
(action listener)
:
JPanel buttonPanel = new JPanel();
JButton newButton = new JButton("Add Customer");
newButton.addActionListener(this);
buttonPanel.add(newButton);
JButton deleteButton = new JButton("Remove Customer");
deleteButton.addActionListener(this);
buttonPanel.add(deleteButton);
getContentPane().add(buttonPanel,BorderLayout.SOUTH);

CustomerPanel :
customerPanel = new CustomerPanel();
getContentPane().add(customerPanel,BorderLayout.WEST);

:
pack();
show();
setLocation(50,50);

JDBC

561

setSize(800,375);
setResizable(false);
validate();

,
:
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
try {
con.close();
}catch(SQLException ex) {
ex.printStackTrace();
}
System.exit(0);
}
});
}

main() JDBC URL,


:
public static void main(String args[]) throws Exception {
if(args == null || args.length != 3) {
System.out.print("Usage");
System.out.println("java EmployeeApp
<jdbcURL> <user> <passwd>");
return;
}
CustomerApp app = new CustomerApp(args);
}

:
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
try {

, 
:
if("Add Customer".equals(button.getText())) {
addCustomer();

562

17. PostgreSQL Java

,
:
}else if("Remove Customer".equals(button.getText())) {
removeCustomer();
}
}catch(SQLException ex) {
ex.printStackTrace();
}
validate();
}

:
private void getConnection(String url,String user,String passwd)
throws Exception {
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection(url,user,passwd);
}

:
private void refreshData() throws SQLException {
String sql = "select * from customer";
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery(sql);
ArrayList list = new ArrayList();
while(res.next()) {
Customer cust = new Customer(res.getInt(1),
res.getString(2),res.getString(3),
res.getString(4),res.getString(5),
res.getString(6),res.getString(7),
res.getString(8));
list.add(cust);
}
model.setCustomerList(list);
res.close();
stmt.close();
}

:
private void addCustomer() throws SQLException {
String sql = "insert into customer(" +

JDBC

"title,fname,lname, " +
"addressline,town,zipcode,phone)" +
"values(" +
"?,?,?,?,?,?,?)";

:
PreparedStatement stmt = con.prepareStatement(sql);
Customer cust = customerPanel.getCustomer();

SQL:
stmt.setString(1,cust.getTitle());
stmt.setString(2,cust.getFname());
stmt.setString(3,cust.getLname());
stmt.setString(4,cust.getAddressLine());
stmt.setString(5,cust.getTown());
stmt.setString(6,cust.getZipCode());
stmt.setString(7,cust.getPhone());

SQL:
stmt.executeUpdate();
stmt.close();

:
refreshData();
customerPanel.reset();
}

:
private void removeCustomer() throws SQLException {
String sql = "delete from customer where customer_id = ?";
PreparedStatement stmt = con.prepareStatement(sql);

:
int selectedRow = table.getSelectedRow();
Customer cust = model.getCustomer(selectedRow);
if(cust == null) {
return;
}

:
stmt.setInt(1,cust.getCustomerId());

563

564

17. PostgreSQL Java

SQL:
stmt.executeUpdate();
stmt.close();

:
model.removeCustomer(selectedRow);
}
}


, :
$ javac Customer*.java

Customer.class

CustomerTableModel.class

CustomerPanel.class

CustomerApp.class

:
$ java CustomerApp <JDBC URL> <User> <password>

(. 17.8) .
JVM, , postgresql.jar
.

. 17.8.

565

PostgreSQL
, Java, JDBC. :

JDBC

JDBC PostgreSQL

. JDBC


SQL

JDBC

JDBC API ,
3.0 JDBC API, 
, :

API API
J2EE, J2SE

18

, , , Postgre
SQL, ,
. 7.1 PostgreSQL
SQL92, ,
.
, PostgreSQL 
, , 
. ODBC PostgreSQL 
,
Microsoft Windows.
Postgre
SQL,
, ,
, .
PostgreSQL,
, , , , 
. , ,
PostgreSQL.


30 ,
. 
, 
, .

OLTP, OLAP

567


, 
1990 . 
,
, , 

, .
( XML
) ,
XML , XML. 
, , 
, XML
,
. XML
, 

. ,
.

OLTP, OLAP
: OLTP,
OLAP, Data Warehouses, Data Marts 
. 
, 
,
.

. , 
. ., 
,
.

(On Line Transaction Processing, OLTP).


, 
, .
: 
(Decision Support Systems, DSS),
(Data Warehouses), (Execu
tive Information Systems, EIS)
(Management Information System, MIS). 

(On Line Analytical Processing, OLAP).

OLTP.

568

18.


. 18.1:
18.1. OLAP OLTP
OLTP

OLAP

,  ,

, 




 
 ,

, , 
bpsimple, ,
. 
OLTP.

.

, ,
. , 
, 
.
, , ,
, , .

, . ,
,
.
, 
,
, , , 
. , ,
, 
,
.
,
, , 

569

OLTP, OLAP

. ,
,
.
OLAP. ( 
) ,
,
.
OLAP , 
(fact table)
(dimension table).
OLAP , , 
, : ,
, ,
(. 18.1):

Time
time_id
day of week
date
month
year

Item
item_id
cost price
sell price
description
Sales
item_id
cust_id
time_id
loc_id

Location
loc_id
zipcode
town
state

Customer
cust_id
name
title

. 18.1.

OLAP, ,
, 

.
, 
OLAP 
. 
(data cubes) (data marts).
,
OLAP.

570

18.



, . 18.2:
,

OLAP


OLTP
/
/

OLAP

. 18.2.

OLAP 
,
. ,
Oracle Microsoft,
,
OLAP.

, 
.


, , , 
:

PostgreSQL

http://www.postgresql.org

http://www.unixodbc.org

http://www.greatbridge.org

http://pgdemo.acucore.com

http://www.pgsql.com

http://www.redhat.com Red Hat Database

571

PHP

http://www.php.net
http://www.phpbuilder.com
http://www.phpwizard.net

Perl

http://www.perl.com
http://www.perl.org
http://www.cpan.org
http://activestate.com

Java JDBC

http://www.java.sun.com


DeZign for databases 
. 

SQL .
 (Entity Relationship Diagrams, ERD),
Windows. :

http://www.datanamic.com/dezign/index.html

Toolkit for Conceptual Modeling ( 


) 

, . ERD,
() . UNIX Linux:

http://wwwhome.cs.utwente.nl/~tcm/

Database Design Studio (DDS)


. Win
dows ODBC:

http://www.chillisource.com/dds/

SQL

PostgreSQL Introduction and Concepts (PostgreSQL


), Bruce Momjian ( ). AddisonWesley
(ISBN 0201703319).
PostgreSQL. HTML .

Database Design for Mere Mortals A HandsOn guide to Relational


Database Design ( 

572

18.


), Michael J. Hernandez ( . ). Addi
sonWesley (ISBN 0201694719). 
,
.
The Practical SQL Handbook Using Structured Query Language
( SQL
), Judith S. Bowman ( .
), Sandra L. Emerson ( . ), Marcy Darnovsky
( ). AddisonWesley (ISBN 0201447878).
SQL.
Mastering SQL ( SQL), Martin Gruber ( ).
Sybex (ISBN 0782125387).
SQL.
SQL for Smarties (SQL ), Joe Celko ( 
). Morgan Kaufmann Publishers (ISBN 1558605762). 
, SQL 
.
Instant SQL Programming (
SQL), Joe Celko ( ). Wrox Press (ISBN 1874416508).
SQL.

PHP

Professional PHP Programming ( PHP


), Jesus Castagnetto ( ), Chris Scollo
( ), Sascha Schumann ( ), Harish Rawat
( ), Deepak Veliath ( ). Wrox Press
(ISBN 1861002963). 
PHP, PHP 
.
Beginning PHP4 ( PHP4), Wankyu Choi ( ),
Allan Kent ( ), Ganesh Prasad ( ) Chris Ull
man ( ), Jon Blank ( ) Sean
Cazzell ( ). Wrox Press (ISBN 1861003730). 
PHP,
.

Perl

Beginning Perl ( Perl), Simon Cozens ( ).


Wrox Press (ISBN 1861003439). Perl Windows
UNIX, .
Perl Cookbook. Third Edition (Perl: . 
), Tom Christiansen ( ) Nathan Torkington
( ). OReilly and Associates (ISBN 0596000278).
Perl 5.6 .

573

Professional Perl Programming ( 


Perl), Peter Wainwright ( ), Aldo
Caplini ( ), Simon Cozens ( ), JJ Mere
loGuervos ( ), Aalhad Saraf ( )
Chris Nandor ( ). Wrox Press (ISBN 1861004494).
Perl 5.6, 
.

Java

Beginning Java 2 ( Java 2), Ivor Horton ( ).


Wrox Press (ISBN1861003668). ,
Java. Java, 
 ,
JDBC . .

Professional Java Data ( Java ),


Danny Ayers ( ), John Bell ( ), Carl Cal
vertBettis ( ), Thomas Bishop ( ),
Bjarki Holm ( ), Glenn E. Mitchell ( . ),
Kelly Lin Poon ( ), Sean Rhody ( ),
Mike Bogovich ( ), Matthew Ferris ( ),
Rick Grehan ( ), Tony Loton ( ), Nitin Nanda
( ) Mark Wilcox ( ). Wrox Press (ISBN
1861004109).
 Java.

PostgreSQL
,
, 
. SQL
,
.
Open Source , PostgreSQL,
, . 
, , ,

, 
.
PostgreSQL , . . 
, ,
, 

. .

A

PostgreSQL

,
, ,

.
, PostgreSQL 
. , ,
, 
, .
PostgreSQL ,
.
PostgreSQL 7.1 .
, 
, http://www.postgresql.org.
PostgreSQL FAQ 
.

, , Post
greSQL .
, 
.

. , ,
,
() , , 

. PostgreSQL

575

. , PostgreSQL
.
, , 
. , 
, 
ODBC, . 
, , ,
,
( ) .

:
PostgreSQL
. , 60 . 
60 
.
 PostgreSQL 

, . PostgreSQL
,

, .

: 16 64
PostgreSQL 8 . 
32 
( 2 ),
16 .
PostgreSQL 32 , 
64 .

, , 
PostgreSQL ,
1 .

, 
.

:
PostgreSQL
.

576

. PostgreSQL

COUNT 32 .
, , 
COUNT .

:
PostgreSQL , 
. ,

, .

: 1
PostgreSQL 
.
, 
.

: 250
,
PostgreSQL,
. (8 )
250 . 
1600, 
, , .
.

:
.
, .

B
PostgreSQL

PostgreSQL ,
.
, \dT psql.
, 
PostgreSQL .
SQL,
PostgreSQL,
, PostgreSQL.
PostgreSQL. 
SQL . , 
SQL.



SQL
PostgreSQL
.
boolean
bool
:
TRUE, 't', 'true', 'y', 'yes', '1'.
1 ,
NULL,
.

SQL99, 
.

578

B. PostgreSQL

SQL
smallint



PostgreSQL
,
int2
32768 +32767.

integer, int int4

,
2147483648 +2147483647.

int8

,
18 .

bit

(0 1).

bit varying varbit

. 
, : IN
SERT INTO VALUES(011101::varbit);.

SQL



PostgreSQL
c (precision).
numeric
, 
(precision,
.
scale)
9, (sca
le) 0. ,
8000 .
SQL
(decimal) (numeric) 
, 
, ,

. 
.

decimal
(precision,
scale)

float
float4, float8 
.
(precision)
7 , float4,
float8 15 
. float(15), 
SQL double precision.
real

float4

float(precision).

double
precision

float8

float(15).

money

decimal(9,2). 
, . . ,

PostgreSQL.

B. PostgreSQL

579

SQL



PostgreSQL

timestamp

datetime

timestamp
with
timezone
interval

4713 . . .
1 465 001 . . ., 1 .
1903 . . .
2037 . . ., 1 .

interval,
timespan


+/ 178 000 000 ,
1 .

date

4713 . . . 32 767 . . .
1 .

time

0 23:59:59.99, 
1 .

time with
timezone

time, .

SQL



PostgreSQL

char

char(n)

n ,
, . 

.

char
varying(n)

varchar(n)

, 
n ,
. 
.

text

PostgreSQL varchar,

.

580

B. PostgreSQL

SQL



PostgreSQL
point

x,y

line

(pt1, pt2)

lseg

(pt1, pt2)

box

path

polygon

,
,  
PostgreSQL

circle

SQL



PostgreSQL
SQL serial ,

.
PostgreSQL serial
, SQL 
. PostgreSQL in
teger 

.
serial
.

.

serial

oid

. PostgreSQL
oid 
, 
4 .

.

B. PostgreSQL

SQL

581



PostgreSQL
cidr

x.x.x.x/y, y
.
CIDR Classless InterDomain Routing (c
). 
IP : A, B C, 
8, 16 24 ,
16.7 , 65
254 . CIDR
, 
IP
.

inet

cidr, 
0.

macaddr

MAC XX:XX:XX:XX:XX:XX.

C
SQL PostgreSQL
SQL PostgreSQL
ABORT

ALTER GROUP
ALTER TABLE
ALTER USER
BEGIN
CHECKPOINT
CLOSE
CLUSTER
COMMENT
COMMIT
COPY
CREATE AGGREGATE
CREATE CONSTRAINT TRIGGER
CREATE DATABASE
CREATE FUNCTION
CREATE GROUP
CREATE INDEX
CREATE LANGUAGE
CREATE OPERATOR
CREATE RULE
CREATE SEQUENCE
CREATE TABLE
CREATE TABLE AS

CREATE TRIGGER
CREATE TYPE
CREATE USER
CREATE VIEW
DECLARE
DELETE
DROP AGGREGATE
DROP DATABASE
DROP FUNCTION
DROP GROUP
DROP INDEX
DROP LANGUAGE
DROP OPERATOR
DROP RULE
DROP SEQUENCE
DROP TABLE
DROP TRIGGER
DROP TYPE
DROP USER
DROP VIEW
END
EXPLAIN
FETCH

GRANT
INSERT
LISTEN
LOAD
LOCK
MOVE
NOTIFY
REINDEX
RESET
REVOKE
ROLLBACK
SELECT
SELECT INTO
SET
SET CONSTRAINTS
SET TRANSACTION
SHOW
TRUNCATE
UNLISTEN
UPDATE
VACUUM

C. SQL PostgreSQL

583

SQL PostgreSQL
ABORT
ABORT [ WORK | TRANSACTION ]

:
ALTER GROUP
ALTER GROUP name ADD USER username [, ... ]
ALTER GROUP name DROP USER username [, ... ]

: ,

ALTER TABLE
ALTER TABLE [ ONLY ] table [ * ]
ADD [ COLUMN ] column type
ALTER TABLE [ ONLY ] table [ * ]
ALTER [ COLUMN ] column { SET DEFAULT value | DROP DEFAULT }
ALTER TABLE table [ * ]
RENAME [ COLUMN ] column TO newcolumn
ALTER TABLE table
RENAME TO newtable
ALTER TABLE table
ADD table constraint definition
ALTER TABLE table
OWNER TO new owner

:
ALTER USER
ALTER
[
[
[

USER username
WITH PASSWORD 'password' ]
CREATEDB | NOCREATEDB ] [ CREATEUSER | NOCREATEUSER ]
VALID UNTIL 'abstime' ]

:
BEGIN
BEGIN [ WORK | TRANSACTION ]

:
CHECKPOINT
CHECKPOINT

584

. SQL PostgreSQL

CLOSE
CLOSE cursor

:
CLUSTER
CLUSTER indexname ON tablename

:
COMMENT
COMMENT ON
[
[ DATABASE | INDEX | RULE | SEQUENCE | TABLE | TYPE | VIEW ]
object_name |
COLUMN table_name.column_name|
AGGREGATE agg_name agg_type|
FUNCTION func_name (arg1, arg2, ...)|
OPERATOR op (leftoperand_type rightoperand_type) |
TRIGGER trigger_name ON table_name
] IS 'text'

:
COMMIT
COMMIT [ WORK | TRANSACTION ]

:
COPY
COPY [ BINARY ] table [ WITH OIDS ]
FROM { 'filename' | stdin }
[ [USING] DELIMITERS 'delimiter' ]
[ WITH NULL AS 'null string' ]
COPY [ BINARY ] table [ WITH OIDS ]
TO { 'filename' | stdout }
[ [USING] DELIMITERS 'delimiter' ]
[ WITH NULL AS 'null string' ]

:
CREATE AGGREGATE
CREATE AGGREGATE name ( BASETYPE = input_data_type,
SFUNC = sfunc, STYPE = state_type
[ , FINALFUNC = ffunc ]
[ , INITCOND = initial_condition ] )

C. SQL PostgreSQL

585

CREATE CONSTRAINT TRIGGER


CREATE CONSTRAINT TRIGGER name
AFTER events ON
relation constraint attributes
FOR EACH ROW EXECUTE PROCEDURE func '(' args ')'

: , 

CREATE DATABASE
CREATE DATABASE name
[ WITH [ LOCATION = 'dbpath' ]
[ TEMPLATE = template ]
[ ENCODING = encoding ] ]

:
CREATE FUNCTION
CREATE FUNCTION name ( [ ftype
RETURNS rtype
AS definition
LANGUAGE 'langname'
[ WITH ( attribute [, ...]
CREATE FUNCTION name ( [ ftype
RETURNS rtype
AS obj_file , link_symbol
LANGUAGE 'langname'
[ WITH ( attribute [, ...]

[, ...] ] )

) ]
[, ...] ] )

) ]

:
CREATE GROUP
CREATE GROUP name
[ WITH
[ SYSID gid ]
[ USER username [, ...] ] ]

:
CREATE INDEX
CREATE [ UNIQUE ] INDEX index_name ON table
[ USING acc_name ] ( column [ ops_name ] [, ...] )
CREATE [ UNIQUE ] INDEX index_name ON table
[ USING acc_name ] ( func_name( column [, ... ]) [ ops_name ] )

586

. SQL PostgreSQL

CREATE LANGUAGE
CREATE [ TRUSTED ] [ PROCEDURAL ] LANGUAGE 'langname'
HANDLER call_handler
LANCOMPILER 'comment'

:
CREATE OPERATOR
CREATE OPERATOR name ( PROCEDURE = func_name
[, LEFTARG = type1 ] [, RIGHTARG = type2 ]
[, COMMUTATOR = com_op ] [, NEGATOR = neg_op ]
[, RESTRICT = res_proc ] [, JOIN = join_proc ]
[, HASHES ] [, SORT1 = left_sort_op ] [, SORT2 =
right_sort_op ] )

:
CREATE RULE
CREATE RULE name AS ON event
TO object [ WHERE condition ]
DO [ INSTEAD ] action

action () :
NOTHING
|
query
|
( query ; query ... )
|
[ query ; query ... ]

:
CREATE SEQUENCE
CREATE SEQUENCE seqname [ INCREMENT increment ]
[ MINVALUE minvalue ] [ MAXVALUE maxvalue ]
[ START start ] [ CACHE cache ] [ CYCLE ]

:
CREATE TABLE
CREATE [ TEMPORARY | TEMP ] TABLE table_name (
{ column_name type [ column_constraint [ ... ] ]
| table_constraint } [, ... ]
) [ INHERITS ( inherited_table [, ... ] ) ]

C. SQL PostgreSQL

587

column_constraint ( ) :
[ CONSTRAINT constraint_name ]
{ NOT NULL | NULL | UNIQUE | PRIMARY KEY | DEFAULT value | CHECK (condition) |
REFERENCES table [ ( column ) ] [ MATCH FULL | MATCH PARTIAL ]
[ ON DELETE action ] [ ON UPDATE action ]
[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
}

table_constraint ( ) :
[ CONSTRAINT constraint_name ]
{ UNIQUE ( column_name [, ... ] ) |
PRIMARY KEY ( column_name [, ... ] ) |
CHECK ( condition ) |
FOREIGN KEY ( column_name [, ... ] ) REFERENCES table [ ( column [, ... ] ) ]
[ MATCH FULL | MATCH PARTIAL ] [ ON DELETE action ] [ ON UPDATE action ]
[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE
]
}

:
CREATE TABLE AS
CREATE TABLE table [ (column [, ...] ) ]
AS select_clause

:
CREATE TRIGGER
CREATE TRIGGER name { BEFORE | AFTER } { event [OR ...] }
ON table FOR EACH { ROW | STATEMENT }
EXECUTE PROCEDURE func ( arguments )

:
CREATE TYPE
CREATE TYPE typename ( INPUT = input_function, OUTPUT = output_function
, INTERNALLENGTH = { internallength | VARIABLE }
[ , EXTERNALLENGTH = { externallength | VARIABLE } ]
[ , DEFAULT = "default" ]
[ , ELEMENT = element ] [ , DELIMITER = delimiter ]
[ , SEND = send_function ] [ , RECEIVE = receive_function ]
[ , PASSEDBYVALUE ]
[ , ALIGNMENT = alignment ]
[ , STORAGE = storage ]
)

588

. SQL PostgreSQL

CREATE USER
CREATE USER username
[ WITH
[ SYSID uid ]
[ PASSWORD 'password' ] ]
[ CREATEDB | NOCREATEDB ] [ CREATEUSER | NOCREATEUSER ]
[ IN GROUP
groupname [, ...] ]
[ VALID UNTIL 'abstime' ]

:
CREATE VIEW
CREATE VIEW view AS SELECT query

:
DECLARE
DECLARE cursorname [ BINARY ] [ INSENSITIVE ] [ SCROLL ]
CURSOR FOR query
[ FOR { READ ONLY | UPDATE [ OF column [, ...] ] ]

:
DELETE
DELETE FROM [ ONLY ] table [ WHERE condition ]

:
DROP AGGREGATE
DROP AGGREGATE name type

:
DROP DATABASE
DROP DATABASE name

:
DROP FUNCTION
DROP FUNCTION name ( [ type [, ...] ] )

: C
DROP GROUP
DROP GROUP name

C. SQL PostgreSQL

589

DROP INDEX
DROP INDEX index_name [, ...]

:
DROP LANGUAGE
DROP [ PROCEDURAL ] LANGUAGE 'name'

:
DROP OPERATOR
DROP OPERATOR id ( lefttype | NONE , righttype | NONE )

:
DROP RULE
DROP RULE name [, ...]

:
DROP SEQUENCE
DROP SEQUENCE name [, ...]

:
DROP TABLE
DROP TABLE name [, ...]

:
DROP TRIGGER
DROP TRIGGER name ON table

:
DROP TYPE
DROP TYPE typename [, ...]

DROP USER
DROP USER name

590

. SQL PostgreSQL

DROP VIEW
DROP VIEW name [, ...]

:
END
END [ WORK | TRANSACTION ]

:
EXPLAIN
EXPLAIN [ VERBOSE ] query

:
FETCH
FETCH [ direction ] [ count ] { IN | FROM } cursor
FETCH [ FORWARD | BACKWARD | RELATIVE ] [ # | ALL | NEXT | PRIOR ]
{ IN | FROM } cursor

:
GRANT
GRANT privilege [, ...] ON object [, ...]
TO { PUBLIC | GROUP group | username }

: ,

INSERT
INSERT INTO table [ ( column [, ...] ) ]
{ DEFAULT VALUES | VALUES ( expression [, ...] ) | SELECT query }

:
LISTEN
LISTEN name

:
LOAD
LOAD 'filename'

:
LOCK
LOCK [ TABLE ] name
LOCK [ TABLE ] name IN [ ROW | ACCESS ]

C. SQL PostgreSQL

591

{ SHARE | EXCLUSIVE } MODE


LOCK [ TABLE ] name IN SHARE ROW EXCLUSIVE MODE

:
MOVE
MOVE [ direction ] [ count ]
{ IN | FROM } cursor

:
NOTIFY
NOTIFY name

: ,

REINDEX
REINDEX { TABLE | DATABASE | INDEX } name [ FORCE ]

: Postgr
eSQL
RESET
RESET variable

: 

REVOKE
REVOKE privilege [, ...]
ON object [, ...]
FROM { PUBLIC | GROUP groupname | username }

: , 

ROLLBACK
ROLLBACK [ WORK | TRANSACTION ]

:
SELECT
SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]
* | expression [ AS output_name ] [, ...]
[ INTO [ TEMPORARY | TEMP ] [ TABLE ] new_table ]
[ FROM from_item [, ...] ]
[ WHERE condition ]

592

. SQL PostgreSQL

[
[
[
[
[
[

GROUP BY expression [, ...] ]


HAVING condition [, ...] ]
{ UNION | INTERSECT | EXCEPT [ ALL ] } select ]
ORDER BY expression [ ASC | DESC | USING operator ] [, ...] ]
FOR UPDATE [ OF tablename [, ...] ] ]
LIMIT { count | ALL } [ { OFFSET | , } start ]]

from_item :
[ ONLY ] table_name [ * ]
[ [ AS ] alias [ ( column_alias_list ) ] ]
|
( select )
[ AS ] alias [ ( column_alias_list ) ]
|
from_item [ NATURAL ] join_type from_item
[ ON join_condition | USING ( join_column_list ) ]

:
SELECT INTO
SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]
* | expression [ AS output_name ] [, ...]
INTO [ TEMPORARY | TEMP ] [ TABLE ] new_table
[ FROM from_item [, ...] ]
[ WHERE condition ]
[ GROUP BY expression [, ...] ]
[ HAVING condition [, ...] ]
[ { UNION | INTERSECT | EXCEPT [ ALL ] } select ]
[ ORDER BY expression [ ASC | DESC | USING operator ] [, ...] ]
[ FOR UPDATE [ OF tablename [, ...] ] ]
[ LIMIT { count | ALL } [ { OFFSET | , } start ]]

from_item :
[ ONLY ] table_name [ * ]
[ [ AS ] alias [ ( column_alias_list ) ] ]
|
( select )
[ AS ] alias [ ( column_alias_list ) ]
|
from_item [ NATURAL ] join_type from_item
[ ON join_condition | USING ( join_column_list ) ]

:
SET
SET variable { TO | = } { value | 'value' | DEFAULT }
SET TIME ZONE { 'timezone' | LOCAL | DEFAULT }

C. SQL PostgreSQL

593

SET CONSTRAINTS
SET CONSTRAINTS { ALL | constraint [, ...] } { DEFERRED | IMMEDIATE }

:
SQL
SET TRANSACTION
SET TRANSACTION ISOLATION LEVEL { READ COMMITTED | SERIALIZABLE }
SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL { READ COMMITTED |
SERIALIZABLE }

: SQL
SHOW
SHOW name

:
TRUNCATE
TRUNCATE [ TABLE ] name

:
UNLISTEN
UNLISTEN { notifyname | * }

:
UPDATE
UPDATE [ ONLY ] table SET col = expression [, ...]
[ FROM fromlist ]
[ WHERE condition ]

:
VACUUM
VACUUM [ VERBOSE ] [ ANALYZE ] [ table ]
VACUUM [ VERBOSE ] ANALYZE [ table [ (column [, ...] ) ] ]

: PostgreSQL
psql.
, \h,
, \h <>.

D
psql
psql
:
psql [options] [dbname [username]]

:
a

A

(P format=una
ligned)

c <query>

(query) ( , 
)

d <dbname>

(dbname) 

e

E

f <filename>

filename 

F <string>

(string) ( |)
(P fieldsep=)

h <host>

(host)

H

HTML (P format=html)

l

n

readline

o <filename>

(filename) (
|pipe)

D. psql

595

p <port>

P var[=arg]

var arg (. \pset)

q

R <string>

(P recordsep=)

s

( )

S

( )

t

(P tuples_only)

T text

HTML (,
) (P tableattr=)

U <username>

v name=val

psql name value

V

W

( 
)

x

(P expanded)

X

(~/.psqlrc)

psql
a

\c[onnect]
[dbname|[user]]

\C <title>

\copy ...

SQL COPY

\copyright

Post
greSQL

\d <table>

( , , 
)

\d{t|i|s|v}

///

\d{p|S|l}

/ /

\da

\dd [object]

, ,

\df

\do

\dT

596

D. psql

()
\e [file]

[file] 

\echo <text>

text

\f <sep>

\h [cmd]

SQL, *

\i <file>

<file>

\l

\lo_export,
\lo_import,
\lo_list,
\lo_unlink

\o [file]

[file] |pipe

\p

\pset <opt>

<opt> = {format | border | expanded |


fieldsep | null | recordsep | tuples_only | title | tableattr
| pager}

\q

psql

\qecho <text>

text (. \o)

\r

()

\s [file]


[file]

\set <var> <value>


\t

\T <tags>

HTML

\unset <var>

()

\w <file>

<file>

\x

\z

\! [cmd]


psql.

, , 
, 
. E.1:
ORDERINFO
ORDERINFO ID
CUSTOMER_ID
DATE_PLACED
DATE_SHIPPED
SHIPPING

INTEGER
INTEGER
DATE
DATE
NUMERIC(7,2)

CUSTOMER_ID  CUSTOMER_ID

ORDERLINE
ORDERINFO ID
ITEM ID
QUANTITY

INTEGER
INTEGER
INTEGER

CUSTOMER
ORDERINGINFO_ID ORDERINGINFO_ID

ITEM_ID  ITEM_ID

CUSTOMER ID
TITLE
FNAME
LNAME
ADDRESSLINE
TOWN
ZIPCODE
PHONE

ITEM
ITEM ID
DESCRIPTION
COST_PRICE
SELL_PRICE

INTEGER
VARCHAR(64)
NUMERIC(7,2)
NUMERIC(7,2)

ITEM_ID  ITEM_ID

STOCK
ITEM ID
INTEGER
QUANTITY
INTEGER

ITEM_ID  ITEM_ID

BARCODE
BARCODE EAN
ITEM_ID

CHAR(13)
INTEGER

. E.1.

INTEGER
CHAR(4)
VARCHAR(32)
VARCHAR(32)
VARCHAR(64)
VARCHAR(32)
CHAR(10)
VARCHAR(16)

598

E.

, 
( 
).
. :

CUSTOMER

ORDERINFO

ITEM

ORDERLINE

STOCK

BARCODE

SQL, 
bpsimple, :
customer
create table customer
(
customer_id
title
fname
lname
addressline
town
zipcode
phone
CONSTRAINT
);

serial,
char(4),
varchar(32),
varchar(32) not null,
varchar(64),
varchar(32),
char(10) not null,
varchar(16),
customer_pk PRIMARY KEY(customer_id)

orderinfo
create table orderinfo
(
orderinfo_id
serial,
customer_id
integer not null,
date_placed
date not null,
date_shipped
date,
shipping
numeric(7,2) ,
CONSTRAINT
orderinfo_pk PRIMARY KEY(orderinfo_id),
CONSTRAINT orderinfo_customer_id_fk FOREIGN KEY(customer_id) REFERENCES
customer(customer_id)
);

item
create table item
(
item_id

serial,

599

E.

description
cost_price
sell_price
CONSTRAINT

varchar(64) not null,


numeric(7,2),
numeric(7,2),
item_pk PRIMARY KEY(item_id)

);

orderline
create table orderline
(
orderinfo_id
integer not null,
item_id
integer not null,
quantity
integer not null,
CONSTRAINT
orderline_pk PRIMARY KEY(orderinfo_id,
item_id),
CONSTRAINT orderline_orderinfo_id_fk FOREIGN KEY(orderinfo_id) REFERENCES
orderinfo(orderinfo_id),
CONSTRAINT orderline_item_id_fk FOREIGN KEY(item_id) REFERENCES
item(item_id)
);

stock
create table stock
(
item_id
integer not null,
quantity
integer not null,
CONSTRAINT
stock_pk PRIMARY KEY(item_id),
CONSTRAINT stock_item_id_fk FOREIGN KEY(item_id) REFERENCES item(item_id)
);

barcode
create table barcode
(
barcode_ean
char(13) not null,
item_id
integer not null,
CONSTRAINT
barcode_pk PRIMARY KEY(barcode_ean),
CONSTRAINT barcode_item_id_fk FOREIGN KEY(item_id) REFERENCES
item(item_id)
);


bpsimple .

F

PostgreSQL


. (,
) .
. 
PostgreSQL 
.
PostgreSQL 
,
, .
. 
,
PostgreSQL.

, 
, .
,
 .
PostgreSQL , 
BLOB,
. .

F. PostgreSQL

601


.
:


. ,
,
,
.
.
, .
,
. stock ,
:
CREATE TABLE image
(
item_id
INTEGER NOT NULL,
picture
VARCHAR(512),
CONSTRAINT image_pk PRIMARY KEY(item_id),
CONSTRAINT image_item_id_fk FOREIGN KEY(item_id) REFERENCES
item(item_id)
);

, 
.
image 
:
INSERT INTO image VALUES (3, 'http://server/images/rubik.jpg');
INSERT INTO image VALUES (9, '//server/images/coin.bmp');
INSERT INTO image VALUES (5, '/mnt/server/images/frame.png');

.
,
,
, 
, , .
, . .

.

602

F. PostgreSQL

.
:

URL 

UNC Windows

NFS UNIX


.
,  ,
, . 

(  ),
. ,
, . , NFS
,
.
PostgreSQL 7.1 1 .
,
. text 
. ,
.
 , 
.  ,
, MIME. 
,
, 
, 
ODBC. ,
,
.
, ,
PostgreSQL 
, 
BLOB.

BLOB
PostgreSQL oid 
, . ,


. , 
,
.

F. PostgreSQL

603

image
BLOB, oid:
CREATE TABLE image
(
item_id
INTEGER NOT NULL,
picture
OID,
CONSTRAINT image_pk PRIMARY KEY(item_id),
CONSTRAINT image_item_id_fk FOREIGN KEY(item_id) REFERENCES
item(item_id)
);


PostgreSQL , 
SQL BLOB , 
.
, SQL
lo_import :
INSERT INTO image VALUES (3, lo_import('/tmp/image.jpg'));

BLOB
. image oid, NULL, 
BLOB:
bpfinal=# SELECT * FROM image;
item_id | picture
+
3 | 163055
(1 row)
bpfinal=>

, , 
psql \lo_list \dl:
bpfinal=# \dl
Large objects
ID | Description
+
163055 |
(1 row)
bpfinal=>

lo_export,
, BLOB:
bpfinal=# SELECT lo_export(picture, '/tmp/image2.jpg')
bpfinal# FROM image WHERE item_id = 3;
lo_export

604

F. PostgreSQL
1
(1 row)
bpfinal=#

, lo_unlink:
bpfinal=# SELECT lo_unlink(picture) FROM image WHERE item_id = 3;
lo_unlink

1
(1 row)
bpfinal=# \dl
Large objects
ID | Description
+
(0 rows)
bpfinal=#


, . . :
bpfinal=# SELECT * FROM image;
item_id | picture
+
3 | 163055
(1 row)
bpfinal=#


, , , BLOB,
. ,
BLOB, NULL,
:
bpfinal=# UPDATE image SET picture=null WHERE item_id = 3;


psql. ,
lo_import lo_export ,
psql. , SQL,

.
.
, 
, , import ex
port, , 
, . psql :
INSERT INTO image VALUES (3, lo_import('image.jpg'));

F. PostgreSQL

605

, PostgreSQL 
, . , 
. ()
, .

.
, ,
, ,
, 
, postgres .

SQL, BEGIN COMMIT
END. psql SQL 
, ,
, , 
.


SQL lo_import lo_export 
, BLOB. psql
,
.
BLOB \lo_import,
. 
,
\lo_list:
bpfinal=# \lo_import image.jpg
lo_import 163059
bpfinal=# \lo_list
Large objects
ID | Description
+
163059 |
(1 row)
bpfinal=#

BLOB image, 
:
bpfinal=# UPDATE image SET picture=163059 WHERE item_id = 3;
UPDATE 1
bpfinal=# SELECT * FROM image;
item_id | picture
+
3 | 163059
(1 row)
bpfinal=#

606

F. PostgreSQL

BLOB \lo_export,
.  
:
bpfinal=# \lo_export 163059 image2.jpg
lo_export
bpfinal=#

, \lo_unlink:
bpfinal=# \lo_unlink 163059
lo_unlink 163059
bpfinal=#


, 
BLOB , 
PostgreSQL.
C libpq lo_import,
lo_export lo_unlink , :
Oid lo_import(PGconn *conn, const char *filename);
int lo_export(PGconn *conn, Oid lobjId, const char *filename);
int lo_unlink(PGconn *conn, Oid lobjId);

,
. ,
:
#include <stdlib.h>
#include <libpqfe.h>
int main()
{
PGconn *myconnection = PQconnectdb("");
PGresult *res;
Oid blob;
IF(PQstatus(myconnection) == CONNECTION_OK)
printf("connection made\n");
ELSE
printf("connection failed\n");
res = PQexec(myconnection, "begin");
PQclear(res);
blob = lo_import(myconnection, "image.jpg");
printf("import returned oid %d\n", blob);

F. PostgreSQL

607

res = PQexec(myconnection, "end");


PQclear(res);
PQfinish(myconnection);
return EXIT_SUCCESS;
}

,
.

libpq 13:
$ make import
cc I/usr/local/pgsql/include L/usr/local/pgsql/lib lpq import.c
import
$ PGDATABASE=bpfinal ./import
connection made
import returned oid 163066
$

o


. , Tcl Post
greSQL pg_lo_import, pg_lo_export pg_lo_unlink.
Post
greSQL ,
, , ,
:
int
int
int
int
int
Oid
int

lo_open(PGconn *conn, Oid lobjId, int mode);


lo_close(PGconn *conn, int fd);
lo_read(PGconn *conn, int fd, char *buf, size_t len);
lo_write(PGconn *conn, int fd, char *buf, size_t len);
lo_lseek(PGconn *conn, int fd, int offset, int whence);
lo_creat(PGconn *conn, int mode);
lo_tell(PGconn *conn, int fd);


.

\ ( )

, 177

, 176, 177
% ( )

LIKE, 120
' ' ( )

WHERE , 117
opy,
, 186

INSERT, 176
; ( )
SQL psql, 107
. ( )
, 474
? ( )
SQL, 490
,
543
@ ()

PHP, 485
_ ( )

LIKE, 120
| ( )

, 187
> , 294

A
absolute(),
java.sql.ResultSet, , 532

acceptsURL(),
java.sql.Driver, , 525
add_one, , 306
addBatch(),
java.sql.Statement, , 540
AFTER, , 328
afterLast(),
java.sql.ResultSet, , 533
ALTER GROUP,
, PostgreSQL, 347
ALTER TABLE,
, 252
, 252
,
253
, 252
, 252, 253
, 252
ALTER USER,
, PostgreSQL, 345
AND,
WHERE, , 117
ANSI, , 279, 284
Read committed, , 284
Read uncommitted, , 284
Repeatable read, , 284
Serializable, , 284
SET TRANSACTION ISOLATION
LEVEL, , 285
, 279
, 279
, 280
,
282
, 281
Ant, ,
Java, 519
AS,
, 109


ASCII
, 119
AutoCommit, , DBI, 504
available_drivers,
DBI, 508
AVG,
DISTINCT, , 211

, 211

B
BatchUpdateException, ,
546
BEFORE, , 328
beforeFirst(),
java.sql.ResultSet, , 533
BEGIN WORK, , 444
, 270
Berkeley Software Distribution
PostgreSQL, 38
BETWEEN,
WHERE, , 118
,

, 119

, 120
bin, , 336
BLOB, 602

, 606

C
c, , 
, 362
cancelRowUpdates(),
java.sql.ResultSet, , 536
CASE, , 318
CAST,

, 115, 126, 240
, 242
, 241

, 129
CHAR, , 66, 234
CHAR(N), , 234
, 234
clearBatch(),
java.sql.Statement, , 540

609
clearParameters(),
java.sql.PreparedStatement, 
, 545
close(),
java.sql.ResultSet, , 537
COMMIT WORK, , 444
commit(),
java.sql.Connection, , 527
Comprehensive Perl Archive Network
. CPAN, 494
configure,
PostgreSQL
PHP, 470
CONNECT,
database_url, , 446
connect(),
java.sql.Driver, , 525
copy, psql
USING DELIMITERS, , 186
INSERT,
185

, 187
COPY, SQL

, 186
COUNT(*), , 201
GROUP BY, , 201, 203
, 204
, 204
, 203
HAVING, , 201, 205
, 207
, 205, 206
, 207
, 203
, 203
, 202

COUNT(column name), 209
COUNT(*),

WHERE, 194
COUNT(column name),
, 208
NULL , 208

COUNT(*), 209
CPAN, , 494
DBIx::Easy, , 510
DBIx::XML_RDB, , 512

610
XML::Parser, , 515
DBI, 501
pgsql_perl5, 494
PostgreSQL
DBD, 501
CREATE DATABASE, , 350
ENCODING, , 350
LOCATION, , 350
TEMPLATE, , 350
CREATE FUNCTION,
, 305
CREATE GROUP,
, PostgreSQL, 345
CREATE INDEX, , 366
unique, , 366
, 367
CREATE TABLE, , 244, 412, 415
INHERITS, , 245
, 245
, 249
, 247, 250
, 245
, 244
, 244
CREATE TEMPORARY TABLE,
, 254
CREATE TRIGGER, , 327
CREATE TYPE, , 239
CREATE USER, , 345
CREATE VIEW, , 255

, 255
, 255

, 256
createdb, , 350
createlang, , 304
createStatement(),
java.sql.Connection, , 526
createuser, , 344
, 344
crypt,
, PostgreSQL, 358
CURRENT_DATE,
, 243
CURRENT_TIME,
, 243
CURRENT_TIMESTAMP,
, 243
CURRENT_USER,
, 243


currval(),

, 181, 188
Customer,
JDBC

, 548
customer,

JDBC, 541, 542
JDBC

, 547

, 388
, 392
CustomerApp,
JDBC

, 549, 559
CustomerPanel,
JDBC

, 549, 556
CustomerTableModel,
JDBC

, 548, 555
Cygwin, UNIX Windows, 91

D
\d,
, 175

, 146
\dt,
, 106
,
146
data, , 338
data_sources,
DBI, 508
eval, , 508
Database Design Studio,
, 571
Database Driver,
. DBD, 500
Database Interface
. DBI, , 500
DataTruncation, , 547


DATE, , 66, 123, 238
,
124
DATESTYLE,
SELECT
CAST, 127

, 125
DB::Connect(), , 489
DB::IsError(), , 488
DBD, 500
DBD::CSV, , 502
ODBC, 501
PostgreSQL DBD, 501
DBD::CSV, , 502
DBD::Pg,
. PostgreSQL, DBD, 501
DBI, , 500
AutoCommit, , 504
available_drivers, , 508
data_sources, , 508
eval, , 508
DBD, 500, 501
DBD::CSV, 502
do, , 506
doSQL(), , 504
fetchall_arrayref, , 505
fetchrow_array, , 505
fetchrow_arrayref, , 505
fetchrow_hashref, , 505
Name, , 509
PrintError, , 509
RaiseError, , 509
selectall_arrayref, , 506
selectrow_array, , 506
, 509
Post
greSQL Perl, 500
, 508
, 506
, 502
, 507
pgsql_perl5,
505, 510
, 501
CPAN, 501
DBIx::Easy, , 510
insert, , 512
makemap, , 512
process, , 512
update, , 512

611
, 510
, 511
DBIx::XML_RDB, , 512
doSQL(), , 513
doSQLquery, , 513
GetData, , 513
sql2xml.pl, , 514
, 514
XML , 512
xml2sql.pl, , 514
, 515
dbname, PQcon
nectdb(), 406
DDL (Data Definition Language),
, 30, 345
DEBUG, , 316
DEFERRABLE,
, 266
DELETE, , 196, 415
TRUNCATE,
, 197

PHP, 475

WHERE, 196
deleteRow(),
java.sql.ResultSet, , 535
deregisterDriver(),
java.sql.DriverManager, , 520
DeZign for databases,
, 571
die,
pgsql_perl5, , 500
DISCONNECT, , 446
DISTINCT,
AVG, , 211
SELECT, , 113

, 140
SUM, , 211
, 114
do,
DBI, , 506
doc, , 337
doSQL(),
DBI, , 504
DBIx::XML_RDB, , 513
pgsql_perl5, , 497
doSQLquery,
DBIx::XML_RDB, , 513
DROP DATABASE, , 350, 439

612
DROP GROUP,
, PostgreSQL, 347
DROP LANGUAGE, , 305
DROP TABLE, , 414

, 253
, 253
, 253
DROP TRIGGER, , 327
DROP USER, , 345
DROP VIEW, , 258
dropdb, , 350
, 350
dropuser, , 345

E
ecpg, SQL
, 443
, 455
, 456
printf(), , 458
strcpy(), , 458

, 452


, 442
, 466
, 459
SQL, 439
ecpg, 443
ECPGstatus(), , 447
PostgreSQL, 445
Entry SQL,
SQL92, 30
PostgreSQL
, 30
esqlc, , 450
, 450
WHENEVER, , 451
eval,
data_sources, , 508
EXCEPTION, , 316
ExecStatusType,
, 411
execute(),
java.sql.PreparedStatement,
, 544
java.sql.Statement, , 539
PEAR_Error, , 490


executeBatch(),
java.sql.Statement, , 541,
542
executeQuery(),
java.sql.PreparedStatement,
, 544
executeUpdate(),
java.sql.PreparedStatement,
, 544
java.sql.Statement, , 539
EXISTS,
WHERE,

, 221
EXPLAIN,
, PostgreSQL,
364

F
f, , 146
fetchall_arrayref,
DBI, , 505
fetchrow,
pgsql_perl5, , 498
fetchrow_array,
DBI, , 505
fetchrow_arrayref,
DBI, , 505
fetchrow_hashref,
DBI, , 505
first(),
java.sql.ResultSet, , 532,
533
FLOAT, , 236
FOR, , 320
,
, 325
forName(),
Class, , 523
Full SQL,
SQL92, 30

G
\g,
SQL psql, 107
getAutoCommit(),
java.sql.Connection, , 527
getBoolean(),
java.sql.ResultSet, , 534
getConcurrency(),
java.sql.ResultSet, , 531

613


getConnection(),
java.sql.DriverManager, , 521,
541
GetData,
DBIx::XML_RDB, , 513
getDriver(),
java.sql.DriverManager, , 521
getDrivers(),
java.sql.DriverManager, , 521
getFetchDirection(),
java.sql.ResultSet, , 534
getFetchSize(),
java.sql.ResultSet, , 534
getInt(),
java.sql.ResultSet, , 534
getLoginTimeout(),
java.sql.DriverManager, , 522
getLogWriter(),
java.sql.DriverManager, , 522
getMajorVersion(),
java.sql.Driver, , 525
getMetaData(),
java.sql.Connection, , 528
java.sql.ResultSet, , 537
getMinorVersion(),
java.sql.Driver, , 525
getMoreResults(),
java.sql.Statement, , 540
getResultSet(),
java.sql.Statement, , 540
getString(),
java.sql.ResultSet, , 535
getTransactionIsolation(),
java.sql.Connection, , 527
getType(),
java.sql.ResultSet, , 531
getUpdateCount(),
java.sql.Statement, , 540
GnoRPM,
, 72
GNUmake,
PostgreSQL
, 78
GRANT,
, PostgreSQL, 347
GROUP BY,
SELECT,
COUNT(*), 201, 203
GUI (
),
SQL, 55

JDBC
, 547

H
HAVING,
SELECT,
COUNT(*), 201, 205
host, PQconnectdb(),
406
hostaddr, PQcon
nectdb(), 406

I
\i, , psql
, 186
Ident,
, PostgreSQL, 358
IF . .THEN . . .ELSE, , 318
IN, ,
JDBC,
543
IN,
WHERE, , 118
include, , 337
Ingres,
Postgres, 35
INHERITS,
CREATE TABLE, , 245
initdb,
, 80, 339
INSERT INTO, , 412
, 251

, 189, 191
INSERT,
NULL, 183
, 185
, 
, 178

NULL, 184
, 175
, 175

, 179
,
, 176
SERIAL, 179
insert,
DBIx::Easy, , 512

614
insertRow(),
java.sql.ResultSet, , 537
INSTALL,
PostgreSQL
, 77
INSTSRV SRVANY,
PostgreSQL,
99
INTEGER, ,
, 392
Intermediate SQL,
SQL92, 30
INTERVAL, , 238
IPC Daemon,
PostgreSQL,
99
IS NOT NULL, , 123
IS NULL, , 122
isAfterLast(),
java.sql.ResultSet, , 533
isBeforeFirst(),
java.sql.ResultSet, , 533
ISO8601,
,
124, 127
isvalid,

, 192
item,

, 388

J
Java
PostgreSQL , 516
,
Java,
, 518
, 573
, JDBC
PostgreSQL, 535
Java JDBC, , 571
java.sql.CallableStatement, ,
538
java.sql.Connection, , 525
java.sql.Driver, , 523
, 525
, 520
java.sql.DriverManager,
, 520


JDBC, 520
JDBC, 522
, 521

, 522
java.sql.PreparedStatement, ,
543
java.sql.ResultSet, , 530
java.sql.Statement, , 538
, 541
javax.swing.JFrame,
JDBC

, 549
JDBC API, 516
API
java.sql, J2SE, 517
3.0,
, 565
JDBC, 517
PostgreSQL, 519

JDBC, 541
, 518

SQL, 546

3.0, 565
SQL
, 538
JDBC,
543
, 545

, 547

javax.sql, J2EE, 517
, 539
JDBC, 535
jdbcCompliant(),
java.sql.Driver, , 525
join,
pgsql_perl5, , 498
JPanel, JDBC

, 557
JTable,
JDBC 

, 548

615

K
Kpackage,
, 72
Kpsql, SQL, 159
Kerberos,
Krb4, , 358
Krb5, , 358

L
last(),
java.sql.ResultSet, , 532,
533
LEFT OUTER JOIN,
, 226
lib, , 337
libpq
, 431
, 432
, 431
,
420
SQL, 410
, 412
, 413
SQL, 415
, 404
, 405
, 424

, 424

, 410
SQL
sprintf, 452

, 436
, 408
C, 405, 407 409
, 405
, 404
, 431
libpq,
PQbinaryTuples(), , 430
PQcancelRequest(), , 435
PQclear(), , 412
PQcmdTuples(), , 415, 418
Pqconnectdb(), , 406
PQconnectPoll(), , 435
PQconnectStart(), , 435
PQconsumeInput(), , 434

PQerrorMessage(), , 409, 432


PQexec(), , 410, 412, 414, 427
PQfinish(), , 408
PQflush(), , 434
PQfnumber(), , 417
PQfsize(), , 417
PQgetisnull(), , 420, 459
PQgetlength(), , 418
PQgetResult(), , 432, 435
PQgetvalue(), , 418, 419
PQisBusy(), , 434
PQnfields(), , 417
PQntuples(), , 417, 427
PQprint(), , 420
PQreset(), , 410
PQresStatus(), , 412
PQresultErrorMessage(), ,
412, 418
PqresultErrorMessage(),
, 413
PQresultStatus(), , 410
PQsendQuery(), , 432
PQsetnonblocking(), , 432
PQsocket(), , 434
PQstatus(), , 407
libpq,
SQL , 438
pgsql_perl5,
494
PostgreSQL, 438
LIKE, ,
, 120
LIMIT, ,
,
SELECT, 121
Linux,
, 72

M
Makefile, ,
408
, 408, 442
makemap,
DBIx::Easy, , 512
man, , 338
MAX, , 210

VARCHAR, 209
, 210

MIN, 210

616
MIN, , 209

VARCHAR, 209
, 209
MAX, 210
MONEY, , 236
SQL, 236

,
392
moveToCurrentRow(),
java.sql.ResultSet, , 537
moveToInsertRow(),
java.sql.ResultSet, , 537
MS Access, 163
, 167
, 189

PostgreSQL, 163
, 168
Post
greSQL, 164
, 164
MS Excel
, 169
Post
greSQL, 169

N
name,
, 376
Name, , DBI, 509
next(),
java.sql.ResultSet, , 532
nextval(),

, 181
NOT NULL, , 184
NOTICE, , 316
now(), , 129
NULL, , 67
COUNT (column name),

NULL ,
208
INSERT, , 176, 183

, 184
PHP,
PostgreSQL, 482



, 387
, 67
,
NULL , 391
, 68, 122
NULLIF, , 318
NUMERIC, , 66, 236
, 236
, 236

O
ODBC (Open DataBase Connectivity), 150
DBD, 501

Access, 189
, 189

, 150

Windows, 48
Windows
, 150

, 150
Windows, 152
DLL, 152
OID, , 176
, 243, 244
OLAP, 567
, 568
OLTP, 567
, 569
OLTP, 567
, 568
OLAP, 567
ON DELETE,
, 266
ON UPDATE,
, 266
pen Source, 37
Berkeley Software Distribution,
, 38
OR,
WHERE, , 117
ORDER BY,

, 141

, 111
,
110


orderinfo,

, 388
orderline,

, 389

P
password, , ,
PostgreSQL, 358
PQconnectdb(),
406
PEAR ( 
PHP)
CPAN Perl, 486
PEAR_Error
, 489
, 488
Perl
DBI, 500
DBD, 500
DBIx::Easy, , 510
DBIx::XML_RDB, , 512
pgsql_perl5, , 492
XML::Parser, , 515
, 570
PostgreSQL , 491
Perl,
492

PostgreSQL Perl, 492, 500

PostgreSQL Perl, 492
, 572
, 497
, 497
Pg,
. pgsql_perl5, , 492
pg_client_encoding(), , 486
pg_close(), , 473
pg_cmdtuples(), , 478
pg_config,

, 361
pg_connect(), , 471
pg_ctl,
, 342
, 342
pg_dump,

, 352

617
, 354
pg_dumpall,

, 352
pg_errormessage(), , 477, 484
pg_exec(), , 476
pg_fetch_array(), , 480
pg_fetch_object(), , 481
pg_fetch_row(), , 480
pg_fieldisnull(), , 482
pg_fieldname(), , 482
pg_fieldnum(), , 482
pg_fieldprtlen(), , 483
pg_fieldsize(), , 483
pg_fieldtype(), , 483
pg_freeresult(), , 483
pg_group, , 346
pg_hba.conf,

, 358
pg_numfields(), , 477
pg_numrows(), , 477
pg_passwd,

, 360
pg_pconnect(), , 472
pg_restore,

, 352
, 355
pg_result(), , 478
pg_set_client_encoding(), , 486
pg_shadow, , 105, 349
pg_upgrade,
, 357
pg_user
, 349
, 343
PgAccess,
Tcl/Tk, , 160
Tcl/
Tk 8.0 , 160
Post
greSQL, 160
, 48
, 161
, 160
, 53
, 48
, 162

SQL, 163

618
, 162
Tcl, 163
pgadmin, , 154, 346
, 154
, PostgreSQL, 346
, 158

, 158
, 158
, PostgreSQL, 348
, 156
, 155
, 155
, 155
PGDATESTYLE,


, 126
PGRES_COMMAND_OK, ,
ExecStatusType
SQL, 411
PGRES_EMPTY_QUERY, ,
ExecStatusType
SQL, 411
PGRES_TUPLES_OK, , Exec
StatusType
SQL, 411
pgsql_perl5, , 492
die, , 500
doSQL(), , 497
fetchrow, , 498
join, , 498
, 494
Post
greSQL Perl, 493
DBI, 505, 510
libpq, 494
, 493
CPAN, 494
PHP,
, 570
PostgreSQL
PHP, 469
PostgreSQL , 468
, 572
, 484
API PostgreSQL, 470
php.ini,
, 485
PL/pgSQL,
, 303


CREATE FUNCTION,
, 305
, 309
ALIAS, , 309
, 308
, 311
, 309

, 309
, 308

, 310
port,
PQconnectdb(), , 406
postgres

, 80
, 105
,

, 79
, 79
, , 340
PostgreSQL, , 21, 34
Cygwin, Windows, 90, 91
Install For All, 
, 95
IPC, 96
, 99
, 91
, 92
DBD, 501
, 501
ODBC, 150, 155, 501
PgAccess,
, 48
psql,
, 47
psqlodbc, ODBC, 150

INSTSRV SRVANY,
, 99
IPC, 99
postmaster, 102
, 36
TCP/IP, 37
, 37
, 36

, 36
, 36


PostgreSQL
,
48
, 357
, 21
, 570
, 350
, 574
, 142
, 345
Windows, 48
, 153

, 153
Perl, 491
, 275
, 35
Ingres, 35
, 49
, 49
, 96
, 97, 360
, 97
postgres,
97
BSD, 38
, 285
, 90


, 78
SQL, 34
, 600
BLOB, 602

, 601
, 343
, 348
, 347
, 363
, 90
, 34
, 582
, 81
,
createuser, 84
,
create_tables.sql, 85
, 32

619
PostgreSQL
, 231, 577
OID, , 243

CAST, 240
, 232
, 243
, 239
, 233
, 239
Post
greSQL, 238

, 242
, 238
, 235
SQL,
438
ecpg, 439
,
drop_tables.sql, 86
, 81
, 340
, 76

, 336

Linux, 71, 72
RPM, , 72
YaST, , 72
, 72
, 
,
74
, 76
GNUmake, 78
initdb, ,
, 80
INSTALL, , 77
postmaster, , 79

, 82

, 80


, 81

, 76

620
PostgreSQL

()
, 87
pop_tablename.sql, 
, 87
barcode, 89
customer, 87
item, 88
orderinfo, 89
orderline, 89
stock, 89
, 76
GNU, 76
, , 71
SuSE, ,
, 74
, 74
, 73
, 285
, 289
postgresql.conf,

, 362
PostgreSQLMetaData, , 528
postmaster,

PostgreSQL, 102
, 79
, 340
, 340
postgres, 340

, 82
, 80
, 340
, 340
PGDATESTYLE
, 126
URL PostgreSQL, 521
PQbinaryTuples(), , 430
PQcancelRequest(), , 435
PQclear(),

, 412
PQcmdTuples(), , 415, 418
PQconnectdb(),
conninfo, , 406
PQconnectPoll(), , 435
PQconnectStart(), , 435
PQconsumeInput(), , 434


PQerrorMessage(), , 432
, 409
PQexec(), , 427
CREATE TABLE, , 412
SQL, 416

SQL, 414
FETCH, 424
SQL, 410
, 416
PQfinish(), , 408
NULL, 409
PQflush(), , 434
PQfnumber(), , 417
PQfsize(), , 417
PQgetisnull(), , 420, 459
PQgetlength(), , 418
PQgetResult(), , 432, 435
PQgetvalue(), , 418, 419
PQisBusy(), , 434
PQnfields(),

, 417
PQntuples(), , 427

, 417
PQprint(), , 420

PostgreSQL, 420
PqprintOpt, , 421
PQreset(), , 410
PQresStatus(), , 412
PQresultErrorMessage(), , 412,
413, 418
PQresultStatus(), , 410
, 411
PQsendQuery(), , 432
PQsetnonblocking(), , 432
PQsocket(), , 434
PQstatus(), , 407
NULL, 409
prepare(),
PEAR_Error, , 490
prepareCall(),
java.sql.Connection, , 527
prepareStatement(),
java.sql.Connection, , 526
previous(),
java.sql.ResultSet, , 532
PrintError, , DBI, 509
printf(), ,
ecpg, 458

621


println(),
java.sql.DriverManager, , 522
process,
DBIx::Easy, , 512
psql, , 175,
198
CREATE LANGUAGE, , 304
DROP LANGUAGE, , 305
, 595
, 148
, 143
, 143

, 143
, 146
\d, , 146
\dt, , 146
,
50
, 144
SQL, 144
, 144
, 145
, 594
, 147
, 47
, 143
, 145
.sql ,
146
f ,
146
, 146
,
145
, 104

, 179
, 106
psqlodbc, ODBC, 150

Q
QBE, , 30
QUEL, , 30

R
RAISE, , 316
RaiseError, , DBI, 509
Read committed,
ANSI, , 284

Post
greSQL, 285
Read uncommitted,
ANSI, , 284
PostgreSQL,
285
readline, , GNU

, 106
REAL, , 236
RedHat Package Manager
. RPM, , 72
REFERENCES,
, 260
, 260
, 261
refreshRow(),
java.sql.ResultSet, , 536
registerDriver(),
java.sql.DriverManager, , 520
reject,
, PostgreSQL, 358
relative(),
java.sql.ResultSet, , 532
RENAME, , 312
Repeatable read, , 285
ANSI, , 284
REVOKE,
, PostgreSQL, 347
RIGHT OUTER JOIN, , 227
rollback(),
java.sql.Connection, , 527
rowDeleted(),
java.sql.ResultSet, , 535
rowUpdated(),
java.sql.ResultSet, , 537

S
SELECT, , 32, 104
add_one, , 306
AS, , 109
AVG, , 211
CAST, ,
, 115
COUNT(*), , 201
GROUP BY, , 201, 203
HAVING, , 201, 205
COUNT(column name),
, 208
DISTINCT, , 113
INTO, , 314, 456

622
SELECT,
LIMIT, , 121
MAX, , 210
MIN, , 209
ORDER BY, , 110, 111

, 111
SUM, , 211
UNION, , 212
WHERE, , 116, 295
EXISTS,

, 221
, 228
, 215
, 223
, 219
, 227
,
, 300
, 107

, 108
, 416

, 136
,
, 293


, 224

, 200

, 130
selectall_arrayref,
DBI, 506
selectrow_array,
DBI, 506
SERIAL, , 65, 236

SERIAL, 181, 190
INSERT
SERIAL, 179
Serializable,
ANSI, , 284
PostgreSQL, 285
SET TRANSACTION ISOLATION LE
VEL,
ANSI, , 285
setAutoCommit(),
java.sql.Connection, , 527


setBoolean(),
java.sql.PreparedStatement,
, 544
setFetchDirection(),
java.sql.ResultSet, , 534
setInt(),
java.sql.PreparedStatement,
, 545
setLoginTimeout(),
java.sql.DriverManager, , 523
setLogWriter(),
java.sql.DriverManager, , 522
setString(),
java.sql.PreparedStatement,
, 545
setval(),

, 182, 188
share, , 338
SHOW,
DATESTYLE,
127
SMALLINT, , 236
Solaris, 71
sprintf(),
SQL,
474
SQL, , 30
ALTER GROUP, , 347
ALTER TABLE, , 252
ALTER USER, , 345
CREATE DATABASE, , 350
CREATE FUNCTION, , 303
CREATE GROUP, , 345
CREATE INDEX, , 366
CREATE TABLE, , 244
CREATE TEMPORARY TABLE,
, 254
CREATE USER, , 345
CREATE VIEW, , 255
DROP DATABASE, , 350
DROP GROUP, , 347
DROP TABLE, , 253
DROP USER, , 345
DROP VIEW, , 258
EXPLAIN, , 364
GRANT, , 347
REVOKE, , 347
SELECT, , 32
SET TRANSACTION ISOLATION
LEVEL, , 285

623


SQL,
UNION, , 212
VACUUM, , 363
, 201
, 223
libpq, 410
, 412
, 540
, 52
, 31
, 571
, 54
, 214
, 
JDBC, 543
, 31
, 222
,
302
, 270, 415
, 325
, 325
, 325
sql2xml.pl,
DBIx::XML_RDB, , 514
, 514
SQL89,

, 226
SQL92, , 30

, 226

, 226
sqlca,
, 449
SQL,
448
sqlca.sqlcode, , 448, 464
sqlca.sqlerrd, , 449, 464
sqlca.sqlerrm.sqlerrml, , 448
sqlca.sqlwarn, , 449
SQLException, , 547
SRVANY INSTSRV,
, 99
StarOffice Base,
, 55
StatementClient,

JDBC, 541, 543

strcpy(),
cpg, 458
su, , 105
SUM, , 211
DISTINCT, , 211

, 211

T
TEXT, , 234
SQL, 233
, 234
, 234
TIME, , 238
TIMESTAMP, , 123, 238

, 128
to_char, ,
, 302
Toolkit for Conceptual Modeling,

, 571
TRUNCATE,
DELETE,
197
, 198
trust,
, PostgreSQL, 358
TZ, , 128

U
UNION,
, 213
, 214
, 213
, 213
UPDATE, , 193, 415
FROM, ,
, 195
SET, ,
, 196

WHERE, 194
update,
DBIx::Easy, , 512
updateBoolean(),
java.sql.ResultSet, , 536
updateInt(),
java.sql.ResultSet, , 536

624

updateRow(),
java.sql.ResultSet, , 536
updateString(),
java.sql.ResultSet, , 536
URL JDBC DriverManager, 521
user,
PQconnectdb(), , 406
USING DELIMITERS,
, psql, 186

WHILE, , 320

VACUUM,
ANALYZE, , 364
, 363

, 363
, 364
, PostgreSQL,
363
, 363
vacuumdb, , 365
, 365
VARCHAR, , 66, 234

MIN MAX , 209
,
, 392
, 234

YaST,
PostgreSQL, 72

W
whenever,
, 451
, 451
WHERE,
EXISTS,

, 221
SELECT, , 116
, 118
, 228

, 132
, 215
, 120
, 219


DELETE, , 196
UPDATE, , 194
, 223

X
XML,
DBIx::XML_RDB, , 512
XML::Parser, , 515
xml2sql.pl,
DBIx::XML_RDB, , 514
, 515

,
PEAR, 486
,
, 321
, 201
AVG, 211
COUNT(*), 201
COUNT(column name), 208
MAX, 210
MIN, 209
SUM, 211
,
, 379

, 380
, 379, 393

. OLAP, 567

ALIAS, , 309
, 297
(ACID), , 273
, 273
, 274
, 274, 279, 284
, 273
, , 296

, 372, 373



, 387
, DBI, 509

625


, 376

, 396
, 377

crypt, , 358
Ident, , 358
Krb4, , 358
Krb5, , 358
password, , 358
reject, , 358
trust, , 358
, ,
358
,
358


, 175

, 185

, 175
, 574
, 23

, 24
, 25

, 24
UNIX, 23
, 395
, 192
, 405, 445
CONNECT, , 445
DISCONNECT, , 446
, 84
createuser, , 84
initdb, , 339
PostgreSQL
, 84
, 350
CREATE DATABASE, ,
350
createdb, , 350
DROP DATABASE, , 350
dropdb, , 350


, 597
, 25

, 27
, 27
, 26
, 196
, PostgreSQL, 357

, 358
pg_hba.conf, , 358
pg_passwd, , 360
,
, 358
, 319
,
, 394
, 430

, 286
, 290
, 286, 287, 288
, 291
, 289
, 290
, 289
, 309
, , 600
BLOB, 602
, 606
,
601

, PostgreSQL, 350
, 357
, 357
pg_upgrade, , 357

, 351
pg_dump, , 352
pg_dumpall, , 352
pg_restore, , 352
, 350
CREATE DATABASE, ,
350
createdb, , 350
DROP DATABASE, , 350
dropdb, , 350

626
, 216
,
PostgreSQL, 277
, 258
DEFERRABLE, , 266
ON DELETE, , 266

, 267
ON UPDATE, , 266

, 267
REFERENCES, , 260
, 260
, 261
, 265
, 264
, 263
, 389
, 260
, 223
LEFT OUTER JOIN, 226
RIGHT OUTER JOIN, 227
SELECT, , 227
WHERE, , 228
SQL89, 226
, 227, 228


, 224
,
226
SQL92, 226


, 374

,
, 373
, 254
CREATE TEMPORARY TABLE,
, 254
, 
, 537
SQL
ecpg, 441

, 454
, 440
, 463
, 460
, 447
sqlca, 448


SQL

, 452
, 439, 450
update.c, 441

ecpg
libpq, 441
, 442

psql, 442
SQL, 444
, 438

ecpg, 441
, 396
,

java.sql.ResultSet interface, 533
JDBC
PostgreSQL, 538
,
JDBC 3.0, 565
PostgreSQL
Perl, 492
DBI, 500
SELECT, 114

, 
, 487
,
, 379

. , , 381
, 142
Kpsql, 159
MS Access, 160
MS Excel, 169
PgAccess, 160
pgadmin, 154
psql, 143
, 173

PostgreSQL, 345
ALTER GROUP, , 347
CREATE GROUP, , 345
DROP GROUP, , 347
pg_group, , 346
pgadmin, , 346

627


java.sql.Statement, 540

JDBC, 542

, PostgreSQL, 350
, 50

, 200
SELECT , 200

, 242
, 459
, , 460
, , 123
,
, 392
,
, 397
, PHP, 471
, 473
, 471
, 324
FOR, 325
,
324

 , 274


WHERE, 
, 119


pqsl, 104

, PostgreSQL, 275


,
187
, 189
,
PHP, 472

, DBI , 506

PHP, 476
, 416

, 136
PHP, 473
PEAR,
489

PHP, 475

SQL, 490
,
543

, 181

, 181

, 188
,

INSERT, 175

, 186

, 185

, 27

, 399

, 400

ALTER TABLE, , 252
INSERT INTO, , 251

ANSI, , 279, 284
Read committed, , 284
Read uncommitted, , 284
Repeatable read, , 284
Serializable, , 284
 , 274
, 279
, 279
, 280
,
282

628

, 
, 378
, ,
377
,
, 388
, 391

CREATE INDEX, , 366


, 369

pg_fetch_array(), 480
,
369
, 369
, 367
, PostgreSQL,
366
,
387
, 369
, , 571

, PEAR, 488
, , 316
DEBUG, 316
EXCEPTION, 316
NOTICE, 316

JDBC API, 546



JDBC

, 552


PHP , 471
. , 176

, 176, 177
,

, 187

, 381

bin, 336
data, 338
doc, 337
include, 337
lib, 337
man, 338
share, 338
, 
, 106
/, , 59
, 60
,
61
, 61
, 62
, 571

JDBC

, 560, 561

psql, , 175
, ecpg, 443
, 309

JDBC
, 564

, 474
PostgreSQL, 360
, 362
c, ,
362
postgresql.conf, , 362
, 360
pg_config, , 361
, 381
, 386
, 28
, 423
BINARY, , 430

, 463
SQL, 463
,
424
, 424, 463

java.sql.ResultSet, 532

629

, 425
, 464



WHERE, 116

, 388

, 387
, 231
, 232
, 233
, 375
.
, 381

. , 379
,

, 358

, 243
CURRENT_DATE, 243
CURRENT_TIME, 243
CURRENT_TIMESTAMP, 243
CURRENT_USER, 243
, 243


pg_fetch_array(), 480

, 475
, 300


java.sql.Connection, 528

JDBC 3.0, 565
, 553
, 553
, 374
,
, 278
ANSI, , 279
, 286
, 289

INSERT, 178

AS,
109

,
132
, 279
, 486
, 280
, 566
, 285

. , 285
PostgreSQL
Perl, 492
pgsql_perl5, , 493
, 395

,
,
373


JDBC, 544

, 535, 536

. OLTP, 567


, 177

, 176, 177
,
JDBC

, 555, 561

, ,
379
 
PHP, 486

, 377
, 375

, 377

630

, 258, 260, 261


REFERENCES, , 260
, 245, 260
, 245, 249, 261
, 190
 
, 394
CREATE TABLE, , 245
, 246
, 249
, 247, 250
, 245


WHERE , 117
, ,
, 186

INSERT, 176
, 46
,
, 274
, 276
, 275

, 297
, 296
WHERE, 295
, 299
, 295

, 296

, 295
, 294, 298
, 299
, 295
, 298

, 371

, 117
, 374
, 65
SERIAL, , 65
,
, 66

orderline orderinfo, 384


, 398
, 389

, 381
SELECT
, 130, 134

, 372
, 61
, 54
, 381

, 381
, 398
, 136
, 139
, 381
, 383
, 
, 385
, 389, 390
, 393


, 386
, 447
DBIx::Easy, , 511
PHP, 484

PEAR, 488

, , 483
, 
JDBC, 530
, psql, 594
,
JDBC 3.0,
565
, 396
, 46
,
, 396

, 387
,
, 397

, 311

PGDATESTYLE, 126
TZ, 128

, , 452

RENAME, 312
,
312
CONSTANT, ,
312
NOT NULL, , 312

, 313
RECORD, , 313

ROWTYPE, 313
, 312

. , 486
, 392
JDBC , 518

DISTINCT,
112

, 382
, 24

, 24
, 543
JDBC, 538
, 526

PHP, 485
, 214
WHERE,
SELECT, 215
, 216
, 217
, 221
EXISTS,
WHERE, 221
, 221
, 217
, 216
, 219
, 217


LIKE, 120

, WHERE,
LIKE, 120

631


NULL, 122
PHP, 473

JDBC

, 557
, 

PHP, 482

PostgreSQL, 343
ALTER USER, , 345
CREATE USER, , 345
createuser, , 344
DROP USER, , 345
dropuser, , 345
pg_user, , 343
, 345
, 348
, 347

. 
, 358

, 373, 386, 395

, 371, 375
, 22
,
PHP, 472

, 387
, 282
, 283
, 254, 348
CREATE VIEW, , 255
DROP VIEW, , 258
pg_user, 349
, 258
, 255
, 254
, 256
PostgreSQL, 255
, 373

SQL 
PHP, 474

632

, , PHP,
484
, PostgreSQL, 347
GRANT, , 347
pgadmin, , 348
REVOKE, , 347
, 348
, psql

, 179

, 31
, 31

PERFORM, , 315
SELECT INTO, , 314
, SQL, 139
, 21
, 23
, 22
, 370
, 372
, 372
, 386
, 394
, 401

, 397

, 375
, 375
,
374
, 56
, 58

, 58
, 57

, 58
,
PostgreSQL, 363
EXPLAIN, , 364
VACUUM, , 363
, 487

, 397

, 374


, 374
, 475
vacuumdb, , 365
, 366
CREATE INDEX, ,
366

, JDBC

, 560
, 531


, 374
, 302
CREATE FUNCTION, , 303
PL/pgSQL, 303

, 304
,
, 303
, 303
, 303
, 304


LIKE, 120
,

, 400
, 109
, 135
, 223
, 219

, ,
362
c, , 362
postgresql.conf, , 362
, 362
, 362
, 
, 188

, 200
SELECT, , 200

633


, 201
, 223
, 214

, , 222
,
SQL,
, 104
, 117
, 119
SQL, 444
ECPGdebug(), , 444
, 239, 382
, 
, 106

java.sql.ResultSet, , 530
JDBC,
, 539
JDBC, ,
JDBC 3.0, 565
, 534

, 537

JDBC, 526
, 478

PHP, 482
, 535

java.sql.ResultSet, 531
, 483
PHP , 477
, 400
, , 40
/, 59
, 50
, 52
, 53

, 28
, 29
, 29
, 29

, 65
, 56
, 48

, 40, 44


, 56
, 47

, 44

, 46
, 46
, 45
,
45
, 28

, 222, 400
WHERE, , 223
, 223
,
, 375
, ,
360
pg_config, , 361
, 360, 361
, Perl, 497
, 
, , 281
, 219
WHERE,
SELECT, 219
, 219

, 221
, 220
, 220
,
 , 398

DBI , 507
,
SELECT, 130

, 273
, 26
, 27
, 27
, 26
,
Perl, 497
,
PHP , 485

634

INSERT, ,
, 176


WHERE, 117

, 392
, 233
CHAR, 234
CHAR(N), 234
TEXT, 234
VARCHAR, 234
, 235
, 234

, 132

. , 32
,

, 390

. , 475
,
JDBC, 547
, 273


CREATE DATABASE,
, 350
createdb, , 350

java.sql.Connection, ,
526

CREATE TABLE, , 244


PostgreSQL,
238


, 372
, 394
,

WHERE, 116
, 298
, 129
, 29

, 238



, 231
, 233
, 235
, 394

, 377

, 387

INSERT, 178


TRUNCATE, 198
, 289
,
SELECT, 116, 121
,
109
, 109

, 176,
177

, 299
PHP

SQL , 474

, 33

, 33
, 33
, 34
, 371, 375
, 370

JDBC

, 550
PHP, , 470

PostgreSQL 
, 85

PostgreSQL 
, 86

, 290
, 254

isvalid, , 192
,
190

, 189
SELECT
, 130



, 224
, 136
, 139
.
, 139

, 372
, , 394
, 381
, 377
, 377

, 256
, , 522

,
, 392

PortgreSQL, 392
, , 393
,
, 395
JDBC,
530
, 231, 577
OID, , 243

, 391
,
387
, PHP, 484

CAST, 115, 240
, 242
, 241
, 231
, 243

635

java JDBC Post
greSQL, 535
, 239
, 233
, CREATE TYPE,
, 239
, PostgreSQL, 238

, 242
, 238
DATE, 238
INTERVAL, 238
TIME, 238
TIMESTAMP, 238
, 235

SQL, psql, 107, 139
psql,
, 188
,
, 474

JDBC 3.0, 565
, 269
BEGIN WORK, , 270
, 273
, 286
, 286
, 286
, 286
, 289
, 278
, 274
, 277
psql, , 198
, 278
, 285
, 193

java.sql.Connection, 527
,
277
ecpg, 459
, 273
, 285
,

, 386
, 397

636
, 326, 328
AFTER BEFORE, 328
OPAQUE, , 328
, 399
, 329
, 331
, 333
, 394
, 327
CREATE TRIGGER, , 327
DROP TRIGGER, , 327
,
330

, 
, 535
, DROP TABLE, ,
253


, 475
, , 295
,
298
,
, 387

JDBC,
java.sql.DriverManager, , 520
JDBC,
java.sql.DriverManager, , 522
, 340
postgres, , 340
postmaster, , 340
, pg_ctl,
, 342
, pg_ctl,
, 342
, java.sql.DriverMana
ger, , 521
 ,
java.sql.DriverManager, , 522

, 316
, 316
RAISE, , 316
, 318
, 319



IF . .THEN . . .ELSE, , 318
NULLIF CASE, , 318
PostgreSQL ,
336
bin, , 336
data, , 338
doc, , 337
include, , 337
lib, , 337
man, , 338
share, , 338
, 339
initdb, , 339

, 388
, 382


, 389, 390
, 393
,
387
, 281, 282

DECLARE, , 310
PHP API PostgreSQL, 470
to_char, 302
libpq,
. libpq,
, 309

SELECT, 300
, 308
, 309
, 300
, 310
, 311

SQL, 302
, 302
CREATE FUNCTION,
, 303, 305
SELECT,
add_one, , 306
, 307
, 307

637

, 308
,
, 321
, 309
, 538
, 324
, 309
, 314
, 333
, 326
, 315



, 373
, 260
, 285

JDBC

PostgreSQL, 523
JDBC

, 550, 551
, 319
BEGIN ... END, , 319
FOR, , 320
NULLIF CASE, , 318
WHILE, 319, 320
, 319

, 128
, , 294
, 235
MONEY, 236
NUMERIC, 236
REAL, 236
SERIAL, 236
SMALLINT, 236
, 238
, 237


JDBC,
530


,
, 397

,
, 392


barcode, 388


,
176, 177

, 42

, 42
, 43
, 42
, 41


PostgreSQL , 289
, 289
, 289
, 290
, 289

. , 285

(DML), , 30, 345
(DDL), 30
, 30
, 29
QBE, 30
QUEL, 30
, 29

 
Books.Ru
ISBN 593286043X,
PostgreSQL.  Books.Ru
. 
, 
. 
, 
 ([email protected]),
.

Вам также может понравиться