Fetch records
Retrieve by primary key
Retrieving a record by primary key method accepts an integer and returns a single row corresponding to where the value of the id
column equals to the integer:
Searching records
Rwf supports searching records by any column in its respective table. For example, the User
model has three columns, all of which are searchable:
ID | Value |
---|---|
$1 |
'admin@example.com' |
$2 |
'2024-10-16T11:27:56-07:00' |
Rwf supports multiple comparison operations for most data types:
Method | Operator | Example |
---|---|---|
filter |
= |
id = 5 |
not / filter_not |
!= |
email != 'user@example.com' |
filter_gt |
> |
created_at > NOW() |
filter_lt |
< |
created_at < '2024-10-16' |
filter_gte |
>= |
id >= 5 |
filter_lte |
<= |
id <= 25 |
filter |
IN |
id IN (1, 2, 3) |
not |
NOT IN |
id NOT IN (4, 5, 6) |
The filter
(and not
) methods accept lists of values (in Rust, those are called "slices") which translate to the IN
and NOT IN
filters in SQL respectively:
Search by NULL
Searching columns that have no value, i.e. the value is NULL
, is a special case and is handled by passing the Value::Null
explicitly:
Searching by the opposite, where a column is not NULL
:
Optional results
When using fetch
, if no rows exist, the ORM will return a RecordNotFound
error.
To avoid this, use fetch_optional
which will return an Option
instead:
Limiting results
Fetching many records at once can be inefficient and slow. To limit how many rows your queries return, you can add a LIMIT
clause:
Paginating results
Pagination is supported using the OFFSET
clause:
Ordering results
It's often more efficient and simpler to order rows in the database instead of in the application. Rwf supports ordering by any column
in the query, by specifying them using the order
method:
Locking rows
In busy production applications, it's common for the same row to be accessed from multiple places at the same time. If you'd like to prevent that row from being accessed while you're doing something to it, for example updating it with new values, you can use a row-level lock:
The lock on the row(s) returned by a query last only for the duration of the transaction. It's common to use that time to update multiple tables that have some kind of relationship to the row being locked. This mechanism allows to perform atomic operations (all or nothing) in a concurrent environment without data races or inconsistencies.