CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 1.2 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 1.2
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Classes

  • AclBase
  • AclBehavior
  • AclComponent
  • AclNode
  • AclShell
  • Aco
  • AcoAction
  • AjaxHelper
  • ApcEngine
  • ApiShell
  • App
  • AppController
  • AppHelper
  • AppModel
  • Aro
  • AuthComponent
  • BakeShell
  • BehaviorCollection
  • Cache
  • CacheEngine
  • CacheHelper
  • CakeErrorController
  • CakeLog
  • CakeSchema
  • CakeSession
  • CakeSocket
  • ClassRegistry
  • Component
  • Configure
  • ConnectionManager
  • ConsoleShell
  • ContainableBehavior
  • Controller
  • ControllerTask
  • CookieComponent
  • DataSource
  • DbAcl
  • DbAclSchema
  • DbConfigTask
  • DboAdodb
  • DboDb2
  • DboFirebird
  • DboMssql
  • DboMysql
  • DboMysqlBase
  • DboMysqli
  • DboOdbc
  • DboOracle
  • DboPostgres
  • DboSource
  • DboSqlite
  • DboSybase
  • Debugger
  • EmailComponent
  • ErrorHandler
  • ExtractTask
  • File
  • FileEngine
  • Flay
  • Folder
  • FormHelper
  • Helper
  • HtmlHelper
  • HttpSocket
  • I18n
  • I18nModel
  • i18nSchema
  • I18nShell
  • Inflector
  • IniAcl
  • JavascriptHelper
  • JsHelper
  • JsHelperObject
  • L10n
  • MagicDb
  • MagicFileResource
  • MediaView
  • MemcacheEngine
  • Model
  • ModelBehavior
  • ModelTask
  • Multibyte
  • NumberHelper
  • Object
  • Overloadable
  • Overloadable2
  • PagesController
  • PaginatorHelper
  • Permission
  • PluginTask
  • ProjectTask
  • RequestHandlerComponent
  • Router
  • RssHelper
  • Sanitize
  • Scaffold
  • ScaffoldView
  • SchemaShell
  • Security
  • SecurityComponent
  • SessionComponent
  • SessionHelper
  • SessionsSchema
  • Set
  • Shell
  • String
  • TestSuiteShell
  • TestTask
  • TextHelper
  • ThemeView
  • TimeHelper
  • TranslateBehavior
  • TreeBehavior
  • Validation
  • View
  • ViewTask
  • XcacheEngine
  • Xml
  • XmlElement
  • XmlHelper
  • XmlManager
  • XmlNode
  • XmlTextNode

Functions

  • __enclose
  • make_clean_css
  • mb_encode_mimeheader
  • mb_stripos
  • mb_stristr
  • mb_strlen
  • mb_strpos
  • mb_strrchr
  • mb_strrichr
  • mb_strripos
  • mb_strrpos
  • mb_strstr
  • mb_strtolower
  • mb_strtoupper
  • mb_substr
  • mb_substr_count
  • write_css_cache
  1: <?php
  2: /* SVN FILE: $Id$ */
  3: /**
  4:  * MS SQL layer for DBO
  5:  *
  6:  * Long description for file
  7:  *
  8:  * PHP versions 4 and 5
  9:  *
 10:  * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 11:  * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 12:  *
 13:  * Licensed under The MIT License
 14:  * Redistributions of files must retain the above copyright notice.
 15:  *
 16:  * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 17:  * @link          http://cakephp.org CakePHP(tm) Project
 18:  * @package       cake
 19:  * @subpackage    cake.cake.libs.model.datasources.dbo
 20:  * @since         CakePHP(tm) v 0.10.5.1790
 21:  * @version       $Revision$
 22:  * @modifiedby    $LastChangedBy$
 23:  * @lastmodified  $Date$
 24:  * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 25:  */
 26: /**
 27:  * Short description for class.
 28:  *
 29:  * Long description for class
 30:  *
 31:  * @package       cake
 32:  * @subpackage    cake.cake.libs.model.datasources.dbo
 33:  */
 34: class DboMssql extends DboSource {
 35: /**
 36:  * Driver description
 37:  *
 38:  * @var string
 39:  */
 40:     var $description = "MS SQL DBO Driver";
 41: /**
 42:  * Starting quote character for quoted identifiers
 43:  *
 44:  * @var string
 45:  */
 46:     var $startQuote = "[";
 47: /**
 48:  * Ending quote character for quoted identifiers
 49:  *
 50:  * @var string
 51:  */
 52:     var $endQuote = "]";
 53: /**
 54:  * Creates a map between field aliases and numeric indexes.  Workaround for the
 55:  * SQL Server driver's 30-character column name limitation.
 56:  *
 57:  * @var array
 58:  */
 59:     var $__fieldMappings = array();
 60: /**
 61:  * Base configuration settings for MS SQL driver
 62:  *
 63:  * @var array
 64:  */
 65:     var $_baseConfig = array(
 66:         'persistent' => true,
 67:         'host' => 'localhost',
 68:         'login' => 'root',
 69:         'password' => '',
 70:         'database' => 'cake',
 71:         'port' => '1433',
 72:     );
 73: /**
 74:  * MS SQL column definition
 75:  *
 76:  * @var array
 77:  */
 78:     var $columns = array(
 79:         'primary_key' => array('name' => 'IDENTITY (1, 1) NOT NULL'),
 80:         'string'    => array('name' => 'varchar', 'limit' => '255'),
 81:         'text'      => array('name' => 'text'),
 82:         'integer'   => array('name' => 'int', 'formatter' => 'intval'),
 83:         'float'     => array('name' => 'numeric', 'formatter' => 'floatval'),
 84:         'datetime'  => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
 85:         'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
 86:         'time'      => array('name' => 'datetime', 'format' => 'H:i:s', 'formatter' => 'date'),
 87:         'date'      => array('name' => 'datetime', 'format' => 'Y-m-d', 'formatter' => 'date'),
 88:         'binary'    => array('name' => 'image'),
 89:         'boolean'   => array('name' => 'bit')
 90:     );
 91: /**
 92:  * Index of basic SQL commands
 93:  *
 94:  * @var array
 95:  * @access protected
 96:  */
 97:     var $_commands = array(
 98:         'begin'    => 'BEGIN TRANSACTION',
 99:         'commit'   => 'COMMIT',
100:         'rollback' => 'ROLLBACK'
101:     );
102: /**
103:  * Define if the last query had error
104:  *
105:  * @var string
106:  * @access private
107:  */
108:     var $__lastQueryHadError = false;
109: /**
110:  * MS SQL DBO driver constructor; sets SQL Server error reporting defaults
111:  *
112:  * @param array $config Configuration data from app/config/databases.php
113:  * @return boolean True if connected successfully, false on error
114:  */
115:     function __construct($config, $autoConnect = true) {
116:         if ($autoConnect) {
117:             if (!function_exists('mssql_min_message_severity')) {
118:                 trigger_error("PHP SQL Server interface is not installed, cannot continue.  For troubleshooting information, see http://php.net/mssql/", E_USER_WARNING);
119:             }
120:             mssql_min_message_severity(15);
121:             mssql_min_error_severity(2);
122:         }
123:         return parent::__construct($config, $autoConnect);
124:     }
125: /**
126:  * Connects to the database using options in the given configuration array.
127:  *
128:  * @return boolean True if the database could be connected, else false
129:  */
130:     function connect() {
131:         $config = $this->config;
132: 
133:         $os = env('OS');
134:         if (!empty($os) && strpos($os, 'Windows') !== false) {
135:             $sep = ',';
136:         } else {
137:             $sep = ':';
138:         }
139:         $this->connected = false;
140: 
141:         if (is_numeric($config['port'])) {
142:             $port = $sep . $config['port']; // Port number
143:         } elseif ($config['port'] === null) {
144:             $port = '';                     // No port - SQL Server 2005
145:         } else {
146:             $port = '\\' . $config['port']; // Named pipe
147:         }
148: 
149:         if (!$config['persistent']) {
150:             $this->connection = mssql_connect($config['host'] . $port, $config['login'], $config['password'], true);
151:         } else {
152:             $this->connection = mssql_pconnect($config['host'] . $port, $config['login'], $config['password']);
153:         }
154: 
155:         if (mssql_select_db($config['database'], $this->connection)) {
156:             $this->_execute("SET DATEFORMAT ymd");
157:             $this->connected = true;
158:         }
159:         return $this->connected;
160:     }
161: /**
162:  * Check that MsSQL is installed/loaded
163:  *
164:  * @return boolean
165:  **/
166:     function enabled() {
167:         return extension_loaded('mssql');
168:     }
169: /**
170:  * Disconnects from database.
171:  *
172:  * @return boolean True if the database could be disconnected, else false
173:  */
174:     function disconnect() {
175:         @mssql_free_result($this->results);
176:         $this->connected = !@mssql_close($this->connection);
177:         return !$this->connected;
178:     }
179: /**
180:  * Executes given SQL statement.
181:  *
182:  * @param string $sql SQL statement
183:  * @return resource Result resource identifier
184:  * @access protected
185:  */
186:     function _execute($sql) {
187:         $result = @mssql_query($sql, $this->connection);
188:         $this->__lastQueryHadError = ($result === false);
189:         return $result;
190:     }
191: /**
192:  * Returns an array of sources (tables) in the database.
193:  *
194:  * @return array Array of tablenames in the database
195:  */
196:     function listSources() {
197:         $cache = parent::listSources();
198: 
199:         if ($cache != null) {
200:             return $cache;
201:         }
202:         $result = $this->fetchAll('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES', false);
203: 
204:         if (!$result || empty($result)) {
205:             return array();
206:         } else {
207:             $tables = array();
208: 
209:             foreach ($result as $table) {
210:                 $tables[] = $table[0]['TABLE_NAME'];
211:             }
212: 
213:             parent::listSources($tables);
214:             return $tables;
215:         }
216:     }
217: /**
218:  * Returns an array of the fields in given table name.
219:  *
220:  * @param Model $model Model object to describe
221:  * @return array Fields in table. Keys are name and type
222:  */
223:     function describe(&$model) {
224:         $cache = parent::describe($model);
225: 
226:         if ($cache != null) {
227:             return $cache;
228:         }
229: 
230:         $table = $this->fullTableName($model, false);
231:         $cols = $this->fetchAll("SELECT COLUMN_NAME as Field, DATA_TYPE as Type, COL_LENGTH('" . $table . "', COLUMN_NAME) as Length, IS_NULLABLE As [Null], COLUMN_DEFAULT as [Default], COLUMNPROPERTY(OBJECT_ID('" . $table . "'), COLUMN_NAME, 'IsIdentity') as [Key], NUMERIC_SCALE as Size FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" . $table . "'", false);
232: 
233:         $fields = false;
234:         foreach ($cols as $column) {
235:             $field = $column[0]['Field'];
236:             $fields[$field] = array(
237:                 'type' => $this->column($column[0]['Type']),
238:                 'null' => (strtoupper($column[0]['Null']) == 'YES'),
239:                 'default' => preg_replace("/^[(]{1,2}'?([^')]*)?'?[)]{1,2}$/", "$1", $column[0]['Default']),
240:                 'length' => intval($column[0]['Length']),
241:                 'key' => ($column[0]['Key'] == '1') ? 'primary' : false
242:             );
243:             if ($fields[$field]['default'] === 'null') {
244:                 $fields[$field]['default'] = null;
245:             } else {
246:                 $this->value($fields[$field]['default'], $fields[$field]['type']);
247:             }
248: 
249:             if ($fields[$field]['key'] && $fields[$field]['type'] == 'integer') {
250:                 $fields[$field]['length'] = 11;
251:             } elseif (!$fields[$field]['key']) {
252:                 unset($fields[$field]['key']);
253:             }
254:             if (in_array($fields[$field]['type'], array('date', 'time', 'datetime', 'timestamp'))) {
255:                 $fields[$field]['length'] = null;
256:             }
257:         }
258:         $this->__cacheDescription($this->fullTableName($model, false), $fields);
259:         return $fields;
260:     }
261: /**
262:  * Returns a quoted and escaped string of $data for use in an SQL statement.
263:  *
264:  * @param string $data String to be prepared for use in an SQL statement
265:  * @param string $column The column into which this data will be inserted
266:  * @param boolean $safe Whether or not numeric data should be handled automagically if no column data is provided
267:  * @return string Quoted and escaped data
268:  */
269:     function value($data, $column = null, $safe = false) {
270:         $parent = parent::value($data, $column, $safe);
271: 
272:         if ($parent != null) {
273:             return $parent;
274:         }
275:         if ($data === null) {
276:             return 'NULL';
277:         }
278:         if (in_array($column, array('integer', 'float', 'binary')) && $data === '') {
279:             return 'NULL';
280:         }
281:         if ($data === '') {
282:             return "''";
283:         }
284: 
285:         switch ($column) {
286:             case 'boolean':
287:                 $data = $this->boolean((bool)$data);
288:             break;
289:             default:
290:                 if (get_magic_quotes_gpc()) {
291:                     $data = stripslashes(str_replace("'", "''", $data));
292:                 } else {
293:                     $data = str_replace("'", "''", $data);
294:                 }
295:             break;
296:         }
297: 
298:         if (in_array($column, array('integer', 'float', 'binary')) && is_numeric($data)) {
299:             return $data;
300:         }
301:         return "'" . $data . "'";
302:     }
303: /**
304:  * Generates the fields list of an SQL query.
305:  *
306:  * @param Model $model
307:  * @param string $alias Alias tablename
308:  * @param mixed $fields
309:  * @return array
310:  */
311:     function fields(&$model, $alias = null, $fields = array(), $quote = true) {
312:         if (empty($alias)) {
313:             $alias = $model->alias;
314:         }
315:         $fields = parent::fields($model, $alias, $fields, false);
316:         $count = count($fields);
317: 
318:         if ($count >= 1 && strpos($fields[0], 'COUNT(*)') === false) {
319:             $result = array();
320:             for ($i = 0; $i < $count; $i++) {
321:                 $prepend = '';
322: 
323:                 if (strpos($fields[$i], 'DISTINCT') !== false) {
324:                     $prepend = 'DISTINCT ';
325:                     $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
326:                 }
327:                 $fieldAlias = count($this->__fieldMappings);
328: 
329:                 if (!preg_match('/\s+AS\s+/i', $fields[$i])) {
330:                     if (substr($fields[$i], -1) == '*') {
331:                         if (strpos($fields[$i], '.') !== false && $fields[$i] != $alias . '.*') {
332:                             $build = explode('.', $fields[$i]);
333:                             $AssociatedModel = $model->{$build[0]};
334:                         } else {
335:                             $AssociatedModel = $model;
336:                         }
337: 
338:                         $_fields = $this->fields($AssociatedModel, $AssociatedModel->alias, array_keys($AssociatedModel->schema()));
339:                         $result = array_merge($result, $_fields);
340:                         continue;
341:                     }
342: 
343:                     if (strpos($fields[$i], '.') === false) {
344:                         $this->__fieldMappings[$alias . '__' . $fieldAlias] = $alias . '.' . $fields[$i];
345:                         $fieldName  = $this->name($alias . '.' . $fields[$i]);
346:                         $fieldAlias = $this->name($alias . '__' . $fieldAlias);
347:                     } else {
348:                         $build = explode('.', $fields[$i]);
349:                         $this->__fieldMappings[$build[0] . '__' . $fieldAlias] = $fields[$i];
350:                         $fieldName  = $this->name($build[0] . '.' . $build[1]);
351:                         $fieldAlias = $this->name(preg_replace("/^\[(.+)\]$/", "$1", $build[0]) . '__' . $fieldAlias);
352:                     }
353:                     if ($model->getColumnType($fields[$i]) == 'datetime') {
354:                         $fieldName = "CONVERT(VARCHAR(20), {$fieldName}, 20)";
355:                     }
356:                     $fields[$i] =  "{$fieldName} AS {$fieldAlias}";
357:                 }
358:                 $result[] = $prepend . $fields[$i];
359:             }
360:             return $result;
361:         } else {
362:             return $fields;
363:         }
364:     }
365: /**
366:  * Generates and executes an SQL INSERT statement for given model, fields, and values.
367:  * Removes Identity (primary key) column from update data before returning to parent, if
368:  * value is empty.
369:  *
370:  * @param Model $model
371:  * @param array $fields
372:  * @param array $values
373:  * @param mixed $conditions
374:  * @return array
375:  */
376:     function create(&$model, $fields = null, $values = null) {
377:         if (!empty($values)) {
378:             $fields = array_combine($fields, $values);
379:         }
380:         $primaryKey = $this->_getPrimaryKey($model);
381: 
382:         if (array_key_exists($primaryKey, $fields)) {
383:             if (empty($fields[$primaryKey])) {
384:                 unset($fields[$primaryKey]);
385:             } else {
386:                 $this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($model) . ' ON');
387:             }
388:         }
389:         $result = parent::create($model, array_keys($fields), array_values($fields));
390:         if (array_key_exists($primaryKey, $fields) && !empty($fields[$primaryKey])) {
391:             $this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($model) . ' OFF');
392:         }
393:         return $result;
394:     }
395: /**
396:  * Generates and executes an SQL UPDATE statement for given model, fields, and values.
397:  * Removes Identity (primary key) column from update data before returning to parent.
398:  *
399:  * @param Model $model
400:  * @param array $fields
401:  * @param array $values
402:  * @param mixed $conditions
403:  * @return array
404:  */
405:     function update(&$model, $fields = array(), $values = null, $conditions = null) {
406:         if (!empty($values)) {
407:             $fields = array_combine($fields, $values);
408:         }
409:         if (isset($fields[$model->primaryKey])) {
410:             unset($fields[$model->primaryKey]);
411:         }
412:         if (empty($fields)) {
413:             return true;
414:         }
415:         return parent::update($model, array_keys($fields), array_values($fields), $conditions);
416:     }
417: /**
418:  * Returns a formatted error message from previous database operation.
419:  *
420:  * @return string Error message with error number
421:  */
422:     function lastError() {
423:         if ($this->__lastQueryHadError) {
424:             $error = mssql_get_last_message();
425:             if ($error && !preg_match('/contexto de la base de datos a|contesto di database|changed database|contexte de la base de don|datenbankkontext/i', $error)) {
426:                 return $error;
427:             }
428:         }
429:         return null;
430:     }
431: /**
432:  * Returns number of affected rows in previous database operation. If no previous operation exists,
433:  * this returns false.
434:  *
435:  * @return integer Number of affected rows
436:  */
437:     function lastAffected() {
438:         if ($this->_result) {
439:             return mssql_rows_affected($this->connection);
440:         }
441:         return null;
442:     }
443: /**
444:  * Returns number of rows in previous resultset. If no previous resultset exists,
445:  * this returns false.
446:  *
447:  * @return integer Number of rows in resultset
448:  */
449:     function lastNumRows() {
450:         if ($this->_result) {
451:             return @mssql_num_rows($this->_result);
452:         }
453:         return null;
454:     }
455: /**
456:  * Returns the ID generated from the previous INSERT operation.
457:  *
458:  * @param unknown_type $source
459:  * @return in
460:  */
461:     function lastInsertId($source = null) {
462:         $id = $this->fetchRow('SELECT SCOPE_IDENTITY() AS insertID', false);
463:         return $id[0]['insertID'];
464:     }
465: /**
466:  * Returns a limit statement in the correct format for the particular database.
467:  *
468:  * @param integer $limit Limit of results returned
469:  * @param integer $offset Offset from which to start results
470:  * @return string SQL limit/offset statement
471:  */
472:     function limit($limit, $offset = null) {
473:         if ($limit) {
474:             $rt = '';
475:             if (!strpos(strtolower($limit), 'top') || strpos(strtolower($limit), 'top') === 0) {
476:                 $rt = ' TOP';
477:             }
478:             $rt .= ' ' . $limit;
479:             if (is_int($offset) && $offset > 0) {
480:                 $rt .= ' OFFSET ' . $offset;
481:             }
482:             return $rt;
483:         }
484:         return null;
485:     }
486: /**
487:  * Converts database-layer column types to basic types
488:  *
489:  * @param string $real Real database-layer column type (i.e. "varchar(255)")
490:  * @return string Abstract column type (i.e. "string")
491:  */
492:     function column($real) {
493:         if (is_array($real)) {
494:             $col = $real['name'];
495: 
496:             if (isset($real['limit'])) {
497:                 $col .= '(' . $real['limit'] . ')';
498:             }
499:             return $col;
500:         }
501:         $col = str_replace(')', '', $real);
502:         $limit = null;
503:         if (strpos($col, '(') !== false) {
504:             list($col, $limit) = explode('(', $col);
505:         }
506: 
507:         if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
508:             return $col;
509:         }
510:         if ($col == 'bit') {
511:             return 'boolean';
512:         }
513:         if (strpos($col, 'int') !== false) {
514:             return 'integer';
515:         }
516:         if (strpos($col, 'char') !== false) {
517:             return 'string';
518:         }
519:         if (strpos($col, 'text') !== false) {
520:             return 'text';
521:         }
522:         if (strpos($col, 'binary') !== false || $col == 'image') {
523:             return 'binary';
524:         }
525:         if (in_array($col, array('float', 'real', 'decimal', 'numeric'))) {
526:             return 'float';
527:         }
528:         return 'text';
529:     }
530: /**
531:  * Enter description here...
532:  *
533:  * @param unknown_type $results
534:  */
535:     function resultSet(&$results) {
536:         $this->results =& $results;
537:         $this->map = array();
538:         $numFields = mssql_num_fields($results);
539:         $index = 0;
540:         $j = 0;
541: 
542:         while ($j < $numFields) {
543:             $column = mssql_field_name($results, $j);
544: 
545:             if (strpos($column, '__')) {
546:                 if (isset($this->__fieldMappings[$column]) && strpos($this->__fieldMappings[$column], '.')) {
547:                     $map = explode('.', $this->__fieldMappings[$column]);
548:                 } elseif (isset($this->__fieldMappings[$column])) {
549:                     $map = array(0, $this->__fieldMappings[$column]);
550:                 } else {
551:                     $map = array(0, $column);
552:                 }
553:                 $this->map[$index++] = $map;
554:             } else {
555:                 $this->map[$index++] = array(0, $column);
556:             }
557:             $j++;
558:         }
559:     }
560: /**
561:  * Builds final SQL statement
562:  *
563:  * @param string $type Query type
564:  * @param array $data Query data
565:  * @return string
566:  */
567:     function renderStatement($type, $data) {
568:         switch (strtolower($type)) {
569:             case 'select':
570:                 extract($data);
571:                 $fields = trim($fields);
572: 
573:                 if (strpos($limit, 'TOP') !== false && strpos($fields, 'DISTINCT ') === 0) {
574:                     $limit = 'DISTINCT ' . trim($limit);
575:                     $fields = substr($fields, 9);
576:                 }
577: 
578:                 if (preg_match('/offset\s+([0-9]+)/i', $limit, $offset)) {
579:                     $limit = preg_replace('/\s*offset.*$/i', '', $limit);
580:                     preg_match('/top\s+([0-9]+)/i', $limit, $limitVal);
581:                     $offset = intval($offset[1]) + intval($limitVal[1]);
582:                     $rOrder = $this->__switchSort($order);
583:                     list($order2, $rOrder) = array($this->__mapFields($order), $this->__mapFields($rOrder));
584:                     return "SELECT * FROM (SELECT {$limit} * FROM (SELECT TOP {$offset} {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order}) AS Set1 {$rOrder}) AS Set2 {$order2}";
585:                 } else {
586:                     return "SELECT {$limit} {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order}";
587:                 }
588:             break;
589:             case "schema":
590:                 extract($data);
591: 
592:                 foreach ($indexes as $i => $index) {
593:                     if (preg_match('/PRIMARY KEY/', $index)) {
594:                         unset($indexes[$i]);
595:                         break;
596:                     }
597:                 }
598: 
599:                 foreach (array('columns', 'indexes') as $var) {
600:                     if (is_array(${$var})) {
601:                         ${$var} = "\t" . implode(",\n\t", array_filter(${$var}));
602:                     }
603:                 }
604:                 return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
605:             break;
606:             default:
607:                 return parent::renderStatement($type, $data);
608:             break;
609:         }
610:     }
611: /**
612:  * Reverses the sort direction of ORDER statements to get paging offsets to work correctly
613:  *
614:  * @param string $order
615:  * @return string
616:  * @access private
617:  */
618:     function __switchSort($order) {
619:         $order = preg_replace('/\s+ASC/i', '__tmp_asc__', $order);
620:         $order = preg_replace('/\s+DESC/i', ' ASC', $order);
621:         return preg_replace('/__tmp_asc__/', ' DESC', $order);
622:     }
623: /**
624:  * Translates field names used for filtering and sorting to shortened names using the field map
625:  *
626:  * @param string $sql A snippet of SQL representing an ORDER or WHERE statement
627:  * @return string The value of $sql with field names replaced
628:  * @access private
629:  */
630:     function __mapFields($sql) {
631:         if (empty($sql) || empty($this->__fieldMappings)) {
632:             return $sql;
633:         }
634:         foreach ($this->__fieldMappings as $key => $val) {
635:             $sql = preg_replace('/' . preg_quote($val) . '/', $this->name($key), $sql);
636:             $sql = preg_replace('/' . preg_quote($this->name($val)) . '/', $this->name($key), $sql);
637:         }
638:         return $sql;
639:     }
640: /**
641:  * Returns an array of all result rows for a given SQL query.
642:  * Returns false if no rows matched.
643:  *
644:  * @param string $sql SQL statement
645:  * @param boolean $cache Enables returning/storing cached query results
646:  * @return array Array of resultset rows, or false if no rows matched
647:  */
648:     function read(&$model, $queryData = array(), $recursive = null) {
649:         $results = parent::read($model, $queryData, $recursive);
650:         $this->__fieldMappings = array();
651:         return $results;
652:     }
653: /**
654:  * Fetches the next row from the current result set
655:  *
656:  * @return unknown
657:  */
658:     function fetchResult() {
659:         if ($row = mssql_fetch_row($this->results)) {
660:             $resultRow = array();
661:             $i = 0;
662: 
663:             foreach ($row as $index => $field) {
664:                 list($table, $column) = $this->map[$index];
665:                 $resultRow[$table][$column] = $row[$index];
666:                 $i++;
667:             }
668:             return $resultRow;
669:         } else {
670:             return false;
671:         }
672:     }
673: /**
674:  * Inserts multiple values into a table
675:  *
676:  * @param string $table
677:  * @param string $fields
678:  * @param array $values
679:  * @access protected
680:  */
681:     function insertMulti($table, $fields, $values) {
682:         $primaryKey = $this->_getPrimaryKey($table);
683:         $hasPrimaryKey = $primaryKey != null && (
684:             (is_array($fields) && in_array($primaryKey, $fields)
685:             || (is_string($fields) && strpos($fields, $this->startQuote . $primaryKey . $this->endQuote) !== false))
686:         );
687: 
688:         if ($hasPrimaryKey) {
689:             $this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($table) . ' ON');
690:         }
691:         parent::insertMulti($table, $fields, $values);
692:         if ($hasPrimaryKey) {
693:             $this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($table) . ' OFF');
694:         }
695:     }
696: /**
697:  * Generate a database-native column schema string
698:  *
699:  * @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]),
700:  *   where options can be 'default', 'length', or 'key'.
701:  * @return string
702:  */
703:     function buildColumn($column) {
704:         $result = preg_replace('/(int|integer)\([0-9]+\)/i', '$1', parent::buildColumn($column));
705:         if (strpos($result, 'DEFAULT NULL') !== false) {
706:             $result = str_replace('DEFAULT NULL', 'NULL', $result);
707:         } else if (array_keys($column) == array('type', 'name')) {
708:             $result .= ' NULL';
709:         }
710:         return $result;
711:     }
712: /**
713:  * Format indexes for create table
714:  *
715:  * @param array $indexes
716:  * @param string $table
717:  * @return string
718:  */
719:     function buildIndex($indexes, $table = null) {
720:         $join = array();
721: 
722:         foreach ($indexes as $name => $value) {
723:             if ($name == 'PRIMARY') {
724:                 $join[] = 'PRIMARY KEY (' . $this->name($value['column']) . ')';
725:             } else if (isset($value['unique']) && $value['unique']) {
726:                 $out = "ALTER TABLE {$table} ADD CONSTRAINT {$name} UNIQUE";
727: 
728:                 if (is_array($value['column'])) {
729:                     $value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
730:                 } else {
731:                     $value['column'] = $this->name($value['column']);
732:                 }
733:                 $out .= "({$value['column']});";
734:                 $join[] = $out;
735:             }
736:         }
737:         return $join;
738:     }
739: /**
740:  * Makes sure it will return the primary key
741:  *
742:  * @param mixed $model
743:  * @access protected
744:  * @return string
745:  */
746:     function _getPrimaryKey($model) {
747:         if (is_object($model)) {
748:             $schema = $model->schema();
749:         } else {
750:             $schema = $this->describe($model);
751:         }
752: 
753:         foreach ($schema as $field => $props) {
754:             if (isset($props['key']) && $props['key'] == 'primary') {
755:                 return $field;
756:             }
757:         }
758:         return null;
759:     }
760: }
761: ?>
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs