Misc in PostgresSQL

Sequence

A serial-type column in a table, e.g.

create table os (
  id                            serial,
  ...

it is actually defined as

postgres=> \d os
                         Table "public.os"
 Column | Type | Modifiers
---------+-------------+-------------------------------------------------
 id      | integer     | not null default nextval('os_id_seq'::regclass)
 ...

That is, a sequence named <table>_<column>_seq is created implicitly.

Sequence is guaranteed to advance every time nextval() is called, even the update is canceled by rollback. So “holes” might be left. It won’t skip existing values either (for example, suppose id is a unique key, and a value is inserted before the sequence reaches that value, a unique violation will occur when the sequence advanced to the value). The best practice is never set serial directly. In some special cases, such as restore/copy data, always call setval() after the data are copied.

Here are sequence functions

Function Return Type Description
currval(regclass) bigint Return value most recently obtained with nextval for specified sequence
lastval() bigint Return value most recently obtained with nextval for any sequence
nextval(regclass) bigint Advance sequence and return new value
setval(regclass, bigint) bigint Set sequence’s current value
setval(regclass, bigint, boolean) bigint Set sequence’s current value and is_called flag

See details at PostgreSQL Document 9.16. Sequence Manipulation Functions

 

Password File

In a trusted environment, accessing database with password can be eliminated with saved password file. On Posix systems, it is $HOME/.pgpass, on Windows, it is %APPDATA%\postgresql\pgpass.conf.

The file contains lines of following format:

hostname:port:database:username:password

except password, the first 4 fields can be *, which matches anything.

The permission of .pgpass should be stricter than 0600, otherwise the file will be ignored. However the permission of pgpass.conf is not checked on Windows.

Reference: PostgreSQL Manual: 31.15. The Password File

Errors and Messages

RAISE statement is used to report message and raise error in SQL/PLSQL

RAISE [ level ] 'format' [, expression [, ... ]] [ USING option = expression [, ... ] ];
RAISE [ level ] condition_name [ USING option = expression [, ... ] ];
RAISE [ level ] SQLSTATE 'sqlstate' [ USING option = expression [, ... ] ];
RAISE [ level ] USING option = expression [, ... ];
RAISE ;

level

  • DEBUG
  • LOG
  • NOTICE
  • WARNING
  • EXCEPTION (default, which aborts the current transaction))

‘format’

Must be a string literal (not an expression), followed by optional arguments to be inserted into the message, where % is replaced by the string representation of arguments.

USING option

  • MESSAGE
  • DETAIL
  • HINT
  • ERRCODE
  • COLUMN, CONSTRAINT, DATATYPE, TABLE, SCHEMA

Common Error Codes

  • 02000 – no_data_found
  • 22000 – data_exception
  • 23000 – integrity_constraint_violation
  • 40000 – transaction_rollback
  • 42000 – syntax_error_or_access_rule_violation

Note:

  • although the name of 02000 is “no_data” in all versions of manual, the actual is no_data_found

Please check the full error code list

Detect No Data in PL/SQL

Example 1 (not reliable)

declare
    pid int;
begin
    select id into pid
    from table_foo
    where name='foo';
    -- not reliable, e.g. the value of id is null
    if pid is null then
        raise no_data_found
        using detail=format('name %s is not found', 'foo');
    end if;
end;

Example 2

begin
    update build
    set state='start'
    where name='foo';
    if not found then
        raise no_data_found
        using detail=format('name %s is not found', 'foo');
    end if;
end;

Trapping Errors in PL/SQL

[ <> ]
[ DECLARE
      DECLARATIONS ]
BEGIN
    statements
EXCEPTION
    WHEN condition [ OR condition ... ] THEN
        handler_statements
   [WHEN condition [ OR condition ...] THEN
        handler_statements
    ...]
END;

Here is an example that traps error for SELECT … INTO STRICT var. INTO STRICT means there is EXACTLY one row retrieved

BEGIN
    SELECT * INTO STRICT myrec FROM emp WHERE empname = myname;
EXCEPTION
    WHEN NO_DATA_FOUND THEN
        RAISE EXCEPTION 'employee % not found', myname;
    WHEN TOO_MANY_ROWS THEN
        RAISE EXCEPTION 'employee % not unique', myname;
END;

Here are some examples of condition

WHEN division_by_zero THEN ...
WHEN SQLSTATE '22012' THEN ...

Advertisements