File: dio_Tdbc.tcl

package info (click to toggle)
libapache2-mod-rivet 3.2.8-1
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 6,392 kB
  • sloc: tcl: 9,156; xml: 8,617; ansic: 7,071; sh: 5,040; makefile: 223; sql: 91; lisp: 78
file content (389 lines) | stat: -rw-r--r-- 13,608 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# tdbc.tcl -- connector for tdbc, the Tcl database abstraction layer
#
# Copyright 2024 The Apache Software Foundation
#
#    Licensed to the Apache Software Foundation (ASF) under one
#    or more contributor license agreements.  See the NOTICE file
#    distributed with this work for additional information
#    regarding copyright ownership.  The ASF licenses this file
#    to you under the Apache License, Version 2.0 (the
#    "License"); you may not use this file except in compliance
#    with the License.  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing,
#    software distributed under the License is distributed on an
#    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
#    KIND, either express or implied. See the License for the
#    specific language governing permissions and limitations
#    under the License.

package require tdbc
package require DIO      1.2.3
package provide dio_Tdbc 1.2.5

namespace eval DIO {
    ::itcl::class Tdbc {
        inherit Database

        private common   connector_n    -1
        private variable connector
        private variable connector_name
        private variable tdbc_connector
        private variable tdbc_arguments [list -encoding     \
                                              -isolation    \
                                              -readonly     \
                                              -timeout]

        constructor {interface_name args} {eval configure -interface $interface_name $args} {
            set connector   ""

            # I should check this one: we only accept connector
            # interfaces that map into one of tdbc's supported drivers
            #puts "tdbc interface: $interface_name"

            set connector_name [::string tolower $interface_name]
            switch $connector_name {
                "oracle" {
                    set connector_name "odbc"
                } 
                "postgresql" {
                    set connector_name "postgres"
                }
                "sqlite" {
                    set connector_name "sqlite3"
                }
                "mariadb" {
                    set connector_name "mysql"
                }
                "sqlite3" -
                "odbc" -
                "postgres" -
                "mysql" {
                    # OK
                }
                default {
                    return -code error -errorcode invalid_tdbc_driver "Invalid TDBC driver '$connector_name'"
                }
            }

            set interface $connector_name
            $this set_field_formatter ::DIO::formatters::[::string totitle $interface]
            set tdbc_connector "tdbc::${interface}"

            uplevel #0 package require ${tdbc_connector}
        }

        destructor { }

        private method check_connector {} {
            if {$connector == ""} { open }
        }

        public method tdbc_connector {} { return $connector }

        public method open {}  {
            set connector_cmd "${tdbc_connector}::connection create ${tdbc_connector}#[incr connector_n]"
            if {$user != ""} { lappend connector_cmd -user      $user }
            if {$db   != ""} {
                if {$connector_name == "sqlite3"} {
                    lappend connector_cmd $db
                } else {
                    lappend connector_cmd -db $db
                }
            }
            if {$pass != ""} { lappend connector_cmd -password  $pass }
            if {$port != ""} { lappend connector_cmd -port      $port }
            if {$host != ""} { lappend connector_cmd -host      $host }

            if {$clientargs != ""} { lappend connector_cmd {*}$clientargs }

            set connector [eval $connector_cmd]
            incr connector_n
        }

        public method close {} {
            if {$connector == ""} { return }
            $connector close
            set connector ""
        }

        protected method handle_client_arguments {cargs} {
            set clientargs {}
            lmap {k v} $cargs {
                if {[lsearch $k $tdbc_arguments] >= 0} {
                    lappend clientargs $k $v
                }
            }
        }

        public method tdbc_exec {sql sql_values_d {results_v ""}} {

            $this check_connector
            if {[::string index $sql end] == ";"} {set sql [::string range $sql 0 end-1]}

            set is_select [regexp -nocase {^\(*\s*select\s+} $sql]
            set tdbc_statement [$connector prepare $sql]

            #puts "--> $sql_values"
            if {[catch {set tdbc_result [$tdbc_statement execute $sql_values_d]} e errorinfo]} {
                $tdbc_statement close
                return -code error -errorinfo [::list $errorinfo]
            } else {

                # we must store also the TDBC SQL statement as it owns
                # the TDBC results set represented by tdbc_result. Closing
                # a tdbc::statement closes also any active tdbc::resultset
                # owned by it

                set result_obj [$this result TDBC -resultid   $tdbc_result      \
                                                  -statement  $tdbc_statement   \
                                                  -isselect   $is_select        \
                                                  -fields     [::list [$tdbc_result columns]]] 
            }

            # this doesn't work on postgres, you've got to use cmdRows,
            # we need to figure out what to do with this

            set numrows [$result_obj numrows]
            if {$is_select && ($numrows > 0) && ($results_v != "")} {
                upvar 1 $results_v results_o
                set results_o $result_obj
            } else {
                $result_obj destroy
            }
            return $numrows

        }


        # delete -
        #
        #

        method delete {key args} {
            table_check $args

            set sql "DELETE FROM $myTable"
            set sql_values_d [dict create]
            if {[$special_fields_formatter has_special_fields $table]} {
                append sql [build_key_where_clause $myKeyfield $key]
            } else {
                set where_key_value_pairs [lmap field $myKeyfield {
                    set v "${field}=:${field}"
                }]
                set sql "$sql WHERE [join $where_key_value_pairs { AND }]"
                foreach field $myKeyfield k $key { dict set sql_values_d $field $k }
            }

            #puts $sql

            return [$this tdbc_exec $sql $sql_values_d]
        }


        #
        # update - reimplementation of the ::DIO::Database::update
        # method that is supposed to exploit the named arguments
        # feature of TDBC. 
        #
        method update {arrayName args} {
            upvar 1 $arrayName row_a
            $this table_check $args

            # myTable is implicitly set by table_check
            
            $this configure -table $myTable
            set key [makekey row_a $myKeyfield]

            #puts "-> table: $table"
            #puts "-> key: $key"
            #puts "-> keyfield: $myKeyfield"

            set sql_values_d [dict create {*}[::array get row_a]] 
            set fields     [::array names row_a]
            if {[$special_fields_formatter has_special_fields $table]} {

                # the special fields formatter is fundamentally incompatible with
                # TDBC's named arguments mechanism. We resort to the superclass method
                # where a literal SQL statement is built

                set sql     [$this build_update_query row_a $fields $table]
                append sql  [$this build_key_where_clause $myKeyfield $key]

            } else {

                set set_key_value_pairs [lmap field $fields {
                    set v "${field}=:${field}"
                }]
                set where_key_value_pairs [lmap field $myKeyfield {
                    set v "${field}=:${field}"
                }]

                ::lappend where_key_value_pairs "1 = 1"
                set sql [join [::list "UPDATE $table" \
                                      "SET   [join $set_key_value_pairs {, }]" \
                                      "WHERE [join $where_key_value_pairs { AND }]"] " "]

            }

            #puts $sql
            return [$this tdbc_exec $sql $sql_values_d]
        }

        #
        # insert - 
        #
        # overriding method 'insert' as in case of registered special fields
        # we have to give up with the idea of using the named arguments approach
        #
        method insert {table arrayName} {
            upvar 1 $arrayName row_a

            set sql_values_d [dict create {*}[::array get row_a]]
            set fields     [::array names row_a]
            if {[$special_fields_formatter has_special_fields $table]} {
                set sql [build_insert_query row_a [::array names row_a] $table]
            } else {
                set values [lmap field $fields { set v ":${field}" }]

                set sql "INSERT INTO $table ([join $fields {,}]) VALUES ([join $values {,}])"
            }

            #puts $sql
            #puts $sql_values_d
            return [$this tdbc_exec $sql $sql_values_d]

        }

        # fetch
        #
        #

        method fetch {key arrayName args} {
            upvar 1 $arrayName row_a
            table_check $args
            key_check $myKeyfield $key

            $this configure -table $myTable
            set sql_values_d [dict create]
            set sql "SELECT * FROM $myTable"
            if {[$special_fields_formatter has_special_fields $table]} {
                append sql [build_key_where_clause $myKeyfield $key]
            } else {
                set where_key_value_pairs [lmap field $myKeyfield {
                    set v "${field}=:${field}"
                }]
                set sql "$sql WHERE [join $where_key_value_pairs { AND }]"
                foreach field $myKeyfield k $key { 
                    if {$field == ""} { continue }
                    dict set sql_values_d $field $k
                }
            }

            #puts $sql
            set numrows [$this tdbc_exec $sql $sql_values_d result_o]
            if {$numrows > 0} {
                $result_o next -array row_a
                $result_o destroy
            }
            return $numrows
        }

        #
        # exec
        #
        #

        public method exec {sql} {
            $this check_connector

            # tdbc doesn't like ';' at the end of a SQL statement

            if {[::string index $sql end] == ";"} {set sql [::string range $sql 0 end-1]}
            set is_select [regexp -nocase {^\(*\s*select\s+} $sql]

            set tdbc_statement [uplevel 1 $connector prepare [::list $sql]]

            # errorinfo is a public variable of the parent class Database.
            # Not a good object design practice

            if {[catch {set tdbc_result [uplevel 1 $tdbc_statement execute]} e errorinfo]} {
                set result_obj [$this result TDBC -error 1 -errorinfo [::list $errorinfo] -isselect false]
            } else {

                # we must store also the TDBC SQL statement as it owns
                # the TDBC results set represented by tdbc_result. Closing
                # a tdbc::statement closes also any active tdbc::resultset
                # owned by it

                set result_obj [$this result TDBC -resultid   $tdbc_result      \
                                                  -statement  $tdbc_statement   \
                                                  -isselect   $is_select        \
                                                  -fields     [::list [$tdbc_result columns]]] 
            }

            return $result_obj
        }

    }

    ::itcl::class TDBCResult {
        inherit Result
        public variable     isselect false
        public variable     statement

        public variable     rowid
        public variable     cached_rows
        public variable     columns

        constructor {args} { 
            eval configure  $args
            set cached_rows {}
            set columns     {}
            set rowid       0
            set rownum      0
            set statement   ""
        }
        destructor {}

        public method destroy {} {
            if {$statement != ""} { $statement close }

            Result::destroy
        }

        public method current_row {} { return $rowid }
        public method cached_results {} { return $cached_rows }

        public method nextrow {} {
            if {[llength $cached_rows] == 0} {
                if {![$resultid nextrow -as lists row]} {
                    return ""
                }
            } else {
                set cached_rows [lassign $cached_rows row]
            }
            incr rowid
            return $row
        }

        public method numrows {} {
            if {$isselect} {

                # this is not scaling well at all but tdbc is not telling
                # the number of columns for a select so must determine it
                # from the whole set of results

                if {[llength $cached_rows] == 0} {
                    set cached_rows [$resultid allrows -as lists -columnsvariable columns]
                }
                return [expr [llength $cached_rows] + $rowid]
            } else {
                return [$resultid rowcount]
            }
        }

    }
}