Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
jorgeepc committed Sep 13, 2023
1 parent 80164f7 commit 8ef6441
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 9 deletions.
9 changes: 6 additions & 3 deletions server/datastore/datastore_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ func (r *Repository) Update(ctx context.Context, dataStore DataStore) (DataStore
}
defer tx.Rollback()

query, params := sqlutil.Tenant(ctx, deleteQuery, DataStoreSingleID)
query, params := sqlutil.TenantWithReplacedID(ctx, deleteQuery, DataStoreSingleID)
_, err = tx.ExecContext(ctx, query, params...)
if err != nil {
return DataStore{}, fmt.Errorf("datastore repository sql exec delete: %w", err)
Expand All @@ -103,6 +103,9 @@ func (r *Repository) Update(ctx context.Context, dataStore DataStore) (DataStore
}

tenantID := sqlutil.TenantID(ctx)
if tenantID != nil {
dataStore.ID = id.ID(*tenantID)
}

_, err = tx.ExecContext(ctx, insertQuery,
dataStore.ID,
Expand Down Expand Up @@ -132,7 +135,7 @@ func (r *Repository) Delete(ctx context.Context, id id.ID) error {
}
defer tx.Rollback()

query, params := sqlutil.Tenant(ctx, deleteQuery, id)
query, params := sqlutil.TenantWithReplacedID(ctx, deleteQuery, id)
_, err = tx.ExecContext(ctx, query, params...)
if err != nil {
return fmt.Errorf("datastore repository sql exec delete: %w", err)
Expand Down Expand Up @@ -167,7 +170,7 @@ func (r *Repository) Current(ctx context.Context) (DataStore, error) {
}

func (r *Repository) Get(ctx context.Context, id id.ID) (DataStore, error) {
query, params := sqlutil.Tenant(ctx, getQuery, id)
query, params := sqlutil.TenantWithReplacedID(ctx, getQuery, id)
row := r.db.QueryRowContext(ctx, query, params...)

dataStore, err := r.readRow(row)
Expand Down
3 changes: 0 additions & 3 deletions server/migrations/33_add_composite_pkey.down.sql

This file was deleted.

3 changes: 0 additions & 3 deletions server/migrations/33_add_composite_pkey.up.sql

This file was deleted.

14 changes: 14 additions & 0 deletions server/pkg/sqlutil/tenant.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,20 @@ func TenantWithPrefix(ctx context.Context, query string, prefix string, params .
return query + condition, append(params, *tenantID)
}

func TenantWithReplacedID(ctx context.Context, query string, params ...any) (string, []any) {
tenantID := TenantID(ctx)
if tenantID == nil {
return query, params
}

prefix := getQueryPrefix(query)
paramNumber := len(params) + 1
condition := fmt.Sprintf(" %s tenant_id = $%d", prefix, paramNumber)

var newParams []any
return query + condition, append(newParams, *tenantID, *tenantID)
}

func TenantID(ctx context.Context) *string {
tenantID := ctx.Value(middleware.TenantIDKey)

Expand Down

0 comments on commit 8ef6441

Please sign in to comment.