Polyscope - The agent-first dev environment for Laravel

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
Statamic logo

Statamic

The drop-in ready Laravel CMS you’re been waiting for. Go full-stack or headless, flat file or database – it’s up to you.

Statamic
Securing Laravel logo

Securing Laravel

The essential security resource for Laravel devs, covering everything you need to keep your apps secure. Sign up to receive weekly security tips and monthly in depth articles, diving deep into security concepts you need to know!

Securing Laravel
The Certification of Competence for Laravel logo

The Certification of Competence for Laravel

A community-driven, proctored assessment across 4 levels designed to validate real-world Laravel knowledge, from Junior to mastery-level Artisan. Official Vue.js, Official Nuxt, Angular, React, JS certifications also available.

The Certification of Competence for Laravel
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
Celebian logo

Celebian

Celebian is a social media marketing agency specializing in helping their clients go viral on TikTok. Whether you're looking to reach a bigger audience or gain more Tiktok followers, likes, and views, they've got you covered.

Celebian
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift