Created
January 5, 2025 07:57
-
-
Save HelgeSverre/c5c53ecf76a0d434f8ce65a6297aee86 to your computer and use it in GitHub Desktop.
Laravel Command for generating a database context file for use with AI-coding tools
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Console\Commands; | |
use Illuminate\Console\Command; | |
use Illuminate\Support\Facades\DB; | |
class DumpContext extends Command | |
{ | |
protected $signature = 'db:dump-context'; | |
protected $description = 'Dump database structure and sample records for AI context'; | |
public function handle() | |
{ | |
$output = fopen('database-context.csv', 'w'); | |
// Write CSV header | |
fputcsv($output, [ | |
'Table', | |
'Column', | |
'Type', | |
'Nullable', | |
'Key', | |
'Sample Record 1', | |
'Sample Record 2', | |
'Sample Record 3', | |
]); | |
// Get all tables from the database | |
$tables = collect(DB::select('SHOW TABLES'))->map(function ($val) { | |
return get_object_vars($val)[key(get_object_vars($val))]; | |
})->values(); | |
foreach ($tables as $tableName) { | |
// Get columns info | |
$columnsInfo = DB::select("SHOW COLUMNS FROM {$tableName}"); | |
// Get 3 random records | |
$sampleRecords = DB::table($tableName) | |
->inRandomOrder() | |
->limit(3) | |
->get(); | |
foreach ($columnsInfo as $column) { | |
$row = [ | |
$tableName, | |
$column->Field, | |
$column->Type, | |
$column->Null, | |
$column->Key, | |
]; | |
// Add sample values for this column from each record | |
foreach ($sampleRecords as $record) { | |
$value = $record->{$column->Field} ?? 'NULL'; | |
// Clean up any non-string values for CSV | |
if (is_array($value) || is_object($value)) { | |
$value = json_encode($value); | |
} | |
if ($value instanceof \DateTime) { | |
$value = $value->format('Y-m-d H:i:s'); | |
} | |
$row[] = $value; | |
} | |
fputcsv($output, $row); | |
} | |
// Add a blank line between tables | |
fputcsv($output, []); | |
} | |
fclose($output); | |
$this->info('Database context has been exported to database-context.csv'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment