NewSQLRepository takes a database driver, URL, and dialect for the asset repository and connects to it.
(dbDriver, dbURL string, dialect SQLRepositoryDialect)
| 36 | |
| 37 | // NewSQLRepository takes a database driver, URL, and dialect for the asset repository and connects to it. |
| 38 | func NewSQLRepository(dbDriver, dbURL string, dialect SQLRepositoryDialect) (*SQLRepository, error) { |
| 39 | db, err := sql.Open(dbDriver, dbURL) |
| 40 | if err != nil { |
| 41 | return nil, fmt.Errorf("unable to connect database: %w", err) |
| 42 | } |
| 43 | |
| 44 | _, err = db.Exec(dialect.CreateTable()) |
| 45 | if err != nil { |
| 46 | return nil, helper.CloseDatabaseWithError(db, fmt.Errorf("unable to create table: %w", err)) |
| 47 | } |
| 48 | |
| 49 | assetQuery, err := db.Prepare(dialect.Assets()) |
| 50 | if err != nil { |
| 51 | return nil, helper.CloseDatabaseWithError(db, fmt.Errorf("unable to prepare assets: %w", err)) |
| 52 | } |
| 53 | |
| 54 | getSinceQuery, err := db.Prepare(dialect.GetSince()) |
| 55 | if err != nil { |
| 56 | return nil, helper.CloseDatabaseWithError(db, fmt.Errorf("unable to prepare get since query: %w", err)) |
| 57 | } |
| 58 | |
| 59 | lastDateQuery, err := db.Prepare(dialect.LastDate()) |
| 60 | if err != nil { |
| 61 | return nil, helper.CloseDatabaseWithError(db, fmt.Errorf("unable to prepare last date query: %w", err)) |
| 62 | } |
| 63 | |
| 64 | appendQuery, err := db.Prepare(dialect.Append()) |
| 65 | if err != nil { |
| 66 | return nil, helper.CloseDatabaseWithError(db, fmt.Errorf("unable to prepare append: %w", err)) |
| 67 | } |
| 68 | |
| 69 | repository := &SQLRepository{ |
| 70 | db, |
| 71 | dialect, |
| 72 | assetQuery, |
| 73 | getSinceQuery, |
| 74 | lastDateQuery, |
| 75 | appendQuery, |
| 76 | } |
| 77 | |
| 78 | return repository, nil |
| 79 | } |
| 80 | |
| 81 | // Close closes the database connection. |
| 82 | func (s *SQLRepository) Close() error { |