From 5d1cadd47caeac9f0255e4ecfaf1f5d829066049 Mon Sep 17 00:00:00 2001 From: Ryan Leckey Date: Thu, 18 Feb 2021 21:40:41 -0800 Subject: [PATCH] feat(mysql): expand MySqlColumn, add various helper methods --- sqlx-mysql/src/column.rs | 50 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/sqlx-mysql/src/column.rs b/sqlx-mysql/src/column.rs index e629d60c..771bab7f 100644 --- a/sqlx-mysql/src/column.rs +++ b/sqlx-mysql/src/column.rs @@ -1,23 +1,68 @@ use bytestring::ByteString; use sqlx_core::Column; +use crate::protocol::{ColumnDefinition, ColumnFlags}; +use crate::{MySql, MySqlTypeInfo}; + +/// Represents a column from a query in MySQL. #[allow(clippy::module_name_repetitions)] +#[derive(Debug, Clone)] pub struct MySqlColumn { ordinal: usize, name: ByteString, + type_info: MySqlTypeInfo, + flags: ColumnFlags, } impl MySqlColumn { + pub(crate) fn new(ordinal: usize, def: ColumnDefinition) -> Self { + Self { type_info: MySqlTypeInfo::new(&def), ordinal, name: def.name, flags: def.flags } + } +} + +impl MySqlColumn { + /// Returns the name of the column. + /// + /// If the original name of the column has been aliased, this will return + /// the aliased name. + /// pub fn name(&self) -> &str { &self.name } + /// Returns type information of the column. + pub fn type_info(&self) -> &MySqlTypeInfo { + &self.type_info + } + + /// Returns the (zero-based) position of the column. pub const fn ordinal(&self) -> usize { self.ordinal } + + /// Returns `true` if the column is (or is part of) a `PRIMARY KEY`. + pub const fn is_primary_key(&self) -> bool { + self.flags.contains(ColumnFlags::PRIMARY_KEY) + } + + /// Returns `true` if the column is nullable. + pub const fn is_nullable(&self) -> bool { + !self.flags.contains(ColumnFlags::NOT_NULL) + } + + /// Returns `true` if the column is has a default value. + /// + /// Always returns `true` if the column is nullable as `NULL` is + /// a valid default value. + /// + pub const fn has_default_value(&self) -> bool { + !self.flags.contains(ColumnFlags::NO_DEFAULT_VALUE) + } } impl Column for MySqlColumn { + type Database = MySql; + #[inline] fn name(&self) -> &str { self.name() @@ -27,4 +72,9 @@ impl Column for MySqlColumn { fn ordinal(&self) -> usize { self.ordinal() } + + #[inline] + fn type_info(&self) -> &MySqlTypeInfo { + self.type_info() + } }