File size: 9,231 Bytes
015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 5d7cf95 015c315 | 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 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 | <?php
/**
* CorpusDB PHP SDK
*
* Official client library for CorpusDB API
* https://corpusdb.66ghz.com
*
* @version 1.0.0
* @license MIT
*/
class CorpusDB {
private $apiKey;
private $secretKey;
private $baseUrl;
/**
* Initialize CorpusDB client
*
* @param string $apiKey Your API key (cDb_xxx or CDB-xxx)
* @param string $secretKey Your secret key
* @param string $baseUrl API base URL
*/
public function __construct($apiKey, $secretKey, $baseUrl = 'https://corpusdb.66ghz.com/api') {
if (empty($apiKey) || empty($secretKey)) {
throw new Exception('API key and secret key are required');
}
$this->apiKey = $apiKey;
$this->secretKey = $secretKey;
$this->baseUrl = rtrim($baseUrl, '/');
}
/**
* Make API request
*
* @param string $endpoint API endpoint
* @param string $method HTTP method
* @param array|null $data Request body data
* @return array API response
* @throws Exception If API request fails
*/
private function request($endpoint, $method = 'GET', $data = null) {
$url = $this->baseUrl . $endpoint;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-Api-Key: ' . $this->apiKey,
'X-Secret-Key: ' . $this->secretKey,
'Content-Type: application/json'
]);
if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
if ($data) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
} elseif ($method === 'PUT') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
if ($data) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
} elseif ($method === 'DELETE') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
$error = curl_error($ch);
curl_close($ch);
throw new Exception("CorpusDB API Error: $error");
}
curl_close($ch);
$result = json_decode($response, true);
if (!isset($result['ok']) || !$result['ok']) {
$error = $result['error'] ?? 'API request failed';
throw new Exception("CorpusDB API Error: $error");
}
return $result;
}
/**
* List all databases
*
* @return array List of databases
*/
public function listDatabases() {
$result = $this->request('/cdb/databases');
return $result['databases'] ?? [];
}
/**
* List all tables
*
* @return array List of tables
*/
public function listTables() {
return $this->request('/cdb/tables');
}
/**
* Execute SQL query
*
* @param string $sql SQL query to execute
* @return array Query result with data
*/
public function query($sql) {
return $this->request('/cdb/query', 'POST', ['sql' => $sql]);
}
/**
* Get rows from table
*
* @param string $database Database name
* @param string $table Table name
* @param int $limit Number of rows to return
* @param int $offset Offset for pagination
* @return array Rows data
*/
public function getRows($database, $table, $limit = 100, $offset = 0) {
return $this->request("/cdb/rows/$database/$table?limit=$limit&offset=$offset");
}
/**
* Insert row into table
*
* @param string $database Database name
* @param string $table Table name
* @param array $data Row data to insert
* @return array Insert result
*/
public function insertRow($database, $table, $data) {
return $this->request("/cdb/rows/$database/$table", 'POST', $data);
}
/**
* Escape SQL identifier (double-quote)
*/
private function escapeIdentifier($id) {
return str_replace('"', '""', $id);
}
/**
* Escape SQL value (single-quote)
*/
private function escapeValue($val) {
return str_replace("'", "''", $val);
}
/**
* Validate ORDER BY to prevent injection
*/
private function validateOrderBy($orderBy) {
$parts = trim($orderBy);
if (!preg_match('/^[\w.\s,]+$/i', $parts)) {
throw new \InvalidArgumentException("Invalid ORDER BY clause: $orderBy");
}
$forbidden = [';', '--', '/*', '*/', 'UNION', 'INSERT', 'UPDATE', 'DELETE', 'DROP', 'CREATE', 'ALTER'];
$upper = strtoupper($parts);
foreach ($forbidden as $kw) {
if (strpos($upper, $kw) !== false) {
throw new \InvalidArgumentException("Invalid ORDER BY clause: contains $kw");
}
}
return $parts;
}
/**
* Select data from table (safe from SQL injection)
*/
public function select($database, $table, $options = []) {
$db = $this->escapeIdentifier($database);
$tbl = $this->escapeIdentifier($table);
$sql = "SELECT * FROM \"$db\".\"$tbl\"";
if (isset($options['where'])) {
$conditions = [];
foreach ($options['where'] as $key => $value) {
$col = $this->escapeIdentifier($key);
$val = $this->escapeValue($value);
$conditions[] = "\"$col\" = '$val'";
}
$sql .= ' WHERE ' . implode(' AND ', $conditions);
}
if (isset($options['orderBy'])) {
$sql .= ' ORDER BY ' . $this->validateOrderBy($options['orderBy']);
}
if (isset($options['limit'])) {
$sql .= ' LIMIT ' . intval($options['limit']);
}
if (isset($options['offset'])) {
$sql .= ' OFFSET ' . intval($options['offset']);
}
return $this->query($sql);
}
/**
* Insert data into table (safe from SQL injection)
*/
public function insert($database, $table, $data) {
$db = $this->escapeIdentifier($database);
$tbl = $this->escapeIdentifier($table);
$columns = implode(', ', array_map(function($k) { return '"' . $this->escapeIdentifier($k) . '"'; }, array_keys($data)));
$values = implode(', ', array_map(function($v) { return "'" . $this->escapeValue($v) . "'"; }, array_values($data)));
$sql = "INSERT INTO \"$db\".\"$tbl\" ($columns) VALUES ($values)";
return $this->query($sql);
}
/**
* Update data in table (safe from SQL injection)
*/
public function update($database, $table, $data, $where) {
$db = $this->escapeIdentifier($database);
$tbl = $this->escapeIdentifier($table);
$sets = [];
foreach ($data as $key => $value) {
$col = $this->escapeIdentifier($key);
$val = $this->escapeValue($value);
$sets[] = "\"$col\" = '$val'";
}
$conditions = [];
foreach ($where as $key => $value) {
$col = $this->escapeIdentifier($key);
$val = $this->escapeValue($value);
$conditions[] = "\"$col\" = '$val'";
}
$sql = "UPDATE \"$db\".\"$tbl\" SET " . implode(', ', $sets) .
" WHERE " . implode(' AND ', $conditions);
return $this->query($sql);
}
/**
* Delete data from table (safe from SQL injection)
*/
public function delete($database, $table, $where) {
$db = $this->escapeIdentifier($database);
$tbl = $this->escapeIdentifier($table);
$conditions = [];
foreach ($where as $key => $value) {
$col = $this->escapeIdentifier($key);
$val = $this->escapeValue($value);
$conditions[] = "\"$col\" = '$val'";
}
$sql = "DELETE FROM \"$db\".\"$tbl\" WHERE " . implode(' AND ', $conditions);
return $this->query($sql);
}
}
// Example usage
if (basename(__FILE__) == basename($_SERVER['PHP_SELF'])) {
// Initialize client
$db = new CorpusDB(
'cDb_your_api_key',
'your-secret-key'
);
// List databases
$databases = $db->listDatabases();
echo "Databases: " . json_encode($databases) . "\n";
// Execute query
$result = $db->query('SELECT * FROM mydb.users LIMIT 10');
echo "Query result: " . json_encode($result) . "\n";
// Select with conditions
$users = $db->select('mydb', 'users', [
'where' => ['status' => 'active'],
'limit' => 10
]);
echo "Active users: " . json_encode($users) . "\n";
// Insert data
$db->insert('mydb', 'users', [
'name' => 'John Doe',
'email' => 'john@example.com',
'status' => 'active'
]);
// Update data
$db->update('mydb', 'users',
['status' => 'inactive'],
['email' => 'john@example.com']
);
// Delete data
$db->delete('mydb', 'users', ['status' => 'inactive']);
}
|