~evanj/cms

ref: 40c0e4fc7f8f794524c1f37f2c5d7355b4985475 cms/internal/s/db/content.go -rw-r--r-- 28.0 KiB
40c0e4fcEvan M Jones Chore(readme): Removing tag line. 1 year, 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
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
package db

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"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/value"
	"git.sr.ht/~evanj/cms/internal/m/valuetype"
)

// iota doesn't quite pass the compile time checks I want.
type OrderType struct{ val string }

var (
	OrderAsc  OrderType = OrderType{val: "ASC"}
	OrderDesc OrderType = OrderType{val: "DESC"}
)

const (
	defaultDepth = 3 // For fetching reference types.
)

type Content struct {
	// In DB.
	ContentID           string
	ContentParentTypeID string
	// We set.
	ContentValues []ContentValue
}

type ContentValue struct {
	FieldID            string
	FieldType          string            // StringSmall
	FieldName          string            // Title of a blog post
	FieldValue         string            // "My First Blog Post!"
	FieldReference     content.Content   `json:",omitempty"`
	FieldReferenceList []content.Content `json:",omitempty"`
}

type contentValueJSON struct {
	FieldID            string
	FieldType          string     // StringSmall
	FieldName          string     // Title of a blog post
	FieldValue         string     // "My First Blog Post!"
	FieldReference     *Content   `json:",omitempty"`
	FieldReferenceList []*Content `json:",omitempty"`
}

type ContentNewParam struct {
	Type  string
	Name  string
	Value string
}

type ContentUpdateParam struct {
	ID    string
	Type  string
	Value string
}

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

	queryContentDelete = []string{

		// Need delete from w/ joins per final cms_value_* table.

		`DELETE FROM cms_value_reference WHERE ID IN ( 
			SELECT VALUE_ID FROM cms_value 
			JOIN cms_contenttype_to_valuetype
			ON cms_contenttype_to_valuetype.ID = CONTENTTYPE_TO_VALUETYPE_ID
			JOIN cms_valuetype
			ON cms_valuetype.ID = VALUETYPE_ID 
			WHERE CONTENT_ID = ?
			AND cms_valuetype.VALUE = 'Reference'
		)`,

		`DELETE FROM cms_value_reference_list WHERE ID IN ( 
			SELECT VALUE_ID FROM cms_value 
			JOIN cms_contenttype_to_valuetype
			ON cms_contenttype_to_valuetype.ID = CONTENTTYPE_TO_VALUETYPE_ID
			JOIN cms_valuetype
			ON cms_valuetype.ID = VALUETYPE_ID 
			WHERE CONTENT_ID = ?
			AND cms_valuetype.VALUE = 'ReferenceList'
		)`,

		`DELETE FROM cms_value_string_small WHERE ID IN ( 
			SELECT VALUE_ID FROM cms_value 
			JOIN cms_contenttype_to_valuetype
			ON cms_contenttype_to_valuetype.ID = CONTENTTYPE_TO_VALUETYPE_ID
			JOIN cms_valuetype
			ON cms_valuetype.ID = VALUETYPE_ID 
			WHERE CONTENT_ID = ?
			AND cms_valuetype.VALUE = 'StringSmall'
		)`,

		`DELETE FROM cms_value_string_big WHERE ID IN ( 
			SELECT VALUE_ID FROM cms_value 
			JOIN cms_contenttype_to_valuetype
			ON cms_contenttype_to_valuetype.ID = CONTENTTYPE_TO_VALUETYPE_ID
			JOIN cms_valuetype
			ON cms_valuetype.ID = VALUETYPE_ID 
			WHERE CONTENT_ID = ?
			AND cms_valuetype.VALUE = 'StringBig'
		)`,

		`DELETE FROM cms_value_date WHERE ID IN ( 
			SELECT VALUE_ID FROM cms_value 
			JOIN cms_contenttype_to_valuetype
			ON cms_contenttype_to_valuetype.ID = CONTENTTYPE_TO_VALUETYPE_ID
			JOIN cms_valuetype
			ON cms_valuetype.ID = VALUETYPE_ID 
			WHERE CONTENT_ID = ?
			AND cms_valuetype.VALUE = 'Date'
		)`,

		"DELETE FROM cms_value WHERE CONTENT_ID = ?;", // TODO: I don't think we actually need this query due to cascades.
		"DELETE FROM cms_content WHERE ID = ?;",
	}

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

	queryContentListByContentType = func(order OrderType) string {
		// Careful, we only do this for OrderType.
		return fmt.Sprintf(`
			SELECT cms_content.ID, cms_content.CONTENTTYPE_ID
			FROM cms_value
	
			JOIN cms_content
			ON cms_value.CONTENT_ID = cms_content.ID
	
			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
	
			LEFT JOIN cms_value_string_small
			ON cms_value_string_small.ID = cms_value.VALUE_ID
	
			LEFT JOIN cms_value_string_big
			ON cms_value_string_big.ID = cms_value.VALUE_ID
			
			LEFT JOIN cms_value_date
			ON cms_value_date.ID = cms_value.VALUE_ID
	
		 	WHERE cms_content.CONTENTTYPE_ID = ? 
		 	AND cms_contenttype_to_valuetype.NAME = ?
	
			ORDER BY cms_value_date.VALUE %s, cms_value_string_small.VALUE %s, cms_value_string_big.VALUE %s
		 	LIMIT ? OFFSET ?
		`, order.val, order.val, order.val)
	}

	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 (?);
	`

	queryValueNewReference = `
		INSERT INTO cms_value_reference (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 = ? );
	`

	queryValueUpdateReference = `
		UPDATE cms_value_reference
		SET value = ?
		WHERE cms_value_reference.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 = ?;
	`

	queryValueGetReferenceByID = `
		SELECT cms_value.ID as ID, cms_valuetype.VALUE as TYPE, cms_contenttype_to_valuetype.NAME, cms_value_reference.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_reference
		ON cms_value_reference.ID = cms_value.VALUE_ID
		WHERE cms_value.ID = ?;
	`

	queryValueGetReferenceListByID = `
		SELECT cms_value.ID as ID, cms_valuetype.VALUE as TYPE, cms_contenttype_to_valuetype.NAME
		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_reference_list
		ON cms_value_reference_list.ID = cms_value.VALUE_ID
		WHERE cms_value.ID = ?;
	`

	queryValueGetReferenceListValuesByID = `
		SELECT cms_value.ID as ID, cms_valuetype.VALUE as TYPE, cms_contenttype_to_valuetype.NAME, cms_value_reference_list_values.CONTENT_ID as 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_reference_list
		ON cms_value_reference_list.ID = cms_value.VALUE_ID
		JOIN cms_value_reference_list_values
		ON cms_value_reference_list.ID = cms_value_reference_list_values.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'
			)

			UNION

			SELECT cms_value.ID as ID, cms_valuetype.VALUE as TYPE, cms_contenttype_to_valuetype.NAME, cms_value_reference.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_reference
			ON cms_value_reference.ID = cms_value.VALUE_ID
			WHERE CONTENT_ID = ?
			AND (
				cms_valuetype.VALUE = 'Reference'
			)

			UNION

			SELECT cms_value.ID as ID, cms_valuetype.VALUE as TYPE, cms_contenttype_to_valuetype.NAME, cms_value_reference_list.ID as 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_reference_list
			ON cms_value_reference_list.ID = cms_value.VALUE_ID
			WHERE CONTENT_ID = ?
			AND (
				cms_valuetype.VALUE = 'ReferenceList'
			)

		) AS A

		ORDER BY ORDER_ID ASC;
	`

	queryContentListByNameAndContentType = `
		SELECT cms_content.ID
		FROM cms_value

		JOIN cms_content
		ON cms_value.CONTENT_ID = cms_content.ID

		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

		LEFT JOIN cms_value_string_small
		ON cms_value_string_small.ID = cms_value.VALUE_ID

		LEFT JOIN cms_value_string_big
		ON cms_value_string_big.ID = cms_value.VALUE_ID
		
		LEFT JOIN cms_value_date
		ON cms_value_date.ID = cms_value.VALUE_ID

	 	WHERE cms_content.CONTENTTYPE_ID = ? 
	 	AND cms_contenttype_to_valuetype.NAME = ?
	 	AND (
			cms_value_string_small.VALUE LIKE ?
			OR cms_value_date.VALUE LIKE ?
		)
	 	LIMIT ? OFFSET ?;
	`
)

func (db *DB) valueReferenceListUpdate(s space.Space, ct contenttype.ContentType, c *Content, t *sql.Tx, valueID string, IDs []string, depth int) error {
	if len(IDs) < 1 {
		return fmt.Errorf("reference list type has no values")
	}

	// wipe out old list values
	// create new list values
	// TODO: Remove these inline queries, please.
	var refListID string
	if err := t.QueryRow("SELECT cms_value_reference_list.ID FROM cms_value JOIN cms_value_reference_list ON cms_value_reference_list.ID = cms_value.VALUE_ID WHERE cms_value.ID = ?", valueID).Scan(&refListID); err != nil {
		db.log.Println("valueID", valueID, "Error", err)
		return fmt.Errorf("failed to query for reference list identifier before reference list update")
	}

	if _, err := t.Exec("DELETE FROM cms_value_reference_list_values WHERE VALUE_ID = ?", refListID); err != nil {
		return fmt.Errorf("failed to remove old reference list values before update")
	}

	var value ContentValue
	value.FieldValue = strings.Join(IDs, "-") // Match what client should send us.
	if err := t.QueryRow(queryValueGetReferenceListByID, valueID).Scan(&value.FieldID, &value.FieldType, &value.FieldName); err != nil {
		return err
	}

	for _, cid := range IDs {
		_, err := t.Exec("INSERT INTO cms_value_reference_list_values (VALUE_ID, CONTENT_ID) VALUES (?, ?);", refListID, cid)
		if err != nil {
			return err
		}
	}

	db.contentValueAttachRefList(t, &value, depth)
	c.ContentValues = append(c.ContentValues, value)
	return nil
}

func (db *DB) valueReferenceListNew(s space.Space, ct contenttype.ContentType, c *Content, t *sql.Tx, fieldName string, IDs []string, depth int) error {
	if len(IDs) < 1 {
		return fmt.Errorf("reference list type has no values")
	}

	res, err := t.Exec("INSERT INTO cms_value_reference_list () VALUES ();")
	if err != nil {
		db.log.Println(err)
		return fmt.Errorf("failed to attach field value of content")
	}

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

	res, err = t.Exec(queryValueNew, c.ID(), ct.ID(), fieldName, refListID)
	if err != nil {
		db.log.Println(err)
		return fmt.Errorf("failed to attach field value of content")
	}

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

	var value ContentValue
	value.FieldValue = strings.Join(IDs, "-") // Match what client should send us.
	if err := t.QueryRow(queryValueGetReferenceListByID, valueID).Scan(&value.FieldID, &value.FieldType, &value.FieldName); err != nil {
		return err
	}

	for _, cid := range IDs {
		_, err := t.Exec("INSERT INTO cms_value_reference_list_values (VALUE_ID, CONTENT_ID) VALUES (?, ?);", refListID, cid)
		if err != nil {
			return err
		}
	}

	db.contentValueAttachRefList(t, &value, depth)
	c.ContentValues = append(c.ContentValues, value)
	return nil
}

func (db *DB) contentNew(space space.Space, ct contenttype.ContentType, params []ContentNewParam, depth int) (content.Content, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	res, err := t.Exec(queryContentNew, ct.ID())
	if err != nil {
		return nil, fmt.Errorf("failed to create new content attached to contenttype of '%s'", ct.Name())
	}

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

	var content Content
	if err := t.QueryRow(queryContentGetByID, contentID).Scan(&content.ContentID, &content.ContentParentTypeID); err != nil {
		return nil, fmt.Errorf("failed to find content created")
	}

	for _, item := range params {
		// Special data type. Life is hard.
		if item.Type == valuetype.ReferenceList {
			if err := db.valueReferenceListNew(space, ct, &content, t, item.Name, strings.Split(item.Value, "-"), depth); err != nil {
				return nil, err
			}
			continue
		}

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

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

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

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

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

		var value ContentValue
		if err := t.QueryRow(queryValueGetTypeByID, valueID).Scan(&value.FieldID, &value.FieldType, &value.FieldName, &value.FieldValue); err != nil {
			return nil, fmt.Errorf("failed to find value created")
		}

		if err := db.contentValueAttachRef(&value, depth); err != nil {
			return nil, err
		}

		content.ContentValues = append(content.ContentValues, value)
	}

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

	return &content, t.Commit()
}
func (db *DB) ContentNew(space space.Space, ct contenttype.ContentType, params []ContentNewParam) (content.Content, error) {
	return db.contentNew(space, ct, params, defaultDepth)
}

func (db *DB) ContentUpdate(space space.Space, ct contenttype.ContentType, content content.Content, newParams []ContentNewParam, updateParams []ContentUpdateParam) (content.Content, error) {
	depth := defaultDepth

	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	// TODO: Do we have to do this w/ types? Can you not find a better way?
	// I'm beginning to think we're over using interfaces and it's hurting.
	c, ok := content.(*Content)
	if !ok {
		return nil, fmt.Errorf("failed to type cast value type before attempting to update content")
	}

	for _, item := range updateParams {
		// Special data type. Life is hard.
		if item.Type == valuetype.ReferenceList {

			if err := db.valueReferenceListUpdate(space, ct, c, t, item.ID, strings.Split(item.Value, "-"), depth); err != nil {
				return nil, err
			}
			continue
		}

		_, _, queryValueUpdate, err := db.valueQuerySetByType(item.Type)
		if err != nil {
			return nil, err
		}

		if _, err := t.Exec(queryValueUpdate, item.Value, item.ID); err != nil {
			db.log.Println(err)
			return nil, fmt.Errorf("failed to create update content value '%s'", item.Value)
		}
	}

	for _, item := range newParams {
		// Special data type. Life is hard.
		if item.Type == valuetype.ReferenceList {
			if err := db.valueReferenceListNew(space, ct, c, t, item.Name, strings.Split(item.Value, "-"), depth); err != nil {
				return nil, err
			}
			continue
		}

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

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

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

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

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

		var value ContentValue
		if err := t.QueryRow(queryValueGetTypeByID, valueID).Scan(&value.FieldID, &value.FieldType, &value.FieldName, &value.FieldValue); err != nil {
			return nil, fmt.Errorf("failed to find value created")
		}

		if err := db.contentValueAttachRef(&value, depth); err != nil {
			return nil, err
		}

		c.ContentValues = append(c.ContentValues, value)
	}

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

	return db.ContentGet(space, ct, content.ID())
}

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

	defer t.Rollback()

	for _, q := range queryContentDelete {
		_, err := t.Exec(q, content.ID())
		if err != nil {
			return err
		}
	}

	if err := t.Commit(); err != nil {
		db.log.Println("failed to delete content", err)
	}

	return nil
}

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

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

		rows, err := db.Query(queryValueListByContent, content.ContentID, content.ContentID, content.ContentID, content.ContentID, content.ContentID)
		if err != nil {
			return nil, err
		}
		defer rows.Close()

		for rows.Next() {
			var value ContentValue
			if err := rows.Scan(&value.FieldID, &value.FieldType, &value.FieldName, &value.FieldValue); err != nil {
				return nil, err
			}
			// TODO: Should we really fetch reference type values in lists? Probably a
			// horrible idea.
			content.ContentValues = append(content.ContentValues, value)
		}

		ret = append(ret, &content)
	}

	return ret, nil
}

func (db *DB) ContentSearch(space space.Space, ct contenttype.ContentType, name, query string, page int) ([]content.Content, error) {
	s := fmt.Sprintf("%%%s%%", query)

	var ret []content.Content
	rows, err := db.Query(queryContentListByNameAndContentType, ct.ID(), name, s, s, perPage, perPage*page)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		var contentID string
		if err := rows.Scan(&contentID); err != nil {
			return nil, err
		}

		c, err := db.ContentGet(space, ct, contentID)
		if err != nil {
			return nil, err
		}

		ret = append(ret, c)
	}

	return ret, nil
}

func (db *DB) contentGet(space space.Space, ct contenttype.ContentType, contentID string, depth int) (content.Content, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	var content Content
	if err := t.QueryRow(queryContentGetByID, contentID).Scan(&content.ContentID, &content.ContentParentTypeID); err != nil {
		return nil, fmt.Errorf("failed to find content")
	}

	// TODO: For some reason t.Query(...) is causing errors here.
	// See: https://github.com/go-sql-driver/mysql/issues/314
	rows, err := db.Query(queryValueListByContent, content.ID(), content.ID(), content.ID(), content.ID(), content.ID())
	if err != nil {
		return nil, fmt.Errorf("failed to find value(s)")
	}
	defer rows.Close()

	for rows.Next() {
		var value ContentValue
		if err := rows.Scan(&value.FieldID, &value.FieldType, &value.FieldName, &value.FieldValue); err != nil {
			return nil, fmt.Errorf("failed to scan values(s)")
		}

		if err := db.contentValueAttachRef(&value, depth); err != nil {
			return nil, err
		}

		if err := db.contentValueAttachRefList(t, &value, depth); err != nil {
			return nil, err
		}

		content.ContentValues = append(content.ContentValues, value)
	}

	return &content, t.Commit()
}

func (db *DB) ContentGet(space space.Space, ct contenttype.ContentType, contentID string) (content.Content, error) {
	if space == nil {
		return nil, fmt.Errorf("must provide parent space")
	}
	if ct == nil {
		return nil, fmt.Errorf("must provide parent contenttype")
	}

	return db.contentGet(space, ct, contentID, defaultDepth)
}

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

	case valuetype.Reference:
		return queryValueNewReference, queryValueGetReferenceByID, queryValueUpdateReference, nil

	}

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

func (db *DB) contentValueAttachRef(c *ContentValue, depth int) error {
	depth--
	if c.Type() != valuetype.Reference || depth < 1 {
		return nil
	}

	ref, err := db.contentGet(nil, nil, c.Value(), depth)
	if err != nil {
		return err
	}

	c.FieldReference = ref
	return nil
}

func (db *DB) contentValueAttachRefList(t *sql.Tx, c *ContentValue, depth int) error {
	depth--
	if c.Type() != valuetype.ReferenceList || depth < 1 {
		return nil
	}

	rows, err := t.Query(queryValueGetReferenceListValuesByID, c.ID())
	if err != nil {
		return err
	}
	defer rows.Close()

	var ids []string
	for rows.Next() {
		var value ContentValue
		if err := rows.Scan(&value.FieldID, &value.FieldType, &value.FieldName, &value.FieldValue); err != nil {
			return err
		}

		ref, err := db.contentGet(nil, nil, value.FieldValue, depth)
		if err != nil {
			return err
		}

		c.FieldReferenceList = append(c.FieldReferenceList, ref)
		ids = append(ids, ref.ID())
	}

	c.FieldValue = strings.Join(ids, "-") // Match what client sends us.
	return nil
}

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

func (c *Content) Type() string {
	return c.ContentParentTypeID
}

func (c *Content) Values() []value.Value {
	var ret []value.Value
	for _, item := range c.ContentValues {
		ret = append(ret, &ContentValue{
			item.FieldID,
			item.FieldType,
			item.FieldName,
			item.FieldValue,
			item.FieldReference,
			item.FieldReferenceList,
		})
	}
	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 *ContentValue) ID() string {
	return c.FieldID
}

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

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

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

func (c *ContentValue) RefName() string {
	return c.FieldReference.MustValueByName("name").Value()
}

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

func (c *ContentValue) RefListNames() string {
	var names []string
	for _, item := range c.FieldReferenceList {
		names = append(names, item.MustValueByName("name").Value())
	}
	return strings.Join(names, ", ")
}

func (c *ContentValue) RefListIDs() []string {
	var ids []string
	for _, item := range c.FieldReferenceList {
		ids = append(ids, item.ID())
	}
	return ids
}

func (c *ContentValue) MarshalJSON() (ret []byte, err error) {
	var v contentValueJSON

	v.FieldID = c.FieldID
	v.FieldType = c.FieldType
	v.FieldName = c.FieldName
	v.FieldValue = c.FieldValue

	if c.FieldReference != nil {
		var ok bool
		v.FieldReference, ok = c.FieldReference.(*Content)
		if !ok {
			return ret, fmt.Errorf("corrupted reference value")
		}
	}

	if len(c.FieldReferenceList) > 0 {
		for _, prev := range c.FieldReferenceList {
			next, ok := prev.(*Content)
			if !ok {
				return ret, fmt.Errorf("corrupted reference list value")
			}
			v.FieldReferenceList = append(v.FieldReferenceList, next)
		}
	}

	return json.Marshal(v)
}

func (c *ContentValue) UnmarshalJSON(b []byte) error {
	var v contentValueJSON

	if err := json.Unmarshal(b, &v); err != nil {
		return err
	}

	c.FieldID = v.FieldID
	c.FieldType = v.FieldType
	c.FieldName = v.FieldName
	c.FieldValue = v.FieldValue
	c.FieldReference = v.FieldReference
	for _, item := range v.FieldReferenceList {
		c.FieldReferenceList = append(c.FieldReferenceList, item)
	}

	return nil
}