diff --git a/.github/workflows/cleanup_cache.yml b/.github/workflows/cleanup_cache.yml index 5d20ebf..1e498d0 100644 --- a/.github/workflows/cleanup_cache.yml +++ b/.github/workflows/cleanup_cache.yml @@ -10,7 +10,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Check out code - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Cleanup run: | diff --git a/.github/workflows/main_cleanup_cache.yml b/.github/workflows/main_cleanup_cache.yml new file mode 100644 index 0000000..178dbf3 --- /dev/null +++ b/.github/workflows/main_cleanup_cache.yml @@ -0,0 +1,35 @@ +name: Main Cleanup Cache + +on: + push: + branches: + - main + +jobs: + clean_cache: + name: Cleanup main cache + runs-on: ubuntu-latest + steps: + - name: Check out code + uses: actions/checkout@v4 + + - name: Cleanup + run: | + gh extension install actions/gh-actions-cache + + REPO=${{ github.repository }} + BRANCH="main" + + echo "Fetching list of cache key" + cacheKeysForPR=$(gh actions-cache list -R $REPO -B $BRANCH | cut -f 1 ) + + ## Setting this to not fail the workflow while deleting cache keys. + set +e + echo "Deleting caches..." + for cacheKey in $cacheKeysForPR + do + gh actions-cache delete $cacheKey -R $REPO -B $BRANCH --confirm + done + echo "Done" + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/main_coverage.yml b/.github/workflows/main_coverage.yml deleted file mode 100644 index 036d796..0000000 --- a/.github/workflows/main_coverage.yml +++ /dev/null @@ -1,74 +0,0 @@ -name: Main Coverage - -on: - push: - branches: - - main - -jobs: - coverage: - name: Coverage - if: "startsWith(github.event.head_commit.message, 'bump:')" - runs-on: ubuntu-latest - steps: - - name: Checkout code - uses: actions/checkout@v3.3.0 - - - name: Install Go - uses: actions/setup-go@v4 - with: - go-version: 1.20.x - - - name: Config private packages - run: git config --global url.https://${{ secrets.ACCESS_TOKEN }}@github.com/Drafteame.insteadOf https://github.com/Drafteame - - - name: Install dependencies - run: go mod download - - - name: Test - run: | - go test -json -v -race -cover -coverprofile=coverage.out ./... - - - name: Convert out to xml - run: | - go install github.com/axw/gocov/gocov@latest - go install github.com/AlekSi/gocov-xml@latest - gocov convert coverage.out | gocov-xml > coverage.xml - - - name: Review coverage - uses: codecov/codecov-action@v3 - with: - token: ${{ secrets.CODECOV_TOKEN }} - files: ./coverage.xml - fail_ci_if_error: false - verbose: true - - clean_cache: - name: Cleanup main cache - runs-on: ubuntu-latest - needs: - - coverage - steps: - - name: Check out code - uses: actions/checkout@v3 - - - name: Cleanup - run: | - gh extension install actions/gh-actions-cache - - REPO=${{ github.repository }} - BRANCH="main" - - echo "Fetching list of cache key" - cacheKeysForPR=$(gh actions-cache list -R $REPO -B $BRANCH | cut -f 1 ) - - ## Setting this to not fail the workflow while deleting cache keys. - set +e - echo "Deleting caches..." - for cacheKey in $cacheKeysForPR - do - gh actions-cache delete $cacheKey -R $REPO -B $BRANCH --confirm - done - echo "Done" - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index af70443..7b7cbcb 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -11,57 +11,35 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v3.3.0 + uses: actions/checkout@v4 - name: Install Go - uses: actions/setup-go@v4 + uses: actions/setup-go@v5 with: - go-version: 1.20.x + go-version: 1.21.x - name: Config private packages run: git config --global url.https://${{ secrets.ACCESS_TOKEN }}@github.com/Drafteame.insteadOf https://github.com/Drafteame - - name: Checkout - uses: actions/checkout@v3.3.0 - - name: Install dependencies - run: go mod download - - - name: Set up gotestfmt - uses: gotesttools/gotestfmt-action@v2 - with: - token: "${{ secrets.ACCESS_TOKEN }}" - - - name: Test - run: | - set -euo pipefail - go test -json -v -race -cover -coverprofile=coverage.out ./... 2>&1 | tee /tmp/gotest.log | gotestfmt - - - name: Convert out to xml run: | - go install github.com/axw/gocov/gocov@latest - go install github.com/AlekSi/gocov-xml@latest - gocov convert coverage.out | gocov-xml > coverage.xml + go mod download + go install gotest.tools/gotestsum@latest - - name: Review coverage - uses: codecov/codecov-action@v3 - with: - token: ${{ secrets.CODECOV_TOKEN }} - files: ./coverage.xml - fail_ci_if_error: false - verbose: true + - name: Test + run: gotestsum --format pkgname-and-test-fails --raw-command -- go test -v -race -json -coverprofile=coverage.out ./... lint: name: Lint runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v3.3.0 + uses: actions/checkout@v4 - name: Install Go uses: actions/setup-go@v4 with: - go-version: 1.20.x + go-version: 1.21.x - name: Config private packages run: git config --global url.https://${{ secrets.ACCESS_TOKEN }}@github.com/Drafteame.insteadOf https://github.com/Drafteame @@ -79,7 +57,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: token: '${{ secrets.ACCESS_TOKEN }}' fetch-depth: 0 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7bdd91d..6f96eea 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,7 +20,7 @@ jobs: name: "Bump version" steps: - name: Check out - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 token: "${{ secrets.ACCESS_TOKEN }}" @@ -62,7 +62,7 @@ jobs: - bump_version steps: - name: Check out - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 token: "${{ secrets.ACCESS_TOKEN }}" @@ -71,7 +71,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v4 with: - go-version: 1.20.x + go-version: 1.21.x - name: Config private packages run: git config --global url.https://${{ secrets.ACCESS_TOKEN }}@github.com/Drafteame.insteadOf https://github.com/Drafteame diff --git a/.golangci.yml b/.golangci.yml deleted file mode 100644 index d54a384..0000000 --- a/.golangci.yml +++ /dev/null @@ -1,33 +0,0 @@ -run: - go: '1.18' - timeout: 5m - skip-files: - - generated.* - - mage.* - -linters: - enable: - - asciicheck - - bodyclose - - depguard - - gocritic - - gofmt - - goimports - - goprintffuncname - - gosimple - - govet - - ineffassign - - misspell - - rowserrcheck - - staticcheck - - stylecheck - - typecheck - - unconvert - - unused - - whitespace - - errcheck - disable: - - unparam - - structcheck - - varcheck - - deadcode diff --git a/.gotestfmt/downloads.gotpl b/.gotestfmt/downloads.gotpl deleted file mode 100644 index 78ecd5e..0000000 --- a/.gotestfmt/downloads.gotpl +++ /dev/null @@ -1,37 +0,0 @@ -{{- /*gotype: github.com/gotesttools/gotestfmt/v2/renderer.Downloads*/ -}} -{{- /* -This template contains the format for a package download. -*/ -}} -{{- $settings := .Settings -}} -{{- if or .Packages .Reason -}} - {{- if or (not $settings.HideSuccessfulDownloads) .Failed -}} - {{- if .Failed -}} - {{ "\033" }}[0;31m❌ - {{- else -}} - {{ "\033" }}[0;34m📥 - {{- end -}} - {{ " " }}Dependency downloads - {{- "\033" }}[0m{{ "\n" -}} - - {{- range .Packages -}} - {{- if or (not $settings.HideSuccessfulDownloads) .Failed -}} - {{- " " -}} - {{- if .Failed -}} - {{ "\033" }}[0;31m❌ - {{- else -}} - 📦 - {{- end -}} - {{- " " -}} - {{- .Package }} {{ .Version -}} - {{- "\033" }}[0m - {{- "\n" -}} - {{ with .Reason -}} - {{- " " -}}{{ . -}}{{ "\n" -}} - {{- end -}} - {{- end -}} - {{- end -}} - {{- end -}} - {{- with .Reason -}} - {{- " " -}}{{- "\033" }}[0;31m🛑 {{ . }}{{- "\033" }}[0m{{ "\n" -}} - {{- end -}} -{{- end -}} \ No newline at end of file diff --git a/.gotestfmt/package.gotpl b/.gotestfmt/package.gotpl deleted file mode 100644 index 1f1e6fb..0000000 --- a/.gotestfmt/package.gotpl +++ /dev/null @@ -1,24 +0,0 @@ -{{- /*gotype: github.com/gotesttools/gotestfmt/v2/renderer.Package*/ -}} -{{- /* -This template contains the format for an individual package. -*/ -}} - -{{- $settings := .Settings -}} - -{{- if and (or (not $settings.HideSuccessfulPackages) (ne .Result "PASS")) (or (not $settings.HideEmptyPackages) (ne .Result "SKIP") (ne (len .TestCases) 0)) -}} - {{- if and (not (eq .Result "PASS")) (not (eq .Result "SKIP")) -}} - {{ "\033" }}[0;31m📦 {{ .Name -}}{{- "\033" }}[0m - {{- "\n" -}} - {{- with .TestCases -}} - {{- range . -}} - {{ " \033" }}[0;31m❌{{ " " }}{{- .Name -}} - {{- "\033" -}}[0;37m ({{if $settings.ShowTestStatus}}{{.Result}}; {{end}}{{ .Duration -}}){{- "\033" -}}[0m{{- "\n" -}} - {{- with .Output -}} - {{- formatTestOutput . $settings -}} - {{- "\n" -}} - {{- end -}} - {{- end -}} - {{- end -}} - {{- "\n" -}} - {{- end -}} -{{- end -}} \ No newline at end of file diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 086344a..dd1d7d3 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,25 +1,28 @@ # See https://pre-commit.com for more information # See https://pre-commit.com/hooks.html for more hooks repos: + - repo: https://github.com/Bahjat/pre-commit-golang + rev: v1.0.3 + hooks: + - id: go-vet + - repo: https://github.com/Drafteame/pre-commit-golang - rev: 0.7.0 + rev: 0.10.1 hooks: - id: go-mod-tidy - id: goimports-reviser + args: [ "-excludes=bin,node_modules,tmp,.git" ] + - id: revive + args: [ "-config=revive.toml", "-formatter=friendly" ] - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 + rev: v4.5.0 hooks: - id: check-yaml - id: check-added-large-files - repo: https://github.com/commitizen-tools/commitizen - rev: v2.42.1 + rev: v3.14.1 hooks: - id: commitizen stages: [commit-msg] - - - repo: https://github.com/tekwizely/pre-commit-golang - rev: v1.0.0-rc.1 - hooks: - - id: go-revive \ No newline at end of file diff --git a/go.mod b/go.mod index 6c6fc66..1d19e5c 100644 --- a/go.mod +++ b/go.mod @@ -1,13 +1,13 @@ module github.com/Drafteame/cassandra-builder -go 1.18 +go 1.20 require ( - github.com/avast/retry-go/v4 v4.3.3 - github.com/gocql/gocql v1.3.1 - github.com/magefile/mage v1.14.0 + github.com/avast/retry-go/v4 v4.5.1 + github.com/gocql/gocql v1.6.0 + github.com/magefile/mage v1.15.0 github.com/scylladb/gocqlx v1.5.0 - github.com/stretchr/testify v1.8.1 + github.com/stretchr/testify v1.8.4 ) require ( diff --git a/go.sum b/go.sum index 67cbeed..99a1896 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -github.com/avast/retry-go/v4 v4.3.3 h1:G56Bp6mU0b5HE1SkaoVjscZjlQb0oy4mezwY/cGH19w= -github.com/avast/retry-go/v4 v4.3.3/go.mod h1:rg6XFaiuFYII0Xu3RDbZQkxCofFwruZKW8oEF1jpWiU= +github.com/avast/retry-go/v4 v4.5.1 h1:AxIx0HGi4VZ3I02jr78j5lZ3M6x1E0Ivxa6b0pUUh7o= +github.com/avast/retry-go/v4 v4.5.1/go.mod h1:/sipNsvNB3RRuT5iNcb6h73nw3IBmXJ/H3XrCQYSOpc= github.com/bitly/go-hostpool v0.0.0-20171023180738-a3a6125de932 h1:mXoPYz/Ul5HYEDvkta6I8/rnYM5gSdSV2tJ6XbZuEtY= github.com/bitly/go-hostpool v0.0.0-20171023180738-a3a6125de932/go.mod h1:NOuUCSz6Q9T7+igc/hlvDOUdtWKryOrtFyIVABv/p7k= github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY= @@ -8,8 +8,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/gocql/gocql v0.0.0-20200131111108-92af2e088537/go.mod h1:DL0ekTmBSTdlNF25Orwt/JMzqIq3EJ4MVa/J/uK64OY= -github.com/gocql/gocql v1.3.1 h1:BTwM4rux+ah5G3oH6/MQa+tur/TDd/XAAOXDxBBs7rg= -github.com/gocql/gocql v1.3.1/go.mod h1:3gM2c4D3AnkISwBxGnMMsS8Oy4y2lhbPRsH4xnJrHG8= +github.com/gocql/gocql v1.6.0 h1:IdFdOTbnpbd0pDhl4REKQDM+Q0SzKXQ1Yh+YZZ8T/qU= +github.com/gocql/gocql v1.6.0/go.mod h1:3gM2c4D3AnkISwBxGnMMsS8Oy4y2lhbPRsH4xnJrHG8= github.com/golang/snappy v0.0.0-20170215233205-553a64147049/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= @@ -24,8 +24,8 @@ github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORN github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/magefile/mage v1.14.0 h1:6QDX3g6z1YvJ4olPhT1wksUcSa/V0a1B+pJb73fBjyo= -github.com/magefile/mage v1.14.0/go.mod h1:z5UZb/iS3GoOSn0JgWuiw7dxlurVYTu+/jHXqQg881A= +github.com/magefile/mage v1.15.0 h1:BvGheCMAsG3bWUDbZ8AyXXpCNwU9u5CB6sM+HNb9HYg= +github.com/magefile/mage v1.15.0/go.mod h1:z5UZb/iS3GoOSn0JgWuiw7dxlurVYTu+/jHXqQg881A= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/scylladb/go-reflectx v1.0.1/go.mod h1:rWnOfDIRWBGN0miMLIcoPt/Dhi2doCMZqwMCJ3KupFc= @@ -38,8 +38,8 @@ github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpE github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= diff --git a/magefiles/mage.format.go b/magefiles/mage.format.go index c23b1f8..3d18bb2 100644 --- a/magefiles/mage.format.go +++ b/magefiles/mage.format.go @@ -4,28 +4,46 @@ package main import ( "fmt" + "github.com/magefile/mage/mg" "github.com/magefile/mage/sh" ) -// Lint Runs golangci-lint checks over the code. +// Vet execute `go vet` checks. +func Vet() error { + command := "go" + args := []string{"vet", "./..."} + + out, err := sh.Output(command, args...) + + if out != "" { + fmt.Println(out) + } + + return err +} + +// Lint Runs revive checks over the code. func Lint() error { + mg.Deps(Vet) + command := "revive" - args := []string{"-config=revive.toml", "-formatter=friendly", "-exclude=magefiles/...", "./..."} + args := []string{"-config=revive.toml", "-formatter=friendly", "./..."} out, err := sh.Output(command, args...) - fmt.Println(out) + if out != "" { + fmt.Println(out) + } + return err } // Format Runs gofmt over the code. func Format() error { - outImp, err := sh.Output("goimports-reviser", "-format", "./...") - if err != nil { - return err + out, err := sh.Output("goimports-reviser", "-format", "./...") + if out != "" { + fmt.Println(out) } - fmt.Println(outImp) - - return nil + return err } diff --git a/magefiles/mage.install.go b/magefiles/mage.install.go index a71670d..276543f 100644 --- a/magefiles/mage.install.go +++ b/magefiles/mage.install.go @@ -1,4 +1,4 @@ -//nolint +// nolint package main import ( diff --git a/qb/client.go b/qb/client.go deleted file mode 100644 index da43e22..0000000 --- a/qb/client.go +++ /dev/null @@ -1,130 +0,0 @@ -package qb - -import ( - "github.com/gocql/gocql" - - models "github.com/Drafteame/cassandra-builder/qb/models" - "github.com/Drafteame/cassandra-builder/qb/qcount" - "github.com/Drafteame/cassandra-builder/qb/qdelete" - "github.com/Drafteame/cassandra-builder/qb/qinsert" - "github.com/Drafteame/cassandra-builder/qb/qselect" - "github.com/Drafteame/cassandra-builder/qb/qupdate" -) - -type client struct { - canRestart bool - config models.Config - session *gocql.Session -} - -var _ Client = &client{} - -func (c *client) Select(f ...string) *qselect.Query { - return qselect.New(c).Fields(f...) -} - -func (c *client) Insert(f ...string) *qinsert.Query { - return qinsert.New(c).Fields(f...) -} - -func (c *client) Update(t string) *qupdate.Query { - return qupdate.New(c).Table(t) -} - -func (c *client) Delete() *qdelete.Query { - return qdelete.New(c) -} - -func (c *client) Count() *qcount.Query { - return qcount.New(c) -} - -func (c *client) Debug() bool { - return c.config.Debug -} - -func (c *client) Close() { - c.session.Close() -} - -func (c *client) Session() *gocql.Session { - return c.session -} - -func (c *client) Config() models.Config { - return c.config -} - -func (c *client) Restart() error { - c.Close() - - session, err := createSession(c.config) - if err != nil { - return err - } - - c.session = session - - return nil -} - -func createSession(c models.Config) (*gocql.Session, error) { - cluster := gocql.NewCluster(c.ContactPoints...) - cluster.Keyspace = c.KeyspaceName - cluster.Consistency = gocql.Consistency(c.Consistency) - cluster.ProtoVersion = c.ProtoVersion - - if c.Port != 0 { - cluster.Port = c.Port - } - - if c.DisableInitialHostLookup { - cluster.DisableInitialHostLookup = c.DisableInitialHostLookup - } - - if c.Username != "" && c.Password != "" { - cluster.Authenticator = gocql.PasswordAuthenticator{ - Username: c.Username, - Password: c.Password, - } - } - - if c.CaPath != "" { - cluster.SslOpts = &gocql.SslOptions{ - CaPath: c.CaPath, - } - } - - if c.Timeout != 0 { - cluster.Timeout = c.Timeout - } - - if c.ConnectTimeout != 0 { - cluster.ConnectTimeout = c.ConnectTimeout - } - - return cluster.CreateSession() -} - -// NewClient creates a new cassandra client manager from config -func NewClient(conf models.Config) (Client, error) { - session, err := createSession(conf) - if err != nil { - return nil, err - } - - return &client{ - session: session, - config: conf, - canRestart: true, - }, nil -} - -// NewClientWithSession creates a new cassandra client manager from a given session. -func NewClientWithSession(session *gocql.Session, conf models.Config) Client { - return &client{ - session: session, - config: conf, - canRestart: false, - } -} diff --git a/qb/errors/errors.go b/qb/errors/errors.go index a1f33e7..a61d067 100644 --- a/qb/errors/errors.go +++ b/qb/errors/errors.go @@ -1,6 +1,8 @@ package errors -import "errors" +import ( + "errors" +) var ( ErrNilBinding = errors.New("cassandra-builder: nil bind is not allowed") @@ -9,5 +11,4 @@ var ( ErrNoSliceOfStructsBinding = errors.New("cassandra-builder: bind value should be a slice of structs") ErrClosedConnection = errors.New("cassandra-builder: can execute on closed connection") ErrNilIterator = errors.New("cassandra-builder: nil iterator is not allowed") - ErrParsing = errors.New("cassandra-builder: error parsing row") ) diff --git a/qb/interface.go b/qb/interface.go new file mode 100644 index 0000000..8ef397c --- /dev/null +++ b/qb/interface.go @@ -0,0 +1,45 @@ +package qb + +import ( + "github.com/gocql/gocql" + + "github.com/Drafteame/cassandra-builder/qb/models" + "github.com/Drafteame/cassandra-builder/qb/qcount" + delete2 "github.com/Drafteame/cassandra-builder/qb/qdelete" + "github.com/Drafteame/cassandra-builder/qb/qinsert" + _select "github.com/Drafteame/cassandra-builder/qb/qselect" + "github.com/Drafteame/cassandra-builder/qb/qupdate" +) + +// Client is the main cassandra client abstraction to work with the database +type Client interface { + // Select start a select query + Select(f ...string) *_select.Query + + // Insert start a new insert query statement + Insert(f ...string) *qinsert.Query + + // Update start an update query statement + Update(t string) *qupdate.Query + + // Delete start a new delete query statement + Delete() *delete2.Query + + // Count start new count query statement + Count() *qcount.Query + + // Session return the plain session object to build some direct query + Session() *gocql.Session + + // Debug return an assertion for debugging + Debug() bool + + // Restart should close and start a new connection. + Restart() error + + // Config return current client configuration + Config() models.Config + + // Close ends cassandra connection pool + Close() +} diff --git a/qb/methods.go b/qb/methods.go new file mode 100644 index 0000000..6077e9f --- /dev/null +++ b/qb/methods.go @@ -0,0 +1,75 @@ +package qb + +import ( + "github.com/gocql/gocql" + + "github.com/Drafteame/cassandra-builder/qb/models" + "github.com/Drafteame/cassandra-builder/qb/qcount" + "github.com/Drafteame/cassandra-builder/qb/qdelete" + "github.com/Drafteame/cassandra-builder/qb/qinsert" + "github.com/Drafteame/cassandra-builder/qb/qselect" + "github.com/Drafteame/cassandra-builder/qb/qupdate" +) + +// Select creates a new select query. +func (c *client) Select(f ...string) *qselect.Query { + return qselect.New(c).Fields(f...) +} + +// Insert creates a new insert query. +func (c *client) Insert(f ...string) *qinsert.Query { + return qinsert.New(c).Fields(f...) +} + +// Update creates a new update query. +func (c *client) Update(t string) *qupdate.Query { + return qupdate.New(c).Table(t) +} + +// Delete creates a new delete query. +func (c *client) Delete() *qdelete.Query { + return qdelete.New(c) +} + +// Count creates a new count query. +func (c *client) Count() *qcount.Query { + return qcount.New(c) +} + +// Debug returns the debug flag. +func (c *client) Debug() bool { + return c.config.Debug +} + +// Close closes the session. +func (c *client) Close() { + if c.session == nil { + return + } + + c.session.Close() +} + +// Session returns the session from gocql driver +func (c *client) Session() *gocql.Session { + return c.session +} + +// Config returns the configuration used to create the session. +func (c *client) Config() models.Config { + return c.config +} + +// Restart restarts the session. +func (c *client) Restart() error { + c.Close() + + sess, err := c.sessionCreator(c.config) + if err != nil { + return err + } + + c.session = sess + + return nil +} diff --git a/qb/options.go b/qb/options.go new file mode 100644 index 0000000..ff51f04 --- /dev/null +++ b/qb/options.go @@ -0,0 +1,17 @@ +package qb + +import "github.com/Drafteame/cassandra-builder/session" + +type options struct { + sessionCreator session.Creator +} + +// Option is a function that sets some option on the client. +type Option func(*options) + +// WithSessionCreator sets the session creator on the client. +func WithSessionCreator(creator session.Creator) Option { + return func(o *options) { + o.sessionCreator = creator + } +} diff --git a/qb/qb.go b/qb/qb.go index 87c2d64..2c06f9b 100644 --- a/qb/qb.go +++ b/qb/qb.go @@ -3,43 +3,45 @@ package qb import ( "github.com/gocql/gocql" - models "github.com/Drafteame/cassandra-builder/qb/models" - "github.com/Drafteame/cassandra-builder/qb/qcount" - delete2 "github.com/Drafteame/cassandra-builder/qb/qdelete" - "github.com/Drafteame/cassandra-builder/qb/qinsert" - _select "github.com/Drafteame/cassandra-builder/qb/qselect" - "github.com/Drafteame/cassandra-builder/qb/qupdate" + "github.com/Drafteame/cassandra-builder/qb/models" + "github.com/Drafteame/cassandra-builder/session" ) -// Client is the main cassandra client abstraction to work with the database -type Client interface { - // Select start a select query - Select(f ...string) *_select.Query - - // Insert start a new insert query statement - Insert(f ...string) *qinsert.Query - - // Update start an update query statement - Update(t string) *qupdate.Query - - // Delete start a new delete query statement - Delete() *delete2.Query +type client struct { + canRestart bool + config models.Config + session *gocql.Session + sessionCreator session.Creator +} - // Count start new count query statement - Count() *qcount.Query +var _ Client = &client{} - // Session return the plain session object to build some direct query - Session() *gocql.Session +// NewClient creates a new cassandra client manager from config +func NewClient(conf models.Config, opts ...Option) (Client, error) { + copts := options{sessionCreator: session.Create} - // Debug return an assertion for debugging - Debug() bool + for _, opt := range opts { + opt(&copts) + } - // Restart should close and start a new connection. - Restart() error + sess, err := copts.sessionCreator(conf) + if err != nil { + return nil, err + } - // Config return current client configuration - Config() models.Config + return &client{ + session: sess, + config: conf, + canRestart: true, + sessionCreator: copts.sessionCreator, + }, nil +} - // Close ends cassandra connection pool - Close() +// NewClientWithSession creates a new cassandra client manager from a given session. +func NewClientWithSession(sess *gocql.Session, conf models.Config) Client { + return &client{ + session: sess, + config: conf, + canRestart: false, + } } diff --git a/qb/query/where.go b/qb/query/where.go index eaedcf4..edc20ba 100644 --- a/qb/query/where.go +++ b/qb/query/where.go @@ -1,6 +1,8 @@ package query -import "github.com/scylladb/gocqlx/qb" +import ( + "github.com/scylladb/gocqlx/qb" +) // WhereOp represents a where operation type type WhereOp string @@ -29,7 +31,7 @@ const ( type WhereStm struct { Field string Op WhereOp - Value interface{} + Value any } // BuildWhere create a complete where statement to be used on select, delete, count and update queries diff --git a/revive.toml b/revive.toml index 34c2b88..29c8f38 100644 --- a/revive.toml +++ b/revive.toml @@ -1,9 +1,9 @@ ignoreGeneratedHeader = false severity = "warning" confidence = 0.8 -errorCode = 0 +errorCode = 1 warningCode = 0 -exclue = ["magefiles/..."] +exclude = ["magefiles/...", "examples/..."] [rule.blank-imports] [rule.context-as-argument] @@ -21,7 +21,7 @@ exclue = ["magefiles/..."] [rule.errorf] [rule.empty-block] [rule.superfluous-else] -[rule.unused-parameter] +# [rule.unused-parameter] [rule.unreachable-code] [rule.redefines-builtin-id] [rule.time-equal] @@ -34,4 +34,4 @@ exclue = ["magefiles/..."] [rule.unconditional-recursion] [rule.use-any] [rule.datarace] -[rule.comment-spacings] \ No newline at end of file +# [rule.comment-spacings] \ No newline at end of file diff --git a/session/session.go b/session/session.go new file mode 100644 index 0000000..09f617f --- /dev/null +++ b/session/session.go @@ -0,0 +1,46 @@ +package session + +import ( + "github.com/gocql/gocql" + + "github.com/Drafteame/cassandra-builder/qb/models" +) + +// Create creates a new Cassandra session using the given configuration. +func Create(c models.Config) (*gocql.Session, error) { + cluster := gocql.NewCluster(c.ContactPoints...) + cluster.Keyspace = c.KeyspaceName + cluster.Consistency = gocql.Consistency(c.Consistency) + cluster.ProtoVersion = c.ProtoVersion + + if c.Port != 0 { + cluster.Port = c.Port + } + + if c.DisableInitialHostLookup { + cluster.DisableInitialHostLookup = c.DisableInitialHostLookup + } + + if c.Username != "" && c.Password != "" { + cluster.Authenticator = gocql.PasswordAuthenticator{ + Username: c.Username, + Password: c.Password, + } + } + + if c.CaPath != "" { + cluster.SslOpts = &gocql.SslOptions{ + CaPath: c.CaPath, + } + } + + if c.Timeout != 0 { + cluster.Timeout = c.Timeout + } + + if c.ConnectTimeout != 0 { + cluster.ConnectTimeout = c.ConnectTimeout + } + + return cluster.CreateSession() +} diff --git a/session/types.go b/session/types.go new file mode 100644 index 0000000..ca92348 --- /dev/null +++ b/session/types.go @@ -0,0 +1,10 @@ +package session + +import ( + "github.com/gocql/gocql" + + "github.com/Drafteame/cassandra-builder/qb/models" +) + +// Creator is a function that creates a new Cassandra session using the given configuration. +type Creator func(cfg models.Config) (*gocql.Session, error)