forked from tangled.org/core
Monorepo for Tangled — https://tangled.org
at master 2.4 kB view raw
1package db 2 3import ( 4 "fmt" 5 "strings" 6 "time" 7 8 "github.com/go-git/go-git/v5/plumbing" 9 "github.com/ipfs/go-cid" 10 "tangled.org/core/appview/models" 11 "tangled.org/core/orm" 12) 13 14func AddArtifact(e Execer, artifact models.Artifact) error { 15 _, err := e.Exec( 16 `insert or ignore into artifacts ( 17 did, 18 rkey, 19 repo_at, 20 tag, 21 created, 22 blob_cid, 23 name, 24 size, 25 mimetype 26 ) 27 values (?, ?, ?, ?, ?, ?, ?, ?, ?)`, 28 artifact.Did, 29 artifact.Rkey, 30 artifact.RepoAt, 31 artifact.Tag[:], 32 artifact.CreatedAt.Format(time.RFC3339), 33 artifact.BlobCid.String(), 34 artifact.Name, 35 artifact.Size, 36 artifact.MimeType, 37 ) 38 return err 39} 40 41func GetArtifact(e Execer, filters ...orm.Filter) ([]models.Artifact, error) { 42 var artifacts []models.Artifact 43 44 var conditions []string 45 var args []any 46 for _, filter := range filters { 47 conditions = append(conditions, filter.Condition()) 48 args = append(args, filter.Arg()...) 49 } 50 51 whereClause := "" 52 if conditions != nil { 53 whereClause = " where " + strings.Join(conditions, " and ") 54 } 55 56 query := fmt.Sprintf(`select 57 did, 58 rkey, 59 repo_at, 60 tag, 61 created, 62 blob_cid, 63 name, 64 size, 65 mimetype 66 from artifacts %s`, 67 whereClause, 68 ) 69 70 rows, err := e.Query(query, args...) 71 if err != nil { 72 return nil, err 73 } 74 defer rows.Close() 75 76 for rows.Next() { 77 var artifact models.Artifact 78 var createdAt string 79 var tag []byte 80 var blobCid string 81 82 if err := rows.Scan( 83 &artifact.Did, 84 &artifact.Rkey, 85 &artifact.RepoAt, 86 &tag, 87 &createdAt, 88 &blobCid, 89 &artifact.Name, 90 &artifact.Size, 91 &artifact.MimeType, 92 ); err != nil { 93 return nil, err 94 } 95 96 artifact.CreatedAt, err = time.Parse(time.RFC3339, createdAt) 97 if err != nil { 98 artifact.CreatedAt = time.Now() 99 } 100 artifact.Tag = plumbing.Hash(tag) 101 artifact.BlobCid = cid.MustParse(blobCid) 102 103 artifacts = append(artifacts, artifact) 104 } 105 106 if err := rows.Err(); err != nil { 107 return nil, err 108 } 109 110 return artifacts, nil 111} 112 113func DeleteArtifact(e Execer, filters ...orm.Filter) error { 114 var conditions []string 115 var args []any 116 for _, filter := range filters { 117 conditions = append(conditions, filter.Condition()) 118 args = append(args, filter.Arg()...) 119 } 120 121 whereClause := "" 122 if conditions != nil { 123 whereClause = " where " + strings.Join(conditions, " and ") 124 } 125 126 query := fmt.Sprintf(`delete from artifacts %s`, whereClause) 127 128 _, err := e.Exec(query, args...) 129 return err 130}