Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Debug trait to all data structures #55

Merged
merged 1 commit into from
Mar 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion butane_cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ fn main() {
}
}

#[derive(Serialize, Deserialize, Default)]
#[derive(Debug, Default, Deserialize, Serialize)]
struct CliState {
embedded: bool,
}
Expand Down
2 changes: 1 addition & 1 deletion butane_core/src/codegen/dbobj.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use quote::{quote, quote_spanned};
use syn::{spanned::Spanned, Field, ItemStruct};

// Configuration that can be specified with attributes to override default behavior
#[derive(Default)]
#[derive(Debug, Default)]
pub struct Config {
pub table_name: Option<String>,
}
Expand Down
1 change: 1 addition & 0 deletions butane_core/src/codegen/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,7 @@ fn sqlval_from_lit(lit: Lit) -> std::result::Result<SqlVal, CompilerErrorMsg> {
}
}

#[derive(Debug)]
struct CustomTypeInfo {
name: String,
ty: DeferredSqlType,
Expand Down
10 changes: 5 additions & 5 deletions butane_core/src/custom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ use serde::{Deserialize, Serialize};
use std::fmt;

/// For use with [SqlType::Custom](crate::SqlType)
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum SqlTypeCustom {
#[cfg(feature = "pg")]
Pg(#[serde(with = "pgtypeser")] postgres::types::Type),
}

/// For use with [SqlVal::Custom](crate::SqlVal)
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum SqlValCustom {
#[cfg(feature = "pg")]
Pg {
Expand Down Expand Up @@ -151,7 +151,7 @@ mod pgtypeser {
}

//Serializable version of postgres::types::Type
#[derive(Serialize, Deserialize, Clone)]
#[derive(Clone, Debug, Deserialize, Serialize)]
struct SerializablePgType {
name: String,
oid: u32,
Expand All @@ -174,7 +174,7 @@ mod pgtypeser {
}
}

#[derive(Serialize, Deserialize, Clone)]
#[derive(Clone, Debug, Deserialize, Serialize)]
enum SerializablePgKind {
Simple,
Enum(Vec<String>),
Expand Down Expand Up @@ -217,7 +217,7 @@ mod pgtypeser {
}
}

#[derive(Serialize, Deserialize, Clone)]
#[derive(Clone, Debug, Deserialize, Serialize)]
struct SerializablePgField {
name: String,
ty: SerializablePgType,
Expand Down
2 changes: 2 additions & 0 deletions butane_core/src/db/connmethods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ pub trait ConnectionMethods {

/// Represents a database column. Most users do not need to use this
/// directly.
#[derive(Debug)]
pub struct Column {
name: &'static str,
ty: SqlType,
Expand Down Expand Up @@ -134,6 +135,7 @@ pub trait ConnectionMethodWrapper {
fn wrapped_connection_methods(&self) -> Result<&Self::Wrapped>;
}

#[derive(Debug)]
pub(crate) struct VecRows<T> {
rows: Vec<T>,
idx: usize,
Expand Down
9 changes: 6 additions & 3 deletions butane_core/src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use crate::query::BoolExpr;
use crate::{migrations::adb, Error, Result, SqlVal, SqlValRef};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::fmt::Debug;
use std::fs;
use std::io::Write;
use std::ops::{Deref, DerefMut};
Expand All @@ -42,7 +43,7 @@ pub use connmethods::{
};

/// Database connection.
pub trait BackendConnection: ConnectionMethods + Send + 'static {
pub trait BackendConnection: ConnectionMethods + Debug + Send + 'static {
/// Begin a database transaction. The transaction object must be
/// used in place of this connection until it is committed and aborted.
fn transaction(&mut self) -> Result<Transaction>;
Expand All @@ -56,6 +57,7 @@ pub trait BackendConnection: ConnectionMethods + Send + 'static {

/// Database connection. May be a connection to any type of database
/// as it is a boxed abstraction over a specific connection.
#[derive(Debug)]
pub struct Connection {
conn: Box<dyn BackendConnection>,
}
Expand Down Expand Up @@ -88,7 +90,7 @@ connection_method_wrapper!(Connection);
/// Connection specification. Contains the name of a database backend
/// and the backend-specific connection string. See [connect][crate::db::connect]
/// to make a [Connection][crate::db::Connection] from a `ConnectionSpec`.
#[derive(Serialize, Deserialize)]
#[derive(Debug, Deserialize, Serialize)]
pub struct ConnectionSpec {
pub backend_name: String,
pub conn_str: String,
Expand Down Expand Up @@ -166,7 +168,7 @@ pub fn connect(spec: &ConnectionSpec) -> Result<Connection> {
.connect(&spec.conn_str)
}

trait BackendTransaction<'c>: ConnectionMethods {
trait BackendTransaction<'c>: ConnectionMethods + Debug {
/// Commit the transaction Unfortunately because we use this as a
/// trait object, we can't consume self. It should be understood
/// that no methods should be called after commit. This trait is
Expand All @@ -184,6 +186,7 @@ trait BackendTransaction<'c>: ConnectionMethods {
///
/// Begin a transaction using the `BackendConnection`
/// [`transaction`][crate::db::BackendConnection::transaction] method.
#[derive(Debug)]
pub struct Transaction<'c> {
trans: Box<dyn BackendTransaction<'c> + 'c>,
}
Expand Down
26 changes: 25 additions & 1 deletion butane_core/src/db/pg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use std::fmt::Write;
pub const BACKEND_NAME: &str = "pg";

/// Pg [Backend][crate::db::Backend] implementation.
#[derive(Default)]
#[derive(Debug, Default)]
pub struct PgBackend {}
impl PgBackend {
pub fn new() -> PgBackend {
Expand Down Expand Up @@ -53,11 +53,15 @@ impl Backend for PgBackend {

/// Pg database connection.
pub struct PgConnection {
#[cfg(feature = "debug")]
params: Box<str>,
conn: RefCell<postgres::Client>,
}
impl PgConnection {
fn open(params: &str) -> Result<Self> {
Ok(PgConnection {
#[cfg(feature = "debug")]
params: params.into(),
conn: RefCell::new(Self::connect(params)?),
})
}
Expand Down Expand Up @@ -95,6 +99,16 @@ impl BackendConnection for PgConnection {
self.conn.borrow().is_closed()
}
}
impl Debug for PgConnection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut d = f.debug_struct("PgConnection");
#[cfg(feature = "debug")]
d.field("params", &self.params);
// postgres::Client doesnt expose any internal state
d.field("conn", &!self.is_closed());
d.finish()
}
}

type DynToSqlPg<'a> = (dyn postgres::types::ToSql + Sync + 'a);

Expand Down Expand Up @@ -316,6 +330,15 @@ impl<'c> PgTransaction<'c> {
Error::Internal("transaction has already been consumed".to_string())
}
}
impl<'c> Debug for PgTransaction<'c> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PgTransaction")
// postgres::Transaction doesnt expose any internal state
.field("trans", &self.trans.is_some())
.finish()
}
}

impl<'c> PgConnectionLike for PgTransaction<'c> {
type Client = postgres::Transaction<'c>;
fn cell(&self) -> Result<&RefCell<Self::Client>> {
Expand Down Expand Up @@ -706,6 +729,7 @@ fn pgtype_for_val(val: &SqlVal) -> postgres::types::Type {
}
}

#[derive(Debug)]
struct PgPlaceholderSource {
n: i8,
}
Expand Down
1 change: 1 addition & 0 deletions butane_core/src/db/r2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::Result;
pub use r2d2::ManageConnection;

/// R2D2 support for Butane. Implements [`r2d2::ManageConnection`].
#[derive(Debug)]
pub struct ConnectionManager {
spec: ConnectionSpec,
}
Expand Down
7 changes: 6 additions & 1 deletion butane_core/src/db/sqlite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const SQLITE_DT_FORMAT: &str = "%Y-%m-%d %H:%M:%S";
pub const BACKEND_NAME: &str = "sqlite";

/// SQLite [Backend][crate::db::Backend] implementation.
#[derive(Default)]
#[derive(Debug, Default)]
pub struct SQLiteBackend {}
impl SQLiteBackend {
pub fn new() -> SQLiteBackend {
Expand Down Expand Up @@ -60,6 +60,7 @@ impl Backend for SQLiteBackend {
}

/// SQLite database connection.
#[derive(Debug)]
pub struct SQLiteConnection {
conn: rusqlite::Connection,
}
Expand Down Expand Up @@ -249,6 +250,7 @@ impl ConnectionMethods for rusqlite::Connection {
}
}

#[derive(Debug)]
struct SqliteTransaction<'c> {
trans: Option<rusqlite::Transaction<'c>>,
}
Expand Down Expand Up @@ -329,6 +331,7 @@ fn sqlvalref_to_sqlite<'a>(valref: &SqlValRef<'a>) -> rusqlite::types::ToSqlOutp
}

#[pin_project]
// Debug can not be derived because rusqlite::Rows doesn't implement it.
struct QueryAdapterInner<'a> {
stmt: rusqlite::Statement<'a>,
// will always be Some when the constructor has finished. We use an option only to get the
Expand Down Expand Up @@ -363,6 +366,7 @@ impl<'a> QueryAdapterInner<'a> {
}
}

// Debug can not be derived because QueryAdapterInner above doesn't implement it.
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

my guess is this struct and QueryAdapterInner above wont be encountered very often by developers, of butane or butane apps, so wasnt worth adding custom impls. But I dont mind doing them for completeness.

struct QueryAdapter<'a> {
inner: Pin<Box<QueryAdapterInner<'a>>>,
}
Expand Down Expand Up @@ -608,6 +612,7 @@ pub fn sql_insert_or_update(table: &str, columns: &[Column], w: &mut impl Write)
write!(w, ")").unwrap();
}

#[derive(Debug)]
struct SQLitePlaceholderSource {}
impl SQLitePlaceholderSource {
fn new() -> Self {
Expand Down
1 change: 0 additions & 1 deletion butane_core/src/fkey.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ use std::fmt::{Debug, Formatter};
/// blog: ForeignKey<Blog>,
/// ...
/// }
///
pub struct ForeignKey<T>
where
T: DataObject,
Expand Down
4 changes: 2 additions & 2 deletions butane_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ pub type Result<T> = std::result::Result<T, crate::Error>;
/// in the database yet. Butane automatically creates the field
/// `state: ObjectState` on `#[model]` structs. When initializing the
/// state field, use `ObjectState::default()`.
#[derive(Clone, Default, Debug)]
#[derive(Clone, Debug, Default)]
pub struct ObjectState {
pub saved: bool,
}
Expand Down Expand Up @@ -202,7 +202,7 @@ impl From<rusqlite::types::FromSqlError> for Error {
/// Enumeration of the types a database value may take.
///
/// See also [`SqlVal`][crate::SqlVal].
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum SqlType {
Bool,
/// 4 bytes
Expand Down
2 changes: 1 addition & 1 deletion butane_core/src/many.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ fn default_oc<T>() -> OnceCell<Vec<T>> {
/// U::PKType. Table name is T_ManyToMany_foo where foo is the name of
/// the Many field
//
#[derive(Clone, Debug, Serialize, Deserialize)]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Many<T>
where
T: DataObject,
Expand Down
16 changes: 9 additions & 7 deletions butane_core/src/migrations/adb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use std::collections::{HashMap, HashSet};
/// [SqlType](crate::SqlType) and identifiers known only by name. The
/// latter is used for custom types. `SqlType::Custom` cannot easily be used
/// directly at compile time when the proc macro serializing type information runs.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum TypeIdentifier {
Ty(SqlType),
Name(String),
Expand All @@ -23,7 +23,7 @@ impl From<SqlType> for TypeIdentifier {
}

/// Key used to help resolve `DeferredSqlType`
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum TypeKey {
/// Represents a type which is the primary key for a table with the given name
PK(String),
Expand Down Expand Up @@ -60,6 +60,8 @@ impl<'de> Deserialize<'de> for TypeKey {
deserializer.deserialize_string(TypeKeyVisitor)
}
}

#[derive(Debug)]
struct TypeKeyVisitor;
impl<'de> Visitor<'de> for TypeKeyVisitor {
type Value = TypeKey;
Expand Down Expand Up @@ -138,7 +140,7 @@ impl TypeResolver {
}

/// Abstract representation of a database schema.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct ADB {
tables: HashMap<String, ATable>,
extra_types: HashMap<TypeKey, DeferredSqlType>,
Expand Down Expand Up @@ -246,7 +248,7 @@ impl ADB {
}

/// Abstract representation of a database table schema.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ATable {
pub name: String,
pub columns: Vec<AColumn>,
Expand Down Expand Up @@ -280,7 +282,7 @@ impl ATable {
}

/// SqlType which may not yet be known.
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum DeferredSqlType {
Known(SqlType), // Kept for backwards deserialization compat, supplanted by KnownId
KnownId(TypeIdentifier),
Expand Down Expand Up @@ -311,7 +313,7 @@ impl From<TypeIdentifier> for DeferredSqlType {
}

/// Abstract representation of a database column schema.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct AColumn {
name: String,
sqltype: DeferredSqlType,
Expand Down Expand Up @@ -386,7 +388,7 @@ impl AColumn {
}

/// Individual operation use to apply a migration.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum Operation {
//future improvement: support column renames
AddTable(ATable),
Expand Down
4 changes: 3 additions & 1 deletion butane_core/src/migrations/fs.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use std::fmt::Debug;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};

/// Filesystem abstraction for `Migrations`. Primarily intended to
/// allow bypassing the real filesystem during testing, but
/// implementations that do not call through to the real filesystem
/// are supported in production.
pub trait Filesystem {
pub trait Filesystem: Debug {
/// Ensure a directory exists, recursively creating missing components
fn ensure_dir(&self, path: &Path) -> std::io::Result<()>;
/// List all paths in a directory
Expand All @@ -16,6 +17,7 @@ pub trait Filesystem {
fn read(&self, path: &Path) -> std::io::Result<Box<dyn Read>>;
}

#[derive(Debug)]
pub struct OsFilesystem {}

impl Filesystem for OsFilesystem {
Expand Down
Loading