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:  * IBM DB2 for DBO
  5:  *
  6:  * This file supports IBM DB2 and Cloudscape (aka Apache Derby,
  7:  * Sun Java DB) using the native ibm_db2 extension:
  8:  * http://pecl.php.net/package/ibm_db2
  9:  *
 10:  * PHP versions 4 and 5
 11:  *
 12:  * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 13:  * Copyright 2007, Cake Software Foundation, Inc.
 14:  *
 15:  * Licensed under The MIT License
 16:  * Redistributions of files must retain the above copyright notice.
 17:  *
 18:  * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 19:  * @link          http://cakephp.org CakePHP(tm) Project
 20:  * @package       cake
 21:  * @subpackage    cake.cake.libs.model.datasources.dbo
 22:  * @since         CakePHP(tm) v 0.10.5.1790
 23:  * @version       $Revision$
 24:  * @modifiedby    $LastChangedBy$
 25:  * @lastmodified  $Date$
 26:  * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 27:  */
 28: /**
 29:  * IBM DB2 for DBO
 30:  *
 31:  * This file supports IBM DB2 and Cloudscape (aka Apache Derby,
 32:  * Sun Java DB) using the native ibm_db2 extension:
 33:  * http://pecl.php.net/package/ibm_db2
 34:  *
 35:  * @package       cake
 36:  * @subpackage    cake.cake.libs.model.datasources.dbo
 37:  */
 38: class DboDb2 extends DboSource {
 39: /**
 40:  * A short description of the type of driver.
 41:  *
 42:  * @var string
 43:  */
 44:     var $description = 'IBM DB2 DBO Driver';
 45: /**
 46:  * The start quote in which database column and table names should be wrapped.
 47:  *
 48:  * @var string
 49:  */
 50:     var $startQuote = '';
 51: /**
 52:  * The end quote in which database column and table names should be wrapped.
 53:  *
 54:  * @var string
 55:  */
 56:     var $endQuote = '';
 57: /**
 58:  * An array of base configuration settings to be used if settings are not
 59:  * provided, i.e. default host, port, and connection method.
 60:  *
 61:  * @var array
 62:  */
 63:     var $_baseConfig = array(
 64:         'persistent'    => true,
 65:         'login'         => 'db2inst1',
 66:         'password'      => '',
 67:         'database'      => 'cake',
 68:         'schema'        => '',
 69:         'hostname'      => '127.0.0.1',
 70:         'port'          => '50001',
 71:         'encoding'      => 'UTF-8',
 72:         'cataloged'     => true,
 73:         'autocommit'    => true
 74:     );
 75: /**
 76:  * An array that maps Cake column types to database native column types.
 77:  * The mapped information can include a reference to a function that should
 78:  * be used to format the data, as well as a string that defines the
 79:  * formatting according to that function.
 80:  *
 81:  * @var array
 82:  */
 83:     var $columns = array(
 84:         'primary_key'   => array('name' => 'not null generated by default as identity (start with 1, increment by 1)'),
 85:         'string'        => array('name' => 'varchar', 'limit' => '255'),
 86:         'text'          => array('name' => 'clob'),
 87:         'integer'       => array('name' => 'integer', 'limit' => '10', 'formatter' => 'intval'),
 88:         'float'         => array('name' => 'double', 'formatter' => 'floatval'),
 89:         'datetime'      => array('name' => 'timestamp', 'format' => 'Y-m-d-H.i.s', 'formatter' => 'date'),
 90:         'timestamp'     => array('name' => 'timestamp', 'format' => 'Y-m-d-H.i.s', 'formatter' => 'date'),
 91:         'time'          => array('name' => 'time', 'format' => 'H.i.s', 'formatter' => 'date'),
 92:         'date'          => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
 93:         'binary'        => array('name' => 'blob'),
 94:         'boolean'       => array('name' => 'smallint', 'limit' => '1')
 95:     );
 96: /**
 97:  * A map for every result mapping tables to columns
 98:  *
 99:  * @var array result -> ( table -> column )
100:  */
101:     var $_resultMap = array();
102: /**
103:  * Connects to the database using options in the given configuration array.
104:  *
105:  * @return boolean True if the database could be connected, else false
106:  */
107:     function connect() {
108:         $config = $this->config;
109:         $connect = 'db2_connect';
110:         if ($config['persistent']) {
111:             $connect = 'db2_pconnect';
112:         }
113:         $this->connected = false;
114: 
115:         if ($config['cataloged']) {
116:             $this->connection = $connect($config['database'], $config['login'], $config['password']);
117:         } else {
118:             $connString = sprintf(
119:                 "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=%s;HOSTNAME=%s;PORT=%d;PROTOCOL=TCPIP;UID=%s;PWD=%s;",
120:                 $config['database'],
121:                 $config['hostname'],
122:                 $config['port'],
123:                 $config['login'],
124:                 $config['password']
125:             );
126:             $this->connection = db2_connect($connString, '', '');
127:         }
128: 
129:         if ($this->connection) {
130:             $this->connected = true;
131:         }
132: 
133:         if ($config['schema'] !== '') {
134:             $this->_execute('SET CURRENT SCHEMA = ' . $config['schema']);
135:         }
136:         return $this->connected;
137:     }
138: /**
139:  * Check that the DB2 extension is installed/loaded
140:  *
141:  * @return boolean
142:  **/
143:     function enabled() {
144:         return extension_loaded('ibm_db2');
145:     }
146: /**
147:  * Disconnects from database.
148:  *
149:  * @return boolean True if the database could be disconnected, else false
150:  */
151:     function disconnect() {
152:         @db2_free_result($this->results);
153:         $this->connected = !@db2_close($this->connection);
154:         return !$this->connected;
155:     }
156: /**
157:  * Executes given SQL statement.  We should use prepare / execute to allow the
158:  * database server to reuse its access plan and increase the efficiency
159:  * of your database access
160:  *
161:  * @param string $sql SQL statement
162:  * @return resource Result resource identifier
163:  * @access protected
164:  */
165:     function _execute($sql) {
166:         // get result from db
167:         $result = db2_exec($this->connection, $sql);
168: 
169:         if (!is_bool($result)) {
170:             // build table/column map for this result
171:             $map = array();
172:             $numFields = db2_num_fields($result);
173:             $index = 0;
174:             $j = 0;
175:             $offset = 0;
176: 
177:             while ($j < $numFields) {
178:                 $columnName = strtolower(db2_field_name($result, $j));
179:                 $tmp = strpos($sql, '.' . $columnName, $offset);
180:                 $tableName = substr($sql, $offset, ($tmp-$offset));
181:                 $tableName = substr($tableName, strrpos($tableName, ' ') + 1);
182:                 $map[$index++] = array($tableName, $columnName);
183:                 $j++;
184:                 $offset = strpos($sql, ' ', $tmp);
185:             }
186: 
187:             $this->_resultMap[$result] = $map;
188:         }
189: 
190:         return $result;
191:     }
192: /**
193:  * Returns an array of all the tables in the database.
194:  * Should call parent::listSources twice in the method:
195:  * once to see if the list is cached, and once to cache
196:  * the list if not.
197:  *
198:  * @return array Array of tablenames in the database
199:  */
200:     function listSources() {
201:         $cache = parent::listSources();
202: 
203:         if ($cache != null) {
204:             return $cache;
205:         }
206:         $result = db2_tables($this->connection);
207:         $tables = array();
208: 
209:         while (db2_fetch_row($result)) {
210:             $tables[] = strtolower(db2_result($result, 'TABLE_NAME'));
211:         }
212:         parent::listSources($tables);
213:         return $tables;
214:     }
215: /**
216:  * Returns an array of the fields in given table name.
217:  *
218:  * @param Model $model Model object to describe
219:  * @return array Fields in table. Keys are name and type
220:  */
221:     function &describe(&$model) {
222:         $cache = parent::describe($model);
223: 
224:         if ($cache != null) {
225:             return $cache;
226:         }
227:         $fields = array();
228:         $result = db2_columns($this->connection, '', '', strtoupper($this->fullTableName($model)));
229: 
230:         while (db2_fetch_row($result)) {
231:             $fields[strtolower(db2_result($result, 'COLUMN_NAME'))] = array(
232:                 'type' => $this->column(strtolower(db2_result($result, 'TYPE_NAME'))),
233:                 'null' => db2_result($result, 'NULLABLE'),
234:                 'default' => db2_result($result, 'COLUMN_DEF'),
235:                 'length' => db2_result($result, 'COLUMN_SIZE')
236:             );
237:         }
238:         $this->__cacheDescription($model->tablePrefix . $model->table, $fields);
239:         return $fields;
240:     }
241: /**
242:  * Returns a quoted name of $data for use in an SQL statement.
243:  *
244:  * @param string $data Name (table.field) to be prepared for use in an SQL statement
245:  * @return string Quoted for MySQL
246:  */
247:     function name($data) {
248:         return $data;
249:     }
250: /**
251:  * Returns a quoted and escaped string of $data for use in an SQL statement.
252:  *
253:  * @param string $data String to be prepared for use in an SQL statement
254:  * @param string $column The column into which this data will be inserted
255:  * @return string Quoted and escaped
256:  * @todo Add logic that formats/escapes data based on column type
257:  */
258:     function value($data, $column = null, $safe = false) {
259:         $parent = parent::value($data, $column, $safe);
260: 
261:         if ($parent != null) {
262:             return $parent;
263:         }
264: 
265:         if ($data === null) {
266:             return 'NULL';
267:         }
268: 
269:         if ($data === '') {
270:             return  "''";
271:         }
272: 
273:         switch ($column) {
274:             case 'boolean':
275:                 $data = $this->boolean((bool)$data);
276:             break;
277:             case 'integer':
278:                 $data = intval($data);
279:             break;
280:             default:
281:                 $data = str_replace("'", "''", $data);
282:             break;
283:         }
284: 
285:         if ($column == 'integer' || $column == 'float') {
286:             return $data;
287:         }
288:         return "'" . $data . "'";
289:     }
290: /**
291:  * Not sure about this one, MySQL needs it but does ODBC?  Safer just to leave it
292:  * Translates between PHP boolean values and MySQL (faked) boolean values
293:  *
294:  * @param mixed $data Value to be translated
295:  * @return mixed Converted boolean value
296:  */
297:     function boolean($data) {
298:         if ($data === true || $data === false) {
299:             if ($data === true) {
300:                 return 1;
301:             }
302:             return 0;
303:         } else {
304:             if (intval($data !== 0)) {
305:                 return true;
306:             }
307:             return false;
308:         }
309:     }
310: /**
311:  * Begins a transaction.  Returns true if the transaction was
312:  * started successfully, otherwise false.
313:  *
314:  * @param unknown_type $model
315:  * @return boolean True on success, false on fail
316:  * (i.e. if the database/model does not support transactions).
317:  */
318:     function begin(&$model) {
319:         if (parent::begin($model)) {
320:             if (db2_autocommit($this->connection, DB2_AUTOCOMMIT_OFF)) {
321:                 $this->_transactionStarted = true;
322:                 return true;
323:             }
324:         }
325:         return false;
326:     }
327: /**
328:  * Commit a transaction
329:  *
330:  * @param unknown_type $model
331:  * @return boolean True on success, false on fail
332:  * (i.e. if the database/model does not support transactions,
333:  * or a transaction has not started).
334:  */
335:     function commit(&$model) {
336:         if (parent::commit($model)) {
337:             if (db2_commit($this->connection)) {
338:                 $this->_transactionStarted = false;
339:                 db2_autocommit($this->connection, DB2_AUTOCOMMIT_ON);
340:                 return true;
341:             }
342:         }
343:         return false;
344:     }
345: /**
346:  * Rollback a transaction
347:  *
348:  * @param unknown_type $model
349:  * @return boolean True on success, false on fail
350:  * (i.e. if the database/model does not support transactions,
351:  * or a transaction has not started).
352:  */
353:     function rollback(&$model) {
354:         if (parent::rollback($model)) {
355:             $this->_transactionStarted = false;
356:             db2_autocommit($this->connection, DB2_AUTOCOMMIT_ON);
357:             return db2_rollback($this->connection);
358:         }
359:         return false;
360:     }
361: /**
362:  * Removes Identity (primary key) column from update data before returning to parent
363:  *
364:  * @param Model $model
365:  * @param array $fields
366:  * @param array $values
367:  * @return array
368:  */
369:     function update(&$model, $fields = array(), $values = array()) {
370:         foreach ($fields as $i => $field) {
371:             if ($field == $model->primaryKey) {
372:                 unset ($fields[$i]);
373:                 unset ($values[$i]);
374:                 break;
375:             }
376:         }
377:         return parent::update($model, $fields, $values);
378:     }
379: /**
380:  * Returns a formatted error message from previous database operation.
381:  * DB2 distinguishes between statement and connnection errors so we
382:  * must check for both.
383:  *
384:  * @return string Error message with error number
385:  */
386:     function lastError() {
387:         if (db2_stmt_error()) {
388:             return db2_stmt_error() . ': ' . db2_stmt_errormsg();
389:         } elseif (db2_conn_error()) {
390:             return db2_conn_error() . ': ' . db2_conn_errormsg();
391:         }
392:         return null;
393:     }
394: /**
395:  * Returns number of affected rows in previous database operation. If no previous operation exists,
396:  * this returns false.
397:  *
398:  * @return integer Number of affected rows
399:  */
400:     function lastAffected() {
401:         if ($this->_result) {
402:             return db2_num_rows($this->_result);
403:         }
404:         return null;
405:     }
406: /**
407:  * Returns number of rows in previous resultset. If no previous resultset exists,
408:  * this returns false.
409:  *
410:  * @return integer Number of rows in resultset
411:  */
412:     function lastNumRows() {
413:         if ($this->_result) {
414:             return db2_num_rows($this->_result);
415:         }
416:         return null;
417:     }
418: /**
419:  * Returns the ID generated from the previous INSERT operation.
420:  *
421:  * @param unknown_type $source
422:  * @return in
423:  */
424:     function lastInsertId($source = null) {
425:         $data = $this->fetchRow(sprintf('SELECT SYSIBM.IDENTITY_VAL_LOCAL() AS ID FROM %s FETCH FIRST ROW ONLY', $source));
426: 
427:         if ($data && isset($data[0]['id'])) {
428:             return $data[0]['id'];
429:         }
430:         return null;
431:     }
432: /**
433:  * Returns a limit statement in the correct format for the particular database.
434:  *
435:  * @param integer $limit Limit of results returned
436:  * @param integer $offset Offset from which to start results
437:  * @return string SQL limit/offset statement
438:  */
439:     function limit($limit, $offset = null) {
440:         if ($limit) {
441:             $rt = '';
442: 
443:             // If limit is not in the passed value already, add a limit clause.
444:             if (!strpos(strtolower($limit), 'limit') || strpos(strtolower($limit), 'limit') === 0) {
445:                 $rt = sprintf('FETCH FIRST %d ROWS ONLY', $limit);
446:             }
447: 
448:             // TODO: Implement paging with the offset.  This could get hairy.
449:             /*
450:             WITH WHOLE AS
451:             (SELECT FIRSTNME, MIDINIT, LASTNAME, SALARY,
452:             ROW_NUMBER() OVER (ORDER BY SALARY DESC) AS RN
453:             FROM EMPLOYEE)
454:             SELECT FIRSTNME, MIDINIT, LASTNAME, SALARY, RN
455:             FROM WHOLE
456:             WHERE RN BETWEEN 10 AND 15
457:             */
458: 
459:             /*
460:             if ($offset) {
461:                 $rt .= ' ' . $offset . ',';
462:             }
463: 
464:             $rt .= ' ' . $limit;
465:             */
466: 
467:             return $rt;
468:         }
469:         return null;
470:     }
471: /**
472:  * Converts database-layer column types to basic types
473:  *
474:  * @param string $real Real database-layer column type (i.e. "varchar(255)")
475:  * @return string Abstract column type (i.e. "string")
476:  */
477:     function column($real) {
478:         if (is_array($real)) {
479:             $col = $real['name'];
480: 
481:             if (isset($real['limit'])) {
482:                 $col .= '(' . $real['limit'] . ')';
483:             }
484:             return $col;
485:         }
486:         $col                = str_replace(')', '', $real);
487:         $limit              = null;
488:         if (strpos($col, '(') !== false) {
489:             list($col, $limit) = explode('(', $col);
490:         }
491: 
492:         if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
493:             return $col;
494:         }
495: 
496:         if ($col == 'smallint') {
497:             return 'boolean';
498:         }
499: 
500:         if (strpos($col, 'char') !== false) {
501:             return 'string';
502:         }
503: 
504:         if (strpos($col, 'clob') !== false) {
505:             return 'text';
506:         }
507: 
508:         if (strpos($col, 'blob') !== false || $col == 'image') {
509:             return 'binary';
510:         }
511: 
512:         if (in_array($col, array('double', 'real', 'decimal'))) {
513:             return 'float';
514:         }
515:         return 'text';
516:     }
517: /**
518:  * Maps a result set to an array so that returned fields are
519:  * grouped by model.  Any calculated fields, or fields that
520:  * do not correspond to a particular model belong under array
521:  * key 0.
522:  *
523:  * 1. Gets the column headers
524:  * {{{
525:  * Post.id
526:  * Post.title
527:  *
528:  *  [0] => Array
529:  *       (
530:  *           [0] => Post
531:  *           [1] => id
532:  *       )
533:  *
534:  *  [1] => Array
535:  *      (
536:  *          [0] => Post
537:  *          [1] => title
538:  *      )
539:  * }}}
540:  * @param unknown_type $results
541:  */
542:     function resultSet(&$results, $sql = null) {
543:         $this->results =& $results;
544:         $this->map = $this->_resultMap[$this->results];
545:     }
546: /**
547:  * Fetches the next row from the current result set
548:  * Maps the records in the $result property to the map
549:  * created in resultSet().
550:  *
551:  * 2. Gets the actual values.
552:  *
553:  * @return unknown
554:  */
555:     function fetchResult() {
556:         if ($row = db2_fetch_array($this->results)) {
557:             $resultRow = array();
558:             $i = 0;
559: 
560:             foreach ($row as $index => $field) {
561:                 $table = $this->map[$index][0];
562:                 $column = strtolower($this->map[$index][1]);
563:                 $resultRow[$table][$column] = $row[$index];
564:                 $i++;
565:             }
566:             return $resultRow;
567:         }
568:         return false;
569:     }
570: }
571: ?>
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