forked from ichikaway/cakephp-mongodb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMongodbSource.php
executable file
·1614 lines (1452 loc) · 39.6 KB
/
MongodbSource.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
/**
* A CakePHP datasource for the mongoDB (http://www.mongodb.org/) document-oriented database.
*
* This datasource uses Pecl Mongo (http://php.net/mongo)
* and is thus dependent on PHP 5.0 and greater.
*
* Original implementation by ichikaway(Yasushi Ichikawa) http://github.com/ichikaway/
*
* Reference:
* Nate Abele's lithium mongoDB datasource (http://li3.rad-dev.org/)
* Joél Perras' divan(http://github.com/jperras/divan/)
*
* Copyright 2010, Yasushi Ichikawa http://github.com/ichikaway/
*
* Contributors: Predominant, Jrbasso, tkyk, AD7six
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2010, Yasushi Ichikawa http://github.com/ichikaway/
* @package mongodb
* @subpackage mongodb.models.datasources
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
App::uses('DboSource', 'Model/Datasource');
App::uses('SchemalessBehavior', 'Mongodb.Model/Behavior');
/**
* MongoDB Source
*
* @package mongodb
* @subpackage mongodb.models.datasources
*/
class MongodbSource extends DboSource {
/**
* Are we connected to the DataSource?
*
* true - yes
* null - haven't tried yet
* false - nope, and we can't connect
*
* @var boolean
* @access public
*/
public $connected = null;
/**
* Database Instance
*
* @var resource
* @access protected
*/
protected $_db = null;
/**
* Mongo Driver Version
*
* @var string
* @access protected
*/
protected $_driverVersion = Mongo::VERSION;
/**
* startTime property
*
* If debugging is enabled, stores the (micro)time the current query started
*
* @var mixed null
* @access protected
*/
protected $_startTime = null;
/**
* Direct connection with database, isn't the
* same of DboSource::_connection
*
* @var mixed null | Mongo
* @access private
*/
public $connection = null;
/**
* Base Config
*
* set_string_id:
* true: In read() method, convert MongoId object to string and set it to array 'id'.
* false: not convert and set.
*
* @var array
* @access public
*
*/
public $_baseConfig = array(
'set_string_id' => true,
'persistent' => true,
'host' => 'localhost',
'database' => '',
'port' => '27017',
'login' => '',
'password' => '',
'replicaset' => '',
);
/**
* column definition
*
* @var array
*/
public $columns = array(
'boolean' => array('name' => 'boolean'),
'string' => array('name' => 'varchar'),
'text' => array('name' => 'text'),
'integer' => array('name' => 'integer', 'format' => null, 'formatter' => 'intval'),
'float' => array('name' => 'float', 'format' => null, 'formatter' => 'floatval'),
'datetime' => array('name' => 'datetime', 'format' => null, 'formatter' => 'MongodbDateFormatter'),
'timestamp' => array('name' => 'timestamp', 'format' => null, 'formatter' => 'MongodbDateFormatter'),
'time' => array('name' => 'time', 'format' => null, 'formatter' => 'MongodbDateFormatter'),
'date' => array('name' => 'date', 'format' => null, 'formatter' => 'MongodbDateFormatter'),
);
/**
* Default schema for the mongo models
*
* @var array
* @access protected
*/
protected $_defaultSchema = array(
'_id' => array('type' => 'string', 'length' => 24, 'key' => 'primary'),
'created' => array('type' => 'datetime', 'default' => null),
'modified' => array('type' => 'datetime', 'default' => null)
);
/**
* construct method
*
* By default don't try to connect until you need to
*
* @param array $config Configuration array
* @param bool $autoConnect false
* @return void
* @access public
*/
function __construct($config = array(), $autoConnect = false) {
return parent::__construct($config, $autoConnect);
}
/**
* Destruct
*
* @access public
*/
public function __destruct() {
if ($this->connected) {
$this->disconnect();
}
}
/**
* commit method
*
* MongoDB doesn't support transactions
*
* @return void
* @access public
*/
public function commit() {
return false;
}
/**
* Connect to the database
*
* If using 1.0.2 or above use the mongodb:// format to connect
* The connect syntax changed in version 1.0.2 - so check for that too
*
* If authentication information in present then authenticate the connection
*
* @return boolean Connected
* @access public
*/
public function connect() {
$this->connected = false;
try{
$host = $this->createConnectionName($this->config, $this->_driverVersion);
$class = 'MongoClient';
if(!class_exists($class)){
$class = 'Mongo';
}
if (isset($this->config['replicaset']) && count($this->config['replicaset']) === 2) {
$this->connection = new $class($this->config['replicaset']['host'], $this->config['replicaset']['options']);
} else if ($this->_driverVersion >= '1.3.0') {
$this->connection = new $class($host);
} else if ($this->_driverVersion >= '1.2.0') {
$this->connection = new $class($host, array("persist" => $this->config['persistent']));
} else {
$this->connection = new $class($host, true, $this->config['persistent']);
}
if (isset($this->config['slaveok'])) {
if (method_exists($this->connection, 'setSlaveOkay')) {
$this->connection->setSlaveOkay($this->config['slaveok']);
} else {
$this->connection->setReadPreference($this->config['slaveok']
? $class::RP_SECONDARY_PREFERRED : $class::RP_PRIMARY);
}
}
if ($this->_db = $this->connection->selectDB($this->config['database'])) {
if (!empty($this->config['login']) && $this->_driverVersion < '1.2.0') {
$return = $this->_db->authenticate($this->config['login'], $this->config['password']);
if (!$return || !$return['ok']) {
trigger_error('MongodbSource::connect ' . $return['errmsg']);
return false;
}
}
$this->connected = true;
}
} catch(MongoException $e) {
$this->error = $e->getMessage();
trigger_error($this->error);
}
return $this->connected;
}
/**
* create connection name.
*
* @param array $config
* @param string $version version of MongoDriver
*/
public function createConnectionName($config, $version) {
$host = null;
if ($version >= '1.0.2') {
$host = "mongodb://";
} else {
$host = '';
}
$hostname = $config['host'] . ':' . $config['port'];
if(!empty($config['login'])){
$host .= $config['login'] .':'. $config['password'] . '@' . $hostname . '/'. $config['database'];
} else {
$host .= $hostname;
}
return $host;
}
/**
* Inserts multiple values into a table
*
* @param string $table
* @param string $fields
* @param array $values
* @access public
*/
public function insertMulti($table, $fields, $values) {
$table = $this->fullTableName($table);
if (!is_array($fields) || !is_array($values)) {
return false;
}
$inUse = array_search('id', $fields);
$default = array_search('_id', $fields);
if ($inUse !== false && $default === false) {
$fields[$inUse] = '_id';
}
$values = $this->normalizeValues($table, $fields, $values);
$data = array();
foreach ($values as $row) {
if (is_string($row)) {
$row = explode(', ', substr($row, 1, -1));
}
$data[] = array_combine($fields, $row);
}
$this->_prepareLogQuery($table); // just sets a timer
try{
$return = $this->_db
->selectCollection($table)
->batchInsert($data, array('w' => 1));
} catch (MongoException $e) {
$this->error = $e->getMessage();
trigger_error($this->error);
}
if ($this->fullDebug) {
$this->logQuery("db.{$table}.insertMulti( :data , array('w' => 1))", compact('data'));
}
}
public function normalizeValues($table, $fields, $values) {
$Model = ClassRegistry::init(Inflector::classify($table));
foreach ($values as $key => $value) {
foreach ($value as $k => $v) {
switch($Model->mongoSchema[$fields[$k]]['type']) {
case 'datetime':
case 'timestamp':
case 'date':
case 'time':
if (is_string($values[$key][$k])) {
$values[$key][$k] = new MongoDate(strtotime($v));
}
break;
default:
break;
}
}
}
return $values;
}
/**
* check connection to the database
*
* @return boolean Connected
* @access public
*/
public function isConnected() {
if ($this->connected === false) {
return false;
}
return $this->connect();
}
/**
* get MongoDB Object
*
* @return mixed MongoDB Object
* @access public
*/
public function getMongoDb() {
if ($this->connected === false) {
return false;
}
return $this->_db;
}
/**
* get MongoDB Collection Object
*
* @return mixed MongoDB Collection Object
* @access public
*/
public function getMongoCollection(&$Model) {
if ($this->connected === false) {
return false;
}
$table = $this->fullTableName($Model);
$collection = $this->_db
->selectCollection($table);
return $collection;
}
/**
* isInterfaceSupported method
*
* listSources is infact supported, however: cake expects it to return a complete list of all
* possible sources in the selected db - the possible list of collections is infinte, so it's
* faster and simpler to tell cake that the interface is /not/ supported so it assumes that
* <insert name of your table here> exist
*
* @param mixed $interface
* @return void
* @access public
*/
public function isInterfaceSupported($interface) {
if ($interface === 'listSources') {
return false;
}
return parent::isInterfaceSupported($interface);
}
/**
* Close database connection
*
* @return boolean Connected
* @access public
*/
public function close() {
return $this->disconnect();
}
/**
* Disconnect from the database
*
* @return boolean Connected
* @access public
*/
public function disconnect() {
if ($this->connected) {
$this->connected = !$this->connection->close();
unset($this->_db, $this->connection);
return !$this->connected;
}
return true;
}
/**
* Get list of available Collections
*
* @param array $data
* @return array Collections
* @access public
*/
public function listSources($data = null) {
if (!$this->isConnected()) {
return false;
}
return true;
}
/**
* Describe
*
* Automatically bind the schemaless behavior if there is no explicit mongo schema.
* When called, if there is model data it will be used to derive a schema. a row is plucked
* out of the db and the data obtained used to derive the schema.
*
* @param Model $Model
* @return array if model instance has mongoSchema, return it.
* @access public
*/
public function describe($Model) {
if(empty($Model->primaryKey)) {
$Model->primaryKey = '_id';
}
$schema = array();
$table = $this->fullTableName($Model);
if (!empty($Model->mongoSchema) && is_array($Model->mongoSchema)) {
$schema = $Model->mongoSchema;
return $schema + array($Model->primaryKey => $this->_defaultSchema['_id']);
} elseif ($this->isConnected() && is_a($Model, 'Model') && !empty($Model->Behaviors)) {
$Model->Behaviors->attach('Mongodb.Schemaless');
if (!$Model->data) {
if ($this->_db->selectCollection($table)->count()) {
return $this->deriveSchemaFromData($Model, $this->_db->selectCollection($table)->findOne());
}
}
}
return $this->deriveSchemaFromData($Model);
}
/**
* begin method
*
* Mongo doesn't support transactions
*
* @return void
* @access public
*/
public function begin() {
return false;
}
/**
* Calculate
*
* @param Model $Model
* @return array
* @access public
*/
public function calculate(Model $Model, $func, $params = array()) {
return array('count' => true);
}
/**
* Quotes identifiers.
*
* MongoDb does not need identifiers quoted, so this method simply returns the identifier.
*
* @param string $name The identifier to quote.
* @return string The quoted identifier.
*/
public function name($name) {
return $name;
}
/**
* Create Data
*
* @param Model $Model Model Instance
* @param array $fields Field data
* @param array $values Save data
* @return boolean Insert result
* @access public
*/
public function create(Model $Model, $fields = null, $values = null) {
if (!$this->isConnected()) {
return false;
}
if ($fields !== null && $values !== null) {
$data = array_combine($fields, $values);
} else {
$data = $Model->data;
}
if($Model->primaryKey !== '_id' && isset($data[$Model->primaryKey]) && !empty($data[$Model->primaryKey])) {
$data['_id'] = $data[$Model->primaryKey];
unset($data[$Model->primaryKey]);
}
if (!empty($data['_id'])) {
$this->_convertId($data['_id']);
}
$this->_prepareLogQuery($Model); // just sets a timer
$table = $this->fullTableName($Model);
try{
if ($this->_driverVersion >= '1.3.0') {
$return = $this->_db
->selectCollection($table)
->insert($data, array('safe' => true));
} else {
$return = $this->_db
->selectCollection($table)
->insert($data, true);
}
} catch (MongoException $e) {
$this->error = $e->getMessage();
trigger_error($this->error);
}
if ($this->fullDebug) {
$this->logQuery("db.{$table}.insert( :data , true)", compact('data'));
}
if (!empty($return) && $return['ok']) {
$id = $data['_id'];
if($this->config['set_string_id'] && is_object($data['_id'])) {
$id = $data['_id']->__toString();
}
$Model->setInsertID($id);
$Model->id = $id;
return true;
}
return false;
}
/**
* createSchema method
*
* Mongo no care for creating schema. Mongo work with no schema.
*
* @param mixed $schema
* @param mixed $tableName null
* @return void
* @access public
*/
public function createSchema($schema, $tableName = null) {
return true;
}
/**
* dropSchema method
*
* Return a command to drop each table
*
* @param mixed $schema
* @param mixed $tableName null
* @return void
* @access public
*/
public function dropSchema(CakeSchema $schema, $tableName = null) {
if (!$this->isConnected()) {
return false;
}
if (!is_a($schema, 'CakeSchema')) {
trigger_error(__('Invalid schema object', true), E_USER_WARNING);
return null;
}
if ($tableName) {
return "db.{$tableName}.drop();";
}
$toDrop = array();
foreach ($schema->tables as $curTable => $columns) {
if ($tableName === $curTable) {
$toDrop[] = $curTable;
}
}
if (count($toDrop) === 1) {
return "db.{$toDrop[0]}.drop();";
}
$return = "toDrop = :tables;\nfor( i = 0; i < toDrop.length; i++ ) {\n\tdb[toDrop[i]].drop();\n}";
$tables = '["' . implode($toDrop, '", "') . '"]';
return String::insert($return, compact('tables'));
}
/**
* distinct method
*
* @param mixed $Model
* @param array $keys array()
* @param array $params array()
* @return void
* @access public
*/
public function distinct(&$Model, $keys = array(), $params = array()) {
if (!$this->isConnected()) {
return false;
}
$this->_prepareLogQuery($Model); // just sets a timer
if (array_key_exists('conditions', $params)) {
$params = $params['conditions'];
}
$table = $this->fullTableName($Model);
try{
$return = $this->_db
->selectCollection($table)
->distinct($keys, $params);
} catch (MongoException $e) {
$this->error = $e->getMessage();
trigger_error($this->error);
}
if ($this->fullDebug) {
$this->logQuery("db.{$table}.distinct( :keys, :params )", compact('keys', 'params'));
}
return $return;
}
/**
* group method
*
* @param array $params array()
* Set params same as MongoCollection::group()
* key,initial, reduce, options(conditions, finalize)
*
* Ex. $params = array(
* 'key' => array('field' => true),
* 'initial' => array('csum' => 0),
* 'reduce' => 'function(obj, prev){prev.csum += 1;}',
* 'options' => array(
* 'condition' => array('age' => array('$gt' => 20)),
* 'finalize' => array(),
* ),
* );
* @param mixed $Model
* @return void
* @access public
*/
public function group($params, $Model = null) {
if (!$this->isConnected() || count($params) === 0 || $Model === null) {
return false;
}
$this->_prepareLogQuery($Model); // just sets a timer
$key = (empty($params['key'])) ? array() : $params['key'];
$initial = (empty($params['initial'])) ? array() : $params['initial'];
$reduce = (empty($params['reduce'])) ? array() : $params['reduce'];
$options = (empty($params['options'])) ? array() : $params['options'];
$table = $this->fullTableName($Model);
try{
$return = $this->_db
->selectCollection($table)
->group($key, $initial, $reduce, $options);
} catch (MongoException $e) {
$this->error = $e->getMessage();
trigger_error($this->error);
}
if ($this->fullDebug) {
$this->logQuery("db.{$table}.group( :key, :initial, :reduce, :options )", $params);
}
return $return;
}
/**
* ensureIndex method
*
* @param mixed $Model
* @param array $keys array()
* @param array $params array()
* @return void
* @access public
*/
public function ensureIndex(&$Model, $keys = array(), $params = array()) {
if (!$this->isConnected()) {
return false;
}
$this->_prepareLogQuery($Model); // just sets a timer
$table = $this->fullTableName($Model);
try{
$return = $this->_db
->selectCollection($table)
->ensureIndex($keys, $params);
} catch (MongoException $e) {
$this->error = $e->getMessage();
trigger_error($this->error);
}
if ($this->fullDebug) {
$this->logQuery("db.{$table}.ensureIndex( :keys, :params )", compact('keys', 'params'));
}
return $return;
}
/**
* Update Data
*
* This method uses $set operator automatically with MongoCollection::update().
* If you don't want to use $set operator, you can chose any one as follw.
* 1. Set TRUE in Model::mongoNoSetOperator property.
* 2. Set a mongodb operator in a key of save data as follow.
* Model->save(array('_id' => $id, '$inc' => array('count' => 1)));
* Don't use Model::mongoSchema property,
* CakePHP delete '$inc' data in Model::Save().
* 3. Set a Mongo operator in Model::mongoNoSetOperator property.
* Model->mongoNoSetOperator = '$inc';
* Model->save(array('_id' => $id, array('count' => 1)));
*
* @param Model $Model Model Instance
* @param array $fields Field data
* @param array $values Save data
* @return boolean Update result
* @access public
*/
public function update(Model $Model, $fields = null, $values = null, $conditions = null) {
if (!$this->isConnected()) {
return false;
}
if ($fields !== null && $values !== null) {
$data = array_combine($fields, $values);
} elseif($fields !== null && $conditions !== null) {
return $this->updateAll($Model, $fields, $conditions);
} else{
$data = $Model->data;
}
if($Model->primaryKey !== '_id' && isset($data[$Model->primaryKey]) && !empty($data[$Model->primaryKey])) {
$data['_id'] = $data[$Model->primaryKey];
unset($data[$Model->primaryKey]);
}
if (empty($data['_id'])) {
$data['_id'] = $Model->id;
}
$this->_convertId($data['_id']);
$table = $this->fullTableName($Model);
try{
$mongoCollectionObj = $this->_db
->selectCollection($table);
} catch (MongoException $e) {
$this->error = $e->getMessage();
trigger_error($this->error);
return false;
}
$this->_prepareLogQuery($Model); // just sets a timer
if (!empty($data['_id'])) {
$this->_convertId($data['_id']);
$cond = array('_id' => $data['_id']);
unset($data['_id']);
$data = $this->setMongoUpdateOperator($Model, $data);
try{
if ($this->_driverVersion >= '1.3.0') {
$return = $mongoCollectionObj->update($cond, $data, array("multiple" => false, 'safe' => true));
} else {
$return = $mongoCollectionObj->update($cond, $data, array("multiple" => false));
}
} catch (MongoException $e) {
$this->error = $e->getMessage();
trigger_error($this->error);
}
if ($this->fullDebug) {
$this->logQuery("db.{$table}.update( :conditions, :data, :params )",
array('conditions' => $cond, 'data' => $data, 'params' => array("multiple" => false))
);
}
} else {
try{
if ($this->_driverVersion >= '1.3.0') {
$return = $mongoCollectionObj->save($data, array('safe' => true));
} else {
$return = $mongoCollectionObj->save($data);
}
} catch (MongoException $e) {
$this->error = $e->getMessage();
trigger_error($this->error);
}
if ($this->fullDebug) {
$this->logQuery("db.{$table}.save( :data )", compact('data'));
}
}
return $return;
}
/**
* setMongoUpdateOperator
*
* Set Mongo update operator following saving data.
* This method is for update() and updateAll.
*
* @param Model $Model Model Instance
* @param array $values Save data
* @return array $data
* @access public
*/
public function setMongoUpdateOperator(&$Model, $data) {
if(isset($data['updated'])) {
$updateField = 'updated';
} else {
$updateField = 'modified';
}
//setting Mongo operator
if(empty($Model->mongoNoSetOperator)) {
if(!preg_grep('/^\$/', array_keys($data))) {
$data = array('$set' => $data);
} else {
if(!empty($data[$updateField])) {
$modified = $data[$updateField];
unset($data[$updateField]);
$data['$set'] = array($updateField => $modified);
}
}
} elseif(substr($Model->mongoNoSetOperator,0,1) === '$') {
if(!empty($data[$updateField])) {
$modified = $data[$updateField];
unset($data[$updateField]);
$data = array($Model->mongoNoSetOperator => $data, '$set' => array($updateField => $modified));
} else {
$data = array($Model->mongoNoSetOperator => $data);
}
}
return $data;
}
/**
* Update multiple Record
*
* @param Model $Model Model Instance
* @param array $fields Field data
* @param array $conditions
* @return boolean Update result
* @access public
*/
public function updateAll(&$Model, $fields = null, $conditions = null) {
if (!$this->isConnected()) {
return false;
}
$this->_stripAlias($conditions, $Model->alias);
$this->_stripAlias($fields, $Model->alias, false, 'value');
$fields = $this->setMongoUpdateOperator($Model, $fields);
$this->_prepareLogQuery($Model); // just sets a timer
$table = $this->fullTableName($Model);
try{
if ($this->_driverVersion >= '1.3.0') {
// not use 'upsert'
$return = $this->_db
->selectCollection($table)
->update($conditions, $fields, array("multiple" => true, 'safe' => true));
if (isset($return['updatedExisting'])) {
$return = $return['updatedExisting'];
}
} else {
$return = $this->_db
->selectCollection($table)
->update($conditions, $fields, array("multiple" => true));
}
} catch (MongoException $e) {
$this->error = $e->getMessage();
trigger_error($this->error);
}
if ($this->fullDebug) {
$this->logQuery("db.{$table}.update( :conditions, :fields, :params )",
array('conditions' => $conditions, 'fields' => $fields, 'params' => array("multiple" => true))
);
}
return $return;
}
/**
* deriveSchemaFromData method
*
* @param mixed $Model
* @param array $data array()
* @return void
* @access public
*/
public function deriveSchemaFromData($Model, $data = array()) {
if (!$data) {
$data = $Model->data;
if ($data && array_key_exists($Model->alias, $data)) {
$data = $data[$Model->alias];
}
}
$return = $this->_defaultSchema;
if ($data) {
$fields = array_keys($data);
foreach($fields as $field) {
if (in_array($field, array('created', 'modified', 'updated'))) {
$return[$field] = array('type' => 'datetime', 'null' => true);
} else {
$return[$field] = array('type' => 'string', 'length' => 2000);
}
}
}
return $return;
}
/**
* Delete Data
*
* For deleteAll(true, false) calls - conditions will arrive here as true - account for that and
* convert to an empty array
* For deleteAll(array('some conditions')) calls - conditions will arrive here as:
* array(
* Alias._id => array(1, 2, 3, ...)
* )
*
* This format won't be understood by mongodb, it'll find 0 rows. convert to:
*
* array(
* Alias._id => array('$in' => array(1, 2, 3, ...))
* )
*
* @TODO bench remove() v drop. if it's faster to drop - just drop the collection taking into
* account existing indexes (recreate just the indexes)
* @param Model $Model Model Instance
* @param array $conditions
* @return boolean Update result
* @access public
*/
public function delete(Model $Model, $conditions = null) {
if (!$this->isConnected()) {
return false;
}
$id = null;
$this->_stripAlias($conditions, $Model->alias);
if ($conditions === true) {
$conditions = array();
} elseif (empty($conditions)) {
$id = $Model->id;
} elseif (!empty($conditions) && !is_array($conditions)) {
$id = $conditions;
$conditions = array();
} elseif (!empty($conditions['id'])) { //for cakephp2.0
$id = $conditions['id'];
unset($conditions['id']);
}
$table = $this->fullTableName($Model);
$mongoCollectionObj = $this->_db
->selectCollection($table);