forked from sourcegraph/sourcegraph-public-snapshot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorgs.go
More file actions
366 lines (311 loc) · 11.3 KB
/
orgs.go
File metadata and controls
366 lines (311 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
package database
import (
"context"
"fmt"
"time"
"github.com/jackc/pgconn"
"github.com/keegancsmith/sqlf"
"github.com/sourcegraph/sourcegraph/internal/database/basestore"
"github.com/sourcegraph/sourcegraph/internal/types"
"github.com/sourcegraph/sourcegraph/lib/errors"
)
// OrgNotFoundError occurs when an organization is not found.
type OrgNotFoundError struct {
Message string
}
func (e *OrgNotFoundError) Error() string {
return fmt.Sprintf("org not found: %s", e.Message)
}
func (e *OrgNotFoundError) NotFound() bool {
return true
}
var errOrgNameAlreadyExists = errors.New("organization name is already taken (by a user or another organization)")
type OrgStore interface {
AddOrgsOpenBetaStats(ctx context.Context, userID int32, data string) (string, error)
Count(context.Context, OrgsListOptions) (int, error)
Create(ctx context.Context, name string, displayName *string) (*types.Org, error)
Delete(ctx context.Context, id int32) (err error)
Done(error) error
GetByID(ctx context.Context, orgID int32) (*types.Org, error)
GetByName(context.Context, string) (*types.Org, error)
GetByUserID(ctx context.Context, userID int32) ([]*types.Org, error)
GetOrgsWithRepositoriesByUserID(ctx context.Context, userID int32) ([]*types.Org, error)
HardDelete(ctx context.Context, id int32) (err error)
List(context.Context, *OrgsListOptions) ([]*types.Org, error)
Transact(context.Context) (OrgStore, error)
Update(ctx context.Context, id int32, displayName *string) (*types.Org, error)
UpdateOrgsOpenBetaStats(ctx context.Context, id string, orgID int32) error
With(basestore.ShareableStore) OrgStore
basestore.ShareableStore
}
type orgStore struct {
*basestore.Store
}
// OrgsWith instantiates and returns a new OrgStore using the other store handle.
func OrgsWith(other basestore.ShareableStore) OrgStore {
return &orgStore{Store: basestore.NewWithHandle(other.Handle())}
}
func (o *orgStore) With(other basestore.ShareableStore) OrgStore {
return &orgStore{Store: o.Store.With(other)}
}
func (o *orgStore) Transact(ctx context.Context) (OrgStore, error) {
txBase, err := o.Store.Transact(ctx)
return &orgStore{Store: txBase}, err
}
// GetByUserID returns a list of all organizations for the user. An empty slice is
// returned if the user is not authenticated or is not a member of any org.
func (o *orgStore) GetByUserID(ctx context.Context, userID int32) ([]*types.Org, error) {
return o.getByUserID(ctx, userID, false)
}
// GetOrgsWithRepositoriesByUserID returns a list of all organizations for the user that have a repository attached.
// An empty slice is returned if the user is not authenticated or is not a member of any org.
func (o *orgStore) GetOrgsWithRepositoriesByUserID(ctx context.Context, userID int32) ([]*types.Org, error) {
return o.getByUserID(ctx, userID, true)
}
// getByUserID returns a list of all organizations for the user. An empty slice is
// returned if the user is not authenticated or is not a member of any org.
//
// onlyOrgsWithRepositories parameter determines, if the function returns all organizations
// or only those with repositories attached
func (o *orgStore) getByUserID(ctx context.Context, userID int32, onlyOrgsWithRepositories bool) ([]*types.Org, error) {
queryString :=
`SELECT orgs.id, orgs.name, orgs.display_name, orgs.created_at, orgs.updated_at
FROM org_members
LEFT OUTER JOIN orgs ON org_members.org_id = orgs.id
WHERE user_id=$1
AND orgs.deleted_at IS NULL`
if onlyOrgsWithRepositories {
queryString += `
AND EXISTS(
SELECT
FROM external_service_repos
WHERE external_service_repos.org_id = orgs.id
LIMIT 1
)`
}
rows, err := o.Handle().QueryContext(ctx, queryString, userID)
if err != nil {
return []*types.Org{}, err
}
orgs := []*types.Org{}
defer rows.Close()
for rows.Next() {
org := types.Org{}
err := rows.Scan(&org.ID, &org.Name, &org.DisplayName, &org.CreatedAt, &org.UpdatedAt)
if err != nil {
return nil, err
}
orgs = append(orgs, &org)
}
if err = rows.Err(); err != nil {
return nil, err
}
return orgs, nil
}
func (o *orgStore) GetByID(ctx context.Context, orgID int32) (*types.Org, error) {
orgs, err := o.getBySQL(ctx, "WHERE deleted_at IS NULL AND id=$1 LIMIT 1", orgID)
if err != nil {
return nil, err
}
if len(orgs) == 0 {
return nil, &OrgNotFoundError{fmt.Sprintf("id %d", orgID)}
}
return orgs[0], nil
}
func (o *orgStore) GetByName(ctx context.Context, name string) (*types.Org, error) {
orgs, err := o.getBySQL(ctx, "WHERE deleted_at IS NULL AND name=$1 LIMIT 1", name)
if err != nil {
return nil, err
}
if len(orgs) == 0 {
return nil, &OrgNotFoundError{fmt.Sprintf("name %s", name)}
}
return orgs[0], nil
}
func (o *orgStore) Count(ctx context.Context, opt OrgsListOptions) (int, error) {
q := sqlf.Sprintf("SELECT COUNT(*) FROM orgs WHERE %s", o.listSQL(opt))
var count int
if err := o.QueryRow(ctx, q).Scan(&count); err != nil {
return 0, err
}
return count, nil
}
// OrgsListOptions specifies the options for listing organizations.
type OrgsListOptions struct {
// Query specifies a search query for organizations.
Query string
*LimitOffset
}
func (o *orgStore) List(ctx context.Context, opt *OrgsListOptions) ([]*types.Org, error) {
if opt == nil {
opt = &OrgsListOptions{}
}
q := sqlf.Sprintf("WHERE %s ORDER BY id ASC %s", o.listSQL(*opt), opt.LimitOffset.SQL())
return o.getBySQL(ctx, q.Query(sqlf.PostgresBindVar), q.Args()...)
}
func (*orgStore) listSQL(opt OrgsListOptions) *sqlf.Query {
conds := []*sqlf.Query{sqlf.Sprintf("deleted_at IS NULL")}
if opt.Query != "" {
query := "%" + opt.Query + "%"
conds = append(conds, sqlf.Sprintf("name ILIKE %s OR display_name ILIKE %s", query, query))
}
return sqlf.Sprintf("(%s)", sqlf.Join(conds, ") AND ("))
}
func (o *orgStore) getBySQL(ctx context.Context, query string, args ...any) ([]*types.Org, error) {
rows, err := o.Handle().QueryContext(ctx, "SELECT id, name, display_name, created_at, updated_at FROM orgs "+query, args...)
if err != nil {
return nil, err
}
orgs := []*types.Org{}
defer rows.Close()
for rows.Next() {
org := types.Org{}
err := rows.Scan(&org.ID, &org.Name, &org.DisplayName, &org.CreatedAt, &org.UpdatedAt)
if err != nil {
return nil, err
}
orgs = append(orgs, &org)
}
if err = rows.Err(); err != nil {
return nil, err
}
return orgs, nil
}
func (o *orgStore) Create(ctx context.Context, name string, displayName *string) (newOrg *types.Org, err error) {
tx, err := o.Transact(ctx)
if err != nil {
return nil, err
}
defer func() {
err = tx.Done(err)
}()
newOrg = &types.Org{
Name: name,
DisplayName: displayName,
}
newOrg.CreatedAt = time.Now()
newOrg.UpdatedAt = newOrg.CreatedAt
err = tx.Handle().QueryRowContext(
ctx,
"INSERT INTO orgs(name, display_name, created_at, updated_at) VALUES($1, $2, $3, $4) RETURNING id",
newOrg.Name, newOrg.DisplayName, newOrg.CreatedAt, newOrg.UpdatedAt).Scan(&newOrg.ID)
if err != nil {
var e *pgconn.PgError
if errors.As(err, &e) {
switch e.ConstraintName {
case "orgs_name":
return nil, errOrgNameAlreadyExists
case "orgs_name_max_length", "orgs_name_valid_chars":
return nil, errors.Errorf("org name invalid: %s", e.ConstraintName)
case "orgs_display_name_max_length":
return nil, errors.Errorf("org display name invalid: %s", e.ConstraintName)
}
}
return nil, err
}
// Reserve organization name in shared users+orgs namespace.
if _, err := tx.Handle().ExecContext(ctx, "INSERT INTO names(name, org_id) VALUES($1, $2)", newOrg.Name, newOrg.ID); err != nil {
return nil, errOrgNameAlreadyExists
}
return newOrg, nil
}
func (o *orgStore) Update(ctx context.Context, id int32, displayName *string) (*types.Org, error) {
org, err := o.GetByID(ctx, id)
if err != nil {
return nil, err
}
// NOTE: It is not possible to update an organization's name. If it becomes possible, we need to
// also update the `names` table to ensure the new name is available in the shared users+orgs
// namespace.
if displayName != nil {
org.DisplayName = displayName
if _, err := o.Handle().ExecContext(ctx, "UPDATE orgs SET display_name=$1 WHERE id=$2 AND deleted_at IS NULL", org.DisplayName, id); err != nil {
return nil, err
}
}
org.UpdatedAt = time.Now()
if _, err := o.Handle().ExecContext(ctx, "UPDATE orgs SET updated_at=$1 WHERE id=$2 AND deleted_at IS NULL", org.UpdatedAt, id); err != nil {
return nil, err
}
return org, nil
}
func (o *orgStore) Delete(ctx context.Context, id int32) (err error) {
// Wrap in transaction because we delete from multiple tables.
tx, err := o.Transact(ctx)
if err != nil {
return err
}
defer func() {
err = tx.Done(err)
}()
res, err := tx.Handle().ExecContext(ctx, "UPDATE orgs SET deleted_at=now() WHERE id=$1 AND deleted_at IS NULL", id)
if err != nil {
return err
}
rows, err := res.RowsAffected()
if err != nil {
return err
}
if rows == 0 {
return &OrgNotFoundError{fmt.Sprintf("id %d", id)}
}
// Release the organization name so it can be used by another user or org.
if _, err := tx.Handle().ExecContext(ctx, "DELETE FROM names WHERE org_id=$1", id); err != nil {
return err
}
if _, err := tx.Handle().ExecContext(ctx, "UPDATE org_invitations SET deleted_at=now() WHERE deleted_at IS NULL AND org_id=$1", id); err != nil {
return err
}
if _, err := tx.Handle().ExecContext(ctx, "UPDATE registry_extensions SET deleted_at=now() WHERE deleted_at IS NULL AND publisher_org_id=$1", id); err != nil {
return err
}
return nil
}
func (o *orgStore) HardDelete(ctx context.Context, id int32) (err error) {
// Check if the org exists even if it has been previously soft deleted
orgs, err := o.getBySQL(ctx, "WHERE id=$1 LIMIT 1", id)
if err != nil {
return err
}
if len(orgs) == 0 {
return &OrgNotFoundError{fmt.Sprintf("id %d", id)}
}
tx, err := o.Transact(ctx)
if err != nil {
return err
}
defer func() {
err = tx.Done(err)
}()
// Some tables that reference the "orgs" table do not have ON DELETE CASCADE set, so we need to manually delete their entries before
// hard deleting an org.
tablesAndKeys := map[string]string{
"org_members": "org_id",
"org_invitations": "org_id",
"registry_extensions": "publisher_org_id",
"saved_searches": "org_id",
"notebooks": "namespace_org_id",
"settings": "org_id",
"orgs": "id",
}
// 🚨 SECURITY: Be cautious about changing order here.
tables := []string{"org_members", "org_invitations", "registry_extensions", "saved_searches", "notebooks", "settings", "orgs"}
for _, t := range tables {
query := sqlf.Sprintf(fmt.Sprintf("DELETE FROM %s WHERE %s=%d", t, tablesAndKeys[t], id))
_, err := tx.Handle().ExecContext(ctx, query.Query(sqlf.PostgresBindVar), query.Args()...)
if err != nil {
return err
}
}
return nil
}
func (o *orgStore) AddOrgsOpenBetaStats(ctx context.Context, userID int32, data string) (id string, err error) {
query := sqlf.Sprintf("INSERT INTO orgs_open_beta_stats(user_id, data) VALUES(%d, %s) RETURNING id;", userID, data)
err = o.Handle().QueryRowContext(ctx, query.Query(sqlf.PostgresBindVar), query.Args()...).Scan(&id)
return id, err
}
func (o *orgStore) UpdateOrgsOpenBetaStats(ctx context.Context, id string, orgID int32) error {
query := sqlf.Sprintf("UPDATE orgs_open_beta_stats SET org_id=%d WHERE id=%s;", orgID, id)
_, err := o.Handle().ExecContext(ctx, query.Query(sqlf.PostgresBindVar), query.Args()...)
return err
}