Datasource Abstraktion

Hier eine Abstraktionsklasse für Datenbanken.

Die Klasse kann so erweitert werden, dass auch Abfragen auf CSV-Dateien, auf Prop-Dateien oder auf das Dateisystem möglich sind.

Für Datenbanken verwendet die Klasse über PDO 'Prepared Statements'. Sie speichert alle Abfragen in einem kleinen Cache. So müssen sich wiederholende Abfragen von der Datenbank nicht erneut geparsed werden. Dies ist besonders hilfreich, wenn viele gleiche Abfragen (mit unterschiedlichen Werten natürlich) hintereinander ausgeführt werden. Allerdings muss man natürlich sagen, dass dies zu Lasten von PHP geht und es letzten Endes fraglich ist, ob das wirklich schneller ist. Ich werde dies bei Zeiten einmal untersuchen und Tests dazu machen.

Beispiele für die Anwendung siehe hier: Datasource Anwendung

ddatasource.inc
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
<?php

define
('TYP_INT''INT');
define('TYP_VARCHAR''VARCHAR');
define('TYP_TEXT''TEXT');

define('NOT_NULL''NOT_NULL');
define('ALLOW_NULL''NULL');
define('AUTO''AUTO_INCREMENT');
define('PK''PRIMARY KEY');



define('FETCH_ASSOC'PDO::FETCH_ASSOC);
define('FETCH_NUM'PDO::FETCH_NUM);
define('FETCH_BOTH'PDO::FETCH_BOTH);
//define('FETCH_ASSOC', MYSQL_ASSOC);
//define('FETCH_NUM', MYSQL_NUM);
//define('FETCH_BOTH', MYSQL_BOTH);

if(!function_exists('debug')) { function debug($str) { global $debugStr;$debugStr .= $str "<br>\n";} }

interface 
result {
    function 
fetch($f=FETCH_BOTH);
    function 
execute($d=null);
    function 
rowCount();
    function 
toArray();
}

interface 
datasource {

    function 
select($fields$tab$con$join$group$order$limit);
    function 
insert($data$tab);
    function 
update($data$tab$con);
    function 
delete($tab$con);

    function 
addTable($tab$fields);
    function 
delTable($tab);
    function 
getTables();
    function 
getFields($tab);

    function 
save();
    function 
rollback();

}

class 
sqlHelper {
    var 
$fields '*';
    var 
$tab '';
    var 
$con '';
    var 
$join '';
    var 
$order '';
    var 
$group '';
    var 
$limit '';
    function 
resetHelper() {$this->fields '*';$this->tab '';$this->con '';$this->join '';$this->order '';$this->group '';$this->limit ''; }
    function 
SELECT($fields) { $this->fields $fields; return $this; }
    function 
FROM($tab){ $this->tab $tab; return $this; }
    function 
WHERE($con) { $this->con $con; return $this; }
    function 
JOIN($join) {$this->join $join; return $this; }
    function 
ORDERBY($order) {$this->order $order; return $this; }
    function 
GROUPBY($group) {$this->group $group; return $this; }
    function 
LIMIT($limit) {$this->limit $limit; return $this; }
    function 
execute() { $f=$this->fields$t=$this->tab$c=$this->con$j=$this->join$g=$this->group;$o=$this->order;$l=$this->limit$this->resetHelper(); return $this->select($f$t$c$j$g$o$l); }
}

class 
resultDB  {
    var 
$stmt;
    function 
resultDB($stmt) { $this->__construct($stmt); }
    function 
__construct($stmt) { $this->stmt $stmt; }
    function 
fetch($f=FETCH_BOTH) { return $this->stmt->fetch($f); }
    function 
execute($d=null) { return $this->stmt->execute($d); }
    function 
rowCount() { return $this->stmt->rowCount(); }
    function 
toArray($id=''$f=FETCH_ASSOC)  { $ret=array(); while($row $this->stmt->fetch($f)) if(empty($id)) $ret[] = $row; else $ret[$row[$id]] = $row; return $ret; }
    function 
toHtmlTable() {
        
$out '<table class="display"><thead><tr>';
        
$row $this->stmt->fetch(FETCH_ASSOC);
        foreach(
$row as $k=>$v)
            
$out .='<th>'.$k.'</th>';
        
$out .= '</tr></thead><tbody>';
        do {
            
$out .= '<tr>';
            foreach(
$row as $k=>$v)
                
$out .='<td>'.$v.'&nbsp;</td>';
            
$out .= '</tr>';
        }while(
$row $this->stmt->fetch(FETCH_ASSOC));
        return 
$out.'</tbody></table>';
    }
}
class 
database extends sqlHelper {
    var 
$ds;
    var 
$last = array();
    function 
database($config) { $this->__construct($config); }
    function 
__construct($config) { $this->ds = new PDO($config['driver'].':host='.$config['host'].(empty($config['port']) ? '' ';port='.$config['port']).';dbname='.$config['db'], $config['user'], $config['password']);
        
$this->ds->query("SET NAMES 'utf8';");
    }
    
    function 
getCon($con, &$values=array()) { 
        if(empty(
$con)) {
            return 
'';
        } else if(
is_array($con)) {
            
$ret='';
            foreach(
$con as $k=>$v) {
                
$tl substr($v,0,2);
                if(
substr($v,0,4)=='like') {
                    
$ret .= $k.' like ? AND ';
                    
$values[] = substr($v,4);
                }elseif(
$tl=='<=' || $tl=='>=' || $tl=='<>') {
                    
$ret .= $k.$tl.'? AND ';
                    
$values[] = substr($v,2);
                } elseif(
$v[0]=='='||$v[0]=='<'||$v[0]=='>') {
                    
$ret .= $k.$v[0].'? AND ';
                    
$values[] = substr($v,1);
                } else {
                    
$ret .= $k.'=? AND ';
                    
$values[] = $v;
                }
            }
            return 
" WHERE ".substr($ret,0,-5);
        } else if(!
strstr($con,'=') && !strstr($con,'<') && !strstr($con,'>')) {
            
$values = array($con);
            return 
' WHERE id=?'
        } else {
            return 
' WHERE '.$con;
        }
    }
    function 
select($fields$tab=''$con=''$join=''$group=''$order=''$limit='') {
        if(
func_num_args()==1) {
            
$this->fields $fields
            return 
$this;
        }

        
$conValues = array();

        if(!empty(
$join)) {
            
$sql "SELECT $fields FROM `$tab` ".$join[0]." ".$join[1]." ON ".$join[2]." = ".$join[3]." ".$this->getCon($con$conValues);
        } else { 
            
$sql "SELECT $fields FROM `$tab` ".$this->getCon($con$conValues);
        }
        if(!empty(
$group)) 
            
$sql .= ' GROUP BY '.$group;
        if(!empty(
$order)) 
            
$sql .= ' ORDER BY '.$order;
        if(!empty(
$limit)) 
            
$sql .= ' LIMIT '.$limit;
        
        
$id md5($sql);
        if(!
array_key_exists($id$this->last)) {
            
debug('new Statement:'.$sql.' '.print_r($conValuestrue));
            
$this->last[$id] = $this->ds->prepare($sql);
        } else 
            
debug('old Statement:'.$sql.' '.print_r($conValuestrue));

        
        
$this->last[$id]->execute($conValues);
        return new 
resultDB($this->last[$id]);
    }
    function 
insert($data$tab) { 
        if(!
is_array($data[0]))
            
$data = array($data);
        
$ids = array();
        foreach(
$data as $d) { 
            
$sql "INSERT INTO `$tab` ".(isset($d[0])?'':("(".implode(',',array_keys($d)).")"))." VALUES (".(count($d)>? (str_repeat('?,',count($d)-1)."?"):'').")";
            
$id md5($sql);
            if(!
array_key_exists($id$this->last)) {
                
debug('new Statement:'.$sql.' '.print_r(array_values($d), true));
                
$this->last[$id] = $this->ds->prepare($sql);
            } else 
                
debug('old Statement:'.$sql.' '.print_r(array_values($d), true));
                
            
$this->last[$id]->execute(array_values($d));
            
$ids[] = $this->ds->lastInsertId();
        }
        return (
count($ids)==$ids[0] : $ids);
    }
    function 
update($data$tab$con) {
        if(!
is_array($data) || !isset($data[0]) ) {
            
$data = array($data);
            
$con = array($con);
        }
        
        foreach(
$data as $nr=>$d) {
            
            
$conValues = array();
            if(
is_array($d)) {
                
$sql "UPDATE `$tab` SET `".implode('` = ?,`',array_keys($d))."` = ? ".$this->getCon($con[$nr], $conValues);
                
$id md5($sql);
                if(!
array_key_exists($id$this->last)) {
                    
debug('new Statement:'.$sql.' '.print_r(array_merge(array_values($d),$conValues), true));
                    
$this->last[$id] = $this->ds->prepare($sql);
                } else 
                    
debug('old Statement:'.$sql.' '.print_r(array_merge(array_values($d),$conValues), true));
                
$this->last[$id]->execute(array_merge(array_values($d),$conValues) );
            
            } else {
                
$sql "UPDATE `$tab` SET ".$d." ".$this->getCon($con[$nr], $conValues);
                
$id md5($sql);
                if(!
array_key_exists($id$this->last)) {
                    
debug('new Statement:'.$sql.' '.print_r($conValuestrue));
                    
$this->last[$id] = $this->ds->prepare($sql);
                } else 
                    
debug('old Statement:'.$sql.' '.print_r($conValuestrue));
                
$this->last[$id]->execute($conValues);
            }
        }
        return;
    }
    function 
delete($tab$con) { 
        
$conValues = array();
        
$sql "DELETE FROM `$tab` ".$this->getCon($con$conValues);
        
$id md5($sql);
        if(!
array_key_exists($id$this->last)) {
            
debug('new Statement:'.$sql.' '.print_r($conValuestrue));
            
$this->last[$id] = $this->ds->prepare($sql);
        } else 
            
debug('old Statement:'.$sql.' '.print_r($conValuestrue));
        
$this->last[$id]->execute($conValues);
        return;
    }
    
    function 
getFields($tab) {
        
$stmt $this->ds->prepare("SHOW COLUMNS FROM `".$tab."`");
        
$stmt->execute(); 
        return new 
resultDB($stmt);
    }
    function 
getTables() {
        
$stmt $this->ds->prepare("SHOW TABLES");
        
$stmt->execute(); 
        return new 
resultDB($stmt);
    }

    
    
    function 
addTable($tab$fields) {
        
$options[TYP_INT] = 'INT';
        
$options[TYP_VARCHAR] = 'VARCHAR';
        
$options[TYP_TEXT] = 'TEXT';

        
$options[NOT_NULL] = 'NOT NULL';
        
$options[ALLOW_NULL] = 'NULL';
        
$options[AUTO] = 'AUTO_INCREMENT';
        
$options[PK] = 'PRIMARY KEY';

        
$sql "CREATE TABLE `".$tab."` ( ";
        if(
is_array($fields)) {
            foreach(
$fields as $k=>$o) {
                if(!
is_numeric($k)) {
                    
$sql .= "`".$k."` ";
                    if(
is_array($o))
                        foreach(
$o as $v)
                            if(
is_numeric($v))
                                
$sql .= '('.$v.') ';
                            else
                                
$sql .= $options[$v].' ';
                    else
                        
$sql .= $o;
                    
$sql .= ', ';
                } else
                    
$sql .= "`".$o."` , ";
            }
            
$sql substr($sql,0,-2);
        } else
            
$sql .= $fields;

        
$sql .= " )";
        
debug($sql);
        
$stmt $this->ds->prepare($sql);
        
$stmt->execute(); 
    }

    function 
delTable($tab) {
        
$sql "DROP TABLE `".$tab."`";
        
debug($sql);
        
$stmt $this->ds->prepare($sql);
        
$stmt->execute(); 
        return;
    }
/*
 CREATE TABLE `db10478474-blf`.`test` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`title` VARCHAR( 255 ) NOT NULL ,
`text` TEXT NOT NULL
) ENGINE = MYISAM 

*/
    
function save() {}
    function 
rollback() {}
}
















define('CSV_DEL'';');
define('CSV_MAX_LINE'1000);
class 
resultArray {
    var 
$data;
    var 
$i=0;
    function 
__construct($data) { $this->data $data; }
    function 
fetch($f=FETCH_BOTH) { if($this->i>=count($this->data)) return false; else return $this->data[$this->i++]; }
    function 
execute($d=null) { die('not implemented yet');  }
    function 
rowCount() { return count($this->data); }
    function 
toArray() { return $this->data; }
}
/*class File {
    static function getFileObject($config) {
        switch($config['driver']) {
            case 'csv':
                return new csvFile($config);
            case 'prop':
                return new propFile($config);
            default:
                die('not implemented driver for file');
        }
    }
}*/
class csvFile {
    var 
$config;
    function 
__construct($config) { $this->config $config; }
    function 
getFile($tab) {
        global 
$inc_root;
        return 
$inc_root.'data/ds/'.$this->config['db'].'/'.$tab.".csv";
    }
    function 
loadFields($tab) {
        
$handle fopen($this->getFile($tab),"r");
        
$data fgetcsv($handleCSV_MAX_LINECSV_DEL);
        
fclose($handle);
        return 
$data;
    }
    function 
select($fields$tab$con='') {
        
$handle fopen($this->getFile($tab),"r");
        
$header fgetcsv($handleCSV_MAX_LINECSV_DEL);
        while( (
$data fgetcsv ($handleCSV_MAX_LINECSV_DEL)) !== FALSE ) {
            
$ret[] = array_combine($header$data);
        }
        
fclose($handle);
        return new 
resultArray($ret);
    }
    function 
insert($data$tab) { die('not implemented yet');
        
    }
    function 
update($data$tab$con) { die('not implemented yet');
        
    }
    function 
delete($tab$con) { die('not implemented yet');
        
    }
    
    function 
getFields($tab) {
        
$data $this->loadFields($tab);
        
$ret=array();
        foreach(
$data as $v)
            
$ret[] = array('Field'=>$v'Type'=>'text'); 
        return new 
resultArray($ret);
    }
    function 
getTables() {
        global 
$inc_root;
        
$data getFilesFromDir($inc_root.'data/ds/'.$this->config['db']);
        
$ret=array();
        foreach(
$data as $v)
            
$ret[] = array(str_replace('.csv','',$v)); 
        return new 
resultArray($ret);
    }

    function 
save() {}
    function 
rollback() {}
}

class 
propFile {
    var 
$config;
    function 
__construct($config) { $this->config $config; }
    function 
getFile($tab) {
        global 
$inc_root;
        return 
$inc_root.'data/ds/'.$this->config['db'].'/'.$tab.".csv";
    }
    function 
select($fields$tab$con='') {
        
$prop=array();
        
$handle fopen($this->getFile($tab),"r");
        while(!
feof($handle)) {
            
$buffer fgets($handle4096);
            
$s substr(strstr($buffer'='),1);
            if(
$s[0]==" "$s substr($s,1);
            
$s str_replace("\n","",$s);
            
$prop[] = array('id'=> trim(strstr($buffer'='true)), 'value'=>$s);
        }
        
fclose($handle);
        return new 
resultArray($ret);
    }
    function 
insert($data$tab) { die('not implemented yet');
        
    }
    function 
update($data$tab$con) { die('not implemented yet');
        
    }
    function 
delete($tab$con) { die('not implemented yet');
        
    }
    
    function 
getFields($tab) {
        
$ret=array( array('Field'=>'key''Type'=>'text'),
                    array(
'Field'=>'value''Type'=>'text'));
        return new 
resultArray($ret);
    }
    function 
getTables() {
        global 
$inc_root;
        
$data getFilesFromDir($inc_root.'data/ds/'.$this->config['db']);
        
$ret=array();
        foreach(
$data as $v)
            
$ret[] = array(str_replace('.properties','',$v)); 
        return new 
resultArray($ret);
    }

    function 
save() {}
    function 
rollback() {}
}