summaryrefslogtreecommitdiffstats
path: root/modules/database/classes/driver/pdo/db.php
blob: 59705f718ba8cfaa88f67c33f86a7f088bdaf5b8 (plain)
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
<?php

/**
 * PDO Database implementation.
 * @package Database
 */
class DB_PDO_Driver extends DB{

    /**
     * Connection object
     * @var PDO 
     * @access public 
	 * @link http://php.net/manual/en/class.pdo.php
     */
	public $conn;
	
	/**
     * Type of the database, e.g. mysql, pgsql etc.
     * @var string 
     * @access public 
     */
	public $db_type;
	
    /**
     * Initializes database connection
     * 
     * @param string $config Name of the connection to initialize
     * @return void    
     * @access public  
     */
	public function __construct($config) {
		$this->conn = new PDO(
			Config::get("database.{$config}.connection"),
			Config::get("database.{$config}.user",''),
			Config::get("database.{$config}.password",'')
		);
		$this->db_type=strtolower(str_replace('PDO_', '', $this->conn->getAttribute(PDO::ATTR_DRIVER_NAME)));
	}

    /**
     * Builds a new Query implementation
     * 
     * @param string $type Query type. Available types: select,update,insert,delete,count
     * @return Query_PDO_Driver  Returns a PDO implementation of a Query.
     * @access public  
	 * @see Query_Database
     */
	public function build_query($type) {
		return new Query_PDO_Driver($this,$type);
	}

    /**
     * Gets the id of the last inserted row.
     * 
     * @return mixed Row id
     * @access public 
     */
	public function get_insert_id() {
		if ($this->db_type == 'pgsql')
			return $this->execute('SELECT lastval() as id')->current()->id;
		return $this->conn->lastInsertId();
	}

    /**
     * Executes a prepared statement query
     * 
     * @param string   $query  A prepared statement query
     * @param array     $params Parameters for the query
     * @return Result_PDO_Driver    PDO implementation of a database result
     * @access public    
     * @throws Exception If the query resulted in an error
	 * @see Database_Result
     */
	public function execute($query, $params = array()) {
		$cursor = $this->conn->prepare($query);
		if(!$cursor->execute($params))
			throw new Exception("Database error: ".implode(' ',$this->conn->errorInfo())." \n in query:\n{$query}");
		return new Result_PDO_Driver($cursor);
	}
}