~evanj/cms

ref: afc228cb59683180b3b2957aceb6bf1aa0bf0d0e cms/internal/s/db/space.go -rw-r--r-- 11.0 KiB
afc228cbEvan J Feat(db): Tweaking db.SetMaxOpenConns, db.SetMaxIdleConns, and 1 year, 25 days ago
                                                                                
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
package db

import (
	"database/sql"
	"errors"
	"fmt"
	"strconv"
	"strings"

	"git.sr.ht/~evanj/cms/internal/m/content"
	"git.sr.ht/~evanj/cms/internal/m/contenttype"
	"git.sr.ht/~evanj/cms/internal/m/org"
	"git.sr.ht/~evanj/cms/internal/m/space"
	"git.sr.ht/~evanj/cms/internal/m/user"
	"git.sr.ht/~evanj/cms/internal/m/valuetype"
)

type Space struct {
	SpaceID   string
	SpaceName string
	SpaceDesc string
	SpaceOrg  Org
}

var (
	queryCreateNewSpace = `INSERT INTO cms_space (NAME, DESCRIPTION, ORG_ID) VALUES (?, ?, ?);`
	queryUpdateSpace    = `UPDATE cms_space SET NAME = ?, DESCRIPTION = ? WHERE ID = ?;`

	queryDeleteSpace = `
		DELETE cms_space FROM cms_space
		JOIN cms_org ON cms_org.ID=cms_space.ORG_ID
		JOIN cms_user ON cms_user.ORG_ID=cms_org.ID
		WHERE cms_user.ID=? 
		AND cms_space.ID=?
	`

	queryFindSpaceByUserAndID = `
		SELECT cms_space.ID, cms_space.NAME, cms_space.DESCRIPTION, cms_org.ID, cms_billing.TIER_NAME, cms_billing.PAYMENT_CUSTOMER 
		FROM cms_space
		JOIN cms_org ON cms_org.ID=cms_space.ORG_ID
		JOIN cms_user ON cms_user.ORG_ID=cms_org.ID
		LEFT JOIN cms_billing ON cms_billing.ORG_ID=cms_org.ID
		WHERE cms_user.ID=? 
		AND cms_space.ID=?
	`

	copyHooksQuery = `
		INSERT INTO cms_hooks (URL, SPACE_ID)
		SELECT URL, ?
		FROM cms_hooks 
		WHERE SPACE_ID=?
	`

	copyContentTypeQuery = `
		INSERT INTO cms_contenttype (NAME, SPACE_ID)
		SELECT NAME, ?
		FROM cms_contenttype 
		WHERE ID=?
	`

	copyValueTypeQuery = `
		INSERT INTO cms_contenttype_to_valuetype (NAME, CONTENTTYPE_ID, VALUETYPE_ID)
		SELECT NAME, ?, VALUETYPE_ID
		FROM cms_contenttype_to_valuetype 
		WHERE CONTENTTYPE_ID=?
	`
)

func (db *DB) spaceNew(t *sql.Tx, user user.User, name, desc string) (space.Space, error) {
	res, err := t.Exec(queryCreateNewSpace, name, desc, user.Org().ID())
	if err != nil {
		return nil, fmt.Errorf("space '%s' already exists", name)
	}

	id, err := res.LastInsertId()
	if err != nil {
		return nil, fmt.Errorf("failed to create space")
	}

	return db.spaceGet(t, user, strconv.FormatInt(id, 10))
}

func (db *DB) SpaceNew(user user.User, name, desc string) (space.Space, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	space, err := db.spaceNew(t, user, name, desc)
	if err != nil {
		return nil, err
	}

	return space, t.Commit()
}

func (db *DB) SpaceUpdate(user user.User, space space.Space, name, desc string) (space.Space, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	res, err := t.Exec(queryUpdateSpace, name, desc, space.ID())
	if err != nil {
		return nil, err
	}

	c, err := res.RowsAffected()
	if err != nil {
		return nil, err
	}

	if c != 1 {
		// Or maybe too much was updated.
		return nil, errors.New("space was not updated")
	}

	next, err := db.spaceGet(t, user, space.ID())
	if err != nil {
		return nil, err
	}

	return next, t.Commit()
}

func (db *DB) SpaceCopy(user user.User, prevS space.Space, name, desc string) (space.Space, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	res, err := t.Exec(queryCreateNewSpace, name, desc, user.Org().ID())
	if err != nil {
		return nil, err
	}

	nextID, err := res.LastInsertId()
	if err != nil {
		return nil, err
	}

	// Copy all webhooks.
	if _, err := t.Exec(copyHooksQuery, nextID, prevS.ID()); err != nil {
		return nil, err
	}

	next, err := db.spaceGet(t, user, strconv.FormatInt(nextID, 10))
	if err != nil {
		return nil, err
	}

	if err := db.spaceCopyContentTypes(t, user, next, prevS); err != nil {
		return nil, err
	}

	return next, t.Commit()
}

func (db *DB) spaceCopyContentTypes(t *sql.Tx, u user.User, next, prevS space.Space) error {
	type cct struct {
		ct contenttype.ContentType
		c  content.Content
	}

	// We've made a change to the content copy impl. We skip first pass of ref
	// types then update contents. This fixes loop references.

	// todo are contents that could not be processes yet, due to Reference and
	// ReferenceList dependencies. They will be taken care of in later iterations
	// (up to a depth of three).
	var todo []cct

	// refmap is used for todo to pull information from.
	// old content ID -> new content
	refmap := make(map[string]content.Content)

	// Copy all content types and their value types.
	// Copy all contents and their values.
	iter := db.ContentTypeIter(t, u, prevS)
	for iter.Next() {
		prevCT, err := iter.Scan()
		if err != nil {
			return err
		}

		// Copy content type.
		res, err := t.Exec(copyContentTypeQuery, next.ID(), prevCT.ID())
		if err != nil {
			return err
		}

		ctID, err := res.LastInsertId()
		if err != nil {
			return err
		}

		// Copy value type.
		if _, err := t.Exec(copyValueTypeQuery, ctID, prevCT.ID()); err != nil {
			return err
		}

		ct, err := db.contentTypeGet(t, next, strconv.FormatInt(ctID, 10))
		if err != nil {
			return err
		}

		// Copy all contents and their values.
		iter := db.contentIter(t, u, prevS, prevCT, "name") // TODO: What is this sort type for?
		for iter.Next() {
			prevC, err := iter.Scan()
			if err != nil {
				return err
			}

			ok, err := db.spaceCopyContent(t, next, ct, prevC, refmap)
			if err != nil {
				return fmt.Errorf("failed to copy %s: %w", prevC.MustValueByName("name").Value(), err)
			}

			if !ok {
				// If we're not OK that means we need to update the content to account for ref types.
				todo = append(todo, cct{ct, prevC})
			}
		}
	}

	// Update reference types that were skipped because content was not createt.
	for _, set := range todo {
		err := db.spaceUpdateContent(t, next, set.ct, set.c, refmap)
		if err != nil {
			return fmt.Errorf("failed to copy for references %s: %w", set.c.MustValueByName("name").Value(), err)
		}
	}

	return nil
}

func (db *DB) spaceCopyContent(t *sql.Tx, next space.Space, ct contenttype.ContentType, prevC content.Content, refmap map[string]content.Content) (bool, error) {
	var (
		params []ContentNewParam
		skip   bool
	)

	for _, prevF := range ct.Fields() {
		prevV, ok := prevC.ValueByName(prevF.Name())
		if !ok {
			if prevF.Type() == valuetype.Reference || prevF.Type() == valuetype.ReferenceList {
				// Referenced content was deleted.
				continue
			}

			// "null" field. E.G. empty StringSmall.
			prevV = &ContentValue{
				FieldType: string(prevF.Type()),
				FieldName: prevF.Name(),
			}
		}

		switch prevF.Type() {

		case valuetype.Reference:
			ref, ok := refmap[prevV.RefID()]
			if !ok {
				skip = true
				continue
			}
			params = append(params, ContentNewParam{prevV.Type(), prevV.Name(), ref.ID()})

		case valuetype.ReferenceList:
			var IDs []string
			for _, refID := range prevV.RefListIDs() {
				ref, ok := refmap[refID]
				if !ok {
					skip = true
					continue
				}
				IDs = append(IDs, ref.ID())
			}
			params = append(params, ContentNewParam{prevV.Type(), prevV.Name(), strings.Join(IDs, "-")})

		default:
			params = append(params, ContentNewParam{prevV.Type(), prevV.Name(), prevV.Value()})

		}
	}

	c, err := db.contentNew(t, next, ct, params, defaultDepth)
	if err != nil {
		return false, err
	}

	refmap[prevC.ID()] = c

	return !skip, nil
}

func (db *DB) spaceUpdateContent(t *sql.Tx, next space.Space, ct contenttype.ContentType, prevC content.Content, refmap map[string]content.Content) error {
	var params []ContentNewParam

	for _, prevF := range ct.Fields() {
		prevV, ok := prevC.ValueByName(prevF.Name())
		if !ok {
			if prevF.Type() == valuetype.Reference || prevF.Type() == valuetype.ReferenceList {
				// Referenced content was deleted.
				continue
			}

			// "null" field. E.G. empty StringSmall.
			prevV = &ContentValue{
				FieldType: string(prevF.Type()),
				FieldName: prevF.Name(),
			}
		}

		switch prevF.Type() {

		case valuetype.Reference:
			ref, ok := refmap[prevV.RefID()]
			if !ok {
				return errors.New("failed to copy reference value: content not created")
			}
			params = append(params, ContentNewParam{prevV.Type(), prevV.Name(), ref.ID()})

		case valuetype.ReferenceList:
			var IDs []string
			for _, refID := range prevV.RefListIDs() {
				ref, ok := refmap[refID]
				if !ok {
					return errors.New("failed to copy reference list value(s): content not created")
				}
				IDs = append(IDs, ref.ID())
			}
			params = append(params, ContentNewParam{prevV.Type(), prevV.Name(), strings.Join(IDs, "-")})

		}
	}

	return db.contentUpdate(t, next, ct, refmap[prevC.ID()], params, []ContentUpdateParam{})
}

func (db *DB) spaceGet(t *sql.Tx, user user.User, spaceID string) (space.Space, error) {
	var s Space
	err := t.QueryRow(queryFindSpaceByUserAndID, user.ID(), spaceID).Scan(
		&s.SpaceID, &s.SpaceName, &s.SpaceDesc,
		&s.SpaceOrg.OrgID, &s.SpaceOrg.OrgBillingTierName, &s.SpaceOrg.OrgPaymentCustomer,
	)
	if err != nil {
		return nil, fmt.Errorf("failed to find space")
	}
	return &s, nil
}

func (db *DB) SpaceGet(user user.User, spaceID string) (space.Space, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	space, err := db.spaceGet(t, user, spaceID)
	if err != nil {
		return nil, err
	}

	return space, t.Commit()
}

func (db *DB) SpaceDelete(user user.User, space space.Space) error {
	t, err := db.Begin()
	if err != nil {
		return err
	}
	defer t.Rollback()

	if _, err := t.Exec(queryDeleteSpace, user.ID(), space.ID()); err != nil {
		return err
	}

	return t.Commit()
}

func (db *DB) spacesPerUser(t *sql.Tx, user user.User, before int) (space.SpaceList, error) {
	var (
		r       []space.Space
		id      int
		hasMore bool
	)

	before = beformat(before)

	q := `
		SELECT cms_space.ID FROM cms_space
		JOIN cms_org ON cms_org.ID=cms_space.ORG_ID
		JOIN cms_user on cms_user.ORG_ID=cms_org.ID
		WHERE cms_user.ID=? AND cms_space.ID<?
		ORDER BY cms_space.ID DESC LIMIT ?
	`

	rows, err := t.Query(q, user.ID(), before, perPage+1)
	if err != nil {
		return nil, err
	}

	var ids []int
	for i := 0; rows.Next(); i++ {
		if i == perPage {
			hasMore = true
			break
		}

		if err := rows.Scan(&id); err != nil {
			return nil, err
		}

		ids = append(ids, id)
	}

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

	for _, id := range ids {
		s, err := db.spaceGet(t, user, strconv.Itoa(id))
		if err != nil {
			return nil, err
		}

		r = append(r, s)
	}

	return newSpaceList(r, hasMore, id), nil
}

func (db *DB) SpacesPerUser(user user.User, before int) (space.SpaceList, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	list, err := db.spacesPerUser(t, user, before)
	if err != nil {
		return nil, err
	}

	return list, t.Commit()
}

func (s *Space) ID() string   { return s.SpaceID }
func (s *Space) Name() string { return s.SpaceName }
func (s *Space) Desc() string { return s.SpaceDesc }
func (s *Space) Org() org.Org { return s.SpaceOrg }

// SPACE LIST STRUCT / INTERFACE

type SpaceList struct {
	SpaceList       []space.Space
	SpaceListMore   bool
	SpaceListBefore int
}

func newSpaceList(list []space.Space, hasMore bool, last int) *SpaceList {
	return &SpaceList{list, hasMore, last}
}

func (sl *SpaceList) List() []space.Space { return sl.SpaceList }
func (sl *SpaceList) More() bool          { return sl.SpaceListMore }
func (sl *SpaceList) Before() int         { return sl.SpaceListBefore }