~evanj/cms

ref: 27de4d9c907e2258a828fbfcda8f22b910df0f63 cms/internal/s/db/contenttype.go -rw-r--r-- 8.4 KiB
27de4d9cEvan M Jones Feat(spaces): Added the ability to copy an entire space. 1 year, 3 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
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 = ?;`
	queryFindContentTypeByNameAndSpace = `SELECT ID, NAME FROM cms_contenttype WHERE NAME LIKE ? AND SPACE_ID = ? LIMIT ? OFFSET ?;`
	queryFindContentTypesBySpace       = `SELECT ID, NAME FROM cms_contenttype WHERE SPACE_ID = ? LIMIT ? OFFSET ?;`
	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(space space.Space, page int) ([]contenttype.ContentType, error) {
	var ret []contenttype.ContentType
	rows, err := db.Query(queryFindContentTypesBySpace, space.ID(), perPage, perPage*page)
	if err != nil {
		db.log.Println(err)
		return ret, err
	}

	for rows.Next() {
		var ct ContentType
		if err := rows.Scan(&ct.ContentTypeID, &ct.ContentTypeName); err != nil {
			return nil, err
		}
		ret = append(ret, &ct)
	}

	return ret, nil
}

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, page int) ([]contenttype.ContentType, error) {
	var ret []contenttype.ContentType
	rows, err := db.Query(queryFindContentTypeByNameAndSpace, fmt.Sprintf("%%%s%%", query), space.ID(), perPage, perPage*page)
	if err != nil {
		db.log.Println(err)
		return ret, err
	}

	for rows.Next() {
		var ct ContentType
		if err := rows.Scan(&ct.ContentTypeID, &ct.ContentTypeName); err != nil {
			return nil, err
		}
		ret = append(ret, &ct)
	}

	return ret, 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) 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
	space space.Space
	page  int
}

func (db *DB) ContentTypeIter(space space.Space) *contentTypeIter {
	return &contentTypeIter{db, space, 0}
}

func (iter *contentTypeIter) Next() (ret []contenttype.ContentType, hasMore bool, err error) {
	ret, err = iter.db.ContentTypesPerSpace(iter.space, iter.page)
	if err != nil {
		return
	}

	hasMore = len(ret) > 0
	iter.page++

	return
}