Skip to content

Commit 8eb7d7c

Browse files
authored
Improve butane_core docstrings (#401)
1 parent aabd026 commit 8eb7d7c

File tree

25 files changed

+268
-214
lines changed

25 files changed

+268
-214
lines changed

butane_core/src/autopk.rs

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,10 @@ use serde::{Deserialize, Serialize};
77

88
use super::{FieldType, FromSql, PrimaryKeyType, Result, SqlType, SqlVal, SqlValRef, ToSql};
99

10-
/// Wrapper around a [PrimaryKeyType] to indicate the the primary key
11-
/// will be initialized automatically when the object is created in
12-
/// the database.
10+
/// Used to implement a primary key that is automatically populated by the backend.
11+
///
12+
/// Wrapper around a [`PrimaryKeyType`] to indicate the primary key will be initialized automatically.
13+
///
1314
/// Dereferences to an `Option<T>`.
1415
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
1516
pub struct AutoPk<T: PrimaryKeyType> {
@@ -25,8 +26,9 @@ impl<T: PrimaryKeyType> AutoPk<T> {
2526
Self::default()
2627
}
2728

28-
/// Create an initialized primary key value for a previously saved
29-
/// object. You do not usually need to call this directly (it will
29+
/// Create an initialized primary key value for a previously saved object.
30+
///
31+
/// You do not usually need to call this directly (it will
3032
/// happen implicitly when you load from the database).
3133
fn with_value(val: T) -> Self {
3234
AutoPk { inner: Some(val) }
@@ -53,10 +55,11 @@ impl<T: PrimaryKeyType> FromSql for AutoPk<T> {
5355
Ok(AutoPk::with_value(T::from_sql_ref(val)?))
5456
}
5557

56-
/// Used to convert a SqlVal into another type. The default
57-
/// implementation calls `Self::from_sql_ref(val.as_ref())`, which
58-
/// may be inefficient. This method is chiefly used only for
59-
/// primary keys: a more efficient implementation is unlikely to
58+
/// Used to convert a `SqlVal` into another type.
59+
///
60+
/// The default implementation calls `Self::from_sql_ref(val.as_ref())`, which
61+
/// may be inefficient. This method is chiefly used only
62+
/// for primary keys: a more efficient implementation is unlikely to
6063
/// provide benefits for types not used as primary keys.
6164
fn from_sql(val: SqlVal) -> Result<Self>
6265
where

butane_core/src/codegen/dbobj.rs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,13 @@ use super::{
1111
use crate::migrations::adb::{DeferredSqlType, TypeIdentifier, MANY_SUFFIX};
1212
use crate::SqlType;
1313

14-
/// Configuration that can be specified with attributes to override default behavior
14+
/// Configuration that can be specified with attributes to override default behavior.
1515
#[derive(Clone, Debug, Default)]
1616
pub struct Config {
1717
pub table_name: Option<String>,
1818
}
1919

20-
/// Code generation to implement the DataObject trait for a model
20+
/// Code generation to implement the [`DataObject`] trait for a model.
2121
pub fn impl_dbobject(ast_struct: &ItemStruct, config: &Config) -> TokenStream2 {
2222
let tyname = &ast_struct.ident;
2323
let tablelit = make_tablelit(config, tyname);
@@ -157,7 +157,7 @@ pub fn impl_dbobject(ast_struct: &ItemStruct, config: &Config) -> TokenStream2 {
157157
)
158158
}
159159

160-
/// Code generation to implement the DataResult trait for a model
160+
/// Code generation to implement the DataResult trait for a model.
161161
pub fn impl_dataresult(ast_struct: &ItemStruct, dbo: &Ident, config: &Config) -> TokenStream2 {
162162
let tyname = &ast_struct.ident;
163163
let numdbfields = fields(ast_struct).filter(|f| is_row_field(f)).count();
@@ -413,8 +413,9 @@ fn verify_fields(ast_struct: &ItemStruct) -> Option<TokenStream2> {
413413
None
414414
}
415415

416-
/// Builds code for pushing SqlVals for each column satisfying predicate into a vec called `values`
417-
/// that excludes any auto values.
416+
/// Build code to push [`SqlVal`]s for each column satisfying `predicate` into a `Vec` called `values`.
417+
///
418+
/// It excludes any auto values.
418419
fn push_values<P>(ast_struct: &ItemStruct, mut predicate: P) -> Vec<TokenStream2>
419420
where
420421
P: FnMut(&Field) -> bool,

butane_core/src/codegen/mod.rs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,7 @@ where
240240
}
241241
}
242242

243-
/// Create a [`struct@LitStr`] (UTF-8 string literal) from an [Ident].
243+
/// Create a [`struct@LitStr`] (UTF-8 string literal) from an [`Ident`].
244244
pub fn make_ident_literal_str(ident: &Ident) -> LitStr {
245245
let as_str = ident.strip_raw().to_string();
246246
make_lit(&as_str)
@@ -374,13 +374,13 @@ fn is_option(field: &Field) -> bool {
374374
get_type_argument(&field.ty, "Option").is_some()
375375
}
376376

377-
/// Check for special fields which won't correspond to rows and don't
378-
/// implement FieldType
377+
/// Check for special fields which won't correspond to rows and don't implement [`FieldType`].
379378
fn is_row_field(f: &Field) -> bool {
380379
!is_many_to_many(f)
381380
}
382381

383-
/// Gets the type argument of a type.
382+
/// Get the type argument of a type.
383+
///
384384
/// E.g. for `Foo<T>`, returns `T`.
385385
fn get_type_argument<'a>(ty: &'a syn::Type, tyname: &'static str) -> Option<&'a syn::Path> {
386386
let path = match ty {
@@ -390,7 +390,8 @@ fn get_type_argument<'a>(ty: &'a syn::Type, tyname: &'static str) -> Option<&'a
390390
get_path_argument(path, tyname)
391391
}
392392

393-
/// Gets the type argument of a path.
393+
/// Get the type argument of a path.
394+
///
394395
/// E.g. for `Foo<T>``, returns `T`.
395396
fn get_path_argument<'a>(path: &'a syn::Path, tyname: &str) -> Option<&'a syn::Path> {
396397
if let Some(resolved) = PATH_RESOLVER.resolve(path) {
@@ -430,9 +431,9 @@ fn get_foreign_sql_type(path: &syn::Path, tyname: &str) -> Option<DeferredSqlTyp
430431
})
431432
}
432433

433-
/// Determine whether a type refers to a data type that is supported directly by butane,
434-
/// or is a custom defined struct.
435-
/// It looks inside an [Option] or [crate::fkey::ForeignKey] to determine the inner type.
434+
/// Determine whether a type refers to a data type that is supported directly by butane, or is a custom defined struct.
435+
///
436+
/// It looks inside an `Option` or [`ForeignKey`](crate::fkey::ForeignKey) to determine the inner type.
436437
pub fn get_deferred_sql_type(path: &syn::Path) -> DeferredSqlType {
437438
get_primitive_sql_type(path)
438439
.or_else(|| get_option_sql_type(path))

butane_core/src/custom.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,14 @@ use serde::{Deserialize, Serialize};
1414
#[cfg(feature = "pg")]
1515
use tokio_postgres as postgres;
1616

17-
/// For use with [SqlType::Custom](crate::SqlType)
17+
/// For use with [`SqlType::Custom`](crate::SqlType).
1818
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
1919
pub enum SqlTypeCustom {
2020
#[cfg(feature = "pg")]
2121
Pg(#[serde(with = "pgtypeser")] tokio_postgres::types::Type),
2222
}
2323

24-
/// For use with [SqlVal::Custom](crate::SqlVal)
24+
/// For use with [`SqlVal::Custom`](crate::SqlVal).
2525
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
2626
pub enum SqlValCustom {
2727
#[cfg(feature = "pg")]
@@ -89,7 +89,7 @@ impl postgres::types::ToSql for SqlValCustom {
8989
postgres::types::to_sql_checked!();
9090
}
9191

92-
/// For use with [SqlValRef::Custom](crate::SqlValRef)
92+
/// For use with [`SqlValRef::Custom`](crate::SqlValRef).
9393
#[derive(Clone, Debug)]
9494
pub enum SqlValRefCustom<'a> {
9595
/// Used with Postgres, but suitable only for input (e.g. input to

butane_core/src/db/adapter.rs

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,10 @@ impl AsyncAdapterEnv {
4242
}
4343
}
4444

45-
/// Invokes a blocking function `func` as if it were async. This
46-
/// is implemented by running it on the special thread created when the `AsyncAdapterEnv` was created.
45+
/// Invokes a blocking function `func` as if it were async.
46+
///
47+
/// This is implemented by running it on the special thread created
48+
/// when the `AsyncAdapterEnv` was created.
4749
async fn invoke<'c, 's, 'result, F, T, U>(
4850
&'s self,
4951
context: &SyncSendPtrMut<T>,
@@ -153,8 +155,9 @@ impl Drop for AsyncAdapterEnv {
153155
}
154156
}
155157

156-
/// Wrapper around a raw pointer that we assert is [Send]. Needless to
157-
/// say, this requires care. See comments on `AsyncAdapterEnv::invoke`
158+
/// Wrapper around a raw pointer that we assert is [`Send`].
159+
///
160+
/// Needless to say, this requires care. See comments on [`AsyncAdapterEnv::invoke`]
158161
/// for why we believe this to be sound.
159162
struct SendPtr<T: ?Sized> {
160163
inner: *const T,
@@ -166,7 +169,7 @@ impl<T: ?Sized> SendPtr<T> {
166169
}
167170
unsafe impl<T: ?Sized> Send for SendPtr<T> {}
168171

169-
/// Like [SendPtrMut] but we also assert that it is [Sync]
172+
/// Like [`SendPtrMut`] but we also assert that it is [`Sync`].
170173
struct SyncSendPtrMut<T: ?Sized> {
171174
inner: *mut T,
172175
}
@@ -205,7 +208,7 @@ pub(super) struct AsyncAdapter<T: ?Sized> {
205208
}
206209

207210
impl<T: ?Sized> AsyncAdapter<T> {
208-
/// Create a new AsyncAdapter with the given context and using the same `env` as self. Not a public method.
211+
/// Create an `AsyncAdapter` with the given context, using the same `env` as self.
209212
fn create_with_same_env<U: ?Sized>(&self, context_ptr: SyncSendPtrMut<U>) -> AsyncAdapter<U> {
210213
AsyncAdapter {
211214
env: self.env.clone(),
@@ -248,7 +251,7 @@ impl<T: ?Sized> AsyncAdapter<T> {
248251
}
249252

250253
impl<T> AsyncAdapter<T> {
251-
/// Create a new async adapter using `create_context` to create an instance of the inner type `T`.
254+
/// Create an async adapter using `create_context` to create an instance of the inner type `T`.
252255
pub(super) fn new<F>(create_context: F) -> Result<Self>
253256
where
254257
Self: Sized,
@@ -389,8 +392,9 @@ where
389392
ok_or_panic_with_adapter_error(self.invoke_blocking(|conn| Ok(conn.backend_name())))
390393
}
391394

392-
/// Tests if the connection has been closed. Backends which do not
393-
/// support this check should return false.
395+
/// Tests if the connection has been closed.
396+
///
397+
/// Backends which do not support this check should return `false`.
394398
fn is_closed(&self) -> bool {
395399
ok_or_panic_with_adapter_error(self.invoke_blocking(|conn| Ok(conn.is_closed())))
396400
}
@@ -442,8 +446,9 @@ where
442446
}
443447
}
444448

445-
/// Create an async connection using the synchronous `connect` method of `backend`. Use this when authoring
446-
/// a backend which doesn't natively support async.
449+
/// Create an async connection via the synchronous `connect` method of `backend`.
450+
///
451+
/// Use this when authoring a backend which doesn't natively support async.
447452
pub async fn connect_async_via_sync<B>(backend: &B, conn_str: &str) -> Result<ConnectionAsync>
448453
where
449454
B: Backend + Clone + 'static,

butane_core/src/db/connmethods.rs

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,11 @@ use async_trait::async_trait;
88
use crate::query::{BoolExpr, Expr, Order};
99
use crate::{Result, SqlType, SqlVal, SqlValRef};
1010

11-
/// Methods available on a database connection. Most users do not need
12-
/// to call these methods directly and will instead use methods on
13-
/// [DataObject][crate::DataObject] or the `query!` macro. This trait is
14-
/// implemented by both database connections and transactions.
11+
/// Methods available on a database connection.
12+
///
13+
/// Most users do not need to call these methods directly and will instead
14+
/// use methods on [`DataObject`][`crate::DataObject`] or the `query!` macro.
15+
/// This trait is implemented by both database connections and transactions.
1516
#[maybe_async_cfg::maybe(
1617
sync(keep_self),
1718
async(feature = "async", self = "ConnectionMethodsAsync"),
@@ -69,8 +70,9 @@ pub trait ConnectionMethods: super::internal::AsyncRequiresSync {
6970
async fn has_table(&self, table: &str) -> Result<bool>;
7071
}
7172

72-
/// Represents a database column. Most users do not need to use this
73-
/// directly.
73+
/// Represents a database column.
74+
///
75+
/// Most users do not need to use this directly.
7476
#[derive(Clone, Debug)]
7577
pub struct Column {
7678
name: &'static str,
@@ -88,8 +90,9 @@ impl Column {
8890
}
8991
}
9092

91-
/// Backend-specific row abstraction. Only implementors of new
92-
/// backends need use this trait directly.
93+
/// Backend-specific row abstraction.
94+
///
95+
/// Only implementors of new backends need use this trait directly.
9396
pub trait BackendRow {
9497
fn get(&self, idx: usize, ty: SqlType) -> Result<SqlValRef<'_>>;
9598
fn len(&self) -> usize;
@@ -99,9 +102,10 @@ pub trait BackendRow {
99102
}
100103
}
101104

102-
/// Abstraction of rows returned from a query. Most users do not need
103-
/// to deal with this directly and should use the `query!` macro or
104-
/// [Query](crate::query::Query) type.
105+
/// Abstraction of rows returned from a query.
106+
///
107+
/// Most users do not need to deal with this directly and should use
108+
/// the `query!` macro or [`Query`](crate::query::Query) type.
105109
pub trait BackendRows {
106110
// Advance to the next item and get it
107111
fn next<'a>(&'a mut self) -> Result<Option<&'a (dyn BackendRow + 'a)>>;

butane_core/src/db/dummy.rs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,9 @@ use crate::{Error, Result, SqlVal, SqlValRef};
1212
#[derive(Clone, Debug)]
1313
struct DummyBackend {}
1414

15-
/// Provides a backend implementation which fails all operations with [Error::PoisonedConnection].
16-
/// Exists so that it can be returned from the [BackendConnection] implementation of [DummyConnection].
15+
/// Provides a backend implementation which fails all operations with [`Error::PoisonedConnection`].
16+
///
17+
/// Exists so that it can be returned from the [`BackendConnection`] implementation of [`DummyConnection`].
1718
#[async_trait]
1819
impl Backend for DummyBackend {
1920
fn name(&self) -> &'static str {
@@ -33,10 +34,11 @@ impl Backend for DummyBackend {
3334
}
3435
}
3536

36-
/// Provides a connection implementation which fails all operations with [Error::PoisonedConnection].
37+
/// Provides a connection implementation which fails all operations with [`Error::PoisonedConnection`].
38+
///
39+
/// [`ConnectionAsync`] provides a `with_sync` method which allows running a non-async function.
40+
/// which takes synchronous [`Connection`]. This is implemented using [`std::mem::swap`] to satisfy the borrow checker.
3741
///
38-
/// [ConnectionAsync] provides a `with_sync` method which allows running a non-async function
39-
/// which takes synchronous [Connection]. This is implemented using std::mem::swap to satisfy the borrow checker.
4042
/// The original async connection is replaced with a dummy one while the sync operation is being run.
4143
#[derive(Clone, Debug)]
4244
pub(crate) struct DummyConnection {}

butane_core/src/db/helper.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,10 @@ pub fn quote_reserved_word(word: &str) -> Cow<'_, str> {
2828
}
2929
}
3030

31-
/// Writes to `w` the SQL to express the expression given in `expr`. Values contained in `expr` are rendered
32-
/// as placeholders in the SQL string and the actual values are added to `values`.
31+
/// Writes to `w` the SQL to express the expression given in `expr`.
32+
///
33+
/// Values contained in `expr` are rendered as placeholders in the SQL
34+
/// string and the actual values are added to `values`.
3335
pub fn sql_for_expr<F, P, W>(expr: Expr, f: F, values: &mut Vec<SqlVal>, pls: &mut P, w: &mut W)
3436
where
3537
F: Fn(Expr, &mut Vec<SqlVal>, &mut P, &mut W),
@@ -169,8 +171,7 @@ pub fn sql_insert_with_placeholders(
169171
}
170172
}
171173

172-
/// Writes to `w` the SQL of an UPDATE to `table` of `columns` using values in `pls`,
173-
/// for the row uniquely identified by `pkcol`.
174+
/// Write to `w` a SQL UPDATE to `table` of `columns` using values in `pls`, for the row uniquely identified by `pkcol`.
174175
pub fn sql_update_with_placeholders(
175176
table: &str,
176177
pkcol: Column,

0 commit comments

Comments
 (0)