Skip to main content

TableName

Struct TableName 

Source
pub struct TableName<'a> { /* private fields */ }
Expand description

A table outside the queue’s own description, such as the table dead-lettered rows move to.

It is read from table or schema.table, and checked when it is read: no segment is empty, and there is at most one schema.

§Examples

use ruststream_sqlx_dialect::{
    Dialect, Param, Statement, StatementError, TableName, TableSpec,
};

/// SQL Server, a database without a built-in dialect.
#[derive(Debug)]
pub struct Mssql;

impl Dialect for Mssql {
    fn name(&self) -> &'static str {
        "mssql"
    }

    // A dead email of the service's one queue table moves with the time it died.
    fn dead_letter_table(
        &self,
        _spec: &TableSpec<'_>,
        target: TableName<'_>,
    ) -> Result<Vec<Statement>, StatementError> {
        let mut into = String::new();
        self.quote_into(target.schema().unwrap_or("dbo"), &mut into);
        into.push('.');
        self.quote_into(target.table(), &mut into);
        Ok(vec![
            Statement::new(
                format!(
                    "INSERT INTO {into} ([job_id], [payload], [died_at]) \
                     SELECT [job_id], [payload], @p1 FROM [email_jobs] WHERE [job_id] = @p2"
                ),
                [Param::Now, Param::Id],
            ),
            Statement::new("DELETE FROM [email_jobs] WHERE [job_id] = @p1", [Param::Id]),
        ])
    }

    fn quote_into(&self, ident: &str, out: &mut String) {
        out.push('[');
        out.push_str(&ident.replace(']', "]]"));
        out.push(']');
    }
}

Implementations§

Source§

impl<'a> TableName<'a>

Source

pub fn parse(name: &'a str) -> Result<Self, ParseTableNameError>

Reads table or schema.table.

§Errors

ParseTableNameError::EmptySegment when the name or one of its segments is empty; ParseTableNameError::TooManySegments when the name has more than one dot.

§Examples
use ruststream_sqlx_dialect::{Column, Dialect, Form, Postgres, TableName, TableSpec};

const EMAILS: TableSpec<'static> =
    TableSpec::new("email_jobs", Column::new("job_id"), Form::RowLock)
        .payload(Column::new("payload"));

// A dead email moves to the table the configuration names, in the `archive` schema.
let target = TableName::parse("archive.email_jobs_dead")?;
let moves = Postgres.dead_letter_table(&EMAILS, target)?;
assert_eq!(
    moves[0].sql(),
    r#"WITH moved AS (DELETE FROM "email_jobs" WHERE "job_id" = $1 RETURNING "job_id", "payload") INSERT INTO "archive"."email_jobs_dead" ("job_id", "payload") SELECT "job_id", "payload" FROM moved"#
);
Source

pub const fn schema(&self) -> Option<&'a str>

The schema, or None for the connection’s default.

§Examples
use ruststream_sqlx_dialect::{
    Dialect, Param, Statement, StatementError, TableName, TableSpec,
};

/// SQL Server, a database without a built-in dialect.
#[derive(Debug)]
pub struct Mssql;

impl Dialect for Mssql {
    fn name(&self) -> &'static str {
        "mssql"
    }

    fn dead_letter_table(
        &self,
        spec: &TableSpec<'_>,
        target: TableName<'_>,
    ) -> Result<Vec<Statement>, StatementError> {
        // A struct that flattens another hides columns, so its row moves by position.
        let mut columns = String::new();
        if spec.selects_all() {
            columns.push('*');
        } else {
            for column in spec.columns() {
                if !columns.is_empty() {
                    columns.push_str(", ");
                }
                self.quote_into(column.name(), &mut columns);
            }
        }
        // A target that names no schema lives in SQL Server's default one, `dbo`.
        let mut into = String::new();
        self.quote_into(target.schema().unwrap_or("dbo"), &mut into);
        into.push('.');
        self.quote_into(target.table(), &mut into);
        let mut from = String::new();
        self.quote_into(spec.table(), &mut from);
        let mut id = String::new();
        self.quote_into(spec.id().name(), &mut id);
        let into_columns = if spec.selects_all() {
            String::new()
        } else {
            format!(" ({columns})")
        };
        Ok(vec![
            Statement::new(
                format!(
                    "INSERT INTO {into}{into_columns} SELECT {columns} FROM {from} \
                     WHERE {id} = @p1"
                ),
                [Param::Id],
            ),
            Statement::new(format!("DELETE FROM {from} WHERE {id} = @p1"), [Param::Id]),
        ])
    }
}
Source

pub const fn table(&self) -> &'a str

The table’s name, without its schema.

§Examples
use ruststream_sqlx_dialect::{
    Dialect, Param, Statement, StatementError, TableName, TableSpec,
};

/// SQL Server, a database without a built-in dialect.
#[derive(Debug)]
pub struct Mssql;

impl Dialect for Mssql {
    fn name(&self) -> &'static str {
        "mssql"
    }

    fn dead_letter_table(
        &self,
        spec: &TableSpec<'_>,
        target: TableName<'_>,
    ) -> Result<Vec<Statement>, StatementError> {
        // A struct that flattens another hides columns, so its row moves by position.
        let mut columns = String::new();
        if spec.selects_all() {
            columns.push('*');
        } else {
            for column in spec.columns() {
                if !columns.is_empty() {
                    columns.push_str(", ");
                }
                self.quote_into(column.name(), &mut columns);
            }
        }
        // A target that names no schema lives in SQL Server's default one, `dbo`.
        let mut into = String::new();
        self.quote_into(target.schema().unwrap_or("dbo"), &mut into);
        into.push('.');
        self.quote_into(target.table(), &mut into);
        let mut from = String::new();
        self.quote_into(spec.table(), &mut from);
        let mut id = String::new();
        self.quote_into(spec.id().name(), &mut id);
        let into_columns = if spec.selects_all() {
            String::new()
        } else {
            format!(" ({columns})")
        };
        Ok(vec![
            Statement::new(
                format!(
                    "INSERT INTO {into}{into_columns} SELECT {columns} FROM {from} \
                     WHERE {id} = @p1"
                ),
                [Param::Id],
            ),
            Statement::new(format!("DELETE FROM {from} WHERE {id} = @p1"), [Param::Id]),
        ])
    }
}

Trait Implementations§

Source§

impl<'a> Clone for TableName<'a>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'a> Copy for TableName<'a>

Source§

impl<'a> Debug for TableName<'a>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'a> Eq for TableName<'a>

Source§

impl<'a> Hash for TableName<'a>

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<'a> PartialEq for TableName<'a>

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl<'a> StructuralPartialEq for TableName<'a>

Auto Trait Implementations§

§

impl<'a> Freeze for TableName<'a>

§

impl<'a> RefUnwindSafe for TableName<'a>

§

impl<'a> Send for TableName<'a>

§

impl<'a> Sync for TableName<'a>

§

impl<'a> Unpin for TableName<'a>

§

impl<'a> UnsafeUnpin for TableName<'a>

§

impl<'a> UnwindSafe for TableName<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.