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_firebird.php 7945 2008-12-19 02:16:01Z gwoo $ */
3
/**
4
 * Firebird/Interbase 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.dbo
21
 * @since         CakePHP(tm) v 1.2.0.5152
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
 * Short description for class.
29
 *
30
 * Long description for class
31
 *
32
 * @package       cake
33
 * @subpackage    cake.cake.libs.model.dbo
34
 */
35
class DboFirebird extends DboSource {
36
/**
37
 * Enter description here...
38
 *
39
 * @var unknown_type
40
 */
41
	var $description = "Firebird/Interbase DBO Driver";
42
/**
43
 * Saves the original table name
44
 *
45
 * @var unknown_type
46
 */
47
	var $modeltmp = array();
48
/**
49
 * Enter description here...
50
 *
51
 * @var unknown_type
52
 */
53
	var $startQuote = "\'";
54
/**
55
 * Enter description here...
56
 *
57
 * @var unknown_type
58
 */
59
	var $endQuote = "\'";
60
/**
61
 * Enter description here...
62
 *
63
 * @var unknown_type
64
 */
65
	var $alias = ' ';
66
/**
67
 * Enter description here...
68
 *
69
 * @var unknown_type
70
 */
71
	var $goofyLimit = true;
72
/**
73
 * Creates a map between field aliases and numeric indexes.
74
 *
75
 * @var array
76
 */
77
	var $__fieldMappings = array();
78
/**
79
 * Base configuration settings for Firebird driver
80
 *
81
 * @var array
82
 */
83
	var $_baseConfig = array(
84
		'persistent' => true,
85
		'host' => 'localhost',
86
		'login' => 'SYSDBA',
87
		'password' => 'masterkey',
88
		'database' => 'c:\\CAKE.FDB',
89
		'port' => '3050',
90
		'connect' => 'ibase_connect'
91
	);
92
/**
93
 * Firebird column definition
94
 *
95
 * @var array
96
 */
97
	var $columns = array(
98
		'primary_key' => array('name' => 'IDENTITY (1, 1) NOT NULL'),
99
		'string'	=> array('name'	 => 'varchar', 'limit' => '255'),
100
		'text'		=> array('name' => 'BLOB SUB_TYPE 1 SEGMENT SIZE 100 CHARACTER SET NONE'),
101
		'integer'	=> array('name' => 'integer'),
102
		'float'		=> array('name' => 'float', 'formatter' => 'floatval'),
103
		'datetime'	=> array('name' => 'timestamp', 'format'	=> 'd.m.Y H:i:s', 'formatter' => 'date'),
104
		'timestamp' => array('name'	=> 'timestamp', 'format'	 => 'd.m.Y H:i:s', 'formatter' => 'date'),
105
		'time'		=> array('name' => 'time', 'format'	   => 'H:i:s', 'formatter' => 'date'),
106
		'date'		=> array('name' => 'date', 'format'	   => 'd.m.Y', 'formatter' => 'date'),
107
		'binary'	=> array('name' => 'blob'),
108
		'boolean'	=> array('name' => 'smallint')
109
	);
110
/**
111
 * Firebird Transaction commands.
112
 *
113
 * @var array
114
 **/
115
	var $_commands = array(
116
		'begin'	   => 'SET TRANSACTION',
117
		'commit'   => 'COMMIT',
118
		'rollback' => 'ROLLBACK'
119
	);
120
/**
121
 * Connects to the database using options in the given configuration array.
122
 *
123
 * @return boolean True if the database could be connected, else false
124
 */
125
	function connect() {
126
		$config = $this->config;
127
		$connect = $config['connect'];
128
 
129
		$this->connected = false;
130
		$this->connection = $connect($config['host'] . ':' . $config['database'], $config['login'], $config['password']);
131
		$this->connected = true;
132
	}
133
/**
134
 * Disconnects from database.
135
 *
136
 * @return boolean True if the database could be disconnected, else false
137
 */
138
	function disconnect() {
139
		$this->connected = false;
140
		return @ibase_close($this->connection);
141
	}
142
/**
143
 * Executes given SQL statement.
144
 *
145
 * @param string $sql SQL statement
146
 * @return resource Result resource identifier
147
 * @access protected
148
 */
149
	function _execute($sql) {
150
		return @ibase_query($this->connection,	$sql);
151
	}
152
/**
153
 * Returns a row from given resultset as an array .
154
 *
155
 * @return array The fetched row as an array
156
 */
157
	function fetchRow() {
158
		if ($this->hasResult()) {
159
			$this->resultSet($this->_result);
160
			$resultRow = $this->fetchResult();
161
			return $resultRow;
162
		} else {
163
			return null;
164
		}
165
	}
166
/**
167
 * Returns an array of sources (tables) in the database.
168
 *
169
 * @return array Array of tablenames in the database
170
 */
171
	function listSources() {
172
		$cache = parent::listSources();
173
 
174
		if ($cache != null) {
175
			return $cache;
176
		}
177
		$sql = "select RDB" . "$" . "RELATION_NAME as name
178
				FROM RDB" ."$" . "RELATIONS
179
				Where RDB" . "$" . "SYSTEM_FLAG =0";
180
 
181
		$result = @ibase_query($this->connection,$sql);
182
		$tables = array();
183
		while ($row = ibase_fetch_row ($result)) {
184
			$tables[] = strtolower(trim($row[0]));
185
		}
186
		parent::listSources($tables);
187
		return $tables;
188
	}
189
/**
190
 * Returns an array of the fields in given table name.
191
 *
192
 * @param Model $model Model object to describe
193
 * @return array Fields in table. Keys are name and type
194
 */
195
	function describe(&$model) {
196
		$this->modeltmp[$model->table] = $model->alias;
197
		$cache = parent::describe($model);
198
 
199
		if ($cache != null) {
200
			return $cache;
201
		}
202
		$fields = false;
203
		$sql = "SELECT * FROM " . $this->fullTableName($model, false);
204
		$rs = ibase_query($sql);
205
		$coln = ibase_num_fields($rs);
206
		$fields = false;
207
 
208
		for ($i = 0; $i < $coln; $i++) {
209
			$col_info = ibase_field_info($rs, $i);
210
			$fields[strtolower($col_info['name'])] = array(
211
					'type' => $this->column($col_info['type']),
212
					'null' => '',
213
					'length' => $col_info['length']
214
				);
215
		}
216
		$this->__cacheDescription($this->fullTableName($model, false), $fields);
217
		return $fields;
218
	}
219
/**
220
 * Returns a quoted name of $data for use in an SQL statement.
221
 *
222
 * @param string $data Name (table.field) to be prepared for use in an SQL statement
223
 * @return string Quoted for Firebird
224
 */
225
	function name($data) {
226
		if ($data == '*') {
227
				return '*';
228
		}
229
		$pos = strpos($data, '"');
230
 
231
		if ($pos === false) {
232
			if (!strpos($data, ".")) {
233
				$data = '"' . strtoupper($data) . '"';
234
			} else {
235
				$build = explode('.', $data);
236
				$data = '"' . strtoupper($build[0]) . '"."' . strtoupper($build[1]) . '"';
237
			}
238
		}
239
		return $data;
240
	}
241
/**
242
 * Returns a quoted and escaped string of $data for use in an SQL statement.
243
 *
244
 * @param string $data String to be prepared for use in an SQL statement
245
 * @param string $column The column into which this data will be inserted
246
 * @param boolean $safe Whether or not numeric data should be handled automagically if no column data is provided
247
 * @return string Quoted and escaped data
248
 */
249
	function value($data, $column = null, $safe = false) {
250
		$parent = parent::value($data, $column, $safe);
251
 
252
		if ($parent != null) {
253
			return $parent;
254
		}
255
		if ($data === null) {
256
			return 'NULL';
257
		}
258
		if ($data === '') {
259
			return "''";
260
		}
261
 
262
		switch($column) {
263
			case 'boolean':
264
				$data = $this->boolean((bool)$data);
265
			break;
266
			default:
267
				if (get_magic_quotes_gpc()) {
268
					$data = stripslashes(str_replace("'", "''", $data));
269
				} else {
270
					$data = str_replace("'", "''", $data);
271
				}
272
			break;
273
		}
274
		return "'" . $data . "'";
275
	}
276
/**
277
 * Removes Identity (primary key) column from update data before returning to parent
278
 *
279
 * @param Model $model
280
 * @param array $fields
281
 * @param array $values
282
 * @return array
283
 */
284
	function update(&$model, $fields = array(), $values = array()) {
285
		foreach ($fields as $i => $field) {
286
			if ($field == $model->primaryKey) {
287
				unset ($fields[$i]);
288
				unset ($values[$i]);
289
				break;
290
			}
291
		}
292
		return parent::update($model, $fields, $values);
293
	}
294
/**
295
 * Returns a formatted error message from previous database operation.
296
 *
297
 * @return string Error message with error number
298
 */
299
	function lastError() {
300
		$error = ibase_errmsg();
301
 
302
		if ($error !== false) {
303
			return $error;
304
		}
305
		return null;
306
	}
307
/**
308
 * Returns number of affected rows in previous database operation. If no previous operation exists,
309
 * this returns false.
310
 *
311
 * @return integer Number of affected rows
312
 */
313
	function lastAffected() {
314
		if ($this->_result) {
315
			return ibase_affected_rows($this->connection);
316
		}
317
		return null;
318
	}
319
/**
320
 * Returns number of rows in previous resultset. If no previous resultset exists,
321
 * this returns false.
322
 *
323
 * @return integer Number of rows in resultset
324
 */
325
	function lastNumRows() {
326
		return $this->_result? /*ibase_affected_rows($this->_result)*/ 1: false;
327
	}
328
/**
329
 * Returns the ID generated from the previous INSERT operation.
330
 *
331
 * @param unknown_type $source
332
 * @return in
333
 */
334
	function lastInsertId($source = null, $field = 'id') {
335
		$query = "SELECT RDB\$TRIGGER_SOURCE
336
		FROM RDB\$TRIGGERS WHERE RDB\$RELATION_NAME = '".  strtoupper($source) .  "' AND
337
		RDB\$SYSTEM_FLAG IS NULL AND  RDB\$TRIGGER_TYPE = 1 ";
338
 
339
		$result = @ibase_query($this->connection,$query);
340
		$generator = "";
341
 
342
		while ($row = ibase_fetch_row($result, IBASE_TEXT)) {
343
			if (strpos($row[0], "NEW." . strtoupper($field))) {
344
				$pos = strpos($row[0], "GEN_ID(");
345
 
346
				if ($pos > 0) {
347
					$pos2 = strpos($row[0],",",$pos + 7);
348
 
349
					if ($pos2 > 0) {
350
						$generator = substr($row[0], $pos +7, $pos2 - $pos- 7);
351
					}
352
				}
353
				break;
354
			}
355
		}
356
 
357
		if (!empty($generator)) {
358
			$sql = "SELECT GEN_ID(". $generator	 . ",0) AS maxi FROM RDB" . "$" . "DATABASE";
359
			$res = $this->rawQuery($sql);
360
			$data = $this->fetchRow($res);
361
			return $data['maxi'];
362
		} else {
363
			return false;
364
		}
365
	}
366
/**
367
 * Returns a limit statement in the correct format for the particular database.
368
 *
369
 * @param integer $limit Limit of results returned
370
 * @param integer $offset Offset from which to start results
371
 * @return string SQL limit/offset statement
372
 */
373
	function limit($limit, $offset = null) {
374
		if ($limit) {
375
			$rt = '';
376
 
377
			if (!strpos(strtolower($limit), 'top') || strpos(strtolower($limit), 'top') === 0) {
378
				$rt = ' FIRST';
379
			}
380
			$rt .= ' ' . $limit;
381
 
382
			if (is_int($offset) && $offset > 0) {
383
				$rt .= ' SKIP ' . $offset;
384
			}
385
			return $rt;
386
		}
387
		return null;
388
	}
389
/**
390
 * Converts database-layer column types to basic types
391
 *
392
 * @param string $real Real database-layer column type (i.e. "varchar(255)")
393
 * @return string Abstract column type (i.e. "string")
394
 */
395
	function column($real) {
396
		if (is_array($real)) {
397
			$col = $real['name'];
398
 
399
			if (isset($real['limit'])) {
400
				$col .= '(' . $real['limit'] . ')';
401
			}
402
			return $col;
403
		}
404
 
405
		$col = str_replace(')', '', $real);
406
		$limit = null;
407
		if (strpos($col, '(') !== false) {
408
			list($col, $limit) = explode('(', $col);
409
		}
410
 
411
		if (in_array($col, array('DATE', 'TIME'))) {
412
			return strtolower($col);
413
		}
414
		if ($col == 'TIMESTAMP') {
415
			return 'datetime';
416
		}
417
		if ($col == 'SMALLINT') {
418
			return 'boolean';
419
		}
420
		if (strpos($col, 'int') !== false || $col == 'numeric' || $col == 'INTEGER') {
421
			return 'integer';
422
		}
423
		if (strpos($col, 'char') !== false) {
424
			return 'string';
425
		}
426
		if (strpos($col, 'text') !== false) {
427
			return 'text';
428
		}
429
		if (strpos($col, 'VARCHAR') !== false) {
430
			return 'string';
431
		}
432
		if (strpos($col, 'BLOB') !== false) {
433
			return 'text';
434
		}
435
		if (in_array($col, array('FLOAT', 'NUMERIC', 'DECIMAL'))) {
436
			return 'float';
437
		}
438
		return 'text';
439
	}
440
/**
441
 * Enter description here...
442
 *
443
 * @param unknown_type $results
444
 */
445
	function resultSet(&$results) {
446
		$this->results =& $results;
447
		$this->map = array();
448
		$num_fields = ibase_num_fields($results);
449
		$index = 0;
450
		$j = 0;
451
 
452
		while ($j < $num_fields) {
453
			$column = ibase_field_info($results, $j);
454
			if (!empty($column[2])) {
455
				$this->map[$index++] = array(ucfirst(strtolower($this->modeltmp[strtolower($column[2])])), strtolower($column[1]));
456
			} else {
457
				$this->map[$index++] = array(0, strtolower($column[1]));
458
			}
459
			$j++;
460
		}
461
	}
462
/**
463
 * Builds final SQL statement
464
 *
465
 * @param string $type Query type
466
 * @param array $data Query data
467
 * @return string
468
 */
469
	function renderStatement($type, $data) {
470
		extract($data);
471
 
472
		if (strtolower($type) == 'select') {
473
			if (preg_match('/offset\s+([0-9]+)/i', $limit, $offset)) {
474
				$limit = preg_replace('/\s*offset.*$/i', '', $limit);
475
				preg_match('/top\s+([0-9]+)/i', $limit, $limitVal);
476
				$offset = intval($offset[1]) + intval($limitVal[1]);
477
				$rOrder = $this->__switchSort($order);
478
				list($order2, $rOrder) = array($this->__mapFields($order), $this->__mapFields($rOrder));
479
				return "SELECT * FROM (SELECT {$limit} * FROM (SELECT TOP {$offset} {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$order}) AS Set1 {$rOrder}) AS Set2 {$order2}";
480
			} else {
481
				return "SELECT {$limit} {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$order}";
482
			}
483
		} else {
484
			return parent::renderStatement($type, $data);
485
		}
486
	}
487
/**
488
 * Fetches the next row from the current result set
489
 *
490
 * @return unknown
491
 */
492
	function fetchResult() {
493
		if ($row = ibase_fetch_row($this->results, IBASE_TEXT)) {
494
			$resultRow = array();
495
			$i = 0;
496
 
497
			foreach ($row as $index => $field) {
498
				list($table, $column) = $this->map[$index];
499
 
500
				if (trim($table) == "") {
501
					$resultRow[0][$column] = $row[$index];
502
				} else {
503
					$resultRow[$table][$column] = $row[$index];
504
					$i++;
505
				}
506
			}
507
			return $resultRow;
508
		} else {
509
			return false;
510
		}
511
	}
512
}
513
?>