Merge pull request #23 from torpedro/statements-clean

Clean-Up and Reformatting of Code
This commit is contained in:
Pedro Flemming 2017-02-08 03:15:15 +01:00 committed by GitHub
commit 89a81848b4
31 changed files with 1358 additions and 1239 deletions

View File

@ -1,8 +1,10 @@
--style=google
# indentation # indentation
--indent=spaces=4 --indent=spaces=2
--indent-namespaces --indent-namespaces
--style=java --align-reference=type
--style=attach --align-pointer=type
-A2 --pad-oper

View File

@ -8,39 +8,39 @@
namespace hsql { namespace hsql {
SQLParser::SQLParser() { SQLParser::SQLParser() {
fprintf(stderr, "SQLParser only has static methods atm! Do not initialize!\n"); fprintf(stderr, "SQLParser only has static methods atm! Do not initialize!\n");
}
SQLParserResult* SQLParser::parseSQLString(const char* text) {
SQLParserResult* result = NULL;
yyscan_t scanner;
YY_BUFFER_STATE state;
if (hsql_lex_init(&scanner)) {
// Couldn't initialize the lexer.
fprintf(stderr, "[Error] SQLParser: Error when initializing lexer!\n");
return NULL;
} }
state = hsql__scan_string(text, scanner);
SQLParserResult* SQLParser::parseSQLString(const char *text) { // Parser and return early if it failed.
SQLParserResult* result = NULL; if (hsql_parse(&result, scanner)) {
yyscan_t scanner; // Returns an error stmt object.
YY_BUFFER_STATE state; return result;
if (hsql_lex_init(&scanner)) {
// couldn't initialize
fprintf(stderr, "[Error] SQLParser: Error when initializing lexer!\n");
return NULL;
}
state = hsql__scan_string(text, scanner);
if (hsql_parse(&result, scanner)) {
// Returns an error stmt object
return result;
}
hsql__delete_buffer(state, scanner);
hsql_lex_destroy(scanner);
return result;
} }
hsql__delete_buffer(state, scanner);
SQLParserResult* SQLParser::parseSQLString(const std::string& text) { hsql_lex_destroy(scanner);
return parseSQLString(text.c_str()); return result;
} }
SQLParserResult* SQLParser::parseSQLString(const std::string& text) {
return parseSQLString(text.c_str());
}
} // namespace hsql } // namespace hsql

View File

@ -5,17 +5,20 @@
#include "sql/statements.h" #include "sql/statements.h"
namespace hsql { namespace hsql {
/**
* Main class for parsing SQL strings
*/
class SQLParser {
public:
static SQLParserResult* parseSQLString(const char* sql);
static SQLParserResult* parseSQLString(const std::string& sql);
private: // Static methods used to parse SQL strings.
SQLParser(); class SQLParser {
}; public:
// Parses a given constant character SQL string.
static SQLParserResult* parseSQLString(const char* sql);
// Parses an SQL std::string.
static SQLParserResult* parseSQLString(const std::string& sql);
private:
// Static class can't be instatiated.
SQLParser();
};
} // namespace hsql } // namespace hsql

View File

@ -3,39 +3,64 @@
namespace hsql { namespace hsql {
SQLParserResult::SQLParserResult() : SQLParserResult::SQLParserResult() :
isValid(true), isValid_(true),
errorMsg(NULL) {}; errorMsg_(NULL) {};
SQLParserResult::SQLParserResult(SQLStatement* stmt) :
isValid_(true),
errorMsg_(NULL) {
addStatement(stmt);
};
SQLParserResult::SQLParserResult(SQLStatement* stmt) : SQLParserResult::~SQLParserResult() {
isValid(true), for (SQLStatement* statement : statements_) {
errorMsg(NULL) { delete statement;
addStatement(stmt);
};
SQLParserResult::~SQLParserResult() {
for (std::vector<SQLStatement*>::iterator it = statements.begin(); it != statements.end(); ++it) {
delete *it;
}
delete errorMsg;
} }
delete errorMsg_;
}
void SQLParserResult::addStatement(SQLStatement* stmt) { void SQLParserResult::addStatement(SQLStatement* stmt) {
statements.push_back(stmt); statements_.push_back(stmt);
} }
const SQLStatement* SQLParserResult::getStatement(int index) const {
return statements_[index];
}
SQLStatement* SQLParserResult::getStatement(int id) { SQLStatement* SQLParserResult::getMutableStatement(int index) {
return statements[id]; return statements_[index];
} }
size_t SQLParserResult::size() const {
return statements_.size();
}
size_t SQLParserResult::size() { bool SQLParserResult::isValid() const {
return statements.size(); return isValid_;
} }
const char* SQLParserResult::errorMsg() const {
return errorMsg_;
}
int SQLParserResult::errorLine() const {
return errorLine_;
}
int SQLParserResult::errorColumn() const {
return errorColumn_;
}
void SQLParserResult::setIsValid(bool isValid) {
isValid_ = isValid;
}
void SQLParserResult::setErrorDetails(const char* errorMsg, int errorLine, int errorColumn) {
errorMsg_ = errorMsg;
errorLine_ = errorLine;
errorColumn_ = errorColumn;
}
} // namespace hsql } // namespace hsql

View File

@ -4,31 +4,68 @@
#include "sql/SQLStatement.h" #include "sql/SQLStatement.h"
namespace hsql { namespace hsql {
/** // Represents the result of the SQLParser.
* Represents the result of the SQLParser. // If parsing was successful it contains a list of SQLStatement.
* If parsing was successful it contains a list of SQLStatement. class SQLParserResult {
*/ public:
class SQLParserResult { // Initialize with empty statement list.
public: SQLParserResult();
SQLParserResult(); // Initialize with a single statement.
SQLParserResult(SQLStatement* stmt); // Takes ownership of the statement.
virtual ~SQLParserResult(); SQLParserResult(SQLStatement* stmt);
void addStatement(SQLStatement* stmt); // Deletes all statements in the resul.
virtual ~SQLParserResult();
SQLStatement* getStatement(int id); // Returns true if parsing was successful.
bool isValid() const;
size_t size(); // Returns the number of statements in the result.
size_t size() const;
// public properties // Returns the error message, if an error occurred.
std::vector<SQLStatement*> statements; const char* errorMsg() const;
bool isValid;
const char* errorMsg; // Returns the line number of the occurrance of the error in the query.
int errorLine; int errorLine() const;
int errorColumn;
}; // Returns the column number of the occurrance of the error in the query.
int errorColumn() const;
// Gets the SQL statement with the given index.
const SQLStatement* getStatement(int index) const;
// Gets the non const SQL statement with the given index.
SQLStatement* getMutableStatement(int index);
// Adds a statement to the result list of statements.
// Takes ownership of the statement.
void addStatement(SQLStatement* stmt);
// Set whether parsing was successful.
void setIsValid(bool isValid);
// Set the details of the error, if available.
void setErrorDetails(const char* errorMsg, int errorLine, int errorColumn);
private:
// List of statements within the result.
std::vector<SQLStatement*> statements_;
// Flag indicating the parsing was successful.
bool isValid_;
// Error message, if an error occurred.
const char* errorMsg_;
// Line number of the occurrance of the error in the query.
int errorLine_;
// Column number of the occurrance of the error in the query.
int errorColumn_;
};
} // namespace hsql } // namespace hsql

File diff suppressed because it is too large Load Diff

View File

@ -48,7 +48,7 @@
extern int hsql_debug; extern int hsql_debug;
#endif #endif
/* "%code requires" blocks. */ /* "%code requires" blocks. */
#line 42 "bison_parser.y" /* yacc.c:1909 */ #line 40 "bison_parser.y" /* yacc.c:1909 */
// %code requires block // %code requires block
@ -209,7 +209,7 @@ extern int hsql_debug;
typedef union HSQL_STYPE HSQL_STYPE; typedef union HSQL_STYPE HSQL_STYPE;
union HSQL_STYPE union HSQL_STYPE
{ {
#line 101 "bison_parser.y" /* yacc.c:1909 */ #line 99 "bison_parser.y" /* yacc.c:1909 */
double fval; double fval;
int64_t ival; int64_t ival;

View File

@ -21,10 +21,8 @@ using namespace hsql;
int yyerror(YYLTYPE* llocp, SQLParserResult** result, yyscan_t scanner, const char *msg) { int yyerror(YYLTYPE* llocp, SQLParserResult** result, yyscan_t scanner, const char *msg) {
SQLParserResult* list = new SQLParserResult(); SQLParserResult* list = new SQLParserResult();
list->isValid = false; list->setIsValid(false);
list->errorMsg = strdup(msg); list->setErrorDetails(strdup(msg), llocp->first_line, llocp->first_column);
list->errorLine = llocp->first_line;
list->errorColumn = llocp->first_column;
*result = list; *result = list;
return 0; return 0;

View File

@ -3,60 +3,41 @@
#include "SQLStatement.h" #include "SQLStatement.h"
// Note: Implementations of constructors and destructors can be found in statements.cpp.
namespace hsql { namespace hsql {
/** // Represents definition of a table column
* Represents definition of a table column struct ColumnDefinition {
*/ enum DataType {
struct ColumnDefinition { TEXT,
enum DataType { INT,
TEXT, DOUBLE
INT,
DOUBLE
};
ColumnDefinition(char* name, DataType type) :
name(name),
type(type) {}
virtual ~ColumnDefinition() {
delete name;
}
char* name;
DataType type;
}; };
/** ColumnDefinition(char* name, DataType type);
* Represents SQL Create statements. virtual ~ColumnDefinition();
* Example: "CREATE TABLE students (name TEXT, student_number INTEGER, city TEXT, grade DOUBLE)"
*/
struct CreateStatement : SQLStatement {
enum CreateType {
kTable,
kTableFromTbl // Hyrise file format
};
CreateStatement(CreateType type) : char* name;
SQLStatement(kStmtCreate), DataType type;
type(type), };
ifNotExists(false),
filePath(NULL),
tableName(NULL),
columns(NULL) {};
virtual ~CreateStatement() {
delete columns;
delete filePath;
delete tableName;
}
CreateType type; // Represents SQL Create statements.
// Example: "CREATE TABLE students (name TEXT, student_number INTEGER, city TEXT, grade DOUBLE)"
bool ifNotExists; struct CreateStatement : SQLStatement {
const char* filePath; enum CreateType {
const char* tableName; kTable,
std::vector<ColumnDefinition*>* columns; kTableFromTbl // Hyrise file format
}; };
CreateStatement(CreateType type);
virtual ~CreateStatement();
CreateType type;
bool ifNotExists; // default: false
const char* filePath; // default: NULL
const char* tableName; // default: NULL
std::vector<ColumnDefinition*>* columns; // default: NULL
};
} // namespace hsql } // namespace hsql
#endif #endif

View File

@ -3,27 +3,18 @@
#include "SQLStatement.h" #include "SQLStatement.h"
// Note: Implementations of constructors and destructors can be found in statements.cpp.
namespace hsql { namespace hsql {
/** // Represents SQL Delete statements.
* Represents SQL Delete statements. // Example: "DELETE FROM students WHERE grade > 3.0"
* Example: "DELETE FROM students WHERE grade > 3.0" // Note: if (expr == NULL) => delete all rows (truncate)
* struct DeleteStatement : SQLStatement {
* Note: if (expr == NULL) => delete all rows (truncate) DeleteStatement();
*/ virtual ~DeleteStatement();
struct DeleteStatement : SQLStatement {
DeleteStatement() :
SQLStatement(kStmtDelete),
tableName(NULL),
expr(NULL) {};
virtual ~DeleteStatement() { char* tableName;
delete tableName; Expr* expr;
delete expr; };
}
char* tableName;
Expr* expr;
};
} // namespace hsql } // namespace hsql
#endif #endif

View File

@ -3,32 +3,25 @@
#include "SQLStatement.h" #include "SQLStatement.h"
// Note: Implementations of constructors and destructors can be found in statements.cpp.
namespace hsql { namespace hsql {
/** // Represents SQL Delete statements.
* Represents SQL Delete statements. // Example "DROP TABLE students;"
* Example "DROP TABLE students;" struct DropStatement : SQLStatement {
*/ enum EntityType {
struct DropStatement : SQLStatement { kTable,
enum EntityType { kSchema,
kTable, kIndex,
kSchema, kView,
kIndex, kPreparedStatement
kView,
kPreparedStatement
};
DropStatement(EntityType type) :
SQLStatement(kStmtDrop),
type(type),
name(NULL) {}
virtual ~DropStatement() {
delete name;
}
EntityType type;
const char* name;
}; };
DropStatement(EntityType type);
virtual ~DropStatement();
EntityType type;
const char* name;
};
} // namespace hsql } // namespace hsql
#endif #endif

View File

@ -4,24 +4,17 @@
#include "SQLStatement.h" #include "SQLStatement.h"
namespace hsql { namespace hsql {
/** /**
* Represents SQL Execute statements. * Represents SQL Execute statements.
* Example: "EXECUTE ins_prep(100, "test", 2.3);" * Example: "EXECUTE ins_prep(100, "test", 2.3);"
*/ */
struct ExecuteStatement : SQLStatement { struct ExecuteStatement : SQLStatement {
ExecuteStatement() : ExecuteStatement();
SQLStatement(kStmtExecute), virtual ~ExecuteStatement();
name(NULL),
parameters(NULL) {}
virtual ~ExecuteStatement() { const char* name;
delete name; std::vector<Expr*>* parameters;
delete parameters; };
}
const char* name;
std::vector<Expr*>* parameters;
};
} // namsepace hsql } // namsepace hsql
#endif #endif

View File

@ -5,98 +5,127 @@
namespace hsql { namespace hsql {
char* substr(const char* source, int from, int to) { Expr::Expr(ExprType type) :
int len = to-from; type(type),
char* copy = new char[len+1]; expr(NULL),
strncpy(copy, source+from, len); expr2(NULL),
copy[len] = '\0'; name(NULL),
return copy; table(NULL),
} alias(NULL) {};
Expr::~Expr() {
delete expr;
delete expr2;
delete name;
delete table;
}
Expr* Expr::makeOpUnary(OperatorType op, Expr* expr) {
Expr* e = new Expr(kExprOperator);
e->opType = op;
e->expr = expr;
e->expr2 = NULL;
return e;
}
Expr* Expr::makeOpBinary(Expr* expr1, OperatorType op, Expr* expr2) {
Expr* e = new Expr(kExprOperator);
e->opType = op;
e->opChar = 0;
e->expr = expr1;
e->expr2 = expr2;
return e;
}
Expr* Expr::makeOpBinary(Expr* expr1, char op, Expr* expr2) {
Expr* e = new Expr(kExprOperator);
e->opType = SIMPLE_OP;
e->opChar = op;
e->expr = expr1;
e->expr2 = expr2;
return e;
}
Expr* Expr::makeLiteral(int64_t val) {
Expr* e = new Expr(kExprLiteralInt);
e->ival = val;
return e;
}
Expr* Expr::makeLiteral(double value) {
Expr* e = new Expr(kExprLiteralFloat);
e->fval = value;
return e;
}
Expr* Expr::makeLiteral(char* string) {
Expr* e = new Expr(kExprLiteralString);
e->name = string;
return e;
}
Expr* Expr::makeColumnRef(char* name) {
Expr* e = new Expr(kExprColumnRef);
e->name = name;
return e;
}
Expr* Expr::makeColumnRef(char* table, char* name) {
Expr* e = new Expr(kExprColumnRef);
e->name = name;
e->table = table;
return e;
}
Expr* Expr::makeOpUnary(OperatorType op, Expr* expr) { Expr* Expr::makeFunctionRef(char* func_name, Expr* expr, bool distinct) {
Expr* e = new Expr(kExprOperator); Expr* e = new Expr(kExprFunctionRef);
e->op_type = op; e->name = func_name;
e->expr = expr; e->expr = expr;
e->expr2 = NULL; e->distinct = distinct;
return e; return e;
} }
Expr* Expr::makePlaceholder(int id) {
Expr* e = new Expr(kExprPlaceholder);
e->ival = id;
return e;
}
bool Expr::isType(ExprType e_type) {
return e_type == type;
}
Expr* Expr::makeOpBinary(Expr* expr1, OperatorType op, Expr* expr2) { bool Expr::isLiteral() {
Expr* e = new Expr(kExprOperator); return isType(kExprLiteralInt) || isType(kExprLiteralFloat) || isType(kExprLiteralString) || isType(kExprPlaceholder);
e->op_type = op; }
e->op_char = 0;
e->expr = expr1;
e->expr2 = expr2;
return e;
}
Expr* Expr::makeOpBinary(Expr* expr1, char op, Expr* expr2) { bool Expr::hasAlias() {
Expr* e = new Expr(kExprOperator); return alias != NULL;
e->op_type = SIMPLE_OP; }
e->op_char = op;
e->expr = expr1;
e->expr2 = expr2;
return e;
}
bool Expr::hasTable() {
return table != NULL;
}
char* Expr::getName() {
if (alias != NULL) return alias;
else return name;
}
Expr* Expr::makeLiteral(int64_t val) { bool Expr::isSimpleOp() {
Expr* e = new Expr(kExprLiteralInt); return opType == SIMPLE_OP;
e->ival = val; }
return e;
}
Expr* Expr::makeLiteral(double value) { bool Expr::isSimpleOp(char op) {
Expr* e = new Expr(kExprLiteralFloat); return isSimpleOp() && opChar == op;
e->fval = value; }
return e;
}
Expr* Expr::makeLiteral(char* string) {
Expr* e = new Expr(kExprLiteralString);
e->name = string;
return e;
}
Expr* Expr::makeColumnRef(char* name) {
Expr* e = new Expr(kExprColumnRef);
e->name = name;
return e;
}
Expr* Expr::makeColumnRef(char* table, char* name) {
Expr* e = new Expr(kExprColumnRef);
e->name = name;
e->table = table;
return e;
}
Expr* Expr::makeFunctionRef(char* func_name, Expr* expr, bool distinct) {
Expr* e = new Expr(kExprFunctionRef);
e->name = func_name;
e->expr = expr;
e->distinct = distinct;
return e;
}
Expr* Expr::makePlaceholder(int id) {
Expr* e = new Expr(kExprPlaceholder);
e->ival = id;
return e;
}
Expr::~Expr() {
delete expr;
delete expr2;
delete name;
delete table;
}
char* substr(const char* source, int from, int to) {
int len = to - from;
char* copy = new char[len + 1];
strncpy(copy, source + from, len);
copy[len] = '\0';
return copy;
}
} // namespace hsql } // namespace hsql

View File

@ -6,129 +6,112 @@
namespace hsql { namespace hsql {
// Helper function // Helper function used by the lexer.
char* substr(const char* source, int from, int to); // TODO: move to more appropriate place.
char* substr(const char* source, int from, int to);
enum ExprType {
kExprLiteralFloat,
kExprLiteralString,
kExprLiteralInt,
kExprStar,
kExprPlaceholder,
kExprColumnRef,
kExprFunctionRef,
kExprOperator
};
typedef struct Expr Expr;
typedef enum { // Represents SQL expressions (i.e. literals, operators, column_refs).
kExprLiteralFloat, // TODO: When destructing a placeholder expression, we might need to alter the placeholder_list.
kExprLiteralString, struct Expr {
kExprLiteralInt, // Operator types. These are important for expressions of type kExprOperator.
kExprStar, // Trivial types are those that can be described by a single character e.g:
kExprPlaceholder, // + - * / < > = %
kExprColumnRef, // Non-trivial are: <> <= >= LIKE ISNULL NOT
kExprFunctionRef, enum OperatorType {
kExprOperator SIMPLE_OP,
} ExprType;
// Binary operators.
NOT_EQUALS,
LESS_EQ,
GREATER_EQ,
LIKE,
NOT_LIKE,
AND,
OR,
typedef struct Expr Expr; // Unary operators.
NOT,
/** UMINUS,
* Represents SQL expressions (i.e. literals, operators, column_refs) ISNULL
*
* TODO: When destructing a placeholder expression, we might need to alter the placeholder_list
*/
struct Expr {
/**
* Operator types. These are important for expressions of type kExprOperator
* Trivial types are those that can be described by a single character e.g:
* + - * / < > = %
* Non-trivial are:
* <> <= >= LIKE ISNULL NOT
*/
typedef enum {
SIMPLE_OP,
// Binary
NOT_EQUALS,
LESS_EQ,
GREATER_EQ,
LIKE,
NOT_LIKE,
AND,
OR,
// Unary
NOT,
UMINUS,
ISNULL
} OperatorType;
Expr(ExprType type) :
type(type),
expr(NULL),
expr2(NULL),
name(NULL),
table(NULL),
alias(NULL) {};
// Interesting side-effect:
// Making the destructor virtual used to cause segmentation faults
~Expr();
ExprType type;
Expr* expr;
Expr* expr2;
char* name;
char* table;
char* alias;
float fval;
int64_t ival;
int64_t ival2;
OperatorType op_type;
char op_char;
bool distinct;
/**
* Convenience accessor methods
*/
inline bool isType(ExprType e_type) {
return e_type == type;
}
inline bool isLiteral() {
return isType(kExprLiteralInt) || isType(kExprLiteralFloat) || isType(kExprLiteralString) || isType(kExprPlaceholder);
}
inline bool hasAlias() {
return alias != NULL;
}
inline bool hasTable() {
return table != NULL;
}
inline char* getName() {
if (alias != NULL) return alias;
else return name;
}
inline bool isSimpleOp() {
return op_type == SIMPLE_OP;
}
inline bool isSimpleOp(char op) {
return isSimpleOp() && op_char == op;
}
/**
* Static expression constructors
*/
static Expr* makeOpUnary(OperatorType op, Expr* expr);
static Expr* makeOpBinary(Expr* expr1, char op, Expr* expr2);
static Expr* makeOpBinary(Expr* expr1, OperatorType op, Expr* expr2);
static Expr* makeLiteral(int64_t val);
static Expr* makeLiteral(double val);
static Expr* makeLiteral(char* val);
static Expr* makeColumnRef(char* name);
static Expr* makeColumnRef(char* table, char* name);
static Expr* makeFunctionRef(char* func_name, Expr* expr, bool distinct);
static Expr* makePlaceholder(int id);
}; };
Expr(ExprType type);
// Interesting side-effect:
// Making the destructor virtual used to cause segmentation faults.
// TODO: inspect.
~Expr();
ExprType type;
Expr* expr;
Expr* expr2;
char* name;
char* table;
char* alias;
float fval;
int64_t ival;
int64_t ival2;
OperatorType opType;
char opChar;
bool distinct;
// Convenience accessor methods.
bool isType(ExprType e_type);
bool isLiteral();
bool hasAlias();
bool hasTable();
char* getName();
bool isSimpleOp();
bool isSimpleOp(char op);
// Static constructors.
static Expr* makeOpUnary(OperatorType op, Expr* expr);
static Expr* makeOpBinary(Expr* expr1, char op, Expr* expr2);
static Expr* makeOpBinary(Expr* expr1, OperatorType op, Expr* expr2);
static Expr* makeLiteral(int64_t val);
static Expr* makeLiteral(double val);
static Expr* makeLiteral(char* val);
static Expr* makeColumnRef(char* name);
static Expr* makeColumnRef(char* table, char* name);
static Expr* makeFunctionRef(char* func_name, Expr* expr, bool distinct);
static Expr* makePlaceholder(int id);
};
// Zero initializes an Expr object and assigns it to a space in the heap // Zero initializes an Expr object and assigns it to a space in the heap
// For Hyrise we still had to put in the explicit NULL constructor // For Hyrise we still had to put in the explicit NULL constructor
// http://www.ex-parrot.com/~chris/random/initialise.html // http://www.ex-parrot.com/~chris/random/initialise.html

View File

@ -4,31 +4,23 @@
#include "SQLStatement.h" #include "SQLStatement.h"
namespace hsql { namespace hsql {
/** /**
* Represents SQL Import statements. * Represents SQL Import statements.
*/ */
struct ImportStatement : SQLStatement { struct ImportStatement : SQLStatement {
enum ImportType { enum ImportType {
kImportCSV, kImportCSV,
kImportTbl, // Hyrise file format kImportTbl, // Hyrise file format
};
ImportStatement(ImportType type) :
SQLStatement(kStmtImport),
type(type),
filePath(NULL),
tableName(NULL) {};
virtual ~ImportStatement() {
delete filePath;
delete tableName;
}
ImportType type;
const char* filePath;
const char* tableName;
}; };
ImportStatement(ImportType type);
virtual ~ImportStatement();
ImportType type;
const char* filePath;
const char* tableName;
};
} // namespace hsql } // namespace hsql

View File

@ -5,37 +5,25 @@
#include "SelectStatement.h" #include "SelectStatement.h"
namespace hsql { namespace hsql {
/** /**
* Represents SQL Insert statements. * Represents SQL Insert statements.
* Example: "INSERT INTO students VALUES ('Max', 1112233, 'Musterhausen', 2.3)" * Example: "INSERT INTO students VALUES ('Max', 1112233, 'Musterhausen', 2.3)"
*/ */
struct InsertStatement : SQLStatement { struct InsertStatement : SQLStatement {
enum InsertType { enum InsertType {
kInsertValues, kInsertValues,
kInsertSelect kInsertSelect
};
InsertStatement(InsertType type) :
SQLStatement(kStmtInsert),
type(type),
tableName(NULL),
columns(NULL),
values(NULL),
select(NULL) {}
virtual ~InsertStatement() {
delete tableName;
delete columns;
delete values;
delete select;
}
InsertType type;
const char* tableName;
std::vector<char*>* columns;
std::vector<Expr*>* values;
SelectStatement* select;
}; };
InsertStatement(InsertType type);
virtual ~InsertStatement();
InsertType type;
const char* tableName;
std::vector<char*>* columns;
std::vector<Expr*>* values;
SelectStatement* select;
};
} // namsepace hsql } // namsepace hsql
#endif #endif

View File

@ -7,43 +7,26 @@
#include <algorithm> #include <algorithm>
namespace hsql { namespace hsql {
/**
* Represents SQL Prepare statements.
* Example: "PREPARE ins_prep: SELECT * FROM t1 WHERE c1 = ? AND c2 = ?"
*/
struct PrepareStatement : SQLStatement {
PrepareStatement();
virtual ~PrepareStatement();
/** /**
* Represents SQL Prepare statements. * When setting the placeholders we need to make sure that they are in the correct order.
* Example: "PREPARE ins_prep: SELECT * FROM t1 WHERE c1 = ? AND c2 = ?" * To ensure that, during parsing we store the character position use that to sort the list here.
*
* @param vector of placeholders that the parser found
*/ */
struct PrepareStatement : SQLStatement { void setPlaceholders(std::vector<void*> ph);
PrepareStatement() :
SQLStatement(kStmtPrepare),
name(NULL),
query(NULL) {}
virtual ~PrepareStatement() { const char* name;
delete query; SQLParserResult* query;
delete name; std::vector<Expr*> placeholders;
} };
/**
* When setting the placeholders we need to make sure that they are in the correct order.
* To ensure that, during parsing we store the character position use that to sort the list here.
*
* @param vector of placeholders that the parser found
*/
void setPlaceholders(std::vector<void*> ph) {
for (void* e : ph) {
if (e != NULL)
placeholders.push_back((Expr*) e);
}
// Sort by col-id
std::sort(placeholders.begin(), placeholders.end(), [](Expr* i, Expr* j) -> bool { return (i->ival < j->ival); });
// Set the placeholder id on the Expr. This replaces the previously stored column id
for (uintmax_t i = 0; i < placeholders.size(); ++i) placeholders[i]->ival = i;
}
const char* name;
SQLParserResult* query;
std::vector<Expr*> placeholders;
};
} // namsepace hsql } // namsepace hsql
#endif #endif

View File

@ -5,38 +5,35 @@
#include <vector> #include <vector>
namespace hsql { namespace hsql {
typedef enum { enum StatementType {
kStmtError, // unused kStmtError, // unused
kStmtSelect, kStmtSelect,
kStmtImport, kStmtImport,
kStmtInsert, kStmtInsert,
kStmtUpdate, kStmtUpdate,
kStmtDelete, kStmtDelete,
kStmtCreate, kStmtCreate,
kStmtDrop, kStmtDrop,
kStmtPrepare, kStmtPrepare,
kStmtExecute, kStmtExecute,
kStmtExport, kStmtExport,
kStmtRename, kStmtRename,
kStmtAlter kStmtAlter
} StatementType; };
/** /**
* Base struct for every SQL statement * Base struct for every SQL statement
*/ */
struct SQLStatement { struct SQLStatement {
SQLStatement(StatementType type) : SQLStatement(StatementType type);
_type(type) {};
virtual ~SQLStatement() {} virtual ~SQLStatement();
virtual StatementType type() { virtual StatementType type() const;
return _type;
}
private: private:
StatementType _type; StatementType type_;
}; };
} // namespace hsql } // namespace hsql
#endif // __SQLSTATEMENT_H__ #endif // __SQLSTATEMENT_H__

View File

@ -6,95 +6,66 @@
#include "Table.h" #include "Table.h"
namespace hsql { namespace hsql {
typedef enum { enum OrderType {
kOrderAsc, kOrderAsc,
kOrderDesc kOrderDesc
} OrderType; };
/** /**
* Description of the order by clause within a select statement * Description of the order by clause within a select statement
* TODO: hold multiple expressions to be sorted by * TODO: hold multiple expressions to be sorted by
*/ */
struct OrderDescription { struct OrderDescription {
OrderDescription(OrderType type, Expr* expr) : OrderDescription(OrderType type, Expr* expr);
type(type), virtual ~OrderDescription();
expr(expr) {}
virtual ~OrderDescription() { OrderType type;
delete expr; Expr* expr;
} };
OrderType type; const int64_t kNoLimit = -1;
Expr* expr; const int64_t kNoOffset = -1;
};
const int64_t kNoLimit = -1; /**
const int64_t kNoOffset = -1; * Description of the limit clause within a select statement
*/
struct LimitDescription {
LimitDescription(int64_t limit, int64_t offset);
/** int64_t limit;
* Description of the limit clause within a select statement int64_t offset;
*/ };
struct LimitDescription {
LimitDescription(int64_t limit, int64_t offset) :
limit(limit),
offset(offset) {}
int64_t limit; /**
int64_t offset; * Description of the group-by clause within a select statement
}; */
struct GroupByDescription {
GroupByDescription();
// TODO: make virtual
~GroupByDescription();
/** std::vector<Expr*>* columns;
* Description of the group-by clause within a select statement Expr* having;
*/ };
struct GroupByDescription {
GroupByDescription() :
columns(NULL),
having(NULL) {}
~GroupByDescription() { /**
delete columns; * Representation of a full SQL select statement.
delete having; * TODO: add union_order and union_limit
} */
struct SelectStatement : SQLStatement {
SelectStatement();
virtual ~SelectStatement();
std::vector<Expr*>* columns; TableRef* fromTable;
Expr* having; bool selectDistinct;
}; std::vector<Expr*>* selectList;
Expr* whereClause;
GroupByDescription* groupBy;
/** SelectStatement* unionSelect;
* Representation of a full SQL select statement. OrderDescription* order;
* TODO: add union_order and union_limit LimitDescription* limit;
*/ };
struct SelectStatement : SQLStatement {
SelectStatement() :
SQLStatement(kStmtSelect),
fromTable(NULL),
selectDistinct(false),
selectList(NULL),
whereClause(NULL),
groupBy(NULL),
unionSelect(NULL),
order(NULL),
limit(NULL) {};
virtual ~SelectStatement() {
delete fromTable;
delete selectList;
delete whereClause;
delete groupBy;
delete order;
delete limit;
}
TableRef* fromTable;
bool selectDistinct;
std::vector<Expr*>* selectList;
Expr* whereClause;
GroupByDescription* groupBy;
SelectStatement* unionSelect;
OrderDescription* order;
LimitDescription* limit;
};
} // namespace hsql } // namespace hsql
#endif #endif

View File

@ -7,101 +7,59 @@
namespace hsql { namespace hsql {
struct SelectStatement; struct SelectStatement;
struct JoinDefinition; struct JoinDefinition;
struct TableRef; struct TableRef;
// Possible table reference types.
enum TableRefType {
kTableName,
kTableSelect,
kTableJoin,
kTableCrossProduct
};
/** // Holds reference to tables. Can be either table names or a select statement.
* @enum TableRefType struct TableRef {
* Types table references TableRef(TableRefType type);
*/ virtual ~TableRef();
typedef enum {
kTableName,
kTableSelect,
kTableJoin,
kTableCrossProduct
} TableRefType;
TableRefType type;
/** char* schema;
* @struct TableRef char* name;
* @brief Holds reference to tables. Can be either table names or a select statement. char* alias;
*/
struct TableRef {
TableRef(TableRefType type) :
type(type),
schema(NULL),
name(NULL),
alias(NULL),
select(NULL),
list(NULL),
join(NULL) {}
virtual ~TableRef(); SelectStatement* select;
std::vector<TableRef*>* list;
JoinDefinition* join;
TableRefType type; // Returns true if a schema is set.
bool hasSchema();
char* schema; // Returns the alias, if it is set. Otherwise the name.
char* name; char* getName();
char* alias; };
SelectStatement* select; // Possible types of joins.
std::vector<TableRef*>* list; enum JoinType {
JoinDefinition* join; kJoinInner,
kJoinOuter,
kJoinLeft,
kJoinRight,
};
// Definition of a join construct.
struct JoinDefinition {
JoinDefinition();
virtual ~JoinDefinition();
/** TableRef* left;
* Convenience accessor methods TableRef* right;
*/ Expr* condition;
inline bool hasSchema() {
return schema != NULL;
}
inline char* getName() {
if (alias != NULL) return alias;
else return name;
}
};
/**
* @enum JoinType
* Types of joins
*/
typedef enum {
kJoinInner,
kJoinOuter,
kJoinLeft,
kJoinRight,
} JoinType;
/**
* @struct JoinDefinition
* @brief Definition of a join table
*/
struct JoinDefinition {
JoinDefinition() :
left(NULL),
right(NULL),
condition(NULL),
type(kJoinInner) {}
virtual ~JoinDefinition() {
delete left;
delete right;
delete condition;
}
TableRef* left;
TableRef* right;
Expr* condition;
JoinType type;
};
JoinType type;
};
} // namespace hsql } // namespace hsql
#endif #endif

View File

@ -4,35 +4,26 @@
#include "SQLStatement.h" #include "SQLStatement.h"
namespace hsql { namespace hsql {
/** /**
* Represents "column = value" expressions * Represents "column = value" expressions
*/ */
struct UpdateClause { struct UpdateClause {
char* column; char* column;
Expr* value; Expr* value;
}; };
/** /**
* Represents SQL Update statements. * Represents SQL Update statements.
*/ */
struct UpdateStatement : SQLStatement { struct UpdateStatement : SQLStatement {
UpdateStatement() : UpdateStatement();
SQLStatement(kStmtUpdate), virtual ~UpdateStatement();
table(NULL),
updates(NULL),
where(NULL) {}
virtual ~UpdateStatement() { // TODO: switch to char* instead of TableRef
delete table; TableRef* table;
delete updates; std::vector<UpdateClause*>* updates;
delete where; Expr* where;
} };
// TODO: switch to char* instead of TableRef
TableRef* table;
std::vector<UpdateClause*>* updates;
Expr* where;
};
} // namsepace hsql } // namsepace hsql
#endif #endif

View File

@ -1,16 +0,0 @@
#include "Table.h"
#include "SelectStatement.h"
namespace hsql {
TableRef::~TableRef() {
delete name;
delete alias;
delete select;
delete list;
}
} // namespace hsql

222
src/sql/statements.cpp Normal file
View File

@ -0,0 +1,222 @@
#include "statements.h"
namespace hsql {
// SQLStatement
SQLStatement::SQLStatement(StatementType type) :
type_(type) {};
SQLStatement::~SQLStatement() {}
StatementType SQLStatement::type() const {
return type_;
}
// ColumnDefinition
ColumnDefinition::ColumnDefinition(char* name, DataType type) :
name(name),
type(type) {};
ColumnDefinition::~ColumnDefinition() {
delete name;
}
// CreateStatemnet
CreateStatement::CreateStatement(CreateType type) :
SQLStatement(kStmtCreate),
type(type),
ifNotExists(false),
filePath(NULL),
tableName(NULL),
columns(NULL) {};
CreateStatement::~CreateStatement() {
delete columns;
delete filePath;
delete tableName;
}
// DeleteStatement
DeleteStatement::DeleteStatement() :
SQLStatement(kStmtDelete),
tableName(NULL),
expr(NULL) {};
DeleteStatement::~DeleteStatement() {
delete tableName;
delete expr;
}
// DropStatament
DropStatement::DropStatement(EntityType type) :
SQLStatement(kStmtDrop),
type(type),
name(NULL) {}
DropStatement::~DropStatement() {
delete name;
}
// ExecuteStatement
ExecuteStatement::ExecuteStatement() :
SQLStatement(kStmtExecute),
name(NULL),
parameters(NULL) {}
ExecuteStatement::~ExecuteStatement() {
delete name;
delete parameters;
}
// ImportStatement
ImportStatement::ImportStatement(ImportType type) :
SQLStatement(kStmtImport),
type(type),
filePath(NULL),
tableName(NULL) {};
ImportStatement::~ImportStatement() {
delete filePath;
delete tableName;
}
// InsertStatement
InsertStatement::InsertStatement(InsertType type) :
SQLStatement(kStmtInsert),
type(type),
tableName(NULL),
columns(NULL),
values(NULL),
select(NULL) {}
InsertStatement::~InsertStatement() {
delete tableName;
delete columns;
delete values;
delete select;
}
// PrepareStatement
PrepareStatement::PrepareStatement() :
SQLStatement(kStmtPrepare),
name(NULL),
query(NULL) {}
PrepareStatement::~PrepareStatement() {
delete query;
delete name;
}
void PrepareStatement::setPlaceholders(std::vector<void*> ph) {
for (void* e : ph) {
if (e != NULL)
placeholders.push_back((Expr*) e);
}
// Sort by col-id
std::sort(placeholders.begin(), placeholders.end(), [](Expr * i, Expr * j) -> bool { return (i->ival < j->ival); });
// Set the placeholder id on the Expr. This replaces the previously stored column id
for (uintmax_t i = 0; i < placeholders.size(); ++i) placeholders[i]->ival = i;
}
// SelectStatement.h
// OrderDescription
OrderDescription::OrderDescription(OrderType type, Expr* expr) :
type(type),
expr(expr) {}
OrderDescription::~OrderDescription() {
delete expr;
}
// LimitDescription
LimitDescription::LimitDescription(int64_t limit, int64_t offset) :
limit(limit),
offset(offset) {}
// GroypByDescription
GroupByDescription::GroupByDescription() :
columns(NULL),
having(NULL) {}
GroupByDescription::~GroupByDescription() {
delete columns;
delete having;
}
// SelectStatement
SelectStatement::SelectStatement() :
SQLStatement(kStmtSelect),
fromTable(NULL),
selectDistinct(false),
selectList(NULL),
whereClause(NULL),
groupBy(NULL),
unionSelect(NULL),
order(NULL),
limit(NULL) {};
SelectStatement::~SelectStatement() {
delete fromTable;
delete selectList;
delete whereClause;
delete groupBy;
delete order;
delete limit;
}
// UpdateStatement
UpdateStatement::UpdateStatement() :
SQLStatement(kStmtUpdate),
table(NULL),
updates(NULL),
where(NULL) {}
UpdateStatement::~UpdateStatement() {
delete table;
delete updates;
delete where;
}
// TableRef
TableRef::TableRef(TableRefType type) :
type(type),
schema(NULL),
name(NULL),
alias(NULL),
select(NULL),
list(NULL),
join(NULL) {}
TableRef::~TableRef() {
delete name;
delete alias;
delete select;
delete list;
}
bool TableRef::hasSchema() {
return schema != NULL;
}
char* TableRef::getName() {
if (alias != NULL) return alias;
else return name;
}
// JoinDefinition
JoinDefinition::JoinDefinition() :
left(NULL),
right(NULL),
condition(NULL),
type(kJoinInner) {}
JoinDefinition::~JoinDefinition() {
delete left;
delete right;
delete condition;
}
} // namespace hsql

View File

@ -5,204 +5,204 @@
namespace hsql { namespace hsql {
void printOperatorExpression(Expr* expr, uintmax_t numIndent); void printOperatorExpression(Expr* expr, uintmax_t numIndent);
std::string indent(uintmax_t numIndent) { std::string indent(uintmax_t numIndent) {
return std::string(numIndent, '\t'); return std::string(numIndent, '\t');
}
void inprint(int64_t val, uintmax_t numIndent) {
printf("%s%lld \n", indent(numIndent).c_str(), val);
}
void inprint(float val, uintmax_t numIndent) {
printf("%s%f\n", indent(numIndent).c_str(), val);
}
void inprint(const char* val, uintmax_t numIndent) {
printf("%s%s\n", indent(numIndent).c_str(), val);
}
void inprint(const char* val, const char* val2, uintmax_t numIndent) {
printf("%s%s->%s\n", indent(numIndent).c_str(), val, val2);
}
void inprintC(char val, uintmax_t numIndent) {
printf("%s%c\n", indent(numIndent).c_str(), val);
}
void inprintU(uint64_t val, uintmax_t numIndent) {
printf("%s%llu\n", indent(numIndent).c_str(), val);
}
void printTableRefInfo(TableRef* table, uintmax_t numIndent) {
switch (table->type) {
case kTableName:
inprint(table->name, numIndent);
break;
case kTableSelect:
printSelectStatementInfo(table->select, numIndent);
break;
case kTableJoin:
inprint("Join Table", numIndent);
inprint("Left", numIndent + 1);
printTableRefInfo(table->join->left, numIndent + 2);
inprint("Right", numIndent + 1);
printTableRefInfo(table->join->right, numIndent + 2);
inprint("Join Condition", numIndent + 1);
printExpression(table->join->condition, numIndent + 2);
break;
case kTableCrossProduct:
for (TableRef* tbl : *table->list) printTableRefInfo(tbl, numIndent);
break;
} }
void inprint(int64_t val, uintmax_t numIndent) { if (table->alias != NULL) {
printf("%s%lld \n", indent(numIndent).c_str(), val); inprint("Alias", numIndent + 1);
inprint(table->alias, numIndent + 2);
} }
void inprint(float val, uintmax_t numIndent) { }
printf("%s%f\n", indent(numIndent).c_str(), val);
} void printOperatorExpression(Expr* expr, uintmax_t numIndent) {
void inprint(const char* val, uintmax_t numIndent) { if (expr == NULL) {
printf("%s%s\n", indent(numIndent).c_str(), val); inprint("null", numIndent);
} return;
void inprint(const char* val, const char* val2, uintmax_t numIndent) {
printf("%s%s->%s\n", indent(numIndent).c_str(), val, val2);
}
void inprintC(char val, uintmax_t numIndent) {
printf("%s%c\n", indent(numIndent).c_str(), val);
}
void inprintU(uint64_t val, uintmax_t numIndent) {
printf("%s%llu\n", indent(numIndent).c_str(), val);
} }
void printTableRefInfo(TableRef* table, uintmax_t numIndent) { switch (expr->opType) {
switch (table->type) { case Expr::SIMPLE_OP:
case kTableName: inprintC(expr->opChar, numIndent);
inprint(table->name, numIndent); break;
break; case Expr::AND:
case kTableSelect: inprint("AND", numIndent);
printSelectStatementInfo(table->select, numIndent); break;
break; case Expr::OR:
case kTableJoin: inprint("OR", numIndent);
inprint("Join Table", numIndent); break;
inprint("Left", numIndent+1); case Expr::NOT:
printTableRefInfo(table->join->left, numIndent+2); inprint("NOT", numIndent);
inprint("Right", numIndent+1); break;
printTableRefInfo(table->join->right, numIndent+2); default:
inprint("Join Condition", numIndent+1); inprintU(expr->opType, numIndent);
printExpression(table->join->condition, numIndent+2); break;
break;
case kTableCrossProduct:
for (TableRef* tbl : *table->list) printTableRefInfo(tbl, numIndent);
break;
}
if (table->alias != NULL) {
inprint("Alias", numIndent+1);
inprint(table->alias, numIndent+2);
}
} }
printExpression(expr->expr, numIndent + 1);
if (expr->expr2 != NULL) printExpression(expr->expr2, numIndent + 1);
}
void printOperatorExpression(Expr* expr, uintmax_t numIndent) { void printExpression(Expr* expr, uintmax_t numIndent) {
if (expr == NULL) { switch (expr->type) {
inprint("null", numIndent); case kExprStar:
return; inprint("*", numIndent);
} break;
case kExprColumnRef:
switch (expr->op_type) { inprint(expr->name, numIndent);
case Expr::SIMPLE_OP: break;
inprintC(expr->op_char, numIndent); // case kExprTableColumnRef: inprint(expr->table, expr->name, numIndent); break;
break; case kExprLiteralFloat:
case Expr::AND: inprint(expr->fval, numIndent);
inprint("AND", numIndent); break;
break; case kExprLiteralInt:
case Expr::OR: inprint(expr->ival, numIndent);
inprint("OR", numIndent); break;
break; case kExprLiteralString:
case Expr::NOT: inprint(expr->name, numIndent);
inprint("NOT", numIndent); break;
break; case kExprFunctionRef:
default: inprint(expr->name, numIndent);
inprintU(expr->op_type, numIndent); inprint(expr->expr->name, numIndent + 1);
break; break;
} case kExprOperator:
printExpression(expr->expr, numIndent+1); printOperatorExpression(expr, numIndent);
if (expr->expr2 != NULL) printExpression(expr->expr2, numIndent+1); break;
default:
fprintf(stderr, "Unrecognized expression type %d\n", expr->type);
return;
} }
if (expr->alias != NULL) {
void printExpression(Expr* expr, uintmax_t numIndent) { inprint("Alias", numIndent + 1);
switch (expr->type) { inprint(expr->alias, numIndent + 2);
case kExprStar:
inprint("*", numIndent);
break;
case kExprColumnRef:
inprint(expr->name, numIndent);
break;
// case kExprTableColumnRef: inprint(expr->table, expr->name, numIndent); break;
case kExprLiteralFloat:
inprint(expr->fval, numIndent);
break;
case kExprLiteralInt:
inprint(expr->ival, numIndent);
break;
case kExprLiteralString:
inprint(expr->name, numIndent);
break;
case kExprFunctionRef:
inprint(expr->name, numIndent);
inprint(expr->expr->name, numIndent+1);
break;
case kExprOperator:
printOperatorExpression(expr, numIndent);
break;
default:
fprintf(stderr, "Unrecognized expression type %d\n", expr->type);
return;
}
if (expr->alias != NULL) {
inprint("Alias", numIndent+1);
inprint(expr->alias, numIndent+2);
}
} }
}
void printSelectStatementInfo(SelectStatement* stmt, uintmax_t numIndent) { void printSelectStatementInfo(SelectStatement* stmt, uintmax_t numIndent) {
inprint("SelectStatement", numIndent); inprint("SelectStatement", numIndent);
inprint("Fields:", numIndent+1); inprint("Fields:", numIndent + 1);
for (Expr* expr : *stmt->selectList) printExpression(expr, numIndent+2); for (Expr* expr : *stmt->selectList) printExpression(expr, numIndent + 2);
inprint("Sources:", numIndent+1); inprint("Sources:", numIndent + 1);
printTableRefInfo(stmt->fromTable, numIndent+2); printTableRefInfo(stmt->fromTable, numIndent + 2);
if (stmt->whereClause != NULL) { if (stmt->whereClause != NULL) {
inprint("Search Conditions:", numIndent+1); inprint("Search Conditions:", numIndent + 1);
printExpression(stmt->whereClause, numIndent+2); printExpression(stmt->whereClause, numIndent + 2);
}
if (stmt->unionSelect != NULL) {
inprint("Union:", numIndent+1);
printSelectStatementInfo(stmt->unionSelect, numIndent+2);
}
if (stmt->order != NULL) {
inprint("OrderBy:", numIndent+1);
printExpression(stmt->order->expr, numIndent+2);
if (stmt->order->type == kOrderAsc) inprint("ascending", numIndent+2);
else inprint("descending", numIndent+2);
}
if (stmt->limit != NULL) {
inprint("Limit:", numIndent+1);
inprint(stmt->limit->limit, numIndent+2);
}
} }
if (stmt->unionSelect != NULL) {
void printImportStatementInfo(ImportStatement* stmt, uintmax_t numIndent) { inprint("Union:", numIndent + 1);
inprint("ImportStatment", numIndent); printSelectStatementInfo(stmt->unionSelect, numIndent + 2);
inprint(stmt->filePath, numIndent+1);
inprint(stmt->tableName, numIndent+1);
} }
void printCreateStatementInfo(CreateStatement* stmt, uintmax_t numIndent) { if (stmt->order != NULL) {
inprint("CreateStatment", numIndent); inprint("OrderBy:", numIndent + 1);
inprint(stmt->tableName, numIndent+1); printExpression(stmt->order->expr, numIndent + 2);
inprint(stmt->filePath, numIndent+1); if (stmt->order->type == kOrderAsc) inprint("ascending", numIndent + 2);
else inprint("descending", numIndent + 2);
} }
void printInsertStatementInfo(InsertStatement* stmt, uintmax_t numIndent) { if (stmt->limit != NULL) {
inprint("InsertStatment", numIndent); inprint("Limit:", numIndent + 1);
inprint(stmt->tableName, numIndent+1); inprint(stmt->limit->limit, numIndent + 2);
if (stmt->columns != NULL) {
inprint("Columns", numIndent+1);
for (char* col_name : *stmt->columns) {
inprint(col_name, numIndent+2);
}
}
switch (stmt->type) {
case InsertStatement::kInsertValues:
inprint("Values", numIndent+1);
for (Expr* expr : *stmt->values) {
printExpression(expr, numIndent+2);
}
break;
case InsertStatement::kInsertSelect:
printSelectStatementInfo(stmt->select, numIndent+1);
break;
}
} }
}
void printStatementInfo(SQLStatement* stmt) {
switch (stmt->type()) {
case kStmtSelect: void printImportStatementInfo(ImportStatement* stmt, uintmax_t numIndent) {
printSelectStatementInfo((SelectStatement*) stmt, 0); inprint("ImportStatment", numIndent);
break; inprint(stmt->filePath, numIndent + 1);
case kStmtInsert: inprint(stmt->tableName, numIndent + 1);
printInsertStatementInfo((InsertStatement*) stmt, 0); }
break;
case kStmtCreate: void printCreateStatementInfo(CreateStatement* stmt, uintmax_t numIndent) {
printCreateStatementInfo((CreateStatement*) stmt, 0); inprint("CreateStatment", numIndent);
break; inprint(stmt->tableName, numIndent + 1);
case kStmtImport: inprint(stmt->filePath, numIndent + 1);
printImportStatementInfo((ImportStatement*) stmt, 0); }
break;
default: void printInsertStatementInfo(InsertStatement* stmt, uintmax_t numIndent) {
break; inprint("InsertStatment", numIndent);
} inprint(stmt->tableName, numIndent + 1);
if (stmt->columns != NULL) {
inprint("Columns", numIndent + 1);
for (char* col_name : *stmt->columns) {
inprint(col_name, numIndent + 2);
}
} }
switch (stmt->type) {
case InsertStatement::kInsertValues:
inprint("Values", numIndent + 1);
for (Expr* expr : *stmt->values) {
printExpression(expr, numIndent + 2);
}
break;
case InsertStatement::kInsertSelect:
printSelectStatementInfo(stmt->select, numIndent + 1);
break;
}
}
void printStatementInfo(SQLStatement* stmt) {
switch (stmt->type()) {
case kStmtSelect:
printSelectStatementInfo((SelectStatement*) stmt, 0);
break;
case kStmtInsert:
printInsertStatementInfo((InsertStatement*) stmt, 0);
break;
case kStmtCreate:
printCreateStatementInfo((CreateStatement*) stmt, 0);
break;
case kStmtImport:
printImportStatementInfo((ImportStatement*) stmt, 0);
break;
default:
break;
}
}
} // namespace hsql } // namespace hsql

View File

@ -5,12 +5,12 @@
namespace hsql { namespace hsql {
void printStatementInfo(SQLStatement* stmt); void printStatementInfo(SQLStatement* stmt);
void printSelectStatementInfo(SelectStatement* stmt, uintmax_t num_indent); void printSelectStatementInfo(SelectStatement* stmt, uintmax_t num_indent);
void printImportStatementInfo(ImportStatement* stmt, uintmax_t num_indent); void printImportStatementInfo(ImportStatement* stmt, uintmax_t num_indent);
void printInsertStatementInfo(InsertStatement* stmt, uintmax_t num_indent); void printInsertStatementInfo(InsertStatement* stmt, uintmax_t num_indent);
void printCreateStatementInfo(CreateStatement* stmt, uintmax_t num_indent); void printCreateStatementInfo(CreateStatement* stmt, uintmax_t num_indent);
void printExpression(Expr* expr, uintmax_t num_indent); void printExpression(Expr* expr, uintmax_t num_indent);
} // namespace hsql } // namespace hsql

View File

@ -3,20 +3,20 @@
#define TEST_PARSE_SQL_QUERY(query, outputVar, numStatements) \ #define TEST_PARSE_SQL_QUERY(query, outputVar, numStatements) \
SQLParserResult* outputVar = SQLParser::parseSQLString(query); \ const SQLParserResult* outputVar = SQLParser::parseSQLString(query); \
ASSERT(outputVar->isValid); \ ASSERT(outputVar->isValid()); \
ASSERT_EQ(outputVar->size(), numStatements); ASSERT_EQ(outputVar->size(), numStatements);
#define TEST_PARSE_SINGLE_SQL(query, stmtType, stmtClass, outputVar) \ #define TEST_PARSE_SINGLE_SQL(query, stmtType, stmtClass, outputVar) \
TEST_PARSE_SQL_QUERY(query, stmt_list, 1); \ TEST_PARSE_SQL_QUERY(query, stmt_list, 1); \
ASSERT_EQ(stmt_list->getStatement(0)->type(), stmtType); \ ASSERT_EQ(stmt_list->getStatement(0)->type(), stmtType); \
stmtClass* outputVar = (stmtClass*) stmt_list->getStatement(0); const stmtClass* outputVar = (const stmtClass*) stmt_list->getStatement(0);
#define TEST_CAST_STMT(stmt_list, stmt_index, stmtType, stmtClass, outputVar) \ #define TEST_CAST_STMT(stmt_list, stmt_index, stmtType, stmtClass, outputVar) \
ASSERT_EQ(stmt_list->getStatement(stmt_index)->type(), stmtType); \ ASSERT_EQ(stmt_list->getStatement(stmt_index)->type(), stmtType); \
stmtClass* outputVar = (stmtClass*) stmt_list->getStatement(stmt_index); const stmtClass* outputVar = (const stmtClass*) stmt_list->getStatement(stmt_index);
#endif #endif

View File

@ -7,40 +7,40 @@
using namespace hsql; using namespace hsql;
TEST(SelectTest) { TEST(SelectTest) {
TEST_PARSE_SINGLE_SQL("SELECT * FROM students;", kStmtSelect, SelectStatement, stmt); TEST_PARSE_SINGLE_SQL("SELECT * FROM students;", kStmtSelect, SelectStatement, stmt);
ASSERT_NULL(stmt->whereClause); ASSERT_NULL(stmt->whereClause);
ASSERT_NULL(stmt->groupBy); ASSERT_NULL(stmt->groupBy);
} }
TEST(SelectHavingTest) { TEST(SelectHavingTest) {
TEST_PARSE_SINGLE_SQL("SELECT city, AVG(grade) AS avg_grade FROM students GROUP BY city HAVING AVG(grade) < 2.0", kStmtSelect, SelectStatement, stmt); TEST_PARSE_SINGLE_SQL("SELECT city, AVG(grade) AS avg_grade FROM students GROUP BY city HAVING AVG(grade) < 2.0", kStmtSelect, SelectStatement, stmt);
ASSERT_FALSE(stmt->selectDistinct); ASSERT_FALSE(stmt->selectDistinct);
GroupByDescription* group = stmt->groupBy; GroupByDescription* group = stmt->groupBy;
ASSERT_NOTNULL(group); ASSERT_NOTNULL(group);
ASSERT_EQ(group->columns->size(), 1); ASSERT_EQ(group->columns->size(), 1);
ASSERT(group->having->isSimpleOp('<')); ASSERT(group->having->isSimpleOp('<'));
ASSERT(group->having->expr->isType(kExprFunctionRef)); ASSERT(group->having->expr->isType(kExprFunctionRef));
ASSERT(group->having->expr2->isType(kExprLiteralFloat)); ASSERT(group->having->expr2->isType(kExprLiteralFloat));
} }
TEST(SelectDistinctTest) { TEST(SelectDistinctTest) {
TEST_PARSE_SINGLE_SQL("SELECT DISTINCT grade, city FROM students;", kStmtSelect, SelectStatement, stmt); TEST_PARSE_SINGLE_SQL("SELECT DISTINCT grade, city FROM students;", kStmtSelect, SelectStatement, stmt);
ASSERT(stmt->selectDistinct); ASSERT(stmt->selectDistinct);
ASSERT_NULL(stmt->whereClause); ASSERT_NULL(stmt->whereClause);
} }
TEST(SelectGroupDistinctTest) { TEST(SelectGroupDistinctTest) {
TEST_PARSE_SINGLE_SQL("SELECT city, COUNT(name), COUNT(DISTINCT grade) FROM students GROUP BY city;", kStmtSelect, SelectStatement, stmt); TEST_PARSE_SINGLE_SQL("SELECT city, COUNT(name), COUNT(DISTINCT grade) FROM students GROUP BY city;", kStmtSelect, SelectStatement, stmt);
ASSERT_FALSE(stmt->selectDistinct); ASSERT_FALSE(stmt->selectDistinct);
ASSERT_EQ(stmt->selectList->size(), 3); ASSERT_EQ(stmt->selectList->size(), 3);
ASSERT(!stmt->selectList->at(1)->distinct); ASSERT(!stmt->selectList->at(1)->distinct);
ASSERT(stmt->selectList->at(2)->distinct); ASSERT(stmt->selectList->at(2)->distinct);
} }

View File

@ -3,57 +3,57 @@
class TestsManager { class TestsManager {
// Note: static initialization fiasco // Note: static initialization fiasco
// http://www.parashift.com/c++-faq-lite/static-init-order.html // http://www.parashift.com/c++-faq-lite/static-init-order.html
// http://www.parashift.com/c++-faq-lite/static-init-order-on-first-use.html // http://www.parashift.com/c++-faq-lite/static-init-order-on-first-use.html
public: public:
static std::vector<std::string>& testNames() { static std::vector<std::string>& testNames() {
static std::vector<std::string>* _testNames = new std::vector<std::string>; static std::vector<std::string>* _testNames = new std::vector<std::string>;
return *_testNames; return *_testNames;
} }
static std::vector<void (*)(void)>& tests() { static std::vector<void (*)(void)>& tests() {
static std::vector<void (*)(void)>* tests = new std::vector<void (*)(void)>; static std::vector<void (*)(void)>* tests = new std::vector<void (*)(void)>;
return *tests; return *tests;
} }
}; };
int AddTest(void (*foo)(void), std::string name) { int AddTest(void (*foo)(void), std::string name) {
TestsManager::tests().push_back(foo); TestsManager::tests().push_back(foo);
TestsManager::testNames().push_back(name); TestsManager::testNames().push_back(name);
return 0; return 0;
} }
size_t RunTests() { size_t RunTests() {
size_t numFailed = 0; size_t numFailed = 0;
for (size_t i = 0; i < TestsManager::tests().size(); ++i) { for (size_t i = 0; i < TestsManager::tests().size(); ++i) {
printf("\033[0;32m{ running}\033[0m %s\n", TestsManager::testNames()[i].c_str()); printf("\033[0;32m{ running}\033[0m %s\n", TestsManager::testNames()[i].c_str());
try { try {
// Run test // Run test
(*TestsManager::tests()[i])(); (*TestsManager::tests()[i])();
printf("\033[0;32m{ ok}\033[0m %s\n", TestsManager::testNames()[i].c_str()); printf("\033[0;32m{ ok}\033[0m %s\n", TestsManager::testNames()[i].c_str());
} catch (AssertionFailedException& e) { } catch (AssertionFailedException& e) {
printf("\033[1;31m{ failed} %s\n", TestsManager::testNames()[i].c_str()); printf("\033[1;31m{ failed} %s\n", TestsManager::testNames()[i].c_str());
printf("\tAssertion failed: %s\n\033[0m", e.what()); printf("\tAssertion failed: %s\n\033[0m", e.what());
numFailed++; numFailed++;
}
} }
return numFailed; }
return numFailed;
} }
int main() { int main() {
size_t numFailed = RunTests(); size_t numFailed = RunTests();
if (numFailed == 0) { if (numFailed == 0) {
return 0; return 0;
} else { } else {
return -1; return -1;
} }
} }

View File

@ -31,17 +31,17 @@
class AssertionFailedException: public std::exception { class AssertionFailedException: public std::exception {
public: public:
AssertionFailedException(std::string msg) : AssertionFailedException(std::string msg) :
std::exception(), std::exception(),
_msg(msg) {}; _msg(msg) {};
virtual const char* what() const throw() { virtual const char* what() const throw() {
return _msg.c_str(); return _msg.c_str();
} }
protected: protected:
std::string _msg; std::string _msg;
}; };
int AddTest(void (*foo)(void), std::string name); int AddTest(void (*foo)(void), std::string name);

View File

@ -67,15 +67,15 @@ int main(int argc, char *argv[]) {
start = std::chrono::system_clock::now(); start = std::chrono::system_clock::now();
// Parsing // Parsing
SQLParserResult* stmt_list = SQLParser::parseSQLString(sql.c_str()); SQLParserResult* result = SQLParser::parseSQLString(sql.c_str());
end = std::chrono::system_clock::now(); end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start; std::chrono::duration<double> elapsed_seconds = end-start;
double us = elapsed_seconds.count() * 1000 * 1000; double us = elapsed_seconds.count() * 1000 * 1000;
if (expectFalse == stmt_list->isValid) { if (expectFalse == result->isValid()) {
printf("\033[0;31m{ failed}\033[0m\n"); printf("\033[0;31m{ failed}\033[0m\n");
printf("\t\033[0;31m%s (L%d:%d)\n\033[0m", stmt_list->errorMsg, stmt_list->errorLine, stmt_list->errorColumn); printf("\t\033[0;31m%s (L%d:%d)\n\033[0m", result->errorMsg(), result->errorLine(), result->errorColumn());
printf("\t%s\n", sql.c_str()); printf("\t%s\n", sql.c_str());
numFailed++; numFailed++;
} else { } else {

View File

@ -11,12 +11,12 @@ using namespace hsql;
TEST(DeleteStatementTest) { TEST(DeleteStatementTest) {
SQLParserResult* result = SQLParser::parseSQLString("DELETE FROM students WHERE grade > 2.0;"); const SQLParserResult* result = SQLParser::parseSQLString("DELETE FROM students WHERE grade > 2.0;");
ASSERT(result->isValid); ASSERT(result->isValid());
ASSERT_EQ(result->size(), 1); ASSERT_EQ(result->size(), 1);
ASSERT(result->getStatement(0)->type() == kStmtDelete); ASSERT(result->getStatement(0)->type() == kStmtDelete);
DeleteStatement* stmt = (DeleteStatement*) result->getStatement(0); const DeleteStatement* stmt = (const DeleteStatement*) result->getStatement(0);
ASSERT_STREQ(stmt->tableName, "students"); ASSERT_STREQ(stmt->tableName, "students");
ASSERT_NOTNULL(stmt->expr); ASSERT_NOTNULL(stmt->expr);
ASSERT(stmt->expr->isType(kExprOperator)); ASSERT(stmt->expr->isType(kExprOperator));
@ -25,12 +25,12 @@ TEST(DeleteStatementTest) {
} }
TEST(CreateStatementTest) { TEST(CreateStatementTest) {
SQLParserResult* result = SQLParser::parseSQLString("CREATE TABLE students (name TEXT, student_number INT, city INTEGER, grade DOUBLE)"); const SQLParserResult* result = SQLParser::parseSQLString("CREATE TABLE students (name TEXT, student_number INT, city INTEGER, grade DOUBLE)");
ASSERT(result->isValid); ASSERT(result->isValid());
ASSERT_EQ(result->size(), 1); ASSERT_EQ(result->size(), 1);
ASSERT_EQ(result->getStatement(0)->type(), kStmtCreate); ASSERT_EQ(result->getStatement(0)->type(), kStmtCreate);
CreateStatement* stmt = (CreateStatement*) result->getStatement(0); const CreateStatement* stmt = (const CreateStatement*) result->getStatement(0);
ASSERT_EQ(stmt->type, CreateStatement::kTable); ASSERT_EQ(stmt->type, CreateStatement::kTable);
ASSERT_STREQ(stmt->tableName, "students"); ASSERT_STREQ(stmt->tableName, "students");
ASSERT_NOTNULL(stmt->columns); ASSERT_NOTNULL(stmt->columns);
@ -47,12 +47,12 @@ TEST(CreateStatementTest) {
TEST(UpdateStatementTest) { TEST(UpdateStatementTest) {
SQLParserResult* result = SQLParser::parseSQLString("UPDATE students SET grade = 5.0, name = 'test' WHERE name = 'Max Mustermann';"); const SQLParserResult* result = SQLParser::parseSQLString("UPDATE students SET grade = 5.0, name = 'test' WHERE name = 'Max Mustermann';");
ASSERT(result->isValid); ASSERT(result->isValid());
ASSERT_EQ(result->size(), 1); ASSERT_EQ(result->size(), 1);
ASSERT_EQ(result->getStatement(0)->type(), kStmtUpdate); ASSERT_EQ(result->getStatement(0)->type(), kStmtUpdate);
UpdateStatement* stmt = (UpdateStatement*) result->getStatement(0); const UpdateStatement* stmt = (const UpdateStatement*) result->getStatement(0);
ASSERT_NOTNULL(stmt->table); ASSERT_NOTNULL(stmt->table);
ASSERT_STREQ(stmt->table->name, "students"); ASSERT_STREQ(stmt->table->name, "students");