1 <?php
2 3 4 5 6 7
8 namespace Cross\DB\Connecter;
9
10 use Cross\Exception\CoreException;
11 use Exception;
12 use PDO;
13
14 15 16 17 18
19 class PgSQLConnecter extends BaseConnecter
20 {
21 22 23 24 25
26 private static $instance;
27
28 29 30 31 32
33 private static $options = array();
34
35 36 37 38 39 40 41 42 43
44 private function __construct($dsn, $user, $password, array $options = array())
45 {
46 try {
47 $this->pdo = new PDO($dsn, $user, $password, parent::getOptions(self::$options, $options));
48 } catch (Exception $e) {
49 throw new CoreException($e->getMessage());
50 }
51 }
52
53 54 55 56 57 58 59 60 61
62 static function getInstance($dsn, $user, $password, array $option = array())
63 {
64
65 $key = md5($dsn);
66 if (!isset(self::$instance[$key])) {
67 self::$instance [$key] = new self($dsn, $user, $password, $option);
68 }
69
70 return self::$instance [$key];
71 }
72
73 74 75 76 77
78 public function getPDO()
79 {
80 return $this->pdo;
81 }
82
83 84 85 86 87 88
89 public function getPK($table_name)
90 {
91 $table_info = $this->getMetaData($table_name, false);
92 foreach ($table_info as $info) {
93 if ($info['contype'] == 'p') {
94 return $info['column_name'];
95 }
96 }
97 return false;
98 }
99
100 101 102 103 104
105 public function lastInsertId()
106 {
107 $sql = "SELECT LASTVAL() as insert_id";
108 try {
109 $data = $this->pdo->query($sql)->fetch(PDO::FETCH_ASSOC);;
110 return $data['insert_id'];
111 } catch (Exception $e) {
112 return false;
113 }
114 }
115
116 117 118 119 120 121 122
123 function getMetaData($table, $fields_map = true)
124 {
125 $sql = "select a.column_name, a.is_nullable, a.column_default, p.contype from (
126 select i.column_name, i.is_nullable, i.column_default, i.ordinal_position, c.oid
127 from information_schema.columns i left join pg_class c on c.relname=i.table_name
128 where i.table_name='{$table}'
129 ) a left join pg_constraint p on p.conrelid=a.oid and a.ordinal_position = ANY (p.conkey)";
130
131 try {
132 $data = $this->pdo->query($sql);
133 if ($fields_map) {
134 $result = array();
135 $data->fetchAll(PDO::FETCH_FUNC, function ($column_name, $is_null, $column_default, $con_type) use (&$result) {
136 $auto_increment = preg_match("/nextval\((.*)\)/", $column_default);
137 $result[$column_name] = array(
138 'primary' => $con_type == 'p',
139 'auto_increment' => $auto_increment,
140 'default_value' => $auto_increment ? '' : strval($column_default),
141 'not_null' => $is_null == 'NO',
142 );
143 });
144 return $result;
145 } else {
146 return $data->fetchAll(PDO::FETCH_ASSOC);
147 }
148 } catch (Exception $e) {
149 return array();
150 }
151 }
152 }
153