Updated 2011-07-10 22:45:01 by RLE

Richard Suchenwirth 2002-02-18 - Tcl arrays can be used for implementing a simple database. Here is an "API" that wraps typical accesses, which I originally needed for Tclworld, but it's general enough to be factored out. Let's start with the


  • db name -- declare a database (no harm if repeated)
  • name -- returns all defined keys in no particular order
  • name {} -- clears the whole database
  • name key -- returns all item/value pairs associated with key
  • name key "" -- removes entry key from database
  • name key item -- returns the value for item of key
  • name key item value... -- sets item of key to value

Pretty abstract, but very concise - it's amazing how much functionality can be expressed with a keyword-less language (if you except the initial db), just controlled by the number of arguments. Examples:
 db geo::info
 geo::info Hamburg pop 1234560
 geo::info Hamburg it: Amburgo
 geo::info             ;#=> Hamburg
 geo::info Hamburg     ;#=> pop 1234560 it: Amburgo
 geo::info Hamburg pop ;#=> 1234560
 #-- The code:
 proc db {database args} {
    upvar #0 $database db
    set key "" ;# in case args is empty
    foreach {- key item value} $args break
    set exists [info exists db($key)]
    set res {}
    switch [llength $args] {
        0 {
            array set db {} ;# force to be an array
            interp alias {} $database {} db $database -
            set res $database
        1 {set res [array names db]}
        2 {if {$key != ""} {
                if {$exists} {set res $db($key)}
           } else {array unset db}
        3 {if {$item != ""} {
                if {$exists} {
                    set t $db($key)
                    if {!([set pos [lsearch $t $item]]%2)} {
                        set res [lindex $t [incr pos]]
           } elseif {$exists} {unset db($key)}
        4 {
            if {$exists} {
                if {!([set pos [lsearch $db($key) $item]]%2)} {
                    if {$value != ""} {
                      set db($key) [lreplace $db($key) [incr pos] $pos $value]
                    } else {set db($key) [lreplace $db($key) $pos [incr pos]]}
                } elseif {$value != ""} {
                    lappend db($key) $item $value
            } elseif {$value != ""} {set db($key) [list $item $value]}
            set res $value ;# to be returned
        default {
            if {[llength $args]%2} {error "non-paired item/value list"}
            foreach {item value} [lrange $args 2 end] {
                db $database - $key $item $value
    set res
 #-- Self-test, if this file is sourced as toplevel script: 
 if {[file tail $argv] eq [file tail [info script]]} {
    foreach test [split {
        db Test
        Test Hamburg pop 1234560 cn: Hanbao
        Test Hamburg it: Amburgo
        Test  ;#=> Hamburg
        Test Hamburg ;#=> pop 1234560 it: Amburgo
        Test Hamburg pop ;#=> 1234560
    } \n] {
        puts -nonewline "$test --> " 
        puts [eval $test]

Here's another example, mined off the Web, reformatted to suit the Tclworld database:
 interp alias {} + {} $db ;# hide the real database name

 + Alabama : {state of the USA} abbr AL capital Montgomery nick {Yellow Hammer State} bird {Yellow Hammer} flower Camelia tree {Southern Pine}
 + Alaska : {state of the USA} abbr AK capital Juneau nick {Last Frontier} bird {Willow Ptarmigan} flower Forget-Me-Not tree {Sitka Spurce}
 + Arizona : {state of the USA} abbr AZ capital Phoenix nick {Grand Canyon State} bird {Cactus Wren} flower {Saguaro (Giant Cactus)} tree Paloverde
 + Arkansas : {state of the USA} abbr AR capital {Little Rock} nick {Land of Opportunity} bird Mockingbird flower {Apple Blossom} tree Pine
 + California : {state of the USA} abbr CA capital Sacremento nick {Golden State} bird {California Valley Quail} flower {Golden Poppy} tree {California Redwood}
 + Colorado : {state of the USA} abbr CO capital Denver nick {Centennial State} bird {Lark Bunting} flower {Rocky Mtn. Columbine} tree {Blue Spruce}
 + Connecticut : {state of the USA} abbr CT capital Hartford nick {Constitution State} bird Robin flower {Mountain Laurel} tree {White Oak}
 + Delaware : {state of the USA} abbr DE capital Dover nick {First State} bird {Blue Hen Chicken} flower {Peach Blossom} tree {American Holly}
 + Florida : {state of the USA} abbr FL capital Tallahasse nick {Sunshine State} bird Mockingbird flower {Orange Blossom} tree {Cabbage (Sabal) Palm}
 + Georgia(US) : {state of the USA} abbr GA capital Atlanta nick {Empire State of the South} bird {Brown Thrasher} flower {Cherokee Rose} tree {Live Oak}
 + Hawaii : {state of the USA} abbr HI capital Honolulu nick {Aloha State} bird {Nene (Hawaiian Goose)} flower Hibiscus tree Kukui
 + Idaho : {state of the USA} abbr ID capital Boise nick {Gem State} bird {Mountain Bluebird} flower Syringa tree {Western White pine}
 + Illinois : {state of the USA} abbr IL capital Springfield nick {Land of Lincoln} bird Cardinal flower {Native Violet} tree {White Oak}
 + Indiana : {state of the USA} abbr IN capital Indianapolis nick {Hossier State} bird Cardinal flower Peony tree {Tulip Tree or Yellow Poplar}
 + Iowa : {state of the USA} abbr IA capital {Des Moines} nick {Hawkeye State} bird {Eatern Goldfinch} flower {Wild Rose} tree Oak
 + Kansas : {state of the USA} abbr KS capital Topeka nick {Sunflower State} bird {Western Medowlark} flower Sunflower tree Cottonwood
 + Kentucky : {state of the USA} abbr KY capital Frankfort nick {Bluegrass State} bird {Kentucky Cardinal} flower Goldenrod tree {Kentucky Coffeetree}
 + Louisana : {state of the USA} abbr LA capital {Baton Rouge} nick {Pelican State} bird {Brown Pelican} flower Magnolia tree {Bald Cypress}
 + Maine : {state of the USA} abbr ME capital Augusta nick {Pine Tree State} bird Chickadee flower {White Pine Cone & Tassel} tree {White Pine}
 + Maryland : {state of the USA} abbr MD capital Annapolis nick {Old Line State} bird {Baltimore Oriole} flower {Black-Eyed Susan} tree {White Oak (wye oak)}
 + Massachusetts : {state of the USA} abbr MA capital Boston nick {Bay State} bird Chickadee flower Mayflower tree {American Elm}
 + Michigan : {state of the USA} abbr MI capital Lansing nick {Wolverine State} bird Robin flower {Apple Blossom} tree {White Pine}
 + Minnesota : {state of the USA} abbr MN capital {St. Paul} nick {Gopher State} bird {Common Loon} flower {Pink White Lady's-Slipper} tree {Norway, or Red Pine}
 + Mississippi : {state of the USA} abbr MS capital Jackson nick {Magnolia State} bird Mockingbird flower Magnolia tree Magnolia
 + Missouri : {state of the USA} abbr MO capital {Jefferson City} nick {Show Me State} bird Bluebird flower Hawthorn tree {Flowering Dogwood}
 + Montana : {state of the USA} abbr MT capital Helena nick {Treasure State} bird {Western Meadowlark} flower Bitterroot tree {Ponderosa Pine}
 + Nebraska : {state of the USA} abbr NE capital Lincoln nick {Cornhusker State} bird {Western Meadowlark} flower Goldenrod tree Cottonwood
 + Nevada : {state of the USA} abbr NV capital {Carson City} nick {Silver State} bird {Mountain Bluebird} flower Sagebrush tree {Single-Leaf Pinon}
 + {New Hampshire} : {state of the USA} abbr NH capital Concord nick {Granite State} bird {Purple Finch} flower {Purple Lilac} tree {White Birch}
 + {New Jersey} : {state of the USA} abbr NJ capital Trenton nick {Garden State} bird {Eastern Goldfinch} flower {Purple Violet} tree {Red Oak}
 + {New Mexico} : {state of the USA} abbr NM capital {Santa Fe} nick {Land of Enrichment} bird Roadrunner flower {Yucca Flower} tree {Pinon, or Nut Pine}
 + {New York} : {state of the USA} abbr NY capital Albany nick {Empire State} bird Bluebird flower Rose tree {Sugar Maple}
 + {North Carolina} : {state of the USA} abbr NC capital Raleigh nick {Tar Heel State} bird Cardinal flower {Flowering Dogwood} tree Pine
 + {North Dakota} : {state of the USA} abbr ND capital Bismarck nick {Flickertail State} bird {Western Meadowlark} flower {Wild Prarie Rose} tree {American Elm}
 + Ohio : {state of the USA} abbr OH capital Columbus nick {Buckeye State} bird Cardinal flower {Scarlet Carnation} tree Buckeye
 + Oklahoma : {state of the USA} abbr OK capital {Oklahoma City} nick {Sooner State} bird {Scissor-tailed Flycatcher} flower Mistletoe tree Redbud
 + Oregon : {state of the USA} abbr OR capital Salem nick {Beaver State} bird {Western Meadowlark} flower {Oregon Grape} tree Douglas-Fir
 + Pennsylvania : {state of the USA} abbr PA capital Harrisburg nick {Keystone State} bird {Ruffed Grouse} flower {Carolina Jessamine} tree Palmetto
 + {Rhode Island} : {state of the USA} abbr RI capital Providence nick {Ocean State} bird {Rhode Island Red} flower Violet tree {Red Maple}
 + {South Carolina} : {state of the USA} abbr SC capital Columbia nick {Palmetto State} bird {Carolina Wren} flower {Carolian Jessamine} tree Palmetto
 + {South Dakota} : {state of the USA} abbr SD capital Pierre nick {Sunshine State} bird {Ring-Necked Pheasant} flower {American Pasqueflower} tree {Black Hills Spruce}
 + Tennessee : {state of the USA} abbr TN capital Nashville nick {Volunteer State} bird Mockingbird flower Iris tree {Tulip Poplar}
 + Texas : {state of the USA} abbr TX capital Austin nick {Lone Star State} bird Mockingbird flower Bluebonnet tree Pecan
 + Utah : {state of the USA} abbr UT capital {Salt Lake City} nick {Beehive State} bird {Sea Gull} flower {Sego Lily} tree {Blue Spruce}
 + Vermont : {state of the USA} abbr VT capital Montpelier nick {Green Mountain State} bird {Hermit Thrush} flower {Red Clover} tree {Sugar Maple}
 + Virginia : {state of the USA} abbr VA capital Richmond nick {Old Dominion} bird Cardinal flower Dogwood tree Dogwood
 + Washington : {state of the USA} abbr WA capital Olympia nick {Evergeen State} bird {Willow Goldfinch} flower {Coast Rhododendron} tree {Western Hemlock}
 + {West Virginia} : {state of the USA} abbr WV capital Charleston nick {Mountain State} bird Cardinal flower Rhododendron tree {Sugar Maple}
 + Wisconsin : {state of the USA} abbr WI capital Madison nick {Badger State} bird Robin flower {Wood Violet} tree {Sugar Maple}
 + Wyoming : {state of the USA} abbr WY capital Cheyenne nick {Equality State} bird Meadowlark flower {Indian Paintbrush} tree Cottoonwood

TV Let's hope lots of reasonably-formatted xml downloads become available to provide a huge, world-wide data repository of interesting data for using things like this.

Years ago I also did a 'basic db' with self-adapting ui for a limited number of data elements per page: Database routines for in core and via the link on page [1].

DKF: Neat. Anyone wrapped up LDAP behind this yet? ;^)

RJ Now that's what I'm talking about! We can all be thankful that Richard chooses to use his powers for good.

LV Apparently the above code is referred to as dpapi.tcl in a little database gui.

See also A little database GUI