~evanj/cms

ref: 27de4d9c907e2258a828fbfcda8f22b910df0f63 cms/internal/s/db/space.go -rw-r--r-- 6.2 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
package db

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

	"git.sr.ht/~evanj/cms/internal/m/space"
	"git.sr.ht/~evanj/cms/internal/m/user"
)

type Space struct {
	SpaceID   string
	SpaceName string
	SpaceDesc string
}

var (
	queryCreateNewSpace       = `INSERT INTO cms_space (NAME, DESCRIPTION) VALUES (?, ?);`
	queryDeleteSpace          = `DELETE FROM cms_space WHERE ID = ?;`
	queryFindSpaceByID        = `SELECT ID, NAME, DESCRIPTION FROM cms_space WHERE ID = ?;`
	queryDeleteSpaceByID      = `DELETE FROM cms_space WHERE ID = ?;`
	queryCreateNewUserToSpace = `INSERT INTO cms_user_to_space (USER_ID, SPACE_ID) VALUES (?, ?);`
	queryFindUserToSpace      = `SELECT SPACE_ID FROM cms_user_to_space WHERE USER_ID = ? AND SPACE_ID = ?;`
	queryFindSpacesByUser     = `SELECT DISTINCT cms_space.ID, NAME, DESCRIPTION FROM cms_space JOIN cms_user_to_space ON cms_space.ID = cms_user_to_space.SPACE_ID WHERE USER_ID = ? LIMIT ? OFFSET ?;`

	copyUsersQuery = `
		INSERT INTO cms_user_to_space (USER_ID, SPACE_ID)
		SELECT USER_ID, ?
		FROM cms_user_to_space
		WHERE SPACE_ID=?
	`

	copyHooksQuery = `
		INSERT INTO cms_hooks (URL, SPACE_ID)
		SELECT URL, ?
		FROM cms_hooks 
		WHERE SPACE_ID=?
	`

	copyContentTypeQuery = `
		INSERT INTO cms_contenttype (NAME, SPACE_ID)
		SELECT NAME, ?
		FROM cms_contenttype 
		WHERE ID=?
	`

	copyValueTypeQuery = `
		INSERT INTO cms_contenttype_to_valuetype (NAME, CONTENTTYPE_ID, VALUETYPE_ID)
		SELECT NAME, ?, VALUETYPE_ID
		FROM cms_contenttype_to_valuetype 
		WHERE CONTENTTYPE_ID=?
	`
)

func (db *DB) spaceNew(t *sql.Tx, user user.User, name, desc string) (space.Space, error) {
	res, err := t.Exec(queryCreateNewSpace, name, desc)
	if err != nil {
		return nil, fmt.Errorf("space '%s' already exists", name)
	}

	id, err := res.LastInsertId()
	if err != nil {
		return nil, fmt.Errorf("failed to create space")
	}

	var space Space
	if err := t.QueryRow(queryFindSpaceByID, id).Scan(&space.SpaceID, &space.SpaceName, &space.SpaceDesc); err != nil {
		return nil, fmt.Errorf("failed to find space created")
	}

	if _, err := t.Exec(queryCreateNewUserToSpace, user.ID(), space.ID()); err != nil {
		return nil, fmt.Errorf("failed to attach space to user")
	}

	return &space, nil
}

func (db *DB) SpaceNew(user user.User, name, desc string) (space.Space, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	space, err := db.spaceNew(t, user, name, desc)
	if err != nil {
		return nil, err
	}

	return space, t.Commit()
}

func (db *DB) SpaceCopy(user user.User, prevS space.Space, name, desc string) (space.Space, error) {
	// TODO: NOTE: Normal transactions don't work for us, they are too nested.
	// Figure out a workaround for this.
	// t, err := db.Begin()
	// if err != nil {
	// 	return nil, err
	// }
	// defer t.Rollback()
	t := db

	res, err := t.Exec(queryCreateNewSpace, name, desc)
	if err != nil {
		return nil, err
	}

	nextID, err := res.LastInsertId()
	if err != nil {
		return nil, err
	}

	// Copy all users.
	if _, err := t.Exec(copyUsersQuery, nextID, prevS.ID()); err != nil {
		return nil, err
	}

	// Copy all webhooks.
	if _, err := t.Exec(copyHooksQuery, nextID, prevS.ID()); err != nil {
		return nil, err
	}

	next, err := db.SpaceGet(user, strconv.FormatInt(nextID, 10))
	if err != nil {
		return nil, err
	}

	// Copy all content types and their value types.
	// Copy all contents and their values.
	iter := db.ContentTypeIter(prevS)
	for {
		types, hasMore, err := iter.Next()
		if err != nil {
			return nil, err
		}

		if !hasMore {
			break
		}

		for _, prevCT := range types {
			// Copy content type.
			res, err := t.Exec(copyContentTypeQuery, nextID, prevCT.ID())
			if err != nil {
				return nil, err
			}

			ctID, err := res.LastInsertId()
			if err != nil {
				return nil, err
			}

			// Copy value type.
			if _, err := t.Exec(copyValueTypeQuery, ctID, prevCT.ID()); err != nil {
				return nil, err
			}

			ct, err := db.ContentTypeGet(next, strconv.FormatInt(ctID, 10))
			if err != nil {
				return nil, err
			}

			// Copy all contents and their values.
			iter := db.ContentIter(prevS, prevCT, "name") // TODO: What is this sort type for?
			for {
				contents, hasMore, err := iter.Next()
				if err != nil {
					return nil, err
				}

				if !hasMore {
					break
				}

				for _, prevC := range contents {
					params := make([]ContentNewParam, len(prevC.Values()))
					for i, prevV := range prevC.Values() {
						params[i] = ContentNewParam{prevV.Type(), prevV.Name(), prevV.Value()}
					}

					if _, err := db.ContentNew(next, ct, params); err != nil {
						return nil, err
					}
				} // Contents
			} // ContentsIter
		} // ContentTypes
	} // ContentTypesIter

	// return next, t.Commit()
	return next, nil
}

func (db *DB) spaceGet(t *sql.Tx, user user.User, spaceID string) (space.Space, error) {
	var id string

	if err := t.QueryRow(queryFindUserToSpace, user.ID(), spaceID).Scan(&id); err != nil {
		return nil, fmt.Errorf("failed to find space for user")
	}

	var space Space
	err := t.QueryRow(queryFindSpaceByID, id).Scan(&space.SpaceID, &space.SpaceName, &space.SpaceDesc)
	if err != nil {
		return nil, fmt.Errorf("failed to find space")
	}

	return &space, nil
}

func (db *DB) SpaceGet(user user.User, spaceID string) (space.Space, error) {
	t, err := db.Begin()
	if err != nil {
		return nil, err
	}
	defer t.Rollback()

	space, err := db.spaceGet(t, user, spaceID)
	if err != nil {
		return nil, err
	}

	return space, t.Commit()
}

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

	if _, err := t.Exec(queryDeleteSpace, space.ID()); err != nil {
		return err
	}

	return t.Commit()
}

func (db *DB) SpacesPerUser(user user.User, page int) ([]space.Space, error) {
	var ret []space.Space
	rows, err := db.Query(queryFindSpacesByUser, user.ID(), perPage, perPage*page)
	if err != nil {
		db.log.Println(err)
		return ret, err
	}

	for rows.Next() {
		var space Space
		if err := rows.Scan(&space.SpaceID, &space.SpaceName, &space.SpaceDesc); err != nil {
			return nil, err
		}
		ret = append(ret, &space)
	}

	return ret, nil
}

func (s *Space) ID() string {
	return s.SpaceID
}

func (s *Space) Name() string {
	return s.SpaceName
}

func (s *Space) Desc() string {
	return s.SpaceDesc
}