') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); GitHub - pardnio/php-mysql-cli: Lightweight PHP MySQL client with chainable syntax, query builder and read-write separation. · GitHub
Skip to content

Latest commit

History

11 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

MySQL CLI

Lightweight PHP MySQL client with chainable syntax, query builder and read-write separation.
Following stateless architecture principles, providing stable and reliable database operation experience.

packagistversionlicense
readmereadme

Three Core Features

Chainable Syntax

Intuitive query builder syntax that makes complex SQL queries simple and readable with low learning curve

Read-Write Separation

Automatically identifies query types and routes to corresponding database connections, supports read-write separation architecture, effectively distributes database load and improves overall system performance

Stable Connection

Retry mechanism automatically handles network jitter and temporary connection failures, ensuring reliability in unstable network environments

Features

  • Environment Variable Configuration: Flexible environment variable settings, supports multi-environment deployment
  • Slow Query Monitoring: Automatically logs queries over 20ms, assists with performance optimization
  • Secure Parameter Binding: Prepared statements prevent SQL injection attacks
  • Complete CRUD: Supports full database operations for create, read, update, delete
  • SQL Function Support: Built-in common MySQL function recognition and processing
  • Stateless Design: Independent cleanup for each request

Usage

Installation

composer require pardnchiu/mysql-cli

Environment Variables Setup

Read Database (Optional)

DB_READ_HOST=localhostDB_READ_PORT=3306DB_READ_USER=read_userDB_READ_PASSWORD=read_passwordDB_READ_DATABASE=your_databaseDB_READ_CHARSET=utf8mb4

Write Database (Required for write operations)

DB_WRITE_HOST=localhostDB_WRITE_PORT=3306DB_WRITE_USER=write_userDB_WRITE_PASSWORD=write_passwordDB_WRITE_DATABASE=your_databaseDB_WRITE_CHARSET=utf8mb4

Basic Usage

<?phpusepardnchiu\SQL;
// Basic query$users = SQL::table("users")
->where("status", "active")
->where("age", ">", 18)
->get();
// Complex query with aggregation$reports = SQL::table("orders")
->select("user_id", "COUNT(*) as order_count", "SUM(amount) as total")
->where("created_at", ">=", "2024-01-01")
->groupBy("user_id")
->orderBy("total", "DESC")
->limit(10)
->get();

API Reference

Query Builder

  • table($table, $target = "READ") - Set target table and connection type

    SQL::table("users") // Read operation (default)SQL::table("users", "WRITE") // Write operation
  • select($fields) - Specify query fields

    SQL::table("users")->select("id", "name", "email");
    SQL::table("products")->select("COUNT(*) as total");
  • where($column, $operator, $value) - Add conditions

    // Basic conditionsSQL::table("users")->where("status", "active");
    SQL::table("orders")->where("amount", ">", 100);
    // LIKE search (automatically adds wildcards)SQL::table("users")->where("name", "LIKE", "John");
  • orderBy($column, $direction) - Sorting

    SQL::table("users")->orderBy("created_at", "DESC");
    SQL::table("products")->orderBy("price", "ASC");
  • limit($count) / offset($count) - Pagination

    SQL::table("users")->limit(20)->offset(40);

JOIN Operations

// Inner joinSQL::table("users")
->join("profiles", "users.id", "profiles.user_id")
->get();
// Left joinSQL::table("users")
->leftJoin("orders", "users.id", "orders.user_id")
->select("users.name", "COUNT(orders.id) as order_count")
->get();
// Right joinSQL::table("departments")
->rightJoin("employees", "departments.id", "employees.dept_id")
->get();

Data Operations

// Insert data and get ID$userId = SQL::table("users", "WRITE")
->insertGetId([
"name" => "John Doe",
"email" => "john@example.com", "created_at" => "NOW()"
]);
// Update data$result = SQL::table("users", "WRITE")
->where("id", $userId)
->update([
"last_login" => "NOW()",
"login_count" => "login_count + 1"
]);
// Raw query$customData = SQL::read(
"SELECT u.name, COUNT(o.id) as orders FROM users u LEFT JOIN orders o ON u.id = o.user_id WHERE u.created_at > ? GROUP BY u.id",
["2024-01-01"]
);

Error Handling

try {
$result = SQL::table("users", "WRITE")
->where("id", 1)
->update([
"status" => "active", "updated_at" => "NOW()"
]);
// Check slow query warningsif (!empty($result["info"])) {
error_log("Slow query warning: " . $result["info"]);
}
echo"Update successful, affected rows: " . $result["affected_rows"];
} catch (\PDOException$e) {
// Database related errorserror_log("Database error: " . $e->getMessage());
// Handle based on error code$errorCode = $e->getCode();
if ($errorCode === 2006 || $errorCode === 2013) {
// Connection interrupted, system will auto retryecho"Connection exception, please try again later";
} else {
echo"Database operation failed";
}
} catch (\InvalidArgumentException$e) {
// Parameter errorserror_log("Parameter error: " . $e->getMessage());
echo"Request parameters are incorrect";
} catch (\Exception$e) {
// Other errorserror_log("System error: " . $e->getMessage());
echo"System temporarily unavailable, please contact administrator";
}

Performance Monitoring

// Enable detailed loggingerror_reporting(E_ALL);
// Automatically log slow queries (over 20ms)$users = SQL::table("users")
->where("status", "active")
->get();
// Check system logs:// [Info] PD\SQL: [Slow Query: 25.43ms] [SELECT * FROM users WHERE status = ?]

License

This project is licensed under MIT.

Author

邱敬幃 Pardn Chiu


©️ 2024 邱敬幃 Pardn Chiu

About

Lightweight PHP MySQL client with chainable syntax, query builder and read-write separation.

Topics

Resources

Stars

4 stars

Watchers

1 watching

Forks

Releases

Used by

Contributors

Languages