1 <?php
2 3 4 5 6 7
8
9 namespace Cross\DB\Connecter;
10
11 use Cross\Exception\CoreException;
12 use Exception;
13 use PDO;
14
15 16 17 18 19
20 class SQLiteConnecter extends BaseConnecter
21 {
22 23 24
25 private static $instance;
26
27 28 29 30 31
32 private static $options = array();
33
34 35 36 37 38 39 40
41 private function __construct($dsn, array $options)
42 {
43 try {
44 $this->pdo = new PDO($dsn, null, null, parent::getOptions(self::$options, $options));
45 } catch (Exception $e) {
46 throw new CoreException($e->getMessage());
47 }
48 }
49
50 51 52 53 54 55 56 57
58 static function getInstance($dsn, $user = null, $pwd = null, array $options = array())
59 {
60 $key = md5($dsn);
61 if (empty(self::$instance[$key])) {
62 self::$instance[$key] = new SqliteConnecter($dsn, $options);
63 }
64
65 return self::$instance[$key];
66 }
67
68 69 70 71 72
73 function getPDO()
74 {
75 return $this->pdo;
76 }
77
78 79 80 81 82 83
84 function getPK($table)
85 {
86 $info = $this->getMetaData($table, false);
87 if (!empty($info)) {
88 foreach ($info as $i) {
89 if ($i['pk'] == 1) {
90 return $i['name'];
91 }
92 }
93 }
94
95 return false;
96 }
97
98 99 100
101 function lastInsertId()
102 {
103 return $this->pdo->lastInsertId();
104 }
105
106 107 108 109 110 111 112
113 function getMetaData($table, $fields_map = true)
114 {
115 $sql = "PRAGMA table_info('{$table}')";
116 try {
117 $data = $this->pdo->query($sql);
118 if ($fields_map) {
119 $result = array();
120 $data->fetchAll(PDO::FETCH_FUNC, function ($cid, $name, $type, $notnull, $dflt_value, $pk) use (&$result) {
121 $result[$name] = array(
122 'primary' => $pk == 1,
123 'auto_increment' => (bool)(($pk == 1) && ($type == 'INTEGER')),
124 'default_value' => strval($dflt_value),
125 'not_null' => $notnull == 1
126 );
127 });
128 return $result;
129 } else {
130 return $data->fetchAll(PDO::FETCH_ASSOC);
131 }
132 } catch (Exception $e) {
133 return array();
134 }
135 }
136 }
137