~evanj/cms

ref: 41bddf091e571b359b94d1f4287ccb471fb29d03 cms/internal/s/db/space.go -rw-r--r-- 9.9 KiB
41bddf09Evan M Jones WIP(perPage/after): Testing to see if this is viable. 4 months 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
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/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
}

var (
	queryCreateNewSpace       = `INSERT INTO cms_space (NAME, DESCRIPTION) VALUES (?, ?);`
	queryUpdateSpace          = `UPDATE cms_space SET NAME = ?, DESCRIPTION = ? WHERE ID = ?;`
	queryDeleteSpace          = `DELETE cms_user_to_space, cms_space FROM cms_space JOIN cms_user_to_space ON cms_user_to_space.SPACE_ID = cms_space.ID WHERE SPACE_ID = ? AND USER_ID = ?;`
	queryCreateNewUserToSpace = `INSERT INTO cms_user_to_space (USER_ID, SPACE_ID) VALUES (?, ?);`
	queryFindSpaceByUserAndID = `SELECT cms_space.ID, cms_space.NAME, cms_space.DESCRIPTION FROM cms_space JOIN cms_user_to_space ON SPACE_ID=cms_space.ID WHERE USER_ID=? AND SPACE_ID=?;`

	copyUsersQuery = `
		INSERT INTO cms_user_to_space (USER_ID, SPACE_ID)
		SELECT USER_ID, ?
		FROM cms_user_to_space
		WHERE 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)
	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")
	}

	if _, err := t.Exec(queryCreateNewUserToSpace, user.ID(), id); err != nil {
		return nil, fmt.Errorf("failed to attach space to user")
	}

	var space Space
	if err := t.QueryRow(queryFindSpaceByUserAndID, user.ID(), id).Scan(&space.SpaceID, &space.SpaceName, &space.SpaceDesc); err != nil {
		return nil, fmt.Errorf("failed to find space created")
	}

	return &space, nil
}

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)
	if err != nil {
		return nil, err
	}

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

	// Copy all users.
	if _, err := t.Exec(copyUsersQuery, nextID, prevS.ID()); 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, next, prevS); err != nil {
		return nil, err
	}

	return next, t.Commit()
}

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

	// 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
	var todoN []cct // Used for later for loop.

	// 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, 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, 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 {
				todo = append(todo, cct{ct, prevC})
			}
		}
	}

	// NOTE: Going over defaultDepth should be an impossible case, as we stop
	// user from creating depths of >3 elsewhere. It's a hard limit.
	for i := 0; len(todo) > 0 && i < defaultDepth; i++ {
		todoN = append(todo[:0:0], todo...) // Copy todo to todoN.
		todo = nil

		for _, set := range todoN {
			ok, err := db.spaceCopyContent(t, next, set.ct, set.c, refmap)
			if err != nil {
				return err
			}

			if !ok {
				todo = append(todo, set)
			}
		}
	}

	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

	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 false, nil
			}
			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 false, nil
				}
				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 true, nil
}

func (db *DB) spaceGet(t *sql.Tx, user user.User, spaceID string) (space.Space, error) {
	var space Space
	err := t.QueryRow(queryFindSpaceByUserAndID, user.ID(), spaceID).Scan(&space.SpaceID, &space.SpaceName, &space.SpaceDesc)
	if err != nil {
		return nil, fmt.Errorf("failed to find space")
	}
	return &space, 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, space.ID(), user.ID()); err != nil {
		return err
	}

	return t.Commit()
}

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

	before = bfmt(before)
	after = afmt(after)
	perPage = pfmt(perPage)

	q := `
		SELECT SPACE_ID FROM cms_user_to_space
		WHERE USER_ID = ? AND SPACE_ID < ? AND SPACE_ID > ?
		ORDER BY SPACE_ID DESC LIMIT ?
	`

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

	for i := 0; rows.Next(); i++ {
		if i == perPage {
			hasMore = true
			break
		}

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

		if first == 0 {
			first = id
		}

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

		r = append(r, s)
	}

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

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

	list, err := db.spacesPerUser(t, user, perPage, before, after)
	if err != nil {
		db.log.Println(err)
		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
}

// SPACE LIST STRUCT / INTERFACE

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

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

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 }
func (sl *SpaceList) After() int          { return sl.SpaceListAfter }