forked from sanchezzzhak/kak-clickhouse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Connection.php
287 lines (235 loc) · 6.89 KB
/
Connection.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
<?php
namespace kak\clickhouse;
use yii\base\Component;
use yii\caching\Cache;
use yii\httpclient\Client;
use Yii;
/**
* Class Connection
* @package app\helpers\clickhouse
* @property \yii\httpclient\Client $transport
*/
class Connection extends \yii\db\Connection
{
/**
* @event Event an event that is triggered after a DB connection is established
*/
const EVENT_AFTER_OPEN = 'afterOpen';
/**
* @var string name use database default use value "default"
*/
public $database;
/**
* @var string the hostname or ip address to use for connecting to the click-house server. Defaults to 'localhost'.
*/
public $dsn = 'localhost';
/**
* @var integer the port to use for connecting to the click-house server. Default port is 8123.
*/
public $port = 8123;
/**
* @var string
*/
public $commandClass = 'kak\clickhouse\Command';
public $schemaClass = 'kak\clickhouse\Schema';
public $transportClass = 'yii\httpclient\CurlTransport';
/**
* @var array
*/
public $requestConfig = [
'class' => 'kak\clickhouse\httpclient\Request',
];
public $schemaMap = [
'clickhouse' => 'kak\clickhouse\Schema'
];
/** @var bool|Client */
private $_transport = false;
private $_schema;
/**
* @var array
*/
private $_options = [];
/**
* @return array
*/
public function getOptions()
{
return $this->_options;
}
/**
* log_queries = 1
* @param array $options
* @return $this
*/
public function setOptions(array $options = [])
{
$this->_options = $options;
}
/**
* @param $sql
* @param array $params
* @return \kak\clickhouse\Command
*/
public function createCommand($sql = null, $params = [])
{
$this->open();
\Yii::trace("Executing ClickHouse: {$sql}", __METHOD__);
/** @var $command \kak\clickhouse\Command */
$command = new $this->commandClass([
'db' => $this,
'sql' => $sql,
]);
$command->addOptions($this->getOptions());
return $command->bindValues($params);
}
/**
* @return bool|Client
*/
public function getTransport()
{
return $this->_transport;
}
public function getIsActive()
{
return $this->_transport !== false;
}
public function open()
{
if ($this->getIsActive()) {
return;
}
$url = $this->buildDsnUrl();
$this->_transport = new Client([
'baseUrl' => $url,
'transport' => $this->transportClass,
'requestConfig' => $this->requestConfig,
]);
}
private function buildDsnUrl()
{
if (strpos($this->dsn, '@') !== false) {
$url = $this->dsn;
} else {
$auth = !empty($this->username) ? $this->username . ':' . $this->password . '@' : '';
$parsed = parse_url($this->dsn);
// get default url scheme
$scheme = array_key_exists('scheme', $parsed) ? $parsed['scheme'] : 'http';
$dsn = $this->dsn;
if (strpos($dsn, '://') !== false) {
$dsn = str_replace($scheme . '://', '', $dsn);
}
$url = ($scheme !== '' ? $scheme . '://' : '') . $auth . $dsn . ':' . $this->port;
}
$params = [];
if (!empty($this->database)) {
$params['database'] = $this->database;
}
$url = $this->buildUrl($url, $params);
return $url;
}
public function buildUrl($url, $data = [])
{
$parsed = parse_url($url);
isset($parsed['query']) ? parse_str($parsed['query'], $parsed['query']) : $parsed['query'] = [];
$params = isset($parsed['query']) ? array_merge($parsed['query'], $data) : $data;
$parsed['query'] = !empty($params) ? '?' . http_build_query($params) : '';
if (!isset($parsed['path'])) {
$parsed['path'] = '/';
}
$auth = (!empty($parsed['user']) ? $parsed['user'] : '') . (!empty($parsed['pass']) ? ':' . $parsed['pass'] : '');
$defaultScheme = 'http';
return (isset($parsed['scheme']) ? $parsed['scheme'] : $defaultScheme)
. '://'
. (!empty($auth) ? $auth . '@' : '')
. $parsed['host']
. (!empty($parsed['port']) ? ':' . $parsed['port'] : '')
. $parsed['path']
. $parsed['query'];
}
/**
* Quotes a string value for use in a query.
* Note that if the parameter is not a string or int, it will be returned without change.
* @param string $str string to be quoted
* @return string the properly quoted string
*/
public function quoteValue($str)
{
return $this->getSchema()->quoteValue($str);
}
public function quoteSql($sql)
{
return $sql;
}
public function ping()
{
$this->open();
$query = 'SELECT 1';
$response = $this->transport
->createRequest()
->setHeaders(['Content-Type: application/x-www-form-urlencoded'])
->setMethod('POST')
->setContent($query)
->send();
return trim($response->content) == '1';
}
/**
* Closes the connection when this component is being serialized.
* @return array
*/
public function __sleep()
{
$this->close();
return array_keys(get_object_vars($this));
}
/**
* Closes the currently active DB connection.
* It does nothing if the connection is already closed.
*/
public function close()
{
if ($this->getIsActive()) {
$connection = ($this->dsn . ':' . $this->port);
\Yii::trace('Closing DB connection: ' . $connection, __METHOD__);
}
}
/**
* Initializes the DB connection.
* This method is invoked right after the DB connection is established.
* The default implementation triggers an [[EVENT_AFTER_OPEN]] event.
*/
protected function initConnection()
{
$this->trigger(self::EVENT_AFTER_OPEN);
}
/**
* @return object|\kak\clickhouse\Schema
* @throws \yii\base\InvalidConfigException
*/
public function getSchema()
{
return $this->_schema = Yii::createObject([
'class' => $this->schemaClass,
'db' => $this
]);
}
public function quoteTableName($name)
{
return $name;
}
public function getDriverName()
{
return 'clickhouse';
}
public function quoteColumnName($name)
{
return $name;
}
/**
* Returns the query builder for the current DB connection.
* @return QueryBuilder the query builder for the current DB connection.
*/
public function getQueryBuilder()
{
return $this->getSchema()->getQueryBuilder();
}
}