appropriate.
-<!-- $PostgreSQL: pgsql/doc/src/sgml/advanced.sgml,v 1.53 2007/01/31 20:56:16 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/advanced.sgml,v 1.54 2007/02/01 00:28:16 momjian Exp $ -->
<chapter id="tutorial-advanced">
<title>Advanced Features</title>
is of particular interest to your application, but you do not want
to type the query each time you need it. You can create a
<firstterm>view</firstterm> over the query, which gives a name to
- the query that you can refer to like an ordinary table.
+ the query that you can refer to like an ordinary table:
<programlisting>
CREATE VIEW myview AS
customer accounts, as well as total deposit balances for branches.
Suppose that we want to record a payment of $100.00 from Alice's account
to Bob's account. Simplifying outrageously, the SQL commands for this
- might look like
+ might look like:
<programlisting>
UPDATE accounts SET balance = balance - 100.00
In <productname>PostgreSQL</>, a transaction is set up by surrounding
the SQL commands of the transaction with
<command>BEGIN</> and <command>COMMIT</> commands. So our banking
- transaction would actually look like
+ transaction would actually look like:
<programlisting>
BEGIN;
<para>
For example, the following query finds the names of all cities,
including state capitals, that are located at an altitude
- over 500 ft.:
+ over 500 feet:
<programlisting>
SELECT name, altitude
<para>
On the other hand, the following query finds
all the cities that are not state capitals and
- are situated at an altitude of 500 ft. or higher:
+ are situated at an altitude of 500 feet or higher:
<programlisting>
SELECT name, altitude
-<!-- $PostgreSQL: pgsql/doc/src/sgml/array.sgml,v 1.55 2007/01/31 20:56:16 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/array.sgml,v 1.56 2007/02/01 00:28:16 momjian Exp $ -->
<sect1 id="arrays">
<title>Arrays</title>
<literal>box</> uses a semicolon (<literal>;</>) but all the others
use comma (<literal>,</>). Each <replaceable>val</replaceable> is
either a constant of the array element type, or a subarray. An example
- of an array constant is
+ of an array constant is:
<programlisting>
'{{1,2,3},{4,5,6},{7,8,9}}'
</programlisting>
</para>
<para>
- Now we can show some <command>INSERT</command> statements.
+ Now we can show some <command>INSERT</command> statements:
<programlisting>
INSERT INTO sal_emp
for programs. Dimensions can also be retrieved with
<function>array_upper</function> and <function>array_lower</function>,
which return the upper and lower bound of a
- specified array dimension, respectively.
+ specified array dimension, respectively:
<programlisting>
SELECT array_upper(schedule, 1) FROM sal_emp WHERE name = 'Carol';
<para>
New array values can also be constructed by using the concatenation operator,
- <literal>||</literal>.
+ <literal>||</literal>:
<programlisting>
SELECT ARRAY[1,2] || ARRAY[3,4];
?column?
Remember that what you write in an SQL command will first be interpreted
as a string literal, and then as an array. This doubles the number of
backslashes you need. For example, to insert a <type>text</> array
- value containing a backslash and a double quote, you'd need to write
+ value containing a backslash and a double quote, you'd need to write:
<programlisting>
INSERT ... VALUES (E'{"\\\\","\\""}');
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/backup.sgml,v 2.96 2007/01/31 20:56:16 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/backup.sgml,v 2.97 2007/02/01 00:28:16 momjian Exp $ -->
<chapter id="backup">
<title>Backup and Restore</title>
<title>Use compressed dumps.</title>
<para>
You can use your favorite compression program, for example
- <application>gzip</application>.
+ <application>gzip</application>:
<programlisting>
pg_dump <replaceable class="parameter">dbname</replaceable> | gzip > <replaceable class="parameter">filename</replaceable>.gz
</programlisting>
- Reload with
+ Reload with:
<programlisting>
createdb <replaceable class="parameter">dbname</replaceable>
gunzip -c <replaceable class="parameter">filename</replaceable>.gz | psql <replaceable class="parameter">dbname</replaceable>
</programlisting>
- or
+ or:
<programlisting>
cat <replaceable class="parameter">filename</replaceable>.gz | gunzip | psql <replaceable class="parameter">dbname</replaceable>
pg_dump <replaceable class="parameter">dbname</replaceable> | split -b 1m - <replaceable class="parameter">filename</replaceable>
</programlisting>
- Reload with
+ Reload with:
<programlisting>
createdb <replaceable class="parameter">dbname</replaceable>
<xref linkend="creating-cluster"> it is explained where these files
are located, but you have probably found them already if you are
interested in this method. You can use whatever method you prefer
- for doing usual file system backups, for example
+ for doing usual file system backups, for example:
<programlisting>
tar -cf backup.tar /usr/local/pgsql/data
i.e., the cluster's data directory.)
Write <literal>%%</> if you need to embed an actual <literal>%</>
character in the command. The simplest useful command is something
- like
+ like:
<programlisting>
archive_command = 'cp -i %p /mnt/server/archivedir/%f </dev/null'
</programlisting>
this correctly on some platforms but not others. If the chosen command
does not itself handle this case correctly, you should add a command
to test for pre-existence of the archive file. For example, something
- like
+ like:
<programlisting>
archive_command = 'test ! -f .../%f && cp %p .../%f'
</programlisting>
</listitem>
<listitem>
<para>
- Connect to the database as a superuser, and issue the command
+ Connect to the database as a superuser, and issue the command:
<programlisting>
SELECT pg_start_backup('label');
</programlisting>
</listitem>
<listitem>
<para>
- Again connect to the database as a superuser, and issue the command
+ Again connect to the database as a superuser, and issue the command:
<programlisting>
SELECT pg_stop_backup();
</programlisting>
i.e., the cluster's data directory.)
Write <literal>%%</> if you need to embed an actual <literal>%</>
character in the command. The simplest useful command is
- something like
+ something like:
<programlisting>
restore_command = 'cp /mnt/server/archivedir/%f %p'
</programlisting>
<para>
The least downtime can be achieved by installing the new server in
a different directory and running both the old and the new servers
- in parallel, on different ports. Then you can use something like
+ in parallel, on different ports. Then you can use something like:
<programlisting>
pg_dumpall -p 5432 | psql -d postgres -p 6543
-<!-- $PostgreSQL: pgsql/doc/src/sgml/bki.sgml,v 1.20 2007/01/31 20:56:16 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/bki.sgml,v 1.21 2007/02/01 00:28:16 momjian Exp $ -->
<chapter id="bki">
<title><acronym>BKI</acronym> Backend Interface</title>
table <literal>test_table</literal> with OID 420, having two columns
<literal>cola</literal> and <literal>colb</literal> of type
<type>int4</type> and <type>text</type>, respectively, and insert
- two rows into the table.
+ two rows into the table:
<programlisting>
create test_table 420 (cola = int4, colb = text)
open test_table
-<!-- $PostgreSQL: pgsql/doc/src/sgml/config.sgml,v 1.107 2007/01/31 20:56:16 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/config.sgml,v 1.108 2007/02/01 00:28:16 momjian Exp $ -->
<chapter Id="runtime-config">
<title>Server Configuration</title>
In addition to parameter settings, the <filename>postgresql.conf</>
file can contain <firstterm>include directives</>, which specify
another file to read and process as if it were inserted into the
- configuration file at this point. Include directives simply look like
+ configuration file at this point. Include directives simply look like:
<programlisting>
include 'filename'
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/cvs.sgml,v 1.40 2007/01/31 20:56:16 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/cvs.sgml,v 1.41 2007/02/01 00:28:16 momjian Exp $ -->
<appendix id="cvs">
<appendixinfo>
<para>
Whenever you want to update to the latest <productname>CVS</productname> sources,
<command>cd</command> into
- the <filename>pgsql</filename> subdirectory, and issue
+ the <filename>pgsql</filename> subdirectory, and issue:
<programlisting>
cvs -z3 update -d -P
</programlisting>
<step>
<para>
You can save yourself some typing by making a file <filename>.cvsrc</filename>
- in your home directory that contains
+ in your home directory that contains:
<programlisting>
cvs -z3
This supplies the <option>-z3</option> option to all <command>cvs</> commands, and the
<option>-d</option> and <option>-P</option> options to <command>cvs update</>. Then you just have
- to say
+ to say:
<programlisting>
cvs update
</programlisting>
</para>
<para>
- After you've done the initial checkout on a branch
+ After you've done the initial checkout on a branch:
<programlisting>
cvs checkout -r REL6_4
</programlisting>
anything you do within that directory structure is restricted to that
- branch. If you apply a patch to that directory structure and do a
+ branch. If you apply a patch to that directory structure and do a:
<programlisting>
cvs commit
but had formerly kept it under a
<productname>PostgreSQL</productname> development tree in
<filename>/opt/postgres/cvs/</filename>. If you intend to keep your
- repository in <filename>/home/cvs/</filename>, then put
+ repository in <filename>/home/cvs/</filename>, then put:
<programlisting>
setenv CVSROOT /home/cvs
<para>
Verify that
<application>cvsup</application> is in your path; on most systems
- you can do this by typing
+ you can do this by typing:
<programlisting>
which cvsup
-<!-- $PostgreSQL: pgsql/doc/src/sgml/datatype.sgml,v 1.189 2007/01/31 20:56:16 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/datatype.sgml,v 1.190 2007/02/01 00:28:16 momjian Exp $ -->
<chapter id="datatype">
<title id="datatype-title">Data Types</title>
Both the maximum precision and the maximum scale of a
<type>numeric</type> column can be
configured. To declare a column of type <type>numeric</type> use
- the syntax
+ the syntax:
<programlisting>
NUMERIC(<replaceable>precision</replaceable>, <replaceable>scale</replaceable>)
</programlisting>
The precision must be positive, the scale zero or positive.
- Alternatively,
+ Alternatively:
<programlisting>
NUMERIC(<replaceable>precision</replaceable>)
</programlisting>
- selects a scale of 0. Specifying
+ selects a scale of 0. Specifying:
<programlisting>
NUMERIC
</programlisting>
a notational convenience for setting up unique identifier columns
(similar to the <literal>AUTO_INCREMENT</literal> property
supported by some other databases). In the current
- implementation, specifying
+ implementation, specifying:
<programlisting>
CREATE TABLE <replaceable class="parameter">tablename</replaceable> (
followed by an optional <literal>AD</literal> or <literal>BC</literal>.
(Alternatively, <literal>AD</literal>/<literal>BC</literal> can appear
before the time zone, but this is not the preferred ordering.)
- Thus
+ Thus:
<programlisting>
1999-01-08 04:05:06
</programlisting>
- and
+ and:
<programlisting>
1999-01-08 04:05:06 -8:00
</programlisting>
are valid values, which follow the <acronym>ISO</acronym> 8601
- standard. In addition, the wide-spread format
+ standard. In addition, the wide-spread format:
<programlisting>
January 8 04:05:06 1999 PST
</programlisting>
that units like <literal>century</literal> or
<literal>week</literal> are converted to years and days and
<literal>ago</literal> is converted to an appropriate sign. In
- ISO mode the output looks like
+ ISO mode the output looks like:
<programlisting>
<optional> <replaceable>quantity</> <replaceable>unit</> <optional> ... </> </> <optional> <replaceable>days</> </> <optional> <replaceable>hours</>:<replaceable>minutes</>:<replaceable>seconds</> </optional>
the raw numeric value that type <type>oid</> would use. The alias
types allow simplified lookup of OID values for objects. For example,
to examine the <structname>pg_attribute</> rows related to a table
- <literal>mytable</>, one could write
+ <literal>mytable</>, one could write:
<programlisting>
SELECT * FROM pg_attribute WHERE attrelid = 'mytable'::regclass;
</programlisting>
- rather than
+ rather than:
<programlisting>
SELECT * FROM pg_attribute
WHERE attrelid = (SELECT oid FROM pg_class WHERE relname = 'mytable');
]]></programlisting>
While this is the only way to convert character strings into XML
values according to the SQL standard, the PostgreSQL-specific
- syntaxes
+ syntaxes:
<programlisting><![CDATA[
xml '<foo>bar</foo>'
'<foo>bar</foo>'::xml
-<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.72 2007/01/31 20:56:16 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.73 2007/02/01 00:28:16 momjian Exp $ -->
<chapter id="ddl">
<title>Data Definition</title>
so that it gets set to the time of row insertion. Another common
example is generating a <quote>serial number</> for each row.
In <productname>PostgreSQL</productname> this is typically done by
- something like
+ something like:
<programlisting>
CREATE TABLE products (
product_no integer <emphasis>DEFAULT nextval('products_product_no_seq')</emphasis>,
<para>
A check constraint can also refer to several columns. Say you
store a regular price and a discounted price, and you want to
- ensure that the discounted price is lower than the regular price.
+ ensure that the discounted price is lower than the regular price:
<programlisting>
CREATE TABLE products (
product_no integer,
column it is attached to. (<productname>PostgreSQL</productname> doesn't
enforce that rule, but you should follow it if you want your table
definitions to work with other database systems.) The above example could
- also be written as
+ also be written as:
<programlisting>
CREATE TABLE products (
product_no integer,
CHECK (price > discounted_price)
);
</programlisting>
- or even
+ or even:
<programlisting>
CREATE TABLE products (
product_no integer,
only added to <productname>PostgreSQL</productname> to be
compatible with some other database systems.) Some users, however,
like it because it makes it easy to toggle the constraint in a
- script file. For example, you could start with
+ script file. For example, you could start with:
<programlisting>
CREATE TABLE products (
product_no integer NULL,
<para>
Unique constraints ensure that the data contained in a column or a
group of columns is unique with respect to all the rows in the
- table. The syntax is
+ table. The syntax is:
<programlisting>
CREATE TABLE products (
product_no integer <emphasis>UNIQUE</emphasis>,
price numeric
);
</programlisting>
- when written as a column constraint, and
+ when written as a column constraint, and:
<programlisting>
CREATE TABLE products (
product_no integer,
</para>
<para>
- You can also shorten the above command to
+ You can also shorten the above command to:
<programlisting>
CREATE TABLE orders (
order_id integer PRIMARY KEY,
many-to-many relationship example above: when someone wants to
remove a product that is still referenced by an order (via
<literal>order_items</literal>), we disallow it. If someone
- removes an order, the order items are removed as well.
+ removes an order, the order items are removed as well:
<programlisting>
CREATE TABLE products (
product_no integer PRIMARY KEY,
<para>
This works the same for all constraint types except not-null
- constraints. To drop a not null constraint use
+ constraints. To drop a not null constraint use:
<programlisting>
ALTER TABLE products ALTER COLUMN product_no DROP NOT NULL;
</programlisting>
</para>
<para>
- To remove any default value, use
+ To remove any default value, use:
<programlisting>
ALTER TABLE products ALTER COLUMN price DROP DEFAULT;
</programlisting>
To assign privileges, the <command>GRANT</command> command is
used. For example, if <literal>joe</literal> is an existing user, and
<literal>accounts</literal> is an existing table, the privilege to
- update the table can be granted with
+ update the table can be granted with:
<programlisting>
GRANT UPDATE ON accounts TO joe;
</programlisting>
</para>
<para>
- So to create a table in the new schema, use
+ So to create a table in the new schema, use:
<programlisting>
CREATE TABLE myschema.mytable (
...
<para>
To drop a schema if it's empty (all objects in it have been
- dropped), use
+ dropped), use:
<programlisting>
DROP SCHEMA myschema;
</programlisting>
- To drop a schema including all contained objects, use
+ To drop a schema including all contained objects, use:
<programlisting>
DROP SCHEMA myschema CASCADE;
</programlisting>
<programlisting>
CREATE TABLE products ( ... );
</programlisting>
- and
+ and:
<programlisting>
CREATE TABLE public.products ( ... );
</programlisting>
</para>
<para>
- To put our new schema in the path, we use
+ To put our new schema in the path, we use:
<programlisting>
SET search_path TO myschema,public;
</programlisting>
</para>
<para>
- We could also have written
+ We could also have written:
<programlisting>
SET search_path TO myschema;
</programlisting>
<synopsis>
<literal>OPERATOR(</><replaceable>schema</><literal>.</><replaceable>operator</><literal>)</>
</synopsis>
- This is needed to avoid syntactic ambiguity. An example is
+ This is needed to avoid syntactic ambiguity. An example is:
<programlisting>
SELECT 3 OPERATOR(pg_catalog.+) 4;
</programlisting>
The latter behavior is the default.
For example, the following query finds the names of all cities,
including state capitals, that are located at an altitude over
- 500ft:
+ 500 feet:
<programlisting>
SELECT name, altitude
<para>
On the other hand, the following query finds all the cities that
- are not state capitals and are situated at an altitude over 500ft:
+ are not state capitals and are situated at an altitude over 500 feet:
<programlisting>
SELECT name, altitude
If data will be added only to the latest partition, we can
set up a very simple rule to insert data. We must
redefine this each month so that it always points to the
- current partition.
+ current partition:
<programlisting>
CREATE OR REPLACE RULE measurement_current_partition AS
We might want to insert data and have the server automatically
locate the partition into which the row should be added. We
- could do this with a more complex set of rules as shown below.
+ could do this with a more complex set of rules as shown below:
<programlisting>
CREATE RULE measurement_insert_y2004m02 AS
<para>
Similarly we can add a new partition to handle new data. We can create an
empty partition in the partitioned table just as the original partitions
- were created above.
+ were created above:
<programlisting>
CREATE TABLE measurement_y2006m02 (
As an alternative, it is sometimes more convenient to create the
new table outside the partition structure, and make it a proper
partition later. This allows the data to be loaded, checked, and
- transformed prior to it appearing in the partitioned table.
+ transformed prior to it appearing in the partitioned table:
<programlisting>
CREATE TABLE measurement_y2006m02
<listitem>
<para>
Don't forget that you still need to run <command>ANALYZE</command>
- on each partition individually. A command like
+ on each partition individually. A command like:
<programlisting>
ANALYZE measurement;
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/dfunc.sgml,v 1.34 2006/09/16 00:30:12 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/dfunc.sgml,v 1.35 2007/02/01 00:28:16 momjian Exp $ -->
<sect2 id="dfunc">
<title id="dfunc-title">Compiling and Linking Dynamically-Loaded Functions</title>
The compiler flag of the system compiler to create
<acronym>PIC</acronym> is <option>+z</option>. When using
<application>GCC</application> it's <option>-fpic</option>. The
- linker flag for shared libraries is <option>-b</option>. So
+ linker flag for shared libraries is <option>-b</option>. So:
<programlisting>
cc +z -c foo.c
</programlisting>
- or
+ or:
<programlisting>
gcc -fpic -c foo.c
</programlisting>
- and then
+ and then:
<programlisting>
ld -b -o foo.sl foo.o
</programlisting>
<para>
<acronym>PIC</acronym> is the default, so the compilation command
is the usual one. <command>ld</command> with special options is
- used to do the linking:
+ used to do the linking.
<programlisting>
cc -c foo.c
ld -shared -expect_unresolved '*' -o foo.so foo.o
-<!-- $PostgreSQL: pgsql/doc/src/sgml/dml.sgml,v 1.15 2007/01/31 20:56:16 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/dml.sgml,v 1.16 2007/02/01 00:28:16 momjian Exp $ -->
<chapter id="dml">
<title>Data Manipulation</title>
<para>
If you don't have values for all the columns, you can omit some of
them. In that case, the columns will be filled with their default
- values. For example,
+ values. For example:
<programlisting>
INSERT INTO products (product_no, name) VALUES (1, 'Cheese');
INSERT INTO products VALUES (1, 'Cheese');
You use the <xref linkend="sql-delete" endterm="sql-delete-title">
command to remove rows; the syntax is very similar to the
<command>UPDATE</command> command. For instance, to remove all
- rows from the products table that have a price of 10, use
+ rows from the products table that have a price of 10, use:
<programlisting>
DELETE FROM products WHERE price = 10;
</programlisting>
</para>
<para>
- If you simply write
+ If you simply write:
<programlisting>
DELETE FROM products;
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/docguide.sgml,v 1.69 2007/01/31 20:56:17 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/docguide.sgml,v 1.70 2007/02/01 00:28:16 momjian Exp $ -->
<appendix id="docguide">
<title>Documentation</title>
To allow for easier handling in the final distribution, the files
comprising the HTML documentation can be stored in a tar archive that
is unpacked at installation time. To create the
- <acronym>HTML</acronym> documentation package, use the commands
+ <acronym>HTML</acronym> documentation package, use the commands:
<programlisting>
cd doc/src
gmake postgres.tar.gz
<sgmltag>refentry</sgmltag> pages to *roff output suitable for man
pages. The man pages are also distributed as a tar archive,
similar to the <acronym>HTML</acronym> version. To create the man
- page package, use the commands
+ page package, use the commands:
<programlisting>
cd doc/src
gmake man.tar.gz
-<!-- $PostgreSQL: pgsql/doc/src/sgml/ecpg.sgml,v 1.78 2007/01/31 20:56:17 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/ecpg.sgml,v 1.79 2007/02/01 00:28:16 momjian Exp $ -->
<chapter id="ecpg">
<title><application>ECPG</application> - Embedded <acronym>SQL</acronym> in C</title>
As already stated, programs written for the embedded
<acronym>SQL</acronym> interface are normal C programs with special
code inserted to perform database-related actions. This special
- code always has the form
+ code always has the form:
<programlisting>
EXEC SQL ...;
</programlisting>
<para>
The first option is to explicitly choose a connection for each SQL
- statement, for example
+ statement, for example:
<programlisting>
EXEC SQL AT <replaceable>connection-name</replaceable> SELECT ...;
</programlisting>
</para>
<para>
- This section starts with
+ This section starts with:
<programlisting>
EXEC SQL BEGIN DECLARE SECTION;
</programlisting>
- and ends with
+ and ends with:
<programlisting>
EXEC SQL END DECLARE SECTION;
</programlisting>
Between those lines, there must be normal C variable declarations,
- such as
+ such as:
<programlisting>
int x = 4;
char foo[16], bar[16];
<listitem>
<para>
One of the most common uses of an array declaration is probably the
- allocation of a char array as in
+ allocation of a char array as in:
<programlisting>
EXEC SQL BEGIN DECLARE SECTION;
char str[50];
typedef long serial_t;
EXEC SQL END DECLARE SECTION;
</programlisting>
- Note that you could also use
+ Note that you could also use:
<programlisting>
EXEC SQL TYPE serial_t IS long;
</programlisting>
<para>
The special type <type>VARCHAR</type>
is converted into a named <type>struct</> for every variable. A
- declaration like
+ declaration like:
<programlisting>
VARCHAR var[180];
</programlisting>
- is converted into
+ is converted into:
<programlisting>
struct varchar_var { int len; char arr[180]; } var;
</programlisting>
this mode is active, it tries to behave as if it were the <productname>Informix</productname>
precompiler for <productname>Informix</productname> E/SQL. Generally spoken this will allow you to use
the dollar sign instead of the <literal>EXEC SQL</> primitive to introduce
- embedded SQL commands.
+ embedded SQL commands.:
<programlisting>
$int j = 3;
$CONNECT TO :dbname;
<listitem>
<para>
This statement closes the current connection. In fact, this is a
- synonym for ecpg's <literal>DISCONNECT CURRENT</>.
+ synonym for ecpg's <literal>DISCONNECT CURRENT</>.:
<programlisting>
$CLOSE DATABASE; /* close the current connection */
EXEC SQL CLOSE DATABASE;
<para>
Here is an example that you might want to use in a simple program.
It prints a simple message when a warning occurs and aborts the
- program when an error happens.
+ program when an error happens:
<programlisting>
EXEC SQL WHENEVER SQLWARNING SQLPRINT;
EXEC SQL WHENEVER SQLERROR STOP;
<literal>EXEC SQL WHENEVER</literal> and the SQL statement causing
the condition, regardless of the flow of control in the C program.
So neither of the two following C program excerpts will have the
- desired effect.
+ desired effect:
<programlisting>
/*
* WRONG
</para>
<para>
- Note that this is <emphasis>not</emphasis> the same as
+ Note that this is <emphasis>not</emphasis> the same as:
<programlisting>
#include <<replaceable>filename</replaceable>.h>
</programlisting>
Embedded SQL programs are typically named with an extension
<filename>.pgc</filename>. If you have a program file called
<filename>prog1.pgc</filename>, you can preprocess it by simply
- calling
+ calling:
<programlisting>
ecpg prog1.pgc
</programlisting>
<para>
Note that not all SQL commands are treated in this way. For
- instance, an open cursor statement like
+ instance, an open cursor statement like:
<programlisting>
EXEC SQL OPEN <replaceable>cursor</replaceable>;
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/func.sgml,v 1.356 2007/01/31 20:56:17 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/func.sgml,v 1.357 2007/02/01 00:28:16 momjian Exp $ -->
<chapter id="functions">
<title>Functions and Operators</title>
in single quotes, so that it looks like a literal constant. To
achieve some compatibility with the handling of ordinary
<acronym>SQL</acronym> names, the string will be converted to lowercase
- unless it contains double quotes around the sequence name. Thus
+ unless it contains double quotes around the sequence name. Thus:
<programlisting>
nextval('foo') <lineannotation>operates on sequence <literal>foo</literal></>
nextval('FOO') <lineannotation>operates on sequence <literal>foo</literal></>
All these functions require object OIDs to identify the object to be
checked. If you want to test an object by name, it is convenient to use
the OID alias types (<type>regclass</>, <type>regtype</>,
- <type>regprocedure</>, or <type>regoperator</>), for example
+ <type>regprocedure</>, or <type>regoperator</>), for example:
<programlisting>
SELECT pg_type_is_visible('myschema.widget'::regtype);
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/indices.sgml,v 1.68 2007/01/31 20:56:17 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/indices.sgml,v 1.69 2007/02/01 00:28:17 momjian Exp $ -->
<chapter id="indexes">
<title id="indexes-title">Indexes</title>
content varchar
);
</programlisting>
- and the application requires a lot of queries of the form
+ and the application requires a lot of queries of the form:
<programlisting>
SELECT content FROM test1 WHERE id = <replaceable>constant</replaceable>;
</programlisting>
);
</programlisting>
(say, you keep your <filename class="directory">/dev</filename>
- directory in a database...) and you frequently make queries like
+ directory in a database...) and you frequently make queries like:
<programlisting>
SELECT name FROM test2 WHERE major = <replaceable>constant</replaceable> AND minor = <replaceable>constant</replaceable>;
</programlisting>
then it might be appropriate to define an index on the columns
<structfield>major</structfield> and
- <structfield>minor</structfield> together, e.g.,
+ <structfield>minor</structfield> together, e.g.:
<programlisting>
CREATE INDEX test2_mm_idx ON test2 (major, minor);
</programlisting>
</para>
<para>
- A possible query to use this index would be
+ A possible query to use this index would be:
<programlisting>
SELECT * FROM orders WHERE billed is not true AND order_nr < 10000;
</programlisting>
However, the index can also be used in queries that do not involve
- <structfield>order_nr</> at all, e.g.,
+ <structfield>order_nr</> at all, e.g.:
<programlisting>
SELECT * FROM orders WHERE billed is not true AND amount > 5000.00;
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/information_schema.sgml,v 1.30 2007/01/31 20:56:17 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/information_schema.sgml,v 1.31 2007/02/01 00:28:17 momjian Exp $ -->
<chapter id="information-schema">
<title>The Information Schema</title>
<literal>data_type</literal>. To obtain information on the element
type of the array, you can join the respective view with this view.
For example, to show the columns of a table with data types and
- array element types, if applicable, you could do
+ array element types, if applicable, you could do:
<programlisting>
SELECT c.column_name, c.data_type, e.data_type AS element_type
FROM information_schema.columns c LEFT JOIN information_schema.element_types e
-<!-- $PostgreSQL: pgsql/doc/src/sgml/installation.sgml,v 1.279 2007/01/31 20:56:17 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/installation.sgml,v 1.280 2007/02/01 00:28:17 momjian Exp $ -->
<chapter id="installation">
<title><![%standalone-include[<productname>PostgreSQL</>]]>
The method to set the shared library search path varies between
platforms, but the most widely usable method is to set the
environment variable <envar>LD_LIBRARY_PATH</> like so: In Bourne
- shells (<command>sh</>, <command>ksh</>, <command>bash</>, <command>zsh</>)
+ shells (<command>sh</>, <command>ksh</>, <command>bash</>, <command>zsh</>):
<programlisting>
LD_LIBRARY_PATH=/usr/local/pgsql/lib
export LD_LIBRARY_PATH
</programlisting>
- or in <command>csh</> or <command>tcsh</>
+ or in <command>csh</> or <command>tcsh</>:
<programlisting>
setenv LD_LIBRARY_PATH /usr/local/pgsql/lib
</programlisting>
</indexterm>
If you are on <systemitem class="osname">BSD/OS</>, <systemitem
class="osname">Linux</>, or <systemitem class="osname">SunOS 4</>
- and you have root access you can run
+ and you have root access you can run:
<programlisting>
/sbin/ldconfig /usr/local/pgsql/lib
</programlisting>
manual page of <command>ldconfig</> for more information. On
<systemitem class="osname">FreeBSD</>, <systemitem
class="osname">NetBSD</>, and <systemitem
- class="osname">OpenBSD</> the command is
+ class="osname">OpenBSD</> the command is:
<programlisting>
/sbin/ldconfig -m /usr/local/pgsql/lib
</programlisting>
To enable your system to find the <application>man</>
documentation, you need to add lines like the following to a
shell start-up file unless you installed into a location that is
- searched by default.
+ searched by default:
<programlisting>
MANPATH=/usr/local/pgsql/man:$MANPATH
export MANPATH
<para>
The previous step should have told you how to start up the
database server. Do so now. The command should look something
- like
+ like:
<programlisting>
/usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data
</programlisting>
This will start the server in the foreground. To put the server
- in the background use something like
+ in the background use something like:
<programlisting>
nohup /usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data \
</dev/null >>server.log 2>&1 </dev/null &
-<!-- $PostgreSQL: pgsql/doc/src/sgml/libpq.sgml,v 1.223 2007/01/31 20:56:17 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/libpq.sgml,v 1.224 2007/02/01 00:28:17 momjian Exp $ -->
<chapter id="libpq">
<title><application>libpq</application> - C Library</title>
avoid doing so even in cases where the server by itself cannot determine the
type of the parameter, or chooses a different type than you want. In the
SQL command text, attach an explicit cast to the parameter symbol to show what
-data type you will send. For example,
+data type you will send. For example:
<programlisting>
select * from mytable where x = $1::bigint;
</programlisting>
<para>
The given name is treated like an identifier in an SQL command,
that is, it is downcased unless double-quoted. For example,
- given a query result generated from the SQL command
+ given a query result generated from the SQL command:
<programlisting>
select 1 as FOO, 2 as "BAR";
</programlisting>
</para>
<para>
-The default notice processor is simply
+The default notice processor is simply:
<programlisting>
static void
defaultNoticeProcessor(void *arg, const char *message)
-<!-- $PostgreSQL: pgsql/doc/src/sgml/maintenance.sgml,v 1.68 2007/01/31 20:56:17 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/maintenance.sgml,v 1.69 2007/02/01 00:28:17 momjian Exp $ -->
<chapter id="maintenance">
<title>Routine Database Maintenance Tasks</title>
appearing in that database — it is just the minimum of the
per-table <structfield>relfrozenxid</> values within the database.
A convenient way to
- examine this information is to execute queries such as
+ examine this information is to execute queries such as:
<programlisting>
SELECT relname, age(relfrozenxid) FROM pg_class WHERE relkind = 'r';
collector; it is a semi-accurate count updated by each
<command>UPDATE</command> and <command>DELETE</command> operation. (It
is only semi-accurate because some information might be lost under heavy
- load.) For analyze, a similar condition is used: the threshold, defined as
+ load.) For analyze, a similar condition is used: the threshold, defined as:
<programlisting>
analyze threshold = analyze base threshold + analyze scale factor * number of tuples
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/manage-ag.sgml,v 2.52 2007/01/31 20:56:17 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/manage-ag.sgml,v 2.53 2007/02/01 00:28:17 momjian Exp $ -->
<chapter id="managing-databases">
<title>Managing Databases</title>
<programlisting>
CREATE DATABASE <replaceable>dbname</> OWNER <replaceable>rolename</>;
</programlisting>
- from the SQL environment, or
+ from the SQL environment, or:
<programlisting>
createdb -O <replaceable>rolename</> <replaceable>dbname</>
</programlisting>
</para>
<para>
- To create a database by copying <literal>template0</literal>, use
+ To create a database by copying <literal>template0</literal>, use:
<programlisting>
CREATE DATABASE <replaceable>dbname</> TEMPLATE template0;
</programlisting>
- from the SQL environment, or
+ from the SQL environment, or:
<programlisting>
createdb -T template0 <replaceable>dbname</>
</programlisting>
ordinarily have to either disable it for all databases or make sure
that every connecting client is careful to issue <literal>SET geqo
TO off;</literal>. To make this setting the default within a particular
- database, you can execute the command
+ database, you can execute the command:
<programlisting>
ALTER DATABASE mydb SET geqo TO off;
</programlisting>
<para>
To define a tablespace, use the <xref
linkend="sql-createtablespace" endterm="sql-createtablespace-title">
- command, for example:<indexterm><primary>CREATE TABLESPACE</></>
+ command, for example:<indexterm><primary>CREATE TABLESPACE</></>:
<programlisting>
CREATE TABLESPACE fastspace LOCATION '/mnt/sda1/postgresql/data';
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/monitoring.sgml,v 1.44 2007/01/31 20:56:18 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/monitoring.sgml,v 1.45 2007/02/01 00:28:17 momjian Exp $ -->
<chapter id="monitoring">
<title>Monitoring Database Activity</title>
<para>
The example below shows a DTrace script for analyzing transaction
counts on the system, as an alternative to snapshotting
- <structname>pg_stat_database</> before and after a performance test.
+ <structname>pg_stat_database</> before and after a performance test:
<programlisting>
#!/usr/sbin/dtrace -qs
trace macros. These are chosen according to how many variables will
be made available for inspection at that trace point. Tracing the
occurrence of an event can be achieved with a single line, using
- just the trace point name, e.g.
+ just the trace point name, e.g.:
<programlisting>
PG_TRACE (my__new__trace__point);
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/nls.sgml,v 1.15 2007/01/31 20:56:18 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/nls.sgml,v 1.16 2007/02/01 00:28:17 momjian Exp $ -->
<chapter id="nls">
<chapterinfo>
<para>
If you need to start a new translation effort, then first run the
- command
+ command:
<programlisting>
gmake init-po
</programlisting>
<para>
As the underlying program or library changes, messages might be
changed or added by the programmers. In this case you do not need
- to start from scratch. Instead, run the command
+ to start from scratch. Instead, run the command:
<programlisting>
gmake update-po
</programlisting>
<step>
<para>
Wherever a message that is a candidate for translation is found,
- a call to <function>gettext()</function> needs to be inserted. E.g.,
+ a call to <function>gettext()</function> needs to be inserted. E.g.:
<programlisting>
fprintf(stderr, "panic level %d\n", lvl);
</programlisting>
- would be changed to
+ would be changed to:
<programlisting>
fprintf(stderr, gettext("panic level %d\n"), lvl);
</programlisting>
</para>
<para>
- This tends to add a lot of clutter. One common shortcut is to use
+ This tends to add a lot of clutter. One common shortcut is to use:
<programlisting>
#define _(x) gettext(x)
</programlisting>
<itemizedlist>
<listitem>
<para>
- Do not construct sentences at run-time, like
+ Do not construct sentences at run-time, like:
<programlisting>
printf("Files were %s.\n", flag ? "copied" : "removed");
</programlisting>
printf("copied %d file%s", n, n!=1 ? "s" : "");
</programlisting>
because it assumes how the plural is formed. If you figured you
- could solve it like this
+ could solve it like this:
<programlisting>
if (n==1)
printf("copied 1 file");
If you want to communicate something to the translator, such as
about how a message is intended to line up with other output,
precede the occurrence of the string with a comment that starts
- with <literal>translator</literal>, e.g.,
+ with <literal>translator</literal>, e.g.:
<programlisting>
/* translator: This message is not what it seems to be. */
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/perform.sgml,v 1.61 2007/01/31 20:56:18 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/perform.sgml,v 1.62 2007/02/01 00:28:17 momjian Exp $ -->
<chapter id="performance-tips">
<title>Performance Tips</title>
</para>
<para>
- This is about as straightforward as it gets. If you do
+ This is about as straightforward as it gets. If you do:
<programlisting>
SELECT relpages, reltuples FROM pg_class WHERE relname = 'tenk1';
</para>
<para>
- In a simple join query, such as
+ In a simple join query, such as:
<programlisting>
SELECT * FROM a, b, c WHERE a.id = b.id AND b.ref = c.id;
</programlisting>
<para>
When the query involves outer joins, the planner has less freedom
- than it does for plain (inner) joins. For example, consider
+ than it does for plain (inner) joins. For example, consider:
<programlisting>
SELECT * FROM a LEFT JOIN (b JOIN c ON (b.ref = c.id)) ON (a.id = b.id);
</programlisting>
B to C and then join A to that result. Accordingly, this query takes
less time to plan than the previous query. In other cases, the planner
might be able to determine that more than one join order is safe.
- For example, given
+ For example, given:
<programlisting>
SELECT * FROM a LEFT JOIN b ON (a.bid = b.id) LEFT JOIN c ON (a.cid = c.id);
</programlisting>
<para>
You do not need to constrain the join order completely in order to
cut search time, because it's OK to use <literal>JOIN</> operators
- within items of a plain <literal>FROM</> list. For example, consider
+ within items of a plain <literal>FROM</> list. For example, consider:
<programlisting>
SELECT * FROM a CROSS JOIN b, c, d, e WHERE ...;
</programlisting>
<para>
A closely related issue that affects planning time is collapsing of
- subqueries into their parent query. For example, consider
+ subqueries into their parent query. For example, consider:
<programlisting>
SELECT *
FROM x, y,
This situation might arise from use of a view that contains a join;
the view's <literal>SELECT</> rule will be inserted in place of the view
reference, yielding a query much like the above. Normally, the planner
- will try to collapse the subquery into the parent, yielding
+ will try to collapse the subquery into the parent, yielding:
<programlisting>
SELECT * FROM x, y, a, b, c WHERE something AND somethingelse;
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.61 2007/01/31 20:56:18 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/plperl.sgml,v 2.62 2007/02/01 00:28:17 momjian Exp $ -->
<chapter id="plperl">
<title>PL/Perl - Perl Procedural Language</title>
<para>
A PL/Perl function can return a composite-type result using the same
approach: return a reference to a hash that has the required attributes.
- For example,
+ For example:
<programlisting>
CREATE TYPE testrowperl AS (f1 integer, f2 text, f3 text);
</para>
<para>
- Another way to use the <literal>strict</> pragma is to put
+ Another way to use the <literal>strict</> pragma is to put:
<programlisting>
use strict;
</programlisting>
in the function body. But this only works in <application>PL/PerlU</>
functions, since <literal>use</> is not a trusted operation. In
- <application>PL/Perl</> functions you can instead do
+ <application>PL/Perl</> functions you can instead do:
<programlisting>
BEGIN { strict->import(); }
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/plpgsql.sgml,v 1.104 2007/01/31 20:56:18 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/plpgsql.sgml,v 1.105 2007/02/01 00:28:17 momjian Exp $ -->
<chapter id="plpgsql">
<title><application>PL/pgSQL</application> - <acronym>SQL</acronym> Procedural Language</title>
<para>
While running <application>psql</application>, you can load or reload such
- a function definition file with
+ a function definition file with:
<programlisting>
\i filename.sql
</programlisting>
approach, you never double any quote marks, but instead take care to
choose a different dollar-quoting delimiter for each level of
nesting you need. For example, you might write the <command>CREATE
- FUNCTION</command> command as
+ FUNCTION</command> command as:
<programlisting>
CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $PROC$
....
a_output := ''Blah'';
SELECT * FROM users WHERE f_name=''foobar'';
</programlisting>
- In the dollar-quoting approach, you'd just write
+ In the dollar-quoting approach, you'd just write:
<programlisting>
a_output := 'Blah';
SELECT * FROM users WHERE f_name='foobar';
<literal> AND name LIKE 'foobar' AND xyz</literal>.
</para>
<para>
- In the dollar-quoting approach, you'd write
+ In the dollar-quoting approach, you'd write:
<programlisting>
a_output := a_output || $$ AND name LIKE 'foobar' AND xyz$$
</programlisting>
<literal> AND name LIKE 'foobar'</literal>.
</para>
<para>
- In the dollar-quoting approach, this becomes
+ In the dollar-quoting approach, this becomes:
<programlisting>
a_output := a_output || $$ AND name LIKE 'foobar'$$
</programlisting>
</programlisting>
</para>
<para>
- In the dollar-quoting approach, this becomes
+ In the dollar-quoting approach, this becomes:
<programlisting>
a_output := a_output || $$ if v_$$ || referrer_keys.kind || $$ like '$$
|| referrer_keys.key_string || $$'
<replaceable>name</replaceable> ALIAS FOR $<replaceable>n</replaceable>;
</synopsis>
- The same example in this style looks like
+ The same example in this style looks like:
<programlisting>
CREATE FUNCTION sales_tax(real) RETURNS real AS $$
DECLARE
$$ LANGUAGE plpgsql;
</programlisting>
- and
+ and:
<programlisting>
CREATE FUNCTION logfunc2(logtxt text) RETURNS timestamp AS $$
This two-step process allows
<application>PL/pgSQL</application> to plan the query just once
and re-use the plan on subsequent executions. As an example,
- if you write
+ if you write:
<programlisting>
DECLARE
key TEXT;
...
UPDATE mytab SET val = val + delta WHERE id = key;
</programlisting>
- the query text seen by the main SQL engine will look like
+ the query text seen by the main SQL engine will look like:
<programlisting>
UPDATE mytab SET val = val + $1 WHERE id = $2;
</programlisting>
<para>
Note that dollar quoting is only useful for quoting fixed text.
- It would be a very bad idea to try to do the above example as
+ It would be a very bad idea to try to do the above example as:
<programlisting>
EXECUTE 'UPDATE tbl SET '
|| quote_ident(colname)
<para>
This example uses exception handling to perform either
- <command>UPDATE</> or <command>INSERT</>, as appropriate.
+ <command>UPDATE</> or <command>INSERT</>, as appropriate:
<programlisting>
CREATE TABLE db (a INT PRIMARY KEY, b TEXT);
In <application>PL/pgSQL</>, when an exception is caught by an
<literal>EXCEPTION</> clause, all database changes since the block's
<literal>BEGIN</> are automatically rolled back. That is, the behavior
- is equivalent to what you'd get in Oracle with
+ is equivalent to what you'd get in Oracle with:
<programlisting>
BEGIN
-<!-- $PostgreSQL: pgsql/doc/src/sgml/plpython.sgml,v 1.37 2007/01/31 20:56:18 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/plpython.sgml,v 1.38 2007/02/01 00:28:17 momjian Exp $ -->
<chapter id="plpython">
<title>PL/Python - Python Procedural Language</title>
</programlisting>
The Python code that is given as the body of the function definition
- is transformed into a Python function. For example, the above results in
+ is transformed into a Python function. For example, the above results in:
<programlisting>
def __plpython_procedure_pymax_23456():
</para>
<para>
- For example,
+ For example:
<programlisting>
rv = plpy.execute("SELECT * FROM my_table", 5)
</programlisting>
returns up to 5 rows from <literal>my_table</literal>. If
<literal>my_table</literal> has a column
- <literal>my_column</literal>, it would be accessed as
+ <literal>my_column</literal>, it would be accessed as:
<programlisting>
foo = rv[i]["my_column"]
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/pltcl.sgml,v 2.44 2007/01/31 20:56:18 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/pltcl.sgml,v 2.45 2007/02/01 00:28:17 momjian Exp $ -->
<chapter id="pltcl">
<title>PL/Tcl - Tcl Procedural Language</title>
Tcl variables; remaining rows, if any, are ignored. No storing occurs
if the
query returns no rows. (This case can be detected by checking the
- result of <function>spi_exec</function>.) For example,
-
+ result of <function>spi_exec</function>.) For example:
<programlisting>
spi_exec "SELECT count(*) AS cnt FROM pg_proc"
</programlisting>
a piece of Tcl script that is executed once for each row in the
query result. (<replaceable>loop-body</> is ignored if the given
command is not a <command>SELECT</>.) The values of the current row's columns
- are stored into Tcl variables before each iteration. For example,
+ are stored into Tcl variables before each iteration. For example:
<programlisting>
spi_exec -array C "SELECT * FROM pg_class" {
that are to be inserted into SQL commands given
to <function>spi_exec</function> or
<function>spi_prepare</function>.
- For example, think about an SQL command string like
+ For example, think about an SQL command string like:
<programlisting>
"SELECT '$val' AS ret"
where the Tcl variable <literal>val</> actually contains
<literal>doesn't</literal>. This would result
- in the final command string
+ in the final command string:
<programlisting>
SELECT 'doesn't' AS ret
which would cause a parse error during
<function>spi_exec</function> or
<function>spi_prepare</function>.
- To work properly, the submitted command should contain
+ To work properly, the submitted command should contain:
<programlisting>
SELECT 'doesn''t' AS ret
</programlisting>
- which can be formed in PL/Tcl using
+ which can be formed in PL/Tcl using:
<programlisting>
"SELECT '[ quote $val ]' AS ret"
-<!-- $PostgreSQL: pgsql/doc/src/sgml/queries.sgml,v 1.42 2007/01/31 20:56:18 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/queries.sgml,v 1.43 2007/02/01 00:28:17 momjian Exp $ -->
<chapter id="queries">
<title>Queries</title>
</para>
<para>
- A simple kind of query has the form
+ A simple kind of query has the form:
<programlisting>
SELECT * FROM table1;
</programlisting>
</para>
<para>
- To put this together, assume we have tables <literal>t1</literal>
+ To put this together, assume we have tables <literal>t1</literal>:
<programlisting>
num | name
-----+------
2 | b
3 | c
</programlisting>
- and <literal>t2</literal>
+ and <literal>t2</literal>:
<programlisting>
num | value
-----+-------
<para>
The alias becomes the new name of the table reference for the
current query — it is no longer possible to refer to the table
- by the original name. Thus
+ by the original name. Thus:
<programlisting>
SELECT * FROM my_table AS m WHERE my_table.a > 5;
</programlisting>
<literal>off</> (as it is by default). If it is <literal>on</>,
an implicit table reference will be added to the
<literal>FROM</literal> clause, so the query is processed as if
- it were written as
+ it were written as:
<programlisting>
SELECT * FROM my_table AS m, my_table AS my_table WHERE my_table.a > 5;
</programlisting>
<para>
Table aliases are mainly for notational convenience, but it is
- necessary to use them when joining a table to itself, e.g.,
+ necessary to use them when joining a table to itself, e.g.:
<programlisting>
SELECT * FROM people AS mother JOIN people AS child ON mother.id = child.mother_id;
</programlisting>
<para>
When an alias is applied to the output of a <literal>JOIN</>
clause, using any of these forms, the alias hides the original
- names within the <literal>JOIN</>. For example,
+ names within the <literal>JOIN</>. For example:
<programlisting>
SELECT a.* FROM my_table AS a JOIN your_table AS b ON ...
</programlisting>
- is valid SQL, but
+ is valid SQL, but:
<programlisting>
SELECT a.* FROM (my_table AS a JOIN your_table AS b ON ...) AS c
</programlisting>
<programlisting>
FROM a, b WHERE a.id = b.id AND b.val > 5
</programlisting>
- and
+ and:
<programlisting>
FROM a INNER JOIN b ON (a.id = b.id) WHERE b.val > 5
</programlisting>
- or perhaps even
+ or perhaps even:
<programlisting>
FROM a NATURAL JOIN b WHERE b.val > 5
</programlisting>
<para>
Here is another example: it calculates the total sales for each
- product (rather than the total sales on all products).
+ product (rather than the total sales on all products):
<programlisting>
SELECT product_id, p.name, (sum(s.units) * p.price) AS sales
FROM products p LEFT JOIN sales s USING (product_id)
<para>
If more than one table has a column of the same name, the table
- name must also be given, as in
+ name must also be given, as in:
<programlisting>
SELECT tbl1.a, tbl2.a, tbl1.b FROM ...
</programlisting>
<optional>, <replaceable>sort_expression2</replaceable> <optional>ASC | DESC</optional> <optional>NULLS { FIRST | LAST }</optional> ...</optional>
</synopsis>
The sort expression(s) can be any expression that would be valid in the
- query's select list. An example is
+ query's select list. An example is:
<programlisting>
SELECT a, b FROM table1 ORDER BY a + b, c;
</programlisting>
<para>
For backwards compatibility with the SQL92 version of the standard,
a <replaceable>sort_expression</> can instead be the name or number
- of an output column, as in
+ of an output column, as in:
<programlisting>
SELECT a + b AS sum, c FROM table1 ORDER BY sum;
SELECT a, max(b) FROM table1 GROUP BY a ORDER BY 1;
</para>
<para>
- As an example,
-
+ As an example:
<programlisting>
VALUES (1, 'one'), (2, 'two'), (3, 'three');
</programlisting>
will return a table of two columns and three rows. It's effectively
- equivalent to
-
+ equivalent to:
<programlisting>
SELECT 1 AS column1, 'one' AS column2
UNION ALL
-<!-- $PostgreSQL: pgsql/doc/src/sgml/query.sgml,v 1.49 2007/01/31 20:56:18 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/query.sgml,v 1.50 2007/02/01 00:28:17 momjian Exp $ -->
<chapter id="tutorial-sql">
<title>The <acronym>SQL</acronym> Language</title>
In this example, the sort order isn't fully specified, and so you
might get the San Francisco rows in either order. But you'd always
- get the results shown above if you do
+ get the results shown above if you do:
<programlisting>
SELECT * FROM weather
<para>
As an example, we can find the highest low-temperature reading anywhere
- with
+ with:
<programlisting>
SELECT max(temp_lo) FROM weather;
<indexterm><primary>subquery</primary></indexterm>
If we wanted to know what city (or cities) that reading occurred in,
- we might try
+ we might try:
<programlisting>
SELECT city FROM weather WHERE temp_lo = max(temp_lo); <lineannotation>WRONG</lineannotation>
Aggregates are also very useful in combination with <literal>GROUP
BY</literal> clauses. For example, we can get the maximum low
- temperature observed in each city with
+ temperature observed in each city with:
<programlisting>
SELECT city, max(temp_lo)
which gives us the same results for only the cities that have all
<literal>temp_lo</> values below 40. Finally, if we only care about
cities whose
- names begin with <quote><literal>S</literal></quote>, we might do
+ names begin with <quote><literal>S</literal></quote>, we might do:
<programlisting>
SELECT city, max(temp_lo)
<!--
-$PostgreSQL: pgsql/doc/src/sgml/ref/alter_table.sgml,v 1.93 2007/01/31 23:26:02 momjian Exp $
+$PostgreSQL: pgsql/doc/src/sgml/ref/alter_table.sgml,v 1.94 2007/02/01 00:28:18 momjian Exp $
PostgreSQL documentation
-->
The fact that <literal>ALTER TYPE</> requires rewriting the whole table
is sometimes an advantage, because the rewriting process eliminates
any dead space in the table. For example, to reclaim the space occupied
- by a dropped column immediately, the fastest way is
+ by a dropped column immediately, the fastest way is:
<programlisting>
ALTER TABLE table ALTER COLUMN anycol TYPE anytype;
</programlisting>
<!--
-$PostgreSQL: pgsql/doc/src/sgml/ref/cluster.sgml,v 1.39 2007/01/31 23:26:02 momjian Exp $
+$PostgreSQL: pgsql/doc/src/sgml/ref/cluster.sgml,v 1.40 2007/02/01 00:28:18 momjian Exp $
PostgreSQL documentation
-->
entries are on random pages, so there is one disk page
retrieved for every row moved. (<productname>PostgreSQL</productname> has
a cache, but the majority of a big table will not fit in the cache.)
- The other way to cluster a table is to use
+ The other way to cluster a table is to use:
<programlisting>
CREATE TABLE <replaceable class="parameter">newtable</replaceable> AS
<!--
-$PostgreSQL: pgsql/doc/src/sgml/ref/create_aggregate.sgml,v 1.37 2007/01/31 23:26:03 momjian Exp $
+$PostgreSQL: pgsql/doc/src/sgml/ref/create_aggregate.sgml,v 1.38 2007/02/01 00:28:18 momjian Exp $
PostgreSQL documentation
-->
input row. If this aggregate can be so optimized, indicate it by
specifying a <firstterm>sort operator</>. The basic requirement is that
the aggregate must yield the first element in the sort ordering induced by
- the operator; in other words
+ the operator; in other words:
<programlisting>
SELECT agg(col) FROM tab;
</programlisting>
- must be equivalent to
+ must be equivalent to:
<programlisting>
SELECT col FROM tab ORDER BY col USING sortop LIMIT 1;
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/ref/create_cast.sgml,v 1.24 2007/01/31 23:26:03 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/ref/create_cast.sgml,v 1.25 2007/02/01 00:28:18 momjian Exp $ -->
<refentry id="SQL-CREATECAST">
<refmeta>
<para>
<command>CREATE CAST</command> defines a new cast. A cast
specifies how to perform a conversion between
- two data types. For example,
+ two data types. For example:
<programlisting>
SELECT CAST(42 AS text);
</programlisting>
If the cast is marked <literal>AS ASSIGNMENT</> then it can be invoked
implicitly when assigning a value to a column of the target data type.
For example, supposing that <literal>foo.f1</literal> is a column of
- type <type>text</type>, then
+ type <type>text</type>, then:
<programlisting>
INSERT INTO foo (f1) VALUES (42);
</programlisting>
</programlisting>
will be allowed only if the cast from type <type>timestamp</> to
<type>text</type> is marked <literal>AS IMPLICIT</>. Otherwise it
- will be necessary to write the cast explicitly, for example
+ will be necessary to write the cast explicitly, for example:
<programlisting>
SELECT 'The time is ' || CAST(now() AS text);
</programlisting>
<!--
-$PostgreSQL: pgsql/doc/src/sgml/ref/create_domain.sgml,v 1.30 2007/01/31 23:26:03 momjian Exp $
+$PostgreSQL: pgsql/doc/src/sgml/ref/create_domain.sgml,v 1.31 2007/02/01 00:28:18 momjian Exp $
PostgreSQL documentation
-->
<para>
This example creates the <type>us_postal_code</type> data type and
then uses the type in a table definition. A regular expression test
- is used to verify that the value looks like a valid US postal code.
+ is used to verify that the value looks like a valid US postal code:
<programlisting>
CREATE DOMAIN us_postal_code AS TEXT
<!--
-$PostgreSQL: pgsql/doc/src/sgml/ref/create_operator.sgml,v 1.47 2007/01/31 23:26:03 momjian Exp $
+$PostgreSQL: pgsql/doc/src/sgml/ref/create_operator.sgml,v 1.48 2007/02/01 00:28:18 momjian Exp $
PostgreSQL documentation
-->
<para>
To give a schema-qualified operator name in <replaceable
class="parameter">com_op</replaceable> or the other optional
- arguments, use the <literal>OPERATOR()</> syntax, for example
+ arguments, use the <literal>OPERATOR()</> syntax, for example:
<programlisting>
COMMUTATOR = OPERATOR(myschema.===) ,
</programlisting>
<!--
-$PostgreSQL: pgsql/doc/src/sgml/ref/create_rule.sgml,v 1.49 2007/01/31 23:26:03 momjian Exp $
+$PostgreSQL: pgsql/doc/src/sgml/ref/create_rule.sgml,v 1.50 2007/02/01 00:28:18 momjian Exp $
PostgreSQL documentation
-->
command, the <command>NOTIFY</command> command will be executed
unconditionally, that is, the <command>NOTIFY</command> will be
issued even if there are not any rows that the rule should apply
- to. For example, in
+ to. For example, in:
<programlisting>
CREATE RULE notify_me AS ON UPDATE TO mytable DO ALSO NOTIFY mytable;
<!--
-$PostgreSQL: pgsql/doc/src/sgml/ref/create_sequence.sgml,v 1.46 2007/01/31 23:26:03 momjian Exp $
+$PostgreSQL: pgsql/doc/src/sgml/ref/create_sequence.sgml,v 1.47 2007/02/01 00:28:18 momjian Exp $
PostgreSQL documentation
-->
</para>
<para>
- Although you cannot update a sequence directly, you can use a query like
+ Although you cannot update a sequence directly, you can use a query like:
<programlisting>
SELECT * FROM <replaceable>name</replaceable>;
<!--
-$PostgreSQL: pgsql/doc/src/sgml/ref/create_table.sgml,v 1.106 2007/01/31 23:26:03 momjian Exp $
+$PostgreSQL: pgsql/doc/src/sgml/ref/create_table.sgml,v 1.107 2007/02/01 00:28:18 momjian Exp $
PostgreSQL documentation
-->
<para>
Define a unique table constraint for the table
<literal>films</literal>. Unique table constraints can be defined
- on one or more columns of the table.
+ on one or more columns of the table:
<programlisting>
CREATE TABLE films (
<!--
-$PostgreSQL: pgsql/doc/src/sgml/ref/create_type.sgml,v 1.67 2007/01/31 23:26:03 momjian Exp $
+$PostgreSQL: pgsql/doc/src/sgml/ref/create_type.sgml,v 1.68 2007/02/01 00:28:18 momjian Exp $
PostgreSQL documentation
-->
<para>
If the internal structure of <type>box</type> were an array of four
- <type>float4</> elements, we might instead use
+ <type>float4</> elements, we might instead use:
<programlisting>
CREATE TYPE box (
INTERNALLENGTH = 16,
<!--
-$PostgreSQL: pgsql/doc/src/sgml/ref/create_view.sgml,v 1.34 2007/01/31 23:26:03 momjian Exp $
+$PostgreSQL: pgsql/doc/src/sgml/ref/create_view.sgml,v 1.35 2007/02/01 00:28:18 momjian Exp $
PostgreSQL documentation
-->
<para>
Be careful that the names and types of the view's columns will be
- assigned the way you want. For example,
+ assigned the way you want. For example:
<programlisting>
CREATE VIEW vista AS SELECT 'Hello World';
</programlisting>
is bad form in two ways: the column name defaults to <literal>?column?</>,
and the column data type defaults to <type>unknown</>. If you want a
- string literal in a view's result, use something like
+ string literal in a view's result, use something like:
<programlisting>
CREATE VIEW vista AS SELECT text 'Hello World' AS hello;
</programlisting>
<!--
-$PostgreSQL: pgsql/doc/src/sgml/ref/delete.sgml,v 1.29 2007/01/31 23:26:03 momjian Exp $
+$PostgreSQL: pgsql/doc/src/sgml/ref/delete.sgml,v 1.30 2007/02/01 00:28:19 momjian Exp $
PostgreSQL documentation
-->
<productname>PostgreSQL</productname> lets you reference columns of
other tables in the <literal>WHERE</> condition by specifying the
other tables in the <literal>USING</literal> clause. For example,
- to delete all films produced by a given producer, one can do
+ to delete all films produced by a given producer, one can do:
<programlisting>
DELETE FROM films USING producers
WHERE producer_id = producers.id AND producers.name = 'foo';
What is essentially happening here is a join between <structname>films</>
and <structname>producers</>, with all successfully joined
<structname>films</> rows being marked for deletion.
- This syntax is not standard. A more standard way to do it is
+ This syntax is not standard. A more standard way to do it is:
<programlisting>
DELETE FROM films
WHERE producer_id IN (SELECT id FROM producers WHERE name = 'foo');
<!--
-$PostgreSQL: pgsql/doc/src/sgml/ref/fetch.sgml,v 1.39 2006/09/16 00:30:18 momjian Exp $
+$PostgreSQL: pgsql/doc/src/sgml/ref/fetch.sgml,v 1.40 2007/02/01 00:28:19 momjian Exp $
PostgreSQL documentation
-->
<title>Examples</title>
<para>
- The following example traverses a table using a cursor.
+ The following example traverses a table using a cursor:
<programlisting>
BEGIN WORK;
<!--
-$PostgreSQL: pgsql/doc/src/sgml/ref/grant.sgml,v 1.63 2007/01/31 23:26:04 momjian Exp $
+$PostgreSQL: pgsql/doc/src/sgml/ref/grant.sgml,v 1.64 2007/02/01 00:28:19 momjian Exp $
PostgreSQL documentation
-->
</programlisting>
The above example display would be seen by user <literal>miriam</> after
- creating table <literal>mytable</> and doing
+ creating table <literal>mytable</> and doing:
<programlisting>
GRANT SELECT ON mytable TO PUBLIC;
-<!-- $PostgreSQL: pgsql/doc/src/sgml/ref/pg_restore.sgml,v 1.65 2007/01/31 23:26:04 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/ref/pg_restore.sgml,v 1.66 2007/02/01 00:28:19 momjian Exp $ -->
<refentry id="APP-PGRESTORE">
<refmeta>
<screen>
<prompt>$</prompt> <userinput>pg_restore -l db.dump > db.list</userinput>
</screen>
- The listing file consists of a header and one line for each item, e.g.,
+ The listing file consists of a header and one line for each item, e.g.:
<programlisting>
;
; Archive created at Fri Jul 28 22:28:36 2000
</para>
<para>
- Lines in the file can be commented out, deleted, and reordered. For example,
+ Lines in the file can be commented out, deleted, and reordered. For example:
<programlisting>
10; 145433 TABLE map_resolutions postgres
;2; 145344 TABLE species postgres
<!--
-$PostgreSQL: pgsql/doc/src/sgml/ref/psql-ref.sgml,v 1.181 2007/01/31 23:26:04 momjian Exp $
+$PostgreSQL: pgsql/doc/src/sgml/ref/psql-ref.sgml,v 1.182 2007/02/01 00:28:19 momjian Exp $
PostgreSQL documentation
-->
An alternative way to specify connection parameters is in a
<parameter>conninfo</parameter> string, which is used instead of a
database name. This mechanism give you very wide control over the
- connection. For example,
+ connection. For example:
<programlisting>
$ <userinput>psql "service=myservice sslmode=require"</userinput>
</programlisting>
In normal operation, <application>psql</application> provides a
prompt with the name of the database to which
<application>psql</application> is currently connected, followed by
- the string <literal>=></literal>. For example,
+ the string <literal>=></literal>. For example:
<programlisting>
$ <userinput>psql testdb</userinput>
Welcome to psql &version;, the PostgreSQL interactive terminal.
<listitem>
<para>
The file name that will be used to store the history list. The default
- value is <filename>~/.psql_history</filename>. For example, putting
+ value is <filename>~/.psql_history</filename>. For example, putting:
<programlisting>
\set HISTFILE ~/.psql_history- :DBNAME
</programlisting>
variables is that you can substitute (<quote>interpolate</quote>)
them into regular <acronym>SQL</acronym> statements. The syntax for
this is again to prepend the variable name with a colon
- (<literal>:</literal>).
+ (<literal>:</literal>):
<programlisting>
testdb=> <userinput>\set foo 'my_table'</userinput>
testdb=> <userinput>SELECT * FROM :foo;</userinput>
inserted <acronym>OID</acronym> in subsequent statements to build a
foreign key scenario. Another possible use of this mechanism is to
copy the contents of a file into a table column. First load the file into a
- variable and then proceed as above.
+ variable and then proceed as above:
<programlisting>
testdb=> <userinput>\set content '''' `cat my_file.txt` ''''</userinput>
testdb=> <userinput>INSERT INTO my_table VALUES (:content);</userinput>
non-printing control characters must be designated as invisible
by surrounding them with <literal>%[</literal> and
<literal>%]</literal>. Multiple pairs of these can occur within
- the prompt. For example,
+ the prompt. For example:
<programlisting>
testdb=> \set PROMPT1 '%[%033[1;33;40m%]%n@%/%R%[%033[0m%]%# '
</programlisting>
compatibility this is still supported to some extent,
but we are not going to explain the details here as this use is
discouraged. If you get strange messages, keep this in mind.
- For example
+ For example:
<programlisting>
testdb=> <userinput>\foo</userinput>
Field separator is "oo".
<!--
-$PostgreSQL: pgsql/doc/src/sgml/ref/select.sgml,v 1.97 2007/01/31 23:26:04 momjian Exp $
+$PostgreSQL: pgsql/doc/src/sgml/ref/select.sgml,v 1.98 2007/02/01 00:28:19 momjian Exp $
PostgreSQL documentation
-->
<literal>ORDER BY</> (see above). Note that the <quote>first
row</quote> of each set is unpredictable unless <literal>ORDER
BY</> is used to ensure that the desired row appears first. For
- example,
+ example:
<programlisting>
SELECT DISTINCT ON (location) location, time, report
FROM weather_reports
<para>
Avoid locking a row and then modifying it within a later savepoint or
<application>PL/pgSQL</application> exception block. A subsequent
- rollback would cause the lock to be lost. For example,
+ rollback would cause the lock to be lost. For example:
<programlisting>
BEGIN;
SELECT * FROM mytable WHERE key = 1 FOR UPDATE;
<!--
-$PostgreSQL: pgsql/doc/src/sgml/ref/update.sgml,v 1.42 2007/01/31 23:26:04 momjian Exp $
+$PostgreSQL: pgsql/doc/src/sgml/ref/update.sgml,v 1.43 2007/02/01 00:28:19 momjian Exp $
PostgreSQL documentation
-->
<para>
Attempt to insert a new stock item along with the quantity of stock. If
the item already exists, instead update the stock count of the existing
- item. To do this without failing the entire transaction, use savepoints.
+ item. To do this without failing the entire transaction, use savepoints:
<programlisting>
BEGIN;
-- other operations
<!--
-$PostgreSQL: pgsql/doc/src/sgml/ref/values.sgml,v 1.3 2007/01/31 23:26:05 momjian Exp $
+$PostgreSQL: pgsql/doc/src/sgml/ref/values.sgml,v 1.4 2007/02/01 00:28:19 momjian Exp $
PostgreSQL documentation
-->
</programlisting>
This will return a table of two columns and three rows. It's effectively
- equivalent to
+ equivalent to:
<programlisting>
SELECT 1 AS column1, 'one' AS column2
-<!-- $PostgreSQL: pgsql/doc/src/sgml/regress.sgml,v 1.56 2007/01/31 20:56:18 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/regress.sgml,v 1.57 2007/02/01 00:28:17 momjian Exp $ -->
<chapter id="regress">
<title id="regress-title">Regression Tests</title>
<para>
The <literal>random</literal> test script is intended to produce
random results. In rare cases, this causes the random regression
- test to fail. Typing
+ test to fail. Typing:
<programlisting>
diff results/random.out expected/random.out
</programlisting>
<filename>float8-small-is-zero.out</filename>, which includes
the results to be expected on these systems. To silence the bogus
<quote>failure</quote> message on <systemitem>OpenBSD</systemitem>
- platforms, <filename>resultmap</filename> includes
+ platforms, <filename>resultmap</filename> includes:
<programlisting>
float8/i.86-.*-openbsd=float8-small-is-zero
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/release.sgml,v 1.492 2007/01/31 20:56:18 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/release.sgml,v 1.493 2007/02/01 00:28:17 momjian Exp $ -->
<!--
Typical markup:
COMMIT;
</programlisting>
- Next, if you have installed <filename>contrib/tsearch2</>, do
+ Next, if you have installed <filename>contrib/tsearch2</>, do:
<programlisting>
BEGIN;
template databases then any subsequently created databases will contain
the same errors. <literal>template1</> can be fixed in the same way
as any other database, but fixing <literal>template0</> requires
- additional steps. First, from any database issue
+ additional steps. First, from any database issue:
<programlisting>
UPDATE pg_database SET datallowconn = true WHERE datname = 'template0';
</programlisting>
Next connect to <literal>template0</> and perform the above repair
- procedures. Finally, do
+ procedures. Finally, do:
<programlisting>
-- re-freeze template0:
VACUUM FREEZE;
template databases then any subsequently created databases will contain
the same errors. <literal>template1</> can be fixed in the same way
as any other database, but fixing <literal>template0</> requires
- additional steps. First, from any database issue
+ additional steps. First, from any database issue:
<programlisting>
UPDATE pg_database SET datallowconn = true WHERE datname = 'template0';
</programlisting>
Next connect to <literal>template0</> and perform the above repair
- procedures. Finally, do
+ procedures. Finally, do:
<programlisting>
-- re-freeze template0:
VACUUM FREEZE;
template databases then any subsequently created databases will contain
the same error. <literal>template1</> can be fixed in the same way
as any other database, but fixing <literal>template0</> requires
- additional steps. First, from any database issue
+ additional steps. First, from any database issue:
<programlisting>
UPDATE pg_database SET datallowconn = true WHERE datname = 'template0';
</programlisting>
Next connect to <literal>template0</> and perform the above repair
- procedure. Finally, do
+ procedure. Finally, do:
<programlisting>
-- re-freeze template0:
VACUUM FREEZE;
<step>
<para>
If you do not want host-based authentication, you can comment out
- the line
+ the line:
<programlisting>
HBA = 1
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/rowtypes.sgml,v 2.8 2007/01/31 20:56:18 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/rowtypes.sgml,v 2.9 2007/02/01 00:28:18 momjian Exp $ -->
<sect1 id="rowtypes">
<title>Composite Types</title>
<para>
Whenever you create a table, a composite type is also automatically
created, with the same name as the table, to represent the table's
- row type. For example, had we said
+ row type. For example, had we said:
<programlisting>
CREATE TABLE inventory_item (
name text,
<synopsis>
'( <replaceable>val1</replaceable> , <replaceable>val2</replaceable> , ... )'
</synopsis>
- An example is
+ An example is:
<programlisting>
'("fuzzy dice",42,1.99)'
</programlisting>
ROW('', 42, NULL)
</programlisting>
The ROW keyword is actually optional as long as you have more than one
- field in the expression, so these can simplify to
+ field in the expression, so these can simplify to:
<programlisting>
('fuzzy dice', 42, 1.99)
('', 42, NULL)
<para>
Similar syntactic issues apply whenever you select a field from a composite
value. For instance, to select just one field from the result of a function
- that returns a composite value, you'd need to write something like
+ that returns a composite value, you'd need to write something like:
<programlisting>
SELECT (my_func(...)).field FROM ...
items. Whitespace outside the parentheses is ignored, but within the
parentheses it is considered part of the field value, and might or might not be
significant depending on the input conversion rules for the field data type.
- For example, in
+ For example, in:
<programlisting>
'( 42)'
</programlisting>
backslashes you need (assuming escape string syntax is used).
For example, to insert a <type>text</> field
containing a double quote and a backslash in a composite
- value, you'd need to write
+ value, you'd need to write:
<programlisting>
INSERT ... VALUES (E'("\\"\\\\")');
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.49 2007/01/31 20:56:18 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/rules.sgml,v 1.50 2007/02/01 00:28:18 momjian Exp $ -->
<chapter id="rules">
<title>The Rule System</title>
<para>
Views in <productname>PostgreSQL</productname> are implemented
using the rule system. In fact, there is essentially no difference
- between
+ between:
<programlisting>
CREATE VIEW myview AS SELECT * FROM mytab;
</programlisting>
- compared against the two commands
+ compared against the two commands:
<programlisting>
CREATE TABLE myview (<replaceable>same column list as mytab</replaceable>);
<para>
For the example, we need a little <literal>min</literal> function that
-returns the lower of 2 integer values. We create that as
+returns the lower of 2 integer values. We create that as:
<programlisting>
CREATE FUNCTION min(integer, integer) RETURNS integer AS $$
</para>
<para>
- The views are created as
+ The views are created as:
<programlisting>
CREATE VIEW shoe AS
This is the simplest <command>SELECT</command> you can do on our
views, so we take this opportunity to explain the basics of view
rules. The <literal>SELECT * FROM shoelace</literal> was
- interpreted by the parser and produced the query tree
+ interpreted by the parser and produced the query tree:
<programlisting>
SELECT shoelace.sl_name, shoelace.sl_avail,
range table and checks if there are rules
for any relation. When processing the range table entry for
<literal>shoelace</literal> (the only one up to now) it finds the
- <literal>_RETURN</literal> rule with the query tree
+ <literal>_RETURN</literal> rule with the query tree:
<programlisting>
SELECT s.sl_name, s.sl_avail,
To expand the view, the rewriter simply creates a subquery range-table
entry containing the rule's action query tree, and substitutes this
range table entry for the original one that referenced the view. The
- resulting rewritten query tree is almost the same as if you had typed
+ resulting rewritten query tree is almost the same as if you had typed:
<programlisting>
SELECT shoelace.sl_name, shoelace.sl_avail,
</para>
<para>
- The output of the parser this time is the query tree
+ The output of the parser this time is the query tree:
<programlisting>
SELECT shoe_ready.shoename, shoe_ready.sh_avail,
The first rule applied will be the one for the
<literal>shoe_ready</literal> view and it results in the
- query tree
+ query tree:
<programlisting>
SELECT shoe_ready.shoename, shoe_ready.sh_avail,
relation points to the range-table entry where the result should
go. Everything else is absolutely the same. So having two tables
<literal>t1</> and <literal>t2</> with columns <literal>a</> and
- <literal>b</>, the query trees for the two statements
+ <literal>b</>, the query trees for the two statements:
<programlisting>
SELECT t2.b FROM t1, t2 WHERE t1.a = t2.a;
execution plans: They are both joins over the two tables. For the
<command>UPDATE</command> the missing columns from <literal>t1</> are added to
the target list by the planner and the final query tree will read
- as
+ as:
<programlisting>
UPDATE t1 SET a = t1.a, b = t2.b FROM t2 WHERE t1.a = t2.a;
</programlisting>
and thus the executor run over the join will produce exactly the
- same result set as a
+ same result set as a:
<programlisting>
SELECT t1.a, t2.b FROM t1, t2 WHERE t1.a = t2.a;
file block number and position in the block for the row. Knowing
the table, the <acronym>CTID</> can be used to retrieve the
original row of <literal>t1</> to be updated. After adding the
- <acronym>CTID</> to the target list, the query actually looks like
+ <acronym>CTID</> to the target list, the query actually looks like:
<programlisting>
SELECT t1.a, t2.b, t1.ctid FROM t1, t2 WHERE t1.a = t2.a;
<title>How Update Rules Work</title>
<para>
- Keep the syntax
+ Keep the syntax:
<programlisting>
CREATE [ OR REPLACE ] RULE <replaceable class="parameter">name</replaceable> AS ON <replaceable class="parameter">event</replaceable>
<para>
That's what we expected. What happened in the background is the following.
- The parser created the query tree
+ The parser created the query tree:
<programlisting>
UPDATE shoelace_data SET sl_avail = 6
</programlisting>
There is a rule <literal>log_shoelace</literal> that is <literal>ON UPDATE</> with the rule
- qualification expression
+ qualification expression:
<programlisting>
NEW.sl_avail <> OLD.sl_avail
</programlisting>
- and the action
+ and the action:
<programlisting>
INSERT INTO shoelace_log VALUES (
<para>
The substitutions and the added qualifications
- ensure that, if the original query would be, say,
+ ensure that, if the original query would be, say:
<programlisting>
UPDATE shoelace_data SET sl_color = 'green'
tree does not contain a target list entry for
<literal>sl_avail</>, so <literal>NEW.sl_avail</> will get
replaced by <literal>shoelace_data.sl_avail</>. Thus, the extra
- command generated by the rule is
+ command generated by the rule is:
<programlisting>
INSERT INTO shoelace_log VALUES (
<para>
It will also work if the original query modifies multiple rows. So
- if someone issued the command
+ if someone issued the command:
<programlisting>
UPDATE shoelace_data SET sl_avail = 0
four rows in fact get updated (<literal>sl1</>, <literal>sl2</>, <literal>sl3</>, and <literal>sl4</>).
But <literal>sl3</> already has <literal>sl_avail = 0</>. In this case, the original
query trees qualification is different and that results
- in the extra query tree
+ in the extra query tree:
<programlisting>
INSERT INTO shoelace_log
A simple way to protect view relations from the mentioned
possibility that someone can try to run <command>INSERT</command>,
<command>UPDATE</command>, or <command>DELETE</command> on them is
- to let those query trees get thrown away. So we could create the rules
+ to let those query trees get thrown away. So we could create the rules:
<programlisting>
CREATE RULE shoe_ins_protect AS ON INSERT TO shoe
you need to make the rules include <literal>RETURNING</> clauses that
compute the view rows. This is usually pretty trivial for views on a
single table, but it's a bit tedious for join views such as
- <literal>shoelace</literal>. An example for the insert case is
+ <literal>shoelace</literal>. An example for the insert case is:
<programlisting>
CREATE RULE shoelace_ins AS ON INSERT TO shoelace
It's a long way from the one <literal>INSERT ... SELECT</literal>
to these results. And the description of the query-tree
transformation will be the last in this chapter. First, there is
- the parser's output
+ the parser's output:
<programlisting>
INSERT INTO shoelace_ok
</programlisting>
Now the first rule <literal>shoelace_ok_ins</literal> is applied and turns this
- into
+ into:
<programlisting>
UPDATE shoelace
and throws away the original <command>INSERT</command> on
<literal>shoelace_ok</literal>. This rewritten query is passed to
the rule system again, and the second applied rule
- <literal>shoelace_upd</literal> produces
+ <literal>shoelace_upd</literal> produces:
<programlisting>
UPDATE shoelace_data
Again it's an <literal>INSTEAD</> rule and the previous query tree is trashed.
Note that this query still uses the view <literal>shoelace</literal>.
But the rule system isn't finished with this step, so it continues
- and applies the <literal>_RETURN</literal> rule on it, and we get
+ and applies the <literal>_RETURN</literal> rule on it, and we get:
<programlisting>
UPDATE shoelace_data
</programlisting>
Finally, the rule <literal>log_shoelace</literal> gets applied,
- producing the extra query tree
+ producing the extra query tree:
<programlisting>
INSERT INTO shoelace_log
<para>
So we end up with two final query trees that are equivalent to the
- <acronym>SQL</acronym> statements
+ <acronym>SQL</acronym> statements:
<programlisting>
INSERT INTO shoelace_log
We would like to make a view to check which
<literal>shoelace</literal> entries do not fit any shoe in color.
- The view for this is
+ The view for this is:
<programlisting>
CREATE VIEW shoelace_mismatch AS
(SELECT shoename FROM shoe WHERE slcolor = sl_color);
</programlisting>
- Its output is
+ Its output is:
<programlisting>
SELECT * FROM shoelace_mismatch;
Now we want to set it up so that mismatching shoelaces that are
not in stock are deleted from the database.
To make it a little harder for <productname>PostgreSQL</productname>,
- we don't delete it directly. Instead we create one more view
+ we don't delete it directly. Instead we create one more view:
<programlisting>
CREATE VIEW shoelace_can_delete AS
Since the trigger is called for each individual row deleted from
<literal>computer</>, it can prepare and save the plan for this
command and pass the <structfield>hostname</> value in the
- parameter. The rule would be written as
+ parameter. The rule would be written as:
<programlisting>
CREATE RULE computer_del AS ON DELETE TO computer
</para>
<para>
- Now we look at different types of deletes. In the case of a
+ Now we look at different types of deletes. In the case of a:
<programlisting>
DELETE FROM computer WHERE hostname = 'mypc.local.net';
the table <literal>computer</> is scanned by index (fast), and the
command issued by the trigger would also use an index scan (also fast).
- The extra command from the rule would be
+ The extra command from the rule would be:
<programlisting>
DELETE FROM software WHERE computer.hostname = 'mypc.local.net'
With the next delete we want to get rid of all the 2000 computers
where the <structfield>hostname</> starts with
<literal>old</>. There are two possible commands to do that. One
- is
+ is:
<programlisting>
DELETE FROM computer WHERE hostname >= 'old'
AND hostname < 'ole'
</programlisting>
- The command added by the rule will be
+ The command added by the rule will be:
<programlisting>
DELETE FROM software WHERE computer.hostname >= 'old' AND computer.hostname < 'ole'
-> Index Scan using comp_hostidx on computer
</literallayout>
- The other possible command is
+ The other possible command is:
<programlisting>
DELETE FROM computer WHERE hostname ~ '^old';
</para>
<para>
- The last command we look at is
+ The last command we look at is:
<programlisting>
DELETE FROM computer WHERE manufacturer = 'bim';
Again this could result in many rows to be deleted from
<literal>computer</>. So the trigger will again run many commands
- through the executor. The command generated by the rule will be
+ through the executor. The command generated by the rule will be:
<programlisting>
DELETE FROM software WHERE computer.manufacturer = 'bim'
-<!-- $PostgreSQL: pgsql/doc/src/sgml/runtime.sgml,v 1.375 2007/01/31 20:56:19 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/runtime.sgml,v 1.376 2007/02/01 00:28:18 momjian Exp $ -->
<chapter Id="runtime">
<title>Operating System Environment</title>
<para>
In OS X 10.3.9 and later, instead of editing <filename>/etc/rc</>
you can create a file named <filename>/etc/sysctl.conf</>,
- containing variable assignments such as
+ containing variable assignments such as:
<programlisting>
kern.sysv.shmmax=4194304
kern.sysv.shmmin=1
In the default configuration, only 512 kB of shared memory per
segment is allowed. To increase the setting, first change to the
directory <filename>/etc/conf/cf.d</>. To display the current value of
- <varname>SHMMAX</>, run
+ <varname>SHMMAX</>, run:
<programlisting>
./configure -y SHMMAX
</programlisting>
- To set a new value for <varname>SHMMAX</>, run
+ To set a new value for <varname>SHMMAX</>, run:
<programlisting>
./configure SHMMAX=<replaceable>value</>
</programlisting>
<para>
On <productname>UnixWare</> 7, the maximum size for shared
memory segments is only 512 kB in the default configuration.
- To display the current value of <varname>SHMMAX</>, run
+ To display the current value of <varname>SHMMAX</>, run:
<programlisting>
/etc/conf/bin/idtune -g SHMMAX
</programlisting>
which displays the current, default, minimum, and maximum
values. To set a new value for <varname>SHMMAX</>,
- run
+ run:
<programlisting>
/etc/conf/bin/idtune SHMMAX <replaceable>value</>
</programlisting>
password can be left blank. The program will generate a key that is
passphrase protected; it will not accept a passphrase that is less
than four characters long. To remove the passphrase (as you must if
- you want automatic start-up of the server), run the commands
+ you want automatic start-up of the server), run the commands:
<programlisting>
openssl rsa -in privkey.pem -out server.key
rm privkey.pem
</programlisting>
- Enter the old passphrase to unlock the existing key. Now do
+ Enter the old passphrase to unlock the existing key. Now do:
<programlisting>
openssl req -x509 -in server.req -text -key server.key -out server.crt
chmod og-rwx server.key
-<!-- $PostgreSQL: pgsql/doc/src/sgml/sources.sgml,v 2.22 2007/01/31 21:03:37 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/sources.sgml,v 2.23 2007/02/01 00:28:18 momjian Exp $ -->
<chapter id="source">
<title>PostgreSQL Coding Conventions</title>
<para>
The text browsing tools <application>more</application> and
- <application>less</application> can be invoked as
+ <application>less</application> can be invoked as:
<programlisting>
more -x4
less -x4
<para>
There is an older function <function>elog</> that is still heavily used.
- An <function>elog</> call
+ An <function>elog</> call:
<programlisting>
elog(level, "format string", ...);
</programlisting>
- is exactly equivalent to
+ is exactly equivalent to:
<programlisting>
ereport(level, (errmsg_internal("format string", ...)));
</programlisting>
</para>
<para>
- For example, instead of
+ For example, instead of:
<programlisting>
IpcMemoryCreate: shmget(key=%d, size=%u, 0%o) failed: %m
(plus a long addendum that is basically a hint)
</programlisting>
- write
+ write:
<programlisting>
Primary: could not create shared memory segment: %m
Detail: Failed syscall was shmget(key=%d, size=%u, 0%o).
</para>
<para>
- There is a nontrivial semantic difference between sentences of the form
+ There is a nontrivial semantic difference between sentences of the form:
<programlisting>
could not open file "%s": %m
</programlisting>
-and
+and:
<programlisting>
cannot open file "%s"
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/spi.sgml,v 1.50 2007/01/31 20:56:19 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/spi.sgml,v 1.51 2007/02/01 00:28:18 momjian Exp $ -->
<chapter id="spi">
<title>Server Programming Interface</title>
for all rows that it applies to. If <parameter>count</parameter>
is greater than 0, then the number of rows for which the command
will be executed is restricted (much like a
- <literal>LIMIT</literal> clause). For example,
+ <literal>LIMIT</literal> clause). For example:
<programlisting>
SPI_execute("INSERT INTO foo SELECT * FROM bar", false, 5);
</programlisting>
<para>
During the execution of an SQL command, any data changes made by
the command are invisible to the command itself. For
- example, in
+ example, in:
<programlisting>
INSERT INTO a SELECT * FROM a;
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/syntax.sgml,v 1.112 2007/01/31 20:56:19 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/syntax.sgml,v 1.113 2007/02/01 00:28:18 momjian Exp $ -->
<chapter id="sql-syntax">
<title>SQL Syntax</title>
<primary>case sensitivity</primary>
<secondary>of SQL commands</secondary>
</indexterm>
- Identifier and key word names are case insensitive. Therefore
+ Identifier and key word names are case insensitive. Therefore:
<programlisting>
UPDATE MY_TABLE SET A = 5;
</programlisting>
- can equivalently be written as
+ can equivalently be written as:
<programlisting>
uPDaTE my_TabLE SeT a = 5;
</programlisting>
A convention often used is to write key words in upper
- case and names in lower case, e.g.,
+ case and names in lower case, e.g.:
<programlisting>
UPDATE my_table SET a = 5;
</programlisting>
SELECT 'foo'
'bar';
</programlisting>
- is equivalent to
+ is equivalent to:
<programlisting>
SELECT 'foobar';
</programlisting>
- but
+ but:
<programlisting>
SELECT 'foo' 'bar';
</programlisting>
force a numeric value to be interpreted as a specific data type
by casting it.<indexterm><primary>type cast</primary></indexterm>
For example, you can force a numeric value to be treated as type
- <type>real</> (<type>float4</>) by writing
+ <type>real</> (<type>float4</>) by writing:
<programlisting>
REAL '1.23' -- string style
<literal>></> have a different precedence than the Boolean
operators <literal><=</> and <literal>>=</>. Also, you will
sometimes need to add parentheses when using combinations of
- binary and unary operators. For instance
+ binary and unary operators. For instance:
<programlisting>
SELECT 5 ! - 6;
</programlisting>
- will be parsed as
+ will be parsed as:
<programlisting>
SELECT 5 ! (- 6);
</programlisting>
because the parser has no idea — until it is too late
— that <token>!</token> is defined as a postfix operator,
not an infix one. To get the desired behavior in this case, you
- must write
+ must write:
<programlisting>
SELECT (5 !) - 6;
</programlisting>
<para>
When a schema-qualified operator name is used in the
- <literal>OPERATOR</> syntax, as for example in
+ <literal>OPERATOR</> syntax, as for example in:
<programlisting>
SELECT 3 OPERATOR(pg_catalog.+) 4;
</programlisting>
<para>
For example, consider the definition of a function,
- <function>dept</function>, as
+ <function>dept</function>, as:
<programlisting>
CREATE FUNCTION dept(text) RETURNS dept
to be subscripted is just a column reference or positional parameter.
Also, multiple subscripts can be concatenated when the original array
is multidimensional.
- For example,
+ For example:
<programlisting>
mytable.arraycolumn[4]
In general the row <replaceable>expression</replaceable> must be
parenthesized, but the parentheses can be omitted when the expression
to be selected from is just a table reference or positional parameter.
- For example,
+ For example:
<programlisting>
mytable.mycolumn
consists of the key word <literal>ARRAY</literal>, a left square bracket
<literal>[</>, one or more expressions (separated by commas) for the
array element values, and finally a right square bracket <literal>]</>.
- For example,
+ For example:
<programlisting>
SELECT ARRAY[1,2,3+4];
array
for its member fields. A row constructor consists of the key word
<literal>ROW</literal>, a left parenthesis, zero or more
expressions (separated by commas) for the row field values, and finally
- a right parenthesis. For example,
+ a right parenthesis. For example:
<programlisting>
SELECT ROW(1,2.5,'this is a test');
</programlisting>
in a composite-type table column, or to be passed to a function that
accepts a composite parameter. Also,
it is possible to compare two row values or test a row with
- <literal>IS NULL</> or <literal>IS NOT NULL</>, for example
+ <literal>IS NULL</> or <literal>IS NOT NULL</>, for example:
<programlisting>
SELECT ROW(1,2.5,'this is a test') = ROW(1, 3, 'not the same');
<para>
Furthermore, if the result of an expression can be determined by
evaluating only some parts of it, then other subexpressions
- might not be evaluated at all. For instance, if one wrote
+ might not be evaluated at all. For instance, if one wrote:
<programlisting>
SELECT true OR somefunc();
</programlisting>
then <literal>somefunc()</literal> would (probably) not be called
- at all. The same would be the case if one wrote
+ at all. The same would be the case if one wrote:
<programlisting>
SELECT somefunc() OR true;
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.48 2007/01/31 20:56:19 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/trigger.sgml,v 1.49 2007/02/01 00:28:18 momjian Exp $ -->
<chapter id="triggers">
<title>Triggers</title>
any normal arguments, but it is passed a <quote>context</>
pointer pointing to a <structname>TriggerData</> structure. C
functions can check whether they were called from the trigger
- manager or not by executing the macro
+ manager or not by executing the macro:
<programlisting>
CALLED_AS_TRIGGER(fcinfo)
</programlisting>
- which expands to
+ which expands to:
<programlisting>
((fcinfo)->context != NULL && IsA((fcinfo)->context, TriggerData))
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/user-manag.sgml,v 1.38 2007/01/31 20:56:19 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/user-manag.sgml,v 1.39 2007/02/01 00:28:18 momjian Exp $ -->
<chapter id="user-manag">
<title>Database Roles and Privileges</title>
as the initial role name for a database connection. A role with
the <literal>LOGIN</> attribute can be considered the same thing
as a <quote>database user</>. To create a role with login privilege,
- use either
+ use either:
<programlisting>
CREATE ROLE <replaceable>name</replaceable> LOGIN;
CREATE USER <replaceable>name</replaceable>;
configuration settings described in <xref
linkend="runtime-config">. For example, if for some reason you
want to disable index scans (hint: not a good idea) anytime you
- connect, you can use
+ connect, you can use:
<programlisting>
ALTER ROLE myname SET enable_indexscan TO off;
</programlisting>
To assign privileges, the <command>GRANT</command> command is
used. So, if <literal>joe</literal> is an existing role, and
<literal>accounts</literal> is an existing table, the privilege to
- update the table can be granted with
+ update the table can be granted with:
<programlisting>
GRANT UPDATE ON accounts TO joe;
</programlisting>
considered owned by the group role not the login role. Second, member
roles that have the <literal>INHERIT</> attribute automatically have use of
privileges of roles they are members of. As an example, suppose we have
- done
+ done:
<programlisting>
CREATE ROLE joe LOGIN INHERIT;
CREATE ROLE admin NOINHERIT;
granted to <literal>wheel</> are not available, because even though
<literal>joe</> is indirectly a member of <literal>wheel</>, the
membership is via <literal>admin</> which has the <literal>NOINHERIT</>
- attribute. After
+ attribute. After:
<programlisting>
SET ROLE admin;
</programlisting>
the session would have use of only those privileges granted to
- <literal>admin</>, and not those granted to <literal>joe</>. After
+ <literal>admin</>, and not those granted to <literal>joe</>. After:
<programlisting>
SET ROLE wheel;
</programlisting>
the session would have use of only those privileges granted to
<literal>wheel</>, and not those granted to either <literal>joe</>
or <literal>admin</>. The original privilege state can be restored
- with any of
+ with any of:
<programlisting>
SET ROLE joe;
SET ROLE NONE;
-<!-- $PostgreSQL: pgsql/doc/src/sgml/xaggr.sgml,v 1.34 2007/01/31 20:56:20 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/xaggr.sgml,v 1.35 2007/02/01 00:28:18 momjian Exp $ -->
<sect1 id="xaggr">
<title>User-Defined Aggregates</title>
A function written in C can detect that it is being called as an
aggregate transition or final function by seeing if it was passed
an <structname>AggState</> node as the function call <quote>context</>,
- for example by
+ for example by:
<programlisting>
if (fcinfo->context && IsA(fcinfo->context, AggState))
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/xfunc.sgml,v 1.123 2007/01/31 20:56:20 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/xfunc.sgml,v 1.124 2007/02/01 00:28:18 momjian Exp $ -->
<sect1 id="xfunc">
<title>User-Defined Functions</title>
<para>
In practice one would probably like a more useful result from the
function than a constant 1, so a more likely definition
- is
+ is:
<programlisting>
CREATE FUNCTION tf1 (integer, numeric) RETURNS numeric AS $$
<para>
When creating a family of overloaded functions, one should be
careful not to create ambiguities. For instance, given the
- functions
+ functions:
<programlisting>
CREATE FUNCTION test(int, real) RETURNS ...
CREATE FUNCTION test(smallint, double precision) RETURNS ...
(usually the internal one). The alternative form of the
<literal>AS</> clause for the SQL <command>CREATE
FUNCTION</command> command decouples the SQL function name from
- the function name in the C source code. For instance,
+ the function name in the C source code. For instance:
<programlisting>
CREATE FUNCTION test(int) RETURNS int
AS '<replaceable>filename</>', 'test_1arg'
<para>
The version-1 calling convention relies on macros to suppress most
of the complexity of passing arguments and results. The C declaration
- of a version-1 function is always
+ of a version-1 function is always:
<programlisting>
Datum funcname(PG_FUNCTION_ARGS)
</programlisting>
- In addition, the macro call
+ In addition, the macro call:
<programlisting>
PG_FUNCTION_INFO_V1(funcname);
</programlisting>
</para>
<para>
- Suppose we want to write a function to answer the query
+ Suppose we want to write a function to answer the query:
<programlisting>
SELECT name, c_overpaid(emp, 1500) AS overpaid
<para>
Several helper functions are available for setting up the needed
<structname>TupleDesc</>. The recommended way to do this in most
- functions returning composite values is to call
+ functions returning composite values is to call:
<programlisting>
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo,
Oid *resultTypeId,
<para>
Older, now-deprecated functions for obtaining
- <structname>TupleDesc</>s are
+ <structname>TupleDesc</>s are:
<programlisting>
TupleDesc RelationNameGetTupleDesc(const char *relname)
</programlisting>
to get a <structname>TupleDesc</> for the row type of a named relation,
- and
+ and:
<programlisting>
TupleDesc TypeGetTupleDesc(Oid typeoid, List *colaliases)
</programlisting>
</para>
<para>
- Once you have a <structname>TupleDesc</>, call
+ Once you have a <structname>TupleDesc</>, call:
<programlisting>
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
</programlisting>
- if you plan to work with Datums, or
+ if you plan to work with Datums, or:
<programlisting>
AttInMetadata *TupleDescGetAttInMetadata(TupleDesc tupdesc)
</programlisting>
</para>
<para>
- When working with Datums, use
+ When working with Datums, use:
<programlisting>
HeapTuple heap_form_tuple(TupleDesc tupdesc, Datum *values, bool *isnull)
</programlisting>
</para>
<para>
- When working with C strings, use
+ When working with C strings, use:
<programlisting>
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
</programlisting>
<para>
Once you have built a tuple to return from your function, it
- must be converted into a <type>Datum</>. Use
+ must be converted into a <type>Datum</>. Use:
<programlisting>
HeapTupleGetDatum(HeapTuple tuple)
</programlisting>
<para>
An <acronym>SRF</> uses several functions and macros that
automatically manipulate the <structname>FuncCallContext</>
- structure (and expect to find it via <literal>fn_extra</>). Use
+ structure (and expect to find it via <literal>fn_extra</>). Use:
<programlisting>
SRF_IS_FIRSTCALL()
</programlisting>
to determine if your function is being called for the first or a
- subsequent time. On the first call (only) use
+ subsequent time. On the first call (only) use:
<programlisting>
SRF_FIRSTCALL_INIT()
</programlisting>
to initialize the <structname>FuncCallContext</>. On every function call,
- including the first, use
+ including the first, use:
<programlisting>
SRF_PERCALL_SETUP()
</programlisting>
</para>
<para>
- If your function has data to return, use
+ If your function has data to return, use:
<programlisting>
SRF_RETURN_NEXT(funcctx, result)
</programlisting>
to return it to the caller. (<literal>result</> must be of type
<type>Datum</>, either a single value or a tuple prepared as
described above.) Finally, when your function is finished
- returning data, use
+ returning data, use:
<programlisting>
SRF_RETURN_DONE(funcctx)
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/xindex.sgml,v 1.57 2007/01/31 20:56:20 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/xindex.sgml,v 1.58 2007/02/01 00:28:18 momjian Exp $ -->
<sect1 id="xindex">
<title>Interfacing Extensions To Indexes</title>
is to write the B-tree comparison support function first, and then write the
other functions as one-line wrappers around the support function. This
reduces the odds of getting inconsistent results for corner cases.
- Following this approach, we first write
+ Following this approach, we first write:
<programlisting>
#define Mag(c) ((c)->x*(c)->x + (c)->y*(c)->y)
}
</programlisting>
- Now the less-than function looks like
+ Now the less-than function looks like:
<programlisting>
PG_FUNCTION_INFO_V1(complex_abs_lt);
</para>
<para>
- We could have written the operator entries more verbosely, as in
+ We could have written the operator entries more verbosely, as in:
<programlisting>
OPERATOR 1 < (complex, complex) ,
</programlisting>
Normally, declaring an operator as a member of an operator class
(or family) means
that the index method can retrieve exactly the set of rows
- that satisfy a <literal>WHERE</> condition using the operator. For example,
+ that satisfy a <literal>WHERE</> condition using the operator. For example:
<programlisting>
SELECT * FROM table WHERE integer_column < 4;
</programlisting>
case there's not much value in storing the whole polygon in the index
entry — we might as well store just a simpler object of type
<type>box</>. This situation is expressed by the <literal>STORAGE</>
- option in <command>CREATE OPERATOR CLASS</>: we'd write something like
+ option in <command>CREATE OPERATOR CLASS</>: we'd write something like:
<programlisting>
CREATE OPERATOR CLASS polygon_ops
-<!-- $PostgreSQL: pgsql/doc/src/sgml/xoper.sgml,v 1.39 2007/01/31 20:56:20 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/xoper.sgml,v 1.40 2007/02/01 00:28:18 momjian Exp $ -->
<sect1 id="xoper">
<title>User-Defined Operators</title>
name, not an operator name.) <literal>RESTRICT</> clauses only make sense for
binary operators that return <type>boolean</>. The idea behind a restriction
selectivity estimator is to guess what fraction of the rows in a
- table will satisfy a <literal>WHERE</literal>-clause condition of the form
+ table will satisfy a <literal>WHERE</literal>-clause condition of the form:
<programlisting>
column OP constant
</programlisting>
name, not an operator name.) <literal>JOIN</> clauses only make sense for
binary operators that return <type>boolean</type>. The idea behind a join
selectivity estimator is to guess what fraction of the rows in a
- pair of tables will satisfy a <literal>WHERE</>-clause condition of the form
+ pair of tables will satisfy a <literal>WHERE</>-clause condition of the form:
<programlisting>
table1.column1 OP table2.column2
</programlisting>
-<!-- $PostgreSQL: pgsql/doc/src/sgml/xplang.sgml,v 1.33 2007/01/31 20:56:20 momjian Exp $ -->
+<!-- $PostgreSQL: pgsql/doc/src/sgml/xplang.sgml,v 1.34 2007/02/01 00:28:18 momjian Exp $ -->
<chapter id="xplang">
<title id="xplang-title">Procedural Languages</title>
linkend="app-createlang"> can be used to do this from the shell
command line. For example, to install the language
<application>PL/pgSQL</application> into the database
- <literal>template1</>, use
+ <literal>template1</>, use:
<programlisting>
createlang plpgsql template1
</programlisting>
</para>
<para>
- The command
+ The command:
<programlisting>
CREATE TRUSTED PROCEDURAL LANGUAGE plpgsql
HANDLER plpgsql_call_handler