@@ -144,6 +144,40 @@ impl Category {
144
144
Ok ( rows. iter ( ) . next ( ) . unwrap ( ) . get ( "count" ) )
145
145
}
146
146
147
+ pub fn toplevel ( conn : & GenericConnection ,
148
+ sort : & str ,
149
+ limit : i64 ,
150
+ offset : i64 ) -> CargoResult < Vec < Category > > {
151
+
152
+ let sort_sql = match sort {
153
+ "crates" => "ORDER BY crates_cnt DESC" ,
154
+ _ => "ORDER BY category ASC" ,
155
+ } ;
156
+
157
+ // Collect all the top-level categories and sum up the crates_cnt of
158
+ // the crates in all subcategories
159
+ let stmt = try!( conn. prepare ( & format ! (
160
+ "SELECT c.id, c.category, c.slug, c.description, c.created_at, \
161
+ COALESCE (( \
162
+ SELECT sum(c2.crates_cnt)::int \
163
+ FROM categories as c2 \
164
+ WHERE c2.slug = c.slug \
165
+ OR c2.slug LIKE c.slug || '::%' \
166
+ ), 0) as crates_cnt \
167
+ FROM categories as c \
168
+ WHERE c.category NOT LIKE '%::%' {} \
169
+ LIMIT $1 OFFSET $2",
170
+ sort_sql
171
+ ) ) ) ;
172
+
173
+ let categories: Vec < _ > = try!( stmt. query ( & [ & limit, & offset] ) )
174
+ . iter ( )
175
+ . map ( |row| Model :: from_row ( & row) )
176
+ . collect ( ) ;
177
+
178
+ Ok ( categories)
179
+ }
180
+
147
181
pub fn subcategories ( & self , conn : & GenericConnection )
148
182
-> CargoResult < Vec < Category > > {
149
183
let stmt = try!( conn. prepare ( "\
@@ -183,34 +217,9 @@ pub fn index(req: &mut Request) -> CargoResult<Response> {
183
217
let ( offset, limit) = try!( req. pagination ( 10 , 100 ) ) ;
184
218
let query = req. query ( ) ;
185
219
let sort = query. get ( "sort" ) . map_or ( "alpha" , String :: as_str) ;
186
- let sort_sql = match sort {
187
- "crates" => "ORDER BY crates_cnt DESC" ,
188
- _ => "ORDER BY category ASC" ,
189
- } ;
190
220
191
- // Collect all the top-level categories and sum up the crates_cnt of
192
- // the crates in all subcategories
193
- let stmt = try!( conn. prepare ( & format ! (
194
- "SELECT c.id, c.category, c.slug, c.description, c.created_at, \
195
- COALESCE (( \
196
- SELECT sum(c2.crates_cnt)::int \
197
- FROM categories as c2 \
198
- WHERE c2.slug = c.slug \
199
- OR c2.slug LIKE c.slug || '::%' \
200
- ), 0) as crates_cnt \
201
- FROM categories as c \
202
- WHERE c.category NOT LIKE '%::%' {} \
203
- LIMIT $1 OFFSET $2",
204
- sort_sql
205
- ) ) ) ;
206
-
207
- let categories: Vec < _ > = try!( stmt. query ( & [ & limit, & offset] ) )
208
- . iter ( )
209
- . map ( |row| {
210
- let category: Category = Model :: from_row ( & row) ;
211
- category. encodable ( )
212
- } )
213
- . collect ( ) ;
221
+ let categories = try!( Category :: toplevel ( conn, sort, limit, offset) ) ;
222
+ let categories = categories. into_iter ( ) . map ( Category :: encodable) . collect ( ) ;
214
223
215
224
// Query for the total count of categories
216
225
let total = try!( Category :: count_toplevel ( conn) ) ;
0 commit comments