5.5. Example - Large Objects - Picture Viewer, Part 1 - Store Pictures

This example is the first part of a GIF picture viewer which stores the images as large objects in the database. Given pairs of identifiers (arbitrary names used as keys) and filenames on the command line, it inserts the contents of each file into the database as a large object, and inserts a record in a table to allow retrieving the large object using the provided identifier as the key.

See Section 5.6, “Example - Large Objects - Picture Viewer, Part 2 - View Pictures” for the program used to view the pictures. A different implementation using bytea fields instead of large objects can be found in Section 5.7, “Example - Prepared Queries - Picture Viewer, Part 1 - Store Pictures”. and Section 5.9, “Example - Bytea Escaping - Picture Viewer, Part 1 - Store Pictures”.

The schema is created automatically if the table is not found. This method wouldn't normally be used in production, though. The example assumes database connection information is provided through the environment.

Example 5.12. Large Objects - Store Pictures in Database

# Example - picture storage as Large Object - importer

package require Pgtcl

# Build the table schema:
proc build {conn} {
    pg_execute $conn "CREATE TABLE pics (pname TEXT PRIMARY KEY, poid OID)"

# Insert file 'file' into the database with key 'name':
# If an error occurs, throws a Tcl error.
proc insert_file {conn name file } {
    set qname [pg_escape_string $name]
    pg_execute $conn BEGIN
    if {[catch {
        set oid [pg_lo_import $conn $file]
        pg_execute $conn "INSERT INTO pics (poid, pname) VALUES ($oid, '$qname')"
    } msg]} {
        pg_execute $conn ROLLBACK
        error "Error importing large object: $msg"
    pg_execute $conn COMMIT

if {$argc < 2 || $argc % 2 != 0} {
    puts stderr "Usage: insert_picture name filename \[name filename\]..."
    exit 1

# Connect to the database.
set conn [pg_connect -conninfo ""]

# Check for table:
if {[catch {pg_execute $conn "SELECT COUNT(*) AS n FROM pics"} msg]} {
     puts "Note: unable to select from table. Let's try creating it."
     build $conn

# Insert all the pictures named on the command line:
foreach {name filename} $argv {
    if {[catch {insert_file $conn $name $filename} message]} {
        puts "$filename NOT inserted: $message"
    } else {
        puts "$filename inserted OK as '$name'"

pg_disconnect $conn

SourceForge.net Logo

This version of the manual was produced for the Pgtcl-ng Sourceforge project web service site, which requires the logo on each page.

To download a logo-free copy of the manual, see the Pgtcl-ng project downloads area.