Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 3105 lines (2522 sloc) 71.515 kb
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1 <?php
2 //BRNRDPROJECT-REDBEAN - SOURCE CODE
3
4 /**
5
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
6 --- welcome to
7
8 .______.
9 _______ ____ __| _/\_ |__ ____ _____ ____
10 \_ __ \_/ __ \ / __ | | __ \_/ __ \\__ \ / \
11 | | \/\ ___// /_/ | | \_\ \ ___/ / __ \| | \
12 |__| \___ >____ | |___ /\___ >____ /___| /
13 \/ \/ \/ \/ \/ \/
14
15
16
17 |RedBean Database Objects -
18 |Written by Gabor de Mooij (c) copyright 2009
6e54bde added sean to contributor list
gabor de mooij authored
19
20
21 |List of Contributors:
22 |Sean Hess
e387e99 added Alan Hogan to contributor list
gabor de mooij authored
23 |Alan Hogan
2888565 integrated PDO driver from defrenes manually and added a testing-only mo...
gabor de mooij authored
24 |Desfrenes
6e54bde added sean to contributor list
gabor de mooij authored
25
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
26 ======================================================
27 | RedBean is Licensed BSD
28 ------------------------------------------------------
29 |RedBean is a OOP Database Simulation Middleware layer
30 |for php.
31 ------------------------------------------------------
32 |Loosely based on an idea by Erik Roelofs - thanks man
33
bb67bf9 added kickstart and nto-1 methods
gabor de mooij authored
34 VERSION 0.5
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
35
36 ======================================================
37 Official GIT HUB:
38 git://github.com/buurtnerd/redbean.git
39 http://github.com/buurtnerd/redbean/tree/master
40 ======================================================
41
42
43
44 Copyright (c) 2009, G.J.G.T (Gabor) de Mooij
45 All rights reserved.
46
47 a Buurtnerd project
48
49
50 Redistribution and use in source and binary forms, with or without
51 modification, are permitted provided that the following conditions are met:
52 * Redistributions of source code must retain the above copyright
53 notice, this list of conditions and the following disclaimer.
54 * Redistributions in binary form must reproduce the above copyright
55 notice, this list of conditions and the following disclaimer in the
56 documentation and/or other materials provided with the distribution.
57 * Neither the name of the <organization> nor the
58 names of its contributors may be used to endorse or promote products
59 derived from this software without specific prior written permission.
60
61 All advertising materials mentioning features or use of this software
62 are encouraged to display the following acknowledgement:
431816a added cans
gabor de mooij authored
63 This product is powered by RedBean written by Gabor de Mooij (http://www.redbeanphp.com)
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
64
65
66 ----
67
68
69
70
71 THIS SOFTWARE IS PROVIDED BY GABOR DE MOOIJ ''AS IS'' AND ANY
72 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
73 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
74 DISCLAIMED. IN NO EVENT SHALL GABOR DE MOOIJ BE LIABLE FOR ANY
75 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
76 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
77 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
78 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
79 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
80 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
81
82
83
84 WARNING
85 THIS IS AN PRE-BETA VERSION, DONT USE THIS CODE ON PRODUCTION SERVERS
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
86
87 */
88
89 /*
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
90 @todo: configure your database
91
92
93 === CONFIGURE YOUR REDBEAN LAYER HERE ===
94 Put your database configuration here
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
95 */
96
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
97 //Standard configurations, you may override them in your own code before inclusion if
98 //you don't want to alter these values here.
99
2888565 integrated PDO driver from defrenes manually and added a testing-only mo...
gabor de mooij authored
100
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
101 //For framework intergration if you define $db you can specify a class prefix for models
102 if (!isset($db)) define("PRFX","");
103 if (!isset($db)) define("SFFX","");
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
104
105 /**
106 * Generic interface for Databases
107 */
108 interface IGenericDatabaseDriver {
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
109
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
110 public static function getInstance( $host, $user, $pass, $dbname );
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
111
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
112 public function GetAll( $sql );
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
113
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
114 public function GetCol( $sql );
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
115
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
116 public function GetCell( $sql );
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
117
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
118 public function GetRow( $sql );
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
119
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
120 public function ErrorNo();
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
121
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
122 public function Errormsg();
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
123
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
124 public function Execute( $sql );
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
125
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
126 public function Escape( $str );
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
127
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
128 public function GetInsertID();
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
129
130 public function Affected_Rows();
131
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
132 public function setDebugMode( $tf );
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
133
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
134 public function GetRaw();
135
136 }
137
138 /**
2888565 integrated PDO driver from defrenes manually and added a testing-only mo...
gabor de mooij authored
139 * PDO support driver
140 * the PDO driver has been written by Desfrenes.
141 */
142 class PDODriver implements IGenericDatabaseDriver {
143 private static $instance;
144
145 private $debug = false;
146 private $pdo;
147 private $affected_rows;
148 private $rs;
149
150 public static function getInstance($dsn, $user, $pass, $dbname)
151 {
152 if(is_null(self::$instance))
153 {
154 self::$instance = new PDODriver($dsn, $user, $pass);
155 }
156 return self::$instance;
157 }
158
159 public function __construct($dsn, $user, $pass)
160 {
161 $this->pdo = new PDO(
162 $dsn,
163 $user,
164 $pass,
165 array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
166 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
167 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC)
168 );
169 }
170
171 public function GetAll( $sql )
172 {
173 try{
174 if ($this->debug)
175 {
176 echo "<HR>" . $sql;
177 }
178 $rs = $this->pdo->query($sql);
179 $this->rs = $rs;
180 $rows = $rs->fetchAll();
181 if(!$rows)
182 {
183 $rows = array();
184 }
185
186 if ($this->debug)
187 {
188 if (count($rows) > 0)
189 {
190 echo "<br><b style='color:green'>resultset: " . count($rows) . " rows</b>";
191 }
192
193 $str = $this->Errormsg();
194 if ($str != "")
195 {
196 echo "<br><b style='color:red'>" . $str . "</b>";
197 }
198 }
199 }
58b834d fixed a minor issue in the PDO driver
gabor de mooij authored
200 catch(Exception $e){ return array(); }
2888565 integrated PDO driver from defrenes manually and added a testing-only mo...
gabor de mooij authored
201 return $rows;
202 }
203
204 public function GetCol($sql)
205 {
206 try{
207 $rows = $this->GetAll($sql);
208 $cols = array();
209
210 if ($rows && is_array($rows) && count($rows)>0){
211 foreach ($rows as $row)
212 {
213 $cols[] = array_shift($row);
214 }
215 }
216
217 }
58b834d fixed a minor issue in the PDO driver
gabor de mooij authored
218 catch(Exception $e){ return array(); }
2888565 integrated PDO driver from defrenes manually and added a testing-only mo...
gabor de mooij authored
219 return $cols;
220 }
221
222 public function GetCell($sql)
223 {
224 try{
225 $arr = $this->GetAll($sql);
226 $row1 = array_shift($arr);
227 $col1 = array_shift($row1);
228 }
229 catch(Exception $e){}
230 return $col1;
231 }
232
233 public function GetRow($sql)
234 {
235 try{
236 $arr = $this->GetAll($sql);
237 }
58b834d fixed a minor issue in the PDO driver
gabor de mooij authored
238 catch(Exception $e){ return array(); }
2888565 integrated PDO driver from defrenes manually and added a testing-only mo...
gabor de mooij authored
239 return array_shift($arr);
240 }
241
242 public function ErrorNo()
243 {
244 $infos = $this->pdo->errorInfo();
245 return $infos[1];
246 }
247 public function Errormsg()
248 {
249 $infos = $this->pdo->errorInfo();
250 return $infos[2];
251 }
252 public function Execute( $sql )
253 {
254 try{
255 if ($this->debug)
256 {
257 echo "<HR>" . $sql;
258 }
259 $this->affected_rows = $this->pdo->exec($sql);
260 if ($this->debug)
261 {
262 $str = $this->Errormsg();
263 if ($str != "")
264 {
265 echo "<br><b style='color:red'>" . $str . "</b>";
266 }
267 }
268 }
58b834d fixed a minor issue in the PDO driver
gabor de mooij authored
269 catch(Exception $e){ return 0; }
2888565 integrated PDO driver from defrenes manually and added a testing-only mo...
gabor de mooij authored
270 return $this->affected_rows;
271 }
272 public function Escape( $str )
273 {
274 return substr(substr($this->pdo->quote($str), 1), 0, -1);
275 }
276 public function GetInsertID()
277 {
278 return (int) $this->pdo->lastInsertId();
279 }
280 public function Affected_Rows()
281 {
282 return (int) $this->affected_rows;
283 }
284 public function setDebugMode( $tf )
285 {
286 $this->debug = (bool)$tf;
287 }
288 public function GetRaw()
289 {
290 return $this->rs;
291 }
292 }
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
293
294
295 //Exception for Database problems -- not in use yet...
296 class ExceptionSQL extends Exception {};
297
298 /**
299 * Adapter for ADODB database layer AND RedBean
300 * @author gabordemooij
301 *
302 */
303 class RedBean_DBAdapter {
304
305 /**
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
306 *
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
307 * @var ADODB
308 */
309 private $db = null;
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
310
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
311 public static $log = array();
312
313 /**
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
314 *
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
315 * @param $database
316 * @return unknown_type
317 */
318 public function __construct($database) {
319 $this->db = $database;
320 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
321
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
322 /**
323 * Escapes a string for use in a Query
324 * @param $sqlvalue
325 * @return unknown_type
326 */
327 public function escape( $sqlvalue ) {
328 return $this->db->Escape($sqlvalue);
329 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
330
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
331 /**
332 * Executes SQL code
333 * @param $sql
334 * @return unknown_type
335 */
336 public function exec( $sql ) {
337 self::$log[] = $sql;
338 return $this->db->Execute( $sql );
339 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
340
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
341 /**
342 * Multi array SQL fetch
343 * @param $sql
344 * @return unknown_type
345 */
346 public function get( $sql ) {
347 self::$log[] = $sql;
348 return $this->db->GetAll( $sql );
349 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
350
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
351 /**
352 * SQL row fetch
353 * @param $sql
354 * @return unknown_type
355 */
356 public function getRow( $sql ) {
357 self::$log[] = $sql;
358 return $this->db->GetRow( $sql );
359 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
360
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
361 /**
362 * SQL column fetch
363 * @param $sql
364 * @return unknown_type
365 */
366 public function getCol( $sql ) {
367 self::$log[] = $sql;
368 return $this->db->GetCol( $sql );
369 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
370
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
371 /**
372 * Retrieves a single cell
373 * @param $sql
374 * @return unknown_type
375 */
376 public function getCell( $sql ) {
377 self::$log[] = $sql;
378 $arr = $this->db->GetCol( $sql );
379 if ($arr && is_array($arr)) return ($arr[0]); else return false;
380 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
381
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
382 /**
383 * Returns last inserted id
384 * @return unknown_type
385 */
386 public function getInsertID() {
18bc229 Sean Hess commented out two lines of $sql where it didn't exist
authored
387 // self::$log[] = $sql;
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
388 return $this->db->getInsertID();
389 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
390
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
391 /**
392 * Returns number of affected rows
393 * @return unknown_type
394 */
395 public function getAffectedRows() {
18bc229 Sean Hess commented out two lines of $sql where it didn't exist
authored
396 // self::$log[] = $sql;
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
397 return $this->db->Affected_Rows();
398 }
bb67bf9 added kickstart and nto-1 methods
gabor de mooij authored
399
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
400 /**
bb67bf9 added kickstart and nto-1 methods
gabor de mooij authored
401 * Unwrap the original database object
402 * @return $database
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
403 */
5e6be68 Added extra security tests, export test and count option for find()
gabor de mooij authored
404 public function getDatabase() {
405 return $this->db;
406 }
2dbe278 Added where() method to replace find()
gabor de mooij authored
407
bb67bf9 added kickstart and nto-1 methods
gabor de mooij authored
408 /**
409 * Return latest error message
410 * @return string $message
411 */
2dbe278 Added where() method to replace find()
gabor de mooij authored
412 public function getErrorMsg() {
413 return $this->db->Errormsg();
414 }
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
415
416 }
417
418 /**
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
419 * RedBean OODB (object oriented database) Core class for the RedBean ORM pack
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
420 * @author gabordemooij
421 *
422 */
423 class RedBean_OODB {
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
424
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
425 /**
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
426 *
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
427 * @var float
428 */
bb67bf9 added kickstart and nto-1 methods
gabor de mooij authored
429 private static $version = 0.5;
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
430
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
431 /**
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
432 *
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
433 * @var string
434 */
435 private static $versioninf = "
436 RedBean Object Database layer
bb67bf9 added kickstart and nto-1 methods
gabor de mooij authored
437 VERSION 0.5
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
438 BY G.J.G.T DE MOOIJ
439 LICENSE BSD
440 COPYRIGHT 2009
441 ";
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
442
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
443 /**
444 * Indicates how long one can lock an item,
445 * defaults to ten minutes
446 * If a user opens a bean and he or she does not
447 * perform any actions on it others cannot modify the
448 * bean during this time interval.
449 * @var unknown_type
450 */
451 private static $locktime = 10;
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
452
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
453 /**
454 * a standard adapter for use with RedBean's MYSQL Database wrapper or
455 * ADO library
456 * @var RedBean_DBAdapter
457 */
458 public static $db;
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
459
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
460 /**
461 *
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
462 * @var boolean
463 */
464 private static $locking = true;
465
466 /**
467 *
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
468 * @var array all allowed sql types
469 */
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
470 public static $typeno_sqltype = array(
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
471 " TINYINT(3) UNSIGNED ",
472 " INT(11) UNSIGNED ",
77c2e26 fixed a bug concerning int signed conversions, you might have to change ...
gabor de mooij authored
473 " BIGINT(20) SIGNED ",
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
474 " VARCHAR(255) ",
4372d0d added support for longtext
gabor de mooij authored
475 " TEXT ",
476 " LONGTEXT "
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
477 );
478
479 /**
480 *
481 * @var array all allowed sql types
482 */
483 public static $sqltype_typeno = array(
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
484 "tinyint(3) unsigned"=>0,
485 "int(11) unsigned"=>1,
77c2e26 fixed a bug concerning int signed conversions, you might have to change ...
gabor de mooij authored
486 "bigint(20) signed"=>2,
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
487 "varchar(255)"=>3,
4372d0d added support for longtext
gabor de mooij authored
488 "text"=>4,
489 "longtext"=>5
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
490 );
491
492 /**
493 * @var array all dtype types
494 */
495 public static $dtypes = array(
4372d0d added support for longtext
gabor de mooij authored
496 "tintyintus","intus","ints","varchar255","text","ltext"
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
497 );
498
499 /**
500 *
501 * @var string $pkey - a fingerprint for locking
502 */
503 public static $pkey = false;
504
505 /**
506 *
507 * @var RedBean_OODB
508 */
509 private static $me = null;
510
511 /**
512 *
513 * Indicates the current engine
514 * @var string
515 */
516 private static $engine = "myisam";
517
518 /**
519 * @var boolean $frozen - indicates whether the db may be adjusted or not
520 */
521 private static $frozen = false;
522
62c7a54 added extra configuration options for garbage collector and optimizer
gabor de mooij authored
523
524 /**
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
525 * Closes and unlocks the bean
526 * @return unknown_type
527 */
528 public function __destruct() {
529
530
531 //prepare database
532 if (self::$engine === "innodb") {
533 self::$db->exec("COMMIT");
534 }
535 else if (self::$engine === "myisam"){
536 //nope
537 }
538 RedBean_OODB::releaseAllLocks();
bb67bf9 added kickstart and nto-1 methods
gabor de mooij authored
539
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
540 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
541
542 /**
543 * Returns the version information of this RedBean instance
544 * @return float
545 */
546 public static function getVersionInfo() {
547 return self::$versioninf;
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
548 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
549
550 /**
551 * Returns the version number of this RedBean instance
552 * @return unknown_type
553 */
554 public static function getVersionNumber() {
555 return self::$version;
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
556 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
557
558 /**
559 * Toggles Forward Locking
560 * @param $tf
561 * @return unknown_type
562 */
563 public static function setLocking( $tf ) {
564 self::$locking = $tf;
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
565 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
566
567
568 /**
569 * Gets the current locking mode (on or off)
570 * @return unknown_type
571 */
572 public static function getLocking() {
573 return self::$locking;
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
574 }
bb67bf9 added kickstart and nto-1 methods
gabor de mooij authored
575
62c7a54 added extra configuration options for garbage collector and optimizer
gabor de mooij authored
576
577 /**
578 * Toggles optimizer
579 * @param $bool
580 * @return unknown_type
581 */
582 public static function setOptimizerActive( $bool ) {
583 self::$optimizer = (boolean) $bool;
584 }
585
586 /**
587 * Returns state of the optimizer
588 * @param $bool
589 * @return unknown_type
590 */
591 public static function getOptimizerActive() {
592 return self::$optimizer;
593 }
594
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
595 /**
596 * Checks whether a bean is valid
597 * @param $bean
598 * @return unknown_type
599 */
600 public static function checkBean(OODBBean $bean) {
601
5e6be68 Added extra security tests, export test and count option for find()
gabor de mooij authored
602 foreach($bean as $prop=>$value) {
603 $prop = preg_replace('/[^abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]/',"",$prop);
604 if (strlen(trim($prop))===0) {
605 throw new ExceptionRedBeanSecurity("Invalid Characters in property");
606 }
607 else {
608
609 $bean->$prop = $value;
610 }
611 }
612
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
613 //has redBean already been initialized?
614 if (!self::$pkey) self::init();
615
616 //Is the bean valid? does the bean have an id?
617 if (!isset($bean->id)) {
618 throw new Exception("Invalid bean, no id");
619 }
620
621 //is the id numeric?
622 if (!is_numeric($bean->id)) {
623 throw new Exception("Invalid bean, id not numeric");
624 }
625
626 //does the bean have a type?
627 if (!isset($bean->type)) {
628 throw new Exception("Invalid bean, no type");
629 }
630
631 //is the beantype correct and valid?
632 if (!is_string($bean->type) || is_numeric($bean->type) || strlen($bean->type)<3) {
633 throw new Exception("Invalid bean, wrong type");
634 }
635
636 //is the beantype legal?
637 if ($bean->type==="locking" || $bean->type==="dtyp") {
638 throw new Exception("Beantype is reserved table");
639 }
640
641 //is the beantype allowed?
642 if (strpos($bean->type,"_")!==false && ctype_alnum($bean->type)) {
643 throw new Exception("Beantype contains illegal characters");
644 }
645
646
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
647 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
648
649 /**
650 * same as check bean, but does additional checks for associations
651 * @param $bean
652 * @return unknown_type
653 */
654 public static function checkBeanForAssoc( $bean ) {
655
656 //check the bean
657 self::checkBean($bean);
658
659 //make sure it has already been saved to the database, else we have no id.
660 if (intval($bean->id) < 1) {
661 //if it's not saved, save it
662 $bean->id = self::set( $bean );
663 }
664
665 return $bean;
666
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
667 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
668
669 /**
670 * Returns the current engine
671 * @return unknown_type
672 */
673 public static function getEngine() {
674 return self::$engine;
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
675 }
676
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
677 /**
678 * Sets the current engine
679 * @param $engine
680 * @return unknown_type
681 */
682 public static function setEngine( $engine ) {
683
684 if ($engine=="myisam" || $engine=="innodb") {
685 self::$engine = $engine;
686 }
687 else {
688 throw new Exception("Unsupported database engine");
689 }
690
691 return self::$engine;
692
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
693 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
694
695 /**
696 * Inserts a bean into the database
697 * @param $bean
698 * @return $id
699 */
700 public static function set( OODBBean $bean ) {
701
702 self::checkBean($bean);
703
704
705 $db = self::$db; //I am lazy, I dont want to waste characters...
706
bb67bf9 added kickstart and nto-1 methods
gabor de mooij authored
707
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
708 $table = $db->escape($bean->type); //what table does it want
709
710 //may we adjust the database?
711 if (!self::$frozen) {
712
713 //does this table exist?
714 $tables = self::showTables();
715
716 if (!in_array($table, $tables)) {
717
718 if (self::$engine=="myisam") {
719 //this fellow has no table yet to put his beer on!
720 $createtableSQL = "
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
721 CREATE TABLE `$table` (
722 `id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT ,
723 PRIMARY KEY ( `id` )
724 ) ENGINE = MYISAM
725 ";
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
726 }
727 else {
728 $createtableSQL = "
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
729 CREATE TABLE `$table` (
730 `id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT ,
731 PRIMARY KEY ( `id` )
732 ) ENGINE = InnoDB
733 ";
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
734 }
735 //get a table for our friend!
736 $db->exec( $createtableSQL );
7882b91 Added Querylogger
gabor de mooij authored
737
738
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
739 //jupz, now he has its own table!
740 self::addTable( $table );
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
741 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
742
743 //does the table fit?
744 $columnsRaw = $db->get("describe `$table` ");
745
746 $columns = array();
747 foreach($columnsRaw as $r) {
748 $columns[$r["Field"]]=$r["Type"];
749 }
750
751 $insertvalues = array();
752 $insertcolumns = array();
753 $updatevalues = array();
754
755 foreach( $bean as $p=>$v) {
756 if ($p!="type" && $p!="id") {
757 $p = $db->escape($p);
758 $v = $db->escape($v);
759 //What kind of property are we dealing with?
760 $typeno = self::inferType($v);
761 //Is this property represented in the table?
762 if (isset($columns[$p])) {
763 //yes it is, does it still fit?
764 $sqlt = self::getType($columns[$p]);
765 //echo "TYPE = $sqlt .... $typeno ";
766 if ($typeno > $sqlt) {
767 //no, we have to widen the database column type
768 $changecolumnSQL="ALTER TABLE `$table` CHANGE `$p` `$p` ".self::$typeno_sqltype[$typeno];
769 $db->exec( $changecolumnSQL );
770 }
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
771 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
772 else {
773 //no it is not
774 $addcolumnSQL = "ALTER TABLE `$table` ADD `$p` ".self::$typeno_sqltype[$typeno];
775 $db->exec( $addcolumnSQL );
776 }
777 //Okay, now we are sure that the property value will fit
778 $insertvalues[] = "\"".$v."\"";
779 $insertcolumns[] = "`".$p."`";
780 $updatevalues[] = " `$p`=\"$v\" ";
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
781 }
782 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
783
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
784 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
785 else {
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
786
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
787 foreach( $bean as $p=>$v) {
788 if ($p!="type" && $p!="id") {
789 $p = $db->escape($p);
790 $v = $db->escape($v);
791
792 $insertvalues[] = "\"".$v."\"";
793 $insertcolumns[] = "`".$p."`";
794 $updatevalues[] = " `$p`=\"$v\" ";
795 }
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
796 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
797
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
798 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
799
800 //Does the record exist already?
801 if ($bean->id) {
802 //echo "<hr>Now trying to open bean....";
803 self::openBean($bean, true);
804 //yes it exists, update it
805 if (count($updatevalues)>0) {
806 $updateSQL = "UPDATE `$table` SET ".implode(",",$updatevalues)."WHERE id = ".$bean->id;
807 //execute the previously build query
808 $db->exec( $updateSQL );
809 }
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
810 }
811 else {
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
812 //no it does not exist, create it
813 if (count($insertvalues)>0) {
814 $insertSQL = "INSERT INTO `$table` ";
815 $insertSQL .= " ( id, ".implode(",",$insertcolumns)." ) ";
816 $insertSQL .= " VALUES( null, ".implode(",",$insertvalues)." ) ";
817 }
818 else {
819 $insertSQL = "INSERT INTO `$table` VALUES(null) ";
820 }
821 //execute the previously build query
822 $db->exec( $insertSQL );
823 $bean->id = $db->getInsertID();
824 self::openBean($bean);
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
825 }
826
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
827 return $bean->id;
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
828
829 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
830
831
832 /**
833 * Infers the SQL type of a bean
834 * @param $v
835 * @return $type the SQL type number constant
836 */
837 public static function inferType( $v ) {
838 $db = self::$db;
839 $rawv = $v;
840 $v = "'".$db->escape(strval($v))."'";
4372d0d added support for longtext
gabor de mooij authored
841 $checktypeSQL = "insert into dtyp VALUES(null,$v,$v,$v,$v,$v )";
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
842 $db->exec( $checktypeSQL );
843 $id = $db->getInsertID();
4372d0d added support for longtext
gabor de mooij authored
844 $readtypeSQL = "select tinyintus,intus,ints,varchar255,`text` from dtyp where id=$id";
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
845 $row=$db->getRow($readtypeSQL);
846 $db->exec("truncate table dtyp");
847 $tp = 0;
848 foreach($row as $t=>$tv) {
849 if (strval($tv) === strval($rawv)) {
850 return $tp;
851 }
852 $tp++;
853 }
854 return $tp;
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
855 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
856
857 /**
858 * Returns the RedBean type const for an SQL type
859 * @param $sqlType
860 * @return $typeno
861 */
862 public static function getType( $sqlType ) {
863
864 if (in_array($sqlType,self::$sqltype_typeno)) {
865 $typeno = self::$sqltype_typeno[$sqlType];
866 }
867 else {
868 $typeno = -1;
869 }
870
871 return $typeno;
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
872 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
873
874 /**
875 * Initializes RedBean
876 * @return bool $true
877 */
878 public static function init( $dontclose = false) {
879
880 self::$me = new RedBean_OODB();
881
882
883 //prepare database
884 if (self::$engine === "innodb") {
885 self::$db->exec("SET autocommit=0");
886 self::$db->exec("START TRANSACTION");
887 }
888 else if (self::$engine === "myisam"){
889 self::$db->exec("SET autocommit=1");
890 }
891
892
893 //generate the basic redbean tables
894 //Create the RedBean tables we need -- this should only happen once..
895 if (!self::$frozen) {
77c2e26 fixed a bug concerning int signed conversions, you might have to change ...
gabor de mooij authored
896
897 self::$db->exec("drop tables dtyp");
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
898
899 self::$db->exec("
7882b91 Added Querylogger
gabor de mooij authored
900 CREATE TABLE IF NOT EXISTS `dtyp` (
901 `id` int(11) unsigned NOT NULL auto_increment,
902 `tinyintus` tinyint(3) unsigned NOT NULL,
903 `intus` int(11) unsigned NOT NULL,
904 `ints` bigint(20) NOT NULL,
905
906 `varchar255` varchar(255) NOT NULL,
907 `text` text NOT NULL,
908 PRIMARY KEY (`id`)
909 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
910 ");
911
912 self::$db->exec("
913 CREATE TABLE IF NOT EXISTS `locking` (
914 `tbl` varchar(255) NOT NULL,
915 `id` bigint(20) NOT NULL,
916 `fingerprint` varchar(255) NOT NULL,
917 `expire` int(11) NOT NULL,
918 UNIQUE KEY `tbl` (`tbl`,`id`)
919 ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
920 ");
921
922 //rbt
923 self::$db->exec("
924 CREATE TABLE IF NOT EXISTS `redbeantables` (
925 `id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT ,
926 `tablename` VARCHAR( 255 ) NOT NULL ,
927 PRIMARY KEY ( `id` ),
928 UNIQUE KEY `tablename` (`tablename`)
929 ) ENGINE = MYISAM
930 ");
931
932 self::$db->exec("
933 CREATE TABLE IF NOT EXISTS `searchindex` (
934 `id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT ,
935 `ind` VARCHAR( 255 ) NOT NULL ,
936 `cnt` INT( 11 ) NOT NULL ,
937 PRIMARY KEY ( `id` ),
938 UNIQUE KEY `ind` (`ind`)
939 ) ENGINE = MYISAM ");
940
941
bb67bf9 added kickstart and nto-1 methods
gabor de mooij authored
942
7882b91 Added Querylogger
gabor de mooij authored
943
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
944 }
7882b91 Added Querylogger
gabor de mooij authored
945
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
946 //generate a key
947 if (!self::$pkey) {
948 self::$pkey = str_replace(".","",microtime(true)."".mt_rand());
949 }
950
951 return true;
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
952 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
953
954 /**
955 * Freezes the database so it won't be changed anymore
956 * @return unknown_type
957 */
958 public static function freeze() {
959 self::$frozen = true;
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
960 }
961
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
962 /**
963 * UNFreezes the database so it won't be changed anymore
964 * @return unknown_type
965 */
966 public static function unfreeze() {
967 self::$frozen = false;
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
968 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
969
970 /**
971 * Returns all redbean tables or all tables in the database
972 * @param $all if set to true this function returns all tables instead of just all rb tables
973 * @return array $listoftables
974 */
975 public static function showTables( $all=false ) {
976
977 $db = self::$db;
978
979 if ($all && self::$frozen) {
980 $alltables = $db->getCol("show tables");
981 return $alltables;
982 }
983 else {
984 $alltables = $db->getCol("select tablename from redbeantables");
985 return $alltables;
986 }
987
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
988 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
989
990 /**
991 * Registers a table with RedBean
992 * @param $tablename
993 * @return void
994 */
995 public static function addTable( $tablename ) {
996
997 $db = self::$db;
998
999 $tablename = $db->escape( $tablename );
1000
1001 $db->exec("replace into redbeantables values (null, \"$tablename\") ");
1002
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1003 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1004
1005 /**
1006 * UNRegisters a table with RedBean
1007 * @param $tablename
1008 * @return void
1009 */
1010 public static function dropTable( $tablename ) {
1011
1012 $db = self::$db;
1013
1014 $tablename = $db->escape( $tablename );
1015
1016 $db->exec("delete from redbeantables where tablename = \"$tablename\" ");
1017
1018
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1019 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1020
1021 /**
1022 * Quick and dirty way to release all locks
1023 * @return unknown_type
1024 */
1025 public function releaseAllLocks() {
1026
1027 self::$db->exec("DELETE FROM locking WHERE fingerprint=\"".self::$pkey."\" ");
1028
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1029 }
1030
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1031
1032 /**
1033 * Opens and locks a bean
1034 * @param $bean
1035 * @return unknown_type
1036 */
1037 public static function openBean( $bean, $mustlock=false) {
1038
1039 self::checkBean( $bean );
1040
1041 //echo "trying to open bean... ".print_r($bean,1);
1042
1043 //If locking is turned off, or the bean has no persistance yet (not shared) life is always a success!
1044 if (!self::$locking || $bean->id === 0) return true;
1045
1046 $db = self::$db;
1047
1048 //remove locks that have been expired...
1049 $removeExpiredSQL = "DELETE FROM locking WHERE expire < ".(time()-self::$locktime);
1050 $db->exec($removeExpiredSQL);
1051
1052 $tbl = $db->escape( $bean->type );
1053 $id = intval( $bean->id );
1054
1055 //Is the bean already opened for us?
1056 $checkopenSQL = "SELECT id FROM locking WHERE id=$id AND tbl=\"$tbl\" AND fingerprint=\"".self::$pkey."\" ";
1057 $row = $db->getRow($checkopenSQL);
1058 if ($row && is_array($row) && count($row)>0) {
1059 $updateexpstamp = "UPDATE locking SET expire=".time()." WHERE id =".$row["id"];
1060 return true; //bean is locked for us!
1061 }
1062
1063 //If you must lock a bean then the bean must have been locked by a previous call.
1064 if ($mustlock) {
1065 throw new ExceptionFailedAccessBean("Could not acquire a lock for bean $tbl . $id ");
1066 return false;
1067 }
1068
1069 //try to get acquire lock on the bean
1070 $openSQL = "INSERT INTO locking VALUES(\"$tbl\",$id,\"".self::$pkey."\",\"".time()."\") ";
1071 $trials = 0;
1072 $aff = 0;
ab5110e changed sleep() to usleep()
gabor de mooij authored
1073 while( $aff < 1 && $trials < 5 ) {
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1074 $db->exec($openSQL);
1075 $aff = $db->getAffectedRows();
1076 $trials++;
ab5110e changed sleep() to usleep()
gabor de mooij authored
1077 if ($aff < 1) usleep(500000); //half a sec
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1078 }
1079
1080 if ($trials > 4) {
1081 return false;
1082 }
1083 else {
1084 return true;
1085 }
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1086 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1087
1088 /**
1089 * For internal use, synchronizes a block of code
1090 * @param $toggle
1091 * @return unknown_type
1092 */
1093 private static function sync( $toggle ) {
1094
1095 $bean = RedBean_OODB::dispense("_syncmethod");
1096 $bean->id = 0;
1097
1098 if ($toggle) {
1099 self::openBean( $bean );
1100 }
1101 else {
1102 self::closeBean( $bean );
1103 }
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1104 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1105
1106 /**
1107 * Gets a bean by its primary ID
1108 * @param $type
1109 * @param $id
1110 * @return OODBBean $bean
1111 */
2dbe278 Added where() method to replace find()
gabor de mooij authored
1112 public static function getById($type, $id, $data=false) {
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1113
1114 $bean = self::dispense( $type );
1115 $db = self::$db;
1116 $table = $db->escape( $type );
1117 $id = intval( $id );
1118 $bean->id = $id;
1119
1120 //try to open the bean
1121 self::openBean($bean);
1122
1123 //load the bean using sql
2dbe278 Added where() method to replace find()
gabor de mooij authored
1124 if (!$data) {
1125 $getSQL = "SELECT * FROM `$type` WHERE id = $id ";
1126 $row = $db->getRow( $getSQL );
1127 }
1128 else {
1129 $row = $data;
1130 }
1131
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1132 if ($row && is_array($row) && count($row)>0) {
1133 foreach($row as $p=>$v) {
1134 //populate the bean with the database row
1135 $bean->$p = $v;
1136 }
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1137 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1138 else {
1139 throw new ExceptionFailedAccessBean("bean not found");
1140 }
1141
1142 return $bean;
1143
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1144 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1145
1146 /**
1147 * Checks whether a type-id combination exists
1148 * @param $type
1149 * @param $id
1150 * @return unknown_type
1151 */
1152 public static function exists($type,$id) {
1153
1154 $db = self::$db;
1155 $id = intval( $id );
1156 $type = $db->escape( $type );
1157
1158 //$alltables = $db->getCol("show tables");
1159 $alltables = self::showTables();
1160
1161 if (!in_array($type, $alltables)) {
1162 return false;
1163 }
1164 else {
1165 $no = $db->getCell("select count(*) from `$type` where id=$id");
1166 if (intval($no)) {
1167 return true;
1168 }
1169 else {
1170 return false;
1171 }
1172 }
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1173 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1174
1175 /**
1176 * Counts occurences of a bean
1177 * @param $type
1178 * @return integer $i
1179 */
1180 public static function numberof($type) {
1181
1182 $db = self::$db;
fc0ee3d added strtolower()
gabor de mooij authored
1183 $type = strtolower( $db->escape( $type ) );
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1184
1185 $alltables = self::showTables();
1186
1187 if (!in_array($type, $alltables)) {
1188 return 0;
1189 }
1190 else {
1191 $no = $db->getCell("select count(*) from `$type`");
1192 return $no;
1193 }
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1194 }
34ffc20 Added distinct() method which groups by any field and returns beans
Alan J. Hogan authored
1195
1196 /**
5a0b7f8 Made distinct() method static, as it should be, like sum() et al
Alan J. Hogan authored
1197 * Gets all beans of $type, grouped by $field.
34ffc20 Added distinct() method which groups by any field and returns beans
Alan J. Hogan authored
1198 *
1199 * @param String Object type e.g. "user" (lowercase!)
1200 * @param String Field/parameter e.g. "zip"
1201 * @return Array list of beans with distinct values of $field. Uses GROUP BY
1202 * @author Alan J. Hogan
1203 **/
5a0b7f8 Made distinct() method static, as it should be, like sum() et al
Alan J. Hogan authored
1204 static function distinct($type, $field)
34ffc20 Added distinct() method which groups by any field and returns beans
Alan J. Hogan authored
1205 {
1206 //TODO: Consider if GROUP BY (equivalent meaning) is more portable
1207 //across DB types?
1208 $db = self::$db;
fc0ee3d added strtolower()
gabor de mooij authored
1209 $type = strtolower( $db->escape( $type ) );
34ffc20 Added distinct() method which groups by any field and returns beans
Alan J. Hogan authored
1210 $field = $db->escape( $field );
1211
1212 $alltables = self::showTables();
1213
1214 if (!in_array($type, $alltables)) {
1215 return array();
1216 }
1217 else {
1218 $ids = $db->getCol("SELECT id FROM `$type` GROUP BY $field");
1219 $beans = array();
1220 if (is_array($ids) && count($ids)>0) {
1221 foreach( $ids as $id ) {
1222 $beans[ $id ] = self::getById( $type, $id , false);
1223 }
1224 }
1225 return $beans;
1226 }
1227 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1228
1229 /**
1230 * Simple statistic
1231 * @param $type
1232 * @param $field
1233 * @return integer $i
1234 */
1235 private static function stat($type,$field,$stat="sum") {
1236
1237 $db = self::$db;
fc0ee3d added strtolower()
gabor de mooij authored
1238 $type = strtolower( $db->escape( $type ) );
1239 $field = strtolower( $db->escape( $field ) );
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1240 $stat = $db->escape( $stat );
1241
1242 $alltables = self::showTables();
1243
1244 if (!in_array($type, $alltables)) {
1245 return 0;
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1246 }
1247 else {
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1248 $no = $db->getCell("select $stat(`$field`) from `$type`");
1249 return $no;
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1250 }
1251 }
1252
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1253 /**
1254 * Sum
1255 * @param $type
1256 * @param $field
1257 * @return float $i
1258 */
1259 public static function sumof($type,$field) {
1260 return self::stat( $type, $field, "sum");
1261 }
1262
1263 /**
1264 * AVG
1265 * @param $type
1266 * @param $field
1267 * @return float $i
1268 */
1269 public static function avgof($type,$field) {
1270 return self::stat( $type, $field, "avg");
1271 }
1272
1273 /**
1274 * minimum
1275 * @param $type
1276 * @param $field
1277 * @return float $i
1278 */
1279 public static function minof($type,$field) {
1280 return self::stat( $type, $field, "min");
1281 }
1282
1283 /**
1284 * maximum
1285 * @param $type
1286 * @param $field
1287 * @return float $i
1288 */
1289 public static function maxof($type,$field) {
1290 return self::stat( $type, $field, "max");
1291 }
1292
1293
1294 /**
1295 * Unlocks everything
1296 * @return unknown_type
1297 */
1298 public static function resetAll() {
1299 $sql = "TRUNCATE locking";
1300 self::$db->exec( $sql );
1301 return true;
1302 }
1303
2dbe278 Added where() method to replace find()
gabor de mooij authored
1304
1305 public static function processQuerySlots($sql, $slots) {
1306
1307 $db = self::$db;
1308
1309 //Just a funny code to identify slots based on randomness
1310 $code = sha1(rand(1,1000)*time());
1311
1312 //This ensures no one can hack our queries via SQL template injection
1313 foreach( $slots as $key=>$value ) {
1314 $sql = str_replace( "{".$key."}", "{".$code.$key."}" ,$sql );
1315 }
1316
1317 //replace the slots inside the SQL template
1318 foreach( $slots as $key=>$value ) {
bb67bf9 added kickstart and nto-1 methods
gabor de mooij authored
1319 $sql = str_replace( "{".$code.$key."}", "\"".$db->escape( $value )."\"",$sql );
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1320 }
bb67bf9 added kickstart and nto-1 methods
gabor de mooij authored
1321
1322 return $sql;
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1323 }
bb67bf9 added kickstart and nto-1 methods
gabor de mooij authored
1324
1325 public static function fastLoader( $type, $ids ) {
1326
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1327 $db = self::$db;
bb67bf9 added kickstart and nto-1 methods
gabor de mooij authored
1328 $sql = "SELECT * FROM `$type` WHERE id IN ( ".implode(",", $ids)." ) ORDER BY FIELD(id,".implode(",", $ids).") ASC
1329 ";
1330 return $db->get( $sql );
1331
1332 }
1333
1334 public static function getBySQL( $rawsql, $slots, $table ) {
1335
1336 $db = self::$db;
1337 $sql = $rawsql;
1338
1339 if (is_array($slots)) {
1340 $sql = self::processQuerySlots( $sql, $slots );
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1341 }
bb67bf9 added kickstart and nto-1 methods
gabor de mooij authored
1342
6d1b4cc corrected table specification for getSQL
gabor de mooij authored
1343 $rs = $db->getCol( "select `$table`.id from $table where " . $sql );
bb67bf9 added kickstart and nto-1 methods
gabor de mooij authored
1344
1345 if (is_array($rs)) {
1346 return $rs;
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1347 }
bb67bf9 added kickstart and nto-1 methods
gabor de mooij authored
1348 else {
1349 return array();
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1350 }
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1351 }
bb67bf9 added kickstart and nto-1 methods
gabor de mooij authored
1352
1353
8f0c33a re-added listAll, made listAll() and where() static
gabor de mooij authored
1354 /**
62ee905 added deprecated find() for those who use it
gabor de mooij authored
1355 * Finds a bean using search parameters
1356 * @param $bean
1357 * @param $searchoperators
1358 * @param $start
1359 * @param $end
1360 * @param $orderby
1361 * @return unknown_type
1362 */
1363 public static function find(OODBBean $bean, $searchoperators = array(), $start=0, $end=100, $orderby="id ASC", $extraSQL=false) {
1364
1365 self::checkBean( $bean );
1366 $db = self::$db;
1367 $tbl = $db->escape( $bean->type );
1368
1369 $findSQL = "SELECT id FROM `$tbl` WHERE ";
1370
1371
1372 foreach($bean as $p=>$v) {
1373 if ($p === "type" || $p === "id") continue;
1374 $p = $db->escape($p);
1375 $v = $db->escape($v);
1376 if (isset($searchoperators[$p])) {
1377
1378 if ($searchoperators[$p]==="LIKE") {
1379 $part[] = " `$p`LIKE \"%$v%\" ";
1380 }
1381 else {
1382 $part[] = " `$p` ".$searchoperators[$p]." \"$v\" ";
1383 }
1384 }
1385 else {
1386
1387 }
1388 }
1389
1390 if ($extraSQL) {
1391 $findSQL .= @implode(" AND ",$part) . $extraSQL;
1392 }
1393 else {
1394 $findSQL .= @implode(" AND ",$part) . " ORDER BY $orderby LIMIT $start, $end ";
1395 }
1396
1397
1398 $ids = $db->getCol( $findSQL );
1399 $beans = array();
1400
1401 if (is_array($ids) && count($ids)>0) {
1402 foreach( $ids as $id ) {
1403 $beans[ $id ] = self::getById( $bean->type, $id , false);
1404 }
1405 }
1406
1407 return $beans;
1408
1409 }
bb67bf9 added kickstart and nto-1 methods
gabor de mooij authored
1410
8f0c33a re-added listAll, made listAll() and where() static
gabor de mooij authored
1411
1412 /**
1413 * Returns a plain and simple array filled with record data
1414 * @param $type
1415 * @param $start
1416 * @param $end
1417 * @param $orderby
1418 * @return unknown_type
1419 */
1420 public static function listAll($type, $start=false, $end=false, $orderby="id ASC", $extraSQL = false) {
1421
1422 $db = self::$db;
1423
1424 if ($extraSQL) {
1425
1426 $listSQL = "SELECT * FROM ".$db->escape($type)." ".$extraSQL;
1427
1428 }
1429 else {
1430
1431 $listSQL = "SELECT * FROM ".$db->escape($type)."
1432 ORDER BY ".$orderby;
1433
1434 if ($end !== false && $start===false) {
1435 $listSQL .= " LIMIT ".intval($end);
1436 }
1437
1438 if ($start !== false && $end !== false) {
1439 $listSQL .= " LIMIT ".intval($start).", ".intval($end);
1440 }
1441
1442 if ($start !== false && $end===false) {
1443 $listSQL .= " LIMIT ".intval($start).", 18446744073709551615 ";
1444 }
1445
1446
1447
1448 }
1449
1450 return $db->get( $listSQL );
1451
1452 }
bb67bf9 added kickstart and nto-1 methods
gabor de mooij authored
1453
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1454
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1455 /**
1456 * Associates two beans
1457 * @param $bean1
1458 * @param $bean2
1459 * @return unknown_type
1460 */
1461 public static function associate( OODBBean $bean1, OODBBean $bean2 ) { //@associate
1462
1463 //get a database
1464 $db = self::$db;
1465
1466 //first we check the beans whether they are valid
1467 $bean1 = self::checkBeanForAssoc($bean1);
1468 $bean2 = self::checkBeanForAssoc($bean2);
1469
1470 self::openBean( $bean1, true );
1471 self::openBean( $bean2, true );
1472
1473 //sort the beans
1474 $tp1 = $bean1->type;
1475 $tp2 = $bean2->type;
1476 if ($tp1==$tp2){
1477 $arr = array( 0=>$bean1, 1 =>$bean2 );
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1478 }
1479 else {
1480 $arr = array( $tp1=>$bean1, $tp2 =>$bean2 );
1481 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1482 ksort($arr);
1483 $bean1 = array_shift( $arr );
1484 $bean2 = array_shift( $arr );
1485
1486 $id1 = intval($bean1->id);
1487 $id2 = intval($bean2->id);
1488
1489 //infer the association table
1490 $tables = array();
1491 array_push( $tables, $db->escape( $bean1->type ) );
1492 array_push( $tables, $db->escape( $bean2->type ) );
1493 //sort the table names to make sure we only get one assoc table
1494 sort($tables);
1495 $assoctable = $db->escape( implode("_",$tables) );
1496
1497 //check whether this assoctable already exists
1498 if (!self::$frozen) {
1499 $alltables = self::showTables();
1500 if (!in_array($assoctable, $alltables)) {
1501 //no assoc table does not exist, create it..
1502 $t1 = $tables[0];
1503 $t2 = $tables[1];
1504
1505 if ($t1==$t2) {
1506 $t2.="2";
1507 }
1508
1509 $assoccreateSQL = "
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1510 CREATE TABLE `$assoctable` (
1511 `id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT ,
1512 `".$t1."_id` INT( 11 ) UNSIGNED NOT NULL,
1513 `".$t2."_id` INT( 11 ) UNSIGNED NOT NULL,
1514 PRIMARY KEY ( `id` )
1515 ) ENGINE = ".self::$engine.";
1516 ";
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1517 $db->exec( $assoccreateSQL );
1518 //add a unique constraint
1519 $db->exec( "ALTER TABLE `$assoctable` ADD UNIQUE INDEX `u_$assoctable` (`".$t1."_id`, `".$t2."_id` ) " );
1520 self::addTable( $assoctable );
1521 }
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1522 }
1523
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1524 //now insert the association record
1525 $assocSQL = "REPLACE INTO `$assoctable` VALUES(null,$id1,$id2) ";
1526 $db->exec( $assocSQL );
1527
1528
1529 }
1530
1531 /**
1532 * Breaks the association between a pair of beans
1533 * @param $bean1
1534 * @param $bean2
1535 * @return unknown_type
1536 */
1537 public static function unassociate(OODBBean $bean1, OODBBean $bean2) {
1538
1539 //get a database
1540 $db = self::$db;
1541
1542 //first we check the beans whether they are valid
1543 $bean1 = self::checkBeanForAssoc($bean1);
1544 $bean2 = self::checkBeanForAssoc($bean2);
1545
1546
1547 self::openBean( $bean1, true );
1548 self::openBean( $bean2, true );
1549
1550
1551 $idx1 = intval($bean1->id);
1552 $idx2 = intval($bean2->id);
1553
1554 //sort the beans
1555 $tp1 = $bean1->type;
1556 $tp2 = $bean2->type;
1557
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1558 if ($tp1==$tp2){
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1559 $arr = array( 0=>$bean1, 1 =>$bean2 );
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1560 }
1561 else {
1562 $arr = array( $tp1=>$bean1, $tp2 =>$bean2 );
1563 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1564
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1565 ksort($arr);
1566 $bean1 = array_shift( $arr );
1567 $bean2 = array_shift( $arr );
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1568
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1569 $id1 = intval($bean1->id);
1570 $id2 = intval($bean2->id);
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1571
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1572 //infer the association table
1573 $tables = array();
1574 array_push( $tables, $db->escape( $bean1->type ) );
1575 array_push( $tables, $db->escape( $bean2->type ) );
1576 //sort the table names to make sure we only get one assoc table
1577 sort($tables);
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1578
1579
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1580 $assoctable = $db->escape( implode("_",$tables) );
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1581
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1582 //check whether this assoctable already exists
1583 $alltables = self::showTables();
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1584
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1585 if (in_array($assoctable, $alltables)) {
1586 $t1 = $tables[0];
1587 $t2 = $tables[1];
1588 if ($t1==$t2) {
1589 $t2.="2";
1590 $unassocSQL = "DELETE FROM `$assoctable` WHERE ".$t2."_id = $id1 AND ".$t1."_id = $id2 ";
1591 $db->exec($unassocSQL);
1592 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1593
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1594 $unassocSQL = "DELETE FROM `$assoctable` WHERE ".$t1."_id = $id1 AND ".$t2."_id = $id2 ";
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1595
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1596 $db->exec($unassocSQL);
1597 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1598 if ($tp1==$tp2) {
1599 $assoctable2 = "pc_".$db->escape( $bean1->type )."_".$db->escape( $bean1->type );
1600 //echo $assoctable2;
1601 //check whether this assoctable already exists
1602 $alltables = self::showTables();
1603 if (in_array($assoctable2, $alltables)) {
1604
1605 //$id1 = intval($bean1->id);
1606 //$id2 = intval($bean2->id);
1607 $unassocSQL = "DELETE FROM `$assoctable2` WHERE
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1608 (parent_id = $idx1 AND child_id = $idx2) OR
1609 (parent_id = $idx2 AND child_id = $idx1) ";
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1610 $db->exec($unassocSQL);
1611 }
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1612 }
1613 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1614
1615 /**
1616 * Fetches all beans of type $targettype assoiciated with $bean
1617 * @param $bean
1618 * @param $targettype
1619 * @return array $beans
1620 */
1621 public static function getAssoc(OODBBean $bean, $targettype) {
1622 //get a database
1623 $db = self::$db;
1624 //first we check the beans whether they are valid
1625 $bean = self::checkBeanForAssoc($bean);
1626
1627 $id = intval($bean->id);
1628
1629
1630 //obtain the table names
1631 $t1 = $db->escape( strtolower($bean->type) );
1632 $t2 = $db->escape( $targettype );
1633
1634 //infer the association table
1635 $tables = array();
1636 array_push( $tables, $t1 );
1637 array_push( $tables, $t2 );
1638 //sort the table names to make sure we only get one assoc table
1639 sort($tables);
1640 $assoctable = $db->escape( implode("_",$tables) );
1641
1642 //check whether this assoctable exists
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1643 $alltables = self::showTables();
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1644
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1645 if (!in_array($assoctable, $alltables)) {
1646 return array(); //nope, so no associations...!
1647 }
1648 else {
d4900c4 Sean Hess fixed small bug with self-associated tables
authored
1649 if ($t1==$t2) {
1650 $t2.="2";
1651 }
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1652 $getassocSQL = "SELECT `".$t2."_id` FROM `$assoctable` WHERE `".$t1."_id` = $id ";
1653 $rows = $db->getCol( $getassocSQL );
1654 $beans = array();
1655 if ($rows && is_array($rows) && count($rows)>0) {
1656 foreach($rows as $i) {
1657 $beans[$i] = self::getById( $targettype, $i, false);
1658 }
1659 }
1660 return $beans;
1661 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1662
1663
1664 }
1665
1666
1667 /**
1668 * Removes a bean from the database and breaks associations if required
1669 * @param $bean
1670 * @return unknown_type
1671 */
1672 public static function trash( OODBBean $bean ) {
1673
1674 self::checkBean( $bean );
1675 if (intval($bean->id)===0) return;
1676 self::deleteAllAssoc( $bean );
1677 self::openBean($bean);
1678 self::$db->exec( "DELETE FROM ".self::$db->escape($bean->type)." WHERE id = ".intval($bean->id) );
1679
1680 }
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1681
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1682 /**
1683 * Breaks all associations of a perticular bean $bean
1684 * @param $bean
1685 * @return unknown_type
1686 */
1687 public static function deleteAllAssoc( $bean ) {
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1688
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1689 $db = self::$db;
1690 $bean = self::checkBeanForAssoc($bean);
1691
1692 self::openBean( $bean, true );
1693
1694
1695 $id = intval( $bean->id );
1696
1697 //get all tables
1698 $alltables = self::showTables();
1699
1700 //are there any possible associations?
1701 $t = $db->escape($bean->type);
1702 $checktables = array();
1703 foreach( $alltables as $table ) {
1704 if (strpos($table,$t."_")!==false || strpos($table,"_".$t)!==false){
1705 $checktables[] = $table;
1706 }
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1707 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1708
1709 //remove every possible association
1710 foreach($checktables as $table) {
1711 if (strpos($table,"pc_")===0){
1712 $db->exec("DELETE FROM $table WHERE parent_id = $id OR child_id = $id ");
1713 }
1714 else {
1715 $db->exec("DELETE FROM $table WHERE ".$t."_id = $id ");
1716 $db->exec("DELETE FROM $table WHERE ".$t."2_id = $id ");
1717 }
1718
1719
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1720 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1721 return true;
1722 }
1723
1724 /**
1725 * Breaks all associations of a perticular bean $bean
1726 * @param $bean
1727 * @return unknown_type
1728 */
1729 public static function deleteAllAssocType( $targettype, $bean ) {
1730
1731 $db = self::$db;
1732 $bean = self::checkBeanForAssoc($bean);
1733 self::openBean( $bean, true );
1734
1735 $id = intval( $bean->id );
1736
1737 //obtain the table names
1738 $t1 = $db->escape( strtolower($bean->type) );
1739 $t2 = $db->escape( $targettype );
1740
1741 //infer the association table
1742 $tables = array();
1743 array_push( $tables, $t1 );
1744 array_push( $tables, $t2 );
1745 //sort the table names to make sure we only get one assoc table
1746 sort($tables);
1747 $assoctable = $db->escape( implode("_",$tables) );
1748
1749 if (strpos($assoctable,"pc_")===0){
1750 $db->exec("DELETE FROM $assoctable WHERE parent_id = $id OR child_id = $id ");
1751 }else{
1752 $db->exec("DELETE FROM $assoctable WHERE ".$t1."_id = $id ");
1753 $db->exec("DELETE FROM $assoctable WHERE ".$t1."2_id = $id ");
1754
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1755 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1756
1757 return true;
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1758 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1759
1760
1761 /**
1762 * Dispenses; creates a new OODB bean of type $type
1763 * @param $type
1764 * @return OODBBean $bean
1765 */
1766 public static function dispense( $type="StandardBean" ) {
1767
1768 $oBean = new OODBBean();
1769 $oBean->type = $type;
1770 $oBean->id = 0;
1771 return $oBean;
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1772 }
1773
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1774
1775 /**
1776 * Adds a child bean to a parent bean
1777 * @param $parent
1778 * @param $child
1779 * @return unknown_type
1780 */
1781 public static function addChild( OODBBean $parent, OODBBean $child ) {
1782
1783 //get a database
1784 $db = self::$db;
1785
1786 //first we check the beans whether they are valid
1787 $parent = self::checkBeanForAssoc($parent);
1788 $child = self::checkBeanForAssoc($child);
1789
1790 self::openBean( $parent, true );
1791 self::openBean( $child, true );
1792
1793
1794 //are parent and child of the same type?
1795 if ($parent->type !== $child->type) {
1796 throw new ExceptionInvalidParentChildCombination();
1797 }
1798
1799 $pid = intval($parent->id);
1800 $cid = intval($child->id);
1801
1802 //infer the association table
1803 $assoctable = "pc_".$db->escape($parent->type."_".$parent->type);
1804
1805 //check whether this assoctable already exists
1806 if (!self::$frozen) {
1807 $alltables = self::showTables();
1808 if (!in_array($assoctable, $alltables)) {
1809 //no assoc table does not exist, create it..
1810 $assoccreateSQL = "
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1811 CREATE TABLE `$assoctable` (
1812 `id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT ,
1813 `parent_id` INT( 11 ) UNSIGNED NOT NULL,
1814 `child_id` INT( 11 ) UNSIGNED NOT NULL,
1815 PRIMARY KEY ( `id` )
1816 ) ENGINE = ".self::$engine.";
1817 ";
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1818 $db->exec( $assoccreateSQL );
1819 //add a unique constraint
1820 $db->exec( "ALTER TABLE `$assoctable` ADD UNIQUE INDEX `u_$assoctable` (`parent_id`, `child_id` ) " );
1821 self::addTable( $assoctable );
1822 }
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1823 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1824
1825 //now insert the association record
1826 $assocSQL = "REPLACE INTO `$assoctable` VALUES(null,$pid,$cid) ";
1827 $db->exec( $assocSQL );
1828
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1829 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1830
1831 /**
1832 * Returns all child beans of parent bean $parent
1833 * @param $parent
1834 * @return array $beans
1835 */
1836 public static function getChildren( OODBBean $parent ) {
1837
1838 //get a database
1839 $db = self::$db;
1840
1841 //first we check the beans whether they are valid
1842 $parent = self::checkBeanForAssoc($parent);
1843
1844 $pid = intval($parent->id);
1845
1846 //infer the association table
1847 $assoctable = "pc_".$db->escape( $parent->type . "_" . $parent->type );
1848
1849 //check whether this assoctable exists
1850 $alltables = self::showTables();
1851 if (!in_array($assoctable, $alltables)) {
1852 return array(); //nope, so no children...!
1853 }
1854 else {
1855 $targettype = $parent->type;
1856 $getassocSQL = "SELECT `child_id` FROM `$assoctable` WHERE `parent_id` = $pid ";
1857 $rows = $db->getCol( $getassocSQL );
1858 $beans = array();
1859 if ($rows && is_array($rows) && count($rows)>0) {
1860 foreach($rows as $i) {
1861 $beans[$i] = self::getById( $targettype, $i, false);
1862 }
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1863 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1864 return $beans;
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1865 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1866
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1867 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1868
1869 /**
1870 * Fetches the parent bean of child bean $child
1871 * @param $child
1872 * @return OODBBean $parent
1873 */
1874 public static function getParent( OODBBean $child ) {
1875
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1876
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1877 //get a database
1878 $db = self::$db;
1879
1880 //first we check the beans whether they are valid
1881 $child = self::checkBeanForAssoc($child);
1882
1883 $cid = intval($child->id);
1884
1885 //infer the association table
1886 $assoctable = "pc_".$db->escape( $child->type . "_" . $child->type );
1887 //check whether this assoctable exists
1888 $alltables = self::showTables();
1889 if (!in_array($assoctable, $alltables)) {
1890 return array(); //nope, so no children...!
1891 }
1892 else {
1893 $targettype = $child->type;
1894 $getassocSQL = "SELECT `parent_id` FROM `$assoctable` WHERE `child_id` = $cid ";
1895
1896 $rows = $db->getCol( $getassocSQL );
1897 $beans = array();
1898 if ($rows && is_array($rows) && count($rows)>0) {
1899 foreach($rows as $i) {
1900 $beans[$i] = self::getById( $targettype, $i, false);
1901 }
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1902 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1903
1904 return $beans;
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1905 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1906
61e46ec initial commit, import project to git
Gabor de Mooij, Buurtnerd authored
1907 }
fc59fe8 upgraded oodb to 0.4, added aggregation functions, list functions and re...
Gabor de Mooij, Buurtnerd authored
1908
1909 /**
1910 * Removes a child bean from a parent-child association
1911 * @param $parent
1912 * @param $child
1913 * @return unknown_type
1914 */
1915 public static function removeChild(OODBBean $parent, OODBBean $child) {
1916
1917 //get a database
1918 $db = self::$db;
1919
1920 //first we check the beans whether they are valid
1921 $parent = self::checkBeanForAssoc($parent);