ejaculated_dateの重複エラーをcatch

This commit is contained in:
shibafu 2020-05-21 23:13:39 +09:00
parent fa4827f382
commit 8681c328d0
2 changed files with 34 additions and 3 deletions

View File

@ -8,9 +8,11 @@ use App\Rules\CsvDateTime;
use App\Tag;
use App\User;
use Carbon\Carbon;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use League\Csv\Reader;
use Throwable;
class CheckinCsvImporter
{
@ -78,9 +80,23 @@ class CheckinCsvImporter
continue;
}
$ejaculation->save();
if (!empty($tags)) {
$ejaculation->tags()->sync(collect($tags)->pluck('id'));
DB::beginTransaction();
try {
$ejaculation->save();
if (!empty($tags)) {
$ejaculation->tags()->sync(collect($tags)->pluck('id'));
}
DB::commit();
} catch (QueryException $e) {
DB::rollBack();
if ($e->errorInfo[0] === '23505') {
$errors[] = "{$line} 行 : すでにこの日時のチェックインデータが存在します。";
continue;
}
throw $e;
} catch (Throwable $e) {
DB::rollBack();
throw $e;
}
}

View File

@ -265,4 +265,19 @@ class CheckinCsvImporterTest extends TestCase
$this->assertSame(1, $user->ejaculations()->count());
$this->assertEquals(Ejaculation::SOURCE_CSV, $ejaculation->source);
}
public function testDontThrowUniqueKeyViolation()
{
$user = factory(User::class)->create();
factory(Ejaculation::class)->create([
'user_id' => $user->id,
'ejaculated_date' => Carbon::create(2020, 1, 23, 6, 1, 0, 'Asia/Tokyo')
]);
$this->expectException(CsvImportException::class);
$this->expectExceptionMessage('2 行 : すでにこの日時のチェックインデータが存在します。');
$importer = new CheckinCsvImporter($user, __DIR__ . '/../../fixture/Csv/date.utf8.csv');
$importer->execute();
}
}