laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 31 forks source link

Artisan command to truncate a specific table or all tables in database #2647

Closed RounakSimlai closed 3 years ago

RounakSimlai commented 3 years ago

@taylorotwell @JeffreyWay @jbrooksuk @driesvints @claudiodekker

I have created and using this custom artisan command named 'truncate' to truncate tables in a SQLITE Database.

<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class truncate extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'truncate {table}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Truncates all tables or a single table in the database and resets auto-increment id ';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $table = $this->argument('table');
        if ($table == "all") {
            DB::statement("PRAGMA foreign_keys = OFF");
            $tables = DB::select("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name");
            foreach ($tables as $table) {
                $name = $table->name;
                //if you don't want to truncate migrations
                if ($name == 'migrations') {
                    continue;
                }
                //if you don't want to truncate user data
                if ($name == 'users') {
                    continue;
                }
                DB::table($name)->truncate();
            }
            DB::statement("PRAGMA foreign_keys = ON");
            return $this->info("Truncated all tables successfully");
        }
        else{
            DB::statement("PRAGMA foreign_keys = OFF");
            DB::table($table)->truncate();
            DB::statement("PRAGMA foreign_keys = ON");
            return $this->info("Truncated $table table successfully");
        }
    }
}
driesvints commented 3 years ago

Please don't mass-mention people