1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
use tokio_postgres::{types::ToSql, Row};
pub trait IntoSyntax {
fn as_syntax(&self, local_table: &str) -> String;
}
impl IntoSyntax for &'static [&'static PostgresField] {
fn as_syntax(&self, local_table: &str) -> String {
let mut v = self.iter().map(|x| x.into_syntax(local_table)).fold(String::new(), |acc, x| acc + &x + ",");
v.pop();
v
}
}
impl IntoSyntax for &'static [&'static PostgresJoin] {
fn as_syntax(&self, local_table: &str) -> String {
let mut v = self.iter().map(|x| x.to_read(local_table)).fold(String::new(), |acc, x| acc + &x + " ");
v.pop();
v
}
}
/// A trait for getting a struct from a Postgres row.
///
/// This can be derived provided that each property also
/// implements `FromPostgres`.
pub trait FromPostgres {
fn from_postgres(row: &Row) -> Self;
fn try_from_postgres(row: &Row) -> Result<Self, FromPostgresError>
where
Self: Sized;
}
pub enum FromPostgresError {
InvalidType(&'static str),
MissingColumn(&'static str),
}
/// A struct that defines how Tusk should join
/// tables for you.
pub struct PostgresJoin {
/// The type of join to perform. Examples are INNER JOIN, LEFT JOIN, etc.
pub join_type: &'static str,
/// The table to join.
pub table: &'static str,
/// The field in the local table to join on.
pub local_field: &'static str,
/// The field in the foreign table to join on.
pub foreign_field: &'static str,
/// The condition to join on. Use SQL syntax.
pub condition: &'static str,
}
impl PostgresJoin {
/// Converts the join to a read statement.
pub fn to_read(&self, local_table: &str) -> String {
format!("{} {} ON {}.{} {} {}.{}", self.join_type, self.table, local_table, self.local_field, self.condition, self.table, self.foreign_field)
}
/// Tusk returns the insertered or updated row(s),
/// so this converts the join to a write statement.
pub fn to_write(&self, local_table: &str) -> String {
format!("FROM {} WHERE {}.{} {} {}.{}", self.table, local_table, self.local_field, self.condition, self.table, self.foreign_field)
}
}
/// Describes what kind of field this is.
/// For more information, read [`PostgresField`].
pub enum PostgresFieldLocation {
/// A field on the table itself.
Local(&'static str),
/// An expression that can be evaluated.
Expression(&'static str),
/// A field on a foreign table.
/// Syntax is (table, field).
Join(&'static str, &'static str),
}
/// A struct that symbolizes a field in a Postgres table.
/// This is used for reading from tables.
///
/// Intializing this struct manually is frowned upon.
/// The easiest way to construct a PostgresField is to use
/// the macros provided.
/// - [`local`] for a field on the table itself.
/// - [`local_as`] for a field on the table itself with an alias.
/// - [`expression`] for an expression.
/// - [`foreign`] for a field on a foreign table.
/// - [`foreign_as`] for a field on a foreign table with an alias.
pub struct PostgresField {
pub alias: &'static str,
pub location: PostgresFieldLocation,
}
impl PostgresField {
pub fn into_syntax(&self, local_table: &str) -> String {
format!("{} AS {}", match &self.location {
PostgresFieldLocation::Local(field) => format!("{}.{}", local_table, field),
PostgresFieldLocation::Expression(expr) => expr.to_string().replace("{}", local_table),
PostgresFieldLocation::Join(table, field) => format!("{}.{}", table, field),
}, self.alias)
}
}
/// A macro for creating a local field.
///
/// # Arguments
/// - `$name` - The name of the field, as a &'static str.
#[macro_export]
macro_rules! local {
($name: literal) => {
&tusk_rs::PostgresField {
alias: $name,
location: tusk_rs::PostgresFieldLocation::Local($name),
}
};
}
/// A macro for creating a local field with an alias.
///
/// # Arguments
/// - `$name` - The name of the field, as a &'static str.
/// - `$alias` - The alias of the field, as a &'static str.
#[macro_export]
macro_rules! local_as {
($name: literal, $alias: literal) => {
&tusk_rs::PostgresField {
alias: $alias,
location: tusk_rs::PostgresFieldLocation::Local($name),
}
};
}
/// A macro for creating an expression.
///
/// # Arguments
/// - `$expr` - The expression to evaluate, as a &'static str.
/// - `$alias` - The alias of the expression, as a &'static str.
#[macro_export]
macro_rules! expression {
($expr: literal, $alias: literal) => {
&tusk_rs::PostgresField {
alias: $alias,
location: tusk_rs::PostgresFieldLocation::Expression($expr),
}
};
}
/// A macro for creating a foreign field.
///
/// Using [`foreign_as`] is recommended to prevent conflicts where
/// both a local and foreign field have the same name.
///
/// # Arguments
/// - `$table` - The table to join on, as a &'static str.
/// - `$name` - The name of the field, as a &'static str.
#[macro_export]
macro_rules! foreign {
($table: literal, $name: literal) => {
&tusk_rs::PostgresField {
alias: $name,
location: tusk_rs::PostgresFieldLocation::Join($table, $name),
}
};
}
/// A macro for creating a foreign field with an alias.
///
/// # Arguments
/// - `$table` - The table to join on, as a &'static str.
/// - `$name` - The name of the field, as a &'static str.
/// - `$alias` - The alias of the field, as a &'static str.
#[macro_export]
macro_rules! foreign_as {
($table: literal, $name: literal, $alias: literal) => {
&tusk_rs::PostgresField {
alias: $alias,
location: tusk_rs::PostgresFieldLocation::Join($table, $name),
}
};
}
/// A struct that contains data to write into
/// a Postgres table.
#[derive(Debug)]
pub struct PostgresWrite {
/// The fields that will be provided.
pub fields: &'static [&'static str],
/// The arguments to insert. This supports either
/// a single row or multiple rows.
///
/// arguments.len() % fields.len() must always be 0.
pub arguments: Vec<Box<(dyn ToSql + Sync)>>,
}
impl PostgresWrite {
/// Converts the write struct into an insert statement
pub fn into_insert(&self, table_name: &str) -> (String, Vec<&(dyn ToSql + Sync)>) {
(
format!(
"INSERT INTO {} ({}) VALUES ({})",
table_name,
self.fields.join(","),
(0..self.arguments.len())
.map(|x| format!("${}", x + 1))
.collect::<Vec<String>>()
.join(",")
),
self.arguments
.iter()
.map(|x| x.as_ref())
.collect::<Vec<&(dyn ToSql + Sync)>>(),
)
}
/// Converts the write struct into a bulk insert statement
pub fn into_bulk_insert(&self, table_name: &str) -> (String, Vec<&(dyn ToSql + Sync)>) {
if self.arguments.len() % self.fields.len() != 0 {
panic!("For a bulk insert, arguments % fields must be 0.")
}
let mut arg_groups: Vec<String> = vec![];
for ix in 0..(self.arguments.len() / self.fields.len()) {
let mut iter_args = vec![];
for jx in 0..self.fields.len() {
iter_args.push(format!("${}", ix * self.fields.len() + jx + 1))
}
arg_groups.push(format!("({})", iter_args.join(",")));
}
(
format!(
"INSERT INTO {} ({}) VALUES {}",
table_name,
self.fields.join(","),
arg_groups.join(",")
),
self.arguments
.iter()
.map(|x| x.as_ref())
.collect::<Vec<&(dyn ToSql + Sync)>>(),
)
}
/// Converts the write struct into an update statement
pub fn into_update(
&self,
table_name: &str,
arg_offset: usize,
) -> (String, Vec<&(dyn ToSql + Sync)>) {
if self.fields.len() != self.arguments.len() {
panic!("Field length must equal argument length")
}
(
format!(
"UPDATE {} SET {}",
table_name,
(0..self.arguments.len())
.map(|x| format!("{} = ${}", self.fields[x], x + 1 + arg_offset))
.collect::<Vec<String>>()
.join(",")
),
self.arguments
.iter()
.map(|x| x.as_ref())
.collect::<Vec<&(dyn ToSql + Sync)>>(),
)
}
}
/// A trait for defining a table in Postgres.
/// This is used for determining which table
/// to read/write from. This is required for
/// all Tusk database operations.
pub trait PostgresTable {
/// The name of the table in Postgres.
fn table_name() -> &'static str;
}
/// A trait for defining joins in Postgres.
/// This is used for determining how to join
/// tables. This is required for all Tusk
/// database operations.
///
/// For more info on implementing this trait,
/// read the documentation for [`PostgresJoin`].
pub trait PostgresJoins {
/// The joins to perform.
fn joins() -> &'static [&'static PostgresJoin];
}
/// A trait for defining fields to read from
/// in Postgres. This is required for all
/// Tusk database operations.
///
/// This may be implemented by deriving [`PostgresJoin`],
/// which will read all fields in the struct.
///
/// For more control (for example to include expression columns),
/// implement this manually. To learn more about manual implementation,
/// read the documentation for [`PostgresField`].
pub trait PostgresReadFields {
/// The fields to read.
fn read_fields() -> &'static [&'static PostgresField];
}
/// A trait that declares a struct as readable.
/// Even though there are no methods, this is
/// a stub for future implementations.
///
/// For now, it may be implemented by deriving.
pub trait PostgresReadable: PostgresReadFields + PostgresJoins {}
/// A trait for defining fields to write to
/// in Postgres. This is required for all
/// Tusk database operations.
///
/// Unlike [`PostgresReadFields`], this trait
/// returns static string slices instead of structs.
/// Because the struct data is not needed to perform writes,
/// this improves performance.
pub trait PostgresWriteFields {
fn write_fields() -> &'static [&'static str];
}
/// A trait that declares a struct as writeable.
/// Do not manually implement this. Instead, implement
/// [`PostgresWriteFields`] and [`PostgresJoins`], and derive
/// this trait.
pub trait PostgresWriteable: PostgresWriteFields + PostgresJoins {
fn write(self) -> PostgresWrite;
}
/// A trait for defining a struct as bulk writeable.
/// This is typically defined on collections of structs.
/// Tusk includes a default implementation for Vec<T> where
/// T implements [`PostgresWriteable`].
pub trait PostgresBulkWriteable {
fn into_bulk_write(self) -> PostgresWrite;
}
impl<T: PostgresWriteable + PostgresTable> PostgresBulkWriteable for Vec<T> {
fn into_bulk_write(self) -> PostgresWrite {
PostgresWrite {
arguments: self.into_iter().flat_map(|x| x.write().arguments).collect(),
fields: T::write_fields(),
}
}
}