-
Notifications
You must be signed in to change notification settings - Fork 1
/
mysql.php
126 lines (97 loc) · 2.54 KB
/
mysql.php
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
<?php namespace phpsql\connectors;
include_once('interface.php');
class mysql extends \phpsql\connector_interface
{
private $db;
public function OpenConnection( $user, $pass, $ip, $port, $db, $options )
{
$str = [];
if ($ip) $str[] = "host={$ip}";
if ($port) $str[] = "port={$port}";
if ($db) $str[] = "dbname={$db}";
try
{
$con = new \PDO('mysql:'.(implode(';', $str)), $user, $pass);
} catch (\PDOException $e)
{
die($e->getMessage());
}
$this->db = $con;
return true;
}
public function Query( $q, $p = [] )
{
$this->UnifyParamsConvention($q, $p);
$stmt = $this->db->prepare($q);
$stmt->execute($p);
$issue = $stmt->errorinfo();
assert(is_null($issue[2]), $issue[2]);
$ret = $stmt->fetchAll(\PDO::FETCH_ASSOC);
// If we affect only one row, we could determine affected id
$affected_rows = $stmt->rowCount();
if ($affected_rows == 1 && strpos(strtolower($q), "select") == false)
$this->affected_id = $this->db->lastInsertId();
else
$this->affected_id = false;
$stmt->closeCursor();
unset($stmt);
return $ret;
}
public function Begin()
{
$this->Query("-- BEGIN;");
$this->db->beginTransaction();
}
public function SaveStep( $name )
{
$this->Query("SAVEPOINT nested_transaction_{$name};");
}
public function StepBack( $name )
{
$this->Query("ROLLBACK TO SAVEPOINT nested_transaction_{$name};");
}
public function ForgetStep( $name )
{
$this->Query("RELEASE SAVEPOINT nested_transaction_{$name};");
}
public function Rollback()
{
$this->Query("-- ROLLBACK;");
$this->db->rollBack();
}
public function Commit()
{
$this->Query("-- COMMIT;");
$this->db->commit();
}
public function InTransaction()
{
return !!$this->db->inTransaction();
}
public function RawConnection()
{
return $this->db;
}
private function UnifyParamsConvention(&$q, &$p)
{
$first_english_letter = ord('a');
$new_q = $q;
$new_p = [];
$total_replaced = 0;
for ($i = 0; $i < count($p); $i++)
{
$cur_numb = 1 + $i;
$cur_letter = chr($first_english_letter + $i);
$ancor = ":".$cur_letter;
$new_q = str_replace('$'.$cur_numb, $ancor, $new_q, $replaced);
$total_replaced += (int)(!!$replaced);
$new_p[$ancor] = $p[$i];
}
if ($total_replaced != count($p))
return;
$q = $new_q;
$p = $new_p;
}
}
include_once('phpsql.php');
\phpsql\phpsql::RegisterSchemeHandler("mysql", "\phpsql\connectors\mysql");