Skip to content

Commit

Permalink
feat: initial postgres driver
Browse files Browse the repository at this point in the history
  • Loading branch information
boojack committed Dec 17, 2023
1 parent 41cb597 commit a7d48e8
Show file tree
Hide file tree
Showing 17 changed files with 1,674 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ linters-settings:
disabled: true
- name: early-return
disabled: true
- name: use-any
disabled: true
- name: exported
arguments:
- "disableStutteringCheck"
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ require (
github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.1
github.com/h2non/filetype v1.1.3
github.com/improbable-eng/grpc-web v0.15.0
github.com/lib/pq v1.10.9
github.com/mssola/useragent v1.0.0
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/pkg/errors v0.9.1
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,8 @@ github.com/labstack/echo/v4 v4.11.2/go.mod h1:UcGuQ8V6ZNRmSweBIJkPvGfwCMIlFmiqrP
github.com/labstack/gommon v0.4.0 h1:y7cvthEAEbU0yHOf4axH8ZG2NH8knB9iNSoTO8dyIk8=
github.com/labstack/gommon v0.4.0/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM=
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM=
github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4=
github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ=
Expand Down
3 changes: 3 additions & 0 deletions store/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (

"github.com/yourselfhosted/slash/server/profile"
"github.com/yourselfhosted/slash/store"
"github.com/yourselfhosted/slash/store/db/postgres"
"github.com/yourselfhosted/slash/store/db/sqlite"
)

Expand All @@ -16,6 +17,8 @@ func NewDBDriver(profile *profile.Profile) (store.Driver, error) {
switch profile.Driver {
case "sqlite":
driver, err = sqlite.NewDB(profile)
case "postgres":
driver, err = postgres.NewDB(profile)
default:
return nil, errors.New("unknown db driver")
}
Expand Down
88 changes: 88 additions & 0 deletions store/db/postgres/activity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package postgres

import (
"context"
"fmt"
"strings"

"github.com/yourselfhosted/slash/store"
)

func (d *DB) CreateActivity(ctx context.Context, create *store.Activity) (*store.Activity, error) {
stmt := `
INSERT INTO activity (
creator_id,
type,
level,
payload
)
VALUES ($1, $2, $3, $4)
RETURNING id, created_ts
`
if err := d.db.QueryRowContext(ctx, stmt,
create.CreatorID,
create.Type.String(),
create.Level.String(),
create.Payload,
).Scan(
&create.ID,
&create.CreatedTs,
); err != nil {
return nil, err
}

activity := create
return activity, nil
}

func (d *DB) ListActivities(ctx context.Context, find *store.FindActivity) ([]*store.Activity, error) {
where, args := []string{"1 = 1"}, []any{}
if find.Type != "" {
where, args = append(where, "type = $"+fmt.Sprint(len(args)+1)), append(args, find.Type.String())
}
if find.Level != "" {
where, args = append(where, "level = $"+fmt.Sprint(len(args)+1)), append(args, find.Level.String())
}
if find.Where != nil {
where = append(where, find.Where...)
}

query := `
SELECT
id,
creator_id,
created_ts,
type,
level,
payload
FROM activity
WHERE ` + strings.Join(where, " AND ")
rows, err := d.db.QueryContext(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()

list := []*store.Activity{}
for rows.Next() {
activity := &store.Activity{}
if err := rows.Scan(
&activity.ID,
&activity.CreatorID,
&activity.CreatedTs,
&activity.Type,
&activity.Level,
&activity.Payload,
); err != nil {
return nil, err
}

list = append(list, activity)
}

if err := rows.Err(); err != nil {
return nil, err
}

return list, nil
}
194 changes: 194 additions & 0 deletions store/db/postgres/collection.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
package postgres

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

"github.com/pkg/errors"

"github.com/yourselfhosted/slash/internal/util"
storepb "github.com/yourselfhosted/slash/proto/gen/store"
"github.com/yourselfhosted/slash/store"
)

func (d *DB) CreateCollection(ctx context.Context, create *storepb.Collection) (*storepb.Collection, error) {
set := []string{"creator_id", "name", "title", "description", "shortcut_ids", "visibility"}
args := []any{create.CreatorId, create.Name, create.Title, create.Description, strings.Trim(strings.Join(strings.Fields(fmt.Sprint(create.ShortcutIds)), ","), "[]"), create.Visibility.String()}
placeholder := []string{"$1", "$2", "$3", "$4", "$5", "$6"}

stmt := `
INSERT INTO collection (
` + strings.Join(set, ", ") + `
)
VALUES (` + strings.Join(placeholder, ",") + `)
RETURNING id, created_ts, updated_ts
`
if err := d.db.QueryRowContext(ctx, stmt, args...).Scan(
&create.Id,
&create.CreatedTs,
&create.UpdatedTs,
); err != nil {
return nil, err
}
collection := create
return collection, nil
}

func (d *DB) UpdateCollection(ctx context.Context, update *store.UpdateCollection) (*storepb.Collection, error) {
set, args := []string{}, []any{}
if update.Name != nil {
set, args = append(set, "name = $1"), append(args, *update.Name)
}
if update.Title != nil {
set, args = append(set, "title = $2"), append(args, *update.Title)
}
if update.Description != nil {
set, args = append(set, "description = $3"), append(args, *update.Description)
}
if update.ShortcutIDs != nil {
set, args = append(set, "shortcut_ids = $4"), append(args, strings.Trim(strings.Join(strings.Fields(fmt.Sprint(update.ShortcutIDs)), ","), "[]"))
}
if update.Visibility != nil {
set, args = append(set, "visibility = $5"), append(args, update.Visibility.String())
}
if len(set) == 0 {
return nil, errors.New("no update specified")
}
args = append(args, update.ID)

stmt := `
UPDATE collection
SET
` + strings.Join(set, ", ") + `
WHERE
id = $6
RETURNING id, creator_id, created_ts, updated_ts, name, title, description, shortcut_ids, visibility
`
collection := &storepb.Collection{}
var shortcutIDs, visibility string
if err := d.db.QueryRowContext(ctx, stmt, args...).Scan(
&collection.Id,
&collection.CreatorId,
&collection.CreatedTs,
&collection.UpdatedTs,
&collection.Name,
&collection.Title,
&collection.Description,
&shortcutIDs,
&visibility,
); err != nil {
return nil, err
}

collection.ShortcutIds = []int32{}
if shortcutIDs != "" {
for _, idStr := range strings.Split(shortcutIDs, ",") {
shortcutID, err := util.ConvertStringToInt32(idStr)
if err != nil {
return nil, errors.Wrap(err, "failed to convert shortcut id")
}
collection.ShortcutIds = append(collection.ShortcutIds, shortcutID)
}
}
collection.Visibility = convertVisibilityStringToStorepb(visibility)
return collection, nil
}

func (d *DB) ListCollections(ctx context.Context, find *store.FindCollection) ([]*storepb.Collection, error) {
where, args := []string{"1 = 1"}, []any{}
if v := find.ID; v != nil {
where, args = append(where, "id = $1"), append(args, *v)
}
if v := find.CreatorID; v != nil {
where, args = append(where, "creator_id = $2"), append(args, *v)
}
if v := find.Name; v != nil {
where, args = append(where, "name = $3"), append(args, *v)
}
if v := find.VisibilityList; len(v) != 0 {
list := []string{}
for i, visibility := range v {
list = append(list, fmt.Sprintf("$%d", len(args)+i+1))
args = append(args, visibility)
}
where = append(where, fmt.Sprintf("visibility IN (%s)", strings.Join(list, ",")))
}

rows, err := d.db.QueryContext(ctx, `
SELECT
id,
creator_id,
created_ts,
updated_ts,
name,
title,
description,
shortcut_ids,
visibility
FROM collection
WHERE `+strings.Join(where, " AND ")+`
ORDER BY created_ts DESC`,
args...,
)
if err != nil {
return nil, err
}
defer rows.Close()

list := make([]*storepb.Collection, 0)
for rows.Next() {
collection := &storepb.Collection{}
var shortcutIDs, visibility string
if err := rows.Scan(
&collection.Id,
&collection.CreatorId,
&collection.CreatedTs,
&collection.UpdatedTs,
&collection.Name,
&collection.Title,
&collection.Description,
&shortcutIDs,
&visibility,
); err != nil {
return nil, err
}

collection.ShortcutIds = []int32{}
if shortcutIDs != "" {
for _, idStr := range strings.Split(shortcutIDs, ",") {
shortcutID, err := util.ConvertStringToInt32(idStr)
if err != nil {
return nil, errors.Wrap(err, "failed to convert shortcut id")
}
collection.ShortcutIds = append(collection.ShortcutIds, shortcutID)
}
}
collection.Visibility = storepb.Visibility(storepb.Visibility_value[visibility])
list = append(list, collection)
}

if err := rows.Err(); err != nil {
return nil, err
}
return list, nil
}

func (d *DB) DeleteCollection(ctx context.Context, delete *store.DeleteCollection) error {
if _, err := d.db.ExecContext(ctx, `DELETE FROM collection WHERE id = $1`, delete.ID); err != nil {
return err
}

return nil
}

func vacuumCollection(ctx context.Context, tx *sql.Tx) error {
stmt := `DELETE FROM collection WHERE creator_id NOT IN (SELECT id FROM user)`
_, err := tx.ExecContext(ctx, stmt)
if err != nil {
return err
}

return nil
}
Loading

0 comments on commit a7d48e8

Please sign in to comment.