internal/postgres: update DeleteModule logic

DeleteModule is updated to:

* Remove the DELETE from search_documents, since deleting rows from
  units will cascade to search_documents due to
  search_documents_unit_id_fkey

* Delete the module_path from the paths table if it no longer exists at
  any version in our database, which will also delete it from
  latest_module_versions.

Fixes golang/go#47748

Change-Id: If3b972fafbd42086c8c559b513630f6c12de6dba
Reviewed-on: https://go-review.googlesource.com/c/pkgsite/+/342891
Trust: Julie Qiu <julie@golang.org>
Run-TryBot: Julie Qiu <julie@golang.org>
TryBot-Result: kokoro <noreply+kokoro@google.com>
Reviewed-by: Jonathan Amsterdam <jba@google.com>
diff --git a/internal/postgres/delete.go b/internal/postgres/delete.go
index 806d83b..e447076 100644
--- a/internal/postgres/delete.go
+++ b/internal/postgres/delete.go
@@ -29,16 +29,21 @@
 		if _, err = tx.Exec(ctx, `DELETE FROM version_map WHERE module_path = $1 AND resolved_version = $2`, modulePath, resolvedVersion); err != nil {
 			return err
 		}
-		if _, err = tx.Exec(ctx, `DELETE FROM search_documents WHERE module_path = $1 AND version = $2`, modulePath, resolvedVersion); err != nil {
-			return err
-		}
 
 		var x int
 		err = tx.QueryRow(ctx, `SELECT 1 FROM modules WHERE module_path=$1 LIMIT 1`, modulePath).Scan(&x)
 		if err != sql.ErrNoRows || err == nil {
 			return err
 		}
-		// No versions of this module exist; remove it from imports_unique.
+		// No versions of this module exist; remove it from paths and
+		// imports_unique.
+		//
+		// Deleting from paths will also cascade a DELETE to
+		// latest_module_versions. Other tables should already have removed any
+		// rows referencing the paths table.
+		if _, err = tx.Exec(ctx, `DELETE FROM paths WHERE path = $1`, modulePath); err != nil {
+			return err
+		}
 		return deleteModuleFromImportsUnique(ctx, tx, modulePath)
 	})
 }