public function getLogging() { return $this->query->getLogging(); }
function query($sql) { // Pass it an SQL query and if the query was successful // it returns a MySQLQuery object which you can get results from. $start = getmicrotime(); $q = new MySQLQuery($this->conn); $q->query($sql); $duration = getmicrotime() - $start; global $mysqltotalduration; $mysqltotalduration += $duration; twfy_debug("SQL", "Complete after {$duration} seconds."); // We could also output $q->mysql_info() here, but that's for // PHP >= 4.3.0. return $q; }
public function query($sql, $params = null, $flags = 0, $wantFields = null, $offset = 0, $limit = 0) { $link = $this->link; $handler = $this->dataHandler; $wantFields = array_flip($wantFields); if ($params) { $offs = 0; foreach ($params as $p) { $i = strpos($sql, '?', $offs); if ($i === FALSE) { return 'Too many parameters supplied for the query'; } $d =& $p['data']; if (isset($p['file'])) { $fn = $p['file']; if (!preg_match('/^[0-9a-z\\.\\-]+$/i', $fn)) { return 'Illegal file name'; } $d = file_get_contents($this->path . '/' . $p['file']); } if ($p['type'] == 'b') { $d = 'X\'' . bin2hex($d) . '\''; } else { if ($p['type'] == 's') { $d = '\'' . mysqli_real_escape_string($link, $p['data']) . '\''; } else { $d = $d . ''; } } $sql = substr_replace($sql, $d, $i, 1); $offs = $i + strlen($d); } } $sqlLen = strlen($sql); if ($sqlLen > 0x80000) { $t = MySQLQuery::SimpleQuery($link, 'SHOW VARIABLES LIKE "max_allowed_packet"', TRUE); if (!$t) { throw new Exception("Query is very large ({$sqlLen} bytes). Failed to read the value of 'max_allowed_packed' MySQL variable"); } if ($sqlLen >= $t[0][1]) { throw new Exception("Length of the query ({$sqlLen} bytes) is larger than 'max_allowed_packet' variable ({$t[0][1]} bytes) in MySQL configuration file."); } } $t = microtime(TRUE); if (!$link->multi_query($sql)) { throw new Exception($link->error); } $extime = microtime(TRUE) - $t; $affRows = $link->affected_rows; $results = array(); $noData = $flags & QUERY_ONLY_FIELDS ? TRUE : FALSE; $hashing = $flags & QUERY_WITH_HASHING ? TRUE : FALSE; $totalRows = $totalSize = 0; $warning = ''; do { if (!($result = $link->use_result())) { continue; } $res = array(); $flds = array(); $resRowCnt = 0; foreach ($result->fetch_fields() as $f) { $flds[] = MySQLQuery::GetFieldParams($f); } if ($wantFields) { $flds = array_intersect_key($flds, $wantFields); } if ($handler && ($q = call_user_func_array(array($handler, 'handleResultStarted'), array(&$flds)))) { $warning = $q; } while (!$warning && !$noData) { while ($row = $result->fetch_row()) { if ($offset > 0) { $offset--; continue; } if ($this->maxRows > 0 && ++$totalRows > $this->maxRows) { $warning = "Query aborted: {$this->maxRows} record limit has been reached."; break; } else { if ($wantFields) { $row = array_intersect_key($row, $wantFields); } foreach ($row as $i => &$c) { if ($c === NULL || $c === '') { continue; } $totalSize += strlen($c); if ($hashing) { if ($flds[$i]['binary']) { $c = array('label' => 'Binary', 'hash' => md5($c)); } else { if ($this->maxCellSize > 0 && strlen($c) > $this->maxCellSize) { $c = array('label' => 'Large', 'hash' => md5($c)); } } } } if ($this->maxDataSize > 0 && $totalSize > $this->maxDataSize) { $warning = "Query aborted: {$this->maxDataSize} megabyte limit has been reached."; break; } else { if ($handler) { if ($q = call_user_func_array(array($handler, 'handleRecord'), array(&$row))) { $warning = $q; break; } } else { $res[] = $row; } } if (++$resRowCnt == $limit) { break; } } } break; } $result->free(); $a = array('data' => $handler ? NULL : $res, 'fields' => $flds, 'rowCount' => $resRowCnt); if ($flags & QUERY_CALC_FOUND_ROWS) { $t = MySQLQuery::SimpleQuery($link, 'SELECT FOUND_ROWS()', TRUE); $a['calcFoundRows'] = (int) $t[0][0]; } if ($handler) { call_user_func_array(array($handler, 'handleResultEnded'), array(&$a)); } $results[] = $a; } while ($link->more_results() && $link->next_result()); if ($flags & QUERY_WITH_FIELD_DETAILS) { $cols = array(); foreach ($results as &$r) { foreach ($r['fields'] as &$f) { if (!($t = $f['table'])) { continue; } $c =& $cols[$t]; if (!isset($c)) { $c = MySQLQuery::SimpleQuery($link, 'SHOW COLUMNS FROM ' . ($f['db'] ? '`' . $f['db'] . '`.' : '') . "`{$t}`"); if (!$c) { $f['table'] = ''; continue; } } foreach ($c as &$q) { if ($q['Field'] != $f['field']) { continue; } if ($f['type'] == 'set' || $f['type'] == 'enum') { $f['values'] = str_replace("','", ",", preg_replace("/(enum|set)\\('(.+?)'\\)/", "\\2", $q['Type'])); } else { $f['values'] = ''; } $f['default'] = $q['Default']; break; } } } } $a = array('results' => $results, 'affectedRows' => $affRows < 0 ? 0 : $affRows, 'execTime' => sprintf("%.3f", $extime)); if ($handler) { call_user_func_array(array($handler, 'handleQueryEnded'), array(&$a)); } if (is_string($warning)) { $a['warning'] = $warning; } if ($flags & QUERY_WITH_INSERT_ID) { $t = MySQLQuery::SimpleQuery($link, 'SELECT LAST_INSERT_ID()', TRUE); $a['lastInsertId'] = $t[0][0]; } return $a; }
case 'query': $c = getLink($req['cid']); if ($req['db']) { $c->select_db($req['db']); } $q =& $req['query']; $p =& $req['params']; if ($req['limited']) { $pageSize = $config['queryPageSize']; $cellSize = $config['queryMaxCellSize']; $dataSize = $config['queryMaxDataSize']; $rowsAmnt = $config['queryMaxRows']; } else { $pageSize = $cellSize = $dataSize = $rowsAmnt = 0; } $a = new MySQLQuery($c, $req['limited'] ? new QueryResultJSONWriter($pageSize) : NULL, $cellSize, $dataSize, $rowsAmnt); if (is_array($q)) { $aff = 0; for ($i = 0; $i < count($q); $i++) { $r = $a->query($q[$i], $p[$i], $req['flags']); $aff += $r['affectedRows']; } $a = array('affectedRows' => $aff); } else { $a = $a->query($q, $p, $req['flags']); } if ($req['toFile'] && $a['results']) { $f = new TempFile(); $f->write($a['results'][0]['data'][0][0]); $a = array('file' => $f->name, 'alias' => 'cell-' . date('Ymd-His') . '.data'); }
$this->file->write(";\n"); } } else { $this->file->write("-- Table contains no data\n"); } } public function handleQueryEnded(&$response) { } } foreach ($ARGS['tables_data'] as $t) { $file->write("--\n-- Data for table: {$t}\n--\n" . ($ARGS['with_lock'] ? "LOCK TABLES `{$t}` WRITE;\n" : '') . "ALTER TABLE `{$t}` DISABLE KEYS;\n\n"); $w = new QueryResultSQLWriter($LINK, $file, $t, $ARGS['group_inserts']); $q = new MySQLQuery($LINK, $w); $q = $q->query("SELECT * FROM `{$db}`.`{$t}`"); if (is_string($q)) { return $s; } $file->write("\nALTER TABLE `{$t}` ENABLE KEYS;\n" . ($ARGS['with_lock'] ? "UNLOCK TABLES;\n" : '') . ($ARGS['with_commit'] ? "COMMIT;" : '') . "\n\n"); } } foreach ($ARGS['triggers'] as $t) { $file->write("--\n-- Structure for trigger: {$t}\n--\n"); if ($ARGS['with_drop_obj']) { $file->write("DROP TRIGGER IF EXISTS `{$t}`;\n"); } $q = MySQLQuery::SimpleQuery($LINK, "SHOW CREATE TRIGGER `{$db}`.`{$t}`", TRUE); $file->write(delimit($q[0][2])); } $file->write(getExportFooter($disFKeys)); return array('result' => $file->name);
function __construct() { parent::__construct("admin"); }
<?php /*--------------------------------------------------------------------* | Copyright (c) 2010-2013 Vayer Software Ltd. - All Rights Reserved. | *--------------------------------------------------------------------*/ $res = "--\n-- DbNinja v" . VERSION . " for MySQL\n-- Date: " . date("Y-m-d H:i:s") . " (UTC)\n--\n\n"; foreach ($ARGS['users'] as $i) { $u = "'" . addslashes($i['user']) . "'@'" . addslashes($i['host']) . "'"; if ($i['withDrop']) { $res .= "DROP USER {$u};\n"; } if ($i['withCreate']) { $res .= "CREATE USER {$u};\n"; } if ($i['withGrants'] && (!$i['withDrop'] || $i['withCreate'])) { $q = MySQLQuery::SimpleQuery($LINK, "SHOW GRANTS FOR {$u}", TRUE); if ($q === FALSE) { return $LINK->error; } $res .= $q[0][0] . ";\n"; } $res .= "\n"; } if ($ARGS['to_file']) { $f = new TempFile(); $f->write($res); } return array('result' => $ARGS['to_file'] ? $f->name : $res);
$v = '""'; } } } $b[] = $v; } $dataLineCnt++; $sql .= ($sql ? ",\n" : '') . '(' . implode(', ', $b) . ')'; if (strlen($sql) >= 0x80000) { if ($toFile) { $file->write($sqlPrefix . $sql . ";\n"); } else { if (!MySQLQuery::NoResultQuery($LINK, $sqlPrefix . $sql)) { return $LINK->error; } } $sql = ''; } if ($lim > 0 && $dataLineCnt == $lim) { break; } } fclose($f); if ($sql) { if ($toFile) { $file->write($sqlPrefix . $sql . ";\n"); } elseif (!MySQLQuery::NoResultQuery($LINK, $sqlPrefix . $sql)) { return $LINK->error; } } return array('result' => $toFile ? $file->name : TRUE);
} public function handleResultStarted(&$fields) { $this->fields = $fields; $this->file->write($this->encl[0]); } public function handleResultEnded(&$result) { $this->file->write("\n" . $this->encl[1] . ";\n"); } public function handleQueryEnded(&$response) { $response = array('result' => $this->file->name); } } ///// switch (strtolower($ARGS['format'])) { case 'csv': case 'txt': $handler = new QueryResultExportCSV($LINK, $ARGS); break; case 'sql': $handler = new QueryResultExportSQL($LINK, $ARGS); break; case 'json': case 'php': $handler = new QueryResultExportArrArr($LINK, $ARGS); break; } $q = new MySQLQuery($LINK, $handler); return $q->query($ARGS['query'], NULL, 0, $ARGS['fields'], $ARGS['offset'], $ARGS['limit']);
return "Can't get the value of 'max_allowed_packet' MySQL variable"; } $maxPack = $maxPack[0][0]; $z = new SQLStatementReader($ARGS['file'], @$ARGS['file_encoding'], @$ARGS['offset'] ?: 0); $c = 0; while (!$z->done) { if (($s = $z->read()) === FALSE) { return $z->error; } if ($s && ($s = trim(preg_replace('/^(#|--).*/m', '', $s)))) { if (preg_match('/^USE\\s+(.+)/i', $s, $m)) { $db = trim($m[1], '`'); } else { $s = preg_replace('/\\/\\*!\\d+\\s+|\\s*\\*\\/$/', '', $s); if (preg_match('/^SET\\s+.+/i', $s, $m)) { file_put_contents($sf, $m[0] . ";\n", FILE_APPEND); } } $l = strlen($s); if ($l >= $maxPack) { return "Statement beginning with '<b>" . substr($s, 0, 100) . "...</b>'<br /> is too large ({$l} bytes). " . "Maximum packet size defined in MySQL server's configuration is {$maxPack} bytes. " . "<a href=\"http://dev.mysql.com/doc/refman/5.0/en/packet-too-large.html\" target=\"_blank\">More details here</a>"; } if (!MySQLQuery::NoResultQuery($LINK, $s)) { return $LINK->error; } } if ($ARGS['step'] && ++$c == $ARGS['step']) { break; } } return array('result' => "Successfully executed {$c} statement" . ($c > 1 ? 's' : ''), 'count' => $c, 'offset' => $z->offset + $z->fileOffset, 'done' => $z->done, 'db' => $db);