1: <?php
2: /**
3: * This file contains the CDbCommand class.
4: *
5: * @author Qiang Xue <qiang.xue@gmail.com>
6: * @link http://www.yiiframework.com/
7: * @copyright 2008-2013 Yii Software LLC
8: * @license http://www.yiiframework.com/license/
9: */
10:
11: /**
12: * CDbCommand represents an SQL statement to execute against a database.
13: *
14: * It is usually created by calling {@link CDbConnection::createCommand}.
15: * The SQL statement to be executed may be set via {@link setText Text}.
16: *
17: * To execute a non-query SQL (such as insert, delete, update), call
18: * {@link execute}. To execute an SQL statement that returns result data set
19: * (such as SELECT), use {@link query} or its convenient versions {@link queryRow},
20: * {@link queryColumn}, or {@link queryScalar}.
21: *
22: * If an SQL statement returns results (such as a SELECT SQL), the results
23: * can be accessed via the returned {@link CDbDataReader}.
24: *
25: * CDbCommand supports SQL statement preparation and parameter binding.
26: * Call {@link bindParam} to bind a PHP variable to a parameter in SQL.
27: * Call {@link bindValue} to bind a value to an SQL parameter.
28: * When binding a parameter, the SQL statement is automatically prepared.
29: * You may also call {@link prepare} to explicitly prepare an SQL statement.
30: *
31: * Starting from version 1.1.6, CDbCommand can also be used as a query builder
32: * that builds a SQL statement from code fragments. For example,
33: * <pre>
34: * $user = Yii::app()->db->createCommand()
35: * ->select('username, password')
36: * ->from('tbl_user')
37: * ->where('id=:id', array(':id'=>1))
38: * ->queryRow();
39: * </pre>
40: *
41: * @property string $text The SQL statement to be executed.
42: * @property CDbConnection $connection The connection associated with this command.
43: * @property PDOStatement $pdoStatement The underlying PDOStatement for this command
44: * It could be null if the statement is not prepared yet.
45: * @property string $select The SELECT part (without 'SELECT') in the query.
46: * @property boolean $distinct A value indicating whether SELECT DISTINCT should be used.
47: * @property string $from The FROM part (without 'FROM' ) in the query.
48: * @property string $where The WHERE part (without 'WHERE' ) in the query.
49: * @property mixed $join The join part in the query. This can be an array representing
50: * multiple join fragments, or a string representing a single join fragment.
51: * Each join fragment will contain the proper join operator (e.g. LEFT JOIN).
52: * @property string $group The GROUP BY part (without 'GROUP BY' ) in the query.
53: * @property string $having The HAVING part (without 'HAVING' ) in the query.
54: * @property string $order The ORDER BY part (without 'ORDER BY' ) in the query.
55: * @property string $limit The LIMIT part (without 'LIMIT' ) in the query.
56: * @property string $offset The OFFSET part (without 'OFFSET' ) in the query.
57: * @property mixed $union The UNION part (without 'UNION' ) in the query.
58: * This can be either a string or an array representing multiple union parts.
59: *
60: * @author Qiang Xue <qiang.xue@gmail.com>
61: * @package system.db
62: * @since 1.0
63: */
64: class CDbCommand extends CComponent
65: {
66: /**
67: * @var array the parameters (name=>value) to be bound to the current query.
68: * @since 1.1.6
69: */
70: public $params=array();
71:
72: private $_connection;
73: private $_text;
74: private $_statement;
75: private $_paramLog=array();
76: private $_query;
77: private $_fetchMode = array(PDO::FETCH_ASSOC);
78:
79: /**
80: * Constructor.
81: * @param CDbConnection $connection the database connection
82: * @param mixed $query the DB query to be executed. This can be either
83: * a string representing a SQL statement, or an array whose name-value pairs
84: * will be used to set the corresponding properties of the created command object.
85: *
86: * For example, you can pass in either <code>'SELECT * FROM tbl_user'</code>
87: * or <code>array('select'=>'*', 'from'=>'tbl_user')</code>. They are equivalent
88: * in terms of the final query result.
89: *
90: * When passing the query as an array, the following properties are commonly set:
91: * {@link select}, {@link distinct}, {@link from}, {@link where}, {@link join},
92: * {@link group}, {@link having}, {@link order}, {@link limit}, {@link offset} and
93: * {@link union}. Please refer to the setter of each of these properties for details
94: * about valid property values. This feature has been available since version 1.1.6.
95: *
96: * Since 1.1.7 it is possible to use a specific mode of data fetching by setting
97: * {@link setFetchMode FetchMode}. See {@link http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php}
98: * for more details.
99: */
100: public function __construct(CDbConnection $connection,$query=null)
101: {
102: $this->_connection=$connection;
103: if(is_array($query))
104: {
105: foreach($query as $name=>$value)
106: $this->$name=$value;
107: }
108: else
109: $this->setText($query);
110: }
111:
112: /**
113: * Set the statement to null when serializing.
114: * @return array
115: */
116: public function __sleep()
117: {
118: $this->_statement=null;
119: return array_keys(get_object_vars($this));
120: }
121:
122: /**
123: * Set the default fetch mode for this statement
124: * @param mixed $mode fetch mode
125: * @return static
126: * @see http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php
127: * @since 1.1.7
128: */
129: public function setFetchMode($mode)
130: {
131: $params=func_get_args();
132: $this->_fetchMode = $params;
133: return $this;
134: }
135:
136: /**
137: * Cleans up the command and prepares for building a new query.
138: * This method is mainly used when a command object is being reused
139: * multiple times for building different queries.
140: * Calling this method will clean up all internal states of the command object.
141: * @return static this command instance
142: * @since 1.1.6
143: */
144: public function reset()
145: {
146: $this->_text=null;
147: $this->_query=null;
148: $this->_statement=null;
149: $this->_paramLog=array();
150: $this->params=array();
151: return $this;
152: }
153:
154: /**
155: * @return string the SQL statement to be executed
156: */
157: public function getText()
158: {
159: if($this->_text=='' && !empty($this->_query))
160: $this->setText($this->buildQuery($this->_query));
161: return $this->_text;
162: }
163:
164: /**
165: * Specifies the SQL statement to be executed.
166: * Any previous execution will be terminated or cancel.
167: * @param string $value the SQL statement to be executed
168: * @return static this command instance
169: */
170: public function setText($value)
171: {
172: if($this->_connection->tablePrefix!==null && $value!='')
173: $this->_text=preg_replace('/{{(.*?)}}/',$this->_connection->tablePrefix.'\1',$value);
174: else
175: $this->_text=$value;
176: $this->cancel();
177: return $this;
178: }
179:
180: /**
181: * @return CDbConnection the connection associated with this command
182: */
183: public function getConnection()
184: {
185: return $this->_connection;
186: }
187:
188: /**
189: * @return PDOStatement the underlying PDOStatement for this command
190: * It could be null if the statement is not prepared yet.
191: */
192: public function getPdoStatement()
193: {
194: return $this->_statement;
195: }
196:
197: /**
198: * Prepares the SQL statement to be executed.
199: * For complex SQL statement that is to be executed multiple times,
200: * this may improve performance.
201: * For SQL statement with binding parameters, this method is invoked
202: * automatically.
203: * @throws CDbException if CDbCommand failed to prepare the SQL statement
204: */
205: public function prepare()
206: {
207: if($this->_statement==null)
208: {
209: try
210: {
211: $this->_statement=$this->getConnection()->getPdoInstance()->prepare($this->getText());
212: $this->_paramLog=array();
213: }
214: catch(Exception $e)
215: {
216: Yii::log('Error in preparing SQL: '.$this->getText(),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
217: $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
218: throw new CDbException(Yii::t('yii','CDbCommand failed to prepare the SQL statement: {error}',
219: array('{error}'=>$e->getMessage())),(int)$e->getCode(),$errorInfo);
220: }
221: }
222: }
223:
224: /**
225: * Cancels the execution of the SQL statement.
226: */
227: public function cancel()
228: {
229: $this->_statement=null;
230: }
231:
232: /**
233: * Binds a parameter to the SQL statement to be executed.
234: * @param mixed $name Parameter identifier. For a prepared statement
235: * using named placeholders, this will be a parameter name of
236: * the form :name. For a prepared statement using question mark
237: * placeholders, this will be the 1-indexed position of the parameter.
238: * @param mixed $value Name of the PHP variable to bind to the SQL statement parameter
239: * @param integer $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
240: * @param integer $length length of the data type
241: * @param mixed $driverOptions the driver-specific options (this is available since version 1.1.6)
242: * @return static the current command being executed
243: * @see http://www.php.net/manual/en/function.PDOStatement-bindParam.php
244: */
245: public function bindParam($name, &$value, $dataType=null, $length=null, $driverOptions=null)
246: {
247: $this->prepare();
248: if($dataType===null)
249: $this->_statement->bindParam($name,$value,$this->_connection->getPdoType(gettype($value)));
250: elseif($length===null)
251: $this->_statement->bindParam($name,$value,$dataType);
252: elseif($driverOptions===null)
253: $this->_statement->bindParam($name,$value,$dataType,$length);
254: else
255: $this->_statement->bindParam($name,$value,$dataType,$length,$driverOptions);
256: $this->_paramLog[$name]=&$value;
257: return $this;
258: }
259:
260: /**
261: * Binds a value to a parameter.
262: * @param mixed $name Parameter identifier. For a prepared statement
263: * using named placeholders, this will be a parameter name of
264: * the form :name. For a prepared statement using question mark
265: * placeholders, this will be the 1-indexed position of the parameter.
266: * @param mixed $value The value to bind to the parameter
267: * @param integer $dataType SQL data type of the parameter. If null, the type is determined by the PHP type of the value.
268: * @return static the current command being executed
269: * @see http://www.php.net/manual/en/function.PDOStatement-bindValue.php
270: */
271: public function bindValue($name, $value, $dataType=null)
272: {
273: $this->prepare();
274: if($dataType===null)
275: $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
276: else
277: $this->_statement->bindValue($name,$value,$dataType);
278: $this->_paramLog[$name]=$value;
279: return $this;
280: }
281:
282: /**
283: * Binds a list of values to the corresponding parameters.
284: * This is similar to {@link bindValue} except that it binds multiple values.
285: * Note that the SQL data type of each value is determined by its PHP type.
286: * @param array $values the values to be bound. This must be given in terms of an associative
287: * array with array keys being the parameter names, and array values the corresponding parameter values.
288: * For example, <code>array(':name'=>'John', ':age'=>25)</code>.
289: * @return static the current command being executed
290: * @since 1.1.5
291: */
292: public function bindValues($values)
293: {
294: $this->prepare();
295: foreach($values as $name=>$value)
296: {
297: $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
298: $this->_paramLog[$name]=$value;
299: }
300: return $this;
301: }
302:
303: /**
304: * Executes the SQL statement.
305: * This method is meant only for executing non-query SQL statement.
306: * No result set will be returned.
307: * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
308: * to {@link bindParam} and {@link bindValue}. If you have multiple input parameters, passing
309: * them in this way can improve the performance. Note that if you pass parameters in this way,
310: * you cannot bind parameters or values using {@link bindParam} or {@link bindValue}, and vice versa.
311: * Please also note that all values are treated as strings in this case, if you need them to be handled as
312: * their real data types, you have to use {@link bindParam} or {@link bindValue} instead.
313: * @return integer number of rows affected by the execution.
314: * @throws CDbException execution failed
315: */
316: public function execute($params=array())
317: {
318: if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
319: {
320: $p=array();
321: foreach($pars as $name=>$value)
322: $p[$name]=$name.'='.var_export($value,true);
323: $par='. Bound with ' .implode(', ',$p);
324: }
325: else
326: $par='';
327: Yii::trace('Executing SQL: '.$this->getText().$par,'system.db.CDbCommand');
328: try
329: {
330: if($this->_connection->enableProfiling)
331: Yii::beginProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
332:
333: $this->prepare();
334: if($params===array())
335: $this->_statement->execute();
336: else
337: $this->_statement->execute($params);
338: $n=$this->_statement->rowCount();
339:
340: if($this->_connection->enableProfiling)
341: Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
342:
343: return $n;
344: }
345: catch(Exception $e)
346: {
347: if($this->_connection->enableProfiling)
348: Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
349:
350: $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
351: $message=$e->getMessage();
352: Yii::log(Yii::t('yii','CDbCommand::execute() failed: {error}. The SQL statement executed was: {sql}.',
353: array('{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
354:
355: if(YII_DEBUG)
356: $message.='. The SQL statement executed was: '.$this->getText().$par;
357:
358: throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
359: array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
360: }
361: }
362:
363: /**
364: * Executes the SQL statement and returns query result.
365: * This method is for executing an SQL query that returns result set.
366: * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
367: * to {@link bindParam} and {@link bindValue}. If you have multiple input parameters, passing
368: * them in this way can improve the performance. Note that if you pass parameters in this way,
369: * you cannot bind parameters or values using {@link bindParam} or {@link bindValue}, and vice versa.
370: * Please also note that all values are treated as strings in this case, if you need them to be handled as
371: * their real data types, you have to use {@link bindParam} or {@link bindValue} instead.
372: * @return CDbDataReader the reader object for fetching the query result
373: * @throws CException execution failed
374: */
375: public function query($params=array())
376: {
377: return $this->queryInternal('',0,$params);
378: }
379:
380: /**
381: * Executes the SQL statement and returns all rows.
382: * @param boolean $fetchAssociative whether each row should be returned as an associated array with
383: * column names as the keys or the array keys are column indexes (0-based).
384: * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
385: * to {@link bindParam} and {@link bindValue}. If you have multiple input parameters, passing
386: * them in this way can improve the performance. Note that if you pass parameters in this way,
387: * you cannot bind parameters or values using {@link bindParam} or {@link bindValue}, and vice versa.
388: * Please also note that all values are treated as strings in this case, if you need them to be handled as
389: * their real data types, you have to use {@link bindParam} or {@link bindValue} instead.
390: * @return array all rows of the query result. Each array element is an array representing a row.
391: * An empty array is returned if the query results in nothing.
392: * @throws CException execution failed
393: */
394: public function queryAll($fetchAssociative=true,$params=array())
395: {
396: return $this->queryInternal('fetchAll',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
397: }
398:
399: /**
400: * Executes the SQL statement and returns the first row of the result.
401: * This is a convenient method of {@link query} when only the first row of data is needed.
402: * @param boolean $fetchAssociative whether the row should be returned as an associated array with
403: * column names as the keys or the array keys are column indexes (0-based).
404: * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
405: * to {@link bindParam} and {@link bindValue}. If you have multiple input parameters, passing
406: * them in this way can improve the performance. Note that if you pass parameters in this way,
407: * you cannot bind parameters or values using {@link bindParam} or {@link bindValue}, and vice versa.
408: * Please also note that all values are treated as strings in this case, if you need them to be handled as
409: * their real data types, you have to use {@link bindParam} or {@link bindValue} instead.
410: * @return mixed the first row (in terms of an array) of the query result, false if no result.
411: * @throws CException execution failed
412: */
413: public function queryRow($fetchAssociative=true,$params=array())
414: {
415: return $this->queryInternal('fetch',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
416: }
417:
418: /**
419: * Executes the SQL statement and returns the value of the first column in the first row of data.
420: * This is a convenient method of {@link query} when only a single scalar
421: * value is needed (e.g. obtaining the count of the records).
422: * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
423: * to {@link bindParam} and {@link bindValue}. If you have multiple input parameters, passing
424: * them in this way can improve the performance. Note that if you pass parameters in this way,
425: * you cannot bind parameters or values using {@link bindParam} or {@link bindValue}, and vice versa.
426: * Please also note that all values are treated as strings in this case, if you need them to be handled as
427: * their real data types, you have to use {@link bindParam} or {@link bindValue} instead.
428: * @return mixed the value of the first column in the first row of the query result. False is returned if there is no value.
429: * @throws CException execution failed
430: */
431: public function queryScalar($params=array())
432: {
433: $result=$this->queryInternal('fetchColumn',0,$params);
434: if(is_resource($result) && get_resource_type($result)==='stream')
435: return stream_get_contents($result);
436: else
437: return $result;
438: }
439:
440: /**
441: * Executes the SQL statement and returns the first column of the result.
442: * This is a convenient method of {@link query} when only the first column of data is needed.
443: * Note, the column returned will contain the first element in each row of result.
444: * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
445: * to {@link bindParam} and {@link bindValue}. If you have multiple input parameters, passing
446: * them in this way can improve the performance. Note that if you pass parameters in this way,
447: * you cannot bind parameters or values using {@link bindParam} or {@link bindValue}, and vice versa.
448: * Please also note that all values are treated as strings in this case, if you need them to be handled as
449: * their real data types, you have to use {@link bindParam} or {@link bindValue} instead.
450: * @return array the first column of the query result. Empty array if no result.
451: * @throws CException execution failed
452: */
453: public function queryColumn($params=array())
454: {
455: return $this->queryInternal('fetchAll',array(PDO::FETCH_COLUMN, 0),$params);
456: }
457:
458: /**
459: * @param string $method method of PDOStatement to be called
460: * @param mixed $mode parameters to be passed to the method
461: * @param array $params input parameters (name=>value) for the SQL execution. This is an alternative
462: * to {@link bindParam} and {@link bindValue}. If you have multiple input parameters, passing
463: * them in this way can improve the performance. Note that if you pass parameters in this way,
464: * you cannot bind parameters or values using {@link bindParam} or {@link bindValue}, and vice versa.
465: * Please also note that all values are treated as strings in this case, if you need them to be handled as
466: * their real data types, you have to use {@link bindParam} or {@link bindValue} instead.
467: * @throws CDbException if CDbCommand failed to execute the SQL statement
468: * @return mixed the method execution result
469: */
470: private function queryInternal($method,$mode,$params=array())
471: {
472: $params=array_merge($this->params,$params);
473:
474: if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
475: {
476: $p=array();
477: foreach($pars as $name=>$value)
478: $p[$name]=$name.'='.var_export($value,true);
479: $par='. Bound with '.implode(', ',$p);
480: }
481: else
482: $par='';
483:
484: Yii::trace('Querying SQL: '.$this->getText().$par,'system.db.CDbCommand');
485:
486: if($this->_connection->queryCachingCount>0 && $method!==''
487: && $this->_connection->queryCachingDuration>0
488: && $this->_connection->queryCacheID!==false
489: && ($cache=Yii::app()->getComponent($this->_connection->queryCacheID))!==null)
490: {
491: $this->_connection->queryCachingCount--;
492: $cacheKey='yii:dbquery'.':'.$method.':'.$this->_connection->connectionString.':'.$this->_connection->username;
493: $cacheKey.=':'.$this->getText().':'.serialize(array_merge($this->_paramLog,$params));
494: if(($result=$cache->get($cacheKey))!==false)
495: {
496: Yii::trace('Query result found in cache','system.db.CDbCommand');
497: return $result[0];
498: }
499: }
500:
501: try
502: {
503: if($this->_connection->enableProfiling)
504: Yii::beginProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
505:
506: $this->prepare();
507: if($params===array())
508: $this->_statement->execute();
509: else
510: $this->_statement->execute($params);
511:
512: if($method==='')
513: $result=new CDbDataReader($this);
514: else
515: {
516: $mode=(array)$mode;
517: call_user_func_array(array($this->_statement, 'setFetchMode'), $mode);
518: $result=$this->_statement->$method();
519: $this->_statement->closeCursor();
520: }
521:
522: if($this->_connection->enableProfiling)
523: Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
524:
525: if(isset($cache,$cacheKey))
526: $cache->set($cacheKey, array($result), $this->_connection->queryCachingDuration, $this->_connection->queryCachingDependency);
527:
528: return $result;
529: }
530: catch(Exception $e)
531: {
532: if($this->_connection->enableProfiling)
533: Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
534:
535: $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
536: $message=$e->getMessage();
537: Yii::log(Yii::t('yii','CDbCommand::{method}() failed: {error}. The SQL statement executed was: {sql}.',
538: array('{method}'=>$method, '{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
539:
540: if(YII_DEBUG)
541: $message.='. The SQL statement executed was: '.$this->getText().$par;
542:
543: throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
544: array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
545: }
546: }
547:
548: /**
549: * Builds a SQL SELECT statement from the given query specification.
550: * @param array $query the query specification in name-value pairs. The following
551: * query options are supported: {@link select}, {@link distinct}, {@link from},
552: * {@link where}, {@link join}, {@link group}, {@link having}, {@link order},
553: * {@link limit}, {@link offset} and {@link union}.
554: * @throws CDbException if "from" key is not present in given query parameter
555: * @return string the SQL statement
556: * @since 1.1.6
557: */
558: public function buildQuery($query)
559: {
560: $sql=!empty($query['distinct']) ? 'SELECT DISTINCT' : 'SELECT';
561: $sql.=' '.(!empty($query['select']) ? $query['select'] : '*');
562:
563: if(!empty($query['from']))
564: $sql.="\nFROM ".$query['from'];
565:
566: if(!empty($query['join']))
567: $sql.="\n".(is_array($query['join']) ? implode("\n",$query['join']) : $query['join']);
568:
569: if(!empty($query['where']))
570: $sql.="\nWHERE ".$query['where'];
571:
572: if(!empty($query['group']))
573: $sql.="\nGROUP BY ".$query['group'];
574:
575: if(!empty($query['having']))
576: $sql.="\nHAVING ".$query['having'];
577:
578: if(!empty($query['union']))
579: $sql.="\nUNION (\n".(is_array($query['union']) ? implode("\n) UNION (\n",$query['union']) : $query['union']) . ')';
580:
581: if(!empty($query['order']))
582: $sql.="\nORDER BY ".$query['order'];
583:
584: $limit=isset($query['limit']) ? (int)$query['limit'] : -1;
585: $offset=isset($query['offset']) ? (int)$query['offset'] : -1;
586: if($limit>=0 || $offset>0)
587: $sql=$this->_connection->getCommandBuilder()->applyLimit($sql,$limit,$offset);
588:
589: return $sql;
590: }
591:
592: /**
593: * Sets the SELECT part of the query.
594: * @param mixed $columns the columns to be selected. Defaults to '*', meaning all columns.
595: * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. array('id', 'name')).
596: * Columns can contain table prefixes (e.g. "tbl_user.id") and/or column aliases (e.g. "tbl_user.id AS user_id").
597: * The method will automatically quote the column names unless a column contains some parenthesis
598: * (which means the column contains a DB expression).
599: * @param string $option additional option that should be appended to the 'SELECT' keyword. For example,
600: * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used. This parameter is supported since version 1.1.8.
601: * @return static the command object itself
602: * @since 1.1.6
603: */
604: public function select($columns='*', $option='')
605: {
606: if(is_string($columns) && strpos($columns,'(')!==false)
607: $this->_query['select']=$columns;
608: else
609: {
610: if(!is_array($columns))
611: $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
612:
613: foreach($columns as $i=>$column)
614: {
615: if(is_object($column))
616: $columns[$i]=(string)$column;
617: elseif(strpos($column,'(')===false)
618: {
619: if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$column,$matches))
620: $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' AS '.$this->_connection->quoteColumnName($matches[2]);
621: else
622: $columns[$i]=$this->_connection->quoteColumnName($column);
623: }
624: }
625: $this->_query['select']=implode(', ',$columns);
626: }
627: if($option!='')
628: $this->_query['select']=$option.' '.$this->_query['select'];
629: return $this;
630: }
631:
632: /**
633: * Returns the SELECT part in the query.
634: * @return string the SELECT part (without 'SELECT') in the query.
635: * @since 1.1.6
636: */
637: public function getSelect()
638: {
639: return isset($this->_query['select']) ? $this->_query['select'] : '';
640: }
641:
642: /**
643: * Sets the SELECT part in the query.
644: * @param mixed $value the data to be selected. Please refer to {@link select()} for details
645: * on how to specify this parameter.
646: * @since 1.1.6
647: */
648: public function setSelect($value)
649: {
650: $this->select($value);
651: }
652:
653: /**
654: * Sets the SELECT part of the query with the DISTINCT flag turned on.
655: * This is the same as {@link select} except that the DISTINCT flag is turned on.
656: * @param mixed $columns the columns to be selected. See {@link select} for more details.
657: * @return CDbCommand the command object itself
658: * @since 1.1.6
659: */
660: public function selectDistinct($columns='*')
661: {
662: $this->_query['distinct']=true;
663: return $this->select($columns);
664: }
665:
666: /**
667: * Returns a value indicating whether SELECT DISTINCT should be used.
668: * @return boolean a value indicating whether SELECT DISTINCT should be used.
669: * @since 1.1.6
670: */
671: public function getDistinct()
672: {
673: return isset($this->_query['distinct']) ? $this->_query['distinct'] : false;
674: }
675:
676: /**
677: * Sets a value indicating whether SELECT DISTINCT should be used.
678: * @param boolean $value a value indicating whether SELECT DISTINCT should be used.
679: * @since 1.1.6
680: */
681: public function setDistinct($value)
682: {
683: $this->_query['distinct']=$value;
684: }
685:
686: /**
687: * Sets the FROM part of the query.
688: * @param mixed $tables the table(s) to be selected from. This can be either a string (e.g. 'tbl_user')
689: * or an array (e.g. array('tbl_user', 'tbl_profile')) specifying one or several table names.
690: * Table names can contain schema prefixes (e.g. 'public.tbl_user') and/or table aliases (e.g. 'tbl_user u').
691: * The method will automatically quote the table names unless it contains some parenthesis
692: * (which means the table is given as a sub-query or DB expression).
693: * @return static the command object itself
694: * @since 1.1.6
695: */
696: public function from($tables)
697: {
698: if(is_string($tables) && strpos($tables,'(')!==false)
699: $this->_query['from']=$tables;
700: else
701: {
702: if(!is_array($tables))
703: $tables=preg_split('/\s*,\s*/',trim($tables),-1,PREG_SPLIT_NO_EMPTY);
704: foreach($tables as $i=>$table)
705: {
706: if(strpos($table,'(')===false)
707: {
708: if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
709: $tables[$i]=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
710: else
711: $tables[$i]=$this->_connection->quoteTableName($table);
712: }
713: }
714: $this->_query['from']=implode(', ',$tables);
715: }
716: return $this;
717: }
718:
719: /**
720: * Returns the FROM part in the query.
721: * @return string the FROM part (without 'FROM' ) in the query.
722: * @since 1.1.6
723: */
724: public function getFrom()
725: {
726: return isset($this->_query['from']) ? $this->_query['from'] : '';
727: }
728:
729: /**
730: * Sets the FROM part in the query.
731: * @param mixed $value the tables to be selected from. Please refer to {@link from()} for details
732: * on how to specify this parameter.
733: * @since 1.1.6
734: */
735: public function setFrom($value)
736: {
737: $this->from($value);
738: }
739:
740: /**
741: * Sets the WHERE part of the query.
742: *
743: * The method requires a $conditions parameter, and optionally a $params parameter
744: * specifying the values to be bound to the query.
745: *
746: * The $conditions parameter should be either a string (e.g. 'id=1') or an array.
747: * If the latter, it must be of the format <code>array(operator, operand1, operand2, ...)</code>,
748: * where the operator can be one of the followings, and the possible operands depend on the corresponding
749: * operator:
750: * <ul>
751: * <li><code>and</code>: the operands should be concatenated together using AND. For example,
752: * array('and', 'id=1', 'id=2') will generate 'id=1 AND id=2'. If an operand is an array,
753: * it will be converted into a string using the same rules described here. For example,
754: * array('and', 'type=1', array('or', 'id=1', 'id=2')) will generate 'type=1 AND (id=1 OR id=2)'.
755: * The method will NOT do any quoting or escaping.</li>
756: * <li><code>or</code>: similar as the <code>and</code> operator except that the operands are concatenated using OR.</li>
757: * <li><code>in</code>: operand 1 should be a column or DB expression, and operand 2 be an array representing
758: * the range of the values that the column or DB expression should be in. For example,
759: * array('in', 'id', array(1,2,3)) will generate 'id IN (1,2,3)'.
760: * The method will properly quote the column name and escape values in the range.</li>
761: * <li><code>not in</code>: similar as the <code>in</code> operator except that IN is replaced with NOT IN in the generated condition.</li>
762: * <li><code>like</code>: operand 1 should be a column or DB expression, and operand 2 be a string or an array representing
763: * the values that the column or DB expression should be like.
764: * For example, array('like', 'name', '%tester%') will generate "name LIKE '%tester%'".
765: * When the value range is given as an array, multiple LIKE predicates will be generated and concatenated using AND.
766: * For example, array('like', 'name', array('%test%', '%sample%')) will generate
767: * "name LIKE '%test%' AND name LIKE '%sample%'".
768: * The method will properly quote the column name and escape values in the range.</li>
769: * <li><code>not like</code>: similar as the <code>like</code> operator except that LIKE is replaced with NOT LIKE in the generated condition.</li>
770: * <li><code>or like</code>: similar as the <code>like</code> operator except that OR is used to concatenated the LIKE predicates.</li>
771: * <li><code>or not like</code>: similar as the <code>not like</code> operator except that OR is used to concatenated the NOT LIKE predicates.</li>
772: * </ul>
773: * @param mixed $conditions the conditions that should be put in the WHERE part.
774: * @param array $params the parameters (name=>value) to be bound to the query
775: * @return static the command object itself
776: * @since 1.1.6
777: */
778: public function where($conditions, $params=array())
779: {
780: $this->_query['where']=$this->processConditions($conditions);
781:
782: foreach($params as $name=>$value)
783: $this->params[$name]=$value;
784: return $this;
785: }
786:
787: /**
788: * Appends given condition to the existing WHERE part of the query with 'AND' operator.
789: *
790: * This method works almost the same way as {@link where} except the fact that it appends condition
791: * with 'AND' operator, but not replaces it with the new one. For more information on parameters
792: * of this method refer to the {@link where} documentation.
793: *
794: * @param mixed $conditions the conditions that should be appended to the WHERE part.
795: * @param array $params the parameters (name=>value) to be bound to the query.
796: * @return static the command object itself.
797: * @since 1.1.13
798: */
799: public function andWhere($conditions,$params=array())
800: {
801: if(isset($this->_query['where']))
802: $this->_query['where']=$this->processConditions(array('AND',$this->_query['where'],$conditions));
803: else
804: $this->_query['where']=$this->processConditions($conditions);
805:
806: foreach($params as $name=>$value)
807: $this->params[$name]=$value;
808: return $this;
809: }
810:
811: /**
812: * Appends given condition to the existing WHERE part of the query with 'OR' operator.
813: *
814: * This method works almost the same way as {@link where} except the fact that it appends condition
815: * with 'OR' operator, but not replaces it with the new one. For more information on parameters
816: * of this method refer to the {@link where} documentation.
817: *
818: * @param mixed $conditions the conditions that should be appended to the WHERE part.
819: * @param array $params the parameters (name=>value) to be bound to the query.
820: * @return static the command object itself.
821: * @since 1.1.13
822: */
823: public function orWhere($conditions,$params=array())
824: {
825: if(isset($this->_query['where']))
826: $this->_query['where']=$this->processConditions(array('OR',$this->_query['where'],$conditions));
827: else
828: $this->_query['where']=$this->processConditions($conditions);
829:
830: foreach($params as $name=>$value)
831: $this->params[$name]=$value;
832: return $this;
833: }
834:
835: /**
836: * Returns the WHERE part in the query.
837: * @return string the WHERE part (without 'WHERE' ) in the query.
838: * @since 1.1.6
839: */
840: public function getWhere()
841: {
842: return isset($this->_query['where']) ? $this->_query['where'] : '';
843: }
844:
845: /**
846: * Sets the WHERE part in the query.
847: * @param mixed $value the where part. Please refer to {@link where()} for details
848: * on how to specify this parameter.
849: * @since 1.1.6
850: */
851: public function setWhere($value)
852: {
853: $this->where($value);
854: }
855:
856: /**
857: * Appends an INNER JOIN part to the query.
858: * @param string $table the table to be joined.
859: * Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u').
860: * The method will automatically quote the table name unless it contains some parenthesis
861: * (which means the table is given as a sub-query or DB expression).
862: * @param mixed $conditions the join condition that should appear in the ON part.
863: * Please refer to {@link where} on how to specify conditions.
864: * @param array $params the parameters (name=>value) to be bound to the query
865: * @return CDbCommand the command object itself
866: * @since 1.1.6
867: */
868: public function join($table, $conditions, $params=array())
869: {
870: return $this->joinInternal('join', $table, $conditions, $params);
871: }
872:
873: /**
874: * Returns the join part in the query.
875: * @return mixed the join part in the query. This can be an array representing
876: * multiple join fragments, or a string representing a single join fragment.
877: * Each join fragment will contain the proper join operator (e.g. LEFT JOIN).
878: * @since 1.1.6
879: */
880: public function getJoin()
881: {
882: return isset($this->_query['join']) ? $this->_query['join'] : '';
883: }
884:
885: /**
886: * Sets the join part in the query.
887: * @param mixed $value the join part in the query. This can be either a string or
888: * an array representing multiple join parts in the query. Each part must contain
889: * the proper join operator (e.g. 'LEFT JOIN tbl_profile ON tbl_user.id=tbl_profile.id')
890: * @since 1.1.6
891: */
892: public function setJoin($value)
893: {
894: $this->_query['join']=$value;
895: }
896:
897: /**
898: * Appends a LEFT OUTER JOIN part to the query.
899: * @param string $table the table to be joined.
900: * Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u').
901: * The method will automatically quote the table name unless it contains some parenthesis
902: * (which means the table is given as a sub-query or DB expression).
903: * @param mixed $conditions the join condition that should appear in the ON part.
904: * Please refer to {@link where} on how to specify conditions.
905: * @param array $params the parameters (name=>value) to be bound to the query
906: * @return CDbCommand the command object itself
907: * @since 1.1.6
908: */
909: public function leftJoin($table, $conditions, $params=array())
910: {
911: return $this->joinInternal('left join', $table, $conditions, $params);
912: }
913:
914: /**
915: * Appends a RIGHT OUTER JOIN part to the query.
916: * @param string $table the table to be joined.
917: * Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u').
918: * The method will automatically quote the table name unless it contains some parenthesis
919: * (which means the table is given as a sub-query or DB expression).
920: * @param mixed $conditions the join condition that should appear in the ON part.
921: * Please refer to {@link where} on how to specify conditions.
922: * @param array $params the parameters (name=>value) to be bound to the query
923: * @return CDbCommand the command object itself
924: * @since 1.1.6
925: */
926: public function rightJoin($table, $conditions, $params=array())
927: {
928: return $this->joinInternal('right join', $table, $conditions, $params);
929: }
930:
931: /**
932: * Appends a CROSS JOIN part to the query.
933: * Note that not all DBMS support CROSS JOIN.
934: * @param string $table the table to be joined.
935: * Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u').
936: * The method will automatically quote the table name unless it contains some parenthesis
937: * (which means the table is given as a sub-query or DB expression).
938: * @return CDbCommand the command object itself
939: * @since 1.1.6
940: */
941: public function crossJoin($table)
942: {
943: return $this->joinInternal('cross join', $table);
944: }
945:
946: /**
947: * Appends a NATURAL JOIN part to the query.
948: * Note that not all DBMS support NATURAL JOIN.
949: * @param string $table the table to be joined.
950: * Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u').
951: * The method will automatically quote the table name unless it contains some parenthesis
952: * (which means the table is given as a sub-query or DB expression).
953: * @return CDbCommand the command object itself
954: * @since 1.1.6
955: */
956: public function naturalJoin($table)
957: {
958: return $this->joinInternal('natural join', $table);
959: }
960:
961: /**
962: * Appends a NATURAL LEFT JOIN part to the query.
963: * Note that not all DBMS support NATURAL LEFT JOIN.
964: * @param string $table the table to be joined.
965: * Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u').
966: * The method will automatically quote the table name unless it contains some parenthesis
967: * (which means the table is given as a sub-query or DB expression).
968: * @return CDbCommand the command object itself
969: * @since 1.1.16
970: */
971: public function naturalLeftJoin($table)
972: {
973: return $this->joinInternal('natural left join', $table);
974: }
975:
976: /**
977: * Appends a NATURAL RIGHT JOIN part to the query.
978: * Note that not all DBMS support NATURAL RIGHT JOIN.
979: * @param string $table the table to be joined.
980: * Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u').
981: * The method will automatically quote the table name unless it contains some parenthesis
982: * (which means the table is given as a sub-query or DB expression).
983: * @return CDbCommand the command object itself
984: * @since 1.1.16
985: */
986: public function naturalRightJoin($table)
987: {
988: return $this->joinInternal('natural right join', $table);
989: }
990:
991: /**
992: * Sets the GROUP BY part of the query.
993: * @param mixed $columns the columns to be grouped by.
994: * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. array('id', 'name')).
995: * The method will automatically quote the column names unless a column contains some parenthesis
996: * (which means the column contains a DB expression).
997: * @return static the command object itself
998: * @since 1.1.6
999: */
1000: public function group($columns)
1001: {
1002: if(is_string($columns) && strpos($columns,'(')!==false)
1003: $this->_query['group']=$columns;
1004: else
1005: {
1006: if(!is_array($columns))
1007: $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
1008: foreach($columns as $i=>$column)
1009: {
1010: if(is_object($column))
1011: $columns[$i]=(string)$column;
1012: elseif(strpos($column,'(')===false)
1013: $columns[$i]=$this->_connection->quoteColumnName($column);
1014: }
1015: $this->_query['group']=implode(', ',$columns);
1016: }
1017: return $this;
1018: }
1019:
1020: /**
1021: * Returns the GROUP BY part in the query.
1022: * @return string the GROUP BY part (without 'GROUP BY' ) in the query.
1023: * @since 1.1.6
1024: */
1025: public function getGroup()
1026: {
1027: return isset($this->_query['group']) ? $this->_query['group'] : '';
1028: }
1029:
1030: /**
1031: * Sets the GROUP BY part in the query.
1032: * @param mixed $value the GROUP BY part. Please refer to {@link group()} for details
1033: * on how to specify this parameter.
1034: * @since 1.1.6
1035: */
1036: public function setGroup($value)
1037: {
1038: $this->group($value);
1039: }
1040:
1041: /**
1042: * Sets the HAVING part of the query.
1043: * @param mixed $conditions the conditions to be put after HAVING.
1044: * Please refer to {@link where} on how to specify conditions.
1045: * @param array $params the parameters (name=>value) to be bound to the query
1046: * @return static the command object itself
1047: * @since 1.1.6
1048: */
1049: public function having($conditions, $params=array())
1050: {
1051: $this->_query['having']=$this->processConditions($conditions);
1052: foreach($params as $name=>$value)
1053: $this->params[$name]=$value;
1054: return $this;
1055: }
1056:
1057: /**
1058: * Returns the HAVING part in the query.
1059: * @return string the HAVING part (without 'HAVING' ) in the query.
1060: * @since 1.1.6
1061: */
1062: public function getHaving()
1063: {
1064: return isset($this->_query['having']) ? $this->_query['having'] : '';
1065: }
1066:
1067: /**
1068: * Sets the HAVING part in the query.
1069: * @param mixed $value the HAVING part. Please refer to {@link having()} for details
1070: * on how to specify this parameter.
1071: * @since 1.1.6
1072: */
1073: public function setHaving($value)
1074: {
1075: $this->having($value);
1076: }
1077:
1078: /**
1079: * Sets the ORDER BY part of the query.
1080: * @param mixed $columns the columns (and the directions) to be ordered by.
1081: * Columns can be specified in either a string (e.g. "id ASC, name DESC") or an array (e.g. array('id ASC', 'name DESC')).
1082: * The method will automatically quote the column names unless a column contains some parenthesis
1083: * (which means the column contains a DB expression).
1084: *
1085: * For example, to get "ORDER BY 1" you should use
1086: *
1087: * <pre>
1088: * $criteria->order('(1)');
1089: * </pre>
1090: *
1091: * @return static the command object itself
1092: * @since 1.1.6
1093: */
1094: public function order($columns)
1095: {
1096: if(is_string($columns) && strpos($columns,'(')!==false)
1097: $this->_query['order']=$columns;
1098: else
1099: {
1100: if(!is_array($columns))
1101: $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
1102: foreach($columns as $i=>$column)
1103: {
1104: if(is_object($column))
1105: $columns[$i]=(string)$column;
1106: elseif(strpos($column,'(')===false)
1107: {
1108: if(preg_match('/^(.*?)\s+(asc|desc)$/i',$column,$matches))
1109: $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' '.strtoupper($matches[2]);
1110: else
1111: $columns[$i]=$this->_connection->quoteColumnName($column);
1112: }
1113: }
1114: $this->_query['order']=implode(', ',$columns);
1115: }
1116: return $this;
1117: }
1118:
1119: /**
1120: * Returns the ORDER BY part in the query.
1121: * @return string the ORDER BY part (without 'ORDER BY' ) in the query.
1122: * @since 1.1.6
1123: */
1124: public function getOrder()
1125: {
1126: return isset($this->_query['order']) ? $this->_query['order'] : '';
1127: }
1128:
1129: /**
1130: * Sets the ORDER BY part in the query.
1131: * @param mixed $value the ORDER BY part. Please refer to {@link order()} for details
1132: * on how to specify this parameter.
1133: * @since 1.1.6
1134: */
1135: public function setOrder($value)
1136: {
1137: $this->order($value);
1138: }
1139:
1140: /**
1141: * Sets the LIMIT part of the query.
1142: * @param integer $limit the limit
1143: * @param integer $offset the offset
1144: * @return static the command object itself
1145: * @since 1.1.6
1146: */
1147: public function limit($limit, $offset=null)
1148: {
1149: $this->_query['limit']=(int)$limit;
1150: if($offset!==null)
1151: $this->offset($offset);
1152: return $this;
1153: }
1154:
1155: /**
1156: * Returns the LIMIT part in the query.
1157: * @return string the LIMIT part (without 'LIMIT' ) in the query.
1158: * @since 1.1.6
1159: */
1160: public function getLimit()
1161: {
1162: return isset($this->_query['limit']) ? $this->_query['limit'] : -1;
1163: }
1164:
1165: /**
1166: * Sets the LIMIT part in the query.
1167: * @param integer $value the LIMIT part. Please refer to {@link limit()} for details
1168: * on how to specify this parameter.
1169: * @since 1.1.6
1170: */
1171: public function setLimit($value)
1172: {
1173: $this->limit($value);
1174: }
1175:
1176: /**
1177: * Sets the OFFSET part of the query.
1178: * @param integer $offset the offset
1179: * @return static the command object itself
1180: * @since 1.1.6
1181: */
1182: public function offset($offset)
1183: {
1184: $this->_query['offset']=(int)$offset;
1185: return $this;
1186: }
1187:
1188: /**
1189: * Returns the OFFSET part in the query.
1190: * @return string the OFFSET part (without 'OFFSET' ) in the query.
1191: * @since 1.1.6
1192: */
1193: public function getOffset()
1194: {
1195: return isset($this->_query['offset']) ? $this->_query['offset'] : -1;
1196: }
1197:
1198: /**
1199: * Sets the OFFSET part in the query.
1200: * @param integer $value the OFFSET part. Please refer to {@link offset()} for details
1201: * on how to specify this parameter.
1202: * @since 1.1.6
1203: */
1204: public function setOffset($value)
1205: {
1206: $this->offset($value);
1207: }
1208:
1209: /**
1210: * Appends a SQL statement using UNION operator.
1211: * @param string $sql the SQL statement to be appended using UNION
1212: * @return static the command object itself
1213: * @since 1.1.6
1214: */
1215: public function union($sql)
1216: {
1217: if(isset($this->_query['union']) && is_string($this->_query['union']))
1218: $this->_query['union']=array($this->_query['union']);
1219:
1220: $this->_query['union'][]=$sql;
1221:
1222: return $this;
1223: }
1224:
1225: /**
1226: * Returns the UNION part in the query.
1227: * @return mixed the UNION part (without 'UNION' ) in the query.
1228: * This can be either a string or an array representing multiple union parts.
1229: * @since 1.1.6
1230: */
1231: public function getUnion()
1232: {
1233: return isset($this->_query['union']) ? $this->_query['union'] : '';
1234: }
1235:
1236: /**
1237: * Sets the UNION part in the query.
1238: * @param mixed $value the UNION part. This can be either a string or an array
1239: * representing multiple SQL statements to be unioned together.
1240: * @since 1.1.6
1241: */
1242: public function setUnion($value)
1243: {
1244: $this->_query['union']=$value;
1245: }
1246:
1247: /**
1248: * Creates and executes an INSERT SQL statement.
1249: * The method will properly escape the column names, and bind the values to be inserted.
1250: * @param string $table the table that new rows will be inserted into.
1251: * @param array $columns the column data (name=>value) to be inserted into the table.
1252: * @return integer number of rows affected by the execution.
1253: * @since 1.1.6
1254: */
1255: public function insert($table, $columns)
1256: {
1257: $params=array();
1258: $names=array();
1259: $placeholders=array();
1260: foreach($columns as $name=>$value)
1261: {
1262: $names[]=$this->_connection->quoteColumnName($name);
1263: if($value instanceof CDbExpression)
1264: {
1265: $placeholders[] = $value->expression;
1266: foreach($value->params as $n => $v)
1267: $params[$n] = $v;
1268: }
1269: else
1270: {
1271: $placeholders[] = ':' . $name;
1272: $params[':' . $name] = $value;
1273: }
1274: }
1275: $sql='INSERT INTO ' . $this->_connection->quoteTableName($table)
1276: . ' (' . implode(', ',$names) . ') VALUES ('
1277: . implode(', ', $placeholders) . ')';
1278: return $this->setText($sql)->execute($params);
1279: }
1280:
1281: /**
1282: * Creates and executes an UPDATE SQL statement.
1283: * The method will properly escape the column names and bind the values to be updated.
1284: * @param string $table the table to be updated.
1285: * @param array $columns the column data (name=>value) to be updated.
1286: * @param mixed $conditions the conditions that will be put in the WHERE part. Please
1287: * refer to {@link where} on how to specify conditions.
1288: * @param array $params the parameters to be bound to the query.
1289: * Do not use column names as parameter names here. They are reserved for <code>$columns</code> parameter.
1290: * @return integer number of rows affected by the execution.
1291: * @since 1.1.6
1292: */
1293: public function update($table, $columns, $conditions='', $params=array())
1294: {
1295: $lines=array();
1296: foreach($columns as $name=>$value)
1297: {
1298: if($value instanceof CDbExpression)
1299: {
1300: $lines[]=$this->_connection->quoteColumnName($name) . '=' . $value->expression;
1301: foreach($value->params as $n => $v)
1302: $params[$n] = $v;
1303: }
1304: else
1305: {
1306: $lines[]=$this->_connection->quoteColumnName($name) . '=:' . $name;
1307: $params[':' . $name]=$value;
1308: }
1309: }
1310: $sql='UPDATE ' . $this->_connection->quoteTableName($table) . ' SET ' . implode(', ', $lines);
1311: if(($where=$this->processConditions($conditions))!='')
1312: $sql.=' WHERE '.$where;
1313: return $this->setText($sql)->execute($params);
1314: }
1315:
1316: /**
1317: * Creates and executes a DELETE SQL statement.
1318: * @param string $table the table where the data will be deleted from.
1319: * @param mixed $conditions the conditions that will be put in the WHERE part. Please
1320: * refer to {@link where} on how to specify conditions.
1321: * @param array $params the parameters to be bound to the query.
1322: * @return integer number of rows affected by the execution.
1323: * @since 1.1.6
1324: */
1325: public function delete($table, $conditions='', $params=array())
1326: {
1327: $sql='DELETE FROM ' . $this->_connection->quoteTableName($table);
1328: if(($where=$this->processConditions($conditions))!='')
1329: $sql.=' WHERE '.$where;
1330: return $this->setText($sql)->execute($params);
1331: }
1332:
1333: /**
1334: * Builds and executes a SQL statement for creating a new DB table.
1335: *
1336: * The columns in the new table should be specified as name-definition pairs (e.g. 'name'=>'string'),
1337: * where name stands for a column name which will be properly quoted by the method, and definition
1338: * stands for the column type which can contain an abstract DB type.
1339: * The {@link getColumnType} method will be invoked to convert any abstract type into a physical one.
1340: *
1341: * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
1342: * inserted into the generated SQL.
1343: *
1344: * @param string $table the name of the table to be created. The name will be properly quoted by the method.
1345: * @param array $columns the columns (name=>definition) in the new table.
1346: * @param string $options additional SQL fragment that will be appended to the generated SQL.
1347: * @return integer 0 is always returned. See {@link http://php.net/manual/en/pdostatement.rowcount.php} for more information.
1348: * @since 1.1.6
1349: */
1350: public function createTable($table, $columns, $options=null)
1351: {
1352: return $this->setText($this->getConnection()->getSchema()->createTable($table, $columns, $options))->execute();
1353: }
1354:
1355: /**
1356: * Builds and executes a SQL statement for renaming a DB table.
1357: * @param string $table the table to be renamed. The name will be properly quoted by the method.
1358: * @param string $newName the new table name. The name will be properly quoted by the method.
1359: * @return integer 0 is always returned. See {@link http://php.net/manual/en/pdostatement.rowcount.php} for more information.
1360: * @since 1.1.6
1361: */
1362: public function renameTable($table, $newName)
1363: {
1364: return $this->setText($this->getConnection()->getSchema()->renameTable($table, $newName))->execute();
1365: }
1366:
1367: /**
1368: * Builds and executes a SQL statement for dropping a DB table.
1369: * @param string $table the table to be dropped. The name will be properly quoted by the method.
1370: * @return integer 0 is always returned. See {@link http://php.net/manual/en/pdostatement.rowcount.php} for more information.
1371: * @since 1.1.6
1372: */
1373: public function dropTable($table)
1374: {
1375: return $this->setText($this->getConnection()->getSchema()->dropTable($table))->execute();
1376: }
1377:
1378: /**
1379: * Builds and executes a SQL statement for truncating a DB table.
1380: * @param string $table the table to be truncated. The name will be properly quoted by the method.
1381: * @return integer number of rows affected by the execution.
1382: * @since 1.1.6
1383: */
1384: public function truncateTable($table)
1385: {
1386: $schema=$this->getConnection()->getSchema();
1387: $n=$this->setText($schema->truncateTable($table))->execute();
1388: if(strncasecmp($this->getConnection()->getDriverName(),'sqlite',6)===0)
1389: $schema->resetSequence($schema->getTable($table));
1390: return $n;
1391: }
1392:
1393: /**
1394: * Builds and executes a SQL statement for adding a new DB column.
1395: * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
1396: * @param string $column the name of the new column. The name will be properly quoted by the method.
1397: * @param string $type the column type. The {@link getColumnType} method will be invoked to convert abstract column type (if any)
1398: * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
1399: * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
1400: * @return integer number of rows affected by the execution.
1401: * @since 1.1.6
1402: */
1403: public function addColumn($table, $column, $type)
1404: {
1405: return $this->setText($this->getConnection()->getSchema()->addColumn($table, $column, $type))->execute();
1406: }
1407:
1408: /**
1409: * Builds and executes a SQL statement for dropping a DB column.
1410: * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
1411: * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
1412: * @return integer number of rows affected by the execution.
1413: * @since 1.1.6
1414: */
1415: public function dropColumn($table, $column)
1416: {
1417: return $this->setText($this->getConnection()->getSchema()->dropColumn($table, $column))->execute();
1418: }
1419:
1420: /**
1421: * Builds and executes a SQL statement for renaming a column.
1422: * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
1423: * @param string $name the old name of the column. The name will be properly quoted by the method.
1424: * @param string $newName the new name of the column. The name will be properly quoted by the method.
1425: * @return integer number of rows affected by the execution.
1426: * @since 1.1.6
1427: */
1428: public function renameColumn($table, $name, $newName)
1429: {
1430: return $this->setText($this->getConnection()->getSchema()->renameColumn($table, $name, $newName))->execute();
1431: }
1432:
1433: /**
1434: * Builds and executes a SQL statement for changing the definition of a column.
1435: * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
1436: * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
1437: * @param string $type the new column type. The {@link getColumnType} method will be invoked to convert abstract column type (if any)
1438: * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
1439: * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
1440: * @return integer number of rows affected by the execution.
1441: * @since 1.1.6
1442: */
1443: public function alterColumn($table, $column, $type)
1444: {
1445: return $this->setText($this->getConnection()->getSchema()->alterColumn($table, $column, $type))->execute();
1446: }
1447:
1448: /**
1449: * Builds a SQL statement for adding a foreign key constraint to an existing table.
1450: * The method will properly quote the table and column names.
1451: * @param string $name the name of the foreign key constraint.
1452: * @param string $table the table that the foreign key constraint will be added to.
1453: * @param string|array $columns the name of the column to that the constraint will be added on. If there are multiple columns, separate them with commas or pass as an array of column names.
1454: * @param string $refTable the table that the foreign key references to.
1455: * @param string|array $refColumns the name of the column that the foreign key references to. If there are multiple columns, separate them with commas or pass as an array of column names.
1456: * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
1457: * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
1458: * @return integer number of rows affected by the execution.
1459: * @since 1.1.6
1460: */
1461: public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
1462: {
1463: return $this->setText($this->getConnection()->getSchema()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update))->execute();
1464: }
1465:
1466: /**
1467: * Builds a SQL statement for dropping a foreign key constraint.
1468: * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
1469: * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
1470: * @return integer number of rows affected by the execution.
1471: * @since 1.1.6
1472: */
1473: public function dropForeignKey($name, $table)
1474: {
1475: return $this->setText($this->getConnection()->getSchema()->dropForeignKey($name, $table))->execute();
1476: }
1477:
1478: /**
1479: * Builds and executes a SQL statement for creating a new index.
1480: * @param string $name the name of the index. The name will be properly quoted by the method.
1481: * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
1482: * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns, please separate them
1483: * by commas or pass as an array of column names. Each column name will be properly quoted by the method, unless a parenthesis is found in the name.
1484: * @param boolean $unique whether to add UNIQUE constraint on the created index.
1485: * @return integer number of rows affected by the execution.
1486: * @since 1.1.6
1487: */
1488: public function createIndex($name, $table, $columns, $unique=false)
1489: {
1490: return $this->setText($this->getConnection()->getSchema()->createIndex($name, $table, $columns, $unique))->execute();
1491: }
1492:
1493: /**
1494: * Builds and executes a SQL statement for dropping an index.
1495: * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
1496: * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
1497: * @return integer number of rows affected by the execution.
1498: * @since 1.1.6
1499: */
1500: public function dropIndex($name, $table)
1501: {
1502: return $this->setText($this->getConnection()->getSchema()->dropIndex($name, $table))->execute();
1503: }
1504:
1505: /**
1506: * Generates the condition string that will be put in the WHERE part
1507: * @param mixed $conditions the conditions that will be put in the WHERE part.
1508: * @throws CDbException if unknown operator is used
1509: * @return string the condition string to put in the WHERE part
1510: */
1511: private function processConditions($conditions)
1512: {
1513: if(!is_array($conditions))
1514: return $conditions;
1515: elseif($conditions===array())
1516: return '';
1517: $n=count($conditions);
1518: $operator=strtoupper($conditions[0]);
1519: if($operator==='OR' || $operator==='AND')
1520: {
1521: $parts=array();
1522: for($i=1;$i<$n;++$i)
1523: {
1524: $condition=$this->processConditions($conditions[$i]);
1525: if($condition!=='')
1526: $parts[]='('.$condition.')';
1527: }
1528: return $parts===array() ? '' : implode(' '.$operator.' ', $parts);
1529: }
1530:
1531: if(!isset($conditions[1],$conditions[2]))
1532: return '';
1533:
1534: $column=$conditions[1];
1535: if(strpos($column,'(')===false)
1536: $column=$this->_connection->quoteColumnName($column);
1537:
1538: $values=$conditions[2];
1539: if(!is_array($values))
1540: $values=array($values);
1541:
1542: if($operator==='IN' || $operator==='NOT IN')
1543: {
1544: if($values===array())
1545: return $operator==='IN' ? '0=1' : '';
1546: foreach($values as $i=>$value)
1547: {
1548: if(is_string($value))
1549: $values[$i]=$this->_connection->quoteValue($value);
1550: else
1551: $values[$i]=(string)$value;
1552: }
1553: return $column.' '.$operator.' ('.implode(', ',$values).')';
1554: }
1555:
1556: if($operator==='LIKE' || $operator==='NOT LIKE' || $operator==='OR LIKE' || $operator==='OR NOT LIKE')
1557: {
1558: if($values===array())
1559: return $operator==='LIKE' || $operator==='OR LIKE' ? '0=1' : '';
1560:
1561: if($operator==='LIKE' || $operator==='NOT LIKE')
1562: $andor=' AND ';
1563: else
1564: {
1565: $andor=' OR ';
1566: $operator=$operator==='OR LIKE' ? 'LIKE' : 'NOT LIKE';
1567: }
1568: $expressions=array();
1569: foreach($values as $value)
1570: $expressions[]=$column.' '.$operator.' '.$this->_connection->quoteValue($value);
1571: return implode($andor,$expressions);
1572: }
1573:
1574: throw new CDbException(Yii::t('yii', 'Unknown operator "{operator}".', array('{operator}'=>$operator)));
1575: }
1576:
1577: /**
1578: * Appends an JOIN part to the query.
1579: * @param string $type the join type ('join', 'left join', 'right join', 'cross join', 'natural join')
1580: * @param string $table the table to be joined.
1581: * Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u').
1582: * The method will automatically quote the table name unless it contains some parenthesis
1583: * (which means the table is given as a sub-query or DB expression).
1584: * @param mixed $conditions the join condition that should appear in the ON part.
1585: * Please refer to {@link where} on how to specify conditions.
1586: * @param array $params the parameters (name=>value) to be bound to the query
1587: * @return static the command object itself
1588: * @since 1.1.6
1589: */
1590: private function joinInternal($type, $table, $conditions='', $params=array())
1591: {
1592: if(strpos($table,'(')===false)
1593: {
1594: if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
1595: $table=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
1596: else
1597: $table=$this->_connection->quoteTableName($table);
1598: }
1599:
1600: $conditions=$this->processConditions($conditions);
1601: if($conditions!='')
1602: $conditions=' ON '.$conditions;
1603:
1604: if(isset($this->_query['join']) && is_string($this->_query['join']))
1605: $this->_query['join']=array($this->_query['join']);
1606:
1607: $this->_query['join'][]=strtoupper($type) . ' ' . $table . $conditions;
1608:
1609: foreach($params as $name=>$value)
1610: $this->params[$name]=$value;
1611: return $this;
1612: }
1613:
1614: /**
1615: * Builds a SQL statement for creating a primary key constraint.
1616: * @param string $name the name of the primary key constraint to be created. The name will be properly quoted by the method.
1617: * @param string $table the table who will be inheriting the primary key. The name will be properly quoted by the method.
1618: * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
1619: * Array value can be passed since 1.1.14.
1620: * @return integer number of rows affected by the execution.
1621: * @since 1.1.13
1622: */
1623: public function addPrimaryKey($name,$table,$columns)
1624: {
1625: return $this->setText($this->getConnection()->getSchema()->addPrimaryKey($name,$table,$columns))->execute();
1626: }
1627:
1628: /**
1629: * Builds a SQL statement for dropping a primary key constraint.
1630: * @param string $name the name of the primary key constraint to be dropped. The name will be properly quoted by the method.
1631: * @param string $table the table that owns the primary key. The name will be properly quoted by the method.
1632: * @return integer number of rows affected by the execution.
1633: * @since 1.1.13
1634: */
1635: public function dropPrimaryKey($name,$table)
1636: {
1637: return $this->setText($this->getConnection()->getSchema()->dropPrimaryKey($name,$table))->execute();
1638: }
1639: }
1640: