#!/bin/sh
# Start Tclsh \
exec tclsh8.4 "$0" "$@"

package require Pgtcl

proc main {argc argv} {
	global	id_count
	global	db_cinfo
	global	tab_name
	global	db

	set id_count 1
	set tab_name [lindex $argv 0]
	set db_cinfo [lindex $argv 1]

	expr srand([clock clicks])

	db_connect
	if {[catch {db_exec "drop table $tab_name"} err]} {
		puts $err
	}
	if {[catch {db_exec "create table $tab_name (id int primary key, data text)"} err]} {
		puts $err
		db_disconnect
		exit 1
	}
	db_disconnect

	while {1} {
		db_connect

		while {1} {
			set n [expr int(rand() * 4) + 2]

			if {[catch {
					db_exec "start transaction"
					for {set i 0} {$i < $n} {incr i} {
						db_exec "insert into $tab_name values ([expr $id_count + $i], 'test data')"
					}
					db_exec "commit"
				} err]} {
				puts ""
				puts $err
				if {[regexp "duplicate key" $err]} {
					incr id_count
				}
				break
			}

			incr id_count $n
			puts -nonewline "$id_count rows done\r"
			flush stdout
		}
		puts ""

		db_disconnect
	}
}


proc db_exec {query} {
	global	db

	set res [pg_exec $db $query]
	if {"[pg_result $res -status]" != "PGRES_COMMAND_OK"} {
		set ret "[pg_result $res -status] [string trim [pg_result $res -error]]"
		pg_result $res -clear
		return -code error $ret
	} else {
		pg_result $res -clear
	}
}


proc db_connect {} {
	global	db_cinfo
	global	db

	while {1} {
		if {[catch {
				set db [pg_connect -conninfo $db_cinfo]
			} err]} {
			puts "connect: $err"
			after 2000
			continue
		}
		puts "connect: OK"
		return
	}
}


proc db_disconnect {} {
	global	db

	if {[catch {
			pg_disconnect $db
		} err]} {
		puts "disconnect: $err"
	} else {
		puts "disconnect: OK"
	}
}


main $argc $argv
