File: MySQL.pike

package info (click to toggle)
pike8.0 8.0.1956-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 60,580 kB
  • sloc: ansic: 259,734; xml: 36,320; makefile: 3,748; sh: 1,713; cpp: 1,349; awk: 1,036; lisp: 655; javascript: 468; asm: 242; objc: 240; pascal: 157; sed: 34
file content (194 lines) | stat: -rw-r--r-- 5,902 bytes parent folder | download | duplicates (2)
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

//! An SQL-based storage manager
//!
//! This storage manager provides the means to save data to an SQL-based 
//! backend.
//!
//! For now it's mysql only, dialectization will be added at a later time.
//! Serialization should be taken care of by the low-level SQL drivers.
//!
//! @note
//!   An administrator is supposed to create the database and give
//!   the user enough privileges to write to it. It will be care
//!   of this driver to create the database tables itself.
//!
//! @thanks
//!   Thanks to Francesco Chemolli <kinkie@@roxen.com> for the contribution.

#pike __REAL_VERSION__

inherit Cache.Storage.Base;

#define MAX_KEY_SIZE "255"
#define CREATION_QUERY "create table cache ( \
cachekey varchar(" MAX_KEY_SIZE ") not null primary key, \
atime timestamp, \
ctime timestamp, \
etime timestamp, \
cost float unsigned DEFAULT 1.0 NOT NULL, \
data longblob NOT NULL, \
dependants longblob \
)"

Sql.Sql db;
int have_dependants=0;

#if 0                           // set to 1 to enable debugging
#ifdef debug
#undef debug
#endif // ifdef debug
#define debug(X...) werror("Cache.Storage.mysql: "+X);werror("\n")
#else  // 1
#ifndef debug                   // if there's a clash, let's let it show
#define debug(X...) /**/
#endif // ifndef debug
#endif // 1


//! Database manipulation is done externally. This class only returns
//! values, with some lazy decoding.
class Data {
  inherit Cache.Data;
  private int _size;
  private string db_data;
  private mixed _data;

  void create (mapping q) {
    debug("instantiating data object from %O",q);
    db_data=q->data;
    _size=sizeof(db_data);
    atime=(int)q->atime;
    ctime=(int)q->ctime;
    etime=(int)q->etime;
    cost=(float)q->cost;
  }

  int size() {
    debug("object size requested");
    return _size;
  }

  mixed data() {
    debug("data requested");
    if (_data)
      return _data;
    debug("lazy-decoding data");
    _data=decode_value(db_data);
    db_data=0;
    return _data;
  }
}
//does MySQL support multiple outstanding resultsets?
//we'll know now.
//Notice: this will fail miserably with Sybase, for instance.
//Notice: can and will throw exceptions if anything fails.
private object(Sql.sql_result) enum_result;
int(0..0)|string first() {
  debug("first()");
  if (enum_result)
    destruct(enum_result);
  enum_result=db->big_query("select cachekey from cache");
  return next();
}

int(0..0)|string next() {
  debug("next()");
  array res;
  if (!enum_result)
    return 0;
  if (res=enum_result->fetch_row())
    return res[0];
  enum_result=0;                // enumeration finished
  return 0;  
}

//unfortunately with MySQL we can't optimize much,
//if we want to properly follow the dependencies chain.
//also, we're taking the easy way out using encode_value rather than
// SQL tables. With other databases it would be easier to use
// SQL-related functions rather than doing stuff ourselves (and
// performing plenty of queries).
// I'll try to use a local cache to avoid multiple deletions for
// the same value, since queries are expensive. It could prove
// to be a problem for HUGE caches. Let's hope it won't happen..
void delete(string key, void|int(0..1) hard, void|multiset already_deleted) {
  multiset dependants=0;
  
  debug("deleting %s\n",key);
  if (have_dependants) {
    if (already_deleted && already_deleted[key]) // already deleted. Skip
      return;
    mixed rv=db->query("select dependants from cache where cachekey=%s",key);
    if (rv && sizeof(rv) && rv[0]->dependants) { // there are dependants
      dependants=decode_value(rv[0]->dependants);
    }
    if (!already_deleted) already_deleted=(<>);
  }
  
  if (already_deleted) already_deleted[key]=1;
  db->query("delete from cache where cachekey=%s",key);
  
  if (dependants) {
    foreach (indices(dependants),string dep) {
      werror("chain-deleting %s\n",dep);
      delete(dep);
    }
    werror("done chain-deleting\n");
  }
}

void set(string key, mixed value,
         void|int expire_time, void|float preciousness,
         void|multiset(string) dependants) {
  debug("setting value for key %s (e: %d, v: %f",key,expire_time,
        preciousness?preciousness:1.0);
  db->query("delete from cache where cachekey=%s",key);
  db->query("insert into cache "
            "(cachekey,atime,ctime,etime,cost,data, dependants) "
            "values(%s,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,%s,%s,%s,%s)",
            key,
            (expire_time?db->encode_datetime(expire_time):UNDEFINED),
            (preciousness?(string)preciousness:"1"),
            encode_value(value),
            (dependants?encode_value(dependants):UNDEFINED)
            //BUG: this fails when there are no dependants.
            );
  if (dependants)
    have_dependants=1;
}

int(0..0)|Cache.Data get(string key,void|int notouch) {
  debug("getting value for key %s (nt: %d)",key,notouch);
  array(mapping) result=0;
  mixed err=0;
  catch (result=db->query("select unix_timestamp(atime) as atime,"
                          "unix_timestamp(ctime) as ctime,"
                          "unix_timestamp(etime) as etime,cost,data "
                          "from cache where cachekey=%s", key));
  if (!result || !sizeof(result))
    return 0;
  if (!notouch)
    catch(db->query("update cache set atime=CURRENT_TIMESTAMP "
                    "where cachekey=%s", key));
  return Data(result[0]);
}

void aget(string key,
          function(string,int(0..0)|Cache.Data:void) callback) {
  callback(key,get(key));
}


//!
void create(string sql_url) {
  array result=0;
  mixed err=0;
  db=Sql.Sql(sql_url);
  // used to determine whether there already is a DB here.
  err=catch(result=db->query("select stamp from cache_admin"));
  if (err || !sizeof(result)) {
    db->query(CREATION_QUERY);
    db->query("create table cache_admin (stamp integer primary key)");
    db->query("insert into cache_admin values ('1')");
  }
}