From f2c3c2b1a4f0d7cb8dbdaef0f891c60a828daf02 Mon Sep 17 00:00:00 2001 From: Martin Kleusberg Date: Thu, 6 Nov 2014 18:28:28 +0100 Subject: [PATCH] Parse and save foreign key constraints When parsing a CREATE TABLE statement read and try to parse any foreign key constraints and save that information. --- src/sqlitetypes.cpp | 27 +++++++++++++++++++++++++++ src/sqlitetypes.h | 3 +++ 2 files changed, 30 insertions(+) diff --git a/src/sqlitetypes.cpp b/src/sqlitetypes.cpp index 67329672..e99159f8 100644 --- a/src/sqlitetypes.cpp +++ b/src/sqlitetypes.cpp @@ -190,6 +190,14 @@ QString Table::sql() const if(pks_found) sql += pk + ")"; } + + // foreign keys + foreach(FieldPtr f, m_fields) + { + if(!f->foreignKey().isEmpty()) + sql += QString(",\n\tFOREIGN KEY(`%1`) REFERENCES %2").arg(f->name()).arg(f->foreignKey()); + } + sql += "\n)"; // without rowid @@ -345,6 +353,25 @@ Table CreateTableWalker::table() } } break; + case sqlite3TokenTypes::FOREIGN: + { + tc = tc->getNextSibling(); // FOREIGN + tc = tc->getNextSibling(); // KEY + tc = tc->getNextSibling(); // LPAREN + QString column_name = identifier(tc); + tc = tc->getNextSibling(); // identifier + if(tc->getType() == sqlite3TokenTypes::COMMA) + { + // No support for composite foreign keys + m_bModifySupported = false; + break; + } + tc = tc->getNextSibling(); // RPAREN + tc = tc->getNextSibling(); // REFERENCES + + tab.fields().at(tab.findField(column_name))->setForeignKey(concatTextAST(tc, true)); + } + break; default: { m_bModifySupported = false; diff --git a/src/sqlitetypes.h b/src/sqlitetypes.h index 80299ea4..6eff3516 100644 --- a/src/sqlitetypes.h +++ b/src/sqlitetypes.h @@ -42,6 +42,7 @@ public: void setAutoIncrement(bool autoinc) { m_autoincrement = autoinc; } void setPrimaryKey(bool pk) { m_primaryKey = pk; } void setUnique(bool u) { m_unique = u; } + void setForeignKey(const QString& key) { m_foreignKey = key; } bool isText() const; bool isInteger() const; @@ -54,6 +55,7 @@ public: bool autoIncrement() const { return m_autoincrement; } bool primaryKey() const { return m_primaryKey; } bool unique() const { return m_unique; } + const QString& foreignKey() const { return m_foreignKey; } static QStringList Datatypes; private: @@ -62,6 +64,7 @@ private: bool m_notnull; QString m_check; QString m_defaultvalue; + QString m_foreignKey; // Even though this information is a table constraint easier for accessing and processing to store it here bool m_autoincrement; //! this is stored here for simplification bool m_primaryKey; bool m_unique;