Copyright 2019 The Go Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

package postgres

import (
	
	
	
	
	
	
	
	
	
	

	
	
	
	
	
	
	
	
	
	
	
)
InsertModule inserts a version into the database using db.saveVersion, along with a search document corresponding to each of its packages. It returns whether the version inserted was the latest for the given module path.
func ( *DB) ( context.Context,  *internal.Module,  *internal.LatestModuleVersions) ( bool,  error) {
	defer func() {
		if  == nil {
			derrors.WrapStack(&, "DB.InsertModule(ctx, nil)")
			return
		}
		derrors.WrapStack(&, "DB.InsertModule(ctx, Module(%q, %q))", .ModulePath, .Version)
	}()

	if  := validateModule();  != nil {
		return false, 
The proxy accepts modules with zero commit times, but they are bad.
	if .CommitTime.IsZero() {
		return false, fmt.Errorf("empty commit time: %w", derrors.BadModule)
Compare existing data from the database, and the module to be inserted. Rows that currently exist should not be missing from the new module. We want to be sure that we will overwrite every row that pertains to the module.
	if  := .comparePaths(, );  != nil {
		return false, 
	}
If we are not bypassing license checking, remove data for non-redistributable modules.
		.RemoveNonRedistributableData()
	}
	return .saveModule(, , )
}
saveModule inserts a Module into the database along with its packages, imports, and licenses. If any of these rows already exist, the module and corresponding will be deleted and reinserted. If the module is malformed then insertion will fail. saveModule reports whether the version inserted is the latest known version for the module path (that is, the latest minor version of the module) A derrors.InvalidArgument error will be returned if the given module and licenses are invalid.
func ( *DB) ( context.Context,  *internal.Module,  *internal.LatestModuleVersions) ( bool,  error) {
	defer derrors.WrapStack(&, "saveModule(ctx, tx, Module(%q, %q))", .ModulePath, .Version)
	,  := trace.StartSpan(, "saveModule")
	defer .End()
Insert paths first in a separate transaction, because we've seen various problems like deadlock when we do it as part of the main transaction below. Without RepeatableRead, insertPaths can fail to return some paths. For details, see the commit message for https://golang.org/cl/290269.
	var  map[string]int
	 = .db.Transact(, sql.LevelRepeatableRead, func( *database.DB) error {
		var  error
		,  = insertPaths(, , )
		return 
	})
	if  != nil {
		return false, 
	}

	 = .db.Transact(, sql.LevelRepeatableRead, func( *database.DB) error {
		,  := insertModule(, , )
		if  != nil {
			return 
Compare existing data from the database, and the module to be inserted. Rows that currently exist should not be missing from the new module. We want to be sure that we will overwrite every row that pertains to the module.
		if  := .compareLicenses(, , .Licenses);  != nil {
			return 
		}
		if  := insertLicenses(, , , );  != nil {
			return 
		}
		if  := .insertUnits(, , , , );  != nil {
			return 
		}
Obtain a transaction-scoped exclusive advisory lock on the module path. The transaction that holds the lock is the only one that can execute the subsequent code on any module with the given path. That means that conflicts from two transactions both believing they are working on the latest version of a given module cannot happen. The lock is released automatically at the end of the transaction.
		if  := lock(, , .ModulePath);  != nil {
			return 
		}
We only insert into imports_unique and search_documents if this is the latest version of the module. By the time this function is called, we've already inserted into the modules table. So the query in getLatestGoodVersion will include this version.
		,  := getLatestGoodVersion(, , .ModulePath, )
		if  != nil {
			return 
Update the DB with the latest version, even if we are not the latest. (Perhaps we just learned of a retraction that affects the good latest version.)
		if  := updateLatestGoodVersion(, , .ModulePath, );  != nil {
			return 
		}
		 = .Version == 
		if ! {
			return nil
Here, this module is the latest good version.

		if  := insertImportsUnique(, , );  != nil {
			return 
		}
If the most recent version of this module has an alternative module path, then do not insert its packages into search_documents. This happens when a module that initially does not have a go.mod file is forked or fetched via some non-canonical path (such as an alternative capitalization), and then in a later version acquires a go.mod file. To take an actual example: github.com/sirupsen/logrus@v1.1.0 has a go.mod file that establishes that path as canonical. But v1.0.6 does not have a go.mod file. So the miscapitalized path github.com/Sirupsen/logrus at v1.1.0 is marked as an alternative path (code 491) by internal/fetch.FetchModule and is not inserted into the DB, but at v1.0.6 it is considered valid, and we end up here. We still insert github.com/Sirupsen/logrus@v1.0.6 in the modules table and friends so that users who import it can find information about it, but we don't want it showing up in search results. Note that we end up here only if we first saw the alternative version (github.com/Sirupsen/logrus@v1.1.0 in the example) and then see the valid one. The "if code == 491" section of internal/worker.fetchAndUpdateState handles the case where we fetch the versions in the other order.
		,  := isAlternativeModulePath(, , .ModulePath)
		if  != nil {
			return 
		}
		if  {
			log.Infof(, "%s@%s: not inserting into search documents", .ModulePath, .Version)
			return nil
Insert the module's packages into search_documents.
		return upsertSearchDocuments(, , )
	})
	if  != nil {
		return false, 
	}
	return , nil
}
isAlternativeModulePath reports whether the module path is "alternative," that is, it disagrees with the module path in the go.mod file. This can happen when someone forks a repo and does not change the go.mod file, or when the path used to get a module is a case variant of the correct one (e.g. github.com/Sirupsen/logrus vs. github.com/sirupsen/logrus).
func ( context.Context,  *database.DB,  string) ( bool,  error) {
	defer derrors.WrapStack(&, "isAlternativeModulePath(%q)", )
See if the cooked latest version has a status of 491 (AlternativeModule).
	var  int
	switch  := .QueryRow(, `
		SELECT s.status
		FROM paths p, latest_module_versions l, module_version_states s
		WHERE p.id = l.module_path_id
		AND p.path = s.module_path
		AND l.cooked_version = s.version
	`).Scan(&);  {
Not enough information; assume false so we don't omit a valid module from search.
		return false, nil
	case nil:
		return  == derrors.ToStatus(derrors.AlternativeModule), nil
	default:
		return false, 
	}
}

func ( context.Context,  *database.DB,  *internal.Module) ( int,  error) {
	,  := trace.StartSpan(, "insertModule")
	defer .End()
	defer derrors.WrapStack(&, "insertModule(ctx, %q, %q)", .ModulePath, .Version)
	,  := json.Marshal(.SourceInfo)
	if  != nil {
		return 0, 
	}
	,  := version.ParseType(.Version)
	if  != nil {
		return 0, 
	}
	var  int
	 = .QueryRow(,
		`INSERT INTO modules(
			module_path,
			version,
			commit_time,
			sort_version,
			version_type,
			series_path,
			source_info,
			redistributable,
			has_go_mod,
			incompatible)
		VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)
		ON CONFLICT
			(module_path, version)
		DO UPDATE SET
			source_info=excluded.source_info,
			redistributable=excluded.redistributable
		RETURNING id`,
		.ModulePath,
		.Version,
		.CommitTime,
		version.ForSorting(.Version),
		,
		.SeriesPath(),
		,
		.IsRedistributable,
		.HasGoMod,
		version.IsIncompatible(.Version),
	).Scan(&)
	if  != nil {
		return 0, 
	}
	return , nil
}

func ( context.Context,  *database.DB,  *internal.Module,  int) ( error) {
	,  := trace.StartSpan(, "insertLicenses")
	defer .End()
	defer derrors.WrapStack(&, "insertLicenses(ctx, %q, %q)", .ModulePath, .Version)
	var  []interface{}
	for ,  := range .Licenses {
		var  []byte
		if .Coverage.Percent == 0 && .Coverage.Match == nil {
			,  = json.Marshal(.OldCoverage)
			if  != nil {
				return fmt.Errorf("marshalling %+v: %v", .OldCoverage, )
			}
		} else {
			,  = json.Marshal(.Coverage)
			if  != nil {
				return fmt.Errorf("marshalling %+v: %v", .Coverage, )
			}
		}
		 = append(, .FilePath,
			makeValidUnicode(string(.Contents)), pq.Array(.Types), ,
			)
	}
	if len() > 0 {
		 := []string{
			"file_path",
			"contents",
			"types",
			"coverage",
			"module_id",
		}
		return .BulkUpsert(, "licenses", , ,
			[]string{"module_id", "file_path"})
	}
	return nil
}
insertImportsUnique inserts and removes rows from the imports_unique table. It should only be called if the given module's version is the latest.
func ( context.Context,  *database.DB,  *internal.Module) ( error) {
	,  := trace.StartSpan(, "insertImportsUnique")
	defer .End()
	defer derrors.WrapStack(&, "insertImportsUnique(%q, %q)", .ModulePath, .Version)
Remove the previous rows for this module. We'll replace them with new ones below.
	if ,  := .Exec(,
		`DELETE FROM imports_unique WHERE from_module_path = $1`,
		.ModulePath);  != nil {
		return 
	}

	var  []interface{}
	for ,  := range .Units {
		for ,  := range .Imports {
			 = append(, .Path, .ModulePath, )
		}
	}
	if len() == 0 {
		return nil
	}
	 := []string{"from_path", "from_module_path", "to_path"}
	return .BulkUpsert(, "imports_unique", , , )
}
insertUnits inserts the units for a module into the units table. It can be assume that at least one unit is a package, and there are one or more units in the module.
func ( *DB) ( context.Context,  *database.DB,  *internal.Module,  int,  map[string]int) ( error) {
	defer derrors.WrapStack(&, "insertUnits(ctx, tx, %q, %q)", .ModulePath, .Version)
	,  := trace.StartSpan(, "insertUnits")
	defer .End()
Sort to ensure proper lock ordering, avoiding deadlocks. We have seen deadlocks on package_imports and documentation. They can occur when processing two versions of the same module, which happens regularly.
	sort.Slice(.Units, func(,  int) bool {
		return .Units[].Path < .Units[].Path
	})
	for ,  := range .Units {
		sort.Strings(.Imports)
	}
	var (
		         []string
		    []interface{}
		  = map[string]*internal.Readme{}
		    = map[string][]*internal.Documentation{}
		 = map[string][]string{}
		  = map[int]string{}
	)
	for ,  := range .Units {
		var ,  []string
		for ,  := range .Licenses {
If a license file has no detected license types, we still need to record it as applicable to the package, because we want to fail closed (meaning if there is a LICENSE file containing unknown licenses, we assume them not to be permissive of redistribution.)
				 = append(, "")
				 = append(, .FilePath)
			} else {
				for ,  := range .Types {
					 = append(, )
					 = append(, .FilePath)
				}
			}
		}
		 := internal.V1Path(.Path, .ModulePath)
		,  := [.Path]
		if ! {
			return fmt.Errorf("no entry in paths table for %q; should be impossible", .Path)
		}
		[] = .Path
		 = append(,
			,
			,
			[],
			.Name,
			pq.Array(),
			pq.Array(),
			.IsRedistributable,
		)
		if .Readme != nil {
			[.Path] = .Readme
		}
		for ,  := range .Documentation {
			if .Source == nil {
				return fmt.Errorf("insertUnits: unit %q missing source files for %q, %q", .Path, .GOOS, .GOARCH)
			}
		}
		[.Path] = .Documentation
		if len(.Imports) > 0 {
			[.Path] = .Imports
		}
		 = append(, .Path)
	}
	,  := insertUnits(, , )
	if  != nil {
		return 
	}
	 := map[string]int{}
	for ,  := range  {
		[[]] = 
	}
	if  := insertReadmes(, , , , );  != nil {
		return 
	}
	if  := insertDocs(, , , , );  != nil {
		return 
	}
	if  := insertImports(, , , , );  != nil {
		return 
	}

	,  := getDocIDsForPath(, , , )
	if  != nil {
		return 
Only update symbols if the version type is release.
	,  := version.ParseType(.Version)
	if  != nil {
		return 
	}
	if  == version.TypeRelease {
		return insertSymbols(, , .ModulePath, .Version, , )
	}
	return nil
}
insertPaths inserts all paths in m that aren't already there, and returns a map from each path to its ID in the paths table. Should be run inside a transaction.
Read all existing paths for this module, to avoid a large bulk upsert. (We've seen these bulk upserts hang for so long that they time out (10 minutes)).
	 := map[string]bool{}
	for ,  := range .Units {
		[.Path] = true
		[internal.V1Path(.Path, .ModulePath)] = true
		[internal.SeriesPathForModule(.ModulePath)] = true
	}
	var  []string
	for  := range  {
		 = append(, )
	}
	return upsertPaths(, , )
}

func ( context.Context,  *database.DB,  []interface{}) ( map[int]int,  error) {
	defer derrors.WrapAndReport(&, "insertUnits")
Insert data into the units table.
	 := []string{
		"path_id",
		"module_id",
		"v1path_id",
		"name",
		"license_types",
		"license_paths",
		"redistributable",
	}
	 := []string{"path_id", "module_id"}
	 := []string{"id", "path_id"}
Check to see if any rows have the same path_id and module_id. For golang/go#43899.
	 := map[[2]interface{}]bool{}
	for  := 0;  < len();  += len() {
		 := [2]interface{}{[], [+1]}
		if [] {
			log.Errorf(, "insertUnits: %v occurs twice", )
		} else {
			[] = true
		}
	}

	 = map[int]int{}
	if  := .BulkUpsertReturning(, "units", , ,
		, , func( *sql.Rows) error {
			var ,  int
			if  := .Scan(&, &);  != nil {
				return 
			}
			[] = 
			return nil
		});  != nil {
		log.Errorf(, "got error doing bulk upsert to units (see below); logging path_id, module_id for golang.org/issue/43899")
		for  := 0;  < len();  += len() {
			log.Errorf(, "%v, %v", [], [+1])
		}
		return nil, 
	}
	return , nil
}

func ( context.Context,  *database.DB,
	 []string,
	 map[string]int,
	 map[string][]*internal.Documentation) ( error) {
	defer derrors.WrapStack(&, "insertDocs(%d paths)", len())

	 := func() chan database.RowItem {
		 := make(chan database.RowItem)
		go func() {
			for ,  := range  {
				 := []
				for ,  := range [] {
					if .GOOS == "" || .GOARCH == "" {
						 <- database.RowItem{Err: errors.New("empty GOOS or GOARCH")}
					}
					 <- database.RowItem{Values: []interface{}{, .GOOS, .GOARCH, .Synopsis, .Source}}
				}
			}
			close()
		}()
		return 
	}

	 := []string{"unit_id", "goos", "goarch"}
	 := append(, "synopsis", "source")
	return .CopyUpsert(, "documentation",
		, database.CopyFromChan(()), , "id")
}
getDocIDsForPath returns a map of the unit path to documentation.id to documentation, for all of the docs in pathToDocs. This will be used to insert data into the documentation_symbols.documentation_id column.
func ( context.Context,  *database.DB,
	 map[string]int,
	 map[string][]*internal.Documentation) ( map[string]map[int]*internal.Documentation,  error) {
	defer derrors.WrapStack(&, "getDocIDsForPath")

	 := map[string]map[int]*internal.Documentation{}
	 := map[int]string{}
	 := func( *sql.Rows) error {
		var (
			,    int
			,  string
		)
		if  := .Scan(&, &, &, &);  != nil {
			return 
		}
		 := []
		if ,  := []; ! {
			[] = map[int]*internal.Documentation{}
		}
		for ,  := range [] {
			if .GOOS ==  && .GOARCH ==  {
				[][] = 
			}
		}
		return nil
	}

	var  []int
	for  := range  {
		[[]] = 
		 = append(, [])
	}

	 := `SELECT id, unit_id, goos, goarch FROM documentation WHERE unit_id = ANY($1)`
	if  := .RunQuery(, , , pq.Array());  != nil {
		return nil, 
	}
	return , nil
}

func ( context.Context,  *database.DB,
	 []string,
	 map[string]int,
	 map[string][]string) ( error) {
	defer derrors.WrapStack(&, "insertImports")

	var  []interface{}
	for ,  := range  {
		,  := []
		if ! {
			continue
		}
		 := []
		for ,  := range  {
			 = append(, , )
		}
	}
	 := []string{"unit_id", "to_path"}
	return .BulkUpsert(, "package_imports", , , )
}

func ( context.Context,  *database.DB,
	 []string,
	 map[string]int,
	 map[string]*internal.Readme) ( error) {
	defer derrors.WrapStack(&, "insertReadmes")

	var  []interface{}
	for ,  := range  {
		,  := []
		if ! {
			continue
		}
Do not add a readme with empty or zero contents.
		 := makeValidUnicode(.Contents)
		if len() == 0 {
			continue
		}

		 := []
		 = append(, , .Filepath, )
	}
	 := []string{"unit_id", "file_path", "contents"}
	return .BulkUpsert(, "readmes", , , []string{"unit_id"})
}
ReInsertLatestVersion checks that the latest good version matches the version in search_documents. If it doesn't, it inserts the latest good version into search_documents and imports_unique.
func ( *DB) ( context.Context,  string) ( error) {
	defer derrors.WrapStack(&, "ReInsertLatestVersion(%q)", )

Hold the lock on the module path throughout.
		if  := lock(, , );  != nil {
			return 
		}

		, ,  := getLatestModuleVersions(, , )
		if  != nil {
			return 
		}
		if  == nil {
			log.Debugf(, "ReInsertLatestVersion(%q): no latest-version info", )
			return nil
		}
TODO(golang/go#44710): once we are confident that latest_module_versions is accurate and up to date, we can assume that a missing GoodVersion should mean that there are no good versions remaining, and we should remove the current module from search_documents.
			log.Debugf(, "ReInsertLatestVersion(%q): no good version", )
			return nil
Is the latest good version in search_documents?
		var  int
		switch  := .QueryRow(, `
			SELECT 1
			FROM search_documents
			WHERE module_path = $1
			AND version = $2
		`, , .GoodVersion).Scan(&);  {
		case sql.ErrNoRows:
			break
		case nil:
			log.Debugf(, "ReInsertLatestVersion(%q): good version %s found in search_documents; doing nothing",
				, .GoodVersion)
			return nil
		default:
			return 
		}
The latest good version is not in search_documents. Is this an alternative module path?
		,  := isAlternativeModulePath(, , )
		if  != nil {
			return 
		}
		if  {
			log.Debugf(, "ReInsertLatestVersion(%q): alternative module path; doing nothing", )
			return nil
		}
Not an alternative module path. Read the module information at the latest good version.
		,  := getPackagesInUnit(, , , , .GoodVersion, -1, .bypassLicenseCheck)
		if  != nil {
			return 
We only need the readme for the module.
		,  := getModuleReadme(, , , .GoodVersion)
		if  != nil && !errors.Is(, derrors.NotFound) {
			return 
		}
Insert into search_documents.
		for ,  := range  {
			if isInternalPackage(.Path) {
				continue
			}
			 := UpsertSearchDocumentArgs{
				PackagePath: .Path,
				ModulePath:  ,
				Version:     .GoodVersion,
				Synopsis:    .Synopsis,
			}
			if .Path ==  &&  != nil {
				.ReadmeFilePath = .Filepath
				.ReadmeContents = .Contents
			}
			if  := UpsertSearchDocument(, , );  != nil {
				return 
			}
		}
Remove old rows from imports_unique.
		if ,  := .Exec(, `DELETE FROM imports_unique WHERE from_module_path = $1`, );  != nil {
			return 
		}
Insert this version's imports into imports_unique.
		if ,  := .Exec(, `
			INSERT INTO imports_unique (from_path, from_module_path, to_path)
			SELECT p.path, m.module_path, i.to_path
			FROM units u
			INNER JOIN package_imports i ON (u.id = i.unit_id)
			INNER JOIN paths p ON (p.id = u.path_id)
			INNER JOIN modules m ON (m.id=u.module_id)
			WHERE m.module_path = $1 and m.version = $2
		`, , .GoodVersion);  != nil {
			return 
		}

		log.Debugf(, "ReInsertLatestVersion(%q): re-inserted at latest good version %s", , .GoodVersion)
		return nil
	})
}
lock obtains an exclusive, transaction-scoped advisory lock on modulePath.
func ( context.Context,  *database.DB,  string) ( error) {
	defer derrors.WrapStack(&, "lock(%s)", )
	if !.InTransaction() {
		return errors.New("not in a transaction")
Postgres advisory locks use a 64-bit integer key. Convert modulePath to a key by hashing. This can result in collisions (two module paths hashing to the same key), but they are unlikely and at worst will slow things down a bit. We use the FNV hash algorithm from the standard library. It fits into 64 bits unlike a crypto hash, and is stable across processes, unlike hash/maphash.
	 := fnv.New64()
	io.WriteString(, ) // Writing to a hash.Hash never returns an error.
	 := int64(.Sum64())
	if !database.QueryLoggingDisabled {
		log.Debugf(, "locking %s (%d) ...", , )
See https://www.postgresql.org/docs/11/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS.
	if ,  := .Exec(, `SELECT pg_advisory_xact_lock($1)`, );  != nil {
		return 
	}
	if !database.QueryLoggingDisabled {
		log.Debugf(, "locking %s (%d) succeeded", , )
	}
	return nil
}
validateModule checks that fields needed to insert a module into the database are present. Otherwise, it returns an error listing the reasons the module cannot be inserted. Since the problems it looks for are most likely on our end, the underlying error it returns is always DBModuleInsertInvalid, meaning that this module should be reprocessed.
func ( *internal.Module) ( error) {
	defer func() {
		if  != nil {
			 = fmt.Errorf("%v: %w", , derrors.DBModuleInsertInvalid)
			if  != nil {
				derrors.WrapStack(&, "validateModule(%q, %q)", .ModulePath, .Version)
			}
		}
	}()

	if  == nil {
		return fmt.Errorf("nil module")
	}
	var  []string
	if .Version == "" {
		 = append(, "no specified version")
	}
	if .ModulePath == "" {
		 = append(, "no module path")
	}
	if .ModulePath != stdlib.ModulePath {
		if  := module.CheckPath(.ModulePath);  != nil {
			 = append(, fmt.Sprintf("invalid module path (%s)", ))
		}
		if !semver.IsValid(.Version) {
			 = append(, "invalid version")
		}
	}
	if len(.Packages()) == 0 {
		 = append(, "module does not have any packages")
	}
	if len() != 0 {
		return fmt.Errorf("cannot insert module %q: %s", .Version, strings.Join(, ", "))
	}
	return nil
}
compareLicenses compares m.Licenses with the existing licenses for m.ModulePath and m.Version in the database. It returns an error if there are licenses in the licenses table that are not present in m.Licenses.
func ( *DB) ( context.Context,  int,  []*licenses.License) ( error) {
	defer derrors.WrapStack(&, "compareLicenses(ctx, %d)", )
	,  := .getModuleLicenses(, )
	if  != nil {
		return 
	}

	 := map[string]bool{}
	for ,  := range  {
		[.FilePath] = true
	}
	for ,  := range  {
		if ,  := [.FilePath]; ! {
			return fmt.Errorf("expected license %q in module: %w", .FilePath, derrors.DBModuleInsertInvalid)
		}
	}
	return nil
}
comparePaths compares m.Directories with the existing directories for m.ModulePath and m.Version in the database. It returns an error if there are paths in the paths table that are not present in m.Directories.
func ( *DB) ( context.Context,  *internal.Module) ( error) {
	defer derrors.WrapStack(&, "comparePaths(ctx, %q, %q)", .ModulePath, .Version)
	,  := .getPathsInModule(, .ModulePath, .Version)
	if  != nil {
		return 
	}
	 := map[string]bool{}
	for ,  := range .Units {
		[.Path] = true
	}
	for ,  := range  {
		if ,  := [.path]; ! {
			return fmt.Errorf("expected unit %q in module: %w", .path, derrors.DBModuleInsertInvalid)
		}
	}
	return nil
}
DeleteModule deletes a Version from the database.
func ( *DB) ( context.Context, ,  string) ( error) {
	defer derrors.WrapStack(&, "DeleteModule(ctx, db, %q, %q)", , )
We only need to delete from the modules table. Thanks to ON DELETE CASCADE constraints, that will trigger deletions from all other tables.
		const  = `DELETE FROM modules WHERE module_path=$1 AND version=$2`
		if ,  := .Exec(, , , );  != nil {
			return 
		}
		if _,  = .Exec(, `DELETE FROM version_map WHERE module_path = $1 AND resolved_version = $2`, , );  != nil {
			return 
		}
		if _,  = .Exec(, `DELETE FROM search_documents WHERE module_path = $1 AND version = $2`, , );  != nil {
			return 
		}

		var  int
		 = .QueryRow(, `SELECT 1 FROM modules WHERE module_path=$1 LIMIT 1`, ).Scan(&)
		if  != sql.ErrNoRows ||  == nil {
			return 
No versions of this module exist; remove it from imports_unique.
		_,  = .Exec(, `DELETE FROM imports_unique WHERE from_module_path = $1`, )
		return 
	})
}
makeValidUnicode removes null runes from a string that will be saved in a column of type TEXT, because pq doesn't like them. It also replaces non-unicode characters with the Unicode replacement character, which is the behavior of for ... range on strings.
If s is valid and has no zeroes, don't copy it.
	 := false
	for ,  := range  {
		if  == 0 {
			 = true
			break
		}
	}
	if ! && utf8.ValidString() {
		return 
	}

	var  strings.Builder
	for ,  := range  {
		if  != 0 {
			.WriteRune()
		}
	}
	return .String()