33use std:: marker:: PhantomData ;
44
55use derive_more:: with_trait:: Debug ;
6- use sea_query:: { ExprTrait , IntoColumnRef } ;
6+ use sea_query:: { ExprTrait , IntoColumnRef , Order } ;
77
88use crate :: db;
99use crate :: db:: {
@@ -33,6 +33,7 @@ use crate::db::{
3333pub struct Query < T > {
3434 filter : Option < Expr > ,
3535 limit : Option < u64 > ,
36+ order_by : Option < ( String , Order ) > ,
3637 offset : Option < u64 > ,
3738 phantom_data : PhantomData < fn ( ) -> T > ,
3839}
@@ -55,6 +56,7 @@ impl<T> Clone for Query<T> {
5556 Self {
5657 filter : self . filter . clone ( ) ,
5758 limit : self . limit ,
59+ order_by : self . order_by . clone ( ) ,
5860 offset : self . offset ,
5961 phantom_data : PhantomData ,
6062 }
@@ -98,6 +100,7 @@ impl<T: Model> Query<T> {
98100 Self {
99101 filter : None ,
100102 limit : None ,
103+ order_by : None ,
101104 offset : None ,
102105 phantom_data : PhantomData ,
103106 }
@@ -149,6 +152,28 @@ impl<T: Model> Query<T> {
149152 self
150153 }
151154
155+ /// Set an order for records from the query.
156+ ///
157+ /// # Example
158+ ///
159+ /// ```
160+ /// use cot::db::model;
161+ /// use cot::db::query::{Expr, Query};
162+ ///
163+ /// #[model]
164+ /// struct User {
165+ /// #[model(primary_key)]
166+ /// id: i32,
167+ /// age: i32,
168+ /// }
169+ ///
170+ /// let query = Query::<User>::new().order_by("age", Order::Asc); // or Order::Desc
171+ /// ```
172+ pub fn order_by ( & mut self , order_by : ( String , Order ) ) -> & mut Self {
173+ self . order_by = Some ( self . order_by ) ;
174+ self
175+ }
176+
152177 /// Set the offset for the query.
153178 ///
154179 /// # Example
@@ -244,6 +269,12 @@ impl<T: Model> Query<T> {
244269 }
245270 }
246271
272+ pub ( super ) fn add_order_by_to_statement ( & self , statement : & mut sea_query:: SelectStatement ) {
273+ if let Some ( order_by) = self . order_by {
274+ statement. order_by ( order_by. 0 , order_by. 1 ) ;
275+ }
276+ }
277+
247278 pub ( super ) fn add_offset_to_statement ( & self , statement : & mut sea_query:: SelectStatement ) {
248279 if let Some ( offset) = self . offset {
249280 statement. offset ( offset) ;
0 commit comments