Laravel Slower

halilcosdu/laravel-slower image

Laravel Slower stats

Downloads
1
Stars
3
Open Issues
0
Forks
0

View on GitHub →

Laravel Slower: Optimize Your DB Queries with AI

Laravel Slower: Optimize Your DB Queries with AI

Laravel Slower is a powerful package designed for Laravel developers who want to enhance the performance of their applications. It intelligently identifies slow database queries and leverages AI to suggest optimal indexing strategies and other performance improvements. Whether you're debugging or routinely monitoring your application, Laravel Slower provides actionable insights to streamline database interactions.

Installation

You can install the package via composer:

composer require halilcosdu/laravel-slower

You can publish and run the migrations with:

php artisan vendor:publish --tag="slower-migrations"
php artisan migrate
public function up()
{
Schema::create(config('slower.resources.table_name'), function (Blueprint $table) {
$table->id();
$table->boolean('is_analyzed')->default(false)->index();
$table->string('bindings');
$table->longtext('sql');
$table->unsignedInteger('time')->index();
$table->string('connection');
$table->string('connection_name');
$table->longtext('raw_sql');
$table->longtext('recommendation')->nullable();
 
$table->timestamps();
});
}
 
public function down(): void
{
Schema::dropIfExists(config('slower.resources.table_name'));
}

You can publish the config file with:

php artisan vendor:publish --tag="slower-config"

This is the contents of the published config file:

'enabled' => env('SLOWER_ENABLED', true),
'threshold' => env('SLOWER_THRESHOLD', 10000),
'resources' => [
'table_name' => (new SlowLog)->getTable(),
'model' => SlowLog::class,
],
'ai_recommendation' => env('SLOWER_AI_RECOMMENDATION', true), // You can completely disable AI, and then the package will only log slow queries to the database.
'recommendation_model' => env('SLOWER_AI_RECOMMENDATION_MODEL', 'gpt-4'),
'open_ai' => [
'api_key' => env('OPENAI_API_KEY'),
'organization' => env('OPENAI_ORGANIZATION'),
'request_timeout' => env('OPENAI_TIMEOUT'),
],
'prompt' => env('SLOWER_PROMPT',"As a distinguished database optimization expert, your expertise is invaluable for refining SQL queries to achieve maximum efficiency. Please examine the SQL statement provided below. Based on your analysis, could you recommend sophisticated indexing techniques or query modifications that could significantly improve performance and scalability?")
];

Usage

You can register the commands with your scheduler.

php artisan slower:clean /*{days=15} Delete records older than 15 days.*/
php artisan slower:analyze /*Analyze the records where is_analyzed=false*/
protected $commands = [
AnalyzeQuery::class,
SlowLogCleaner::class,
];
 
/**
* Define the application's command schedule.
*/
protected function schedule(Schedule $schedule): void
{
$schedule->command(AnalyzeQuery::class)->runInBackground()->daily();
$schedule->command(SlowLogCleaner::class)->runInBackground()->daily();
}
$model = \HalilCosdu\Slower\Models\SlowLog::first();
 
\HalilCosdu\Slower\Facades\Slower::analyze($model): Model;
 
dd($model->raw_sql); /*select count(*) as aggregate from "product_prices" where "product_id" = '1' and "price" = '0' and "discount_total" > '0'*/
 
dd($model->recommendation);

Example Recommendation

In order to improve database performance and scalability, here are some suggestions below:

  1. Indexing: Effective database indexing can significantly speed up query performance. For your query, consider adding a combined (composite) index on product_id, price, and discount_total. This index would work well because the where clause covers all these columns.
CREATE INDEX idx_product_prices
ON product_prices (product_id, price, discount_total);

(Note: The order of the columns in the index might depend on the selectivity of the columns and the data distribution. Therefore, you might have to reorder them depending on your specific situation.)

  1. Data Types: Ensure that the values being compared are of appropriate data types. Comparing or converting inappropriate data types at run time will slow down the search. It appears that you're using string comparisons ('1') for product_id, price, and discount_total which are likely numerical columns. Remove the quotes for these where clause conditions.

Updated Query:

SELECT COUNT(*) AS aggregate
FROM product_prices
WHERE product_id = 1
AND price = 0
AND discount_total > 0;
  1. ANALYZE: Another practice to improve query performance could be running the ANALYZE command. This command collects statistics about the contents of tables in the database, and stores the results in the pg_statistic system catalog. Subsequently, the query planner uses these statistics to help determine the most efficient execution plans for queries.
ANALYZE product_prices;

Remember to periodically maintain your index to keep up with the CRUD operations that could lead to index fragmentation. Depending on your DBMS, you might want to REBUILD or REORGANIZE your indices.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.


Halilcosdu Laravel Slower Related Articles

Liminal: A Browser-Based IDE for Laravel Powered by WebAssembly image

Liminal: A Browser-Based IDE for Laravel Powered by WebAssembly

Read article
Optimize Your Eloquent Queries with AI image

Optimize Your Eloquent Queries with AI

Read article
Take part in the State of Laravel Survey 2023 image

Take part in the State of Laravel Survey 2023

Read article
Laravel Dusk Browser Testing: Best Practices & Tips image

Laravel Dusk Browser Testing: Best Practices & Tips

Read article
Mistakes I've Made in AWS image

Mistakes I've Made in AWS

Read article
18 Tips to Optimize Your Laravel Database Queries image

18 Tips to Optimize Your Laravel Database Queries

Read article
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
Typesense Search logo

Typesense Search

Typesense is an open source, blazing-fast search engine, optimized for helping you build delightful search experiences for your sites and apps. Natively integrated with Laravel Scout.

Typesense Search
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $9500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Tighten logo

Tighten

We help companies turn great ideas into amazing apps, products, and services.

Tighten