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
use grammar::{Buffer, Definition, Expression};
use {Result, Typable, Type};
#[derive(Clone, Debug, Default)]
pub struct Column {
name: Option<String>,
kind: Option<Type>,
not_null: Option<()>,
}
impl Column {
#[inline]
pub fn new<T: ToString>(name: T) -> Self {
Column::default().name(name)
}
pub fn name<T: ToString>(mut self, value: T) -> Self {
self.name = Some(value.to_string());
self
}
pub fn kind(mut self, value: Type) -> Self {
self.kind = Some(value);
self
}
pub fn not_null(mut self) -> Self {
self.not_null = Some(());
self
}
}
impl Definition for Column {
fn compile(&self) -> Result<String> {
let mut buffer = Buffer::new();
buffer.push(format!("`{}`", some!(self.name)));
buffer.push(match some!(self.kind) {
&Type::Binary => "BLOB",
&Type::Float => "REAL",
&Type::Integer => "INTEGER",
&Type::String => "TEXT",
});
if let Some(_) = self.not_null {
buffer.push("NOT NULL");
}
Ok(buffer.join(" "))
}
}
impl Expression for Column {
fn compile(&self) -> Result<String> {
Ok(format!("`{}`", some!(self.name)))
}
}
impl Typable for Column {
type Output = Self;
#[inline]
fn kind(self, kind: Type) -> Self {
Column::kind(self, kind)
}
}
impl<'l> Typable for &'l str {
type Output = Column;
#[inline]
fn kind(self, kind: Type) -> Self::Output {
Column::default().name(self).kind(kind)
}
}
#[cfg(test)]
mod tests {
use grammar::Definition;
use prelude::*;
#[test]
fn not_null() {
let column = column("foo").kind(Type::Float).not_null();
assert_eq!(Definition::compile(&column).unwrap(), "`foo` REAL NOT NULL");
}
}