Subversion-Projekte lars-tiefland.cakephp

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 1
<?php
2
/* SVN FILE: $Id: dbo_adodb.php 7945 2008-12-19 02:16:01Z gwoo $ */
3
/**
4
 * AdoDB layer for DBO.
5
 *
6
 * Long description for file
7
 *
8
 * PHP versions 4 and 5
9
 *
10
 * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
11
 * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
12
 *
13
 * Licensed under The MIT License
14
 * Redistributions of files must retain the above copyright notice.
15
 *
16
 * @filesource
17
 * @copyright     Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
18
 * @link          http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
19
 * @package       cake
20
 * @subpackage    cake.cake.libs.model.datasources.dbo
21
 * @since         CakePHP(tm) v 0.2.9
22
 * @version       $Revision: 7945 $
23
 * @modifiedby    $LastChangedBy: gwoo $
24
 * @lastmodified  $Date: 2008-12-18 18:16:01 -0800 (Thu, 18 Dec 2008) $
25
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
26
 */
27
/**
28
 * Include AdoDB files.
29
 */
30
App::import('Vendor', 'NewADOConnection', array('file' => 'adodb' . DS . 'adodb.inc.php'));
31
/**
32
 * AdoDB DBO implementation.
33
 *
34
 * Database abstraction implementation for the AdoDB library.
35
 *
36
 * @package       cake
37
 * @subpackage    cake.cake.libs.model.datasources.dbo
38
 */
39
class DboAdodb extends DboSource {
40
/**
41
 * Enter description here...
42
 *
43
 * @var string
44
 */
45
	var $description = "ADOdb DBO Driver";
46
/**
47
 * ADOConnection object with which we connect.
48
 *
49
 * @var ADOConnection The connection object.
50
 * @access private
51
 */
52
	var $_adodb = null;
53
/**
54
 * Array translating ADOdb column MetaTypes to cake-supported metatypes
55
 *
56
 * @var array
57
 * @access private
58
 */
59
	var $_adodbColumnTypes = array(
60
		'string' => 'C',
61
		'text' => 'X',
62
		'date' => 'D',
63
		'timestamp' => 'T',
64
		'time' => 'T',
65
		'datetime' => 'T',
66
		'boolean' => 'L',
67
		'float' => 'N',
68
		'integer' => 'I',
69
		'binary' => 'R',
70
	);
71
/**
72
 * ADOdb column definition
73
 *
74
 * @var array
75
 */
76
	var $columns = array(
77
		'primary_key' => array('name' => 'R', 'limit' => 11),
78
		'string' => array('name' => 'C', 'limit' => '255'),
79
		'text' => array('name' => 'X'),
80
		'integer' => array('name' => 'I', 'limit' => '11', 'formatter' => 'intval'),
81
		'float' => array('name' => 'N', 'formatter' => 'floatval'),
82
		'timestamp' => array('name' => 'T', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
83
		'time' => array('name' => 'T',  'format' => 'H:i:s', 'formatter' => 'date'),
84
		'datetime' => array('name' => 'T', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
85
		'date' => array('name' => 'D', 'format' => 'Y-m-d', 'formatter' => 'date'),
86
		'binary' => array('name' => 'B'),
87
		'boolean' => array('name' => 'L', 'limit' => '1')
88
	);
89
/**
90
 * Connects to the database using options in the given configuration array.
91
 *
92
 * @param array $config Configuration array for connecting
93
 */
94
	function connect() {
95
		$config = $this->config;
96
		$persistent = strrpos($config['connect'], '|p');
97
 
98
		if ($persistent === false) {
99
			$adodb_driver = $config['connect'];
100
			$connect = 'Connect';
101
		} else {
102
			$adodb_driver = substr($config['connect'], 0, $persistent);
103
			$connect = 'PConnect';
104
		}
105
 
106
		$this->_adodb = NewADOConnection($adodb_driver);
107
 
108
		$this->_adodbDataDict = NewDataDictionary($this->_adodb, $adodb_driver);
109
 
110
		$this->startQuote = $this->_adodb->nameQuote;
111
		$this->endQuote = $this->_adodb->nameQuote;
112
 
113
		$this->connected = $this->_adodb->$connect($config['host'], $config['login'], $config['password'], $config['database']);
114
		$this->_adodbMetatyper = &$this->_adodb->execute('Select 1');
115
		return $this->connected;
116
	}
117
/**
118
 * Disconnects from database.
119
 *
120
 * @return boolean True if the database could be disconnected, else false
121
 */
122
	function disconnect() {
123
		return $this->_adodb->Close();
124
	}
125
/**
126
 * Executes given SQL statement.
127
 *
128
 * @param string $sql SQL statement
129
 * @return resource Result resource identifier
130
 */
131
	function _execute($sql) {
132
		global $ADODB_FETCH_MODE;
133
		$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
134
		return $this->_adodb->execute($sql);
135
	}
136
/**
137
 * Returns a row from current resultset as an array .
138
 *
139
 * @return array The fetched row as an array
140
 */
141
	function fetchRow($sql = null) {
142
		if (!empty($sql) && is_string($sql) && strlen($sql) > 5) {
143
			if (!$this->execute($sql)) {
144
				return null;
145
			}
146
		}
147
 
148
		if (!$this->hasResult()) {
149
			return null;
150
		} else {
151
			$resultRow = $this->_result->FetchRow();
152
			$this->resultSet($resultRow);
153
			return $this->fetchResult();
154
		}
155
	}
156
/**
157
 * Begin a transaction
158
 *
159
 * @param unknown_type $model
160
 * @return boolean True on success, false on fail
161
 * (i.e. if the database/model does not support transactions).
162
 */
163
	function begin(&$model) {
164
		if (parent::begin($model)) {
165
			if ($this->_adodb->BeginTrans()) {
166
				$this->_transactionStarted = true;
167
				return true;
168
			}
169
		}
170
		return false;
171
	}
172
/**
173
 * Commit a transaction
174
 *
175
 * @param unknown_type $model
176
 * @return boolean True on success, false on fail
177
 * (i.e. if the database/model does not support transactions,
178
 * or a transaction has not started).
179
 */
180
	function commit(&$model) {
181
		if (parent::commit($model)) {
182
			$this->_transactionStarted = false;
183
			return $this->_adodb->CommitTrans();
184
		}
185
		return false;
186
	}
187
/**
188
 * Rollback a transaction
189
 *
190
 * @param unknown_type $model
191
 * @return boolean True on success, false on fail
192
 * (i.e. if the database/model does not support transactions,
193
 * or a transaction has not started).
194
 */
195
	function rollback(&$model) {
196
		if (parent::rollback($model)) {
197
			return $this->_adodb->RollbackTrans();
198
		}
199
		return false;
200
	}
201
/**
202
 * Returns an array of tables in the database. If there are no tables, an error is raised and the application exits.
203
 *
204
 * @return array Array of tablenames in the database
205
 */
206
	function listSources() {
207
		$tables = $this->_adodb->MetaTables('TABLES');
208
 
209
		if (!sizeof($tables) > 0) {
210
			trigger_error(ERROR_NO_TABLE_LIST, E_USER_NOTICE);
211
			exit;
212
		}
213
		return $tables;
214
	}
215
/**
216
 * Returns an array of the fields in the table used by the given model.
217
 *
218
 * @param AppModel $model Model object
219
 * @return array Fields in table. Keys are name and type
220
 */
221
	function describe(&$model) {
222
		$cache = parent::describe($model);
223
		if ($cache != null) {
224
			return $cache;
225
		}
226
 
227
		$fields = false;
228
		$cols = $this->_adodb->MetaColumns($this->fullTableName($model, false));
229
 
230
		foreach ($cols as $column) {
231
			$fields[$column->name] = array(
232
										'type' => $this->column($column->type),
233
										'null' => !$column->not_null,
234
										'length' => $column->max_length,
235
									);
236
			if ($column->has_default) {
237
				$fields[$column->name]['default'] = $column->default_value;
238
			}
239
			if ($column->primary_key == 1) {
240
				$fields[$column->name]['key'] = 'primary';
241
			}
242
		}
243
 
244
		$this->__cacheDescription($this->fullTableName($model, false), $fields);
245
		return $fields;
246
	}
247
/**
248
 * Returns a formatted error message from previous database operation.
249
 *
250
 * @return string Error message
251
 */
252
	function lastError() {
253
		return $this->_adodb->ErrorMsg();
254
	}
255
/**
256
 * Returns number of affected rows in previous database operation, or false if no previous operation exists.
257
 *
258
 * @return integer Number of affected rows
259
 */
260
	function lastAffected() {
261
		return $this->_adodb->Affected_Rows();
262
	}
263
/**
264
 * Returns number of rows in previous resultset, or false if no previous resultset exists.
265
 *
266
 * @return integer Number of rows in resultset
267
 */
268
	function lastNumRows() {
269
		return $this->_result ? $this->_result->RecordCount() : false;
270
	}
271
/**
272
 * Returns the ID generated from the previous INSERT operation.
273
 *
274
 * @return int
275
 *
276
 * @Returns the last autonumbering ID inserted. Returns false if function not supported.
277
 */
278
	function lastInsertId() {
279
		return $this->_adodb->Insert_ID();
280
	}
281
/**
282
 * Returns a LIMIT statement in the correct format for the particular database.
283
 *
284
 * @param integer $limit Limit of results returned
285
 * @param integer $offset Offset from which to start results
286
 * @return string SQL limit/offset statement
287
 * @todo Please change output string to whatever select your database accepts. adodb doesn't allow us to get the correct limit string out of it.
288
 */
289
	function limit($limit, $offset = null) {
290
		if ($limit) {
291
			$rt = '';
292
			if (!strpos(strtolower($limit), 'limit') || strpos(strtolower($limit), 'limit') === 0) {
293
				$rt = ' LIMIT';
294
			}
295
 
296
			if ($offset) {
297
				$rt .= ' ' . $offset . ',';
298
			}
299
 
300
			$rt .= ' ' . $limit;
301
			return $rt;
302
		}
303
		return null;
304
		// please change to whatever select your database accepts
305
		// adodb doesn't allow us to get the correct limit string out of it
306
	}
307
/**
308
 * Converts database-layer column types to basic types
309
 *
310
 * @param string $real Real database-layer column type (i.e. "varchar(255)")
311
 * @return string Abstract column type (i.e. "string")
312
 */
313
	function column($real) {
314
		$metaTypes = array_flip($this->_adodbColumnTypes);
315
 
316
		$interpreted_type = $this->_adodbMetatyper->MetaType($real);
317
 
318
		if (!isset($metaTypes[$interpreted_type])) {
319
			return 'text';
320
		}
321
		return $metaTypes[$interpreted_type];
322
	}
323
/**
324
 * Returns a quoted and escaped string of $data for use in an SQL statement.
325
 *
326
 * @param string $data String to be prepared for use in an SQL statement
327
 * @param string $column_type The type of the column into which this data will be inserted
328
 * @param boolean $safe Whether or not numeric data should be handled automagically if no column data is provided
329
 * @return string Quoted and escaped data
330
 */
331
	function value($data, $column = null, $safe = false) {
332
		$parent = parent::value($data, $column, $safe);
333
		if ($parent != null) {
334
			return $parent;
335
		}
336
 
337
		if ($data === null) {
338
			return 'NULL';
339
		}
340
 
341
		if ($data === '') {
342
			return "''";
343
		}
344
		return $this->_adodb->qstr($data);
345
	}
346
 
347
/**
348
 * Generates the fields list of an SQL query.
349
 *
350
 * @param Model $model
351
 * @param string $alias Alias tablename
352
 * @param mixed $fields
353
 * @return array
354
 */
355
	function fields(&$model, $alias = null, $fields = array(), $quote = true) {
356
		if (empty($alias)) {
357
			$alias = $model->alias;
358
		}
359
		$fields = parent::fields($model, $alias, $fields, false);
360
 
361
		if (!$quote) {
362
			return $fields;
363
		}
364
		$count = count($fields);
365
 
366
		if ($count >= 1 && $fields[0] != '*' && strpos($fields[0], 'COUNT(*)') === false) {
367
			for ($i = 0; $i < $count; $i++) {
368
				if (!preg_match('/^.+\\(.*\\)/', $fields[$i]) && !preg_match('/\s+AS\s+/', $fields[$i])) {
369
					$prepend = '';
370
					if (strpos($fields[$i], 'DISTINCT') !== false) {
371
						$prepend = 'DISTINCT ';
372
						$fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
373
					}
374
 
375
					if (strrpos($fields[$i], '.') === false) {
376
						$fields[$i] = $prepend . $this->name($alias) . '.' . $this->name($fields[$i]) . ' AS ' . $this->name($alias . '__' . $fields[$i]);
377
					} else {
378
						$build = explode('.', $fields[$i]);
379
						$fields[$i] = $prepend . $this->name($build[0]) . '.' . $this->name($build[1]) . ' AS ' . $this->name($build[0] . '__' . $build[1]);
380
					}
381
				}
382
			}
383
		}
384
		return $fields;
385
	}
386
/**
387
 * Build ResultSets and map data
388
 *
389
 * @param array $results
390
 */
391
	function resultSet(&$results) {
392
		$num_fields = count($results);
393
		$fields = array_keys($results);
394
		$this->results =& $results;
395
		$this->map = array();
396
		$index = 0;
397
		$j = 0;
398
 
399
		while ($j < $num_fields) {
400
			$columnName = $fields[$j];
401
 
402
			if (strpos($columnName, '__')) {
403
				$parts = explode('__', $columnName);
404
				$this->map[$index++] = array($parts[0], $parts[1]);
405
			} else {
406
				$this->map[$index++] = array(0, $columnName);
407
			}
408
			$j++;
409
		}
410
	}
411
/**
412
 * Fetches the next row from the current result set
413
 *
414
 * @return unknown
415
 */
416
	function fetchResult() {
417
		if (!empty($this->results)) {
418
			$row = $this->results;
419
			$this->results = null;
420
		} else {
421
			$row = $this->_result->FetchRow();
422
		}
423
 
424
		if (empty($row)) {
425
			return false;
426
		}
427
 
428
		$resultRow = array();
429
		$fields = array_keys($row);
430
		$count = count($fields);
431
		$i = 0;
432
		for ($i = 0; $i < $count; $i++) { //$row as $index => $field) {
433
			list($table, $column) = $this->map[$i];
434
			$resultRow[$table][$column] = $row[$fields[$i]];
435
		}
436
		return $resultRow;
437
	}
438
/**
439
 * Generate a database-native column schema string
440
 *
441
 * @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]),
442
 *                      where options can be 'default', 'length', or 'key'.
443
 * @return string
444
 */
445
	function buildColumn($column) {
446
		$name = $type = null;
447
		extract(array_merge(array('null' => true), $column));
448
 
449
		if (empty($name) || empty($type)) {
450
			trigger_error('Column name or type not defined in schema', E_USER_WARNING);
451
			return null;
452
		}
453
 
454
		//$metaTypes = array_flip($this->_adodbColumnTypes);
455
		if (!isset($this->_adodbColumnTypes[$type])) {
456
			trigger_error("Column type {$type} does not exist", E_USER_WARNING);
457
			return null;
458
		}
459
		$metaType = $this->_adodbColumnTypes[$type];
460
		$concreteType = $this->_adodbDataDict->ActualType($metaType);
461
		$real = $this->columns[$type];
462
 
463
		//UUIDs are broken so fix them.
464
		if ($type == 'string' && isset($real['length']) && $real['length'] == 36) {
465
			$concreteType = 'CHAR';
466
		}
467
 
468
		$out = $this->name($name) . ' ' . $concreteType;
469
 
470
		if (isset($real['limit']) || isset($real['length']) || isset($column['limit']) || isset($column['length'])) {
471
			if (isset($column['length'])) {
472
				$length = $column['length'];
473
			} elseif (isset($column['limit'])) {
474
				$length = $column['limit'];
475
			} elseif (isset($real['length'])) {
476
				$length = $real['length'];
477
			} else {
478
				$length = $real['limit'];
479
			}
480
			$out .= '(' . $length . ')';
481
		}
482
		$_notNull = $_default = $_autoInc = $_constraint = $_unsigned = false;
483
 
484
		if (isset($column['key']) && $column['key'] == 'primary' && $type == 'integer') {
485
			$_constraint = '';
486
			$_autoInc = true;
487
		} elseif (isset($column['key']) && $column['key'] == 'primary') {
488
			$_notNull = '';
489
		} elseif (isset($column['default']) && isset($column['null']) && $column['null'] == false) {
490
			$_notNull = true;
491
			$_default = $column['default'];
492
		} elseif ( isset($column['null']) && $column['null'] == true) {
493
			$_notNull = false;
494
			$_default = 'NULL';
495
		}
496
		if (isset($column['default']) && $_default == false) {
497
			$_default = $this->value($column['default']);
498
		}
499
		if (isset($column['null']) && $column['null'] == false) {
500
			$_notNull = true;
501
		}
502
		//use concrete instance of DataDict to make the suffixes for us.
503
		$out .=	$this->_adodbDataDict->_CreateSuffix($out, $metaType, $_notNull, $_default, $_autoInc, $_constraint, $_unsigned);
504
		return $out;
505
 
506
	}
507
/**
508
 * Checks if the result is valid
509
 *
510
 * @return boolean True if the result is valid, else false
511
 */
512
	function hasResult() {
513
		return is_object($this->_result) && !$this->_result->EOF;
514
	}
515
}
516
?>