-
Notifications
You must be signed in to change notification settings - Fork 1
/
rb.php
2884 lines (2883 loc) · 93.5 KB
/
rb.php
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
//Written by Gabor de Mooij and the RedBeanPHP Community, copyright 2009-2011
//Licensed New BSD/GPLV2 - see license.txt
interface RedBean_Driver {
public static function getInstance( $host, $user, $pass, $dbname );
public function GetAll( $sql, $aValues=array() );
public function GetCol( $sql, $aValues=array() );
public function GetCell( $sql, $aValues=array() );
public function GetRow( $sql, $aValues=array() );
public function ErrorNo();
public function Errormsg();
public function Execute( $sql, $aValues=array() );
public function Escape( $str );
public function GetInsertID();
public function Affected_Rows();
public function setDebugMode( $tf );
public function GetRaw();
public function CommitTrans();
public function StartTrans();
public function FailTrans();
}
class RedBean_Driver_PDO implements RedBean_Driver {
private $dsn;
private static $instance;
private $debug = false;
private $pdo;
private $affected_rows;
private $rs;
private $exc =0;
private $connectInfo = array();
public $flagUseStringOnlyBinding = false;
private $isConnected = false;
public static function getInstance($dsn, $user, $pass, $dbname) {
if(is_null(self::$instance)) {
self::$instance = new RedBean_Driver_PDO($dsn, $user, $pass);
}
return self::$instance;
}
public function __construct($dsn, $user = NULL, $pass = NULL) {
if ($dsn instanceof PDO) {
$this->pdo = $dsn;
$this->isConnected = true;
$this->pdo->setAttribute(1002, 'SET NAMES utf8');
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->dsn = $this->getDatabaseType();
} else {
$this->dsn = $dsn;
$this->connectInfo = array( "pass"=>$pass, "user"=>$user );
}
}
public function connect() {
if ($this->isConnected) return;
$user = $this->connectInfo["user"];
$pass = $this->connectInfo["pass"];
$this->pdo = new PDO(
$this->dsn,
$user,
$pass,
array(1002 => 'SET NAMES utf8',
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
)
);
$this->pdo->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, TRUE);
$this->isConnected = true;
}
protected function bindParams($s,$aValues) {
foreach($aValues as $key=>&$value) {
if (is_integer($key)) {
if (is_null($value)){
$s->bindValue($key+1,null,PDO::PARAM_NULL);
}elseif (!$this->flagUseStringOnlyBinding && RedBean_QueryWriter_AQueryWriter::canBeTreatedAsInt($value) && $value < 2147483648) {
$s->bindParam($key+1,$value,PDO::PARAM_INT);
}
else {
$s->bindParam($key+1,$value,PDO::PARAM_STR);
}
}
else {
if (is_null($value)){
$s->bindValue($key,null,PDO::PARAM_NULL);
}
elseif (!$this->flagUseStringOnlyBinding && RedBean_QueryWriter_AQueryWriter::canBeTreatedAsInt($value) && $value < 2147483648) {
$s->bindParam($key,$value,PDO::PARAM_INT);
}
else {
$s->bindParam($key,$value,PDO::PARAM_STR);
}
}
}
}
public function GetAll( $sql, $aValues=array() ) {
$this->connect();
$this->exc = 0;
if ($this->debug) {
echo "<HR>" . $sql.print_r($aValues,1);
}
try {
if (strpos("pgsql",$this->dsn)===0) {
$s = $this->pdo->prepare($sql, array(PDO::PGSQL_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT => true));
}
else {
$s = $this->pdo->prepare($sql);
}
$this->bindParams( $s, $aValues );
$s->execute();
if ($s->columnCount()) {
$this->rs = $s->fetchAll();
}
else {
$this->rs = null;
}
$rows = $this->rs;
}catch(PDOException $e) {
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
$x = new RedBean_Exception_SQL( $e->getMessage(), 0);
}
else {
$x = new RedBean_Exception_SQL( $e->getMessage(), 0, $e );
}
$x->setSQLState( $e->getCode() );
throw $x;
}
if(!$rows) {
$rows = array();
}
if ($this->debug) {
if (count($rows) > 0) {
echo "<br><b style='color:green'>resultset: " . count($rows) . " rows</b>";
}
}
return $rows;
}
public function GetCol($sql, $aValues=array()) {
$this->connect();
$this->exc = 0;
$rows = $this->GetAll($sql,$aValues);
$cols = array();
if ($rows && is_array($rows) && count($rows)>0) {
foreach ($rows as $row) {
$cols[] = array_shift($row);
}
}
return $cols;
}
public function GetCell($sql, $aValues=array()) {
$this->connect();
$this->exc = 0;
$arr = $this->GetAll($sql,$aValues);
$row1 = array_shift($arr);
$col1 = array_shift($row1);
return $col1;
}
public function GetRow($sql, $aValues=array()) {
$this->connect();
$this->exc = 0;
$arr = $this->GetAll($sql, $aValues);
return array_shift($arr);
}
public function ErrorNo() {
$this->connect();
if (!$this->exc) return 0;
$infos = $this->pdo->errorInfo();
return $infos[1];
}
public function Errormsg() {
$this->connect();
if (!$this->exc) return "";
$infos = $this->pdo->errorInfo();
return $infos[2];
}
public function Execute( $sql, $aValues=array() ) {
$this->connect();
$this->exc = 0;
if ($this->debug) {
echo "<HR>" . $sql.print_r($aValues,1);
}
try {
if (strpos("pgsql",$this->dsn)===0) {
$s = $this->pdo->prepare($sql, array(PDO::PGSQL_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT => true));
}
else {
$s = $this->pdo->prepare($sql);
}
$this->bindParams( $s, $aValues );
$s->execute();
$this->affected_rows=$s->rowCount();
return $this->affected_rows;
}
catch(PDOException $e) {
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
$x = new RedBean_Exception_SQL( $e->getMessage(), 0);
}
else {
$x = new RedBean_Exception_SQL( $e->getMessage()." SQL:".$sql, 0, $e );
}
$x->setSQLState( $e->getCode() );
throw $x;
}
}
public function Escape( $str ) {
$this->connect();
return substr(substr($this->pdo->quote($str), 1), 0, -1);
}
public function GetInsertID() {
$this->connect();
return (int) $this->pdo->lastInsertId();
}
public function Affected_Rows() {
$this->connect();
return (int) $this->affected_rows;
}
public function setDebugMode( $tf ) {
$this->connect();
$this->debug = (bool)$tf;
}
public function GetRaw() {
$this->connect();
return $this->rs;
}
public function StartTrans() {
$this->connect();
$this->pdo->beginTransaction();
}
public function CommitTrans() {
$this->connect();
$this->pdo->commit();
}
public function FailTrans() {
$this->connect();
$this->pdo->rollback();
}
public function getDatabaseType() {
$this->connect();
return $this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
}
public function getDatabaseVersion() {
$this->connect();
return $this->pdo->getAttribute(PDO::ATTR_CLIENT_VERSION);
}
public function getPDO() {
$this->connect();
return $this->pdo;
}
}
class RedBean_OODBBean implements IteratorAggregate, ArrayAccess {
private $properties = array();
private $__info = NULL;
private $beanHelper = NULL;
public static $fetchType = NULL;
public function setBeanHelper(RedBean_IBeanHelper $helper) {
$this->beanHelper = $helper;
}
public function getIterator() {
return new ArrayIterator($this->properties);
}
public function import( $arr, $selection=false, $notrim=false ) {
if (is_string($selection)) $selection = explode(",",$selection);
if (!$notrim && is_array($selection)) foreach($selection as $k=>$s){ $selection[$k]=trim($s); }
foreach($arr as $k=>$v) {
if ($k != "__info") {
if (!$selection || ($selection && in_array($k,$selection))) {
$this->$k = $v;
}
}
}
return $this;
}
public function export($meta = false) {
$arr = $this->properties;
foreach($arr as $k=>$v) {
if (is_array($v) || is_object($v)) unset($arr[$k]);
}
if ($meta) $arr["__info"] = $this->__info;
return $arr;
}
public function __isset( $property ) {
return (isset($this->properties[$property]));
}
public function getID() {
$idfield = $this->getMeta("sys.idfield");
return (string) $this->$idfield;
}
public function __unset($property) {
$this->__get($property);
$fieldLink = $property."_id";
if (isset($this->$fieldLink)) {
$this->$fieldLink = null;
return;
}
if ((isset($this->properties[$property]))) {
unset($this->properties[$property]);
}
}
public function removeProperty( $property ) {
unset($this->properties[$property]);
}
public function &__get( $property ) {
if ($this->beanHelper)
$toolbox = $this->beanHelper->getToolbox();
if (!isset($this->properties[$property])) {
$fieldLink = $property."_id";
if (isset($this->$fieldLink) && $fieldLink != $this->getMeta('sys.idfield')) {
$this->setMeta("tainted",true);
$type = $toolbox->getWriter()->getAlias($property);
$targetType = $this->properties[$fieldLink];
$bean = $toolbox->getRedBean()->load($type,$targetType);
return $bean;
}
if (strpos($property,'own')===0) {
$firstCharCode = ord(substr($property,3,1));
if ($firstCharCode>=65 && $firstCharCode<=90) {
$type = (strtolower(str_replace('own','',$property)));
$myFieldLink = $this->getMeta('type')."_id";
$beans = $toolbox->getRedBean()->find($type,array(),array(" $myFieldLink = ? ",array($this->getID())));
$this->properties[$property] = $beans;
$this->setMeta("sys.shadow.".$property,$beans);
$this->setMeta("tainted",true);
return $this->properties[$property];
}
}
if (strpos($property,'shared')===0) {
$firstCharCode = ord(substr($property,6,1));
if ($firstCharCode>=65 && $firstCharCode<=90) {
$type = (strtolower(str_replace('shared','',$property)));
$keys = $toolbox->getRedBean()->getAssociationManager()->related($this,$type);
if (!count($keys)) $beans = array(); else
$beans = $toolbox->getRedBean()->batch($type,$keys);
$this->properties[$property] = $beans;
$this->setMeta("sys.shadow.".$property,$beans);
$this->setMeta("tainted",true);
return $this->properties[$property];
}
}
$this->properties[$property] = null;
}
return $this->properties[$property];
}
public function __set( $property, $value ) {
$this->__get($property);
$this->setMeta("tainted",true);
if ($value===false) {
$value = "0";
}
if ($value===true) {
$value = "1";
}
$this->properties[$property] = $value;
}
public function getMeta( $path, $default = NULL) {
return (isset($this->__info[$path])) ? $this->__info[$path] : $default;
}
public function setMeta( $path, $value ) {
$this->__info[$path] = $value;
}
public function copyMetaFrom( RedBean_OODBBean $bean ) {
$this->__info = $bean->__info;
return $this;
}
public function __sleep() {
$this->setMeta("sys.oodb",null);
return array('properties','__info');
}
public function __call($method, $args) {
if (!isset($this->__info["model"])) {
$modelName = RedBean_ModelHelper::getModelName( $this->getMeta("type") );
if (!class_exists($modelName)) return null;
$obj = new $modelName();
$obj->loadBean($this);
$this->__info["model"] = $obj;
}
if (!method_exists($this->__info["model"],$method)) return null;
return call_user_func_array(array($this->__info["model"],$method), $args);
}
public function __toString() {
$string = $this->__call('__toString',array());
if ($string === null) {
return json_encode($this->properties);
}
else {
return $string;
}
}
public function offsetSet($offset, $value) {
$this->__set($offset, $value);
}
public function offsetExists($offset) {
return isset($this->properties[$offset]);
}
public function offsetUnset($offset) {
unset($this->properties[$offset]);
}
public function offsetGet($offset) {
return $this->__get($offset);
}
public function fetchAs($type) {
self::$fetchType = $type;
return $this;
}
}
abstract class RedBean_Observable {
private $observers = array();
public function addEventListener( $eventname, RedBean_Observer $observer ) {
if (!isset($this->observers[ $eventname ])) {
$this->observers[ $eventname ] = array();
}
foreach($this->observers[$eventname] as $o) if ($o==$observer) return;
$this->observers[ $eventname ][] = $observer;
}
public function signal( $eventname, $info ) {
if (!isset($this->observers[ $eventname ])) {
$this->observers[ $eventname ] = array();
}
foreach($this->observers[$eventname] as $observer) {
$observer->onEvent( $eventname, $info );
}
}
}
interface RedBean_Observer {
public function onEvent( $eventname, $bean );
}
interface RedBean_Adapter {
public function getSQL();
public function escape( $sqlvalue );
public function exec( $sql , $aValues=array(), $noevent=false);
public function get( $sql, $aValues = array() );
public function getRow( $sql, $aValues = array() );
public function getCol( $sql, $aValues = array() );
public function getCell( $sql, $aValues = array() );
public function getAssoc( $sql, $values = array() );
public function getInsertID();
public function getAffectedRows();
public function getDatabase();
public function getErrorMsg();
public function startTransaction();
public function commit();
public function rollback();
}
class RedBean_Adapter_DBAdapter extends RedBean_Observable implements RedBean_Adapter {
private $db = null;
private $sql = "";
public function __construct($database) {
$this->db = $database;
}
public function getSQL() {
return $this->sql;
}
public function escape( $sqlvalue ) {
return $this->db->Escape($sqlvalue);
}
public function exec( $sql , $aValues=array(), $noevent=false) {
if (!$noevent) {
$this->sql = $sql;
$this->signal("sql_exec", $this);
}
return $this->db->Execute( $sql, $aValues );
}
public function get( $sql, $aValues = array() ) {
$this->sql = $sql;
$this->signal("sql_exec", $this);
return $this->db->GetAll( $sql,$aValues );
}
public function getRow( $sql, $aValues = array() ) {
$this->sql = $sql;
$this->signal("sql_exec", $this);
return $this->db->GetRow( $sql,$aValues );
}
public function getCol( $sql, $aValues = array() ) {
$this->sql = $sql;
$this->signal("sql_exec", $this);
return $this->db->GetCol( $sql,$aValues );
}
public function getAssoc( $sql, $aValues = array() ) {
$this->sql = $sql;
$this->signal("sql_exec", $this);
$rows = $this->db->GetAll( $sql, $aValues );
$assoc = array();
if ($rows) {
foreach($rows as $row) {
if (count($row)>0) {
$key = array_shift($row);
}
if (count($row)>0) {
$value = array_shift($row);
}
else {
$value = $key;
}
$assoc[ $key ] = $value;
}
}
return $assoc;
}
public function getCell( $sql, $aValues = array(), $noSignal = null ) {
$this->sql = $sql;
if (!$noSignal) $this->signal("sql_exec", $this);
$arr = $this->db->getCol( $sql, $aValues );
if ($arr && is_array($arr)) return ($arr[0]); else return false;
}
public function getInsertID() {
return $this->db->getInsertID();
}
public function getAffectedRows() {
return $this->db->Affected_Rows();
}
public function getDatabase() {
return $this->db;
}
public function getErrorMsg() {
return $this->db->Errormsg();
}
public function startTransaction() {
return $this->db->StartTrans();
}
public function commit() {
return $this->db->CommitTrans();
}
public function rollback() {
return $this->db->FailTrans();
}
}
interface RedBean_QueryWriter {
const C_SQLSTATE_NO_SUCH_TABLE = 1;
const C_SQLSTATE_NO_SUCH_COLUMN = 2;
const C_SQLSTATE_INTEGRITY_CONSTRAINT_VIOLATION = 3;
public function getFormattedTableName($type);
public function getTables();
public function createTable($type);
public function getColumns($type);
public function scanType($value);
public function addColumn($type, $column, $field);
public function code($typedescription);
public function widenColumn($type, $column, $datatype);
public function updateRecord($type, $updatevalues, $id=null);
public function selectRecord($type, $conditions, $addSql = null, $delete = false, $inverse = false);
public function addUniqueIndex($type,$columns);
public function getIDField($type);
public function sqlStateIn( $state, $list );
public function wipe($type);
public function count($type);
public function setBeanFormatter(RedBean_IBeanFormatter $beanFormatter);
public function createView($referenceType, $types, $viewID);
public function getFieldType($type = "");
public function safeColumn($name, $noQuotes = false);
public function safeTable($name, $noQuotes = false);
public function addConstraint( RedBean_OODBBean $bean1, RedBean_OODBBean $bean2, $dontCache = false );
public function getAssocTableFormat($types);
public function addFK( $type, $targetType, $field, $targetField);
public function addIndex($type, $name, $column);
public function getAlias($type);
public function getTypeForID();
}
abstract class RedBean_QueryWriter_AQueryWriter {
protected $fcache = array();
public $tableFormatter;
public $typeno_sqltype = array();
protected $adapter;
protected $idfield = "id";
protected $defaultValue = 'NULL';
protected $quoteCharacter = '';
public function __construct() {
$this->tableFormatter = new RedBean_DefaultBeanFormatter();
}
public function safeTable($name, $noQuotes = false) {
$name = $this->getFormattedTableName($name);
$name = $this->check($name);
if (!$noQuotes) $name = $this->noKW($name);
return $name;
}
public function safeColumn($name, $noQuotes = false) {
$name = $this->check($name);
if (!$noQuotes) $name = $this->noKW($name);
return $name;
}
protected function getInsertSuffix ($table) {
return "";
}
public function getFormattedTableName($type) {
return $this->tableFormatter->formatBeanTable($type);
}
public function getAlias($type) {
return $this->tableFormatter->getAlias($type);
}
public function setBeanFormatter( RedBean_IBeanFormatter $beanFormatter ) {
$this->tableFormatter = $beanFormatter;
}
public function getFieldType( $type = "" ) {
return array_key_exists($type, $this->typeno_sqltype) ? $this->typeno_sqltype[$type] : "";
}
public function getIDField( $type ) {
$nArgs = func_num_args();
if ($nArgs>1) throw new Exception("Deprecated parameter SAFE, use safeColumn() instead.");
return $this->tableFormatter->formatBeanID($type);
}
protected function check($table) {
if ($this->quoteCharacter && strpos($table, $this->quoteCharacter)!==false) {
throw new Redbean_Exception_Security("Illegal chars in table name");
}
return $this->adapter->escape($table);
}
protected function noKW($str) {
$q = $this->quoteCharacter;
return $q.$str.$q;
}
public function addColumn( $type, $column, $field ) {
$table = $type;
$type = $field;
$table = $this->safeTable($table);
$column = $this->safeColumn($column);
$type = $this->getFieldType($type);
$sql = "ALTER TABLE $table ADD $column $type ";
$this->adapter->exec( $sql );
}
public function updateRecord( $type, $updatevalues, $id=null) {
$table = $type;
if (!$id) {
$insertcolumns = $insertvalues = array();
foreach($updatevalues as $pair) {
$insertcolumns[] = $pair["property"];
$insertvalues[] = $pair["value"];
}
return $this->insertRecord($table,$insertcolumns,array($insertvalues));
}
if ($id && !count($updatevalues)) return $id;
$idfield = $this->safeColumn($this->getIDField($table));
$table = $this->safeTable($table);
$sql = "UPDATE $table SET ";
$p = $v = array();
foreach($updatevalues as $uv) {
$p[] = " {$this->safeColumn($uv["property"])} = ? ";
$v[]=$uv["value"];
}
$sql .= implode(",", $p ) ." WHERE $idfield = ".intval($id);
$this->adapter->exec( $sql, $v );
return $id;
}
protected function insertRecord( $table, $insertcolumns, $insertvalues ) {
$default = $this->defaultValue;
$idfield = $this->safeColumn($this->getIDField($table));
$suffix = $this->getInsertSuffix($table);
$table = $this->safeTable($table);
if (count($insertvalues)>0 && is_array($insertvalues[0]) && count($insertvalues[0])>0) {
foreach($insertcolumns as $k=>$v) {
$insertcolumns[$k] = $this->safeColumn($v);
}
$insertSQL = "INSERT INTO $table ( $idfield, ".implode(",",$insertcolumns)." ) VALUES ";
$insertSQL .= "( $default, ". implode(",",array_fill(0,count($insertcolumns)," ? "))." ) $suffix";
foreach($insertvalues as $i=>$insertvalue) {
$ids[] = $this->adapter->getCell( $insertSQL, $insertvalue, $i );
}
$result = count($ids)===1 ? array_pop($ids) : $ids;
}
else {
$result = $this->adapter->getCell( "INSERT INTO $table ($idfield) VALUES($default) $suffix");
}
if ($suffix) return $result;
$last_id = $this->adapter->getInsertID();
return ($this->adapter->getErrorMsg()=="" ? $last_id : 0);
}
public function selectRecord( $type, $conditions, $addSql=null, $delete=null, $inverse=false ) {
if (!is_array($conditions)) throw new Exception("Conditions must be an array");
$table = $this->safeTable($type);
$sqlConditions = array();
$bindings=array();
foreach($conditions as $column=>$values) {
$sql = $this->safeColumn($column);
$sql .= " ".($inverse ? " NOT ":"")." IN ( ";
$sql .= implode(",",array_fill(0,count($values),"?")).") ";
$sqlConditions[] = $sql;
if (!is_array($values)) $values = array($values);
foreach($values as $k=>$v) {
$values[$k]=strval($v);
}
$bindings = array_merge($bindings,$values);
}
if (is_array($addSql)) {
if (count($addSql)>1) {
$bindings = array_merge($bindings,$addSql[1]);
}
else {
$bindings = array();
}
$addSql = $addSql[0];
}
$sql="";
if (count($sqlConditions)>0) {
$sql = implode(" AND ",$sqlConditions);
$sql = " WHERE ( $sql ) ";
if ($addSql) $sql .= " AND $addSql ";
}
elseif ($addSql) {
$sql = " WHERE ".$addSql;
}
$sql = (($delete) ? "DELETE FROM " : "SELECT * FROM ").$table.$sql;
$rows = $this->adapter->get($sql,$bindings);
return $rows;
}
public function createView($referenceType, $constraints, $viewID) {
$referenceTable = $referenceType;
$viewID = $this->safeTable($viewID,true);
$safeReferenceTable = $this->safeTable($referenceTable);
try{ $this->adapter->exec("DROP VIEW $viewID"); }catch(Exception $e){}
$columns = array_keys( $this->getColumns( $referenceTable ) );
$referenceTable = ($referenceTable);
$joins = array();
foreach($constraints as $table=>$constraint) {
$safeTable = $this->safeTable($table);
$addedColumns = array_keys($this->getColumns($table));
foreach($addedColumns as $addedColumn) {
$newColName = $addedColumn."_of_".$table;
$newcolumns[] = $this->safeTable($table).".".$this->safeColumn($addedColumn) . " AS ".$this->safeColumn($newColName);
}
if (count($constraint)!==2) throw Exception("Invalid VIEW CONSTRAINT");
$referenceColumn = $constraint[0];
$compareColumn = $constraint[1];
$join = $referenceColumn." = ".$compareColumn;
$joins[] = " LEFT JOIN $safeTable ON $join ";
}
$joins = implode(" ", $joins);
foreach($columns as $k=>$column) {
$columns[$k]=$safeReferenceTable.".".$this->safeColumn($column);
}
$columns = implode("\n,",array_merge($newcolumns,$columns));
$sql = "CREATE VIEW $viewID AS SELECT $columns FROM $safeReferenceTable $joins ";
$this->adapter->exec($sql);
return true;
}
public function wipe($type) {
$table = $type;
$table = $this->safeTable($table);
$sql = "TRUNCATE $table ";
$this->adapter->exec($sql);
}
public function count($beanType) {
$table = $this->safeTable($beanType);
$sql = "SELECT count(*) FROM $table ";
return (int) $this->adapter->getCell($sql);
}
public function addIndex($type, $name, $column) {
$table = $type;
$table = $this->safeTable($table);
$name = preg_replace("/\W/","",$name);
$column = $this->safeColumn($column);
try{ $this->adapter->exec("CREATE INDEX $name ON $table ($column) "); }catch(Exception $e){}
}
public static function canBeTreatedAsInt( $value ) {
return (boolean) (ctype_digit(strval($value)) && strval($value)===strval(intval($value)));
}
public function addFK( $type, $targetType, $field, $targetField) {
$table = $this->safeTable($type);
$tableNoQ = $this->safeTable($type,true);
$targetTable = $this->safeTable($targetType);
$column = $this->safeColumn($field);
$targetColumn = $this->safeColumn($targetField);
$db = $this->adapter->getCell("select database()");
$fks = $this->adapter->getCell("
SELECT count(*)
FROM information_schema.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA ='$db' AND TABLE_NAME = '$tableNoQ' AND
CONSTRAINT_NAME <>'PRIMARY' AND REFERENCED_TABLE_NAME is not null
");
if ($fks==0) {
try{
$this->adapter->exec("ALTER TABLE $table
ADD FOREIGN KEY ( $column ) REFERENCES $targetTable (
$targetColumn) ON DELETE NO ACTION ON UPDATE NO ACTION ;");
}
catch(Exception $e) {
}
}
}
public function getAssocTableFormat($types) {
sort($types);
return ( implode("_", $types) );
}
public function addConstraint( RedBean_OODBBean $bean1, RedBean_OODBBean $bean2, $dontCache = false ) {
$table1 = $bean1->getMeta("type");
$table2 = $bean2->getMeta("type");
$writer = $this;
$adapter = $this->adapter;
$table = $this->getAssocTableFormat( array( $table1,$table2) );
$idfield1 = $writer->getIDField($bean1->getMeta("type"));
$idfield2 = $writer->getIDField($bean2->getMeta("type"));
$property1 = $bean1->getMeta("type") . "_id";
$property2 = $bean2->getMeta("type") . "_id";
if ($property1==$property2) $property2 = $bean2->getMeta("type")."2_id";
$table = $adapter->escape($table);
$table1 = $adapter->escape($table1);
$table2 = $adapter->escape($table2);
$property1 = $adapter->escape($property1);
$property2 = $adapter->escape($property2);
$fkCode = "fk".md5($table.$property1.$property2);
if (isset($this->fkcache[$fkCode])) return false;
try {
return $this->constrain($table, $table1, $table2, $property1, $property2, $dontCache);
}
catch(RedBean_Exception_SQL $e) {
if (!$writer->sqlStateIn($e->getSQLState(),
array(
RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_COLUMN,
RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_TABLE)
)) throw $e;
}
return false;
}
abstract protected function constrain($table, $table1, $table2, $p1, $p2, $cache);
}
class RedBean_QueryWriter_MySQL extends RedBean_QueryWriter_AQueryWriter implements RedBean_QueryWriter {
const C_DATATYPE_BOOL = 0;
const C_DATATYPE_UINT8 = 1;
const C_DATATYPE_UINT32 = 2;
const C_DATATYPE_DOUBLE = 3;
const C_DATATYPE_TEXT8 = 4;
const C_DATATYPE_TEXT16 = 5;
const C_DATATYPE_TEXT32 = 6;
const C_DATATYPE_SPECIFIED = 99;
public $typeno_sqltype = array(
RedBean_QueryWriter_MySQL::C_DATATYPE_BOOL=>" SET('1') ",
RedBean_QueryWriter_MySQL::C_DATATYPE_UINT8=>" TINYINT(3) UNSIGNED ",
RedBean_QueryWriter_MySQL::C_DATATYPE_UINT32=>" INT(11) UNSIGNED ",
RedBean_QueryWriter_MySQL::C_DATATYPE_DOUBLE=>" DOUBLE ",
RedBean_QueryWriter_MySQL::C_DATATYPE_TEXT8=>" VARCHAR(255) ",
RedBean_QueryWriter_MySQL::C_DATATYPE_TEXT16=>" TEXT ",
RedBean_QueryWriter_MySQL::C_DATATYPE_TEXT32=>" LONGTEXT "
);
public $sqltype_typeno = array(
"set('1')"=>RedBean_QueryWriter_MySQL::C_DATATYPE_BOOL,
"tinyint(3) unsigned"=>RedBean_QueryWriter_MySQL::C_DATATYPE_UINT8,
"int(11) unsigned"=>RedBean_QueryWriter_MySQL::C_DATATYPE_UINT32,
"double" => RedBean_QueryWriter_MySQL::C_DATATYPE_DOUBLE,
"varchar(255)"=>RedBean_QueryWriter_MySQL::C_DATATYPE_TEXT8,
"text"=>RedBean_QueryWriter_MySQL::C_DATATYPE_TEXT16,
"longtext"=>RedBean_QueryWriter_MySQL::C_DATATYPE_TEXT32
);
protected $adapter;
protected $quoteCharacter = '`';
public function __construct( RedBean_Adapter $adapter ) {
$this->adapter = $adapter;
parent::__construct();
}
public function getTypeForID() {
return self::C_DATATYPE_UINT32;
}
public function getTables() {
return $this->adapter->getCol( "show tables" );
}
public function createTable( $table ) {
$idfield = $this->safeColumn($this->getIDfield($table));
$table = $this->safeTable($table);
$sql = "
CREATE TABLE $table (
$idfield INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT ,
PRIMARY KEY ( $idfield )
) ENGINE = InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
";
$this->adapter->exec( $sql );
}
public function getColumns( $table ) {
$table = $this->safeTable($table);
$columnsRaw = $this->adapter->get("DESCRIBE $table");
foreach($columnsRaw as $r) {
$columns[$r["Field"]]=$r["Type"];
}
return $columns;
}
public function scanType( $value ) {
if (is_null($value)) {
return RedBean_QueryWriter_MySQL::C_DATATYPE_BOOL;
}
$value = strval($value);
if ($value=="1" || $value=="") {
return RedBean_QueryWriter_MySQL::C_DATATYPE_BOOL;
}
if (is_numeric($value) && (floor($value)==$value) && $value >= 0 && $value <= 255 ) {
return RedBean_QueryWriter_MySQL::C_DATATYPE_UINT8;
}
if (is_numeric($value) && (floor($value)==$value) && $value >= 0 && $value <= 4294967295 ) {
return RedBean_QueryWriter_MySQL::C_DATATYPE_UINT32;
}
if (is_numeric($value)) {
return RedBean_QueryWriter_MySQL::C_DATATYPE_DOUBLE;
}
if (strlen($value) <= 255) {
return RedBean_QueryWriter_MySQL::C_DATATYPE_TEXT8;
}
return RedBean_QueryWriter_MySQL::C_DATATYPE_TEXT16;
}
public function code( $typedescription ) {
return ((isset($this->sqltype_typeno[$typedescription])) ? $this->sqltype_typeno[$typedescription] : self::C_DATATYPE_SPECIFIED);
}
public function widenColumn( $type, $column, $datatype ) {
$table = $type;
$type = $datatype;
$table = $this->safeTable($table);
$column = $this->safeColumn($column);
$newtype = $this->getFieldType($type);
$changecolumnSQL = "ALTER TABLE $table CHANGE $column $column $newtype ";
$this->adapter->exec( $changecolumnSQL );
}
public function addUniqueIndex( $table,$columns ) {
$table = $this->safeTable($table);
sort($columns);
foreach($columns as $k=>$v) {
$columns[$k]= $this->safeColumn($v);
}
$r = $this->adapter->get("SHOW INDEX FROM $table");
$name = "UQ_".sha1(implode(',',$columns));
if ($r) {
foreach($r as $i) {
if ($i["Key_name"]== $name) {
return;
}
}
}
$sql = "ALTER IGNORE TABLE $table
ADD UNIQUE INDEX $name (".implode(",",$columns).")";
$this->adapter->exec($sql);
}
public function sqlStateIn($state, $list) {
$sqlState = "0";
if ($state == "42S02") $sqlState = RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_TABLE;
if ($state == "42S22") $sqlState = RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_COLUMN;
if ($state == "23000") $sqlState = RedBean_QueryWriter::C_SQLSTATE_INTEGRITY_CONSTRAINT_VIOLATION;
return in_array($sqlState, $list);
}
protected function constrain($table, $table1, $table2, $property1, $property2, $dontCache) {
try{
$writer = $this;
$adapter = $this->adapter;
$db = $adapter->getCell("select database()");
$fkCode = "fk".md5($table.$property1.$property2);
$fks = $adapter->getCell("
SELECT count(*)
FROM information_schema.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA ='$db' AND TABLE_NAME ='".$writer->getFormattedTableName($table)."' AND
CONSTRAINT_NAME <>'PRIMARY' AND REFERENCED_TABLE_NAME is not null
");
if ($fks>0) return false;
if (!$dontCache) $this->fkcache[ $fkCode ] = true;
$columns = $writer->getColumns($table);
if ($writer->code($columns[$property1])!==RedBean_QueryWriter_MySQL::C_DATATYPE_UINT32) {
$writer->widenColumn($table, $property1, RedBean_QueryWriter_MySQL::C_DATATYPE_UINT32);
}
if ($writer->code($columns[$property2])!==RedBean_QueryWriter_MySQL::C_DATATYPE_UINT32) {
$writer->widenColumn($table, $property2, RedBean_QueryWriter_MySQL::C_DATATYPE_UINT32);
}
$idfield1 = $writer->getIDField($table1);
$idfield2 = $writer->getIDField($table2);
$table = $writer->getFormattedTableName($table);
$table1 = $writer->getFormattedTableName($table1);
$table2 = $writer->getFormattedTableName($table2);
$sql = "
ALTER TABLE ".$writer->noKW($table)."
ADD FOREIGN KEY($property1) references `$table1`($idfield1) ON DELETE CASCADE;
";
$adapter->exec( $sql );
$sql ="
ALTER TABLE ".$writer->noKW($table)."
ADD FOREIGN KEY($property2) references `$table2`($idfield2) ON DELETE CASCADE
";
$adapter->exec( $sql );
return true;
}
catch(Exception $e){
return false;
}
}
}
class RedBean_QueryWriter_SQLiteT extends RedBean_QueryWriter_AQueryWriter implements RedBean_QueryWriter {
protected $adapter;
protected $quoteCharacter = '`';
const C_DATATYPE_INTEGER = 0;
const C_DATATYPE_NUMERIC = 1;
const C_DATATYPE_TEXT = 2;
const C_DATATYPE_SPECIFIED = 99;
public $typeno_sqltype = array(
RedBean_QueryWriter_SQLiteT::C_DATATYPE_INTEGER=>"INTEGER",
RedBean_QueryWriter_SQLiteT::C_DATATYPE_NUMERIC=>"NUMERIC",
RedBean_QueryWriter_SQLiteT::C_DATATYPE_TEXT=>"TEXT",
);
public $sqltype_typeno = array(
"INTEGER"=>RedBean_QueryWriter_SQLiteT::C_DATATYPE_INTEGER,
"NUMERIC"=>RedBean_QueryWriter_SQLiteT::C_DATATYPE_NUMERIC,
"TEXT"=>RedBean_QueryWriter_SQLiteT::C_DATATYPE_TEXT,
);
public function __construct( RedBean_Adapter $adapter ) {
$this->adapter = $adapter;
parent::__construct($adapter);
}
public function getTypeForID() {
return self::C_DATATYPE_INTEGER;
}
public function scanType( $value ) {
if ($value===null) return self::C_DATATYPE_INTEGER;
if (is_numeric($value) && (intval($value)==$value) && $value<2147483648) return self::C_DATATYPE_INTEGER;
if ((is_numeric($value) && $value < 2147483648)
|| preg_match("/\d\d\d\d\-\d\d\-\d\d/",$value)
|| preg_match("/\d\d\d\d\-\d\d\-\d\d\s\d\d:\d\d:\d\d/",$value)