Module functions and constants

The pg module defines a few functions that allow to connect to a database and to define “default variables” that override the environment variables used by PostgreSQL.

These “default variables” were designed to allow you to handle general connection parameters without heavy code in your programs. You can prompt the user for a value, put it in the default variable, and forget it, without having to modify your environment. The support for default variables can be disabled by setting the -DNO_DEF_VAR option in the Python setup file. Methods relative to this are specified by the tag [DV].

All variables are set to None at module initialization, specifying that standard environment variables should be used.

connect – Open a PostgreSQL connection

pg.connect([dbname][, host][, port][, opt][, tty][, user][, passwd])

Open a pg connection

Parameters:
  • dbname – name of connected database (None = defbase)
  • host (str or None) – name of the server host (None = defhost)
  • port (int) – port used by the database server (-1 = defport)
  • opt (str or None) – connection options (None = defopt)
  • tty (str or None) – debug terminal (None = deftty)
  • user (str or None) – PostgreSQL user (None = defuser)
  • passwd (str or None) – password for user (None = defpasswd)
Returns:

If successful, the pgobject handling the connection

Return type:

pgobject

Raises:
  • TypeError – bad argument type, or too many arguments
  • SyntaxError – duplicate argument definition
  • pg.InternalError – some error occurred during pg connection definition
  • Exception – (all exceptions relative to object allocation)

This function opens a connection to a specified database on a given PostgreSQL server. You can use keywords here, as described in the Python tutorial. The names of the keywords are the name of the parameters given in the syntax line. For a precise description of the parameters, please refer to the PostgreSQL user manual.

Example:

import pg

con1 = pg.connect('testdb', 'myhost', 5432, None, None, 'bob', None)
con2 = pg.connect(dbname='testdb', host='localhost', user='bob')

get/set_defhost – default server host [DV]

pg.get_defhost(host)

Get the default host

Returns:the current default host specification
Return type:str or None
Raises:TypeError – too many arguments

This method returns the current default host specification, or None if the environment variables should be used. Environment variables won’t be looked up.

pg.set_defhost(host)

Set the default host

Parameters:host (str or None) – the new default host specification
Returns:the previous default host specification
Return type:str or None
Raises:TypeError – bad argument type, or too many arguments

This methods sets the default host value for new connections. If None is supplied as parameter, environment variables will be used in future connections. It returns the previous setting for default host.

get/set_defport – default server port [DV]

pg.get_defport()

Get the default port

Returns:the current default port specification
Return type:int
Raises:TypeError – too many arguments

This method returns the current default port specification, or None if the environment variables should be used. Environment variables won’t be looked up.

pg.set_defport(port)

Set the default port

Parameters:port (int) – the new default port
Returns:previous default port specification
Return type:int or None

This methods sets the default port value for new connections. If -1 is supplied as parameter, environment variables will be used in future connections. It returns the previous setting for default port.

get/set_defopt – default connection options [DV]

pg.get_defopt()

Get the default connection options

Returns:the current default options specification
Return type:str or None
Raises:TypeError – too many arguments

This method returns the current default connection options specification, or None if the environment variables should be used. Environment variables won’t be looked up.

pg.set_defopt(options)

Set the default connection options

Parameters:options (str or None) – the new default connection options
Returns:previous default options specification
Return type:str or None
Raises:TypeError – bad argument type, or too many arguments

This methods sets the default connection options value for new connections. If None is supplied as parameter, environment variables will be used in future connections. It returns the previous setting for default options.

get/set_deftty – default debug tty [DV]

pg.get_deftty()

Get the default debug terminal

Returns:the current default debug terminal specification
Return type:str or None
Raises:TypeError – too many arguments

This method returns the current default debug terminal specification, or None if the environment variables should be used. Environment variables won’t be looked up. Note that this is ignored in newer PostgreSQL versions.

pg.set_deftty(terminal)

Set the default debug terminal

Parameters:terminal (str or None) – the new default debug terminal
Returns:the previous default debug terminal specification
Return type:str or None
Raises:TypeError – bad argument type, or too many arguments

This methods sets the default debug terminal value for new connections. If None is supplied as parameter, environment variables will be used in future connections. It returns the previous setting for default terminal. Note that this is ignored in newer PostgreSQL versions.

get/set_defbase – default database name [DV]

pg.get_defbase()

Get the default database name

Returns:the current default database name specification
Return type:str or None
Raises:TypeError – too many arguments

This method returns the current default database name specification, or None if the environment variables should be used. Environment variables won’t be looked up.

pg.set_defbase(base)

Set the default database name

Parameters:base (str or None) – the new default base name
Returns:the previous default database name specification
Return type:str or None
Raises:TypeError – bad argument type, or too many arguments

This method sets the default database name value for new connections. If None is supplied as parameter, environment variables will be used in future connections. It returns the previous setting for default host.

get/set_defuser – default database user [DV]

pg.get_defuser()

Get the default database user

Returns:the current default database user specification
Return type:str or None
Raises:TypeError – too many arguments

This method returns the current default database user specification, or None if the environment variables should be used. Environment variables won’t be looked up.

pg.set_defuser(user)

Set the default database user

Parameters:user – the new default database user
Returns:the previous default database user specification
Return type:str or None
Raises:TypeError – bad argument type, or too many arguments

This method sets the default database user name for new connections. If None is supplied as parameter, environment variables will be used in future connections. It returns the previous setting for default host.

get/set_defpasswd – default database password [DV]

pg.get_defpasswd()

Get the default database password

Returns:the current default database password specification
Return type:str or None
Raises:TypeError – too many arguments

This method returns the current default database password specification, or None if the environment variables should be used. Environment variables won’t be looked up.

pg.set_defpasswd(passwd)

Set the default database password

Parameters:passwd – the new default database password
Returns:the previous default database password specification
Return type:str or None
Raises:TypeError – bad argument type, or too many arguments

This method sets the default database password for new connections. If None is supplied as parameter, environment variables will be used in future connections. It returns the previous setting for default host.

escape_string – escape a string for use within SQL

pg.escape_string(string)

Escape a string for use within SQL

Parameters:string (str) – the string that is to be escaped
Returns:the escaped string
Return type:str
Raises:TypeError – bad argument type, or too many arguments

This function escapes a string for use within an SQL command. This is useful when inserting data values as literal constants in SQL commands. Certain characters (such as quotes and backslashes) must be escaped to prevent them from being interpreted specially by the SQL parser. escape_string() performs this operation. Note that there is also a pgobject method with the same name which takes connection properties into account.

Note

It is especially important to do proper escaping when handling strings that were received from an untrustworthy source. Otherwise there is a security risk: you are vulnerable to “SQL injection” attacks wherein unwanted SQL commands are fed to your database.

Example:

name = raw_input("Name? ")
phone = con.query("select phone from employees where name='%s'"
    % escape_string(name)).getresult()

escape_bytea – escape binary data for use within SQL

pg.escape_bytea(datastring)

escape binary data for use within SQL as type bytea

Parameters:datastring (str) – string containing the binary data that is to be escaped
Returns:the escaped string
Return type:str
Raises:TypeError – bad argument type, or too many arguments

Escapes binary data for use within an SQL command with the type bytea. As with escape_string(), this is only used when inserting data directly into an SQL command string. Note that there is also a pgobject method with the same name which takes connection properties into account.

Example:

picture = open('garfield.gif', 'rb').read()
con.query("update pictures set img='%s' where name='Garfield'"
    % escape_bytea(picture))

unescape_bytea – unescape data that has been retrieved as text

pg.unescape_bytea(string)

Unescape bytea data that has been retrieved as text

Parameters:datastring (str) – the bytea data string that has been retrieved as text
Returns:byte string containing the binary data
Return type:str
Raises:TypeError – bad argument type, or too many arguments

Converts an escaped string representation of binary data into binary data – the reverse of escape_bytea(). This is needed when retrieving bytea data with one of the pgqueryobject.getresult(), pgqueryobject.dictresult() or pgqueryobject.namedresult() methods.

Example:

picture = unescape_bytea(con.query(
      "select img from pictures where name='Garfield'").getresult[0][0])
open('garfield.gif', 'wb').write(picture)

get/set_decimal – decimal type to be used for numeric values

pg.get_decimal()

Get the decimal type to be used for numeric values

Returns:the Python class used for PostgreSQL numeric values
Return type:class

This function returns the Python class that is used by PyGreSQL to hold PostgreSQL numeric values. The default class is decimal.Decimal if available, otherwise the float type is used.

pg.set_decimal(cls)

Set a decimal type to be used for numeric values

Parameters:cls (class) – the Python class to be used for PostgreSQL numeric values

This function can be used to specify the Python class that shall be used by PyGreSQL to hold PostgreSQL numeric values. The default class is decimal.Decimal if available, otherwise the float type is used.

get/set_decimal_point – decimal mark used for monetary values

pg.get_decimal_point()

Get the decimal mark used for monetary values

Returns:string with one character representing the decimal mark
Return type:str

This function returns the decimal mark used by PyGreSQL to interpret PostgreSQL monetary values when converting them to decimal numbers. The default setting is '.' as a decimal point. This setting is not adapted automatically to the locale used by PostGreSQL, but you can use set_decimal() to set a different decimal mark manually. A return value of None means monetary values are not interpreted as decimal numbers, but returned as strings including the formatting and currency.

New in version 4.1.1.

pg.set_decimal_point(string)

Specify which decimal mark is used for interpreting monetary values

Parameters:string (str) – string with one character representing the decimal mark

This function can be used to specify the decimal mark used by PyGreSQL to interpret PostgreSQL monetary values. The default value is ‘.’ as a decimal point. This value is not adapted automatically to the locale used by PostGreSQL, so if you are dealing with a database set to a locale that uses a ',' instead of '.' as the decimal point, then you need to call set_decimal(',') to have PyGreSQL interpret monetary values correctly. If you don’t want money values to be converted to decimal numbers, then you can call set_decimal(None), which will cause PyGreSQL to return monetary values as strings including their formatting and currency.

New in version 4.1.1.

get/set_bool – whether boolean values are returned as bool objects

pg.get_bool()

Check whether boolean values are returned as bool objects

Returns:whether or not bool objects will be returned
Return type:bool

This function checks whether PyGreSQL returns PostgreSQL boolean values converted to Python bool objects, or as 'f' and 't' strings which are the values used internally by PostgreSQL. By default, conversion to bool objects is not activated, but you can enable this with the set_bool() method.

New in version 4.2.

pg.set_bool(on)

Set whether boolean values are returned as bool objects

Parameters:on – whether or not bool objects shall be returned

This function can be used to specify whether PyGreSQL shall return PostgreSQL boolean values converted to Python bool objects, or as 'f' and 't' strings which are the values used internally by PostgreSQL. By default, conversion to bool objects is not activated, but you can enable this by calling set_bool(True).

New in version 4.2.

get/set_namedresult – conversion to named tuples

pg.get_namedresult()

Get the function that converts to named tuples

This returns the function used by PyGreSQL to construct the result of the pgqueryobject.namedresult() method.

New in version 4.1.

pg.set_namedresult(func)

Set a function that will convert to named tuples

Parameters:func – the function to be used to convert results to named tuples

You can use this if you want to create different kinds of named tuples returned by the pgqueryobject.namedresult() method. If you set this function to None, then it will become equal to pgqueryobject.getresult().

New in version 4.1.

Module constants

Some constants are defined in the module dictionary. They are intended to be used as parameters for methods calls. You should refer to the libpq description in the PostgreSQL user manual for more information about them. These constants are:

version, __version__

constants that give the current version

INV_READ, INV_WRITE

large objects access modes, used by pgobject.locreate() and pglarge.open()

SEEK_SET, SEEK_CUR, SEEK_END:

positional flags, used by pglarge.seek()