Version 0 of Another simple database

Updated 2004-03-22 17:18:00

if 0 {Richard Suchenwirth 2004-03-22 - In A simple database, I showed how databases may be implemented with Tcl arrays. This take here is closer to traditional relational databases, with tables of pre-defined columns (modeled here as a list of lists, the first being the column heading, the rest the "records"), and mimicks the SQL SELECT statement a bit:}

 proc select {fields "from" tbl "where" condition} {
    set infields [lindex $tbl 0]
    if {$fields eq "*"} {set fields $infields}
    set res [list $fields]
    foreach inrow [lrange $tbl 1 end] {
        foreach $infields $inrow break
        if $condition {
            set row {}
            foreach field $fields {lappend row [set $field]}
            lappend res $row
        }
    }
    set res

} #-- Test data:

 set table {
    {number description pieces}
    {1234 Foo 100}
    {2345 Bar 50}
    {3456 Grill 2}
 }

if 0 {#-- Testing:

 % select * from $table where {$pieces < 100}
 {number description pieces} {2345 Bar 50} {3456 Grill 2}

 % select {pieces description} from $table where {$number != 1234}
 {pieces description} {50 Bar} {2 Grill}

Cute, ain't it? There is a danger though, if you happen to name a "database" column condition, row, fields, res or so... because the column names are used as variables, and could override the working variables.


Arts and crafts of Tcl-Tk programming }