~evanj/cms

ref: 41bddf091e571b359b94d1f4287ccb471fb29d03 cms/internal/s/db/contenttype.go -rw-r--r-- 11.0 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
437
438
439
440
441
442
443
444
package db

import (
	"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/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(space space.Space, name string, params []ContentTypeNewParam) (contenttype.ContentType, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	res, err := t.Exec(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 {
		if _, err := t.Exec(queryCreateContentTypeConnection, item.Name, id, item.Type); err != nil {
			return nil, fmt.Errorf("failed to create field(s)")
		}
	}

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

	rows, err := t.Query(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 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(space space.Space, contenttype contenttype.ContentType, name string, newParams []ContentTypeNewParam, updateParams []ContentTypeUpdateParam) (contenttype.ContentType, error) {
	t, err := db.Begin()
	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.Exec(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.Exec(queryDeleteContentTypeFieldsNotIn(fieldIDs), contenttype.ID()); err != nil {
		return nil, err
	}

	// Update name of CT itself.

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

	// Create new fields given.

	for _, item := range newParams {
		if _, err := t.Exec(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(space, contenttype.ID())
}

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

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

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

	rows, err := db.Query(q, space.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
		}

		ct, err := db.contentTypeGet(t, space, strconv.Itoa(id))
		if err != nil {
			return nil, err
		}

		r = append(r, ct)
	}

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

func (db *DB) ContentTypesPerSpace(space space.Space, perPage, before, after int) (contenttype.ContentTypeList, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	list, err := db.contentTypesPerSpace(t, space, perPage, before, after)
	if err != nil {
		db.log.Println(err)
		return nil, err
	}

	return list, t.Commit()
}

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

	rows, err := t.Query(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)
	}

	return &ct, nil
}

func (db *DB) ContentTypeGet(space space.Space, contenttypeID string) (contenttype.ContentType, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	ct, err := db.contentTypeGet(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(space space.Space, query string, perPage, before, after int) (contenttype.ContentTypeList, error) {
	var (
		r       []contenttype.ContentType
		first   int
		id      int
		hasMore bool
	)

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

	// 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 < ?  AND ID > ? ORDER BY ID DESC LIMIT ?`

	rows, err := db.Query(q, fmt.Sprintf("%%%s%%", query), space.ID(), before, after, perPage)
	if err != nil {
		db.log.Println("1", err)
		return nil, err
	}

	for rows.Next() {
		if err := rows.Scan(&id); err != nil {
			db.log.Println("2", err)
			return nil, err
		}

		if first == 0 {
			first = id
		}

		ct, err := db.ContentTypeGet(space, strconv.Itoa(id))
		if err != nil {
			db.log.Println("3", err)
			return nil, err
		}

		r = append(r, ct)
	}

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

func (db *DB) ContentTypeDelete(space space.Space, ct contenttype.ContentType) error {
	t, err := db.Begin()
	if err != nil {
		return err
	}
	defer t.Rollback()

	if _, err := t.Exec(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
	t     *sql.Tx
	space space.Space

	// For pump
	list contenttype.ContentTypeList
	err  error
}

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

func (iter *contentTypeIter) pump() {
	list, err := iter.db.contentTypesPerSpace(iter.t, iter.space, maxPerPage, iter.list.Before(), iter.list.After())
	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(), iter.list.After())
	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
	ContentTypeListAfter  int
}

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

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 }
func (ctl *ContentTypeList) After() int                      { return ctl.ContentTypeListAfter }