github.com/quay/claircore@v1.5.28/test/postgres/distribution_scanartifact.go (about)

     1  package postgres
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/jackc/pgx/v4/pgxpool"
     8  
     9  	"github.com/quay/claircore"
    10  	"github.com/quay/claircore/indexer"
    11  )
    12  
    13  // InsertDistScanArtifacts will create DistributionScanArtifacts linking the
    14  // layer hash, dist, and scanner artifacts.
    15  //
    16  // If multiple scanners are provided they will be linked in i % n fashion where
    17  // "i" is the current index of the dists slice and "n" is the length of the
    18  // scnrs slice.
    19  func InsertDistScanArtifacts(ctx context.Context, pool *pgxpool.Pool, layerHash claircore.Digest, dists []*claircore.Distribution, scnrs indexer.VersionedScanners) error {
    20  	query := `
    21  WITH
    22  	layer_insert
    23  		AS (
    24  			INSERT
    25  			INTO
    26  				layer (hash)
    27  			VALUES
    28  				($1)
    29  			ON CONFLICT
    30  				(hash)
    31  			DO
    32  				UPDATE SET hash = $1
    33  			RETURNING
    34  				id AS layer_id
    35  		)
    36  INSERT
    37  INTO
    38  	dist_scanartifact (layer_id, dist_id, scanner_id)
    39  VALUES
    40  	((SELECT layer_id FROM layer_insert), $2, $3);
    41  `
    42  
    43  	insertLayer := `
    44  INSERT INTO layer (hash) VALUES ($1);
    45  `
    46  
    47  	_, err := pool.Exec(ctx, insertLayer, &layerHash)
    48  	if err != nil {
    49  		return fmt.Errorf("failed to insert layer %v", err)
    50  	}
    51  
    52  	n := len(scnrs)
    53  	for i, dist := range dists {
    54  		nn := i % n
    55  		_, err := pool.Exec(ctx, query, &layerHash, &dist.ID, &nn)
    56  		if err != nil {
    57  			return fmt.Errorf("failed to insert scan artifact %v", err)
    58  		}
    59  	}
    60  
    61  	return nil
    62  }