# copyright (C) 1997-2006 Jean-Luc Fontaine (mailto:jfontain@free.fr)
# this program is free software: please read the COPYRIGHT file enclosed in this package or use the Help Copyright menu

# $Id: myquery.tcl,v 2.31 2006/03/16 21:29:56 jfontain Exp $


package provide myquery [lindex {$Revision: 2.31 $} 1]
if {[catch {package require Thread 2.5}]} {
    package require mysqltcl
} else {                                               ;# use threads so that core is not blocked on connection problems with server
    package require stooop 4.1
    namespace import stooop::*
    package require threads 1
    namespace eval myquery {
        variable thread
        set thread(busy) 0
        set thread(worker) [new worker]
        worker::evaluate $thread(worker) {
            package require mysqltcl                                                                    ;# use a thread safe version
        }
    }
}


namespace eval myquery {

    array set data {
        updates 0
        0,label {} 0,type integer 0,message {row number in order of arrival}
        pollTimes {10 5 20 30 60 120 300}
        switches {--host 1 --password 1 --port 1 -q 1 --query 1 --swap 0 -t 1 --table 1 --user 1}
        persistent 1
        sort {0 increasing}
    }
    set file [open myquery.htm]
    set data(helpText) [read $file]                                                           ;# initialize HTML help data from file
    close $file
    if {[info exists thread]} {                     ;# show on last line of this module help window that we are running with threads
        regsub -nocase </body> $data(helpText) "<p><i>(currently running in threaded mode)</i>\n\\0" data(helpText)
    }

    proc initialize {optionsName} {
        upvar 1 $optionsName options
        variable thread
        variable connection
        variable data
        variable statement

        catch {set query $options(-q)}
        catch {set query $options(--query)}                                                                     ;# favor long option
        catch {set table $options(-t)}
        catch {set table $options(--table)}                                                                     ;# favor long option
        if {[info exists query] && [info exists table]} {
            error {use either table or query option but not both}
        }
        if {[info exists query]} {
            set statement $query
        } elseif {[info exists table]} {
            set statement "select * from $table"
        } else {
            error {either query (-q (--query)) or table (-t (--table)) must be specified}
        }
        if {[info exists options(--port)] && (![info exists options(--host)] || [string equal $options(--host) localhost])} {
            error {--port option useless with local socket connection (localhost as host)}
        }
        set arguments {}
        catch {lappend arguments -host $options(--host)}
        set user $::tcl_platform(user)                                                                                 ;# by default
        catch {set user $options(--user)}
        catch {lappend arguments -user $user}
        catch {lappend arguments -password $options(--password)}
        catch {lappend arguments -port $options(--port)}
        if {[info exists thread]} {
            set connection [worker::wait $thread(worker) "mysqlconnect $arguments"]                               ;# do not hang GUI
            set host [worker::evaluate $thread(worker) "lindex \[mysqlinfo $connection host\] 0"]
        } else {
            set connection [eval mysqlconnect $arguments]
            set host [lindex [mysqlinfo $connection host] 0]               ;# work around mysqltcl 3 return value: "host via TCP/IP"
        }
        set data(identifier) myquery($host)
        if {[info exists thread]} {
            worker::evaluate $thread(worker) "mysqlsel $connection [list $statement]"
            set lists [worker::evaluate $thread(worker) "mysqlcol $connection -current {name type length numeric decimals}"]
        } else {
            mysqlsel $connection $statement
            set lists [mysqlcol $connection -current {name type length numeric decimals}]
        }
        set column 1
        foreach list $lists {
            foreach {name type width numeric decimals} $list {}
            set data($column,label) $name
            if {$numeric} {
                set data($column,type) real                     ;# so that cell may be dropped in viewers that expect a numeric type
                if {$decimals > 0} {
                    set data($column,message) "$name (${type}([expr {$width-$decimals}].$decimals))"
                } else {
                    set data($column,message) "$name (${type}($width))"
                }
            } else {
                set data($column,type) ascii
                set data($column,anchor) left
                set data($column,message) "$name (${type}($width))"
            }
            incr column
        }
        if {[info exists options(--swap)]} {
            for {set index 0} {$index < $column} {incr index} {
                lappend indices $index
            }
            set data(views) [list [list indices $indices swap 1]]
        }
        if {[info exists thread]} {
            while {[llength [worker::evaluate $thread(worker) "mysqlnext $connection"]] > 0} {}
        } else {
            while {[llength [mysqlnext $connection]] > 0} {}
        }
    }

    proc update {} {
        variable thread

        if {[info exists thread]} {
            if {$thread(busy)} return
            set thread(busy) 1
        }
        query
    }

    proc query {{result {}} {errorInformation {}}} {
        variable thread
        variable connection
        variable statement
        variable data

        array unset data {[0-9]*,[0-9]*}                                                                    ;# clear data every time
        set error 0
        if {[info exists thread]} {
            if {[string length $result] == 0} {                                                        ;# launch query in background
                worker::evaluate $thread(worker) "mysqlsel $connection [list $statement]; list 1" myquery::query
                return                                       ;# this procedure is invoked back with a non-empty result (1) when done
            } elseif {[string length $errorInformation] > 0} {                                                   ;# an error occured
                set error 1
                set message $result
            }                                                                           ;# else the query was executed with no error
        } else {
            set error [catch {mysqlsel $connection $statement} message]
        }
        if {$error} {                                                                                     ;# problem reaching server
            flashMessage "error: $message"
        } else {
            set row 0
            while {1} {
                if {[info exists thread]} {
                    # no need for background work since the whole data is already in this client (mysql_store_result() used):
                    set list [worker::evaluate $thread(worker) "mysqlnext $connection"]
                } else {
                    set list [mysqlnext $connection]
                }
                if {[llength $list] == 0} break
                set data($row,0) $row
                set column 1
                foreach value $list {
                    set data($row,$column) $value
                    incr column
                }
                incr row
            }
        }
        if {[info exists thread]} {
            set thread(busy) 0
        }
        incr data(updates)
    }

    proc terminate {} {
        variable thread
        variable connection

        if {![info exists connection]} return                                        ;# connection may have failed in initialization
        if {[info exists thread]} {
            worker::evaluate $thread(worker) "mysqlclose $connection" list          ;# try to close connection while ignoring errors
            delete $thread(worker)
        } else {
            catch {mysqlclose $connection}
        }
    }

}
