Support SELECT DISTINCT

This commit is contained in:
Nickolay Ponomarev 2019-04-20 14:15:05 +03:00
parent 31b6076d05
commit bbf1805729
3 changed files with 17 additions and 1 deletions

View file

@ -110,6 +110,7 @@ impl ToString for SQLSetOperator {
/// to a set operation like `UNION`. /// to a set operation like `UNION`.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct SQLSelect { pub struct SQLSelect {
pub distinct: bool,
/// projection expressions /// projection expressions
pub projection: Vec<SQLSelectItem>, pub projection: Vec<SQLSelectItem>,
/// FROM /// FROM
@ -127,7 +128,8 @@ pub struct SQLSelect {
impl ToString for SQLSelect { impl ToString for SQLSelect {
fn to_string(&self) -> String { fn to_string(&self) -> String {
let mut s = format!( let mut s = format!(
"SELECT {}", "SELECT{} {}",
if self.distinct { " DISTINCT" } else { "" },
self.projection self.projection
.iter() .iter()
.map(|p| p.to_string()) .map(|p| p.to_string())

View file

@ -1352,6 +1352,7 @@ impl Parser {
/// Parse a restricted `SELECT` statement (no CTEs / `UNION` / `ORDER BY`), /// Parse a restricted `SELECT` statement (no CTEs / `UNION` / `ORDER BY`),
/// assuming the initial `SELECT` was already consumed /// assuming the initial `SELECT` was already consumed
pub fn parse_select(&mut self) -> Result<SQLSelect, ParserError> { pub fn parse_select(&mut self) -> Result<SQLSelect, ParserError> {
let distinct = self.parse_keyword("DISTINCT");
let projection = self.parse_select_list()?; let projection = self.parse_select_list()?;
let (relation, joins) = if self.parse_keyword("FROM") { let (relation, joins) = if self.parse_keyword("FROM") {
@ -1381,6 +1382,7 @@ impl Parser {
}; };
Ok(SQLSelect { Ok(SQLSelect {
distinct,
projection, projection,
selection, selection,
relation, relation,

View file

@ -50,11 +50,23 @@ fn parse_where_delete_statement() {
fn parse_simple_select() { fn parse_simple_select() {
let sql = "SELECT id, fname, lname FROM customer WHERE id = 1 LIMIT 5"; let sql = "SELECT id, fname, lname FROM customer WHERE id = 1 LIMIT 5";
let select = verified_only_select(sql); let select = verified_only_select(sql);
assert_eq!(false, select.distinct);
assert_eq!(3, select.projection.len()); assert_eq!(3, select.projection.len());
let select = verified_query(sql); let select = verified_query(sql);
assert_eq!(Some(ASTNode::SQLValue(Value::Long(5))), select.limit); assert_eq!(Some(ASTNode::SQLValue(Value::Long(5))), select.limit);
} }
#[test]
fn parse_select_distinct() {
let sql = "SELECT DISTINCT name FROM customer";
let select = verified_only_select(sql);
assert_eq!(true, select.distinct);
assert_eq!(
&SQLSelectItem::UnnamedExpression(ASTNode::SQLIdentifier("name".to_string())),
only(&select.projection)
);
}
#[test] #[test]
fn parse_select_wildcard() { fn parse_select_wildcard() {
let sql = "SELECT * FROM foo"; let sql = "SELECT * FROM foo";