Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Sql Formatter Laravel Package

jdorn/sql-formatter

View on GitHub
Deep Wiki
Context7
## Getting Started
Install via Composer:
```bash
composer require vendor/sql-formatter-package

Register the package in config/app.php under providers (if not auto-discovered). The core class SqlFormatter is now more feature-rich—start with basic usage:

use Vendor\SqlFormatter\SqlFormatter;

$query = "SELECT * FROM users WHERE id = (SELECT MAX(id) FROM posts)";
$formatter = new SqlFormatter();
echo $formatter->format($query); // Pretty-prints SQL

First use case: Debugging raw queries in logs or IDEs. The new compress() method is ideal for CLI debugging:

echo $formatter->compress($query); // Single-line output for copy/pasting

Implementation Patterns

1. Query Debugging & Logging

  • Pretty-printing: Use format() for readable logs or IDE tooltips.
    $logger->info('Query:', ['formatted' => $formatter->format($rawQuery)]);
    
  • CLI-friendly output: Use compress() for one-liners in terminal commands or scripts:
    $compressed = $formatter->compress($query);
    shell_exec("mysql -e \"$compressed\"");
    

2. IDE/Editor Integration

  • Syntax highlighting: The package now supports SQL variables (@var) and binary/hex literals (e.g., 0b1010, 0xFF). Configure your IDE (PHPStorm/VSCode) to use the formatter for SQL snippets.
  • Reserved word handling: Avoid false positives for keywords like count (now only flagged as reserved when followed by (). Safe to use in dynamic queries:
    $column = 'count'; // Won't trigger reserved-word warnings unless used as `count()`
    

3. Performance-Critical Scenarios

  • Batch formatting: The package includes performance improvements. For bulk queries (e.g., migrations or seeders), cache the formatter instance:
    $formatter = new SqlFormatter(); // Reuse instance
    foreach ($queries as $query) {
        $formatter->format($query);
    }
    

4. Dynamic Query Building

  • Safe concatenation: Use the formatter to validate/clean SQL strings before execution:
    $safeQuery = $formatter->format($userInput);
    DB::select($safeQuery); // Reduced risk of syntax errors
    

Gotchas and Tips

Pitfalls

  1. Reserved Word Overrides:

    • The count keyword is now context-sensitive. If you dynamically build queries like:
      $query = "SELECT $column FROM users"; // ❌ Fails if `$column = 'count'`
      
      Use backticks or aliases:
      $query = "SELECT `$column` FROM users"; // ✅ Works
      
  2. Binary/Hex Literals:

    • Older versions may misformat 0b or 0x prefixes. Test edge cases like:
      WHERE data = 0xFF OR flag = 0b1010
      
  3. LIMIT Clause Formatting:

    • The LIMIT clause now groups better with OFFSET:
      -- Before: Might split across lines
      -- After: Cleanly formatted
      SELECT * FROM users LIMIT 10 OFFSET 20
      

Debugging Tips

  • Verify formatting: Use compress() to debug syntax errors in the terminal:
    php artisan tinker
    >>> $formatter->compress($query);
    
  • Coverage gaps: The package claims 100% PHPUnit coverage, but test edge cases like:
    • Nested Common Table Expressions (CTEs).
    • Database-specific syntax (e.g., PostgreSQL RETURNING, MySQL ENGINE).

Extension Points

  1. Custom Reserved Words: Add to the formatter’s config (if supported) or extend the ReservedWords class:

    $formatter->addReservedWords(['my_custom_keyword']);
    
  2. Output Customization: Override the format() method or use a decorator pattern for custom formatting rules.

  3. Performance Profiling: For large datasets, profile the formatter’s impact on query generation time:

    $start = microtime(true);
    $formatter->format($hugeQuery);
    echo microtime(true) - $start; // Benchmark
    

NO_UPDATE_NEEDED would **not** apply here—this release introduces meaningful new features and usage patterns.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
yandex/translate-api
voku/simple_html_dom
league/flysystem-vfs
bkwld/upchuck
filament/spatie-laravel-tags-plugin
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php