RawSql.php 8.14 KB
Newer Older
1
<?php
lsmith's avatar
lsmith committed
2
/*
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.phpdoctrine.com>.
 */
21
Doctrine::autoload('Doctrine_Hydrate');
22 23 24
/**
 * Doctrine_RawSql
 *
25 26 27 28 29 30 31 32
 * @package     Doctrine
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @category    Object Relational Mapping
 * @link        www.phpdoctrine.com
 * @since       1.0
 * @version     $Revision$
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 */
lsmith's avatar
lsmith committed
33 34
class Doctrine_RawSql extends Doctrine_Hydrate
{
35 36 37 38 39 40 41 42 43 44 45 46
    /**
     * @var array $fields
     */
    private $fields;
    /**
     * __call
     * method overloader
     *
     * @param string $name
     * @param array $args
     * @return Doctrine_RawSql
     */
lsmith's avatar
lsmith committed
47 48
    public function __call($name, $args)
    {
lsmith's avatar
lsmith committed
49
        if ( ! isset($this->parts[$name])) {
50
            throw new Doctrine_RawSql_Exception("Unknown overload method $name. Availible overload methods are ".implode(" ",array_keys($this->parts)));
lsmith's avatar
lsmith committed
51 52
        }
        if ($name == 'select') {
53 54 55 56
            preg_match_all('/{([^}{]*)}/U', $args[0], $m);

            $this->fields = $m[1];
            $this->parts["select"] = array();
lsmith's avatar
lsmith committed
57
        } else {
58
            $this->parts[$name][] = $args[0];
lsmith's avatar
lsmith committed
59
        }
60 61
        return $this;
    }
zYne's avatar
zYne committed
62 63 64
    /**
     * get
     */
lsmith's avatar
lsmith committed
65 66
    public function get($name)
    {
lsmith's avatar
lsmith committed
67
        if ( ! isset($this->parts[$name])) {
68
            throw new Doctrine_RawSql_Exception('Unknown query part '.$name);
lsmith's avatar
lsmith committed
69
        }
zYne's avatar
zYne committed
70 71
        return $this->parts[$name];
    }
72 73 74 75
    /**
     * parseQuery
     *
     * @param string $query
doctrine's avatar
doctrine committed
76
     * @return Doctrine_RawSql
77
     */
lsmith's avatar
lsmith committed
78 79
    public function parseQuery($query)
    {
80
        preg_match_all('/{([^}{]*)}/U', $query, $m);
81 82 83 84

        $this->fields = $m[1];
        $this->clear();

85
        $e = Doctrine_Query::sqlExplode($query,' ');
86

lsmith's avatar
lsmith committed
87
        foreach ($e as $k => $part) {
88
            $low = strtolower($part);
lsmith's avatar
lsmith committed
89
            switch (strtolower($part)) {
90 91 92 93 94 95
                case "select":
                case "from":
                case "where":
                case "limit":
                case "offset":
                case "having":
96
                    $p = $low;
97 98 99 100 101 102 103 104 105 106 107
                    if ( ! isset($parts[$low])) {
                        $parts[$low] = array();
                    }
                    break;
                case "order":
                case "group":
                    $i = ($k + 1);
                    if (isset($e[$i]) && strtolower($e[$i]) === "by") {
                        $p = $low;
                        $p .= "by";
                        $parts[$low."by"] = array();
lsmith's avatar
lsmith committed
108

109 110 111 112 113 114 115 116 117 118 119 120
                    } else {
                        $parts[$p][] = $part;
                    }
                    break;
                case "by":
                    continue;
                default:
                    if ( ! isset($parts[$p][0])) {
                        $parts[$p][0] = $part;
                    } else {
                        $parts[$p][0] .= ' '.$part;
                    }
lsmith's avatar
lsmith committed
121 122
            };
        };
123 124 125

        $this->parts = $parts;
        $this->parts["select"] = array();
lsmith's avatar
lsmith committed
126

doctrine's avatar
doctrine committed
127
        return $this;
128 129 130
    }
    /**
     * getQuery
131 132
     *
     *
133 134
     * @return string
     */
lsmith's avatar
lsmith committed
135 136
    public function getQuery()
    {
lsmith's avatar
lsmith committed
137
        foreach ($this->fields as $field) {
138
            $e = explode(".", $field);
lsmith's avatar
lsmith committed
139
            if ( ! isset($e[1])) {
140
                throw new Doctrine_RawSql_Exception("All selected fields in Sql query must be in format tableAlias.fieldName");
lsmith's avatar
lsmith committed
141 142
            }
            if ( ! isset($this->tables[$e[0]])) {
143 144
                try {
                    $this->addComponent($e[0], ucwords($e[0]));
145
                } catch(Doctrine_Exception $exception) {
146
                    throw new Doctrine_RawSql_Exception("The associated component for table alias $e[0] couldn't be found.");
147 148 149
                }
            }

lsmith's avatar
lsmith committed
150 151
            if ($e[1] == '*') {
                foreach ($this->tables[$e[0]]->getColumnNames() as $name) {
152 153 154 155 156 157 158 159
                    $field = $e[0].".".$name;
                    $this->parts["select"][$field] = $field." AS ".$e[0]."__".$name;
                }
            } else {
                $field = $e[0].".".$e[1];
                $this->parts["select"][$field] = $field." AS ".$e[0]."__".$e[1];
            }
        }
160

161 162
        // force-add all primary key fields

lsmith's avatar
lsmith committed
163 164
        foreach ($this->tableAliases as $alias) {
            foreach ($this->tables[$alias]->getPrimaryKeys() as $key) {
zYne's avatar
zYne committed
165
                $field = $alias . '.' . $key;
lsmith's avatar
lsmith committed
166
                if ( ! isset($this->parts["select"][$field])) {
167
                    $this->parts["select"][$field] = $field." AS ".$alias."__".$key;
lsmith's avatar
lsmith committed
168
                }
169 170 171
            }
        }

172
        $q = 'SELECT '.implode(', ', $this->parts['select']);
173

174
        $string = $this->applyInheritance();
lsmith's avatar
lsmith committed
175
        if ( ! empty($string)) {
176
            $this->parts['where'][] = $string;
lsmith's avatar
lsmith committed
177
        }
178 179 180
        $copy = $this->parts;
        unset($copy['select']);

181 182 183 184 185
        $q .= ( ! empty($this->parts['from']))?    ' FROM '     . implode(' ', $this->parts['from']) : '';
        $q .= ( ! empty($this->parts['where']))?   ' WHERE '    . implode(' AND ', $this->parts['where']) : '';
        $q .= ( ! empty($this->parts['groupby']))? ' GROUP BY ' . implode(', ', $this->parts['groupby']) : '';
        $q .= ( ! empty($this->parts['having']))?  ' HAVING '   . implode(' ', $this->parts['having']) : '';
        $q .= ( ! empty($this->parts['orderby']))? ' ORDER BY ' . implode(' ', $this->parts['orderby']) : '';
zYne's avatar
zYne committed
186 187
        $q .= ( ! empty($this->parts['limit']))?   ' LIMIT ' . implode(' ', $this->parts['limit']) : '';
        $q .= ( ! empty($this->parts['offset']))?  ' OFFSET ' . implode(' ', $this->parts['offset']) : '';
188

lsmith's avatar
lsmith committed
189
        if ( ! empty($string)) {
190
            array_pop($this->parts['where']);
lsmith's avatar
lsmith committed
191
        }
192
        return $q;
193 194 195 196 197 198
    }
    /**
     * getFields
     *
     * @return array
     */
lsmith's avatar
lsmith committed
199 200
    public function getFields()
    {
201 202 203 204 205 206 207
        return $this->fields;
    }
    /**
     * addComponent
     *
     * @param string $tableAlias
     * @param string $componentName
doctrine's avatar
doctrine committed
208
     * @return Doctrine_RawSql
209
     */
lsmith's avatar
lsmith committed
210 211
    public function addComponent($tableAlias, $componentName)
    {
zYne's avatar
zYne committed
212
        $e = explode('.', $componentName);
213

214
        $currPath = '';
pookey's avatar
pookey committed
215
        $table = null;
216

lsmith's avatar
lsmith committed
217
        foreach ($e as $k => $component) {
zYne's avatar
zYne committed
218
            $currPath .= '.' . $component;
lsmith's avatar
lsmith committed
219
            if ($k == 0)
220 221
                $currPath = substr($currPath,1);

lsmith's avatar
lsmith committed
222
            if (isset($this->tableAliases[$currPath])) {
223
                $alias = $this->tableAliases[$currPath];
lsmith's avatar
lsmith committed
224
            } else {
225
                $alias = $tableAlias;
lsmith's avatar
lsmith committed
226
            }
227

lsmith's avatar
lsmith committed
228
            if ($table) {
zYne's avatar
zYne committed
229 230
                $tableName = $table->getAliasName($component);

231
                $table = $this->conn->getTable($tableName);
pookey's avatar
pookey committed
232
            } else {
233
                $table = $this->conn->getTable($component);
pookey's avatar
pookey committed
234
            }
235 236 237 238
            $this->tables[$alias]           = $table;
            $this->fetchModes[$alias]       = Doctrine::FETCH_IMMEDIATE;
            $this->tableAliases[$currPath]  = $alias;

lsmith's avatar
lsmith committed
239
            if ($k !== 0) {
240
                $this->joins[$alias]        = $prevAlias;
lsmith's avatar
lsmith committed
241
            }
242 243 244
            $prevAlias = $alias;
            $prevPath  = $currPath;
        }
lsmith's avatar
lsmith committed
245

doctrine's avatar
doctrine committed
246
        return $this;
247 248 249
    }

}