~aleteoryx/tclircc

ref: 7fdaa9361e04b0445c322ca41537ede6fc8bda72 tclircc/src/history.tcl -rw-r--r-- 1.2 KiB
7fdaa936Aleteoryx subcommand system 7 days ago
                                                                                
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
namespace eval hist {
  variable known_channels
}

# channel names can't contain spaces
proc hist::to_tablename {chan} {
  regsub {\\} $chan { s} chan
  regsub {"} $chan { q} chan
  return $chan
}

proc hist::ensure {db chan} {
  variable known_channels
  set chan [hist::to_tablename $chan]
  if [dict exists [set known_channels($db)] $chan] { return }

  if ![$db exists {SELECT * FROM sqlite_master WHERE type='table' AND name=$chan}] {
    $db eval "CREATE TABLE \"$chan\" (id TEXT NOT NULL PRIMARY KEY, src TEXT NOT NULL, msg TEXT NOT NULL, ts INTEGER NOT NULL, metadata TEXT NOT NULL);"
    $db eval "CREATE INDEX \"${chan}_src\" ON \"$chan\" (src);"
    $db eval "CREATE INDEX \"${chan}_ts\" ON \"$chan\" (ts);"
  }
  dict set known_channels($db) $chan {}

  set cleanup_script {}
  foreach chan [dict keys [set known_channels($db)]] {
    append cleanup_script "REINDEX \"$chan\"; REINDEX \"${chan}_src\"; REINDEX \"${chan}_ts\"; "
  }

  dict set ::db::autocleanup_steps $db $cleanup_script
}

proc hist::put {db chan source message timestamp metadata} {
  set chan [hist::to_tablename $chan]
  hist::ensure $db $chan
}

proc hist::open {db path} {
  variable known_channels
  sqlite3 $db $path
  set known_channels($db) {}
  lappend ::db::autocleanup_dbs $db
}