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 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
use core::fmt;
/// Represents the creation of a table with specified columns and options.
pub struct CreateTable {
table: String,
columns: Vec<Column>,
if_not_exists: bool,
}
impl CreateTable {
/// Creates a new `CreateTable` instance with the given table name and columns.
/// # Example
/// ```
/// use lumus_sql_builder::sqlite::{CreateTable, Column};
/// CreateTable::new("users", vec![
/// Column::new("name").text().not_null().primary_key(),
/// Column::new("age").literal("INTEGER NOT NULL"),
/// ]);
/// ```
pub fn new<T: Into<String>>(table: T, columns: Vec<Column>) -> CreateTable {
CreateTable {
table: table.into(),
columns,
if_not_exists: false,
}
}
/// Specifies that the table should be created only if it does not already exist.
pub fn if_not_exists(mut self) -> Self {
self.if_not_exists = true;
self
}
/// Builds and returns the SQL statement for creating the table.
pub fn build(&self) -> String {
let mut statement = String::new();
if self.if_not_exists {
statement.push_str(&format!("CREATE TABLE IF NOT EXISTS {} ", self.table));
} else {
statement.push_str(&format!("CREATE TABLE {} ", self.table));
}
statement.push('(');
for (i, column) in self.columns.iter().enumerate() {
statement.push_str(&column.build());
if i < self.columns.len() - 1 {
statement.push_str(", ");
}
}
statement.push_str(");");
statement
}
}
/// Implementation of the Display trait for `CreateTable`, allowing it to be printed.
impl fmt::Display for CreateTable {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.build())
}
}
/// Represents the possible data types for a table column.
#[derive(Debug)]
pub enum ColumnType {
Integer,
Text,
Real,
Boolean,
Blob,
Numeric,
Date,
Time,
Datetime,
}
/// Implementation of the Display trait for `ColumnType`, allowing it to be printed.
impl fmt::Display for ColumnType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ColumnType::Integer => write!(f, "INTEGER"),
ColumnType::Text => write!(f, "TEXT"),
ColumnType::Real => write!(f, "REAL"),
ColumnType::Boolean => write!(f, "BOOLEAN"),
ColumnType::Blob => write!(f, "BLOB"),
ColumnType::Numeric => write!(f, "NUMERIC"),
ColumnType::Date => write!(f, "DATE"),
ColumnType::Time => write!(f, "TIME"),
ColumnType::Datetime => write!(f, "DATETIME"),
}
}
}
/// Represents the possible options for a table column.
#[derive(Debug)]
pub enum ColumnOption {
NotNull,
Unique,
Default(String),
AutoIncrement,
PrimaryKey,
}
/// Implementation of the Display trait for `ColumnOption`, allowing it to be printed.
impl fmt::Display for ColumnOption {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ColumnOption::NotNull => write!(f, "NOT NULL"),
ColumnOption::Unique => write!(f, "UNIQUE"),
ColumnOption::Default(value) => write!(f, "DEFAULT {}", value),
ColumnOption::AutoIncrement => write!(f, "AUTOINCREMENT"),
ColumnOption::PrimaryKey => write!(f, "PRIMARY KEY"),
}
}
}
/// Represents a table column with a name, data type, and options.
#[derive(Debug)]
pub struct Column {
name: String,
column_type: Option<ColumnType>,
options: Vec<ColumnOption>,
literal: Option<String>,
}
impl Column {
/// Creates a new `Column` instance with the given column name.
/// # Example
/// ```
/// use lumus_sql_builder::sqlite::Column;
/// Column::new("name").text().not_null();
/// ```
pub fn new(name: &str) -> Column {
Self {
name: name.to_string(),
column_type: None,
options: Vec::new(),
literal: None,
}
}
/// Specifies that the column has an `INTEGER` data type.
pub fn integer(mut self) -> Self {
self.column_type = Some(ColumnType::Integer);
self
}
/// Specifies that the column has a `TEXT` data type.
pub fn text(mut self) -> Self {
self.column_type = Some(ColumnType::Text);
self
}
/// Specifies that the column has a `REAL` data type.
pub fn real(mut self) -> Self {
self.column_type = Some(ColumnType::Real);
self
}
/// Specifies that the column has a `BOOLEAN` data type.
pub fn boolean(mut self) -> Self {
self.column_type = Some(ColumnType::Boolean);
self
}
/// Specifies that the column has a `BLOB` data type.
pub fn blob(mut self) -> Self {
self.column_type = Some(ColumnType::Blob);
self
}
/// Specifies that the column has a `NUMERIC` data type.
pub fn numeric(mut self) -> Self {
self.column_type = Some(ColumnType::Numeric);
self
}
/// Specifies that the column has a `DATE` data type.
pub fn date(mut self) -> Self {
self.column_type = Some(ColumnType::Date);
self
}
/// Specifies that the column has a `TIME` data type.
pub fn time(mut self) -> Self {
self.column_type = Some(ColumnType::Time);
self
}
/// Specifies that the column has a `DATETIME` data type.
pub fn datetime(mut self) -> Self {
self.column_type = Some(ColumnType::Datetime);
self
}
/// Specifies that the column cannot have `NULL` values.
pub fn not_null(mut self) -> Self {
self.options.push(ColumnOption::NotNull);
self
}
/// Specifies that the column values must be unique across rows.
pub fn unique(mut self) -> Self {
self.options.push(ColumnOption::Unique);
self
}
/// Specifies a default value for the column.
pub fn default(mut self, value: &str) -> Self {
self.options.push(ColumnOption::Default(value.to_string()));
self
}
/// Specifies that the column values should auto-increment.
pub fn auto_increment(mut self) -> Self {
self.options.push(ColumnOption::AutoIncrement);
self
}
/// Specifies that the column is a primary key.
pub fn primary_key(mut self) -> Self {
self.options.push(ColumnOption::PrimaryKey);
self
}
/// Specifies a `literal` value for the column.
pub fn literal(mut self, value: &str) -> Self {
self.literal = Some(value.to_string());
self
}
/// Builds and returns the SQL representation of the column.
pub fn build(&self) -> String {
let column_type_str = match &self.column_type {
Some(ct) => ct.to_string(),
None => String::new(),
};
let options_str: String = self
.options
.iter()
.map(|opt| opt.to_string())
.collect::<Vec<String>>()
.join(" ");
if options_str.len() > 0 {
return format!(
"{}{}",
self.name,
format!(" {} {}", column_type_str, options_str)
);
}
if !column_type_str.is_empty() {
return format!("{} {}", self.name, column_type_str);
}
let literal_str = match &self.literal {
Some(lit) => lit.clone(),
None => String::new(),
};
return format!("{} {}", self.name, literal_str);
}
}
impl fmt::Display for Column {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.build())
}
}
pub struct Select {
table: String,
distinct: bool,
columns: Option<String>,
group: Option<String>,
order: Option<String>,
limit: Option<u32>,
offset: Option<u32>,
}
impl Select {
/// Creates a new `Select` instance with the specified table name.
/// # Example
/// ```
/// use lumus_sql_builder::sqlite::Select;
/// Select::new("users").columns("name, age");
/// ```
pub fn new<T: Into<String>>(table: T) -> Select {
Select {
table: table.into(),
distinct: false,
columns: None,
group: None,
order: None,
limit: None,
offset: None,
}
}
/// Specifies that the select statement should return distinct rows.
pub fn distinct(&mut self) -> &mut Self {
self.distinct = true;
self
}
/// Specifies the columns to be selected in the query.
pub fn columns<T: Into<String>>(&mut self, columns: T) -> &mut Self {
self.columns = Some(columns.into());
self
}
/// Specifies the grouping for the query results.
pub fn group<T: Into<String>>(&mut self, group: T) -> &mut Self {
self.group = Some(group.into());
self
}
/// Specifies the ordering for the query results.
pub fn order<T: Into<String>>(&mut self, order: T) -> &mut Self {
self.order = Some(order.into());
self
}
/// Specifies the maximum number of rows to be returned by the query.
pub fn limit(&mut self, limit: u32) -> &mut Self {
self.limit = Some(limit);
self
}
/// Specifies the offset for the query results.
pub fn offset(&mut self, offset: u32) -> &mut Self {
self.offset = Some(offset);
self
}
/// Builds and returns the SQL statement for the select query.
pub fn build(&self) -> String {
let mut statement = String::from("SELECT");
if self.distinct {
statement.push_str(" DISTINCT");
}
if let Some(columns) = &self.columns {
statement.push_str(&format!(" {}", columns));
} else {
statement.push_str(" *");
}
statement.push_str(&format!(" FROM {}", self.table));
if let Some(group) = &self.group {
statement.push_str(&format!(" GROUP BY {}", group));
}
if let Some(order) = &self.order {
statement.push_str(&format!(" ORDER BY {}", order));
}
if let Some(limit) = &self.limit {
statement.push_str(&format!(" LIMIT {}", limit));
}
if let Some(offset) = &self.offset {
statement.push_str(&format!(" OFFSET {}", offset));
}
statement.push(';');
statement
}
}
impl fmt::Display for Select {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.build())
}
}