Mokuji /www/libs/dibi/libs/DibiConnection.php

Language PHP Lines 739
MD5 Hash 3e23bf7de5cc0648f9ed1415e4e9570a
Repository https://github.com/bazo/Mokuji.git View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
<?php

/**
 * dibi - tiny'n'smart database abstraction layer
 * ----------------------------------------------
 *
 * @copyright  Copyright (c) 2005, 2010 David Grudl
 * @license    http://dibiphp.com/license  dibi license
 * @link       http://dibiphp.com
 * @package    dibi
 */



/**
 * dibi connection.
 *
 * @copyright  Copyright (c) 2005, 2010 David Grudl
 * @package    dibi
 */
class DibiConnection extends DibiObject
{
	/** @var array  Current connection configuration */
	private $config;

	/** @var IDibiDriver  Driver */
	private $driver;

	/** @var IDibiProfiler  Profiler */
	private $profiler;

	/** @var bool  Is connected? */
	private $connected = FALSE;



	/**
	 * Creates object and (optionally) connects to a database.
	 * @param  array|string|ArrayObject connection parameters
	 * @param  string       connection name
	 * @throws DibiException
	 */
	public function __construct($config, $name = NULL)
	{
		// DSN string
		if (is_string($config)) {
			parse_str($config, $config);

		} elseif ($config instanceof ArrayObject) {
			$config = (array) $config;

		} elseif (!is_array($config)) {
			throw new InvalidArgumentException('Configuration must be array, string or ArrayObject.');
		}

		self::alias($config, 'username', 'user');
		self::alias($config, 'password', 'pass');
		self::alias($config, 'host', 'hostname');

		if (!isset($config['driver'])) {
			$config['driver'] = dibi::$defaultDriver;
		}

		$driver = preg_replace('#[^a-z0-9_]#', '_', $config['driver']);
		$class = "Dibi" . $driver . "Driver";
		if (!class_exists($class, FALSE)) {
			include_once dirname(__FILE__) . "/../drivers/$driver.php";

			if (!class_exists($class, FALSE)) {
				throw new DibiException("Unable to create instance of dibi driver '$class'.");
			}
		}

		$config['name'] = $name;
		$this->config = $config;
		$this->driver = new $class;

		if (!empty($config['profiler'])) {
			$class = $config['profiler'];
			if (is_numeric($class) || is_bool($class)) {
				$class = 'DibiProfiler';
			}
			if (!class_exists($class)) {
				throw new DibiException("Unable to create instance of dibi profiler '$class'.");
			}
			$this->setProfiler(new $class);
		}

		if (!empty($config['substitutes'])) {
			foreach ($config['substitutes'] as $key => $value) {
				dibi::addSubst($key, $value);
			}
		}

		if (empty($config['lazy'])) {
			$this->connect();
		}
	}



	/**
	 * Automatically frees the resources allocated for this result set.
	 * @return void
	 */
	public function __destruct()
	{
		// disconnects and rolls back transaction - do not rely on auto-disconnect and rollback!
		$this->disconnect();
	}



	/**
	 * Connects to a database.
	 * @return void
	 */
	final protected function connect()
	{
		if (!$this->connected) {
			if ($this->profiler !== NULL) {
				$ticket = $this->profiler->before($this, IDibiProfiler::CONNECT);
			}
			$this->driver->connect($this->config);
			$this->connected = TRUE;
			if (isset($ticket)) {
				$this->profiler->after($ticket);
			}
		}
	}



	/**
	 * Disconnects from a database.
	 * @return void
	 */
	final public function disconnect()
	{
		if ($this->connected) {
			$this->driver->disconnect();
			$this->connected = FALSE;
		}
	}



	/**
	 * Returns TRUE when connection was established.
	 * @return bool
	 */
	final public function isConnected()
	{
		return $this->connected;
	}



	/**
	 * Returns configuration variable. If no $key is passed, returns the entire array.
	 * @see self::__construct
	 * @param  string
	 * @param  mixed  default value to use if key not found
	 * @return mixed
	 */
	final public function getConfig($key = NULL, $default = NULL)
	{
		if ($key === NULL) {
			return $this->config;

		} elseif (isset($this->config[$key])) {
			return $this->config[$key];

		} else {
			return $default;
		}
	}



	/**
	 * Apply configuration alias or default values.
	 * @param  array  connect configuration
	 * @param  string key
	 * @param  string alias key
	 * @return void
	 */
	public static function alias(&$config, $key, $alias=NULL)
	{
		if (isset($config[$key])) return;

		if ($alias !== NULL && isset($config[$alias])) {
			$config[$key] = $config[$alias];
			unset($config[$alias]);
		} else {
			$config[$key] = NULL;
		}
	}



	/**
	 * Returns the connection resource.
	 * @return IDibiDriver
	 */
	final public function getDriver()
	{
		return $this->driver;
	}



	/**
	 * Returns the connection resource.
	 * @return resource
	 * @deprecated use getDriver()->getResource()
	 */
	final public function getResource()
	{
		trigger_error('Deprecated: use getDriver()->getResource(...) instead.', E_USER_WARNING);
		return $this->driver->getResource();
	}



	/**
	 * Generates (translates) and executes SQL query.
	 * @param  array|mixed      one or more arguments
	 * @return DibiResult|int   result set object (if any)
	 * @throws DibiException
	 */
	final public function query($args)
	{
		$args = func_get_args();
		$this->connect();
		$translator = new DibiTranslator($this->driver);
		return $this->nativeQuery($translator->translate($args));
	}



	/**
	 * Generates and returns SQL query.
	 * @param  array|mixed      one or more arguments
	 * @return string
	 * @throws DibiException
	 */
	final public function sql($args)
	{
		$args = func_get_args();
		$this->connect();
		$translator = new DibiTranslator($this->driver);
		return $translator->translate($args);
	}



	/**
	 * Generates and prints SQL query.
	 * @param  array|mixed  one or more arguments
	 * @return bool
	 */
	final public function test($args)
	{
		$args = func_get_args();
		$this->connect();
		try {
			$translator = new DibiTranslator($this->driver);
			dibi::dump($translator->translate($args));
			return TRUE;

		} catch (DibiException $e) {
			dibi::dump($e->getSql());
			return FALSE;
		}
	}



	/**
	 * Generates (translates) and returns SQL query as DibiDataSource.
	 * @param  array|mixed      one or more arguments
	 * @return DibiDataSource
	 * @throws DibiException
	 */
	final public function dataSource($args)
	{
		$args = func_get_args();
		$this->connect();
		$translator = new DibiTranslator($this->driver);
		return new DibiDataSource($translator->translate($args), $this);
	}



	/**
	 * Executes the SQL query.
	 * @param  string           SQL statement.
	 * @return DibiResult|int   result set object (if any)
	 * @throws DibiException
	 */
	final public function nativeQuery($sql)
	{
		$this->connect();

		if ($this->profiler !== NULL) {
			$event = IDibiProfiler::QUERY;
			if (preg_match('#\s*(SELECT|UPDATE|INSERT|DELETE)#i', $sql, $matches)) {
				static $events = array(
					'SELECT' => IDibiProfiler::SELECT, 'UPDATE' => IDibiProfiler::UPDATE,
					'INSERT' => IDibiProfiler::INSERT, 'DELETE' => IDibiProfiler::DELETE,
				);
				$event = $events[strtoupper($matches[1])];
			}
			$ticket = $this->profiler->before($this, $event, $sql);
		}

		dibi::$sql = $sql;
		if ($res = $this->driver->query($sql)) { // intentionally =
			$res = new DibiResult($res, $this->config);
		} else {
			$res = $this->driver->getAffectedRows();
		}

		if (isset($ticket)) {
			$this->profiler->after($ticket, $res);
		}
		return $res;
	}



	/**
	 * Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
	 * @return int  number of rows
	 * @throws DibiException
	 */
	public function getAffectedRows()
	{
		$rows = $this->driver->getAffectedRows();
		if (!is_int($rows) || $rows < 0) throw new DibiException('Cannot retrieve number of affected rows.');
		return $rows;
	}



	/**
	 * Gets the number of affected rows. Alias for getAffectedRows().
	 * @return int  number of rows
	 * @throws DibiException
	 */
	public function affectedRows()
	{
		return $this->getAffectedRows();
	}



	/**
	 * Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
	 * @param  string     optional sequence name
	 * @return int
	 * @throws DibiException
	 */
	public function getInsertId($sequence = NULL)
	{
		$id = $this->driver->getInsertId($sequence);
		if ($id < 1) throw new DibiException('Cannot retrieve last generated ID.');
		return (int) $id;
	}



	/**
	 * Retrieves the ID generated for an AUTO_INCREMENT column. Alias for getInsertId().
	 * @param  string     optional sequence name
	 * @return int
	 * @throws DibiException
	 */
	public function insertId($sequence = NULL)
	{
		return $this->getInsertId($sequence);
	}



	/**
	 * Begins a transaction (if supported).
	 * @param  string  optional savepoint name
	 * @return void
	 */
	public function begin($savepoint = NULL)
	{
		$this->connect();
		if ($this->profiler !== NULL) {
			$ticket = $this->profiler->before($this, IDibiProfiler::BEGIN, $savepoint);
		}
		$this->driver->begin($savepoint);
		if (isset($ticket)) {
			$this->profiler->after($ticket);
		}
	}



	/**
	 * Commits statements in a transaction.
	 * @param  string  optional savepoint name
	 * @return void
	 */
	public function commit($savepoint = NULL)
	{
		if ($this->profiler !== NULL) {
			$ticket = $this->profiler->before($this, IDibiProfiler::COMMIT, $savepoint);
		}
		$this->driver->commit($savepoint);
		if (isset($ticket)) {
			$this->profiler->after($ticket);
		}
	}



	/**
	 * Rollback changes in a transaction.
	 * @param  string  optional savepoint name
	 * @return void
	 */
	public function rollback($savepoint = NULL)
	{
		if ($this->profiler !== NULL) {
			$ticket = $this->profiler->before($this, IDibiProfiler::ROLLBACK, $savepoint);
		}
		$this->driver->rollback($savepoint);
		if (isset($ticket)) {
			$this->profiler->after($ticket);
		}
	}



	/**
	 * Is in transaction?
	 * @return bool
	 */
	public function inTransaction()
	{
		$this->connect();
		return $this->driver->inTransaction();
	}



	/**
	 * Encodes data for use in a SQL statement.
	 * @param  string    unescaped string
	 * @param  string    type (dibi::TEXT, dibi::BOOL, ...)
	 * @return string    escaped and quoted string
	 * @deprecated
	 */
	public function escape($value, $type = dibi::TEXT)
	{
		trigger_error('Deprecated: use getDriver()->escape(...) instead.', E_USER_WARNING);
		$this->connect(); // MySQL & PDO require connection
		return $this->driver->escape($value, $type);
	}



	/**
	 * Decodes data from result set.
	 * @param  string    value
	 * @param  string    type (dibi::BINARY)
	 * @return string    decoded value
	 * @deprecated
	 */
	public function unescape($value, $type = dibi::BINARY)
	{
		trigger_error('Deprecated: use getDriver()->unescape(...) instead.', E_USER_WARNING);
		return $this->driver->unescape($value, $type);
	}



	/**
	 * Delimites identifier (table's or column's name, etc.).
	 * @param  string    identifier
	 * @return string    delimited identifier
	 * @deprecated
	 */
	public function delimite($value)
	{
		trigger_error('Deprecated: use getDriver()->escape(...) instead.', E_USER_WARNING);
		return $this->driver->escape($value, dibi::IDENTIFIER);
	}



	/**
	 * Injects LIMIT/OFFSET to the SQL query.
	 * @param  string &$sql  The SQL query that will be modified.
	 * @param  int $limit
	 * @param  int $offset
	 * @return void
	 * @deprecated
	 */
	public function applyLimit(&$sql, $limit, $offset)
	{
		trigger_error('Deprecated: use getDriver()->applyLimit(...) instead.', E_USER_WARNING);
		$this->driver->applyLimit($sql, $limit, $offset);
	}



	/********************* fluent SQL builders ****************d*g**/



	/**
	 * @return DibiFluent
	 */
	public function command()
	{
		return new DibiFluent($this);
	}



	/**
	 * @param  string    column name
	 * @return DibiFluent
	 */
	public function select($args)
	{
		$args = func_get_args();
		return $this->command()->__call('select', $args);
	}



	/**
	 * @param  string   table
	 * @param  array
	 * @return DibiFluent
	 */
	public function update($table, $args)
	{
		if (!(is_array($args) || $args instanceof ArrayObject)) {
			throw new InvalidArgumentException('Arguments must be array or ArrayObject.');
		}
		return $this->command()->update('%n', $table)->set($args);
	}



	/**
	 * @param  string   table
	 * @param  array
	 * @return DibiFluent
	 */
	public function insert($table, $args)
	{
		if ($args instanceof ArrayObject) {
			$args = (array) $args;
		} elseif (!is_array($args)) {
			throw new InvalidArgumentException('Arguments must be array or ArrayObject.');
		}
		return $this->command()->insert()
			->into('%n', $table, '(%n)', array_keys($args))->values('%l', $args);
	}



	/**
	 * @param  string   table
	 * @return DibiFluent
	 */
	public function delete($table)
	{
		return $this->command()->delete()->from('%n', $table);
	}



	/********************* profiler ****************d*g**/



	/**
	 * @param  IDibiProfiler
	 * @return DibiConnection  provides a fluent interface
	 */
	public function setProfiler(IDibiProfiler $profiler = NULL)
	{
		$this->profiler = $profiler;
		return $this;
	}



	/**
	 * @return IDibiProfiler
	 */
	public function getProfiler()
	{
		return $this->profiler;
	}



	/********************* shortcuts ****************d*g**/



	/**
	 * Executes SQL query and fetch result - shortcut for query() & fetch().
	 * @param  array|mixed    one or more arguments
	 * @return DibiRow
	 * @throws DibiException
	 */
	public function fetch($args)
	{
		$args = func_get_args();
		return $this->query($args)->fetch();
	}



	/**
	 * Executes SQL query and fetch results - shortcut for query() & fetchAll().
	 * @param  array|mixed    one or more arguments
	 * @return array of DibiRow
	 * @throws DibiException
	 */
	public function fetchAll($args)
	{
		$args = func_get_args();
		return $this->query($args)->fetchAll();
	}



	/**
	 * Executes SQL query and fetch first column - shortcut for query() & fetchSingle().
	 * @param  array|mixed    one or more arguments
	 * @return string
	 * @throws DibiException
	 */
	public function fetchSingle($args)
	{
		$args = func_get_args();
		return $this->query($args)->fetchSingle();
	}



	/**
	 * Executes SQL query and fetch pairs - shortcut for query() & fetchPairs().
	 * @param  array|mixed    one or more arguments
	 * @return string
	 * @throws DibiException
	 */
	public function fetchPairs($args)
	{
		$args = func_get_args();
		return $this->query($args)->fetchPairs();
	}



	/********************* misc ****************d*g**/



	/**
	 * Import SQL dump from file - extreme fast!
	 * @param  string  filename
	 * @return int  count of sql commands
	 */
	public function loadFile($file)
	{
		$this->connect();

		@set_time_limit(0); // intentionally @

		$handle = @fopen($file, 'r'); // intentionally @
		if (!$handle) {
			throw new FileNotFoundException("Cannot open file '$file'.");
		}

		$count = 0;
		$sql = '';
		while (!feof($handle)) {
			$s = fgets($handle);
			$sql .= $s;
			if (substr(rtrim($s), -1) === ';') {
				$this->driver->query($sql);
				$sql = '';
				$count++;
			}
		}
		fclose($handle);
		return $count;
	}



	/**
	 * Gets a information about the current database.
	 * @return DibiDatabaseInfo
	 */
	public function getDatabaseInfo()
	{
		$this->connect();
		return new DibiDatabaseInfo($this->driver, isset($this->config['database']) ? $this->config['database'] : NULL);
	}



	/**
	 * Prevents unserialization.
	 */
	public function __wakeup()
	{
		throw new NotSupportedException('You cannot serialize or unserialize ' . $this->getClass() . ' instances.');
	}



	/**
	 * Prevents serialization.
	 */
	public function __sleep()
	{
		throw new NotSupportedException('You cannot serialize or unserialize ' . $this->getClass() . ' instances.');
	}

}
Back to Top