Initial Kohana install
[speedfreak] / Server / system / libraries / ORM.php
1 <?php defined('SYSPATH') OR die('No direct access allowed.');
2 /**
3  * [Object Relational Mapping][ref-orm] (ORM) is a method of abstracting database
4  * access to standard PHP calls. All table rows are represented as model objects,
5  * with object properties representing row data. ORM in Kohana generally follows
6  * the [Active Record][ref-act] pattern.
7  *
8  * [ref-orm]: http://wikipedia.org/wiki/Object-relational_mapping
9  * [ref-act]: http://wikipedia.org/wiki/Active_record
10  *
11  * $Id: ORM.php 4354 2009-05-15 16:51:37Z kiall $
12  *
13  * @package    ORM
14  * @author     Kohana Team
15  * @copyright  (c) 2007-2008 Kohana Team
16  * @license    http://kohanaphp.com/license.html
17  */
18 class ORM_Core {
19
20         // Current relationships
21         protected $has_one                 = array();
22         protected $belongs_to              = array();
23         protected $has_many                = array();
24         protected $has_and_belongs_to_many = array();
25
26         // Relationships that should always be joined
27         protected $load_with = array();
28
29         // Current object
30         protected $object  = array();
31         protected $changed = array();
32         protected $related = array();
33         protected $loaded  = FALSE;
34         protected $saved   = FALSE;
35         protected $sorting;
36
37         // Related objects
38         protected $object_relations = array();
39         protected $changed_relations = array();
40
41         // Model table information
42         protected $object_name;
43         protected $object_plural;
44         protected $table_name;
45         protected $table_columns;
46         protected $ignored_columns;
47
48         // Table primary key and value
49         protected $primary_key = 'id';
50         protected $primary_val = 'name';
51
52         // Array of foreign key name overloads
53         protected $foreign_key = array();
54
55         // Model configuration
56         protected $table_names_plural = TRUE;
57         protected $reload_on_wakeup   = TRUE;
58
59         // Database configuration
60         protected $db = 'default';
61         protected $db_applied = array();
62
63         // With calls already applied
64         protected $with_applied = array();
65
66         // Stores column information for ORM models
67         protected static $column_cache = array();
68
69         /**
70          * Creates and returns a new model.
71          *
72          * @chainable
73          * @param   string  model name
74          * @param   mixed   parameter for find()
75          * @return  ORM
76          */
77         public static function factory($model, $id = NULL)
78         {
79                 // Set class name
80                 $model = ucfirst($model).'_Model';
81
82                 return new $model($id);
83         }
84
85         /**
86          * Prepares the model database connection and loads the object.
87          *
88          * @param   mixed  parameter for find or object to load
89          * @return  void
90          */
91         public function __construct($id = NULL)
92         {
93                 // Set the object name and plural name
94                 $this->object_name   = strtolower(substr(get_class($this), 0, -6));
95                 $this->object_plural = inflector::plural($this->object_name);
96
97                 if (!isset($this->sorting))
98                 {
99                         // Default sorting
100                         $this->sorting = array($this->primary_key => 'asc');
101                 }
102
103                 // Initialize database
104                 $this->__initialize();
105
106                 // Clear the object
107                 $this->clear();
108
109                 if (is_object($id))
110                 {
111                         // Load an object
112                         $this->load_values((array) $id);
113                 }
114                 elseif (!empty($id))
115                 {
116                         // Find an object
117                         $this->find($id);
118                 }
119         }
120
121         /**
122          * Prepares the model database connection, determines the table name,
123          * and loads column information.
124          *
125          * @return  void
126          */
127         public function __initialize()
128         {
129                 if ( ! is_object($this->db))
130                 {
131                         // Get database instance
132                         $this->db = Database::instance($this->db);
133                 }
134
135                 if (empty($this->table_name))
136                 {
137                         // Table name is the same as the object name
138                         $this->table_name = $this->object_name;
139
140                         if ($this->table_names_plural === TRUE)
141                         {
142                                 // Make the table name plural
143                                 $this->table_name = inflector::plural($this->table_name);
144                         }
145                 }
146
147                 if (is_array($this->ignored_columns))
148                 {
149                         // Make the ignored columns mirrored = mirrored
150                         $this->ignored_columns = array_combine($this->ignored_columns, $this->ignored_columns);
151                 }
152
153                 // Load column information
154                 $this->reload_columns();
155         }
156
157         /**
158          * Allows serialization of only the object data and state, to prevent
159          * "stale" objects being unserialized, which also requires less memory.
160          *
161          * @return  array
162          */
163         public function __sleep()
164         {
165                 // Store only information about the object
166                 return array('object_name', 'object', 'changed', 'loaded', 'saved', 'sorting');
167         }
168
169         /**
170          * Prepares the database connection and reloads the object.
171          *
172          * @return  void
173          */
174         public function __wakeup()
175         {
176                 // Initialize database
177                 $this->__initialize();
178
179                 if ($this->reload_on_wakeup === TRUE)
180                 {
181                         // Reload the object
182                         $this->reload();
183                 }
184         }
185
186         /**
187          * Handles pass-through to database methods. Calls to query methods
188          * (query, get, insert, update) are not allowed. Query builder methods
189          * are chainable.
190          *
191          * @param   string  method name
192          * @param   array   method arguments
193          * @return  mixed
194          */
195         public function __call($method, array $args)
196         {
197                 if (method_exists($this->db, $method))
198                 {
199                         if (in_array($method, array('query', 'get', 'insert', 'update', 'delete')))
200                                 throw new Kohana_Exception('orm.query_methods_not_allowed');
201
202                         // Method has been applied to the database
203                         $this->db_applied[$method] = $method;
204
205                         // Number of arguments passed
206                         $num_args = count($args);
207
208                         if ($method === 'select' AND $num_args > 3)
209                         {
210                                 // Call select() manually to avoid call_user_func_array
211                                 $this->db->select($args);
212                         }
213                         else
214                         {
215                                 // We use switch here to manually call the database methods. This is
216                                 // done for speed: call_user_func_array can take over 300% longer to
217                                 // make calls. Most database methods are 4 arguments or less, so this
218                                 // avoids almost any calls to call_user_func_array.
219
220                                 switch ($num_args)
221                                 {
222                                         case 0:
223                                                 if (in_array($method, array('open_paren', 'close_paren', 'enable_cache', 'disable_cache')))
224                                                 {
225                                                         // Should return ORM, not Database
226                                                         $this->db->$method();
227                                                 }
228                                                 else
229                                                 {
230                                                         // Support for things like reset_select, reset_write, list_tables
231                                                         return $this->db->$method();
232                                                 }
233                                         break;
234                                         case 1:
235                                                 $this->db->$method($args[0]);
236                                         break;
237                                         case 2:
238                                                 $this->db->$method($args[0], $args[1]);
239                                         break;
240                                         case 3:
241                                                 $this->db->$method($args[0], $args[1], $args[2]);
242                                         break;
243                                         case 4:
244                                                 $this->db->$method($args[0], $args[1], $args[2], $args[3]);
245                                         break;
246                                         default:
247                                                 // Here comes the snail...
248                                                 call_user_func_array(array($this->db, $method), $args);
249                                         break;
250                                 }
251                         }
252
253                         return $this;
254                 }
255                 else
256                 {
257                         throw new Kohana_Exception('core.invalid_method', $method, get_class($this));
258                 }
259         }
260
261         /**
262          * Handles retrieval of all model values, relationships, and metadata.
263          *
264          * @param   string  column name
265          * @return  mixed
266          */
267         public function __get($column)
268         {
269                 if (array_key_exists($column, $this->object))
270                 {
271                         return $this->object[$column];
272                 }
273                 elseif (isset($this->related[$column]))
274                 {
275                         return $this->related[$column];
276                 }
277                 elseif ($column === 'primary_key_value')
278                 {
279                         return $this->object[$this->primary_key];
280                 }
281                 elseif ($model = $this->related_object($column))
282                 {
283                         // This handles the has_one and belongs_to relationships
284
285                         if (in_array($model->object_name, $this->belongs_to) OR ! array_key_exists($this->foreign_key($column), $model->object))
286                         {
287                                 // Foreign key lies in this table (this model belongs_to target model) OR an invalid has_one relationship
288                                 $where = array($model->table_name.'.'.$model->primary_key => $this->object[$this->foreign_key($column)]);
289                         }
290                         else
291                         {
292                                 // Foreign key lies in the target table (this model has_one target model)
293                                 $where = array($this->foreign_key($column, $model->table_name) => $this->primary_key_value);
294                         }
295
296                         // one<>alias:one relationship
297                         return $this->related[$column] = $model->find($where);
298                 }
299                 elseif (isset($this->has_many[$column]))
300                 {
301                         // Load the "middle" model
302                         $through = ORM::factory(inflector::singular($this->has_many[$column]));
303
304                         // Load the "end" model
305                         $model = ORM::factory(inflector::singular($column));
306
307                         // Join ON target model's primary key set to 'through' model's foreign key
308                         // User-defined foreign keys must be defined in the 'through' model
309                         $join_table = $through->table_name;
310                         $join_col1  = $through->foreign_key($model->object_name, $join_table);
311                         $join_col2  = $model->table_name.'.'.$model->primary_key;
312
313                         // one<>alias:many relationship
314                         return $this->related[$column] = $model
315                                 ->join($join_table, $join_col1, $join_col2)
316                                 ->where($through->foreign_key($this->object_name, $join_table), $this->object[$this->primary_key])
317                                 ->find_all();
318                 }
319                 elseif (in_array($column, $this->has_many))
320                 {
321                         // one<>many relationship
322                         $model = ORM::factory(inflector::singular($column));
323                         return $this->related[$column] = $model
324                                 ->where($this->foreign_key($column, $model->table_name), $this->object[$this->primary_key])
325                                 ->find_all();
326                 }
327                 elseif (in_array($column, $this->has_and_belongs_to_many))
328                 {
329                         // Load the remote model, always singular
330                         $model = ORM::factory(inflector::singular($column));
331
332                         if ($this->has($model, TRUE))
333                         {
334                                 // many<>many relationship
335                                 return $this->related[$column] = $model
336                                         ->in($model->table_name.'.'.$model->primary_key, $this->changed_relations[$column])
337                                         ->find_all();
338                         }
339                         else
340                         {
341                                 // empty many<>many relationship
342                                 return $this->related[$column] = $model
343                                         ->where($model->table_name.'.'.$model->primary_key, NULL)
344                                         ->find_all();
345                         }
346                 }
347                 elseif (isset($this->ignored_columns[$column]))
348                 {
349                         return NULL;
350                 }
351                 elseif (in_array($column, array
352                         (
353                                 'object_name', 'object_plural', // Object
354                                 'primary_key', 'primary_val', 'table_name', 'table_columns', // Table
355                                 'loaded', 'saved', // Status
356                                 'has_one', 'belongs_to', 'has_many', 'has_and_belongs_to_many', 'load_with' // Relationships
357                         )))
358                 {
359                         // Model meta information
360                         return $this->$column;
361                 }
362                 else
363                 {
364                         throw new Kohana_Exception('core.invalid_property', $column, get_class($this));
365                 }
366         }
367
368         /**
369          * Handles setting of all model values, and tracks changes between values.
370          *
371          * @param   string  column name
372          * @param   mixed   column value
373          * @return  void
374          */
375         public function __set($column, $value)
376         {
377                 if (isset($this->ignored_columns[$column]))
378                 {
379                         return NULL;
380                 }
381                 elseif (isset($this->object[$column]) OR array_key_exists($column, $this->object))
382                 {
383                         if (isset($this->table_columns[$column]))
384                         {
385                                 // Data has changed
386                                 $this->changed[$column] = $column;
387
388                                 // Object is no longer saved
389                                 $this->saved = FALSE;
390                         }
391
392                         $this->object[$column] = $this->load_type($column, $value);
393                 }
394                 elseif (in_array($column, $this->has_and_belongs_to_many) AND is_array($value))
395                 {
396                         // Load relations
397                         $model = ORM::factory(inflector::singular($column));
398
399                         if ( ! isset($this->object_relations[$column]))
400                         {
401                                 // Load relations
402                                 $this->has($model);
403                         }
404
405                         // Change the relationships
406                         $this->changed_relations[$column] = $value;
407
408                         if (isset($this->related[$column]))
409                         {
410                                 // Force a reload of the relationships
411                                 unset($this->related[$column]);
412                         }
413                 }
414                 else
415                 {
416                         throw new Kohana_Exception('core.invalid_property', $column, get_class($this));
417                 }
418         }
419
420         /**
421          * Checks if object data is set.
422          *
423          * @param   string  column name
424          * @return  boolean
425          */
426         public function __isset($column)
427         {
428                 return (isset($this->object[$column]) OR isset($this->related[$column]));
429         }
430
431         /**
432          * Unsets object data.
433          *
434          * @param   string  column name
435          * @return  void
436          */
437         public function __unset($column)
438         {
439                 unset($this->object[$column], $this->changed[$column], $this->related[$column]);
440         }
441
442         /**
443          * Displays the primary key of a model when it is converted to a string.
444          *
445          * @return  string
446          */
447         public function __toString()
448         {
449                 return (string) $this->object[$this->primary_key];
450         }
451
452         /**
453          * Returns the values of this object as an array.
454          *
455          * @return  array
456          */
457         public function as_array()
458         {
459                 $object = array();
460
461                 foreach ($this->object as $key => $val)
462                 {
463                         // Reconstruct the array (calls __get)
464                         $object[$key] = $this->$key;
465                 }
466
467                 return $object;
468         }
469
470         /**
471          * Binds another one-to-one object to this model.  One-to-one objects
472          * can be nested using 'object1:object2' syntax
473          *
474          * @param string $target_path
475          * @return void
476          */
477         public function with($target_path)
478         {
479                 if (isset($this->with_applied[$target_path]))
480                 {
481                         // Don't join anything already joined
482                         return $this;
483                 }
484
485                 // Split object parts
486                 $objects = explode(':', $target_path);
487                 $target  = $this;
488                 foreach ($objects as $object)
489                 {
490                         // Go down the line of objects to find the given target
491                         $parent = $target;
492                         $target = $parent->related_object($object);
493
494                         if ( ! $target)
495                         {
496                                 // Can't find related object
497                                 return $this;
498                         }
499                 }
500
501                 $target_name = $object;
502
503                 // Pop-off top object to get the parent object (user:photo:tag becomes user:photo - the parent table prefix)
504                 array_pop($objects);
505                 $parent_path = implode(':', $objects);
506
507                 if (empty($parent_path))
508                 {
509                         // Use this table name itself for the parent object
510                         $parent_path = $this->table_name;
511                 }
512                 else
513                 {
514                         if( ! isset($this->with_applied[$parent_path]))
515                         {
516                                 // If the parent object hasn't been joined yet, do it first (otherwise LEFT JOINs fail)
517                                 $this->with($parent_path);
518                         }
519                 }
520
521                 // Add to with_applied to prevent duplicate joins
522                 $this->with_applied[$target_path] = TRUE;
523
524                 // Use the keys of the empty object to determine the columns
525                 $select = array_keys($target->object);
526                 foreach ($select as $i => $column)
527                 {
528                         // Add the prefix so that load_result can determine the relationship
529                         $select[$i] = $target_path.'.'.$column.' AS '.$target_path.':'.$column;
530                 }
531
532
533                 // Select all of the prefixed keys in the object
534                 $this->db->select($select);
535
536                 if (in_array($target->object_name, $parent->belongs_to) OR ! isset($target->object[$parent->foreign_key($target_name)]))
537                 {
538                         // Parent belongs_to target, use target's primary key as join column
539                         $join_col1 = $target->foreign_key(TRUE, $target_path);
540                         $join_col2 = $parent->foreign_key($target_name, $parent_path);
541                 }
542                 else
543                 {
544                         // Parent has_one target, use parent's primary key as join column
545                         $join_col2 = $parent->foreign_key(TRUE, $parent_path);
546                         $join_col1 = $parent->foreign_key($target_name, $target_path);
547                 }
548
549                 // This allows for models to use different table prefixes (sharing the same database)
550                 $join_table = new Database_Expression($target->db->table_prefix().$target->table_name.' AS '.$this->db->table_prefix().$target_path);
551
552                 // Join the related object into the result
553                 $this->db->join($join_table, $join_col1, $join_col2, 'LEFT');
554
555                 return $this;
556         }
557
558         /**
559          * Finds and loads a single database row into the object.
560          *
561          * @chainable
562          * @param   mixed  primary key or an array of clauses
563          * @return  ORM
564          */
565         public function find($id = NULL)
566         {
567                 if ($id !== NULL)
568                 {
569                         if (is_array($id))
570                         {
571                                 // Search for all clauses
572                                 $this->db->where($id);
573                         }
574                         else
575                         {
576                                 // Search for a specific column
577                                 $this->db->where($this->table_name.'.'.$this->unique_key($id), $id);
578                         }
579                 }
580
581                 return $this->load_result();
582         }
583
584         /**
585          * Finds multiple database rows and returns an iterator of the rows found.
586          *
587          * @chainable
588          * @param   integer  SQL limit
589          * @param   integer  SQL offset
590          * @return  ORM_Iterator
591          */
592         public function find_all($limit = NULL, $offset = NULL)
593         {
594                 if ($limit !== NULL AND ! isset($this->db_applied['limit']))
595                 {
596                         // Set limit
597                         $this->limit($limit);
598                 }
599
600                 if ($offset !== NULL AND ! isset($this->db_applied['offset']))
601                 {
602                         // Set offset
603                         $this->offset($offset);
604                 }
605
606                 return $this->load_result(TRUE);
607         }
608
609         /**
610          * Creates a key/value array from all of the objects available. Uses find_all
611          * to find the objects.
612          *
613          * @param   string  key column
614          * @param   string  value column
615          * @return  array
616          */
617         public function select_list($key = NULL, $val = NULL)
618         {
619                 if ($key === NULL)
620                 {
621                         $key = $this->primary_key;
622                 }
623
624                 if ($val === NULL)
625                 {
626                         $val = $this->primary_val;
627                 }
628
629                 // Return a select list from the results
630                 return $this->select($key, $val)->find_all()->select_list($key, $val);
631         }
632
633         /**
634          * Validates the current object. This method should generally be called
635          * via the model, after the $_POST Validation object has been created.
636          *
637          * @param   object   Validation array
638          * @return  boolean
639          */
640         public function validate(Validation $array, $save = FALSE)
641         {
642                 $safe_array = $array->safe_array();
643
644                 if ( ! $array->submitted())
645                 {
646                         foreach ($safe_array as $key => $value)
647                         {
648                                 // Get the value from this object
649                                 $value = $this->$key;
650
651                                 if (is_object($value) AND $value instanceof ORM_Iterator)
652                                 {
653                                         // Convert the value to an array of primary keys
654                                         $value = $value->primary_key_array();
655                                 }
656
657                                 // Pre-fill data
658                                 $array[$key] = $value;
659                         }
660                 }
661
662                 // Validate the array
663                 if ($status = $array->validate())
664                 {
665                         // Grab only set fields (excludes missing data, unlike safe_array)
666                         $fields = $array->as_array();
667
668                         foreach ($fields as $key => $value)
669                         {
670                                 if (isset($safe_array[$key]))
671                                 {
672                                         // Set new data, ignoring any missing fields or fields without rules
673                                         $this->$key = $value;
674                                 }
675                         }
676
677                         if ($save === TRUE OR is_string($save))
678                         {
679                                 // Save this object
680                                 $this->save();
681
682                                 if (is_string($save))
683                                 {
684                                         // Redirect to the saved page
685                                         url::redirect($save);
686                                 }
687                         }
688                 }
689
690                 // Return validation status
691                 return $status;
692         }
693
694         /**
695          * Saves the current object.
696          *
697          * @chainable
698          * @return  ORM
699          */
700         public function save()
701         {
702                 if ( ! empty($this->changed))
703                 {
704                         $data = array();
705                         foreach ($this->changed as $column)
706                         {
707                                 // Compile changed data
708                                 $data[$column] = $this->object[$column];
709                         }
710
711                         if ($this->loaded === TRUE)
712                         {
713                                 $query = $this->db
714                                         ->where($this->primary_key, $this->object[$this->primary_key])
715                                         ->update($this->table_name, $data);
716
717                                 // Object has been saved
718                                 $this->saved = TRUE;
719                         }
720                         else
721                         {
722                                 $query = $this->db
723                                         ->insert($this->table_name, $data);
724
725                                 if ($query->count() > 0)
726                                 {
727                                         if (empty($this->object[$this->primary_key]))
728                                         {
729                                                 // Load the insert id as the primary key
730                                                 $this->object[$this->primary_key] = $query->insert_id();
731                                         }
732
733                                         // Object is now loaded and saved
734                                         $this->loaded = $this->saved = TRUE;
735                                 }
736                         }
737
738                         if ($this->saved === TRUE)
739                         {
740                                 // All changes have been saved
741                                 $this->changed = array();
742                         }
743                 }
744
745                 if ($this->saved === TRUE AND ! empty($this->changed_relations))
746                 {
747                         foreach ($this->changed_relations as $column => $values)
748                         {
749                                 // All values that were added
750                                 $added = array_diff($values, $this->object_relations[$column]);
751
752                                 // All values that were saved
753                                 $removed = array_diff($this->object_relations[$column], $values);
754
755                                 if (empty($added) AND empty($removed))
756                                 {
757                                         // No need to bother
758                                         continue;
759                                 }
760
761                                 // Clear related columns
762                                 unset($this->related[$column]);
763
764                                 // Load the model
765                                 $model = ORM::factory(inflector::singular($column));
766
767                                 if (($join_table = array_search($column, $this->has_and_belongs_to_many)) === FALSE)
768                                         continue;
769
770                                 if (is_int($join_table))
771                                 {
772                                         // No "through" table, load the default JOIN table
773                                         $join_table = $model->join_table($this->table_name);
774                                 }
775
776                                 // Foreign keys for the join table
777                                 $object_fk  = $this->foreign_key(NULL);
778                                 $related_fk = $model->foreign_key(NULL);
779
780                                 if ( ! empty($added))
781                                 {
782                                         foreach ($added as $id)
783                                         {
784                                                 // Insert the new relationship
785                                                 $this->db->insert($join_table, array
786                                                 (
787                                                         $object_fk  => $this->object[$this->primary_key],
788                                                         $related_fk => $id,
789                                                 ));
790                                         }
791                                 }
792
793                                 if ( ! empty($removed))
794                                 {
795                                         $this->db
796                                                 ->where($object_fk, $this->object[$this->primary_key])
797                                                 ->in($related_fk, $removed)
798                                                 ->delete($join_table);
799                                 }
800
801                                 // Clear all relations for this column
802                                 unset($this->object_relations[$column], $this->changed_relations[$column]);
803                         }
804                 }
805
806                 return $this;
807         }
808
809         /**
810          * Deletes the current object from the database. This does NOT destroy
811          * relationships that have been created with other objects.
812          *
813          * @chainable
814          * @return  ORM
815          */
816         public function delete($id = NULL)
817         {
818                 if ($id === NULL AND $this->loaded)
819                 {
820                         // Use the the primary key value
821                         $id = $this->object[$this->primary_key];
822                 }
823
824                 // Delete this object
825                 $this->db->where($this->primary_key, $id)->delete($this->table_name);
826
827                 return $this->clear();
828         }
829
830         /**
831          * Delete all objects in the associated table. This does NOT destroy
832          * relationships that have been created with other objects.
833          *
834          * @chainable
835          * @param   array  ids to delete
836          * @return  ORM
837          */
838         public function delete_all($ids = NULL)
839         {
840                 if (is_array($ids))
841                 {
842                         // Delete only given ids
843                         $this->db->in($this->primary_key, $ids);
844                 }
845                 elseif (is_null($ids))
846                 {
847                         // Delete all records
848                         $this->db->where('1=1');
849                 }
850                 else
851                 {
852                         // Do nothing - safeguard
853                         return $this;
854                 }
855
856                 // Delete all objects
857                 $this->db->delete($this->table_name);
858
859                 return $this->clear();
860         }
861
862         /**
863          * Unloads the current object and clears the status.
864          *
865          * @chainable
866          * @return  ORM
867          */
868         public function clear()
869         {
870                 // Create an array with all the columns set to NULL
871                 $columns = array_keys($this->table_columns);
872                 $values  = array_combine($columns, array_fill(0, count($columns), NULL));
873
874                 // Replace the current object with an empty one
875                 $this->load_values($values);
876
877                 return $this;
878         }
879
880         /**
881          * Reloads the current object from the database.
882          *
883          * @chainable
884          * @return  ORM
885          */
886         public function reload()
887         {
888                 return $this->find($this->object[$this->primary_key]);
889         }
890
891         /**
892          * Reload column definitions.
893          *
894          * @chainable
895          * @param   boolean  force reloading
896          * @return  ORM
897          */
898         public function reload_columns($force = FALSE)
899         {
900                 if ($force === TRUE OR empty($this->table_columns))
901                 {
902                         if (isset(ORM::$column_cache[$this->object_name]))
903                         {
904                                 // Use cached column information
905                                 $this->table_columns = ORM::$column_cache[$this->object_name];
906                         }
907                         else
908                         {
909                                 // Load table columns
910                                 ORM::$column_cache[$this->object_name] = $this->table_columns = $this->list_fields();
911                         }
912                 }
913
914                 return $this;
915         }
916
917         /**
918          * Tests if this object has a relationship to a different model.
919          *
920          * @param   object   related ORM model
921          * @param   boolean  check for any relations to given model
922          * @return  boolean
923          */
924         public function has(ORM $model, $any = FALSE)
925         {
926                 // Determine plural or singular relation name
927                 $related = ($model->table_names_plural === TRUE) ? $model->object_plural : $model->object_name;
928
929                 if (($join_table = array_search($related, $this->has_and_belongs_to_many)) === FALSE)
930                         return FALSE;
931
932                 if (is_int($join_table))
933                 {
934                         // No "through" table, load the default JOIN table
935                         $join_table = $model->join_table($this->table_name);
936                 }
937
938                 if ( ! isset($this->object_relations[$related]))
939                 {
940                         // Load the object relationships
941                         $this->changed_relations[$related] = $this->object_relations[$related] = $this->load_relations($join_table, $model);
942                 }
943
944                 if ( ! $model->empty_primary_key())
945                 {
946                         // Check if a specific object exists
947                         return in_array($model->primary_key_value, $this->changed_relations[$related]);
948                 }
949                 elseif ($any)
950                 {
951                         // Check if any relations to given model exist
952                         return ! empty($this->changed_relations[$related]);
953                 }
954                 else
955                 {
956                         return FALSE;
957                 }
958         }
959
960         /**
961          * Adds a new relationship to between this model and another.
962          *
963          * @param   object   related ORM model
964          * @return  boolean
965          */
966         public function add(ORM $model)
967         {
968                 if ($this->has($model))
969                         return TRUE;
970
971                 // Get the faked column name
972                 $column = $model->object_plural;
973
974                 // Add the new relation to the update
975                 $this->changed_relations[$column][] = $model->primary_key_value;
976
977                 if (isset($this->related[$column]))
978                 {
979                         // Force a reload of the relationships
980                         unset($this->related[$column]);
981                 }
982
983                 return TRUE;
984         }
985
986         /**
987          * Adds a new relationship to between this model and another.
988          *
989          * @param   object   related ORM model
990          * @return  boolean
991          */
992         public function remove(ORM $model)
993         {
994                 if ( ! $this->has($model))
995                         return FALSE;
996
997                 // Get the faked column name
998                 $column = $model->object_plural;
999
1000                 if (($key = array_search($model->primary_key_value, $this->changed_relations[$column])) === FALSE)
1001                         return FALSE;
1002
1003                 // Remove the relationship
1004                 unset($this->changed_relations[$column][$key]);
1005
1006                 if (isset($this->related[$column]))
1007                 {
1008                         // Force a reload of the relationships
1009                         unset($this->related[$column]);
1010                 }
1011
1012                 return TRUE;
1013         }
1014
1015         /**
1016          * Count the number of records in the table.
1017          *
1018          * @return  integer
1019          */
1020         public function count_all()
1021         {
1022                 // Return the total number of records in a table
1023                 return $this->db->count_records($this->table_name);
1024         }
1025
1026         /**
1027          * Proxy method to Database list_fields.
1028          *
1029          * @param   string  table name or NULL to use this table
1030          * @return  array
1031          */
1032         public function list_fields($table = NULL)
1033         {
1034                 if ($table === NULL)
1035                 {
1036                         $table = $this->table_name;
1037                 }
1038
1039                 // Proxy to database
1040                 return $this->db->list_fields($table);
1041         }
1042
1043         /**
1044          * Proxy method to Database field_data.
1045          *
1046          * @param   string  table name
1047          * @return  array
1048          */
1049         public function field_data($table)
1050         {
1051                 // Proxy to database
1052                 return $this->db->field_data($table);
1053         }
1054
1055         /**
1056          * Proxy method to Database field_data.
1057          *
1058          * @chainable
1059          * @param   string  SQL query to clear
1060          * @return  ORM
1061          */
1062         public function clear_cache($sql = NULL)
1063         {
1064                 // Proxy to database
1065                 $this->db->clear_cache($sql);
1066
1067                 ORM::$column_cache = array();
1068
1069                 return $this;
1070         }
1071
1072         /**
1073          * Returns the unique key for a specific value. This method is expected
1074          * to be overloaded in models if the model has other unique columns.
1075          *
1076          * @param   mixed   unique value
1077          * @return  string
1078          */
1079         public function unique_key($id)
1080         {
1081                 return $this->primary_key;
1082         }
1083
1084         /**
1085          * Determines the name of a foreign key for a specific table.
1086          *
1087          * @param   string  related table name
1088          * @param   string  prefix table name (used for JOINs)
1089          * @return  string
1090          */
1091         public function foreign_key($table = NULL, $prefix_table = NULL)
1092         {
1093                 if ($table === TRUE)
1094                 {
1095                         if (is_string($prefix_table))
1096                         {
1097                                 // Use prefix table name and this table's PK
1098                                 return $prefix_table.'.'.$this->primary_key;
1099                         }
1100                         else
1101                         {
1102                                 // Return the name of this table's PK
1103                                 return $this->table_name.'.'.$this->primary_key;
1104                         }
1105                 }
1106
1107                 if (is_string($prefix_table))
1108                 {
1109                         // Add a period for prefix_table.column support
1110                         $prefix_table .= '.';
1111                 }
1112
1113                 if (isset($this->foreign_key[$table]))
1114                 {
1115                         // Use the defined foreign key name, no magic here!
1116                         $foreign_key = $this->foreign_key[$table];
1117                 }
1118                 else
1119                 {
1120                         if ( ! is_string($table) OR ! array_key_exists($table.'_'.$this->primary_key, $this->object))
1121                         {
1122                                 // Use this table
1123                                 $table = $this->table_name;
1124
1125                                 if (strpos($table, '.') !== FALSE)
1126                                 {
1127                                         // Hack around support for PostgreSQL schemas
1128                                         list ($schema, $table) = explode('.', $table, 2);
1129                                 }
1130
1131                                 if ($this->table_names_plural === TRUE)
1132                                 {
1133                                         // Make the key name singular
1134                                         $table = inflector::singular($table);
1135                                 }
1136                         }
1137
1138                         $foreign_key = $table.'_'.$this->primary_key;
1139                 }
1140
1141                 return $prefix_table.$foreign_key;
1142         }
1143
1144         /**
1145          * This uses alphabetical comparison to choose the name of the table.
1146          *
1147          * Example: The joining table of users and roles would be roles_users,
1148          * because "r" comes before "u". Joining products and categories would
1149          * result in categories_products, because "c" comes before "p".
1150          *
1151          * Example: zoo > zebra > robber > ocean > angel > aardvark
1152          *
1153          * @param   string  table name
1154          * @return  string
1155          */
1156         public function join_table($table)
1157         {
1158                 if ($this->table_name > $table)
1159                 {
1160                         $table = $table.'_'.$this->table_name;
1161                 }
1162                 else
1163                 {
1164                         $table = $this->table_name.'_'.$table;
1165                 }
1166
1167                 return $table;
1168         }
1169
1170         /**
1171          * Returns an ORM model for the given object name;
1172          *
1173          * @param   string  object name
1174          * @return  ORM
1175          */
1176         protected function related_object($object)
1177         {
1178                 if (isset($this->has_one[$object]))
1179                 {
1180                         $object = ORM::factory($this->has_one[$object]);
1181                 }
1182                 elseif (isset($this->belongs_to[$object]))
1183                 {
1184                         $object = ORM::factory($this->belongs_to[$object]);
1185                 }
1186                 elseif (in_array($object, $this->has_one) OR in_array($object, $this->belongs_to))
1187                 {
1188                         $object = ORM::factory($object);
1189                 }
1190                 else
1191                 {
1192                         return FALSE;
1193                 }
1194
1195                 return $object;
1196         }
1197
1198         /**
1199          * Loads an array of values into into the current object.
1200          *
1201          * @chainable
1202          * @param   array  values to load
1203          * @return  ORM
1204          */
1205         public function load_values(array $values)
1206         {
1207                 if (array_key_exists($this->primary_key, $values))
1208                 {
1209                         // Replace the object and reset the object status
1210                         $this->object = $this->changed = $this->related = array();
1211
1212                         // Set the loaded and saved object status based on the primary key
1213                         $this->loaded = $this->saved = ($values[$this->primary_key] !== NULL);
1214                 }
1215
1216                 // Related objects
1217                 $related = array();
1218
1219                 foreach ($values as $column => $value)
1220                 {
1221                         if (strpos($column, ':') === FALSE)
1222                         {
1223                                 if (isset($this->table_columns[$column]))
1224                                 {
1225                                         // The type of the value can be determined, convert the value
1226                                         $value = $this->load_type($column, $value);
1227                                 }
1228
1229                                 $this->object[$column] = $value;
1230                         }
1231                         else
1232                         {
1233                                 list ($prefix, $column) = explode(':', $column, 2);
1234
1235                                 $related[$prefix][$column] = $value;
1236                         }
1237                 }
1238
1239                 if ( ! empty($related))
1240                 {
1241                         foreach ($related as $object => $values)
1242                         {
1243                                 // Load the related objects with the values in the result
1244                                 $this->related[$object] = $this->related_object($object)->load_values($values);
1245                         }
1246                 }
1247
1248                 return $this;
1249         }
1250
1251         /**
1252          * Loads a value according to the types defined by the column metadata.
1253          *
1254          * @param   string  column name
1255          * @param   mixed   value to load
1256          * @return  mixed
1257          */
1258         protected function load_type($column, $value)
1259         {
1260                 $type = gettype($value);
1261                 if ($type == 'object' OR $type == 'array' OR ! isset($this->table_columns[$column]))
1262                         return $value;
1263
1264                 // Load column data
1265                 $column = $this->table_columns[$column];
1266
1267                 if ($value === NULL AND ! empty($column['null']))
1268                         return $value;
1269
1270                 if ( ! empty($column['binary']) AND ! empty($column['exact']) AND (int) $column['length'] === 1)
1271                 {
1272                         // Use boolean for BINARY(1) fields
1273                         $column['type'] = 'boolean';
1274                 }
1275
1276                 switch ($column['type'])
1277                 {
1278                         case 'int':
1279                                 if ($value === '' AND ! empty($column['null']))
1280                                 {
1281                                         // Forms will only submit strings, so empty integer values must be null
1282                                         $value = NULL;
1283                                 }
1284                                 elseif ((float) $value > PHP_INT_MAX)
1285                                 {
1286                                         // This number cannot be represented by a PHP integer, so we convert it to a string
1287                                         $value = (string) $value;
1288                                 }
1289                                 else
1290                                 {
1291                                         $value = (int) $value;
1292                                 }
1293                         break;
1294                         case 'float':
1295                                 $value = (float) $value;
1296                         break;
1297                         case 'boolean':
1298                                 $value = (bool) $value;
1299                         break;
1300                         case 'string':
1301                                 $value = (string) $value;
1302                         break;
1303                 }
1304
1305                 return $value;
1306         }
1307
1308         /**
1309          * Loads a database result, either as a new object for this model, or as
1310          * an iterator for multiple rows.
1311          *
1312          * @chainable
1313          * @param   boolean       return an iterator or load a single row
1314          * @return  ORM           for single rows
1315          * @return  ORM_Iterator  for multiple rows
1316          */
1317         protected function load_result($array = FALSE)
1318         {
1319                 if ($array === FALSE)
1320                 {
1321                         // Only fetch 1 record
1322                         $this->db->limit(1);
1323                 }
1324
1325                 if ( ! isset($this->db_applied['select']))
1326                 {
1327                         // Select all columns by default
1328                         $this->db->select($this->table_name.'.*');
1329                 }
1330
1331                 if ( ! empty($this->load_with))
1332                 {
1333                         foreach ($this->load_with as $alias => $object)
1334                         {
1335                                 // Join each object into the results
1336                                 if (is_string($alias))
1337                                 {
1338                                         // Use alias
1339                                         $this->with($alias);
1340                                 }
1341                                 else
1342                                 {
1343                                         // Use object
1344                                         $this->with($object);
1345                                 }
1346                         }
1347                 }
1348
1349                 if ( ! isset($this->db_applied['orderby']) AND ! empty($this->sorting))
1350                 {
1351                         $sorting = array();
1352                         foreach ($this->sorting as $column => $direction)
1353                         {
1354                                 if (strpos($column, '.') === FALSE)
1355                                 {
1356                                         // Keeps sorting working properly when using JOINs on
1357                                         // tables with columns of the same name
1358                                         $column = $this->table_name.'.'.$column;
1359                                 }
1360
1361                                 $sorting[$column] = $direction;
1362                         }
1363
1364                         // Apply the user-defined sorting
1365                         $this->db->orderby($sorting);
1366                 }
1367
1368                 // Load the result
1369                 $result = $this->db->get($this->table_name);
1370
1371                 if ($array === TRUE)
1372                 {
1373                         // Return an iterated result
1374                         return new ORM_Iterator($this, $result);
1375                 }
1376
1377                 if ($result->count() === 1)
1378                 {
1379                         // Load object values
1380                         $this->load_values($result->result(FALSE)->current());
1381                 }
1382                 else
1383                 {
1384                         // Clear the object, nothing was found
1385                         $this->clear();
1386                 }
1387
1388                 return $this;
1389         }
1390
1391         /**
1392          * Return an array of all the primary keys of the related table.
1393          *
1394          * @param   string  table name
1395          * @param   object  ORM model to find relations of
1396          * @return  array
1397          */
1398         protected function load_relations($table, ORM $model)
1399         {
1400                 // Save the current query chain (otherwise the next call will clash)
1401                 $this->db->push();
1402
1403                 $query = $this->db
1404                         ->select($model->foreign_key(NULL).' AS id')
1405                         ->from($table)
1406                         ->where($this->foreign_key(NULL, $table), $this->object[$this->primary_key])
1407                         ->get()
1408                         ->result(TRUE);
1409
1410                 $this->db->pop();
1411
1412                 $relations = array();
1413                 foreach ($query as $row)
1414                 {
1415                         $relations[] = $row->id;
1416                 }
1417
1418                 return $relations;
1419         }
1420
1421         /**
1422          * Returns whether or not primary key is empty
1423          *
1424          * @return bool
1425          */
1426         protected function empty_primary_key()
1427         {
1428                 return (empty($this->object[$this->primary_key]) AND $this->object[$this->primary_key] !== '0');
1429         }
1430
1431 } // End ORM