~evanj/cms

ref: 4aa45cc85249c542c4d80aed47e25c86145bcc3c cms/internal/s/db/content.go -rw-r--r-- 11.9 KiB
4aa45cc8Evan M Jones Feat(mysql): Moving to mysql. Getting ready for alpha release (just for 8 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
package db

import (
	"encoding/json"
	"fmt"

	"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/value"
	"git.sr.ht/~evanj/cms/internal/m/valuetype"
)

type Content struct {
	id            string
	contenttypeID string

	contenttype contenttype.ContentType
	values      []ContentValue
}

type ContentValue struct {
	id    string
	typ   string // StringSmall
	name  string // Title of a blog post
	value string // "My First Blog Post!"
}

const (
	queryContentNew = `
		INSERT INTO cms_content (CONTENTTYPE_ID) 
		VALUES (?);
	`

	queryContentDelete = `
		-- Delete joined values.
		DELETE FROM cms_value_string_small 
		WHERE ID IN ( SELECT ID FROM cms_value WHERE CONTENT_ID = ? );
		DELETE FROM cms_value_string_big
		WHERE ID IN ( SELECT ID FROM cms_value WHERE CONTENT_ID = ? );
		DELETE FROM cms_value_date
		WHERE ID IN ( SELECT ID FROM cms_value WHERE CONTENT_ID = ? );
		-- Delete attached values.
		DELETE FROM cms_value
		WHERE CONTENT_ID = ?;
		-- Delete content itself.
		DELETE FROM cms_content 
		WHERE ID = ?;
	`

	queryContentGetByID = `
		SELECT ID, CONTENTTYPE_ID 
		FROM cms_content 
		WHERE ID = ?;
	`

	queryContentListByContentType = `
		SELECT ID, CONTENTTYPE_ID 
		FROM cms_content 
		WHERE CONTENTTYPE_ID = ? LIMIT ? OFFSET ?;
	`

	queryValueNew = `
		INSERT INTO cms_value (CONTENT_ID, CONTENTTYPE_TO_VALUETYPE_ID, VALUE_ID)
		VALUES (?, (SELECT ID FROM cms_contenttype_to_valuetype WHERE CONTENTTYPE_ID = ? AND NAME = ? LIMIT 1), ?);
	`

	queryValueNewStringSmall = `
		INSERT INTO cms_value_string_small (VALUE) 
		VALUES (?);
	`

	queryValueNewStringBig = `
		INSERT INTO cms_value_string_big (VALUE) 
		VALUES (?);
	`

	queryValueNewDate = `
		INSERT INTO cms_value_date (VALUE) 
		VALUES (?);
	`

	queryValueUpdateStringSmall = `
		UPDATE cms_value_string_small
		SET value = ?
		WHERE cms_value_string_small.ID IN ( SELECT VALUE_ID FROM cms_value WHERE cms_value.ID = ? );
	`

	queryValueUpdateStringBig = `
		UPDATE cms_value_string_big
		SET value = ?
		WHERE cms_value_string_big.ID IN ( SELECT VALUE_ID FROM cms_value WHERE cms_value.ID = ? );
	`

	queryValueUpdateDate = `
		UPDATE cms_value_date
		SET value = ?
		WHERE cms_value_date.ID IN ( SELECT VALUE_ID FROM cms_value WHERE cms_value.ID = ? );
	`

	queryValueGetStringSmallByID = `
		SELECT cms_value.ID as ID, cms_valuetype.VALUE as TYPE, cms_contenttype_to_valuetype.NAME, cms_value_string_small.VALUE
		FROM cms_value
		JOIN cms_contenttype_to_valuetype
		ON cms_contenttype_to_valuetype.ID = cms_value.CONTENTTYPE_TO_VALUETYPE_ID
		JOIN cms_valuetype
		ON cms_valuetype.ID = cms_contenttype_to_valuetype.VALUETYPE_ID
		JOIN cms_value_string_small
		ON cms_value_string_small.ID = cms_value.VALUE_ID
		WHERE cms_value.ID = ?;
	`

	queryValueGetStringBigByID = `
		SELECT cms_value.ID as ID, cms_valuetype.VALUE as TYPE, cms_contenttype_to_valuetype.NAME, cms_value_string_big.VALUE
		FROM cms_value
		JOIN cms_contenttype_to_valuetype
		ON cms_contenttype_to_valuetype.ID = cms_value.CONTENTTYPE_TO_VALUETYPE_ID
		JOIN cms_valuetype
		ON cms_valuetype.ID = cms_contenttype_to_valuetype.VALUETYPE_ID
		JOIN cms_value_string_big
		ON cms_value_string_big.ID = cms_value.VALUE_ID
		WHERE cms_value.ID = ?;
	`

	queryValueGetDateByID = `
		SELECT cms_value.ID as ID, cms_valuetype.VALUE as TYPE, cms_contenttype_to_valuetype.NAME, cms_value_date.VALUE
		FROM cms_value
		JOIN cms_contenttype_to_valuetype
		ON cms_contenttype_to_valuetype.ID = cms_value.CONTENTTYPE_TO_VALUETYPE_ID
		JOIN cms_valuetype
		ON cms_valuetype.ID = cms_contenttype_to_valuetype.VALUETYPE_ID
		JOIN cms_value_date
		ON cms_value_date.ID = cms_value.VALUE_ID
		WHERE cms_value.ID = ?;
	`

	queryValueListByContent = `
		SELECT ID, TYPE, NAME, VALUE FROM (

			SELECT cms_value.ID as ID, cms_valuetype.VALUE as TYPE, cms_contenttype_to_valuetype.NAME, cms_value_string_small.VALUE, cms_contenttype_to_valuetype.ID as ORDER_ID
			FROM cms_value
			JOIN cms_contenttype_to_valuetype
			ON cms_contenttype_to_valuetype.ID = cms_value.CONTENTTYPE_TO_VALUETYPE_ID
			JOIN cms_valuetype
			ON cms_valuetype.ID = cms_contenttype_to_valuetype.VALUETYPE_ID
			JOIN cms_value_string_small
			ON cms_value_string_small.ID = cms_value.VALUE_ID
			WHERE CONTENT_ID = ?
			AND (
				cms_valuetype.VALUE = 'StringSmall'
				OR cms_valuetype.VALUE = 'File'
			)

			UNION

			SELECT cms_value.ID as ID, cms_valuetype.VALUE as TYPE, cms_contenttype_to_valuetype.NAME, cms_value_date.VALUE, cms_contenttype_to_valuetype.ID as ORDER_ID
			FROM cms_value
			JOIN cms_contenttype_to_valuetype
			ON cms_contenttype_to_valuetype.ID = cms_value.CONTENTTYPE_TO_VALUETYPE_ID
			JOIN cms_valuetype
			ON cms_valuetype.ID = cms_contenttype_to_valuetype.VALUETYPE_ID
			JOIN cms_value_date
			ON cms_value_date.ID = cms_value.VALUE_ID
			WHERE CONTENT_ID = ?
			AND (
				cms_valuetype.VALUE = 'Date'
			)
			
			UNION

			SELECT cms_value.ID as ID, cms_valuetype.VALUE as TYPE, cms_contenttype_to_valuetype.NAME, cms_value_string_big.VALUE, cms_contenttype_to_valuetype.ID as ORDER_ID
			FROM cms_value
			JOIN cms_contenttype_to_valuetype
			ON cms_contenttype_to_valuetype.ID = cms_value.CONTENTTYPE_TO_VALUETYPE_ID
			JOIN cms_valuetype
			ON cms_valuetype.ID = cms_contenttype_to_valuetype.VALUETYPE_ID
			JOIN cms_value_string_big
			ON cms_value_string_big.ID = cms_value.VALUE_ID
			WHERE CONTENT_ID = ?
			AND (
				cms_valuetype.VALUE = 'StringBig'
				OR cms_valuetype.VALUE = 'InputHTML'
				OR cms_valuetype.VALUE = 'InputMarkdown'
			)

		) AS A

		ORDER BY ORDER_ID ASC;
	`
)

type ContentNewParam struct {
	Type  string
	Name  string
	Value string
}

func (db *DB) ContentNew(space space.Space, ct contenttype.ContentType, params []ContentNewParam) (content.Content, error) {
	res, err := db.Exec(queryContentNew, ct.ID())
	if err != nil {
		db.log.Println("db.Exec", err)
		return nil, fmt.Errorf("failed to create new content attached to contenttype of '%s'", ct.Name())
	}

	contentID, err := res.LastInsertId()
	if err != nil {
		db.log.Println("res.LastInsertId", err)
		return nil, fmt.Errorf("failed to read new content attached to contenttype of '%s'", ct.Name())
	}

	var content Content
	if err := db.QueryRow(queryContentGetByID, contentID).Scan(&content.id, &content.contenttypeID); err != nil {
		db.log.Println("db.QueryRow", err)
		return nil, fmt.Errorf("failed to find content created")
	}

	for _, item := range params {
		queryValueNewType, queryValueGetTypeByID, _, err := db.valueQuerySetByType(item.Type)
		if err != nil {
			return nil, err
		}

		res, err := db.Exec(queryValueNewType, item.Value)
		if err != nil {
			// TODO cleanup orphan content.
			db.log.Println("db.Exec", err)
			return nil, fmt.Errorf("failed to attach field value of content")
		}

		valueID, err := res.LastInsertId()
		if err != nil {
			db.log.Println("res.LastInsertId", err)
			return nil, fmt.Errorf("failed to read new field value of content")
		}

		res, err = db.Exec(queryValueNew, contentID, ct.ID(), item.Name, valueID)
		if err != nil {
			// TODO cleanup orphan content.
			db.log.Println("db.Exec", err)
			return nil, fmt.Errorf("failed to attach field value of content")
		}

		valueID, err = res.LastInsertId()
		if err != nil {
			db.log.Println("res.LastInsertId", err)
			return nil, fmt.Errorf("failed to read new field value of content")
		}

		var value ContentValue
		if err := db.QueryRow(queryValueGetTypeByID, valueID).Scan(&value.id, &value.typ, &value.name, &value.value); err != nil {
			db.log.Println("db.QueryRow", err)
			return nil, fmt.Errorf("failed to find value created")
		}
		content.values = append(content.values, value)
	}

	if len(ct.Fields()) != len(content.values) {
		return nil, fmt.Errorf("failed to create all values")
	}

	content.contenttype = ct
	return &content, nil
}

type ContentUpdateParam struct {
	ID    string
	Type  string
	Value string
}

func (db *DB) ContentUpdate(space space.Space, ct contenttype.ContentType, content content.Content, params []ContentUpdateParam) (content.Content, error) {
	for _, item := range params {
		_, _, queryValueUpdate, err := db.valueQuerySetByType(item.Type)
		if err != nil {
			return nil, err
		}
		if _, err := db.Exec(queryValueUpdate, item.Value, item.ID); err != nil {
			db.log.Println("db.Exec", err)
			return nil, fmt.Errorf("failed to create update content value '%s'", item.Value)
		}
	}
	return db.ContentGet(space, ct, content.ID())
}

func (db *DB) ContentDelete(space space.Space, ct contenttype.ContentType, content content.Content) error {
	id := content.ID()
	_, err := db.Exec(queryContentDelete, id, id, id, id, id)
	return err
}

func (db *DB) ContentPerContentType(space space.Space, ct contenttype.ContentType, page int) ([]content.Content, error) {
	var ret []content.Content
	rows, err := db.Query(queryContentListByContentType, ct.ID(), perPage, perPage*page)
	if err != nil {
		db.log.Println(err)
		return nil, err
	}

	for rows.Next() {
		var content Content
		if err := rows.Scan(&content.id, &content.contenttypeID); err != nil {
			return nil, err
		}

		rows, err := db.Query(queryValueListByContent, content.id, content.id, content.id)
		if err != nil {
			db.log.Println(err)
			return nil, err
		}

		for rows.Next() {
			var value ContentValue
			if err := rows.Scan(&value.id, &value.typ, &value.name, &value.value); err != nil {
				return nil, err
			}
			content.values = append(content.values, value)
		}

		ret = append(ret, &content)
	}

	return ret, nil
}

func (db *DB) ContentGet(space space.Space, ct contenttype.ContentType, contentID string) (content.Content, error) {
	var content Content
	if err := db.QueryRow(queryContentGetByID, contentID).Scan(&content.id, &content.contenttypeID); err != nil {
		db.log.Println("db.QueryRow", err)
		return nil, fmt.Errorf("failed to find space")
	}

	rows, err := db.Query(queryValueListByContent, content.ID(), content.ID(), content.ID())
	if err != nil {
		db.log.Println(err)
		return nil, fmt.Errorf("failed to find values(s)")
	}

	for rows.Next() {
		var value ContentValue
		if err := rows.Scan(&value.id, &value.typ, &value.name, &value.value); err != nil {
			return nil, fmt.Errorf("failed to scan values(s)")
		}
		content.values = append(content.values, value)
	}

	content.contenttype = ct
	return &content, nil
}

func (db *DB) valueQuerySetByType(typ valuetype.ValueTypeEnum) (insert, get, update string, err error) {
	switch typ {

	case valuetype.StringSmall:
		fallthrough
	case valuetype.File:
		return queryValueNewStringSmall, queryValueGetStringSmallByID, queryValueUpdateStringSmall, nil

	case valuetype.StringBig:
		fallthrough
	case valuetype.InputHTML:
		fallthrough
	case valuetype.InputMarkdown:
		return queryValueNewStringBig, queryValueGetStringBigByID, queryValueUpdateStringBig, nil

	case valuetype.Date:
		return queryValueNewDate, queryValueGetDateByID, queryValueUpdateDate, nil

	}

	return "", "", "", fmt.Errorf("%s is not a valid valuetype", typ)
}

func (c *Content) ID() string {
	return c.id
}

func (c *Content) Type() contenttype.ContentType {
	return c.contenttype
}

func (c *Content) Values() []value.Value {
	var ret []value.Value
	for _, item := range c.values {
		ret = append(ret, &ContentValue{
			item.id,
			item.typ,
			item.name,
			item.value,
		})
	}
	return ret
}

func (c *Content) ValueByName(name string) (value.Value, bool) {
	for _, val := range c.Values() {
		if val.Name() == name {
			return val, true
		}
	}
	return nil, false
}

func (c *Content) MustValueByName(name string) (ret value.Value) {
	val, ok := c.ValueByName(name)
	if ok {
		return val
	}
	return
}

func (c *Content) MarshalJSON() ([]byte, error) {
	fields := make(map[string]string)
	for _, item := range c.Values() {
		fields[item.Name()] = item.Value()
	}

	values := make(map[string]interface{})
	values["id"] = c.ID()
	values["fields"] = fields

	return json.Marshal(values)
}

func (c *ContentValue) ID() string {
	return c.id
}

func (c *ContentValue) Type() string {
	return c.typ
}

func (c *ContentValue) Name() string {
	return c.name
}

func (c *ContentValue) Value() string {
	return c.value
}