Newer
Older
<?php
/*********************************************************************
class.orm.php
Simple ORM (Object Relational Mapper) for PHP5 based on Django's ORM,
except that complex filter operations are not supported. The ORM simply
supports ANDed filter operations without any GROUP BY support.
Jared Hancock <jared@osticket.com>
Copyright (c) 2006-2013 osTicket
http://www.osticket.com
Released under the GNU General Public License WITHOUT ANY WARRANTY.
See LICENSE.TXT for details.
vim: expandtab sw=4 ts=4 sts=4:
**********************************************************************/
class OrmException extends Exception {}
class OrmConfigurationException extends Exception {}
/**
* Meta information about a model including edges (relationships), table
* name, default sorting information, database fields, etc.
*
* This class is constructed and built automatically from the model's
* ::_inspect method using a class's ::$meta array.
*/
class ModelMeta implements ArrayAccess {
var $base = array();
function __construct($model) {
$meta = $model::$meta;
// TODO: Merge ModelMeta from parent model (if inherited)
if (!$meta['table'])
throw new OrmConfigurationException(
__('Model does not define meta.table'), $model);
elseif (!$meta['pk'])
throw new OrmConfigurationException(
__('Model does not define meta.pk'), $model);
// Ensure other supported fields are set and are arrays
foreach (array('pk', 'ordering', 'deferred') as $f) {
if (!isset($meta[$f]))
$meta[$f] = array();
elseif (!is_array($meta[$f]))
$meta[$f] = array($meta[$f]);
}
// Break down foreign-key metadata
if (!isset($meta['joins']))
$meta['joins'] = array();
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
foreach ($meta['joins'] as $field => &$j) {
if (isset($j['reverse'])) {
list($model, $key) = explode('.', $j['reverse']);
$info = $model::$meta['joins'][$key];
$constraint = array();
if (!is_array($info['constraint']))
throw new OrmConfigurationException(sprintf(__(
// `reverse` here is the reverse of an ORM relationship
'%s: Reverse does not specify any constraints'),
$j['reverse']));
foreach ($info['constraint'] as $foreign => $local) {
list(,$field) = explode('.', $local);
$constraint[$field] = "$model.$foreign";
}
$j['constraint'] = $constraint;
if (!isset($j['list']))
$j['list'] = true;
}
// XXX: Make this better (ie. composite keys)
$keys = array_keys($j['constraint']);
$foreign = $j['constraint'][$keys[0]];
$j['fkey'] = explode('.', $foreign);
$j['local'] = $keys[0];
}
$this->base = $meta;
}
function offsetGet($field) {
if (!isset($this->base[$field]))
$this->setupLazy($field);
return $this->base[$field];
}
function offsetSet($field, $what) {
$this->base[$field] = $what;
}
function offsetExists($field) {
return isset($this->base[$field]);
}
function offsetUnset($field) {
throw new Exception('Model MetaData is immutable');
}
function setupLazy($what) {
switch ($what) {
case 'fields':
$this->base['fields'] = self::inspectFields();
break;
case 'newInstance':
$class_repr = sprintf(
'O:%d:"%s":0:{}',
strlen($this->model), $this->model
);
$this->base['newInstance'] = function() use ($class_repr) {
return unserialize($class_repr);
};
break;
default:
throw new Exception($what . ': No such meta-data');
}
}
function inspectFields() {
return DbEngine::getCompiler()->inspectTable($this['table']);
}
}
class VerySimpleModel {
static $meta = array(
'table' => false,
'ordering' => false,
'pk' => false
);
var $ht;
var $dirty = array();
var $__deferred__ = array();
function __construct($row) {
$this->ht = $row;
}
function get($field, $default=false) {
if (array_key_exists($field, $this->ht))
return $this->ht[$field];
elseif (isset(static::$meta['joins'][$field])) {
if (!static::$meta instanceof ModelMeta)
static::_inspect();
$j = static::$meta['joins'][$field];
// Support instrumented lists and such
if (isset($this->ht[$j['local']])
&& isset($j['list']) && $j['list']) {
$fkey = $j['fkey'];
$v = $this->ht[$name] = new InstrumentedList(
// Send Model, Foriegn-Field, Local-Id
array($fkey[0], $fkey[1], $this->get($j['local']))
);
return $v;
}
// Support relationships
elseif (isset($j['fkey'])
&& ($class = $j['fkey'][0])
&& class_exists($class)) {
$v = $this->ht[$field] = $class::lookup(
array($j['fkey'][1] => $this->ht[$j['local']]));
return $v;
}
elseif (isset($this->__deferred__[$field])) {
// Fetch deferred field
$row = static::objects()->filter($this->getPk())
->values_flat($field)
->one();
if ($row)
return $this->ht[$field] = $row[0];
}
elseif ($field == 'pk') {
return $this->getPk();
}
if (isset($default))
return $default;
// TODO: Inspect fields from database before throwing this error
throw new OrmException(sprintf(__('%s: %s: Field not defined'),
get_class($this), $field));
}
function __get($field) {
return $this->get($field, null);
}
function __isset($field) {
return array_key_exists($field, $this->ht)
|| isset(static::$meta['joins'][$field]);
function __unset($field) {
unset($this->ht[$field]);
}
// Update of foreign-key by assignment to model instance
if (isset(static::$meta['joins'][$field])) {
$j = static::$meta['joins'][$field];
if ($j['list'] && ($value instanceof InstrumentedList)) {
// Magic list property
$this->ht[$field] = $value;
return;
}
if ($value === null) {
// Pass. Set local field to NULL in logic below
}
elseif ($value instanceof $j['fkey'][0]) {
if ($value->__new__)
$value->save();
// Capture the object under the object's field name
$this->ht[$field] = $value;
$value = $value->get($j['fkey'][1]);
// Fall through to the standard logic below
}
else
throw new InvalidArgumentException(
sprintf(__('Expecting NULL or instance of %s'), $j['fkey'][0]));
// Capture the foreign key id value
$field = $j['local'];
}
// XXX: Fully support or die if updating pk
// XXX: The contents of $this->dirty should be the value after the
// previous fetch or save. For instance, if the value is changed more
// than once, the original value should be preserved in the dirty list
// on the second edit.
$old = isset($this->ht[$field]) ? $this->ht[$field] : null;
if ($old != $value) {
$this->dirty[$field] = $old;
$this->ht[$field] = $value;
}
}
function __set($field, $value) {
return $this->set($field, $value);
}
function setAll($props) {
foreach ($props as $field=>$value)
$this->set($field, $value);
}
static function __oninspect() {}
static function _inspect() {
if (!static::$meta instanceof ModelMeta) {
static::$meta = new ModelMeta(get_called_class());
// Let the model participate
static::__oninspect();
/**
* objects
*
* Retrieve a QuerySet for this model class which can be used to fetch
* models from the connected database. Subclasses can override this
* method to apply forced constraints on the QuerySet.
*/
static function objects() {
return new QuerySet(get_called_class());
}
/**
* lookup
*
* Retrieve a record by its primary key. This method may be short
* circuited by model caching if the record has already been loaded by
* the database. In such a case, the database will not be consulted for
* the model's data.
*
* This method can be called with an array of keyword arguments matching
* the PK of the object or the values of the primary key. Both of these
* usages are correct:
*
* >>> User::lookup(1)
* >>> User::lookup(array('id'=>1))
*
* For composite primary keys and the first usage, pass the values in
* the order they are given in the Model's 'pk' declaration in its meta
* data.
*
* Parameters:
* $criteria - (mixed) primary key for the sought model either as
* arguments or key/value array as the function's first argument
*/
// Model::lookup(1), where >1< is the pk value
if (!is_array($criteria)) {
$criteria = array();
foreach (func_get_args() as $i=>$f)
$criteria[static::$meta['pk'][$i]] = $f;
}
if ($cached = ModelInstanceManager::checkCache(get_called_class(),
$criteria))
return $cached;
return static::objects()->filter($criteria)->one();
$ex = DbEngine::delete($this);
try {
$ex->execute();
if ($ex->affected_rows() != 1)
return false;
Signal::send('model.deleted', $this);
}
catch (OrmException $e) {
return false;
}
}
function save($refetch=false) {
if (count($this->dirty) === 0)
$ex = DbEngine::save($this);
try {
$ex->execute();
if ($ex->affected_rows() != 1)
return false;
catch (OrmException $e) {
return false;
$pk = static::$meta['pk'];
if ($this->__new__) {
if (count($pk) == 1)
// XXX: Ensure AUTO_INCREMENT is set for the field
$this->ht[$pk[0]] = $ex->insert_id();
Signal::send('model.created', $this);
}
else {
$data = array('dirty' => $this->dirty);
Signal::send('model.updated', $this, $data);
}
# Refetch row from database
# XXX: Too much voodoo
if ($refetch) {
// Uncache so that the lookup will not be short-cirtuited to
// return this object
ModelInstanceManager::uncache($this);
$self = static::lookup($this->get('pk'));
$this->ht = $self->ht;
}
$this->dirty = array();
return $this->get($pk[0]);
}
static function create($ht=false) {
if (!$ht) $ht=array();
$class = get_called_class();
$i = new $class(array());
$i->__new__ = true;
foreach ($ht as $field=>$value)
if (!is_array($value))
$i->set($field, $value);
return $i;
}
private function getPk() {
$pk = array();
foreach ($this::$meta['pk'] as $f)
$pk[$f] = $this->ht[$f];
return $pk;
}
}
class SqlFunction {
function SqlFunction($name) {
$this->func = $name;
$this->args = array_slice(func_get_args(), 1);
}
function toSql($compiler=false) {
$args = (count($this->args)) ? implode(',', db_input($this->args)) : "";
return sprintf('%s(%s)', $this->func, $args);
}
static function __callStatic($func, $args) {
$I = new static($func);
$I->args = $args;
return $I;
}
}
class QuerySet implements IteratorAggregate, ArrayAccess {
var $model;
var $constraints = array();
var $ordering = array();
var $limit = false;
var $offset = 0;
var $related = array();
var $values = array();
var $defer = array();
var $lock = false;
const LOCK_EXCLUSIVE = 1;
const LOCK_SHARED = 2;
var $params;
var $query;
function __construct($model) {
$this->model = $model;
}
function filter() {
// Multiple arrays passes means OR
$filter = array();
foreach (func_get_args() as $Q) {
$filter[] = $Q instanceof Q ? $Q : new Q($Q);
}
$this->constraints[] = new Q($filter, Q::ANY);
return $this;
}
function exclude() {
$filter = array();
foreach (func_get_args() as $Q) {
$filter[] = $Q instanceof Q ? $Q->negate() : Q::not($Q);
}
$this->constraints[] = new Q($filter, Q::ANY);
function defer() {
foreach (func_get_args() as $f)
$this->defer[$f] = true;
return $this;
}
function order_by() {
$this->ordering = array_merge($this->ordering, func_get_args());
return $this;
}
function lock($how=false) {
$this->lock = $how ?: self::LOCK_EXCLUSIVE;
return $this;
}
function limit($count) {
$this->limit = $count;
return $this;
}
function offset($at) {
$this->offset = $at;
return $this;
}
function select_related() {
$this->related = array_merge($this->related, func_get_args());
return $this;
}
function values() {
$this->values = func_get_args();
$this->iterator = 'HashArrayIterator';
return $this;
}
function values_flat() {
$this->values = func_get_args();
$this->iterator = 'FlatArrayIterator';
return $this;
}
function all() {
return $this->getIterator()->asArray();
}
$list = $this->limit(1)->all();
if (count($list) == 0)
throw new DoesNotExist();
elseif (count($list) > 1)
throw new ObjectNotUnique('One object was expected; however '
.'multiple objects in the database matched the query. '
.sprintf('In fact, there are %d matching objects.', count($list))
);
// TODO: Throw error if more than one result from database
$class = $this->compiler;
$compiler = new $class();
return $compiler->compileCount($this);
}
function exists() {
return $this->count() > 0;
}
function delete() {
$class = $this->compiler;
$compiler = new $class();
$ex = $compiler->compileBulkDelete($this);
$ex->execute();
return $ex->affected_rows();
}
function update(array $what) {
$class = $this->compiler;
$compiler = new $class;
$ex = $compiler->compileBulkUpdate($this, $what);
$ex->execute();
return $ex->affected_rows();
}
function __clone() {
unset($this->_iterator);
unset($this->query);
}
// IteratorAggregate interface
function getIterator() {
$class = $this->iterator;
$this->_iterator = new $class($this);
return $this->_iterator;
}
// ArrayAccess interface
function offsetExists($offset) {
return $this->getIterator()->offsetExists($offset);
}
function offsetGet($offset) {
return $this->getIterator()->offsetGet($offset);
}
function offsetUnset($a) {
throw new Exception(__('QuerySet is read-only'));
throw new Exception(__('QuerySet is read-only'));
return (string) $this->getQuery();
function getQuery($options=array()) {
if (isset($this->query))
return $this->query;
// Load defaults from model
$model = $this->model;
if (!$this->ordering && isset($model::$meta['ordering']))
$this->ordering = $model::$meta['ordering'];
$class = $this->compiler;
$compiler = new $class($options);
$this->query = $compiler->compileSelect($this);
return $this->query;
}
}
class DoesNotExist extends Exception {}
class ObjectNotUnique extends Exception {}
abstract class ResultSet implements Iterator, ArrayAccess {
var $resource;
var $position = 0;
var $queryset;
function __construct($queryset=false) {
$this->queryset = $queryset;
if ($queryset) {
$this->model = $queryset->model;
$this->resource = $queryset->getQuery();
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
}
}
abstract function fillTo($index);
function asArray() {
$this->fillTo(PHP_INT_MAX);
return $this->cache;
}
// Iterator interface
function rewind() {
$this->position = 0;
}
function current() {
$this->fillTo($this->position);
return $this->cache[$this->position];
}
function key() {
return $this->position;
}
function next() {
$this->position++;
}
function valid() {
$this->fillTo($this->position);
return count($this->cache) > $this->position;
}
// ArrayAccess interface
function offsetExists($offset) {
$this->fillTo($offset);
return $this->position >= $offset;
}
function offsetGet($offset) {
$this->fillTo($offset);
return $this->cache[$offset];
}
function offsetUnset($a) {
throw new Exception(sprintf(__('%s is read-only'), get_class($this)));
}
function offsetSet($a, $b) {
throw new Exception(sprintf(__('%s is read-only'), get_class($this)));
}
}
class ModelInstanceManager extends ResultSet {
var $model;
var $map;
static $objectCache = array();
function __construct($queryset=false) {
parent::__construct($queryset);
if ($queryset) {
$this->map = $this->resource->getMap();
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
function cache($model) {
$model::_inspect();
$key = sprintf('%s.%s',
$model::$meta->model, implode('.', $model->pk));
self::$objectCache[$key] = $model;
}
/**
* uncache
*
* Drop the cached reference to the model. If the model is deleted
* database-side. Lookups for the same model should not be short
* circuited to retrieve the cached reference.
*/
static function uncache($model) {
$key = sprintf('%s.%s',
$model::$meta->model, implode('.', $model->pk));
unset(self::$objectCache[$key]);
}
static function checkCache($modelClass, $fields) {
$key = $modelClass::$meta->model;
foreach ($modelClass::$meta['pk'] as $f)
$key .= '.'.$fields[$f];
return @self::$objectCache[$key];
}
function getOrBuild($modelClass, $fields) {
// Check the cache for the model instance first
if ($m = self::checkCache($modelClass, $fields)) {
// TODO: If the model has deferred fields which are in $fields,
// those can be resolved here
return $m;
}
// Construct and cache the object
$this->cache($m = new $modelClass($fields));
$m->__deferred__ = $this->queryset->defer;
$m->__onload();
return $m;
}
/**
* buildModel
*
* This method builds the model including related models from the record
* received. For related recordsets, a $map should be setup inside this
* object prior to using this method. The $map is assumed to have this
* configuration:
*
* array(array(<modelClass>, <fieldCount>, <relativePath>, <alias>))
*
* Where $modelClass is the name of the foreign (with respect to the
* root model ($this->model), $fieldCount is the number of fields in the
* row for this model, $relativePath is the path that describes the
* relationship between the root model and this model, 'user__account'
* for instance, and <alias> is the alias for the model in the databse
* query — the field names should all start with <alias>_
*/
function buildModel($row) {
// TODO: Traverse to foreign keys
if ($this->map) {
if ($this->model != $this->map[0][1])
throw new OrmException('Internal select_related error');
$offset = 0;
foreach ($this->map as $info) {
@list($count, $model_class, $path, $alias) = $info;
$fields = array_slice($row, $offset, $count);
if (!$path) {
// Build the root model
$model = $this->getOrBuild($this->model, $fields);
$model->__onload();
}
else {
foreach ($fields as $name=>$val) {
$fields[substr($name, strlen($alias)+1)] = $val;
unset($fields[$name]);
}
// Link the related model
$tail = array_pop($path);
$m = $model;
foreach ($path as $field) {
$m = $m->get($field);
}
$m->set($tail, $this->getOrBuild($model_class, $fields));
}
$offset += $count;
}
}
else {
$model = $this->getOrBuild($this->model, $row);
}
function fillTo($index) {
while ($this->resource && $index >= count($this->cache)) {
if ($row = $this->resource->getArray()) {
$this->cache[] = $this->buildModel($row);
} else {
$this->resource->close();
$this->resource = null;
break;
}
}
}
}
class FlatArrayIterator extends ResultSet {
function __construct($queryset) {
$this->resource = $queryset->getQuery();
}
function fillTo($index) {
while ($this->resource && $index >= count($this->cache)) {
if ($row = $this->resource->getRow()) {
} else {
$this->resource->close();
$this->resource = null;
break;
}
}
}
}
class InstrumentedList extends ModelInstanceManager {
function __construct($fkey, $queryset=false) {
list($model, $this->key, $this->id) = $fkey;
if (!$queryset)
$queryset = $model::objects()->filter(array($this->key=>$this->id));
parent::__construct($queryset);
if (!$this->id)
$this->resource = null;
}
function add($object, $at=false) {
if (!$object || !$object instanceof $this->model)
throw new Exception(__('Attempting to add invalid object to list'));
$object->set($this->key, $this->id);
if ($at !== false)
$this->cache[$at] = $object;
else
$this->cache[] = $object;
}
function remove($object) {
$object->delete();
}
function reset() {
$this->cache = array();
}
// QuerySet delegates
function count() {
return $this->queryset->count();
}
function exists() {
return $this->queryset->exists();
}
function expunge() {
if ($this->queryset->delete())
$this->reset();
function update(array $what) {
return $this->queryset->update($what);
}
// Fetch a new QuerySet
function objects() {
return clone $this->queryset;
function offsetUnset($a) {
$this->fillTo($a);
$this->cache[$a]->delete();
}
function offsetSet($a, $b) {
$this->fillTo($a);
$this->cache[$a]->delete();
$this->add($b, $a);
var $joins = array();
var $aliases = array();
var $alias_num = 1;
function __construct($options=false) {
if ($options)
$this->options = array_merge($this->options, $options);
}
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
/**
* Handles breaking down a field or model search descriptor into the
* model search path, field, and operator parts. When used in a queryset
* filter, an expression such as
*
* user__email__hostname__contains => 'foobar'
*
* would be broken down to search from the root model (passed in,
* perhaps a ticket) to the user and email models by inspecting the
* model metadata 'joins' property. The 'constraint' value found there
* will be used to build the JOIN sql clauses.
*
* The 'hostname' will be the field on 'email' model that should be
* compared in the WHERE clause. The comparison should be made using a
* 'contains' function, which in MySQL, might be implemented using
* something like "<lhs> LIKE '%foobar%'"
*
* This function will rely heavily on the pushJoin() function which will
* handle keeping track of joins made previously in the query and
* therefore prevent multiple joins to the same table for the same
* reason. (Self joins are still supported).
*
* Comparison functions supported by this function are defined for each
* respective SqlCompiler subclass; however at least these functions
* should be defined:
*
* function a__function => b
* ----------+------------------------------------------------
* exact | a is exactly equal to b
* gt | a is greater than b
* lte | b is greater than a
* lt | a is less than b
* gte | b is less than a
* ----------+------------------------------------------------
* contains | (string) b is contained within a
* statswith | (string) first len(b) chars of a are exactly b
* endswith | (string) last len(b) chars of a are exactly b
* like | (string) a matches pattern b
* ----------+------------------------------------------------
* in | a is in the list or the nested queryset b
* ----------+------------------------------------------------
* isnull | a is null (if b) else a is not null
*
* If no comparison function is declared in the field descriptor,
* 'exact' is assumed.
*/
function getField($field, $model, $options=array()) {
$joins = array();
// Break apart the field descriptor by __ (double-underbars). The
// first part is assumed to be the root field in the given model.
// The parts after each of the __ pieces are links to other tables.
// The last item (after the last __) is allowed to be an operator
// specifiction.
$parts = explode('__', $field);
$operator = static::$operators['exact'];
if (!isset($options['table'])) {
if (array_key_exists($field, static::$operators)) {
$operator = static::$operators[$field];
$field = array_pop($parts);
}
$alias = (isset($this->joins['']))
? $this->joins['']['alias']
: $this->quote($model::$meta['table']);
// Traverse through the parts and establish joins between the tables
// if the field is joined to a foreign model
if (count($parts) && isset($model::$meta['joins'][$parts[0]])) {
// Call pushJoin for each segment in the join path. A new
// JOIN fragment will need to be emitted and/or cached
$path[] = $p;
$tip = implode('__', $path);
if (!($info = $model::$meta['joins'][$p])) {
throw new OrmException(sprintf(
'Model `%s` does not have a relation called `%s`',
$model, $p));
}
$alias = $this->pushJoin($crumb, $tip, $model, $info);
// Roll to foreign model
foreach ($info['constraint'] as $local => $foreign) {
list($model, $f) = explode('.', $foreign);
if (class_exists($model))
break;
}
}
if (isset($options['table']) && $options['table'])
$field = $alias;
elseif ($alias)
$field = $alias.'.'.$this->quote($field);
if (isset($options['model']) && $options['model'])
$operator = $model;
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
/**
* Uses the compiler-specific `compileJoin` function to compile the join
* statement fragment, and caches the result in the local $joins list. A
* new alias is acquired using the `nextAlias` function which will be
* associated with the join. If the same path is requested again, the
* algorithm is short-circuited and the originally-assigned table alias
* is returned immediately.
*/
function pushJoin($tip, $path, $model, $info) {
// TODO: Build the join statement fragment and return the table
// alias. The table alias will be useful where the join is used in
// the WHERE and ORDER BY clauses
// If the join already exists for the statement-being-compiled, just
// return the alias being used.
if (isset($this->joins[$path]))
return $this->joins[$path]['alias'];
// TODO: Support only using aliases if necessary. Use actual table
// names for everything except oddities like self-joins
$alias = $this->nextAlias();
// Keep an association between the table alias and the model. This
// will make model construction much easier when we have the data
// and the table alias from the database.
$this->aliases[$alias] = $model;
// TODO: Stash joins and join constraints into local ->joins array.
// This will be useful metadata in the executor to construct the
// final models for fetching
// TODO: Always use a table alias. This will further help with
// coordination between the data returned from the database (where
// table alias is available) and the corresponding data.
$this->joins[$path] = array(
'alias' => $alias,
'sql'=> $this->compileJoin($tip, $model, $alias, $info),
);
return $alias;
}
function compileQ(Q $Q, $model) {
$filter = array();