Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Backend interface for ent #4

Merged
merged 14 commits into from
Jun 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
*.so
*.dylib

# SQLite database files
*.db

# Test binary, built with `go test -c`
*.test

Expand Down
6 changes: 6 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,14 @@ help: # Display this help
include internal/backends/ent/Makefile

#@ Development Tools
.PHONY: lint
lint: # Lint Golang code files
golangci-lint run --verbose

.PHONY: lint-fix
lint-fix: # Fix linter findings
golangci-lint run --fix --verbose

.PHONY: test-unit
test-unit: # Run unit tests
go test -failfast -v -coverprofile=coverage.out -covermode=atomic ./...
95 changes: 95 additions & 0 deletions backends/ent/backend.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
// --------------------------------------------------------------
// SPDX-FileCopyrightText: Copyright © 2024 The Protobom Authors
// SPDX-FileType: SOURCE
// SPDX-License-Identifier: Apache-2.0
// --------------------------------------------------------------
package ent

import (
"context"
"database/sql"
"fmt"
"slices"

sqlite "github.com/glebarez/go-sqlite"
"github.com/protobom/protobom/pkg/storage"

"github.com/protobom/storage/internal/backends/ent"
)

// Backend implements the protobom.pkg.storage.Backend interface.
type Backend struct {
client *ent.Client
ctx context.Context

// Options is the set of options common to all ent Backends.
Options *BackendOptions
}

var _ storage.Backend = (*Backend)(nil)

func NewBackend(opts ...Option) *Backend {
backend := &Backend{
Options: NewBackendOptions(),
}

for _, opt := range opts {
opt(backend)
}

return backend
}

func (backend *Backend) InitClient() error {
if backend.Options == nil {
backend.Options = NewBackendOptions()
}

// Register the SQLite driver as "sqlite3".
if !slices.Contains(sql.Drivers(), "sqlite3") {
sqlite.RegisterAsSQLITE3()
}

clientOpts := []ent.Option{}
if backend.Options.Debug {
clientOpts = append(clientOpts, ent.Debug())
}

client, err := ent.Open("sqlite3", backend.Options.DatabaseFile+dsnParams, clientOpts...)
if err != nil {
return fmt.Errorf("failed opening connection to sqlite: %w", err)
}

backend.client = client
backend.ctx = ent.NewContext(context.Background(), client)

// Run the auto migration tool.
if err := backend.client.Schema.Create(backend.ctx); err != nil {
return fmt.Errorf("failed creating schema resources: %w", err)
}

return nil
}

func (backend *Backend) CloseClient() {
backend.client.Close()
}

func (backend *Backend) Debug() *Backend {
backend.Options.Debug = true
backend.client.Debug()

return backend
}

func (backend *Backend) WithBackendOptions(opts *BackendOptions) *Backend {
backend.Options = opts

return backend
}

func (backend *Backend) WithDatabaseFile(file string) *Backend {
backend.Options.DatabaseFile = file

return backend
}
125 changes: 125 additions & 0 deletions backends/ent/example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
// --------------------------------------------------------------
// SPDX-FileCopyrightText: Copyright © 2024 The Protobom Authors
// SPDX-FileType: SOURCE
// SPDX-License-Identifier: Apache-2.0
// --------------------------------------------------------------
package ent_test

import (
"encoding/json"
"fmt"
"os"
"path/filepath"

"github.com/protobom/protobom/pkg/reader"

"github.com/protobom/storage/backends/ent"
)

func Example() {
cwd, err := os.Getwd()
if err != nil {
panic(err)
}

dbFile := filepath.Join(cwd, "example.db")

// Remove example.db if it already exists.
if _, err := os.Stat(dbFile); err == nil {
os.Remove(dbFile)
}

rdr := reader.New()
backend := ent.NewBackend().WithDatabaseFile(dbFile)

if err := backend.InitClient(); err != nil {
panic(err)
}

defer backend.CloseClient()

sbom, err := rdr.ParseFile(filepath.Join(cwd, "testdata", "sbom.cdx.json"))
if err != nil {
panic(err)
}

if err := backend.Store(sbom, nil); err != nil {
panic(err)
}

retrieved, err := backend.Retrieve(sbom.Metadata.Id, nil)
if err != nil {
panic(err)
}

output, err := json.MarshalIndent(retrieved, "", " ")
if err != nil {
panic(err)
}

fmt.Println(string(output))

//nolint:lll
// Output:
// {
// "metadata": {
// "id": "urn:uuid:3e671687-395b-41f5-a30f-a58921a69b79",
// "version": "1",
// "date": {}
// },
// "node_list": {
// "nodes": [
// {
// "id": "protobom-auto--000000001",
// "name": "Acme Application",
// "version": "9.1.1",
// "primary_purpose": [
// 1
// ]
// },
// {
// "id": "pkg:npm/acme/component@1.0.0",
// "name": "tomcat-catalina",
// "version": "9.0.14",
// "licenses": [
// "Apache-2.0"
// ],
// "license_concluded": "Apache-2.0",
// "identifiers": {
// "1": "pkg:npm/acme/component@1.0.0"
// },
// "hashes": {
// "1": "3942447fac867ae5cdb3229b658f4d48",
// "2": "e6b1000b94e835ffd37f4c6dcbdad43f4b48a02a",
// "3": "f498a8ff2dd007e29c2074f5e4b01a9a01775c3ff3aeaf6906ea503bc5791b7b",
// "5": "e8f33e424f3f4ed6db76a482fde1a5298970e442c531729119e37991884bdffab4f9426b7ee11fccd074eeda0634d71697d6f88a460dce0ac8d627a29f7d1282"
// },
// "primary_purpose": [
// 16
// ]
// },
// {
// "id": "protobom-auto--000000003",
// "name": "mylibrary",
// "version": "1.0.0",
// "primary_purpose": [
// 16
// ]
// }
// ],
// "edges": [
// {
// "type": 5,
// "from": "protobom-auto--000000001",
// "to": [
// "pkg:npm/acme/component@1.0.0",
// "protobom-auto--000000003"
// ]
// }
// ],
// "root_elements": [
// "protobom-auto--000000001"
// ]
// }
// }
}
57 changes: 57 additions & 0 deletions backends/ent/options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// --------------------------------------------------------------
// SPDX-FileCopyrightText: Copyright © 2024 The Protobom Authors
// SPDX-FileType: SOURCE
// SPDX-License-Identifier: Apache-2.0
// --------------------------------------------------------------
package ent

import (
"errors"
)

// Enable SQLite foreign key support.
const dsnParams string = "?_pragma=foreign_keys(1)"

var (
errInvalidEntOptions = errors.New("invalid ent backend options")
errUninitializedClient = errors.New("backend client must be initialized")
)

type (
// BackendOptions contains options specific to the protobom ent backend.
BackendOptions struct {
// DatabaseFile is the file path of the SQLite database to be created.
DatabaseFile string

// Debug configures the ent client to output all SQL statements during execution.
Debug bool
}

// Option represents a single configuration option for the ent backend.
Option func(*Backend)
)

// NewBackendOptions creates a new BackendOptions for the backend.
func NewBackendOptions() *BackendOptions {
return &BackendOptions{
DatabaseFile: ":memory:",
}
}

func WithBackendOptions(opts *BackendOptions) Option {
return func(backend *Backend) {
backend.WithBackendOptions(opts)
}
}

func WithDatabaseFile(file string) Option {
return func(backend *Backend) {
backend.WithDatabaseFile(file)
}
}

func Debug() Option {
return func(backend *Backend) {
backend.Debug()
}
}
Loading