~evanj/cms

ref: 892c0c7ea54f6c330a9c4acf52ccfc1ab091b121 cms/internal/s/db/contenttype.go -rw-r--r-- 11.8 KiB
892c0c7eEvan J Feat(pkg/flushresp): Break out wrapped response writer into its own 1 year, 17 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
package db

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

	"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 ContentType struct {
	ContentTypeID     string
	ContentTypeName   string
	ContentTypeFields []ContentTypeField
}

type ContentTypeField struct {
	FieldID   string
	FieldName string
	FieldType string
}

type ContentTypeNewParam struct {
	Name, Type string
}

type ContentTypeUpdateParam struct {
	ID, Name, Type string
}

var (
	queryCreateContentType           = `INSERT INTO cms_contenttype (NAME, SPACE_ID) VALUES (?, ?);`
	queryDeleteContentType           = `DELETE FROM cms_contenttype WHERE ID = ?;`
	queryFindContentTypeByID         = `SELECT ID, NAME FROM cms_contenttype WHERE ID = ?;`
	queryFindContentTypeByIDAndSpace = `SELECT ID, NAME FROM cms_contenttype WHERE ID = ? AND SPACE_ID = ?;`
	queryCreateContentTypeConnection = `INSERT INTO cms_contenttype_to_valuetype (NAME, CONTENTTYPE_ID, VALUETYPE_ID) VALUES (?, ?, ( SELECT ID FROM cms_valuetype WHERE VALUE = ? ));`
	queryFindValueTypes              = `SELECT cms_contenttype_to_valuetype.ID, NAME, VALUE FROM cms_contenttype_to_valuetype JOIN cms_valuetype ON VALUETYPE_ID = cms_valuetype.ID WHERE CONTENTTYPE_ID = ? ORDER BY cms_contenttype_to_valuetype.ID ASC;`

	queryDeleteContentTypeFieldsNotIn = func(values []int) string {
		// WARNING, DANGEROUS. SQL injection will not occur here because we converted
		// to ints, but be careful of updating this code in the future.
		var fieldStringIDs []string
		for _, i := range values {
			str := strconv.Itoa(i)
			fieldStringIDs = append(fieldStringIDs, str)
		}

		return fmt.Sprintf(`DELETE FROM cms_contenttype_to_valuetype 
			WHERE CONTENTTYPE_ID = ?
			AND ID NOT IN (%s)
		`, strings.Join(fieldStringIDs, ", "))
	}

	queryUpdateContentTypeFieldNames = `
		UPDATE cms_contenttype_to_valuetype
		SET NAME = ?
		WHERE ID = ?
	`

	queryUpdateContentTypeName = `
		UPDATE cms_contenttype
		SET NAME = ?
		WHERE ID = ?
	`
)

func (db *DB) ContentTypeNew(ctx context.Context, u user.User, space space.Space, name string, params []ContentTypeNewParam) (contenttype.ContentType, error) {
	t, err := db.BeginTx(ctx, nil)
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	res, err := t.ExecContext(ctx, queryCreateContentType, name, space.ID())
	if err != nil {
		return nil, err
	}

	id, err := res.LastInsertId()
	if err != nil {
		return nil, fmt.Errorf("failed to find identifier of contenttype")
	}

	for _, item := range params {
		db.log.Println(item, id)
		if _, err := t.ExecContext(ctx, queryCreateContentTypeConnection, item.Name, id, item.Type); err != nil {
			return nil, fmt.Errorf("failed to create field(s)")
		}
	}

	var ct ContentType
	if err := t.QueryRowContext(ctx, queryFindContentTypeByID, id).Scan(&ct.ContentTypeID, &ct.ContentTypeName); err != nil {
		return nil, fmt.Errorf("failed to find user created")
	}

	rows, err := t.QueryContext(ctx, queryFindValueTypes, ct.ContentTypeID)
	if err != nil {
		return nil, fmt.Errorf("failed to find field(s)")
	}
	for rows.Next() {
		var field ContentTypeField
		if err := rows.Scan(&field.FieldID, &field.FieldName, &field.FieldType); err != nil {
			return nil, fmt.Errorf("failed to scan field(s)")
		}
		ct.ContentTypeFields = append(ct.ContentTypeFields, field)
	}

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

	if len(ct.ContentTypeFields) != len(params) {
		return nil, fmt.Errorf("failed to create all fields")
	}

	return &ct, t.Commit()
}

// ContentTypeUpdate will either remove fields are add fields to a contenttype.
// Note: field types cannot be changed (e.g. if a field is of type InputHTML it
// cannot become a StringSmall. Field type names can be changed.
func (db *DB) ContentTypeUpdate(ctx context.Context, u user.User, space space.Space, contenttype contenttype.ContentType, name string, newParams []ContentTypeNewParam, updateParams []ContentTypeUpdateParam) (contenttype.ContentType, error) {
	t, err := db.BeginTx(ctx, nil)
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	// Gather update param IDs, delete those not within.
	// Update the names of already existing fields.

	var fieldIDs []int
	for _, p := range updateParams {
		_, err := t.ExecContext(ctx, queryUpdateContentTypeFieldNames, p.Name, p.ID)
		if err != nil {
			return nil, err
		}

		id, err := strconv.Atoi(p.ID)
		if err != nil {
			return nil, err
		}

		fieldIDs = append(fieldIDs, id)
	}

	if _, err := t.ExecContext(ctx, queryDeleteContentTypeFieldsNotIn(fieldIDs), contenttype.ID()); err != nil {
		return nil, err
	}

	// Update name of CT itself.

	if _, err := t.ExecContext(ctx, queryUpdateContentTypeName, name, contenttype.ID()); err != nil {
		return nil, err
	}

	// Create new fields given.

	for _, item := range newParams {
		if _, err := t.ExecContext(ctx, queryCreateContentTypeConnection, item.Name, contenttype.ID(), item.Type); err != nil {
			return nil, fmt.Errorf("failed to create field(s)")
		}
	}

	if err := t.Commit(); err != nil {
		return nil, err
	}

	return db.ContentTypeGet(ctx, u, space, contenttype.ID())
}

func (db *DB) contentTypesPerSpace(ctx context.Context, t *sql.Tx, space space.Space, before int) (contenttype.ContentTypeList, error) {
	var (
		r       []contenttype.ContentType
		id      int
		hasMore bool
	)

	before = beformat(before)

	q := `
		SELECT ID 
		FROM cms_contenttype
		WHERE SPACE_ID = ? AND ID < ?
		ORDER BY ID DESC LIMIT ?
	`

	rows, err := t.QueryContext(ctx, q, space.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 {
		ct, err := db.contentTypeGet(ctx, t, space, strconv.Itoa(id))
		if err != nil {
			return nil, err
		}

		r = append(r, ct)
	}

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

func (db *DB) ContentTypesPerSpace(ctx context.Context, u user.User, space space.Space, before int) (contenttype.ContentTypeList, error) {
	t, err := db.BeginTx(ctx, nil)
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	list, err := db.contentTypesPerSpace(ctx, t, space, before)
	if err != nil {
		return nil, err
	}

	return list, t.Commit()
}

func (db *DB) contentTypeGet(ctx context.Context, t *sql.Tx, space space.Space, contenttypeID string) (contenttype.ContentType, error) {
	var ct ContentType
	if err := t.QueryRowContext(ctx, queryFindContentTypeByIDAndSpace, contenttypeID, space.ID()).Scan(&ct.ContentTypeID, &ct.ContentTypeName); err != nil {
		return nil, fmt.Errorf("failed to find contenttype for space")
	}

	rows, err := t.QueryContext(ctx, queryFindValueTypes, ct.ContentTypeID)
	if err != nil {
		return nil, fmt.Errorf("failed to find field(s)")
	}

	for rows.Next() {
		var field ContentTypeField
		if err := rows.Scan(&field.FieldID, &field.FieldName, &field.FieldType); err != nil {
			return nil, fmt.Errorf("failed to scan field(s)")
		}
		ct.ContentTypeFields = append(ct.ContentTypeFields, field)
	}

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

	return &ct, nil
}

func (db *DB) ContentTypeGet(ctx context.Context, u user.User, space space.Space, contenttypeID string) (contenttype.ContentType, error) {
	t, err := db.BeginTx(ctx, nil)
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	ct, err := db.contentTypeGet(ctx, t, space, contenttypeID)
	if err != nil {
		return nil, err
	}

	return ct, t.Commit()
}

// TODO: Consolidate with other list function here. They are the same except for
// the query used.
func (db *DB) ContentTypeSearch(ctx context.Context, u user.User, space space.Space, query string, before int) (contenttype.ContentTypeList, error) {
	t, err := db.BeginTx(ctx, nil)
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	list, err := db.contentTypeSearch(ctx, t, u, space, query, before)
	if err != nil {
		return nil, err
	}

	return list, t.Commit()
}

func (db *DB) contentTypeSearch(ctx context.Context, t *sql.Tx, u user.User, space space.Space, query string, before int) (contenttype.ContentTypeList, error) {
	var (
		r       []contenttype.ContentType
		id      int
		hasMore bool
	)

	before = beformat(before)

	// TODO: May want to make a temp table for this query for proper ordering.
	q := `SELECT ID FROM cms_contenttype WHERE NAME LIKE ? AND SPACE_ID = ? AND ID < ? ORDER BY ID DESC LIMIT ?`

	rows, err := t.QueryContext(ctx, q, fmt.Sprintf("%%%s%%", query), space.ID(), before, perPage)
	if err != nil {
		return nil, err
	}

	var ids []int
	for rows.Next() {
		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 {
		ct, err := db.contentTypeGet(ctx, t, space, strconv.Itoa(id))
		if err != nil {
			return nil, err
		}

		r = append(r, ct)
	}

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

func (db *DB) ContentTypeDelete(ctx context.Context, u user.User, space space.Space, ct contenttype.ContentType) error {
	t, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer t.Rollback()

	if _, err := t.ExecContext(ctx, queryDeleteContentType, ct.ID()); err != nil {
		return err
	}

	return t.Commit()
}

func (ct *ContentType) ID() string {
	return ct.ContentTypeID
}

func (ct *ContentType) Name() string {
	return ct.ContentTypeName
}

func (ct *ContentType) FieldsWithRefCount() (count int) {
	for _, item := range ct.ContentTypeFields {
		switch item.Type() {
		case valuetype.Reference:
			fallthrough
		case valuetype.ReferenceList:
			count++
		}
	}
	return
}

func (ct *ContentType) Fields() []valuetype.ValueType {
	var ret []valuetype.ValueType
	for _, item := range ct.ContentTypeFields {
		ret = append(ret, &ContentTypeField{
			item.FieldID,
			item.FieldName,
			item.FieldType,
		})
	}
	return ret
}

func (f *ContentTypeField) ID() string {
	return f.FieldID
}

func (f *ContentTypeField) Name() string {
	return f.FieldName
}

func (f *ContentTypeField) Type() string {
	return f.FieldType
}

type contentTypeIter struct {
	db    *DB
	ctx   context.Context
	t     *sql.Tx
	space space.Space

	// For pump
	list contenttype.ContentTypeList
	err  error
}

func (db *DB) ContentTypeIter(ctx context.Context, t *sql.Tx, u user.User, space space.Space) *contentTypeIter {
	iter := &contentTypeIter{db, ctx, t, space, newContentTypeList(nil, false, 0), nil}
	iter.pump()
	return iter
}

func (iter *contentTypeIter) pump() {
	list, err := iter.db.contentTypesPerSpace(iter.ctx, iter.t, iter.space, iter.list.Before())
	iter.list = list
	iter.err = err
}

func (iter *contentTypeIter) Next() bool {
	if iter.err != nil {
		return true // Error is picked up with Scan call.
	}
	return len(iter.list.List()) > 0
}

func (iter *contentTypeIter) Scan() (contenttype.ContentType, error) {
	var (
		first contenttype.ContentType
		err   error
	)

	if iter.err != nil {
		return first, iter.err
	}

	list := iter.list.List()
	first, rest := list[0], list[1:]

	iter.list = newContentTypeList(rest, iter.list.More(), iter.list.Before())
	if err != nil {
		return nil, err
	}

	if len(iter.list.List()) < 1 {
		iter.pump()
	}

	return first, nil
}

// CONTENT TYPE LIST STRUCT / INTERFACE

type ContentTypeList struct {
	ContentTypeList       []contenttype.ContentType
	ContentTypeListMore   bool
	ContentTypeListBefore int
}

func newContentTypeList(list []contenttype.ContentType, hasMore bool, last int) *ContentTypeList {
	return &ContentTypeList{list, hasMore, last}
}

func (ctl *ContentTypeList) List() []contenttype.ContentType { return ctl.ContentTypeList }
func (ctl *ContentTypeList) More() bool                      { return ctl.ContentTypeListMore }
func (ctl *ContentTypeList) Before() int                     { return ctl.ContentTypeListBefore }