Completed
Push — master ( 9276af...006240 )
by Yannick
06:15
created

Connection::getColumnType()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 2
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
<?php
2
require_once(dirname(__FILE__).'/settings.php');
3
4
class Connection{
5
	public $db = null;
6
	public $dbs = array();
7
	public $latest_schema = 35;
8
	
9
	public function __construct($dbc = null,$dbname = null,$user = null,$pass = null) {
10
	    global $globalDBdriver;
11
	    if ($dbc === null) {
12
		if ($this->db === null && $dbname === null) {
13
		    if ($user === null && $pass === null) {
14
			$this->createDBConnection();
15
		    } else {
16
			$this->createDBConnection(null,$user,$pass);
17
		    }
18
		} else {
19
		    $this->createDBConnection($dbname);
20
		}
21
	    } elseif ($dbname === null || $dbname === 'default') {
22
		$this->db = $dbc;
23
		if ($this->connectionExists() === false) {
24
			/*
25
			echo 'Restart Connection !!!'."\n";
26
			$e = new \Exception;
27
			var_dump($e->getTraceAsString());
28
			*/
29
			$this->createDBConnection();
30
		}
31
	    } else {
32
		//$this->connectionExists();
33
		$this->dbs[$dbname] = $dbc;
34
	    }
35
	}
36
37
	public function db() {
38
		if ($this->db === null) {
39
			$this->__construct();
40
		}
41
		if ($this->db === null) {
42
			echo 'Can\'t connect to database. Check configuration and database status.';
43
			die;
44
		} else {
45
			return $this->db;
46
		}
47
	}
48
49
	/**
50
	* Creates the database connection
51
	*
52
	* @return Boolean of the database connection
53
	*
54
	*/
55
56
	public function createDBConnection($DBname = null, $user = null, $pass = null)
57
	{
58
		global $globalDBdriver, $globalDBhost, $globalDBuser, $globalDBpass, $globalDBname, $globalDebug, $globalDB, $globalDBport, $globalDBTimeOut, $globalDBretry, $globalDBPersistent;
59
		if ($DBname === null) {
60
			if ($user === null && $pass === null) {
61
				$DBname = 'default';
62
				$globalDBSdriver = $globalDBdriver;
63
				$globalDBShost = $globalDBhost;
64
				$globalDBSname = $globalDBname;
65
				$globalDBSuser = $globalDBuser;
66
				$globalDBSpass = $globalDBpass;
67
				if (!isset($globalDBport) || $globalDBport === NULL || $globalDBport == '') $globalDBSport = 3306;
68
				else $globalDBSport = $globalDBport;
69
			} else {
70
				$DBname = 'default';
71
				$globalDBSdriver = $globalDBdriver;
72
				$globalDBShost = $globalDBhost;
73
				$globalDBSname = $globalDBname;
74
				$globalDBSuser = $user;
75
				$globalDBSpass = $pass;
76
				if (!isset($globalDBport) || $globalDBport === NULL || $globalDBport == '') $globalDBSport = 3306;
77
				else $globalDBSport = $globalDBport;
78
			}
79
		} else {
80
			$globalDBSdriver = $globalDB[$DBname]['driver'];
81
			$globalDBShost = $globalDB[$DBname]['host'];
82
			$globalDBSname = $globalDB[$DBname]['name'];
83
			$globalDBSuser = $globalDB[$DBname]['user'];
84
			$globalDBSpass = $globalDB[$DBname]['pass'];
85
			if (isset($globalDB[$DBname]['port'])) $globalDBSport = $globalDB[$DBname]['port'];
86
			else $globalDBSport = 3306;
87
		}
88
		// Set number of try to connect to DB
89
		if (!isset($globalDBretry) || $globalDBretry == '' || $globalDBretry === NULL) $globalDBretry = 5;
90
		$i = 0;
91
		while (true) {
92
			try {
93
				if ($globalDBSdriver == 'mysql') {
94
					$this->dbs[$DBname] = new PDO("$globalDBSdriver:host=$globalDBShost;port=$globalDBSport;dbname=$globalDBSname;charset=utf8", $globalDBSuser,  $globalDBSpass);
95
					$this->dbs[$DBname]->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
96
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
97
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
98
					if (!isset($globalDBTimeOut)) $this->dbs[$DBname]->setAttribute(PDO::ATTR_TIMEOUT,500);
99
					else $this->dbs[$DBname]->setAttribute(PDO::ATTR_TIMEOUT,$globalDBTimeOut);
100
					if (!isset($globalDBPersistent)) $this->dbs[$DBname]->setAttribute(PDO::ATTR_PERSISTENT,true);
101
					else $this->dbs[$DBname]->setAttribute(PDO::ATTR_PERSISTENT,$globalDBPersistent);
102
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
103
					$this->dbs[$DBname]->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
104
					// Workaround against "ONLY_FULL_GROUP_BY" mode
105
					// to enable it : $this->dbs[$DBname]->exec('SET sql_mode = "NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,ONLY_FULL_GROUP_BY"');
106
					$this->dbs[$DBname]->exec('SET sql_mode = "NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"');
107
					// Force usage of UTC
108
					$this->dbs[$DBname]->exec('SET SESSION time_zone = "+00:00"');
109
					//$this->dbs[$DBname]->exec('SET @@session.time_zone = "+00:00"');
110
				} else {
111
					$this->dbs[$DBname] = new PDO("$globalDBSdriver:host=$globalDBShost;port=$globalDBSport;dbname=$globalDBSname;options='--client_encoding=utf8'", $globalDBSuser,  $globalDBSpass);
112
					//$this->dbs[$DBname]->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
113
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
114
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
115
					if (!isset($globalDBTimeOut)) $this->dbs[$DBname]->setAttribute(PDO::ATTR_TIMEOUT,200);
116
					else $this->dbs[$DBname]->setAttribute(PDO::ATTR_TIMEOUT,$globalDBTimeOut);
117
					if (!isset($globalDBPersistent)) $this->dbs[$DBname]->setAttribute(PDO::ATTR_PERSISTENT,true);
118
					else $this->dbs[$DBname]->setAttribute(PDO::ATTR_PERSISTENT,$globalDBPersistent);
119
					$this->dbs[$DBname]->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
120
					$this->dbs[$DBname]->exec('SET timezone="UTC"');
121
				}
122
				break;
123
			} catch(PDOException $e) {
124
				$i++;
125
				if (isset($globalDebug) && $globalDebug) echo 'Error connecting to DB: '.$globalDBSname.' - Error: '.$e->getMessage()."\n";
126
				//exit;
127
				if ($i > $globalDBretry) return false;
128
				//return false;
129
			}
130
		}
131
		if ($DBname === 'default') $this->db = $this->dbs['default'];
132
		return true;
133
	}
134
135
	public function tableExists($table)
136
	{
137
		global $globalDBdriver, $globalDBname;
138
		if ($globalDBdriver == 'mysql') {
139
			$query = "SHOW TABLES LIKE '".$table."'";
140
		} else {
141
			$query = "SELECT * FROM pg_catalog.pg_tables WHERE tablename = '".$table."'";
142
		}
143
		if ($this->db == NULL) return false;
144
		try {
145
			//$Connection = new Connection();
146
			$results = $this->db->query($query);
1 ignored issue
show
Bug introduced by
The method query cannot be called on $this->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
147
		} catch(PDOException $e) {
148
			return false;
149
		}
150
		if($results->rowCount()>0) {
151
		    return true; 
152
		}
153
		else return false;
154
	}
155
156
	public function connectionExists()
157
	{
158
		global $globalDBdriver, $globalDBCheckConnection;
159
		if (isset($globalDBCheckConnection) && $globalDBCheckConnection === FALSE) return true;
160
		$query = "SELECT 1 + 1";
161
		if ($this->db === null) return false;
162
		try {
163
			$sum = @$this->db->query($query);
1 ignored issue
show
Bug introduced by
The method query cannot be called on $this->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
164
			if ($sum instanceof \PDOStatement) {
165
				$sum = $sum->fetchColumn(0);
166
			} else $sum = 0;
167
			if (intval($sum) !== 2) {
168
			     return false;
169
			}
170
			
171
		} catch(PDOException $e) {
172
			if($e->getCode() != 'HY000' || !stristr($e->getMessage(), 'server has gone away')) {
173
            			throw $e;
174
	                }
175
	                //echo 'error ! '.$e->getMessage();
176
			return false;
177
		}
178
		return true; 
179
	}
180
181
	/*
182
	* Check if index exist
183
	*/
184
	public function indexExists($table,$index)
185
	{
186
		global $globalDBdriver, $globalDBname;
187
		if ($globalDBdriver == 'mysql') {
188
			$query = "SELECT COUNT(*) as nb FROM INFORMATION_SCHEMA.STATISTICS WHERE table_schema=DATABASE() AND table_name='".$table."' AND index_name='".$index."'";
189
		} else {
190
			$query = "SELECT count(*) as nb FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relname = '".$index."' AND n.nspname = '".$table."'";
191
		}
192
		try {
193
			//$Connection = new Connection();
194
			$results = $this->db->query($query);
1 ignored issue
show
Bug introduced by
The method query cannot be called on $this->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
195
		} catch(PDOException $e) {
196
			return false;
197
		}
198
		$nb = $results->fetchAll(PDO::FETCH_ASSOC);
199
		if($nb[0]['nb'] > 0) {
200
			return true; 
201
		}
202
		else return false;
203
	}
204
205
	/*
206
	* Get columns name of a table
207
	* @return Array all column name in table
208
	*/
209
	public function getColumnName($table)
210
	{
211
		$query = "SELECT * FROM ".$table." LIMIT 0";
212
		try {
213
			$results = $this->db->query($query);
1 ignored issue
show
Bug introduced by
The method query cannot be called on $this->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
214
		} catch(PDOException $e) {
215
			return "error : ".$e->getMessage()."\n";
216
		}
217
		$columns = array();
218
		$colcnt = $results->columnCount();
219
		for ($i = 0; $i < $colcnt; $i++) {
220
			$col = $results->getColumnMeta($i);
221
			$columns[] = $col['name'];
222
		}
223
		return $columns;
224
	}
225
226
	public function getColumnType($table,$column) {
227
		$select = $this->db->query('SELECT '.$column.' FROM '.$table);
1 ignored issue
show
Bug introduced by
The method query cannot be called on $this->db (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
228
		$tomet = $select->getColumnMeta(0);
229
		return $tomet['native_type'];
230
	}
231
232
	/*
233
	* Check if a column name exist in a table
234
	* @return Boolean column exist or not
235
	*/
236
	public function checkColumnName($table,$name)
237
	{
238
		global $globalDBdriver, $globalDBname;
239
		if ($globalDBdriver == 'mysql') {
240
			$query = "SELECT COUNT(*) as nb FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = :database AND TABLE_NAME = :table AND COLUMN_NAME = :name LIMIT 1";
241
		} else {
242
			$query = "SELECT COUNT(*) as nb FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_CATALOG = :database AND TABLE_NAME = :table AND COLUMN_NAME = :name LIMIT 1";
243
		}
244
			try {
245
				$sth = $this->db()->prepare($query);
1 ignored issue
show
Bug introduced by
The method prepare cannot be called on $this->db() (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
246
				$sth->execute(array(':database' => $globalDBname,':table' => $table,':name' => $name));
247
			} catch(PDOException $e) {
248
				echo "error : ".$e->getMessage()."\n";
249
			}
250
			$result = $sth->fetch(PDO::FETCH_ASSOC);
251
			$sth->closeCursor();
252
			if ($result['nb'] > 0) return true;
253
			else return false;
254
/*		} else {
255
			$query = "SELECT * FROM ".$table." LIMIT 0";
256
			try {
257
				$results = $this->db->query($query);
258
			} catch(PDOException $e) {
259
				return "error : ".$e->getMessage()."\n";
260
			}
261
			$colcnt = $results->columnCount();
262
			for ($i = 0; $i < $colcnt; $i++) {
263
				$col = $results->getColumnMeta($i);
264
				if ($name == $col['name']) return true;
265
			}
266
			return false;
267
		}
268
*/
269
	}
270
271
	/*
272
	* Get schema version
273
	* @return integer schema version
274
	*/
275
	public function check_schema_version() {
276
		$version = 0;
277
		if ($this->tableExists('aircraft')) {
278
			if (!$this->tableExists('config')) {
279
	    			$version = '1';
280
	    			return $version;
281
			} else {
282
				$query = "SELECT value FROM config WHERE name = 'schema_version' LIMIT 1";
283
				try {
284
					$sth = $this->db->prepare($query);
285
					$sth->execute();
286
				} catch(PDOException $e) {
287
					return "error : ".$e->getMessage()."\n";
288
				}
289
				$result = $sth->fetch(PDO::FETCH_ASSOC);
290
				$sth->closeCursor();
291
				return $result['value'];
292
			}
293
		} else return $version;
294
	}
295
	
296
	/*
297
	* Check if schema version is latest_schema
298
	* @return Boolean if latest version or not
299
	*/
300
	public function latest() {
301
	    if ($this->check_schema_version() == $this->latest_schema) return true;
302
	    else return false;
303
	}
304
305
}
306
?>
307