RawSql.php 9.99 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_Query_Abstract');
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>
 */
33
class Doctrine_RawSql extends Doctrine_Query_Abstract
lsmith's avatar
lsmith committed
34
{
35 36 37
    /**
     * @var array $fields
     */
zYne's avatar
zYne committed
38
    private $fields = array();
39
    /**
40 41
     * parseQueryPart
     * parses given query part
42
     *
43 44 45 46 47 48
     * @param string $queryPartName     the name of the query part
     * @param string $queryPart         query part to be parsed
     * @param boolean $append           whether or not to append the query part to its stack
     *                                  if false is given, this method will overwrite 
     *                                  the given query part stack with $queryPart
     * @return Doctrine_Query           this object
49
     */
50
    public function parseQueryPart($queryPartName, $queryPart, $append = false) 
lsmith's avatar
lsmith committed
51
    {
52 53
        if ($queryPartName == 'select') {
            preg_match_all('/{([^}{]*)}/U', $queryPart, $m);
54 55

            $this->fields = $m[1];
56
            $this->parts['select'] = array();
lsmith's avatar
lsmith committed
57
        } else {
58 59 60 61 62
            if ( ! $append) {
                $this->parts[$queryPartName] = array($queryPart);
            } else {
                $this->parts[$queryPartName][] = $queryPart;
            }
lsmith's avatar
lsmith committed
63
        }
64 65 66 67
        return $this;
    }
    /**
     * parseQuery
zYne's avatar
zYne committed
68
     * parses an sql query and adds the parts to internal array
69
     *
zYne's avatar
zYne committed
70 71
     * @param string $query         query to be parsed
     * @return Doctrine_RawSql      this object
72
     */
lsmith's avatar
lsmith committed
73 74
    public function parseQuery($query)
    {
75
        preg_match_all('/{([^}{]*)}/U', $query, $m);
76 77 78 79

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

zYne's avatar
zYne committed
80
        $e = Doctrine_Tokenizer::sqlExplode($query,' ');
81

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

104 105 106 107
                    } else {
                        $parts[$p][] = $part;
                    }
                    break;
zYne's avatar
zYne committed
108
                case 'by':
109 110 111 112 113 114 115
                    continue;
                default:
                    if ( ! isset($parts[$p][0])) {
                        $parts[$p][0] = $part;
                    } else {
                        $parts[$p][0] .= ' '.$part;
                    }
116 117
            }
        }
118 119

        $this->parts = $parts;
zYne's avatar
zYne committed
120
        $this->parts['select'] = array();
lsmith's avatar
lsmith committed
121

doctrine's avatar
doctrine committed
122
        return $this;
123 124 125
    }
    /**
     * getQuery
zYne's avatar
zYne committed
126
     * builds the sql query from the given query parts
127
     *
zYne's avatar
zYne committed
128
     * @return string       the built sql query
129
     */
lsmith's avatar
lsmith committed
130 131
    public function getQuery()
    {
zYne's avatar
zYne committed
132 133
    	$select = array();

lsmith's avatar
lsmith committed
134
        foreach ($this->fields as $field) {
zYne's avatar
zYne committed
135
            $e = explode('.', $field);
lsmith's avatar
lsmith committed
136
            if ( ! isset($e[1])) {
zYne's avatar
zYne committed
137
                throw new Doctrine_RawSql_Exception('All selected fields in Sql query must be in format tableAlias.fieldName');
lsmith's avatar
lsmith committed
138
            }
zYne's avatar
zYne committed
139
            // try to auto-add component
zYne's avatar
zYne committed
140
            if ( ! $this->hasTableAlias($e[0])) {
141 142
                try {
                    $this->addComponent($e[0], ucwords($e[0]));
143
                } catch(Doctrine_Exception $exception) {
zYne's avatar
zYne committed
144
                    throw new Doctrine_RawSql_Exception('The associated component for table alias ' . $e[0] . ' couldn\'t be found.');
145 146 147
                }
            }

zYne's avatar
zYne committed
148 149
            $componentAlias = $this->getComponentAlias($e[0]);
            
lsmith's avatar
lsmith committed
150
            if ($e[1] == '*') {
zYne's avatar
zYne committed
151
                foreach ($this->_aliasMap[$componentAlias]['table']->getColumnNames() as $name) {
zYne's avatar
zYne committed
152
                    $field = $e[0] . '.' . $name;
zYne's avatar
zYne committed
153 154

                    $select[$componentAlias][$field] = $field . ' AS ' . $e[0] . '__' . $name;
155 156
                }
            } else {
zYne's avatar
zYne committed
157
                $field = $e[0] . '.' . $e[1];
zYne's avatar
zYne committed
158
                $select[$componentAlias][$field] = $field . ' AS ' . $e[0] . '__' . $e[1];
159 160
            }
        }
161

162 163
        // force-add all primary key fields

zYne's avatar
zYne committed
164
        foreach ($this->getTableAliases() as $tableAlias => $componentAlias) {
zYne's avatar
zYne committed
165 166 167 168 169
            $map = $this->_aliasMap[$componentAlias];

            foreach ($map['table']->getPrimaryKeys() as $key) {
                $field = $tableAlias . '.' . $key;

zYne's avatar
zYne committed
170
                if ( ! isset($this->parts['select'][$field])) {
zYne's avatar
zYne committed
171
                    $select[$componentAlias][$field] = $field . ' AS ' . $tableAlias . '__' . $key;
lsmith's avatar
lsmith committed
172
                }
173 174
            }
        }
zYne's avatar
zYne committed
175 176 177 178
        
        // first add the fields of the root component
        reset($this->_aliasMap);
        $componentAlias = key($this->_aliasMap);
179

zYne's avatar
zYne committed
180 181 182 183 184 185 186 187
        $q = 'SELECT ' . implode(', ', $select[$componentAlias]);
        unset($select[$componentAlias]);

        foreach ($select as $component => $fields) {
            if ( ! empty($fields)) {
                $q .= ', ' . implode(', ', $fields);
            }
        }
188

189
        $string = $this->applyInheritance();
lsmith's avatar
lsmith committed
190
        if ( ! empty($string)) {
191
            $this->parts['where'][] = $string;
lsmith's avatar
lsmith committed
192
        }
193 194 195
        $copy = $this->parts;
        unset($copy['select']);

196 197 198
        $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']) : '';
zYne's avatar
zYne committed
199 200
        $q .= ( ! empty($this->parts['having']))?  ' HAVING '   . implode(' AND ', $this->parts['having']) : '';
        $q .= ( ! empty($this->parts['orderby']))? ' ORDER BY ' . implode(', ', $this->parts['orderby']) : '';
zYne's avatar
zYne committed
201 202
        $q .= ( ! empty($this->parts['limit']))?   ' LIMIT ' . implode(' ', $this->parts['limit']) : '';
        $q .= ( ! empty($this->parts['offset']))?  ' OFFSET ' . implode(' ', $this->parts['offset']) : '';
203

lsmith's avatar
lsmith committed
204
        if ( ! empty($string)) {
205
            array_pop($this->parts['where']);
lsmith's avatar
lsmith committed
206
        }
207
        return $q;
208 209 210
    }
    /**
     * getFields
zYne's avatar
zYne committed
211
     * returns the fields associated with this parser
212
     *
zYne's avatar
zYne committed
213
     * @return array    all the fields associated with this parser
214
     */
lsmith's avatar
lsmith committed
215 216
    public function getFields()
    {
217 218 219 220 221 222 223
        return $this->fields;
    }
    /**
     * addComponent
     *
     * @param string $tableAlias
     * @param string $componentName
doctrine's avatar
doctrine committed
224
     * @return Doctrine_RawSql
225
     */
zYne's avatar
zYne committed
226
    public function addComponent($tableAlias, $path)
lsmith's avatar
lsmith committed
227
    {
zYne's avatar
zYne committed
228 229 230 231 232 233 234
        $tmp           = explode(' ', $path);
        $originalAlias = (count($tmp) > 1) ? end($tmp) : null;

        $e = explode('.', $tmp[0]);

        $fullPath = $tmp[0];
        $fullLength = strlen($fullPath);
235

pookey's avatar
pookey committed
236
        $table = null;
zYne's avatar
zYne committed
237 238 239

        $currPath = '';

zYne's avatar
zYne committed
240 241 242
        if (isset($this->_aliasMap[$e[0]])) {
            $table = $this->_aliasMap[$e[0]]['table'];

zYne's avatar
zYne committed
243
            $currPath = $parent = array_shift($e);
zYne's avatar
zYne committed
244 245
        }

lsmith's avatar
lsmith committed
246
        foreach ($e as $k => $component) {
zYne's avatar
zYne committed
247 248 249 250
            // get length of the previous path
            $length = strlen($currPath);

            // build the current component path
zYne's avatar
zYne committed
251
            $currPath = ($currPath) ? $currPath . '.' . $component : $component;
252

zYne's avatar
zYne committed
253 254 255 256 257
            $delimeter = substr($fullPath, $length, 1);

            // if an alias is not given use the current path as an alias identifier
            if (strlen($currPath) === $fullLength && isset($originalAlias)) {
                $componentAlias = $originalAlias;
lsmith's avatar
lsmith committed
258
            } else {
zYne's avatar
zYne committed
259
                $componentAlias = $currPath;
lsmith's avatar
lsmith committed
260
            }
zYne's avatar
zYne committed
261 262
            if ( ! isset($table)) {
                $conn = Doctrine_Manager::getInstance()
zYne's avatar
zYne committed
263
                        ->getConnectionForComponent($component);
zYne's avatar
zYne committed
264 265 266 267
                        
                $table = $conn->getTable($component);
                $this->_aliasMap[$componentAlias] = array('table' => $table);
            } else {
zYne's avatar
zYne committed
268
                $relation = $table->getRelation($component);
269

zYne's avatar
zYne committed
270 271 272
                $this->_aliasMap[$componentAlias] = array('table'    => $relation->getTable(),
                                                          'parent'   => $parent,
                                                          'relation' => $relation);
pookey's avatar
pookey committed
273
            }
zYne's avatar
zYne committed
274
            $this->addTableAlias($tableAlias, $componentAlias);
275

zYne's avatar
zYne committed
276
            $parent = $currPath;
277
        }
lsmith's avatar
lsmith committed
278

doctrine's avatar
doctrine committed
279
        return $this;
280 281 282
    }

}