From 81ed7705b993ef974759dc72a831490c9a1980c1 Mon Sep 17 00:00:00 2001 From: kishoramballi Date: Thu, 8 Oct 2009 06:35:51 +0000 Subject: [PATCH] Update in sync with enterprise version. --- include/AbsSqlConnection.h | 30 +++---- include/AbsSqlStatement.h | 74 +++++++++------ include/AggTableImpl.h | 91 ++++++++++--------- include/Allocator.h | 69 +++++++++++--- include/CacheTableLoader.h | 46 ++++++++-- include/CatalogTables.h | 78 ++++++++++++++-- include/Config.h | 42 +-------- include/DataType.h | 43 +++++---- include/DataTypeInline.h | 136 +++++++++++++++++++++++----- include/Database.h | 32 ++++++- include/DatabaseManager.h | 8 +- include/DatabaseManagerImpl.h | 17 ++-- include/Debug.h | 8 +- include/ErrorType.h | 21 ++--- include/Field.h | 40 ++++++--- include/Index.h | 50 +++++++---- include/Info.h | 93 ++++++++++++++++--- include/JoinTableImpl.h | 30 +++++-- include/Lock.h | 9 +- include/Makefile.am | 16 ++-- include/Mutex.h | 18 ++-- include/NanoTimer.h | 16 +--- include/Network.h | 103 ++++++++++++++++----- include/Parser.h | 175 ++++++++++++++++++++++++++++++++---- include/Predicate.h | 19 +++- include/PredicateImpl.h | 32 ++++--- include/Process.h | 3 +- include/Session.h | 23 ++--- include/SessionImpl.h | 7 +- include/SqlConnection.h | 13 ++- include/SqlFactory.h | 17 +--- include/SqlGwConnection.h | 32 +++++-- include/SqlGwStatement.h | 28 +++++- include/SqlLogConnection.h | 51 +++++++++-- include/SqlLogStatement.h | 29 ++++-- include/SqlNetworkHandler.h | 15 ++-- include/SqlNwConnection.h | 9 +- include/SqlNwStatement.h | 17 +++- include/SqlOdbcConnection.h | 50 ++++++++++- include/SqlOdbcStatement.h | 27 ++++-- include/SqlStatement.h | 15 ++++ include/Statement.h | 203 +++++++++++++++++++++++++++++++++++++----- include/Table.h | 7 +- include/TableConfig.h | 75 +++++++++------- include/TableImpl.h | 67 +++++++++----- include/Transaction.h | 24 ++++- include/UserManager.h | 3 + include/UserManagerImpl.h | 2 +- include/Util.h | 134 ++++++++++++++++++++++++---- include/os.h | 7 ++ include/sql.h | 1 + 51 files changed, 1625 insertions(+), 530 deletions(-) rewrite include/Makefile.am (94%) diff --git a/include/AbsSqlConnection.h b/include/AbsSqlConnection.h index f767126b..04a22a0d 100644 --- a/include/AbsSqlConnection.h +++ b/include/AbsSqlConnection.h @@ -1,29 +1,19 @@ /*************************************************************************** - * Copyright (C) 2007 by Prabakaran Thirumalai * - * praba_tuty@yahoo.com * * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * + * Copyright (C) Lakshya Solutions Ltd. All rights reserved. * * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU General Public License for more details. * - * * - * You should have received a copy of the GNU General Public License * - * along with this program; if not, write to the * - * Free Software Foundation, Inc., * - * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef ABSSQLCONNECTION_H #define ABSSQLCONNECTION_H -#include - +#include +#include +#include +#include +class Connection; class CachedTable{ public: char tableName[IDENTIFIER_LENGTH]; + CachedTable() { tableName[0] = '\0'; } }; enum TransSyncMode { @@ -101,8 +91,10 @@ class AbsSqlConnection */ virtual DbRetVal beginTrans (IsolationLevel isoLevel = READ_COMMITTED, TransSyncMode mode = OSYNC) = 0; - virtual ~AbsSqlConnection(){} - + virtual ~AbsSqlConnection() + { + if (innerConn) { delete innerConn; innerConn = NULL; } + } }; #endif diff --git a/include/AbsSqlStatement.h b/include/AbsSqlStatement.h index c1c5a32b..a5dcd2e0 100644 --- a/include/AbsSqlStatement.h +++ b/include/AbsSqlStatement.h @@ -1,31 +1,37 @@ /*************************************************************************** - * Copyright (C) 2007 by Prabakaran Thirumalai * - * praba_tuty@yahoo.com * * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * + * Copyright (C) Lakshya Solutions Ltd. All rights reserved. * * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU General Public License for more details. * - * * - * You should have received a copy of the GNU General Public License * - * along with this program; if not, write to the * - * Free Software Foundation, Inc., * - * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ + #ifndef ABSSQLSTATEMENT_H #define ABSSQLSTATEMENT_H -//#include -//#include "Statement.h" -//#include #include -//#include +#include +#include class Statement; class ParsedData; +#ifndef STMT_TYPE +#define STMT_TYPE +enum StatementType +{ + UnknownStatement, + SelectStatement, + InsertStatement, + UpdateStatement, + DeleteStatement, + CreateTableStatement, + DropTableStatement, + CreateIndexStatement, + DropIndexStatement, + CacheTableStatement, + CompactTableStatement, + CopyTableStatement, + MetaStatement, + UserStatement +}; +#endif + /** * @class AbsSqlStatement @@ -48,6 +54,7 @@ class AbsSqlStatement AbsSqlConnection *con; public: void setInnerStatement(AbsSqlStatement *stmt) { innerStmt = stmt; } + AbsSqlStatement *getInnerStatement() { return innerStmt; } /** sets connection handle to be used for subsequent operations * @param con SqlConnection* */ @@ -61,12 +68,15 @@ class AbsSqlStatement * @returns DbRetVal */ virtual DbRetVal prepare(char *stmt) = 0; + + /** Executes directly for non parameterized statements **/ + virtual DbRetVal executeDirect(char *stmt) = 0; /** Retrieves the tablename of the prepared statement * Used internally to get the tablename of the non select DML stmts * @returns char* tablename */ - virtual char* getTableName(){ return NULL; } + virtual char* getTableName()=0; /** executes the sql statement. For insert, update, delete queries execute performs the * required operation on the table. @@ -75,7 +85,7 @@ class AbsSqlStatement * @param rowsAffect number of rows affected by the sql statement * @returns DbRetVal */ - virtual DbRetVal execute(int &rowsAffect) =0; + virtual DbRetVal execute(int &rowsAffect)=0; /**fetches the next tuple from the result of the execution of sql select query. * execute should be called before calling this method. Application buffer should be @@ -133,6 +143,7 @@ class AbsSqlStatement * @returns address void* */ virtual void* getFieldValuePtr( int pos ) = 0; + virtual void* getFieldValuePtr( char *name ) = 0; /**Frees all the resources held for the sql statement. Needs to be called before calling prepare again on the same statement handle. * @returns DbRetVal @@ -227,14 +238,23 @@ class AbsSqlStatement /**Returns whether the statement prepared is select statement * @return bool true if it is select stmt, false otherwise */ - virtual List getTableNameList(){} + virtual List getTableNameList(){ List dummy; return dummy;} + virtual int getNoOfPagesForTable(char *tblName)=0; + virtual DbRetVal loadRecords(char *tblName, void *buf)=0; + virtual ResultSetPlan getResultSetPlan()=0; virtual bool isSelect() = 0; virtual bool isFldNull(int pos)=0; virtual bool isFldNull(char *name)=0; virtual void setNull(int pos)=0; virtual int getFldPos(char *name)=0; virtual List getAllTableNames(DbRetVal &ret)=0; - virtual ~AbsSqlStatement(){} + virtual List getAllUserNames(DbRetVal &ret)=0; + virtual StatementType getStmtType()=0; + virtual void getProjFieldType( int *data )=0; + virtual ~AbsSqlStatement() + { + if (innerStmt) { delete innerStmt; innerStmt = NULL; } + } }; //used to store the binded field values and parameters from derived clases of @@ -264,13 +284,18 @@ class BindSqlProjectField int length; int offset; char defaultValueBuf[DEFAULT_VALUE_BUF_LENGTH]; + AggType aType; bool isNull; bool isPrimary; bool isDefault; bool isUnique; + bool isFreed; void *value; void *targetvalue; - BindSqlProjectField(){ value = NULL; targetvalue = NULL; } + BindSqlProjectField() + { + value = NULL; targetvalue = NULL; isFreed = false; aType = AGG_UNKNOWN; + } }; class StmtBucket @@ -286,5 +311,4 @@ class StmtNode AbsSqlStatement *stmt; char stmtstr[1024]; }; - #endif diff --git a/include/AggTableImpl.h b/include/AggTableImpl.h index 109ab0fa..14152195 100644 --- a/include/AggTableImpl.h +++ b/include/AggTableImpl.h @@ -25,6 +25,8 @@ #include #include #include +#include +#ifndef AGGTYPE enum AggType { AGG_MIN = 1, @@ -34,6 +36,9 @@ enum AggType AGG_COUNT, AGG_UNKNOWN }; + +#define AGGTYPE +#endif #include class AggFldDef { @@ -43,8 +48,9 @@ class AggFldDef int length; void *bindBuf; void *appBuf; - AggType atype; + AggType aType; bool alreadyBinded; + bool isNullable; AggFldDef() { strcpy(fldName, ""); @@ -52,32 +58,11 @@ class AggFldDef length=0; bindBuf=NULL; appBuf=NULL; - atype=AGG_UNKNOWN; + aType=AGG_UNKNOWN; alreadyBinded=false; + isNullable=false; } }; -class HashMapNode -{ - public: - void *elem; - HashMapNode *next; - HashMapNode() { elem = NULL; next = NULL; } -}; -class HashMap -{ - void **bucket; - int keySize; - int bucketSize; - public: - HashMap(){ keySize = 0; bucketSize = 1009; - bucket = (void**) malloc(bucketSize * sizeof(void*)); - memset(bucket, 0, bucketSize * sizeof(void*)); - } - void setKeySize(int size); - DbRetVal insert(void *elem); - void* find(void *elem); - void removeAll(); -}; class AggTableImpl:public Table { @@ -85,24 +70,28 @@ class AggTableImpl:public Table char tblName_[IDENTIFIER_LENGTH]; void *curTuple; //holds the current tuple ptr. moved during fetch() calls List fldList; - AggFldDef groupFld; + List fldGroupList; Table *tableHdl; List aggNodes; //change this list to some other data structure ListIterator aggNodeIter; HashMap aggNodeMap; //for faster lookup - + Predicate *havingPred; + int grpNullInfo; + long long prjNullInfo; int aggNodeSize; + int groupSize; + char *grpFldBuffer; + + bool optGrpIntNoNull; + void *grpBindBuf; + DbRetVal copyValuesToBindBuffer(void *tuple); public: AggTableImpl(); virtual ~AggTableImpl(); DbRetVal getFieldInfo(const char *fieldName, FieldInfo *&info) { return tableHdl->getFieldInfo(fieldName, info); } - bool isGroupSet() - { - if (groupFld.type == typeUnknown) return false; else return true; - } - void* insertOrGet(); + void* insertOrGetAggNode(); void setTable(Table *impl){ tableHdl = impl;} Table* getTableHdl(){ return tableHdl; } DbRetVal closeScan(); @@ -110,14 +99,30 @@ class AggTableImpl:public Table DbRetVal bindFld(const char *name, void *val); DbRetVal bindFld(const char *name, AggType aggType, void *val); DbRetVal setGroup(const char *name, void *val); - void setCondition(Condition *p){} - DbRetVal markFldNull(const char *name){} - DbRetVal markFldNull(int colpos){} - bool isFldNull(const char *name){return false;} - bool isFldNull(int colpos){return false;} + bool isFldPresentInGrp(char *fname); + int computeGrpNodeSize(); + void* getGroupValueBuffer(); + int getAggOffset(char *fname, AggType aggType); + DbRetVal copyValuesFromGrpBindBuf(char *grpFldBuf, char *fldName); + void setCondition(Condition *p){ havingPred = p->getPredicate();} + DbRetVal markFldNull(const char *name){ return OK;} + inline DbRetVal markFldNull(int colpos){ + SETBIT(grpNullInfo, colpos); + return OK; + } + bool isFldNull(const char *name); + inline bool isFldNull(int colpos) { + if (colpos <= 32) { if (BITSET(prjNullInfo, colpos)) return true; } + else if (BITSET(*(int *)((char *)&prjNullInfo + 4), colpos)) return true; + return false; + } void clearFldNull(const char *name){} - void clearFldNull(int colpos){} - int getFldPos(char *name){} + inline void clearFldNull(int colpos){ + if (colpos <= 32) CLEARBIT(prjNullInfo, colpos); + else CLEARBIT(*(int *)((char*)&prjNullInfo + 4), colpos); + } + DbRetVal compact(){ return OK;} + int getFldPos(char *name){ return 0;} void resetNullinfo(){} DbRetVal insertTuple() { return ErrBadCall; } DbRetVal updateTuple() { return ErrBadCall; } @@ -129,7 +134,8 @@ class AggTableImpl:public Table DbRetVal lock(bool shared) { return ErrBadCall; } DbRetVal unlock(){ return ErrBadCall; } DbRetVal setUndoLogging(bool flag) { return ErrBadCall; } - void printSQLIndexString(){ }; + void printSQLIndexString(FILE *fp, int fd){ }; + void printSQLForeignString(){} char* getName() { return tableHdl->getName(); } List getFieldNameList(){ List list; return list;} DbRetVal execute(); @@ -146,11 +152,12 @@ class AggTableImpl:public Table { printf("Wrong call\n"); } bool isTableInvolved(char *tableName) { printf("Wrong call\n"); return false; } - void printPlan(int space){printf("AGG-PLAN-TODO\n");} - DbRetVal optimize() - { printf("Wrong call\n"); return OK; } + void printPlan(int space); + DbRetVal optimize(); + bool isFKTable(){return false;} ScanType getScanType(){ return unknownScan;} bool hasIndex(char *fName){ return false;} + AggType getAggType(const char *aggName, char *fldName); }; #endif diff --git a/include/Allocator.h b/include/Allocator.h index c587f13e..0fe9c087 100644 --- a/include/Allocator.h +++ b/include/Allocator.h @@ -18,6 +18,7 @@ #include #include #include +#include typedef void Page; @@ -32,7 +33,7 @@ enum AllocType class VarSizeInfo { public: - size_t size_; + int size_; int isUsed_; }; @@ -57,7 +58,7 @@ class PageInfo Page *nextPage_; //next page in the same chunk void setPageAsUsed(size_t offset); void setFirstPageAsUsed(); - + void setPageAsFree(); }; class Chunk; @@ -86,10 +87,47 @@ class ChunkIterator //and it is cached for performance int noOfNodes_; + public: - ChunkIterator() { allocSize_ =0; iterPage_ = NULL; nodeOffset_ =0; + int pageSize; + ChunkIterator() { pageSize = PAGE_SIZE; allocSize_ =0; iterPage_ = NULL; nodeOffset_ =0; chunkID_ = -1; noOfNodes_ =0; } + int isLargeSize() { if (noOfNodes_ == 0) return true; else return false; } void* nextElement(); + void* nextElementIntMatch(int value, int offset); + inline void* nextElementInt() { + if (!data) { + pageSize = PAGE_SIZE; + data = ((char*)iterPage_) + sizeof(PageInfo); + if ((*(int*)data) == 1) return data + sizeof(int); + } + + if(0 == noOfNodes_) return nextElement(); + data += allocSize_; + while(data < iterPageEnd) + { + if (*((int*)data)) { + return data + sizeof(int); + } else { + data += allocSize_; + } + } + while(iterPage_->nextPage_ != NULL) + { + iterPage_ = (PageInfo*)iterPage_->nextPage_; + data = ((char*)iterPage_) + sizeof(PageInfo); + iterPageEnd = ((char*)iterPage_) + pageSize; + while(data < iterPageEnd) + { + if (*((int*)data) == 0) { + data = data + allocSize_; + nodeOffset_++; + } else + return data +sizeof(int); + } + } + return NULL; + } friend class Chunk; }; @@ -130,11 +168,13 @@ class Chunk void setAllocType(AllocType type) { allocType_ = type; } AllocType getAllocType() { return allocType_; } Page* getFirstPage(){ return firstPage_; } - + Page* getCurrentPage(){ return curPage_; } + void setFirstPage(void *fp) { firstPage_ = fp;} + void setCurPage(void *cp) { curPage_ = cp;} PageInfo* getPageInfo(Database *db, void *ptr); - void* allocate(Database *db, DbRetVal *status = NULL); + void* allocate(Database *db, DbRetVal *status); - void* allocate(Database *db, size_t size, DbRetVal *status = NULL); + void* allocate(Database *db, size_t size, DbRetVal *status); void free(Database *db, void* ptr); ChunkIterator getIterator(); @@ -142,7 +182,7 @@ class Chunk long getTotalDataNodes(); int totalPages(); - int compact(); + int compact(int procSlot); private: @@ -150,19 +190,20 @@ class Chunk int getChunkMutex(int procSlot); int releaseChunkMutex(int procSlot); int destroyMutex(); - void createDataBucket(Page *page, size_t totalSize, size_t needSize); - void splitDataBucket(VarSizeInfo *varInfo, size_t needSize); - void* varSizeFirstFitAllocate(size_t size); + int createDataBucket(Page *page, size_t totalSize, size_t needSize, int pslot); + int splitDataBucket(VarSizeInfo *varInfo, size_t needSize, int pslot, DbRetVal *status); + void* varSizeFirstFitAllocate(size_t size, int pslot, DbRetVal *status); void freeForLargeAllocator(void *ptr, int pslot); void freeForVarSizeAllocator(void *ptr, int pslot); void* allocateForLargeDataSize(Database *db); - void* allocateFromFirstPage(Database *db, int noOfDataNodes); - void* allocateFromNewPage(Database *db); + void* allocateFromFirstPage(Database *db, int noOfDataNodes, DbRetVal *status); + void* allocateFromNewPage(Database *db, DbRetVal *status); void* allocateForLargeDataSize(Database *db, size_t size); - void* allocFromNewPageForVarSize(Database *db, size_t size); - void* allocateFromCurPageForVarSize(size_t size); + void* allocFromNewPageForVarSize(Database *db, size_t size, int pslot, + DbRetVal *status); + void* allocateFromCurPageForVarSize(size_t size, int pslot, DbRetVal *status); friend class Database; diff --git a/include/CacheTableLoader.h b/include/CacheTableLoader.h index 00e9832c..07811f31 100644 --- a/include/CacheTableLoader.h +++ b/include/CacheTableLoader.h @@ -13,11 +13,20 @@ * GNU General Public License for more details. * * * ***************************************************************************/ +#ifndef CACHETABLELOADER_H +#define CACHETABLELOADER_H #include #include #include #include +class CacheIndexInfo +{ + public: + char indexName[IDENTIFIER_LENGTH]; + FieldNameList fieldList; +}; + class CacheTableLoader { char tableName[IDENTIFIER_LENGTH]; @@ -26,6 +35,10 @@ class CacheTableLoader char password[IDENTIFIER_LENGTH]; char conditionVal[IDENTIFIER_LENGTH]; //added newly char fieldlistVal[IDENTIFIER_LENGTH]; + char dsnName[IDENTIFIER_LENGTH]; + // char dsnId[IDENTIFIER_LENGTH]; + // char dsnPwd[IDENTIFIER_LENGTH]; + bool shouldForce; public: CacheTableLoader() { @@ -33,13 +46,23 @@ class CacheTableLoader strcpy(conditionVal,""); strcpy(fieldName,""); strcpy(fieldlistVal,""); + strcpy(dsnName,""); + //strcpy(dsnId,""); + //strcpy(dsnPwd,""); + shouldForce = false; } + DbRetVal checkSecondTimeSqlPrimaryKeys(SQLHSTMT hstmtmeta,char *tableName,char *ptr, HashIndexInitInfo *inf,bool &isPriIndex); + DbRetVal createIndex(SQLHSTMT hstmtmeta, char *tableName, HashIndexInitInfo *inf,AbsSqlStatement *stmt,bool isPKFieldSpecified); + void setForceFlag(bool flag){ shouldForce = flag;} void setConnParam(char *user, char *pass){ strcpy(userName, user); strcpy(password, pass); } void setTable(char *tablename) { strcpy(tableName,tablename); } void setCondition(char *condition){strcpy(conditionVal,condition);} //new one + void setDsnName(char *dname) {strcpy(dsnName,dname);} + + //void setDsnId(char *dsnid) { strcpy(dsnId,dsnid); } + //void setDsnPwd(char *dsnpwd){ strcpy(dsnPwd,dsnpwd);} void setFieldName(char *fldname){ strcpy(fieldName,fldname);} DbRetVal addToCacheTableFile(bool isDirect); - static int getTableMode(char *tabname); void setFieldListVal(char *field) {strcpy(fieldlistVal,field);} DbRetVal addToCacheTableFile(); @@ -49,14 +72,11 @@ class CacheTableLoader DbRetVal unload(bool tabDefinition = true); DbRetVal refresh(); DbRetVal recoverAllCachedTables(); - DbRetVal load(Connection *conn, bool tabDef); - static DbRetVal isTableCached(char *tablename); + DbRetVal load(AbsSqlConnection *conn, AbsSqlStatement *stmt, bool tabDef); DbRetVal isTablePresent();// new one by :Jitendra - bool isFieldExist(char *fieldname); DbRetVal CacheInfo(bool isTabPresent); - char *getRealConditionFromFile(char *condition); char *getConditionVal(char *condition); - + void setParamValues(AbsSqlStatement *stmt, int parampos, DataType type, int length, char *value); }; class BindBuffer @@ -65,6 +85,9 @@ class BindBuffer void *csql; void *targetdb; DataType type; + int length; + BindBuffer(){ csql = NULL; targetdb = NULL; type = typeUnknown; length =0; } + ~BindBuffer() { ::free(csql); ::free(targetdb); } }; class CacheTableInfo { @@ -73,8 +96,16 @@ class CacheTableInfo char fieldName[IDENTIFIER_LENGTH]; char projFieldlist[IDENTIFIER_LENGTH]; char condition[IDENTIFIER_LENGTH]; - + char dsnName[IDENTIFIER_LENGTH]; + + //char dsnId[IDENTIFIER_LENGTH]; + //char dsnPwd[IDENTIFIER_LENGTH]; + void setTableName(char *tblName){strcpy(tableName,tblName);} + void setDsnName(char *dsnname) { strcpy(dsnName,dsnname); } + // void setDsnId(char *dsnid) { strcpy(dsnId,dsnid); } + //void setDsnPwd(char *dsnpwd){ strcpy(dsnPwd,dsnpwd);} + void setFieldName(char *fldName){strcpy(fieldName,fldName);} void setProjFieldList(char *fieldlist){ strcpy(projFieldlist,fieldlist);} void setCondition(char *cond){ strcpy(condition,cond);} @@ -83,3 +114,4 @@ class CacheTableInfo char *getCondition(){ return condition;} char *getProjFieldList(){return projFieldlist;} }; +#endif diff --git a/include/CatalogTables.h b/include/CatalogTables.h index c70031ad..8886be43 100644 --- a/include/CatalogTables.h +++ b/include/CatalogTables.h @@ -30,6 +30,22 @@ class FieldNameList; class FieldIterator; class ChunkIterator; +enum ObjectType +{ + Tbl = 0, + hIdx = 1, + tIdx = 2, +}; + +struct Object +{ + char name[64]; + ObjectType type; + void *bucketChunk; + void *firstPage; + void *curPage; +}; + enum CatalogTableID { // chunk id 0 ->userChunkTable @@ -56,8 +72,9 @@ enum CatalogTableID FieldTableId = 13, AccessTableId = 14, IndexTableId = 15, - IndexFieldTableId= 16 - + IndexFieldTableId= 16, + ForeignKeyTableId= 17, + ForeignKeyFieldTableId= 18 }; @@ -91,7 +108,7 @@ class CatalogTableTABLE DbRetVal remove(const char *name, void *&chunk, void *&tptr); DbRetVal getChunkAndTblPtr(const char *name, void *&chunk, void *&tptr); - + DbRetVal setChunkPtr(const char *name, void *firstPage, void *curPage); List getTableList(); }; @@ -108,14 +125,14 @@ class CFIELD //currently default value is supported for string and binary //less than length 32 bytes char defaultValueBuf_[DEFAULT_VALUE_BUF_LENGTH]; + long long autoVal_;//[DEFAULT_VALUE_BUF_LENGTH]; + int width_; + int scale_; bool isNull_; bool isPrimary_; bool isUnique_; bool isDefault_; bool isAutoIncrement_; - long long autoVal_; - int width_; - int scale_; }; class CatalogTableFIELD @@ -159,7 +176,7 @@ class CatalogTableUSER bool &isAuthenticated, bool &isDba); DbRetVal remove(const char *name); DbRetVal changePass(const char *name, const char *pass); - + List getUserList(); }; class CACCESS @@ -213,6 +230,7 @@ class CatalogTableINDEX //pointer to the removed tuple DbRetVal remove(const char *name, void *&chunk, void *&hchunk, void *&iptr); DbRetVal get(const char *name, void *&chunk, void *&hchunk, void *&iptr); + DbRetVal setChunkPtr(const char *name, ObjectType tp, void *chunk, void *firstPage, void *curPage); //get the number of indexes on table pointed by tblPtr int getNumIndexes(void *tblPtr); @@ -226,6 +244,8 @@ class CatalogTableINDEX static int getNoOfBuckets(void *iptr); static int getUnique(void *iptr); static char* getName(void *iptr); + static int getOffsetOfFirstField(void *iptr); + static IndexType getType(void *iptr); }; @@ -252,6 +272,50 @@ class CatalogTableINDEXFIELD DbRetVal getFieldNameAndType(void *iptr, char *&name, DataType &type); DbRetVal getFieldInfo(void *index, FieldList &list); void printAllIndex(); + ListIterator getIndexListIterater(char *name); }; + +class CFK +{ + public: + char fkName_[IDENTIFIER_LENGTH]; + void* pkTblPtr_; + void* fkTblPtr_; +}; + +class CatalogTableFK +{ + Database *systemDatabase_; + public: + CatalogTableFK(Database *db) { systemDatabase_ = db; } + DbRetVal insert(char *name, void *tFkPtr,void *tPkPtr); + DbRetVal remove(void *tptr); + void *getFkCTable(void* tptr); + int getNumFkTable(void *ctptr); + bool isFkTable(void *ctptr); + void getPkTableName(void *ctptr, char **&array); + void getFkTableName(void *ctptr, char **&array); + int getNoOfPkTable(void *ctptr); + int getNoOfFkTable(void *ctptr); + DbRetVal getPkFkFieldInfo(void *cpkptr, void *cfkptr, FieldNameList &pklist,FieldNameList &pklist1); +}; + +class CFKFIELD +{ + public: + void* fkPtr_;//pointer to tuple in catalog table CFK + void* pfFldPtr_; + void* fkFldPtr_; +}; + +class CatalogTableFKFIELD +{ + Database *systemDatabase_; + public: + CatalogTableFKFIELD(Database *db) { systemDatabase_ = db; } + DbRetVal insert(char *cFKName, char **fkFldPtrs, char **pkFldPtrs,int totalFld); + DbRetVal remove(void *fptr); +}; + #endif diff --git a/include/Config.h b/include/Config.h index 1c1268b9..11cac25f 100644 --- a/include/Config.h +++ b/include/Config.h @@ -17,11 +17,7 @@ enum CacheMode { enum TDBInfo { mysql=0, - postgres, - oracle, - sybase, - db2, - sqlserver, + postgres }; class ConfigValues @@ -33,7 +29,6 @@ class ConfigValues char tableConfigFile[MAX_FILE_PATH_LEN]; char dsConfigFile[MAX_FILE_PATH_LEN];// DSN Config file char stderrFile[MAX_FILE_PATH_LEN]; - char replConfigFile[MAX_FILE_PATH_LEN]; char conflResoFile[MAX_FILE_PATH_LEN]; bool isDurable; @@ -41,7 +36,6 @@ class ConfigValues bool isCsqlSqlServer; bool isCache; bool isTwoWay; - bool isReplication; int siteID; int sysDbKey; @@ -69,7 +63,6 @@ class ConfigValues int port; int nwResponseTimeout; int nwConnectTimeout; - int maxReplSites; int msgKey; int asyncMsgMax; @@ -84,7 +77,6 @@ class ConfigValues strcpy(tableConfigFile, "/tmp/csql/csqltable.conf"); strcpy(dsConfigFile,"/tmp/csql/csqlds.conf"); // DSN Config file strcpy(stderrFile, "stderr"); - strcpy(replConfigFile, "/tmp/csql/csqlnw.conf"); strcpy(conflResoFile, "/tmp/csql/ConflResoFile.txt"); isDurable = false; @@ -92,7 +84,6 @@ class ConfigValues isCsqlSqlServer = false; isCache = false; isTwoWay=false; - isReplication = false; siteID=1; sysDbKey = 2222; @@ -120,7 +111,6 @@ class ConfigValues port = 5678; nwResponseTimeout=3; nwConnectTimeout=5; - maxReplSites=1; msgKey=-1; asyncMsgMax = 8192; //default for linux shmKeyForId = -1; @@ -165,15 +155,12 @@ class Config inline char* getDsConfigFile() { return cVal.dsConfigFile; } inline char* getTableConfigFile() { return cVal.tableConfigFile; } inline char* getStderrFile() { return cVal.stderrFile; } - inline bool useReplication() { return cVal.isReplication; } inline bool useDurability() { return cVal.isDurable; } inline int getDurableMode() { return cVal.durableMode; } inline bool useCsqlSqlServer() { return cVal.isCsqlSqlServer; } inline int getPort() { return cVal.port; } - inline char* getReplConfigFile() { return cVal.replConfigFile; } inline char* getConflResoFile() { return cVal.conflResoFile; } inline long getMaxQueueLogs() { return cVal.maxQueueLogs; } - inline int getNoOfReplSites() { return cVal.maxReplSites; } inline int getMsgKey() { return cVal.msgKey; } inline int getAsyncMsgMax() { return cVal.asyncMsgMax; } inline int getShmIDKey() { return cVal.shmKeyForId; } @@ -192,31 +179,4 @@ class Conf static Logger logger; }; -class SiteInfoData -{ - public: - int siteId; - char hostName[IDENTIFIER_LENGTH]; - int port; - char mode[32]; - SiteInfoData() { siteId = -1; port = 0; hostName[0]='\0'; mode[0]='\0';}; -}; - - -class SiteInfo -{ - DbRetVal populateSiteInfoList(); - public: - List siteInfoList; - List asyncSiteList; - List syncSiteList; - bool isAsyncSitePresent(); - bool isSyncSitePresent(); - SiteInfo() { populateSiteInfoList(); } - ~SiteInfo(); - List & getSiteInfoList() { return siteInfoList; } - List & getSyncSiteInfoList() { return syncSiteList; } - List & getAsyncSiteInfoList() { return asyncSiteList; } -}; - #endif diff --git a/include/DataType.h b/include/DataType.h index 86fe423c..dbc4de56 100644 --- a/include/DataType.h +++ b/include/DataType.h @@ -1,23 +1,15 @@ /*************************************************************************** - * Copyright (C) 2007 by www.databasecache.com * - * Contact: praba_tuty@databasecache.com * * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * + * Copyright (C) Lakshya Solutions Ltd. All rights reserved. * * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU General Public License for more details. * - * * - ***************************************************************************/ + ***************************************************************************/ + #ifndef DATATYPE_H #define DATATYPE_H #include #include #include +#include //#include typedef int JulianRep; @@ -65,12 +57,13 @@ enum ComparisionOp { OpGreaterThan, OpGreaterThanEquals, OpLike, // for Like operator + OpIsNull, OpInvalidComparisionOp }; static char CompOpNames[][20] = { "Equals", "NotEquals", "LessThan", "LessThanEquals", "GreaterThan", - "GreaterThanEquals", "Like", "Invalid" + "GreaterThanEquals", "Like", "isNULL", "Invalid" }; @@ -98,12 +91,15 @@ class AllDataType inline static long size(DataType type, int length =0); static char* getSQLString(DataType type); static SQLSMALLINT convertToSQLType(DataType type); - static SQLSMALLINT convertToSQL_C_Type(DataType type); - static DataType convertFromSQLType(SQLSMALLINT type); + static SQLSMALLINT convertToCSQLSQLType(DataType type); + static SQLSMALLINT convertToSQL_C_Type(DataType type,TDBInfo tdbname=mysql); + static DataType convertFromSQLType(SQLSMALLINT type,int length=0, int scale=0, TDBInfo tdbname=mysql); - inline static void copyVal(void* dest, void *src, DataType type, int length = 0); + inline static void copyVal(void* dest, void *src, DataType type, int length = 0,int dbFlag=0); + inline static void copyZeroVal(void* dest, DataType type, int length = 0); + inline static void cachecopyVal(void* dest, void *src, DataType type, int length = 0,int dbFlag=0); inline static void addVal(void* dest, void *src, DataType type); - static void divVal(void* dest, int src, DataType type); + static void divVal(double* dest, int src, DataType type); static void subVal(void* dest, void *src, DataType type); static void mulVal(void* dest, void *src, DataType type); static void mudVal(void* dest, void *src, DataType type); @@ -111,7 +107,6 @@ class AllDataType static void increment(void* dest, void *src, DataType type); static bool isValueZero(void* dest, DataType type); - inline static bool compareVal(void *src1, void *src2, ComparisionOp op, DataType type, long length = 0); static bool compareIntVal(void* src1, void* src2, ComparisionOp op); @@ -137,7 +132,7 @@ class AllDataType static void convertToByteInt(void* dest, void* src, DataType srcType); static void convertToFloat(void* dest, void* src, DataType srcType); static void convertToDouble(void* dest, void* src, DataType srcType); - static void convertToString(void* dest, void* src, DataType srcType, int length=0); + static void convertToString(void* dest, void* src, DataType srcType, int length=0,TDBInfo tdbname=mysql); static void convertToDate(void* dest, void* src, DataType srcType); static void convertToTime(void* dest, void* src, DataType srcType); static void convertToTimeStamp(void* dest, void* src, DataType srcType); @@ -148,9 +143,8 @@ class AllDataType static void* alloc(DataType type, int length =0); static DbRetVal strToValue(void *dest, char *src, DataType type, int length=0); - static int printVal(void *src, DataType type, int length); - - + static int printVal(void *src, DataType type, int length,int dbFlag=0); + inline static bool isValidFieldForAvg(DataType type); }; @@ -318,6 +312,9 @@ class Date { // The class a user would declare to hold date */ int parseFrom(const char *s); + static void changeToCsqlFormat(char *src); + + Date &operator++() { julianDate++; return *this; } Date &operator--() { julianDate--; return *this; } @@ -636,6 +633,8 @@ day". */ int parseTimeFrom(const char *s) { return time.parseFrom(s); } + + static void changeToCsqlFormat(char *src); int parseFrom(const char *s); friend int operator<(const TimeStamp &d1, const TimeStamp &d2); diff --git a/include/DataTypeInline.h b/include/DataTypeInline.h index 337bdf68..d98e73b0 100644 --- a/include/DataTypeInline.h +++ b/include/DataTypeInline.h @@ -1,20 +1,12 @@ /*************************************************************************** - * Copyright (C) 2007 by www.databasecache.com * - * Contact: praba_tuty@databasecache.com * * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * + * Copyright (C) Lakshya Solutions Ltd. All rights reserved. * * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU General Public License for more details. * - * * - ***************************************************************************/ + ***************************************************************************/ + #include #include +#include long AllDataType::size(DataType type, int length ) { if (type == typeInt) return sizeof(int); @@ -68,10 +60,9 @@ long AllDataType::size(DataType type, int length ) } return size; } -void AllDataType::copyVal(void* dest, void *src, DataType type, int length) +void AllDataType::cachecopyVal(void* dest, void *src, DataType type, int length,int dbFlag) { - //Performance optimization. putting likely case first - if (typeInt == type ) + if (typeInt == type ) { *(int*)dest = *(int*)src; return; @@ -80,7 +71,8 @@ void AllDataType::copyVal(void* dest, void *src, DataType type, int length) //null is always put at the last byte by insert //so using strcpy is safe //strcpy((char*)dest, (char*)src); - memcpy((char*)dest, (char*)src, length); + Util::trimRight((char*)src); + strncpy((char*)dest, (char*)src, length); //strncpy((char*)dest, (char*)src, length); //char *d =(char*)dest; //d[length-1] = '\0'; @@ -100,6 +92,52 @@ void AllDataType::copyVal(void* dest, void *src, DataType type, int length) }else if (typeLong == type) { *(long*)dest = *(long*)src; }else if (typeLongLong == type) { + if(1 == dbFlag) + convertToLongLong(dest, src,typeString); + else + *(long long*)dest = *(long long*)src; + }else if (typeByteInt == type) { + *(char*)dest = *(char*)src; + }else if (typeBinary == type) { + os::memcpy(dest, src, length); + }else if (typeComposite == type) { + os::memcpy(dest, src, length); + } + return; +} + +void AllDataType::copyVal(void* dest, void *src, DataType type, int length,int dbFlag) +{ + //Performance optimization. putting likely case first + if (typeInt == type ) + { + *(int*)dest = *(int*)src; + return; + }else if (typeString == type) + { + //null is always put at the last byte by insert + //so using strcpy is safe + //strcpy((char*)dest, (char*)src); + memcpy(dest, src, length); + //strncpy((char*)dest, (char*)src, length); + char *d =(char*)dest; + d[length-1] = '\0'; + return; + }else if (typeShort == type) { + *(short*)dest = *(short*)src; + }else if (typeDouble == type) { + *(double*)dest = *(double*)src; + }else if (typeTimeStamp == type) { + *(TimeStamp*)dest = *(TimeStamp*)src; + }else if (typeDate == type) { + *(Date*)dest = *(Date*)src; + }else if (typeFloat == type) { + *(float*)dest = *(float*)src; + }else if (typeTime == type) { + *(Time*)dest = *(Time*)src; + }else if (typeLong == type) { + *(long*)dest = *(long*)src; + }else if (typeLongLong == type) { *(long long*)dest = *(long long*)src; }else if (typeByteInt == type) { *(char*)dest = *(char*)src; @@ -110,6 +148,43 @@ void AllDataType::copyVal(void* dest, void *src, DataType type, int length) } return; } +void AllDataType::copyZeroVal(void *dest, DataType type, int length) +{ + if (typeInt == type ) + { + *(int*)dest = 0; + }else if (typeString == type) + { + char *d =(char*)dest; + d[0] = '\0'; + }else if (typeShort == type) { + *(short*)dest = 0; + }else if (typeDouble == type) { + *(double*)dest = 0; + }else if (typeTimeStamp == type) { + ((TimeStamp*)dest)->setDate(0,0,0); + ((TimeStamp*)dest)->setTime(0,0,0); + }else if (typeDate == type) { + ((Date*)dest)->set(0,0,0); + }else if (typeFloat == type) { + *(float*)dest = 0; + }else if (typeTime == type) { + ((Time*)dest)->set(0,0,0); + }else if (typeLong == type) { + *(long*)dest = 0; + }else if (typeLongLong == type) { + *(long long*)dest = 0; + }else if (typeByteInt == type) { + *(char*)dest = 0; + }else if (typeBinary == type) { + os::memset(dest, 0, length); + }else if (typeComposite == type) { + os::memset(dest, 0, length); + } + return; + +} + void AllDataType::addVal(void* dest, void *src, DataType type) { if (type == typeInt) @@ -163,18 +238,18 @@ bool AllDataType::compareVal(void *val1, void *val2, ComparisionOp op, if (OpEquals == op) { if (*(int*)val1 == *(int*)val2) return true; else return false; + }else if (OpLessThan == op) { + if (*(int*)val1 < *(int*)val2) return true; + else return false; + }else if (OpGreaterThan == op) { + if (*(int*)val1 > *(int*)val2) return true; + else return false; }else if (OpLessThanEquals == op) { if (*(int*)val1 <= *(int*)val2) return true; else return false; }else if (OpGreaterThanEquals == op) { if (*(int*)val1 >= *(int*)val2) return true; else return false; - }else if (OpGreaterThan == op) { - if (*(int*)val1 > *(int*)val2) return true; - else return false; - }else if (OpLessThan == op) { - if (*(int*)val1 < *(int*)val2) return true; - else return false; }else if (OpNotEquals == op) { if (*(int*)val1 != *(int*)val2) return true; else return false; @@ -227,3 +302,20 @@ ComparisionOp AllDataType::getComparisionOperator(char *str) op = OpInvalidComparisionOp; return op; } + +bool AllDataType::isValidFieldForAvg(DataType type) +{ + switch(type) { + case typeInt: case typeLong: case typeLongLong: case typeShort: + case typeByteInt: case typeDouble: case typeFloat: case typeDecimal: + //TODO::for porting + return true; + case typeDate: + case typeTime: + case typeTimeStamp: + case typeBinary: + case typeString: + default: + return false; + } +} diff --git a/include/Database.h b/include/Database.h index cd5adef7..6d97f85e 100644 --- a/include/Database.h +++ b/include/Database.h @@ -19,9 +19,11 @@ #include #include #include +#include class Bucket; class Transaction; + class DatabaseMetaData { public: @@ -53,6 +55,10 @@ class DatabaseMetaData Mutex dbTransTableMutex_; Mutex dbProcTableMutex_; + + // This mutex is taken for prepare in SqlStatement + Mutex dbPrepareStmtMutex_; + //To generate unique id UniqueID chunkUniqueID_; @@ -68,6 +74,7 @@ class DatabaseManagerImpl; class Table; class ProcInfo; class ThreadInfo; +class Transaction; class Database { @@ -75,8 +82,10 @@ class Database //Only DatabaseManager creates this object //initialization is done only in DatabaseManager during //create, delete, open, close database methods - Database() { metaData_ = NULL; procSlot = -1; } + Database() { metaData_ = NULL; procSlot = -1; fdChkpt = -1; thrInfoOffset=0;} DatabaseMetaData *metaData_; + int fdChkpt; + int thrInfoOffset; public: @@ -87,8 +96,17 @@ class Database Chunk* getSystemDatabaseChunk(int id); Transaction* getSystemDatabaseTrans(int slot); + inline void setThrInfoOffset() { + thrInfoOffset = os::alignLong(sizeof (DatabaseMetaData)) + + os::alignLong( MAX_CHUNKS * sizeof (Chunk)) + + os::alignLong( Conf::config.getMaxProcs()*sizeof(Transaction)); + } + inline ThreadInfo* getThreadInfo(int slot){ + if (!thrInfoOffset) setThrInfoOffset(); + size_t off = thrInfoOffset + slot * sizeof (ThreadInfo); + return (ThreadInfo*)(((char*) metaData_) + off); + } - ThreadInfo* getThreadInfo(int slot); //ThreadInfo* getThreadInfo(int pidSlot, int thrSlot); bool isLastThread(); @@ -113,6 +131,7 @@ class Database DatabaseMetaData* getMetaDataPtr() { return metaData_; } Page* getFirstPage(); Chunk* getHashIndexChunk(); + int getChkptfd() { return fdChkpt; } void setDatabaseID(int id); void setName(const char *name); @@ -124,6 +143,7 @@ class Database void setFirstPage(Page *ptr); void setHashIndexChunk(Chunk* chunk); void setUniqueChunkID(int id); + void setChkptfd(int fd) { fdChkpt = fd; } // Gets the free page // Each page is segmented by PAGE_SIZE, so it checks the pageInfo @@ -149,14 +169,22 @@ class Database DbRetVal getProcessTableMutex(bool procAccount = true); DbRetVal releaseProcessTableMutex(bool procAccount = true); + int initPrepareStmtMutex(); + DbRetVal getPrepareStmtMutex(bool procAccount = true); + DbRetVal releasePrepareStmtMutex(bool procAccount = true); + DbRetVal recoverMutex(Mutex *mut); int procSlot; void setProcSlot(int slot) { procSlot =slot;} //checks whether the ptr falls in the range of the database file size bool isValidAddress(void *ptr); + DbRetVal checkPoint(); + DbRetVal recoverUserDB(); + DbRetVal recoverSystemDB(); friend class DatabaseManagerImpl; friend class Table; + friend class TreeIndex; friend class HashIndex; }; diff --git a/include/DatabaseManager.h b/include/DatabaseManager.h index 8e7d5933..81e4c336 100644 --- a/include/DatabaseManager.h +++ b/include/DatabaseManager.h @@ -51,7 +51,7 @@ class DatabaseManager * @param name name of the table * @return DbRetVal */ - virtual Table* openTable(const char *name)=0; + virtual Table* openTable(const char *name, bool checkpkfk=true)=0; /** closes the table handle passed * @param table handle to the table @@ -61,7 +61,7 @@ class DatabaseManager /** Returns all the tables as list * @return List of table names */ - virtual List getAllTableNames()=0; + virtual List getAllTableNames(int *rv=0)=0; /** creates an index on the specified table.
* Create appropriate derived class object of IndexInitInfo based on the type of
@@ -75,6 +75,10 @@ class DatabaseManager * @param name index name */ virtual DbRetVal dropIndex(const char *name)=0; + virtual DbRetVal checkPoint()=0; + virtual DbRetVal recover()=0; + virtual DbRetVal createForeignKey(char *fkName,ForeignKeyInfo *info)=0; + virtual DbRetVal dropForeignKey(void *ctpr,bool trylock)=0; virtual ~DatabaseManager(){ } }; diff --git a/include/DatabaseManagerImpl.h b/include/DatabaseManagerImpl.h index c623b97b..fe077de3 100644 --- a/include/DatabaseManagerImpl.h +++ b/include/DatabaseManagerImpl.h @@ -78,7 +78,7 @@ class DatabaseManagerImpl : public DatabaseManager Chunk* createUserChunk(size_t size = 0); DbRetVal deleteUserChunk(Chunk *chunk); - + DbRetVal createHashIndex(const char *indName, const char *tableName, FieldNameList &fldList, int bucketSize, bool isUnique, bool isPrimary = false); DbRetVal createTreeIndex(const char *indName, const char *tableName, @@ -86,7 +86,7 @@ class DatabaseManagerImpl : public DatabaseManager void initHashBuckets(Bucket *buck, int bucketSize); DbRetVal dropIndexInt(const char *name, bool takeLock); - + DbRetVal writeSchemaFile(); public: Database* db() { return db_; } @@ -107,14 +107,15 @@ class DatabaseManagerImpl : public DatabaseManager DbRetVal closeDatabase(); - DbRetVal createTable(const char *name, TableDef &def); DbRetVal dropTable(const char *name); - Table* openTable(const char *name); + Table* openTable(const char *name, bool checkpkfk=true); void closeTable(Table *table); DbRetVal createIndex(const char *indName, IndexInitInfo *info); DbRetVal dropIndex(const char *name); - List getAllTableNames(); + DbRetVal createForeignKey(char *kfName,ForeignKeyInfo *info); + DbRetVal dropForeignKey(void *ctptr,bool trylock); + List getAllTableNames(int *rv=NULL); DbRetVal registerThread(); DbRetVal deregisterThread(); @@ -124,7 +125,13 @@ class DatabaseManagerImpl : public DatabaseManager void printDebugTransInfo(); void printDebugChunkInfo(); void printDebugProcInfo(); + int getNoOfPagesForTable(char *tblName); + DbRetVal loadRecords(char *tblName, char *buffer); + DbRetVal pasteRecords(char *tblName, void *buffer); + DbRetVal checkPoint(); + DbRetVal recover(); DbRetVal printIndexInfo(char *name); + void printTreeIndexNodeInfo(char *name,bool flag); friend class SessionImpl; }; #endif diff --git a/include/Debug.h b/include/Debug.h index 6107ffba..57565c7c 100644 --- a/include/Debug.h +++ b/include/Debug.h @@ -27,8 +27,6 @@ extern int DebugDM_Network; extern int DebugDM_Gateway; extern int DebugDM_Adapter; extern int DebugDM_SqlLog; -extern int DebugDM_ReplServer; -extern int DebugDM_ReplTool; extern int DebugDM_CacheServer; extern int DebugDM_TEST; extern int DebugDM_Warning; @@ -59,8 +57,6 @@ enum DebugModule DM_Gateway, DM_Adapter, DM_SqlLog, - DM_ReplServer, - DM_ReplTool, DM_CacheServer, DM_TEST, DM_Warning @@ -69,8 +65,8 @@ static char moduleNames[][20] = { "Alloc", "VariableAlloc", "Lock", "Trans", "UndoLog", "RedoLog", "Index", "HashIndex", "TreeIndex", "SysDb", "Db", "Table", "Predicate", "Iter", - "Procmgmt", "Network", "Gateway", "Adapter", "SqlLog", "ReplServer", - "ReplTool", "CacheServer", "TEST", "Warning" + "Procmgmt", "Network", "Gateway", "Adapter", "SqlLog", + "CacheServer", "TEST", "Warning" }; extern int printDebug1(int module, char *fname, int lineno, char *format, ...); diff --git a/include/ErrorType.h b/include/ErrorType.h index b3bd632a..4a25e946 100644 --- a/include/ErrorType.h +++ b/include/ErrorType.h @@ -1,18 +1,9 @@ /*************************************************************************** - * Copyright (C) 2007 by www.databasecache.com * - * Contact: praba_tuty@databasecache.com * * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * + * Copyright (C) Lakshya Solutions Ltd. All rights reserved. * * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU General Public License for more details. * - * * - ***************************************************************************/ + ***************************************************************************/ + #ifndef ERROR_TYPE_H #define ERROR_TYPE_H /** @@ -25,6 +16,7 @@ enum DbRetVal { + ErrNullValues = 1, //used in evaluate on null values OK = 0, /**< OK. No error. Operation succeded. */ ErrSysFatal = -1, ErrSysInit = -2, @@ -56,8 +48,11 @@ enum DbRetVal ErrSyntax = -28, ErrNotPrepared = -29, ErrNotEmpty = -30, - + ErrReadOnlyCache = -31, + ErrNoPeer = -32, ErrAutoIncUpdate = -33, + ErrForeignKeyInsert=-34, + ErrForeignKeyDelete=-35, // add new error type here ErrUnknown = -98, ErrWarning = -99, diff --git a/include/Field.h b/include/Field.h index 497237ff..a2a95fdd 100644 --- a/include/Field.h +++ b/include/Field.h @@ -1,18 +1,9 @@ /*************************************************************************** - * Copyright (C) 2007 by www.databasecache.com * - * Contact: praba_tuty@databasecache.com * * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * + * Copyright (C) Lakshya Solutions Ltd. All rights reserved. * * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU General Public License for more details. * - * * - ***************************************************************************/ + ***************************************************************************/ + #ifndef FIELD_H #define FIELD_H #include @@ -63,6 +54,7 @@ class FieldDef bool isDefault_; bool isUnique_; bool isAutoIncrement_; + long long autoVal_;//[DEFAULT_VALUE_BUF_LENGTH]; //TODO::width and scale }; @@ -122,6 +114,7 @@ class FieldList size_t getFieldLength(const char *fldName); DbRetVal getFieldInfo(const char *fldName, FieldInfo *&info); + void fillFieldInfo(int fldpos, void *info); int getTupleSize(); @@ -131,4 +124,27 @@ class FieldList return iter; } }; + +//The below struct should be same as Parser.h:FieldValue +//For performance reason and it is +//done such that storage does not have dependency on SQL +struct FieldInfoValue +{ + char fldName[IDENTIFIER_LENGTH]; + char *parsedString; + void *value; + int paramNo; // 0 ->not a param. It stores the param position + DataType type; + int aType; //assumes enum is always int + int length; + bool isNullable; + bool isAllocVal; + bool isInResSet; + + size_t offset; + bool isPrimary; + bool isUnique; + bool isAutoIncrement; +}; + #endif diff --git a/include/Index.h b/include/Index.h index 9ac9a072..6a042cc3 100644 --- a/include/Index.h +++ b/include/Index.h @@ -19,9 +19,8 @@ #include #include - -class Chunk; class Database; +class Chunk; class Transaction; class TableImpl; class CINDEX; @@ -48,16 +47,19 @@ class TreeNode void *min_; void *max_; int noElements_; - int balance_; TreeNode *next_; TreeNode *prev_; + int balance_; //Note::after this array of pointer to tuples are stored - + long long getTotalElements(); + TreeNode* locateNode(Database *db,TreeNode *iter, void *tuple, IndexInfo *indInfo,DbRetVal &rv); + TreeNode *locateNodeFromFirstLevel(TreeNode *ftnode,IndexInfo *indInfo,void *tuple,int *nodepos); + DbRetVal insertNodeIntoFirstLevel(Database * db, IndexInfo * indInfo, void* indexPtr, TreeNode * newNode,int nodepos); DbRetVal insert(Database *db, IndexInfo *info, void *indexPtr, void *tuple); - DbRetVal insert(int position, Database *db, IndexInfo *indInfo, CINDEX *iptr, void *tuple, TreeNode *iter); + DbRetVal insertRecordIntoNodeAndArrangeFirstLevel(Database * db, IndexInfo * indInfo, void* iptr, void * tuple, TreeNode * fstLevel,int nodepos); DbRetVal remove(Database *db, IndexInfo *info, void *indexPtr, void *tuple); DbRetVal update(Database *db, IndexInfo *info, void *indexPtr, void *tuple); - void displayAll(IndexInfo *indInfo, void *indexPtr); + void displayAll(); void displayAll(int offset); }; @@ -65,11 +67,18 @@ class BucketIter { HashIndexNode *iter; HashIndexNode *head; + bool isUnique; + bool recordsOver; public: - BucketIter(){} - BucketIter(HashIndexNode *head) { iter = head = head;} + BucketIter(){iter = head = NULL; + isUnique=false; recordsOver = false;} + void setHead(HashIndexNode *hd) { iter = head = hd; recordsOver=false;} + BucketIter(HashIndexNode *head) { iter = head = head; + isUnique=false; recordsOver = false;} + void setUnique() { isUnique = true; } + bool getUnique() { return isUnique; } HashIndexNode* next(); - void reset() { iter = head; } + void reset() { iter = head; recordsOver=false;} friend class BucketList; }; class BucketList @@ -87,7 +96,6 @@ class BucketList it.iter = head; return it; } - }; class HashIndex; class IndexInfo; @@ -111,7 +119,7 @@ class Index }; class HashIndex : public Index { - + //No members as it will be called by multiple threads public: DbRetVal insert(TableImpl *tbl, Transaction *tr, void *indexPtr, IndexInfo *info, void *tuple, bool undoFlag); DbRetVal remove(TableImpl *tbl, Transaction *tr, void *indexPtr, IndexInfo *info, void *tuple, bool undoFlag); @@ -123,14 +131,15 @@ class HashIndex : public Index class TreeIndex : public Index { - - TreeNode* locateNode(TreeNode *iter, void *tuple, IndexInfo *indInfo); + //No members as it will be called by multiple threads DbRetVal removeElement(Database *db, TreeNode *iter, void *tuple, HashIndexInfo *info); + void removeNode(Database *db,void *indexPtr,TreeNode *fltnode, TreeNode *node,int pos); public: DbRetVal insert(TableImpl *tbl, Transaction *tr, void *indexPtr, IndexInfo *info, void *tuple, bool undoFlag); DbRetVal remove(TableImpl *tbl, Transaction *tr, void *indexPtr, IndexInfo *info, void *tuple, bool undoFlag); DbRetVal update(TableImpl *tbl, Transaction *tr, void *indexPtr, IndexInfo *info, void *tuple, bool undoFlag); - + static DbRetVal insertLogicalUndoLog(Database *sysdb, void *info); + static DbRetVal deleteLogicalUndoLog(Database *sysdb, void *info); }; class TreeIter { @@ -145,17 +154,22 @@ class TreeIter bool firstCall; int nodeOffset; bool recordsOver; - + void *fstLTnode; void* locateNode(); void* locateElement(); + int procSlot; + bool isUnique; public: - TreeIter(){} - TreeIter(TreeNode *hd) { iter = head = hd; firstCall = true; recordsOver=false;} + TreeIter(){ iter=head=NULL; searchKey=fstLTnode=NULL;isUnique = false;} + TreeIter(TreeNode *hd,void *fTnode, int slot ) { fstLTnode = fTnode; iter = head = hd; firstCall = true; recordsOver=false; procSlot=slot; isUnique=false;} + void set(TreeNode *hd,void *fTnode, int slot ) { fstLTnode = fTnode; iter = head = hd; firstCall = true; recordsOver=false; procSlot=slot; isUnique=false;} void setSearchKey(void *key, ComparisionOp cop, bool ascending = true) { searchKey = key; op = cop; asc =ascending; } + void setUnique() { isUnique = true; } + bool getUnique() { return isUnique; } void setFldOffset(int off) { fldOffset = off; } void setTypeLength(DataType t, int l) { type =t ; length =l; } void* prev(); @@ -163,7 +177,7 @@ class TreeIter void nextNode(); void* getFirstElement(); void* getLastElement(); - void reset() { iter = head; firstCall = true; recordsOver=false; } + void reset();// { iter = head; firstCall = true; recordsOver=false; } }; enum IndexIntType diff --git a/include/Info.h b/include/Info.h index ca300ea5..052c75c1 100644 --- a/include/Info.h +++ b/include/Info.h @@ -1,24 +1,74 @@ /*************************************************************************** - * Copyright (C) 2007 by www.databasecache.com * - * Contact: praba_tuty@databasecache.com * * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * + * Copyright (C) Lakshya Solutions Ltd. All rights reserved. * * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU General Public License for more details. * - * * - ***************************************************************************/ + ***************************************************************************/ + #ifndef INFO_H #define INFO_H #include #include #include +#ifndef AGGTYPE +enum AggType +{ + AGG_MIN = 1, + AGG_MAX, + AGG_SUM, + AGG_AVG, + AGG_COUNT, + AGG_UNKNOWN +}; +#define AGGTYPE +#endif + +struct IndexInfoForDriver +{ + char tableName[IDENTIFIER_LENGTH]; + char fieldName[IDENTIFIER_LENGTH]; + char indexName[IDENTIFIER_LENGTH]; + int type; + int position; + int pageUsed; + bool isUnique; + bool isPrimary; +}; + +class DataTypeInfo +{ + public: + char name[IDENTIFIER_LENGTH]; + int type; + int precision; + bool autoIncrement; +}; + +class ForeignKeyMetadata +{ + public: + char pkTableName[IDENTIFIER_LENGTH]; + char pkColName[IDENTIFIER_LENGTH]; + char fkTableName[IDENTIFIER_LENGTH]; + char fkColName[IDENTIFIER_LENGTH]; + short keySeq; + short updateRule; + short deleteRule; +}; + +enum ResultSetPlan +{ + Normal = 0, + GetTables, + GetColumns, + GetIndexes, + GetPriIndex, + GetCatalogs, + GetTableType, + GetDataType, + GetImportKey, + GetExportKey +}; class FieldNameNode; @@ -87,7 +137,7 @@ class TableDef */ int addField(const char *name, DataType type = typeUnknown, size_t length = 0, const void *defaultValue = 0, - bool notNull = false,bool autoIn = false); + bool notNull = false, bool autoIn = false); /** removes a field from the schema definition * @param name field name @@ -119,11 +169,18 @@ class FieldInfo size_t length; size_t offset; char defaultValueBuf[DEFAULT_VALUE_BUF_LENGTH]; + AggType aType; bool isNull; bool isPrimary; bool isDefault; bool isUnique; bool isAutoIncrement; + FieldInfo() + { + fldName[0] = '\0'; type = typeUnknown; length = 0; offset = 0; + defaultValueBuf[0]='\0'; aType = AGG_UNKNOWN; isNull = false; + isPrimary = isDefault = isUnique = isAutoIncrement = false; + } }; @@ -169,4 +226,14 @@ class HashIndexInitInfo : public IndexInitInfo int bucketSize; /** #include #include + +#ifndef JOINTYPE +#define JOINTYPE enum JoinType { INNER_JOIN = 1, - RIGHT_JOIN, LEFT_JOIN, + RIGHT_JOIN, FULL_JOIN, UNKNOWN_JOIN }; +#endif + class JoinProjFieldInfo { public: @@ -83,6 +88,12 @@ class JoinTableImpl:public Table Table *leftTableHdl; Table *rightTableHdl; bool availableLeft; + bool isFirstFetch; + bool isReturnNull; + bool isOuterJoin; + bool isLeftRecOver; + bool isFirstCall; + bool leftSideFail; JoinType jType; ListIterator rsIter; @@ -91,6 +102,7 @@ class JoinTableImpl:public Table DbRetVal copyValuesToBindBuffer(void *tuple); JoinCondition jCondition; Predicate *pred; + List predList; public: JoinTableImpl(); @@ -100,7 +112,7 @@ class JoinTableImpl:public Table void setTable(Table *left, Table *right) { leftTableHdl = left; rightTableHdl = right; } - int getFldPos(char *name){} + int getFldPos(char *name){ return 0;} DbRetVal closeScan(); void setJoinType(JoinType type) { jType = type; } //binding @@ -111,9 +123,10 @@ class JoinTableImpl:public Table void setCondition(Condition *p) { if (p) pred = p->getPredicate(); else pred = NULL;} - DbRetVal markFldNull(const char *name){} - DbRetVal markFldNull(int colpos){} + DbRetVal markFldNull(const char *name){ return ErrBadCall;} + DbRetVal markFldNull(int colpos){ return ErrBadCall;} bool isFldNull(const char *name); + bool isFldNullInt(const char *name); bool isFldNull(int colpos){return false;} void clearFldNull(const char *name){} void clearFldNull(int colpos){} @@ -128,13 +141,16 @@ class JoinTableImpl:public Table DbRetVal lock(bool shared) { return ErrBadCall; } DbRetVal unlock(){ return ErrBadCall; } DbRetVal setUndoLogging(bool flag) { return ErrBadCall; } - void printSQLIndexString(){ }; + void printSQLIndexString(FILE *fp, int fd){ }; + void printSQLForeignString(){} List getFieldNameList(); char* getName() { return NULL; } - + void *fetchRightFail(); + DbRetVal compact(){ return OK;} //bool evaluate(); DbRetVal execute(); void* fetch(); + void* fetchInt(); void* fetch(DbRetVal &rv); void* fetchNoBind(); void* fetchNoBind(DbRetVal &rv); @@ -143,7 +159,7 @@ class JoinTableImpl:public Table long numTuples(); void printInfo(); void *getBindFldAddr(const char *name); - + bool isFKTable(){return false;} bool isTableInvolved(char *tblName); bool pushPredicate(Predicate *pred); void setPredicate(Predicate *pred); diff --git a/include/Lock.h b/include/Lock.h index 5535595a..0dfe8e86 100644 --- a/include/Lock.h +++ b/include/Lock.h @@ -24,11 +24,11 @@ class Transaction; class LockInfo { public: - signed int noOfReaders_; + int noOfReaders_; //-1 indicates write lock is taken - unsigned char waitReaders_; - unsigned char waitWriters_; + int waitReaders_; + int waitWriters_; LockInfo() { noOfReaders_ = 0; waitReaders_ = 0; waitWriters_ = 0; } }; @@ -80,7 +80,8 @@ class LockManager private: LockHashNode* allocLockNode(LockInfo &info, void *tuple, DbRetVal *rv); - void deallocLockNode(LockHashNode *head, Bucket *bucket); + DbRetVal deallocLockNode(LockHashNode *head, Bucket *bucket); + void deallocLockNode(LockHashNode *head); Bucket* getLockBucket(void *tuple); public: diff --git a/include/Makefile.am b/include/Makefile.am dissimilarity index 94% index e6d8a724..f2dd9884 100644 --- a/include/Makefile.am +++ b/include/Makefile.am @@ -1,9 +1,7 @@ -INCLUDES = -METASOURCES = AUTO -include_HEADERS = Allocator.h CatalogTables.h CSql.h Database.h \ - DatabaseManager.h DatabaseManagerImpl.h DataType.h Debug.h ErrorType.h Field.h Index.h \ - Info.h Lock.h Mutex.h NanoTimer.h os.h Predicate.h PredicateImpl.h Session.h \ - SessionImpl.h Table.h TableImpl.h Transaction.h UserManager.h UserManagerImpl.h \ - build.h Config.h Process.h Util.h Globals.h SqlConnection.h SqlStatement.h \ - AbsSqlConnection.h AbsSqlStatement.h SqlFactory.h sqlext.h sql.h sqltypes.h sqlucode.h \ - CacheTableLoader.h AggTableImpl.h JoinTableImpl.h Expression.h DataTypeInline.h +INCLUDES = +METASOURCES = AUTO +include_HEADERS = DataType.h Debug.h ErrorType.h Field.h \ + Info.h Mutex.h NanoTimer.h os.h Session.h \ + build.h Config.h Util.h DataTypeInline.h \ + AbsSqlConnection.h AbsSqlStatement.h SqlFactory.h \ + sqlext.h sql.h sqltypes.h sqlucode.h diff --git a/include/Mutex.h b/include/Mutex.h index cf2833f8..068a3f9b 100644 --- a/include/Mutex.h +++ b/include/Mutex.h @@ -7,10 +7,10 @@ #ifndef MUTEX_H #define MUTEX_H #include -typedef unsigned int Lock; +typedef int Lock; class Mutex { - int noOfRead; + #if defined(sparc) || defined(i686) || defined (x86_64) Lock lock; #else @@ -21,13 +21,21 @@ class Mutex Mutex(); int init(); int init(char *name); - int tryLock(int tries=0, int waitmsecs=0,bool share=false); - int getLock(int procSlot, bool procAccount=true,bool share=false); - int releaseLock(int procSlot, bool procAccount=true,bool share=false); + int tryLock(int tries=0, int waitmsecs=0); + int getLock(int procSlot, bool procAccount=true); + int releaseLock(int procSlot, bool procAccount=true); + int tryShareLock(int tries=0, int waitmsecs=0,bool share=false,bool isDelete=false); + int getShareLock(int procSlot, bool procAccount=true); + int getExclusiveLock(int procSlot, bool procAccount=true,bool isDelete=false); + int releaseShareLock(int procSlot, bool procAccount=true); int destroy(); int recoverMutex(); static int CASL(long *ptr, long oldVal, long newVal); static int CAS(int *ptr, int oldVal, int newVal); + int getLockVal(){ return lock; } + void print() { + printf("Mutex: %d %s\n", lock, name); + } }; #endif diff --git a/include/NanoTimer.h b/include/NanoTimer.h index f6e93ba5..f31dc5f0 100644 --- a/include/NanoTimer.h +++ b/include/NanoTimer.h @@ -1,18 +1,9 @@ /*************************************************************************** - * Copyright (C) 2007 by www.databasecache.com * - * Contact: praba_tuty@databasecache.com * * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * + * Copyright (C) Lakshya Solutions Ltd. All rights reserved. * * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU General Public License for more details. * - * * - ***************************************************************************/ + ***************************************************************************/ + #ifndef NANO_TIMER_H #define NANO_TIMER_H #include @@ -43,6 +34,7 @@ class NanoTimer } long long last() { return last_; } long long avg() { return total/count; } + long long sum() { return total; } long long min() { return min_; } long long max() { return max_; } }; diff --git a/include/Network.h b/include/Network.h index 6768eaaf..a0cf72a9 100644 --- a/include/Network.h +++ b/include/Network.h @@ -31,6 +31,7 @@ ASYNC=2 }; */ + enum NetworkPacketType { NW_PKT_PREPARE =1, @@ -39,6 +40,7 @@ enum NetworkPacketType NW_PKT_FREE =4, NW_PKT_CONNECT =5, NW_PKT_DISCONNECT =6, + SQL_NW_PKT_EXECDIRECT=100, SQL_NW_PKT_CONNECT=101, SQL_NW_PKT_PREPARE=102, SQL_NW_PKT_PARAM_METADATA=103, @@ -51,13 +53,19 @@ enum NetworkPacketType SQL_NW_PKT_FREE=110, SQL_NW_PKT_DISCONNECT=111, SQL_NW_PKT_SHOWTABLES=112, + SQL_NW_PKT_ISTABLEPRESENT=113, + SQL_NW_PKT_GETRECORDS=114, + SQL_NW_PKT_LOADRECORDS=115, }; class ResponsePacket { public: ResponsePacket() - { stmtID = 0; retVal = 0; isSelect = false; rows=0; } + { + stmtID = 0; retVal = 0; errRetVal = OK; isSelect = false; rows=0; + errorString[0] = '\0'; + } ~ResponsePacket() { } int retVal; // will include for fetch end flag, params flag, proj flag DbRetVal errRetVal; @@ -101,6 +109,7 @@ class NetworkClient { void setEntryption(bool encr) { encrypt=encr;} void setConnectFlag(bool flag) { isConnectedFlag=flag;} bool isConnected() { return isConnectedFlag; } + void setIsConnectedFlag(bool fl) { isConnectedFlag = fl; } void setCacheClient() { cacheClient = true; } bool isCacheClient() { return cacheClient; } }; @@ -145,6 +154,7 @@ class NetworkTable { NetworkClient* nwClient; public: + NetworkTable() { nwClient = NULL; } ~NetworkTable(); DbRetVal initialize(); void destroy(){} @@ -207,8 +217,9 @@ class BasePacket{ class PacketPrepare:public BasePacket { public: - PacketPrepare() { buffer=NULL; bufferSize =0; noParams = 0; - type = NULL; length = NULL; pktType = NW_PKT_PREPARE;} + PacketPrepare() { buffer=NULL; bufferSize =0; noParams = 0; stmtString = NULL; + stmtID = 0; stmtLength = 0; type = NULL; length = NULL; + pktType = NW_PKT_PREPARE;} ~PacketPrepare() { free(buffer); bufferSize = 0; buffer = NULL; } int stmtID; int syncMode; @@ -223,7 +234,7 @@ class PacketPrepare:public BasePacket class PacketFree : public BasePacket { public: - PacketFree() { buffer=NULL; bufferSize =0; pktType = NW_PKT_FREE;} + PacketFree() { buffer=NULL; bufferSize =0; stmtID = 0; pktType = NW_PKT_FREE;} ~PacketFree() { free(buffer); bufferSize = 0; buffer = NULL; } int stmtID; DbRetVal marshall(); @@ -233,7 +244,9 @@ class PacketFree : public BasePacket class PacketExecute : public BasePacket { public: - PacketExecute() { buffer=NULL; bufferSize =0; pktType = NW_PKT_EXECUTE;} + PacketExecute() { buffer=NULL; bufferSize =0; + stmtID= 0; noParams= 0; paramValues = NULL; + pktType = NW_PKT_EXECUTE;} ~PacketExecute() { free(buffer); bufferSize = 0; buffer = NULL; } //TODO::need to free paramvalues based on marshall or unmarshall @@ -277,12 +290,17 @@ class SqlPacketConnect : public BasePacket bufferSize = 0; pktType = SQL_NW_PKT_CONNECT; } - ~SqlPacketConnect() { free(buffer); bufferSize = 0; buffer = NULL; } + ~SqlPacketConnect() { free(buffer); bufferSize = 0; buffer = NULL; + } char userName[IDENTIFIER_LENGTH]; char passWord[IDENTIFIER_LENGTH]; char sqlApiImplType; void setConnParam(char *user, char *pass, char tp) - { strcpy(userName, user); strcpy(passWord, pass); sqlApiImplType = tp; } + { + strcpy(userName, user); + strcpy(passWord, pass); + sqlApiImplType = tp; + } DbRetVal marshall(); DbRetVal unmarshall(); }; @@ -291,7 +309,8 @@ class SqlPacketPrepare : public BasePacket { public: SqlPacketPrepare() - { buffer=NULL; bufferSize =0; pktType = SQL_NW_PKT_PREPARE;} + { buffer=NULL; bufferSize =0; + stmtString = NULL; stmtLength = 0; pktType = SQL_NW_PKT_PREPARE; } ~SqlPacketPrepare() { free(buffer); bufferSize = 0; buffer = NULL; } int stmtLength; char *stmtString; @@ -302,8 +321,8 @@ class SqlPacketPrepare : public BasePacket class SqlPacketExecute : public BasePacket { public: - SqlPacketExecute();// { buffer=NULL; bufferSize =0; pktType = SQL_NW_PKT_EXECUTE;} - ~SqlPacketExecute();// { free(buffer); bufferSize = 0; buffer = NULL; paramValues = NULL; noParams = 0; } + SqlPacketExecute(); + ~SqlPacketExecute(); //TODO::need to free paramvalues based on marshall or unmarshall int stmtID; @@ -328,7 +347,7 @@ class SqlPacketParamMetadata : public BasePacket public: SqlPacketParamMetadata() { buffer=NULL; bufferSize =0; noParams = 0; - data = NULL; pktType = SQL_NW_PKT_PARAM_METADATA;} + stmtID= 0; data = NULL; pktType = SQL_NW_PKT_PARAM_METADATA;} ~SqlPacketParamMetadata() { free(buffer); bufferSize = 0; buffer = NULL; } int stmtID; int noParams; @@ -341,7 +360,7 @@ class SqlPacketProjMetadata : public BasePacket { public: SqlPacketProjMetadata() { buffer=NULL; bufferSize =0; noProjs = 0; - data = NULL; pktType = SQL_NW_PKT_PROJ_METADATA; } + data = NULL; stmtID= 0; pktType = SQL_NW_PKT_PROJ_METADATA; } ~SqlPacketProjMetadata() { free(buffer); bufferSize = 0; buffer = NULL; } int stmtID; int noProjs; @@ -354,7 +373,7 @@ class SqlPacketFetch : public BasePacket { public: SqlPacketFetch() { buffer=NULL; bufferSize = 0; - pktType = SQL_NW_PKT_FETCH; } + stmtID= 0; pktType = SQL_NW_PKT_FETCH; } ~SqlPacketFetch() { free(buffer); bufferSize = 0; buffer = NULL; } int stmtID; DbRetVal marshall(); @@ -364,7 +383,7 @@ class SqlPacketFetch : public BasePacket class SqlPacketFree : public BasePacket { public: - SqlPacketFree() { buffer=NULL; bufferSize = 0; + SqlPacketFree() { buffer=NULL; stmtID=0;bufferSize = 0; pktType = SQL_NW_PKT_FREE; } ~SqlPacketFree() { free(buffer); bufferSize = 0; buffer = NULL; } int stmtID; @@ -377,9 +396,12 @@ class SqlPacketResultSet : public BasePacket public: SqlPacketResultSet() { buffer=NULL; bufferSize = 0; noProjs = 0; nullInfo = NULL; projValues=NULL; - pktType = SQL_NW_PKT_RESULT_SET; } - ~SqlPacketResultSet() { free(buffer); bufferSize = 0; buffer = NULL; - nullInfo = NULL; } + hasData=0; nullInfoLen=0; + pktType = SQL_NW_PKT_RESULT_SET; } + ~SqlPacketResultSet() { free(buffer); + bufferSize = 0; buffer = NULL; + if (projValues) delete[] projValues; + nullInfo = NULL; } int hasData; int noProjs; int nullInfoLen; @@ -396,7 +418,7 @@ class SqlPacketShowTables : public BasePacket { public: SqlPacketShowTables() { buffer = NULL; bufferSize = 0; data = NULL; - pktType= SQL_NW_PKT_SHOWTABLES; } + numOfTables=0; pktType= SQL_NW_PKT_SHOWTABLES; } ~SqlPacketShowTables() { free(buffer); bufferSize = 0; buffer = NULL; } int numOfTables; void *data; @@ -404,6 +426,44 @@ class SqlPacketShowTables : public BasePacket DbRetVal unmarshall(); }; +class SqlPacketIsTablePresent : public BasePacket +{ + public: + SqlPacketIsTablePresent() { buffer = NULL; bufferSize = 0; + tblName[0] = '\0'; pktType = SQL_NW_PKT_ISTABLEPRESENT; } + ~SqlPacketIsTablePresent() { free(buffer); bufferSize = 0; buffer = NULL; } + char tblName[IDENTIFIER_LENGTH]; + void setTableName(char *tName) { strcpy(tblName, tName); } + DbRetVal marshall(); + DbRetVal unmarshall(); +}; + +class SqlPacketGetRecords : public BasePacket +{ + public: + SqlPacketGetRecords() { buffer = NULL; bufferSize = 0; pages=0; + tblName[0] = '\0'; pktType = SQL_NW_PKT_GETRECORDS; } + ~SqlPacketGetRecords() { free(buffer); bufferSize = 0; buffer = NULL; } + char tblName[IDENTIFIER_LENGTH]; + int pages; + void setTableName(char *tName) { strcpy(tblName, tName); } + void setPages(int pgs) { pages = pgs; } + DbRetVal marshall(); + DbRetVal unmarshall(); +}; + +class SqlPacketLoadRecords : public BasePacket +{ + public: + SqlPacketLoadRecords() { buffer = NULL; bufferSize = 0; pages = 0; + pktType = SQL_NW_PKT_LOADRECORDS; } + ~SqlPacketLoadRecords() { free(buffer); bufferSize = 0; buffer = NULL; } + int pages; + void setPages(int pgs) { pages = pgs; } + DbRetVal marshall(); + DbRetVal unmarshall(); +}; + class NetworkStmt { public: @@ -414,6 +474,7 @@ class NetworkStmt List paramList; List projList; List tableNamesList; // will be populated only for show tables query + NetworkStmt() { srcNetworkID=0; stmtID=0; stmt=NULL; type = UnknownStatement; } }; class NetworkServer @@ -422,14 +483,14 @@ class NetworkServer int sockfd; int port; public: + NetworkServer() { port =0; sockfd= -1;} void setServerPort(int p) { port = p; } int getSocket(){ return sockfd; } virtual DbRetVal start()=0; virtual DbRetVal stop()=0; virtual DbRetVal handleClient()=0; - virtual DbRetVal send(NetworkPacketType type, char *buf, int len)=0; - }; + class UDPServer : public NetworkServer { struct sockaddr_in clientAddress; @@ -438,7 +499,6 @@ class UDPServer : public NetworkServer DbRetVal start(); DbRetVal stop(); DbRetVal handleClient(); - DbRetVal send(NetworkPacketType type, char *buf, int len) { }//dont know what to write }; class TCPServer : public NetworkServer @@ -450,7 +510,6 @@ class TCPServer : public NetworkServer DbRetVal start(); DbRetVal stop(); DbRetVal handleClient(); - DbRetVal send(NetworkPacketType type, char *buf, int len); }; #endif diff --git a/include/Parser.h b/include/Parser.h index 0f9f3228..61bb9b4d 100644 --- a/include/Parser.h +++ b/include/Parser.h @@ -24,6 +24,8 @@ #include #include #include +#ifndef STMT_TYPE +#define STMT_TYPE enum StatementType { UnknownStatement, @@ -34,9 +36,14 @@ enum StatementType CreateTableStatement, DropTableStatement, CreateIndexStatement, - DropIndexStatement + DropIndexStatement, + CacheTableStatement, + CompactTableStatement, + CopyTableStatement, + MetaStatement, + UserStatement }; - +#endif struct FieldValue { char fldName[IDENTIFIER_LENGTH]; @@ -44,9 +51,15 @@ struct FieldValue void *value; int paramNo; // 0 ->not a param. It stores the param position DataType type; + AggType aType; int length; bool isNullable; bool isAllocVal; + bool isInResSet; + size_t offset; + bool isPrimary; + bool isUnique; + bool isAutoIncrement; }; @@ -56,6 +69,7 @@ struct ConditionValue void *value; int paramNo; // 0 ->not a param. It stores the param position DataType type; + AggType aType; int length; bool opLike; bool isNullable; @@ -66,20 +80,41 @@ struct FieldName { char fldName[IDENTIFIER_LENGTH]; AggType aType; //used only in case of select projection + char aliasFldName[IDENTIFIER_LENGTH]; FieldName() { strcpy(fldName,""); + strcpy(aliasFldName,""); aType = AGG_UNKNOWN; } }; struct TableName { char tblName[IDENTIFIER_LENGTH]; + char aliasName[IDENTIFIER_LENGTH]; TableName() { strcpy(tblName,""); + strcpy(aliasName,""); } }; +#ifndef JOINTYPE +#define JOINTYPE +enum JoinType +{ + INNER_JOIN = 1, + RIGHT_JOIN, + LEFT_JOIN, + FULL_JOIN, + UNKNOWN_JOIN +}; +#endif + +struct JoinTypeNode +{ + JoinType jType; + JoinTypeNode(){ jType = INNER_JOIN; } +}; struct UpdateFieldValue { @@ -93,27 +128,48 @@ struct UpdateFieldValue int paramNo; }; +enum UserNodeType +{ + CREATEUSER=0, + DROPUSER, + ALTERUSER +}; +class UserNode +{ + public: + char userName[IDENTIFIER_LENGTH]; + char passName[IDENTIFIER_LENGTH]; + UserNodeType type; +}; class ParsedData { private: char tblName[IDENTIFIER_LENGTH]; char idxName[IDENTIFIER_LENGTH]; - + char pkTblName[IDENTIFIER_LENGTH];//This is also used as DSN name when cachestatement executed and copy table statemnet StatementType stmtType; + bool isDistinct; + bool isExplain; int paramCounter; List tableNameList; + List joinTypeList; //holds pointer to field names. used in insert to store field name list //and for projection list of select //also used to store primary or unique key fields in create statement List fieldNameList; List groupFieldNameList; + + List havingFieldNameList; + + List orderFieldNameList; //holds pointer to condition values. List conditionValueList; + List secondaryIndexFieldList; //holds pointer to field values. used in insert to store field values //used in update to store the current value returned by fetch().This gets replaced @@ -131,70 +187,152 @@ class ParsedData //stores the where clause condition for SELECT, UPDATE and DELETE Condition predicate; + Condition havingPredicate; + List predList; //stores field information in CREATE TABLE FieldDef fldDef; - + //User Management + UserNode *userNode; //stores list of fields for CREATE TABLE FieldList creFldList; + //Foreign Key storage + List fkFieldNameList; + List pkFieldNameList; + List foreignKeyList; + bool isForeign; + bool shouldCreateTbl; //stores index information bool isUnique; bool isPrimary; + bool isAutoIncrement; IndexType indexType; + ResultSetPlan plan; int bucketSize; - bool isAutoIncrement; + //Cache table + char hcondition[IDENTIFIER_LENGTH]; + char vcondition[IDENTIFIER_LENGTH]; + bool hCondFld; + bool vCondFld; + bool pkFld; + bool forceOption; + bool direct; + bool uncache; + bool noschema; + bool dsn; + int limit; + int offset; public: - ParsedData() { paramCounter = 0; stmtType = UnknownStatement; - isUnique = false; isPrimary = false; indexType = hashIndex; bucketSize=0; isAutoIncrement=false;} + ParsedData() { limit = 0; offset= 0; paramCounter = 0; stmtType = UnknownStatement; isDistinct = false; isExplain=false; + isUnique = false; isPrimary = false; isAutoIncrement=false ;indexType = hashIndex; plan = Normal; bucketSize=0; isForeign=false; hCondFld=false; vCondFld=false;pkFld=false;forceOption=false; direct=false; uncache=false; noschema=false; dsn=false; + shouldCreateTbl=false; userNode = NULL; + } + void createUserNode(char *name, char *password); + char *getUserName() { return userNode->userName; } + char *getPassWord() { return userNode->passName; } + UserNodeType getUserType() { return userNode->type; } + void dropUserNode(char *name); + void alterUserNode(char *name, char *password); + + void setCreateTbl(){ shouldCreateTbl=true; } + bool getCreateTbl(){ return shouldCreateTbl; } + + void setDSN(bool flag){ dsn = flag;} + bool getDSN(){ return dsn; } + void setNoSchema(bool flag){ noschema = flag; } + bool getNoSchema(){return noschema;} + char *getHCondition(){return hcondition;} + char *getVCondition(){return vcondition;} + void setHCondition(char *fld){ strcpy(hcondition,fld);} + void setVCondition(char *fld){ strcpy(vcondition,fld);} + void setHCondFld(bool flag){hCondFld = flag;} + bool getHCondFld(){return hCondFld;} + void setVCondFld(bool flag){vCondFld = flag;} + bool getVCondFld(){return vCondFld;} + void setPkFld(bool flag){pkFld = flag;} + bool getPkFld(){return pkFld;} + void setDirect(bool flag){direct=flag;} + bool getDirect(){return direct;} + void setUnCache(bool flag){uncache=flag;} + bool getUnCache(){return uncache;} + void setLimit(int l, int o) { limit =l; offset=o; } + int getLimit(){ return limit; } + int getOffset(){ return offset; } + + int getBucketSize(){return bucketSize; }; - void setBucketSize(int bucket){ bucketSize = bucket; }; + void setBucketSize(int bucket){ bucketSize = bucket; }; void setStmtType(StatementType type) { stmtType = type; } void setTableName(char *name) { strcpy(tblName, name); } void setIndexName(char *name) { strcpy(idxName, name); } - + void setPKTableName(char *name){strcpy(pkTblName, name); } + void setResultSetPlan(ResultSetPlan pl){plan = pl;} + ResultSetPlan getResultSetPlan(){return plan;} char* getTableName() { return tblName; } char* getIndexName() { return idxName; } + char* getPKTableName(){ return pkTblName;} DbRetVal setAutoIncreament(bool flag); bool getAutoIncreament(); - void insertValue(char *value); void insertInValue(char *value); // third parameter is to avoid conflict between '?' between like operand and parameterized value in sql statement. // eg: select * from t1 where f1 = ? and f2 like '_ti%'; // _ is converted to ? before it is processed - void** insertCondValueAndGetPtr(char *fName, char *value, bool opLike=false); + void** insertCondValueAndGetPtr(char *fName, char *value, bool opLike=false, AggType atp=AGG_UNKNOWN, bool isInHaving=false); void insertCondValue(char *fldName); //For Predecate t1.f1=t2.f1 void insertUpdateValue(char *fldName, char *value); void insertField(char *fName, AggType aggType= AGG_UNKNOWN); + void insertFieldAlias(char *name); void insertGroupField(char *fName); + void insertOrderByField(char *fName, bool isDesc= false); void clearFieldNameList(); void insertTableName(char *value); - - - Predicate* insertPredicate(char *fldName, ComparisionOp op, void** value); - Predicate* insertPredicate(char *fldName1, ComparisionOp op, char *fldName2); + void insertJoinType(JoinType jType); + void insertTableName(char *value, char *alias); + void insertFKField(char *fkName); + void insertPKField(char *pkName); + void insertForeignKeyList(); + Predicate* insertPredicate(char *fldName, ComparisionOp op, void** value, AggType aggType = AGG_UNKNOWN); + Predicate* insertPredicate(char *fldName, ComparisionOp op, char *fldName1); Predicate* insertBetPredicate(char *fldName, ComparisionOp op1, void **value1, ComparisionOp op2, void **value2); Predicate* insertPredicate(Predicate *p1, LogicalOp op, Predicate *p2 = NULL); + Predicate* insertNullPredicate(char *fName, ComparisionOp op,bool nullFlag); void setCondition(Predicate *pred) { - //No body is deleting memory allocated during condition::setTerm for PredicateImpl - //have list in this pared data and delete it during reset predicate.setPredicate(pred); } + void setHavingCondition(Predicate *pred) + { + havingPredicate.setPredicate(pred); + } Condition* getCondition() { return &predicate; } + Condition* getHavingCondition() { return &havingPredicate; } void insertFieldValue(FieldValue *newVal) { fieldValueList.append(newVal); } List getFieldNameList() { return fieldNameList; } List getGroupFieldNameList() { return groupFieldNameList; } + List getHavingFieldNameList() { return havingFieldNameList; } + List getOrderFieldNameList() { return orderFieldNameList; } List getConditionValueList() { return conditionValueList; } List getFieldValueList() { return fieldValueList; } List getInValueList() { return inValueList; } List getUpdateFieldValueList() { return updFldValList; } List getTableNameList() { return tableNameList; } + List getJoinTypeList() { return joinTypeList; } List getSecondaryIndexFieldList() { return secondaryIndexFieldList; } + List getForeignKeyList(){ return foreignKeyList;} + List getPkFieldNameList(){return pkFieldNameList;} + List getFkFieldNameList(){return fkFieldNameList;} + + void setDistinct() { isDistinct = true;} + bool getDistinct() { return isDistinct; } + void setExplain() { isExplain=true; } + bool getExplain() { return isExplain; } + + void setFldName(char *name); void setFldType(DataType type); DataType getFldType(); @@ -202,7 +340,7 @@ class ParsedData void setDefaultValue(char * value); //void setFldDefaultValue -- will need two parametersers, check how u want to pass default value. void setFldNotNull(bool notNull); - + void setForeign(bool foreign){ isForeign = foreign; } void setUnique(bool unique){ isUnique = unique; } void setPrimary(bool primary) { isPrimary = primary; } void setIndexType (IndexType type) { indexType = type; } @@ -222,6 +360,7 @@ class ParsedData char *getFldName(); void setAutoFldName(char *fldName); void reset(); + void init(); }; diff --git a/include/Predicate.h b/include/Predicate.h index 6e5f586a..38fd7425 100644 --- a/include/Predicate.h +++ b/include/Predicate.h @@ -19,6 +19,20 @@ #include class PredicateImpl; class Predicate; +#ifndef AGGTYPE +enum AggType +{ + AGG_MIN = 1, + AGG_MAX, + AGG_SUM, + AGG_AVG, + AGG_COUNT, + AGG_UNKNOWN +}; +#define AGGTYPE +#endif + + /** * @class Condition * @@ -77,7 +91,8 @@ class Condition * @param op comparision operator(=,!=, >,<,>=,<=) * @param opnd** pointer to pointer to the value */ - void setTerm(const char* fName1, ComparisionOp op, void **opnd); + void setTerm(const char* fName1, ComparisionOp op, void **opnd ); + void setTerm(const char* fName1, ComparisionOp op, void **opnd, AggType aggType); /** sets the predicate term of form f1 = f2 && f1 = 100. @@ -111,7 +126,7 @@ class Predicate virtual void setTerm(const char* fName1, ComparisionOp op, void **opnd)=0; virtual void setTerm(Predicate *p1, LogicalOp op, Predicate *p2 = NULL)=0; - + virtual void setTerm(const char* fName1, ComparisionOp op,bool nullFlag)=0; virtual void print(int space)=0; virtual ~Predicate(){} }; diff --git a/include/PredicateImpl.h b/include/PredicateImpl.h index eae1f0ad..886c3773 100644 --- a/include/PredicateImpl.h +++ b/include/PredicateImpl.h @@ -21,6 +21,7 @@ class TableImpl; class Table; class List; +class AggTableImpl; class PredicateImpl:public Predicate { //Members set during initialization of the term @@ -36,10 +37,13 @@ class PredicateImpl:public Predicate int offset1,offset2; DataType type; int length; + bool isNullable; + int fldPos; //Members set during execution void *tuple; //pointer to the tuple List *projList; bool isPushedDown; + AggType aggType; //optimization:caching val1 and val2 for evaluation char *val1; @@ -54,26 +58,29 @@ class PredicateImpl:public Predicate void *operand2; void **operand2Ptr; //This will be set before calling evaluate - TableImpl *table; - + Table *table; + bool isNull; public: PredicateImpl() { strcpy(fldName1, ""); strcpy(fldName2, ""); - operand = NULL; operandPtr = NULL; lhs = rhs = NULL; + lhs = rhs = NULL; tuple = NULL; table = NULL; projList = NULL; parent = NULL; offset1 = -1; offset2 =-1; - type = typeUnknown; - length = 0; + type = typeUnknown; length = 0; isPushedDown=false; isBindBufSet = false; - val1= NULL; - val2=NULL; - val3=NULL; + val1= NULL; val2=NULL; val3=NULL; isNoLeftRight=false; dontEvaluate=false; + aggType = AGG_UNKNOWN; + operand2 = operand = NULL; + operand2Ptr = operandPtr= NULL; + compOp = comp2Op = OpInvalidComparisionOp; + logicalOp = OpInvalidLogicalOp; + isNull=false; } ~PredicateImpl(); @@ -83,20 +90,23 @@ class PredicateImpl:public Predicate void setTerm(const char* fName1, ComparisionOp op, void *opnd); void setTerm(const char* fName1, ComparisionOp op, void **opnd); + void setTerm(const char* fName1, ComparisionOp op, void **opnd, AggType aggType); void setTerm(const char* fName1, ComparisionOp op, void **opnd, ComparisionOp op2, void **opnd2 ); void setTerm(Predicate *p1, LogicalOp op, Predicate *p2 = NULL); - - void* valPtrForIndexField(const char *name); + void setTerm(const char* fName1, ComparisionOp op,bool nullFlag); + void* valPtrForIndexField(const char *name, bool isUnique); ComparisionOp opForIndexField(const char *name); DbRetVal evaluate(bool &result); void evaluateForTable(bool &result, char*tuple); + DbRetVal evaluateForHaving(bool &result, AggTableImpl *aImpl, void* elem); DbRetVal evaluateLogical(bool &result); DbRetVal evaluateLogicalForTable(bool &result, char *tuple); + DbRetVal evaluateLogicalForHaving(bool &result, AggTableImpl *aImpl, void* elem); void setTable(Table *tbl); void setTuple(void *tpl); @@ -104,6 +114,7 @@ class PredicateImpl:public Predicate void setOffsetAndType(); bool isSingleTerm(); bool isNotOrInvolved(); + bool isIsNullInvolved(); //check predicate, whether it has field name and == operator //and does not have OR, NOT operator // TODO:: expression like !(f1 !=100) wont be optimized for now @@ -126,6 +137,7 @@ class PredicateImpl:public Predicate void* getValIfPointLookupOnInt(int &offset); void* getVal1IfBetweenOnInt(int &offset); void* getVal2IfBetweenOnInt(int &offset); + void solveForProjList(Table *tab); }; #endif diff --git a/include/Process.h b/include/Process.h index c28fc347..0dfb5571 100644 --- a/include/Process.h +++ b/include/Process.h @@ -59,8 +59,6 @@ class ThreadInfo void print(); }; -class Database; - class ProcessManager { public: @@ -80,6 +78,7 @@ class ProcessManager static DbRetVal setThreadTransaction(Transaction *trans, int pslot); static Transaction* getThreadTransaction(int pslot); + static Transaction** getThreadTransAddr(int pslot); void printUsageStatistics(); diff --git a/include/Session.h b/include/Session.h index ad6509cb..0437b747 100644 --- a/include/Session.h +++ b/include/Session.h @@ -1,23 +1,15 @@ /*************************************************************************** - * Copyright (C) 2007 by www.databasecache.com * - * Contact: praba_tuty@databasecache.com * * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * + * Copyright (C) Lakshya Solutions Ltd. All rights reserved. * * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU General Public License for more details. * - * * - ***************************************************************************/ + ***************************************************************************/ + #ifndef SESSION_H #define SESSION_H -#include -#include +#include #include +class DatabaseManager; +class UserManager; class Session; /** * @enum IsolationLevel @@ -110,7 +102,9 @@ class Connection * @return DbRetVal */ DbRetVal rollback(); + DbRetVal getExclusiveLock(); + char *getUserName();// { return session->getUserName(); } }; @@ -127,6 +121,7 @@ class Session virtual DbRetVal commit()=0; virtual DbRetVal rollback()=0; virtual DbRetVal getExclusiveLock()=0; + virtual char * getUserName()=0; //TODO:: virtual int setAutoCommit(bool flag)=0; //TODO::support for save points virtual ~Session() { } diff --git a/include/SessionImpl.h b/include/SessionImpl.h index 419da58e..b5fcdc3f 100644 --- a/include/SessionImpl.h +++ b/include/SessionImpl.h @@ -35,7 +35,8 @@ class SessionImpl : public Session public: SessionImpl() { - dbMgr = NULL; uMgr = NULL; isXTaken = false; + dbMgr = NULL; uMgr = NULL; + isXTaken = false; } ~SessionImpl() { @@ -49,14 +50,14 @@ class SessionImpl : public Session DbRetVal open(const char*username, const char*password); DbRetVal close(); - + DatabaseManager* getDatabaseManager(); UserManager* getUserManager(); DbRetVal startTransaction(IsolationLevel level); DbRetVal commit(); DbRetVal rollback(); - + char * getUserName() { return userName;} DbRetVal readConfigFile(); Database* getSystemDatabase(); DbRetVal getExclusiveLock(); diff --git a/include/SqlConnection.h b/include/SqlConnection.h index 308456b6..e623c86c 100644 --- a/include/SqlConnection.h +++ b/include/SqlConnection.h @@ -22,13 +22,21 @@ #include #include #include +class SqlStatement; +struct CachedStmtNode{ + SqlStatement *sqlStmt; + int stmtLength; + char *sqlString; +}; class SqlConnection : public AbsSqlConnection { Connection conn; bool isConnOpen; public: - SqlConnection(){innerConn = NULL; isConnOpen = false; } + List cachedStmts; + SqlConnection(){ innerConn = NULL; isConnOpen = false; } + ~SqlConnection(); /** opens connection to the sql engine * @param user username for authentication @@ -84,6 +92,9 @@ class SqlConnection : public AbsSqlConnection bool isConnectionOpen() { if (isConnOpen) return true; return false; }; DbRetVal getExclusiveLock(){ return conn.getExclusiveLock(); } + SqlStatement* findInCache(char *stmtStr); + void addToCache(SqlStatement *stmt, char *stmtStr); + friend class SqlFactory; }; diff --git a/include/SqlFactory.h b/include/SqlFactory.h index cf0dcfcf..a3c9f279 100644 --- a/include/SqlFactory.h +++ b/include/SqlFactory.h @@ -1,22 +1,9 @@ /*************************************************************************** - * Copyright (C) 2007 by Prabakaran Thirumalai * - * praba_tuty@yahoo.com * * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * + * Copyright (C) Lakshya Solutions Ltd. All rights reserved. * * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU General Public License for more details. * - * * - * You should have received a copy of the GNU General Public License * - * along with this program; if not, write to the * - * Free Software Foundation, Inc., * - * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ + #ifndef SQLFACTORY_H #define SQLFACTORY_H diff --git a/include/SqlGwConnection.h b/include/SqlGwConnection.h index bd2c0962..af70b352 100644 --- a/include/SqlGwConnection.h +++ b/include/SqlGwConnection.h @@ -21,9 +21,20 @@ #define SQLGWCONNECTION_H #include #include +#include #include #include +//List Contains MultiDsn Elements +struct MultiDSN +{ + char dsn[IDENTIFIER_LENGTH]; + AbsSqlConnection *adapter; + struct MultiDSN *next; + bool isConnected; + bool toCommit; +}; + enum GwHandler { NoHandler =0, @@ -31,19 +42,28 @@ enum GwHandler AdapterHandler =2, CSqlAndAdapterHandler =3 }; + class SqlGwConnection : public AbsSqlConnection { Connection dummyConn; AbsSqlConnection *adapter; + // struct MultiDSN *multiAdapter; bool isCSqlConnected; bool isAdapterConnected; char username[IDENTIFIER_LENGTH]; char password[IDENTIFIER_LENGTH]; public: + static List cacheList; + //Head of MultiDsn List + struct MultiDSN *multi_adapter_head; + int noOfCon; GwHandler txnHdlr; TransSyncMode mode; - SqlGwConnection(){innerConn = NULL; mode = OSYNC; } + SqlGwConnection(){innerConn = NULL; mode = OSYNC; multi_adapter_head = NULL; noOfCon = 0; } + ~SqlGwConnection(); + + bool isTableCached(char *name); void setTxnHandler(GwHandler hdlr) { txnHdlr = hdlr; } GwHandler getTxnHandler() { return txnHdlr; } @@ -58,13 +78,15 @@ class SqlGwConnection : public AbsSqlConnection DbRetVal beginTrans (IsolationLevel isoLevel, TransSyncMode mode = OSYNC); friend class SqlFactory; - - void setAdapter(AbsSqlConnection *conn) { adapter = conn; } - AbsSqlConnection* getAdapterConnection() { return adapter; } + bool isCsqlConnected(){ return isCSqlConnected;} + bool isAdptConnected(){ return isAdapterConnected;} + void createAdapters(SqlGwConnection *gateway); + void setAdapter(AbsSqlConnection *conn, char *dsn); + AbsSqlConnection* getAdapterConnection(char *dsn); DbRetVal connectCSqlIfNotConnected(); DbRetVal connectAdapterIfNotConnected(); - + DbRetVal populateCachedTableList(); //Note::forced to implement this as it is pure virtual in base class Connection& getConnObject(){ return dummyConn; } }; diff --git a/include/SqlGwStatement.h b/include/SqlGwStatement.h index 8e4a0d3a..ebe3f0bd 100644 --- a/include/SqlGwStatement.h +++ b/include/SqlGwStatement.h @@ -19,6 +19,7 @@ ***************************************************************************/ #ifndef SQLGWSTATEMENT_H #define SQLGWSTATEMENT_H +#include #include #include #include @@ -28,17 +29,26 @@ class SqlGwStatement: public AbsSqlStatement AbsSqlStatement *adapter; GwHandler stmtHdlr; public: - SqlGwStatement(){innerStmt = NULL; adapter = NULL; con = NULL;} + SqlGwStatement() + { + innerStmt = NULL; adapter = NULL; con = NULL; + stmtHdlr = NoHandler; isPrepared = false; mode = 0; + } + ~SqlGwStatement() + { + if (adapter) { adapter->free(); delete adapter; adapter = NULL; } + } void setAdapter(AbsSqlStatement *stmt) { adapter = stmt; } - int mode; + unsigned int mode; void setConnection(AbsSqlConnection *conn) { if (innerStmt) innerStmt->setConnection(conn->getInnerConnection()); SqlGwConnection *cn = (SqlGwConnection*) conn; - if (adapter) adapter->setConnection(cn->getAdapterConnection()); + // if (adapter) adapter->setConnection(cn->getAdapterConnection()); con = conn; } + DbRetVal executeDirect(char *stmt); DbRetVal prepare(char *stmt); DbRetVal execute(int &rowsAffect); @@ -54,6 +64,7 @@ class SqlGwStatement: public AbsSqlStatement int noOfProjFields(); void* getFieldValuePtr( int pos ); + void* getFieldValuePtr( char *name ); AbsSqlStatement *getInnerStatement(){ return innerStmt;} DbRetVal free(); @@ -79,11 +90,20 @@ class SqlGwStatement: public AbsSqlStatement bool isFldNull(int pos); bool isFldNull(char *name); void setNull(int pos); - int getFldPos(char *name){} + ResultSetPlan getResultSetPlan(); + int getFldPos(char *name){ return -1;} List getAllTableNames(DbRetVal &ret); + List getAllUserNames(DbRetVal &ret); + char *getTableName(){ return "";} + StatementType getStmtType() { return UnknownStatement; } + int getNoOfPagesForTable(char *tbl){ return -1;} + DbRetVal loadRecords(char *tbl, void *buf){ return ErrBadCall;} + void setToCommit(char *dsName); + void getProjFieldType(int *data); private: bool shouldAdapterHandle(); bool shouldCSqlHandle(); + bool isPrepared; friend class SqlFactory; }; diff --git a/include/SqlLogConnection.h b/include/SqlLogConnection.h index 9fee482e..f0e8f015 100644 --- a/include/SqlLogConnection.h +++ b/include/SqlLogConnection.h @@ -29,20 +29,37 @@ * */ +typedef struct my_msgbuffer { + long mtype; + char data[1]; +} Message; + class AbsSqlLogSend { public: - virtual DbRetVal prepare(int txnId, int stmtId, int len, char *stmt)=0; + virtual DbRetVal prepare(int tId, int sId, int len, char *st, + char *tn)=0; virtual DbRetVal commit(int len, void *data)=0; virtual DbRetVal free(int txnId, int stmtId)=0; }; +class MsgQueueSend : public AbsSqlLogSend +{ + int msgQId; + public: + MsgQueueSend() { msgQId = os::msgget(Conf::config.getMsgKey(), 0666); } + DbRetVal prepare(int tId, int sId, int len, char *stmt, char *tn); + DbRetVal commit(int len, void *data); + DbRetVal free(int txnId, int stmtId); +}; + class FileSend : public AbsSqlLogSend { int fdRedoLog; public: FileSend(); - DbRetVal prepare(int txnId, int stmtId, int len, char *stmt); + ~FileSend(); + DbRetVal prepare(int txnId, int stmtId, int len, char *stmt, char*tn); DbRetVal commit(int len, void *data); DbRetVal free(int txnId, int stmtId); }; @@ -62,7 +79,7 @@ class ExecLogInfo int pos; DataType dataType; int len; - char value[1]; + int value; //Extendible value as per parameter type size }; class SqlLogConnection : public AbsSqlConnection @@ -89,20 +106,29 @@ class SqlLogConnection : public AbsSqlConnection //stores client objects in it for peer NetworkTable nwTable; + AbsSqlLogSend *msgQSend; AbsSqlLogSend *fileSend; - static GlobalUniqueID txnUID; + GlobalUniqueID txnUID; static List cacheList; int txnID; DbRetVal populateCachedTableList(); public: SqlLogConnection() { innerConn = NULL; syncMode = ASYNC; + if (Conf::config.useCache() && + Conf::config.getCacheMode()==ASYNC_MODE) + msgQSend = new MsgQueueSend(); + else msgQSend = NULL; if (Conf::config.useDurability()) { fileSend = new FileSend(); } + else fileSend = NULL; + txnUID.open(); execLogStoreSize =0; + noMsgLog = false; } + ~SqlLogConnection(); bool isTableCached(char *name); - + bool noMsgLog; //Note::forced to implement this as it is pure virtual in base class Connection& getConnObject(){ return dummyConn; } @@ -116,19 +142,29 @@ class SqlLogConnection : public AbsSqlConnection DbRetVal beginTrans (IsolationLevel isoLevel, TransSyncMode mode); - DbRetVal fileLogPrepare(int txnId, int stmtId, int len, char *stmt) + DbRetVal msgPrepare(int tId, int sId, int len, char *stmt, char *tname) + { + return msgQSend->prepare(tId, sId, len, stmt, tname); + } + DbRetVal fileLogPrepare(int tId, int sId, int len, char *stmt, char *tname) { - return fileSend->prepare(txnId, stmtId, len, stmt); + return fileSend->prepare(tId, sId, len, stmt, tname); } DbRetVal commitLogs(int logSize, void *data) { int txnId = getTxnID(); + if (((Conf::config.useCache() && + Conf::config.getCacheMode() == ASYNC_MODE)) && !noMsgLog) + msgQSend->commit(logSize, data); if (Conf::config.useDurability()) fileSend->commit(logSize, data); return OK; } DbRetVal freeLogs(int stmtId) { int txnId = getTxnID(); + if ( ((Conf::config.useCache() && + Conf::config.getCacheMode() == ASYNC_MODE)) && !noMsgLog) + msgQSend->free(txnId, stmtId); if (Conf::config.useDurability()) fileSend->free(txnId, stmtId); return OK; } @@ -141,6 +177,7 @@ class SqlLogConnection : public AbsSqlConnection DbRetVal removePreparePacket(int stmtid); DbRetVal setSyncMode(TransSyncMode mode); + void setNoMsgLog(bool nmlog) { noMsgLog = nmlog; } TransSyncMode getSyncMode() { return syncMode; } int getTxnID() { return txnID; } DbRetVal connectIfNotConnected() { return nwTable.connectIfNotConnected(); } diff --git a/include/SqlLogStatement.h b/include/SqlLogStatement.h index b0fcfcac..088cc23b 100644 --- a/include/SqlLogStatement.h +++ b/include/SqlLogStatement.h @@ -29,8 +29,14 @@ class SqlLogStatement: public AbsSqlStatement public: SqlLogStatement() { innerStmt = NULL; con = NULL; needLog= false; - sid=0; isNonSelDML = false; } - + sid=0; isNonSelDML = false; isPrepared = false; + isCached = false; + stmtUID.open(); + } + ~SqlLogStatement() + { + if(isPrepared) free(); stmtUID.close(); + } void setConnection(AbsSqlConnection *conn) { if (innerStmt) innerStmt->setConnection(conn->getInnerConnection()); @@ -40,6 +46,8 @@ class SqlLogStatement: public AbsSqlStatement List getTableNameList() { return innerStmt->getTableNameList(); } char *getTableName() { return innerStmt->getTableName(); } bool isNonSelectDML(char *stmtstr); + + DbRetVal executeDirect(char *stmt); DbRetVal prepare(char *stmt); DbRetVal execute(int &rowsAffect); @@ -79,18 +87,23 @@ class SqlLogStatement: public AbsSqlStatement void setBinaryParam(int paramPos, void *value, int length); bool isSelect(); bool isFldNull(int pos); - bool isFldNull(char *name){} + bool isFldNull(char *name){ return false;} void setNull(int pos); - int getFldPos(char *name){} + int getFldPos(char *name){ return -1;} List getAllTableNames(DbRetVal &ret); - int getNoOfPagesForTable(char *tbl){} - DbRetVal loadRecords(char *tbl, void *buf){} - bool isCached; + List getAllUserNames(DbRetVal &ret); + StatementType getStmtType() { return innerStmt->getStmtType(); } + int getNoOfPagesForTable(char *tbl){ return -1;} + DbRetVal loadRecords(char *tbl, void *buf){ return ErrBadCall;} + ResultSetPlan getResultSetPlan(){ return innerStmt->getResultSetPlan();} + void getProjFieldType(int *data); TableSyncMode mode; bool isNonSelDML; - static GlobalUniqueID stmtUID; + GlobalUniqueID stmtUID; private: + bool isPrepared; bool needLog; + bool isCached; int sid; //statement id //static UniqueID stmtUID; friend class SqlFactory; diff --git a/include/SqlNetworkHandler.h b/include/SqlNetworkHandler.h index 815ccdb7..4d0a798e 100644 --- a/include/SqlNetworkHandler.h +++ b/include/SqlNetworkHandler.h @@ -25,20 +25,20 @@ #include class SqlNetworkHandler { - - DbRetVal applyExecPackets(List sList, List pList); public: - static void setParamValues(AbsSqlStatement *stmt, int parampos, DataType type, int length, char *value); static List stmtList; static List tableNameList; static AbsSqlConnection *conn; static SqlApiImplType type; static int stmtID; static int sockfd; - void fillErrorString(ResponsePacket *rpkt); - void *process(PacketHeader &header, char *buffer); + void * process(PacketHeader &header, char *buffer); + DbRetVal servePacket(PacketHeader &header, void *rpkt); + DbRetVal sendResponse(void *rpkt); void * processSqlConnect(PacketHeader &header, char *buffer); + void * processSqlDisconnect(PacketHeader &header); + void * processSqlExecuteDirect(PacketHeader &header, char *buffer); void * processSqlPrepare(PacketHeader &header, char *buffer); void * processSqlExecute(PacketHeader &header, char *buffer); void * processSqlFetch(PacketHeader &header); @@ -51,9 +51,12 @@ class SqlNetworkHandler void * processSqlShowTables(PacketHeader &header, char *buffer); void * processSqlIsTablePresent(PacketHeader &header, char *buffer); void * processSqlLoadRecords(PacketHeader &header, char *buffer); + DbRetVal closeConnection(); static AbsSqlConnection *createConnection(SqlApiImplType type); static AbsSqlStatement *createStatement(SqlApiImplType type); - + static void setParamValues(AbsSqlStatement *stmt, int parampos, DataType type, int length, char *value); + void fillErrorString(ResponsePacket *rpkt); + DbRetVal send(NetworkPacketType type, char *buf, int len); }; #endif diff --git a/include/SqlNwConnection.h b/include/SqlNwConnection.h index 1b227ba5..f8bba573 100644 --- a/include/SqlNwConnection.h +++ b/include/SqlNwConnection.h @@ -38,7 +38,12 @@ class SqlNwConnection : public AbsSqlConnection public: NetworkClient *nwClient; IsolationLevel prevIsoLevel; - SqlNwConnection(SqlApiImplType tp){nwClient = NULL; innerConn = NULL; isConnOpen = false; sqlApiImplType = tp; } + SqlNwConnection(SqlApiImplType tp) { + nwClient = NULL; + innerConn = NULL; + isConnOpen = false; + sqlApiImplType = tp; + } //Note::forced to implement this as it is pure virtual in base class Connection& getConnObject(){ return dummyConn; } @@ -63,7 +68,9 @@ class SqlNwConnection : public AbsSqlConnection DbRetVal send(NetworkPacketType type) { return nwClient->send(type); } DbRetVal receive() { return nwClient->receive(); } + void setIsConnectedFlag(bool fl) { nwClient->setIsConnectedFlag(fl); } bool isConOpen() { return isConnOpen; } + void setConnClosed(bool status) { isConnOpen = status; } void * getResponsePacket() { return nwClient->getResponsePacket(); } ~SqlNwConnection() { if (isConnOpen) disconnect(); } friend class SqlFactory; diff --git a/include/SqlNwStatement.h b/include/SqlNwStatement.h index ac772040..4b92f4d3 100644 --- a/include/SqlNwStatement.h +++ b/include/SqlNwStatement.h @@ -33,6 +33,8 @@ class SqlNwStatement: public AbsSqlStatement con = conn; } ~SqlNwStatement() { if (isPrepared) free(); } + + DbRetVal executeDirect(char *stmt); DbRetVal prepare(char *stmt); DbRetVal execute(int &rowsAffect); @@ -48,7 +50,7 @@ class SqlNwStatement: public AbsSqlStatement int noOfProjFields(); void* getFieldValuePtr( int pos ); - void* getFieldValuePtr( char *name ){} + void* getFieldValuePtr( char *name ){ return NULL;} DbRetVal free(); @@ -77,9 +79,20 @@ class SqlNwStatement: public AbsSqlStatement bool isFldNull(char *name); void setNull(int pos); void setStmtID(int id) { stmtID = id; } - int getFldPos(char *name){} + int getFldPos(char *name){ return -1;} List getAllTableNames(DbRetVal &ret); + List getAllUserNames(DbRetVal &ret){ List dummy; return dummy;} + char *getTableName(){ return "";} + StatementType getStmtType() { return UnknownStatement; } + int getNoOfPagesForTable(char *tbl){ return -1;} + bool isTablePresent(char *tbName, DbRetVal &rv); + void *getLoadedRecords(char *tbName, DbRetVal &rv); + DbRetVal loadRecords(char *tbName, void *buf){ return ErrBadCall;} + ResultSetPlan getResultSetPlan() { return plan;} + bool isPrepd() { return isPrepared; } + void getProjFieldType(int *data); private: + ResultSetPlan plan; bool isPrepared; bool isSel; int stmtID; diff --git a/include/SqlOdbcConnection.h b/include/SqlOdbcConnection.h index 7c9c581f..a0488f1e 100644 --- a/include/SqlOdbcConnection.h +++ b/include/SqlOdbcConnection.h @@ -25,19 +25,67 @@ #include #include +struct SQLFuncPtrs{ + SQLRETURN (*SQLAllocHandlePtr)(SQLSMALLINT, SQLHANDLE, SQLHANDLE*); + SQLRETURN (*SQLSetEnvAttrPtr)(SQLHENV, SQLINTEGER, SQLPOINTER, SQLINTEGER); + SQLRETURN (*SQLDriverConnectPtr)(SQLHDBC, SQLHWND, SQLCHAR*, SQLSMALLINT, SQLCHAR*, SQLSMALLINT, SQLSMALLINT*, SQLUSMALLINT); + SQLRETURN (*SQLGetDiagRecPtr)(SQLSMALLINT, SQLHANDLE, SQLSMALLINT, SQLCHAR*, SQLINTEGER*, SQLCHAR*, SQLSMALLINT, SQLSMALLINT*); + SQLRETURN (*SQLSetConnectAttrPtr)(SQLHDBC, SQLINTEGER, SQLPOINTER, SQLINTEGER); + SQLRETURN (*SQLFreeHandlePtr)(SQLSMALLINT, SQLHANDLE); + SQLRETURN (*SQLTransactPtr)(SQLHENV, SQLHDBC, SQLUSMALLINT); + + SQLRETURN (*SQLExecDirectPtr)(SQLHSTMT, SQLCHAR*, SQLINTEGER); + SQLRETURN (*SQLPreparePtr)(SQLHSTMT, SQLCHAR*, SQLINTEGER); + SQLRETURN (*SQLNumResultColsPtr)(SQLHSTMT, SQLSMALLINT*); + SQLRETURN (*SQLDescribeColPtr)(SQLHSTMT, SQLUSMALLINT, SQLCHAR*, SQLSMALLINT, SQLSMALLINT*, SQLSMALLINT*, SQLULEN*,SQLSMALLINT*, SQLSMALLINT*); + SQLRETURN (*SQLBindColPtr)(SQLHSTMT, SQLUSMALLINT, SQLSMALLINT, SQLPOINTER, SQLLEN, SQLLEN*); + SQLRETURN (*SQLNumParamsPtr)(SQLHSTMT, SQLSMALLINT*); + SQLRETURN (*SQLDescribeParamPtr)(SQLHSTMT, SQLUSMALLINT, SQLSMALLINT*, SQLULEN*, SQLSMALLINT*, SQLSMALLINT*); + SQLRETURN (*SQLBindParameterPtr)( SQLHSTMT, SQLUSMALLINT, SQLSMALLINT, SQLSMALLINT, SQLSMALLINT, SQLULEN, SQLSMALLINT, SQLPOINTER, SQLLEN, SQLLEN*); + SQLRETURN (*SQLExecutePtr)(SQLHSTMT); + SQLRETURN (*SQLRowCountPtr)(SQLHSTMT, SQLLEN*); + SQLRETURN (*SQLFetchPtr)(SQLHSTMT); + SQLRETURN (*SQLCloseCursorPtr)(SQLHSTMT); + SQLRETURN (*SQLPrimaryKeysPtr)( SQLHSTMT, SQLCHAR*, SQLSMALLINT, SQLCHAR*, SQLSMALLINT, SQLCHAR*, SQLSMALLINT); + SQLRETURN (*SQLGetDataPtr)(SQLHSTMT,SQLUSMALLINT,SQLSMALLINT,SQLPOINTER, SQLLEN,SQLLEN*); + SQLRETURN (*SQLDisconnectPtr)(SQLHDBC); + SQLRETURN (*SQLTablesPtr)(SQLHSTMT ,SQLCHAR *, SQLSMALLINT , SQLCHAR * , SQLSMALLINT, SQLCHAR *, SQLSMALLINT, SQLCHAR*,SQLSMALLINT); + SQLRETURN (*SQLProcedureColumnsPtr)(SQLHSTMT, SQLCHAR *, SQLSMALLINT, SQLCHAR *, SQLSMALLINT, SQLCHAR *, SQLSMALLINT,SQLCHAR *, SQLSMALLINT); + +}; /** * @class SqlOdbcConnection * */ +//class SqlOdbcSym { +// public: +//}; + class SqlOdbcConnection : public AbsSqlConnection { Connection dummyConn; + TDBInfo tdbName; + char errState[STATE_LENGTH]; + char dsnAdapter[IDENTIFIER_LENGTH]; public: SQLHENV envHdl; SQLHDBC dbHdl; + char dsn[IDENTIFIER_LENGTH]; IsolationLevel prevIsoLevel; - SqlOdbcConnection(){innerConn = NULL; } + SqlOdbcConnection() + { strcpy(errState,"00000"); innerConn = NULL; tdbName = mysql; prevIsoLevel = READ_COMMITTED; dsnAdapter[0]='\0';} + ~SqlOdbcConnection(){} + + void setDsn(char *dsn){ strcpy(dsnAdapter,dsn);} + char *getDsn(){return dsnAdapter;} + void setTrDbName(char *name); + TDBInfo getTrDbName(){return tdbName;} + static bool symbolsLoaded; + static struct SQLFuncPtrs ODBCFuncPtrs; + + void setErrorState( SQLHDBC dbc); + DbRetVal loadSymbols(); //Note::forced to implement this as it is pure virtual in base class Connection& getConnObject(){ return dummyConn; } diff --git a/include/SqlOdbcStatement.h b/include/SqlOdbcStatement.h index 7408d361..df5342e2 100644 --- a/include/SqlOdbcStatement.h +++ b/include/SqlOdbcStatement.h @@ -26,7 +26,7 @@ class SqlOdbcStatement: public AbsSqlStatement { public: - SqlOdbcStatement(){innerStmt = NULL; con = NULL; len[0]=0;isSelStmt=NULL; } + SqlOdbcStatement() { innerStmt = NULL; con = NULL; isSelStmt = false; len=NULL; paramlen=NULL; isPrepared = false; strcpy(errState,"00000");} void setConnection(AbsSqlConnection *conn) { @@ -34,6 +34,7 @@ class SqlOdbcStatement: public AbsSqlStatement con = conn; } + DbRetVal executeDirect(char *stmt); DbRetVal prepare(char *stmt); DbRetVal execute(int &rowsAffect); @@ -49,6 +50,7 @@ class SqlOdbcStatement: public AbsSqlStatement int noOfProjFields(); void* getFieldValuePtr( int pos ); + void* getFieldValuePtr( char *name ); DbRetVal free(); @@ -72,21 +74,36 @@ class SqlOdbcStatement: public AbsSqlStatement void setBinaryParam(int paramPos, void *value, int length); bool isSelect(); void getPrimaryKeyFieldName(char *tablename, char *pkfieldname); - void setNullInfo(Table *table); + void setNullInfo(AbsSqlStatement *stmt); +// void setNullInfo(Table *stmt); bool isFldNull(int pos); bool isFldNull(char *name); bool chechStmtType(char *stmtstr); void setNull(int pos); - int getFldPos(char *name){} - List getAllTableNames(DbRetVal &ret){} + int getFldPos(char *name){ return 0;} + List getAllTableNames(DbRetVal &ret){ List dummy; return dummy;} + List getAllUserNames(DbRetVal &ret){ List dummy; return dummy;} + bool isTableExists(char *tblname); + int getNoOfPagesForTable(char *tbl){ return 0;} + DbRetVal loadRecords(char *tbl, void *buf){ return ErrBadCall;} + ResultSetPlan getResultSetPlan(){ return Normal;} + char *getTableName(){ return "";} + StatementType getStmtType() { return UnknownStatement; } + void setErrorState(SQLHSTMT hStmt); + DbRetVal resolveForBindField(SQLHSTMT hstmt); + void getProjFieldType(int *data); private: + char errState[STATE_LENGTH]; + TDBInfo tdbname; bool isSelStmt; bool isPrepared; List paramList; List bindList; SQLHSTMT hstmt; - SQLINTEGER len[IDENTIFIER_LENGTH]; + SQLINTEGER *len; + SQLINTEGER *paramlen; int totalFld; + bool isProcedureCallStmt; friend class SqlFactory; }; diff --git a/include/SqlStatement.h b/include/SqlStatement.h index 874b7a28..3090bd10 100644 --- a/include/SqlStatement.h +++ b/include/SqlStatement.h @@ -31,6 +31,7 @@ class SqlStatement: public AbsSqlStatement { public: SqlStatement(); + ~SqlStatement(); /** sets connection handle to be used for subsequent operations * @param con SqlConnection* */ @@ -46,6 +47,9 @@ class SqlStatement: public AbsSqlStatement */ DbRetVal prepare(char *stmt); + /** Executes directly for the non parameterized statements **/ + DbRetVal executeDirect(char *stmt); + char* getTableName(); /** executes the sql statement. For insert, update, delete queries execute performs the @@ -114,6 +118,7 @@ class SqlStatement: public AbsSqlStatement * @returns address void* */ void* getFieldValuePtr( int pos ); + void* getFieldValuePtr( char *name ); /**Frees all the resources held for the sql statement. Needs to be called before calling prepare again on the same statement handle. * @returns DbRetVal @@ -234,19 +239,29 @@ class SqlStatement: public AbsSqlStatement * @return bool true if it is prepared, false otherwise */ List getTableNameList(); + List getFieldNameList(const char *tblName); + DbRetVal getFieldInfo(const char *tblName, const char *fldName, FieldInfo *&info); bool isPrepared(); StatementType getStmtType() { return pData.getStmtType(); } bool isFldNull(int pos); bool isFldNull(char *name); void setNull(int pos); int getFldPos(char *name); + ResultSetPlan getResultSetPlan(){ return stmt->getResultSetPlan();} List getAllTableNames(DbRetVal &ret); + List getAllUserNames(DbRetVal &ret); + int getNoOfPagesForTable(char *tblName); + DbRetVal loadRecords(char *tblName, void *buffer); + DbRetVal pasteRecords(char *tblName, void *buffer); void setLoading(bool flag); + void getProjFieldType(int *data); + void setCachedStmt(bool flag){ isCachedStmt= flag; } private: SqlConnection *sqlCon; Statement *stmt; ParsedData pData; bool isPrepd; + bool isCachedStmt; friend class SqlFactory; }; diff --git a/include/Statement.h b/include/Statement.h index b2f8cbd1..2782e755 100644 --- a/include/Statement.h +++ b/include/Statement.h @@ -20,7 +20,7 @@ #ifndef STATEMENT_H #define STATEMENT_H #include "Parser.h" - +#include "CacheTableLoader.h" class Statement { protected: @@ -53,6 +53,7 @@ class Statement virtual bool isFldNull(char *name)=0; virtual int getFldPos(char *name)=0; virtual DbRetVal setNull(int pos)=0; + virtual ResultSetPlan getResultSetPlan()=0; virtual ~Statement(){} }; @@ -93,6 +94,7 @@ class DmlStatement : public Statement virtual void* getParamValuePtr( int pos )=0; virtual int getFldPos(char *name)=0; virtual ~DmlStatement(){} + virtual ResultSetPlan getResultSetPlan()=0; void setLoading(bool flag) { table->setLoading(flag); } }; @@ -122,6 +124,7 @@ class InsStatement : public DmlStatement int getFldPos(char *name); DbRetVal setNull(int pos); DbRetVal resolve(); + ResultSetPlan getResultSetPlan(){return Normal;} InsStatement(); ~InsStatement(); }; @@ -132,6 +135,8 @@ class SelStatement : public DmlStatement DbRetVal resolveStar(); DbRetVal setBindFieldAndValues(); DbRetVal resolveForCondition(); + DbRetVal resolveDistinct(); + public: FieldValue **bindFields; @@ -140,6 +145,11 @@ class SelStatement : public DmlStatement bool isPointReturned; bool handleAggWithTbl; + bool isRecLimitReached; + bool isOffsetReached; + int numRecords; + bool isExplain; + bool isJoin; DbRetVal execute(int &rowsAffected); DbRetVal setParam(int paramNo, void *value); @@ -159,18 +169,23 @@ class SelStatement : public DmlStatement DbRetVal replaceStarWithFirstFldName(FieldName *name); DbRetVal resolveGroupFld(AggTableImpl *impl); + DbRetVal resolveOrderByFld(); + bool isInProjectionList(char *name, AggType aType); bool isFldNull(int pos){return table->isFldNull(pos);} - bool isFldNull(char *fldName) { return table->isFldNull(fldName); } + bool isFldNull(char *fldName){ return table->isFldNull(fldName); } int getFldPos(char *name); - DbRetVal setNull(int pos){} + DbRetVal setNull(int pos){ return ErrBadCall;} DbRetVal close(); DbRetVal resolve(); void* handleSingleTableAggWithoutGroup(); + bool isGroupFld(char *fName); + bool isJoinStmt() { return isJoin; } SelStatement(); ~SelStatement(); + bool isTableAlreadyPresent(char* tblName, char* aliasName); DbRetVal openTables(); // DbRetVal resolveGroupFld(AggTableImpl *impl); @@ -190,6 +205,9 @@ class SelStatement : public DmlStatement void *fetchAndPrint(bool SQL); void *next(); void *getFieldValuePtr( int ); + void *getFieldValuePtr( char *name ); + void getProjFieldType(int *data); + ResultSetPlan getResultSetPlan(){ return Normal; } }; class UpdStatement : public DmlStatement @@ -219,8 +237,10 @@ class UpdStatement : public DmlStatement DbRetVal resolve(); UpdStatement(); ~UpdStatement(); + ResultSetPlan getResultSetPlan() {return Normal;} int totalAssignParams; DbRetVal resolveForAssignment(); + ResultSetPlan plan; }; class DelStatement : public DmlStatement @@ -245,14 +265,120 @@ class DelStatement : public DmlStatement bool isFldNull(char *fldName){return table->isFldNull(fldName);} DbRetVal getParamFldInfo(int paramPos, FieldInfo *&info); void* getParamValuePtr(int); - DbRetVal setNull(int pos){} + DbRetVal setNull(int pos){ return ErrBadCall;} DbRetVal resolve(); DelStatement(); ~DelStatement(); int getFldPos(char *name); DbRetVal resolveForCondition(); //TODO::put this is Statement class, duplicated from SelStatement. + ResultSetPlan getResultSetPlan(){return Normal;} }; +class MetadataStatement : public DmlStatement +{ + public: + FieldValue **bindFields; + char **bindFieldValues; + int totalFields; + ListIterator dataListIter; + + int numRecords; + bool isPlanFreed; + bool isSecondFetch; + ResultSetPlan plan; + DbRetVal execute(int &rowsAffected); + DbRetVal setParam(int paramNo, void *value){return OK;}; + + DbRetVal setShortParam(int paramNo, short value){ return OK;}; + DbRetVal setIntParam(int paramNo, int value){ return OK;}; + DbRetVal setLongParam(int paramNo, long value){ return OK;}; + DbRetVal setLongLongParam(int paramNo, long long value){ return OK;}; + DbRetVal setByteIntParam(int paramNo, ByteInt value){ return OK;}; + DbRetVal setFloatParam(int paramNo, float value){ return OK;}; + DbRetVal setDoubleParam(int paramNo, double value){ return OK;}; + DbRetVal setStringParam(int paramNo, char *value){ return OK;}; + DbRetVal setDateParam(int paramNo, Date value){ return OK;}; + DbRetVal setTimeParam(int paramNo, Time value){ return OK;}; + DbRetVal setTimeStampParam(int paramNo, TimeStamp value){ return OK;}; + DbRetVal setBinaryParam(int paramNo, void *value, int length){ return OK;}; + + DbRetVal replaceStarWithFirstFldName(FieldName *name){ return OK;}; + DbRetVal resolveGroupFld(AggTableImpl *impl){ return OK;}; + DbRetVal resolveOrderByFld(){ return OK;}; + bool isFldNull(int pos){return table->isFldNull(pos);} + bool isFldNull(char *fldName){ + if(plan != Normal) return false; + return table->isFldNull(fldName); } + int getFldPos(char *name); + DbRetVal setNull(int pos){ return ErrBadCall;} + DbRetVal close(); + DbRetVal resolve(); + + MetadataStatement(); + ~MetadataStatement(); + + void *getParamValuePtr( int ){ return NULL;} + DbRetVal openTables(); + DbRetVal setBindField(int pos, void* value); + int noOfProjFields(); + DbRetVal getProjFldInfo (int projpos, FieldInfo *&fInfo); + DbRetVal getParamFldInfo(int paramPos, FieldInfo *&info); + DataType getFieldType( int ); + int getFieldLength( int ); + char* getFieldName( int ); + + void *fetch(); + void *fetch(DbRetVal &rv); + void *fetchAndPrint(bool SQL); + void *next(); + void *getFieldValuePtr( int ); + void *getFieldValuePtr( char *name ); + void getProjFieldType(int *data); + void *fetchMetaData(); + void freeMetadata(); + ResultSetPlan getResultSetPlan(){return plan;} + ListIterator getExportKeyIterator(); + ListIterator getImportKeyIterator(); + ListIterator getDataTypeInfoIterator(); +}; +class CopyTblStatement : public DmlStatement +{ + public: + DbRetVal execute(int &rowsAffected); + DbRetVal resolve(); + DbRetVal setParam(int paramNo, void *value); + DbRetVal setShortParam(int paramNo, short value); + DbRetVal setIntParam(int paramNo, int value); + DbRetVal setLongParam(int paramNo, long value); + DbRetVal setLongLongParam(int paramNo, long long value); + DbRetVal setByteIntParam(int paramNo, ByteInt value); + DbRetVal setFloatParam(int paramNo, float value); + DbRetVal setDoubleParam(int paramNo, double value); + DbRetVal setStringParam(int paramNo, char *value); + DbRetVal setDateParam(int paramNo, Date value); + DbRetVal setTimeParam(int paramNo, Time value); + DbRetVal setTimeStampParam(int paramNo, TimeStamp value); + DbRetVal setBinaryParam(int paramNo, void *value, int length); + bool isFldNull(int pos){return table->isFldNull(pos);} + bool isFldNull(char *fldName){return table->isFldNull(fldName);} + DbRetVal getParamFldInfo(int paramPos, FieldInfo *&info); + void* getParamValuePtr(int); + DbRetVal setNull(int pos){ return ErrBadCall;} + int getFldPos(char *name); + ResultSetPlan getResultSetPlan(){return Normal;} + DbRetVal resolveForInsert(); + DbRetVal resolveForCreate(); + CopyTblStatement(); + ~CopyTblStatement(); + private: + void **bindFieldValues; + int totalFields; + Statement *innerSelStmt; + char tblName[IDENTIFIER_LENGTH]; +}; + + + class DdlStatement : public Statement { public: @@ -260,23 +386,24 @@ class DdlStatement : public Statement //TODO: i think rowsAffected is not part of ddl - gopal said its design decision DbRetVal resolve()=0; - DbRetVal setParam(int paramNo, void *value) { } - DbRetVal setShortParam(int paramNo, short value) { } - DbRetVal setIntParam(int paramNo, int value) { } - DbRetVal setLongParam(int paramNo, long value) { } - DbRetVal setLongLongParam(int paramNo, long long value) { } - DbRetVal setByteIntParam(int paramNo, ByteInt value) { } - DbRetVal setFloatParam(int paramNo, float value) { } - DbRetVal setDoubleParam(int paramNo, double value) { } - DbRetVal setStringParam(int paramNo, char *value) { } - DbRetVal setDateParam(int paramNo, Date value) { } - DbRetVal setTimeParam(int paramNo, Time value) { } - DbRetVal setTimeStampParam(int paramNo, TimeStamp value) { } - DbRetVal setBinaryParam(int paramNo, void *value, int length) { } - bool isFldNull(int pos){ } - bool isFldNull(char *fldName ){ } - int getFldPos(char *name){} - DbRetVal setNull(int pos){} + DbRetVal setParam(int paramNo, void *value) { return ErrBadCall; } + DbRetVal setShortParam(int paramNo, short value) { return ErrBadCall; } + DbRetVal setIntParam(int paramNo, int value) { return ErrBadCall; } + DbRetVal setLongParam(int paramNo, long value) { return ErrBadCall; } + DbRetVal setLongLongParam(int paramNo, long long value) { return ErrBadCall; } + DbRetVal setByteIntParam(int paramNo, ByteInt value) { return ErrBadCall; } + DbRetVal setFloatParam(int paramNo, float value) { return ErrBadCall; } + DbRetVal setDoubleParam(int paramNo, double value) { return ErrBadCall; } + DbRetVal setStringParam(int paramNo, char *value) { return ErrBadCall; } + DbRetVal setDateParam(int paramNo, Date value) { return ErrBadCall; } + DbRetVal setTimeParam(int paramNo, Time value) { return ErrBadCall; } + DbRetVal setTimeStampParam(int paramNo, TimeStamp value) { return ErrBadCall;} + DbRetVal setBinaryParam(int paramNo, void *value, int length) { return ErrBadCall;} + bool isFldNull(int pos){ return false;} + bool isFldNull(char *fldName ){ return false;} + int getFldPos(char *name){ return -1;} + DbRetVal setNull(int pos){ return ErrBadCall;} + ResultSetPlan getResultSetPlan(){ ResultSetPlan dummy; return dummy;} }; class CreateTblStatement : public DdlStatement @@ -313,15 +440,47 @@ class DropTblStatement : public DdlStatement DropTblStatement(){} ~DropTblStatement(){} }; +class CacheTblStatement : public DdlStatement +{ + public: + DbRetVal execute(int &rowsAffected); + DbRetVal resolve(); + CacheTableLoader cacheLoader; + CacheTblStatement(){} + +}; + +class UserTblStatement : public DdlStatement +{ + public: + char userName[IDENTIFIER_LENGTH]; + UserManager *usrMgr; + UserNodeType uType; + DbRetVal execute(int &rowsAffected); + DbRetVal resolve(); + void setUserManager(UserManager *mgr,char *user){ usrMgr = mgr; strcpy(userName,user);} + UserTblStatement(){ usrMgr = NULL;} + //~UserTblStatement(){ delete usrMgr;} + +}; + class DropIdxStatement : public DdlStatement { public: DbRetVal execute(int &rowsAffected); DbRetVal resolve() {return OK; } - DropIdxStatement(){} ~DropIdxStatement(){} }; +class CompactTblStatement : public DdlStatement +{ + Table *table; + public: + DbRetVal execute(int &rowsAffected); + DbRetVal resolve(); + CompactTblStatement(){ table=NULL;} + ~CompactTblStatement(){} +}; class StatementFactory { diff --git a/include/Table.h b/include/Table.h index c20793d3..f13c6af1 100644 --- a/include/Table.h +++ b/include/Table.h @@ -205,8 +205,9 @@ class Table virtual DbRetVal getFieldInfo(const char *fieldName, FieldInfo *&info)=0; virtual List getFieldNameList()=0; virtual char* getName()=0; - virtual void printSQLIndexString()=0; - + virtual void printSQLIndexString(FILE *fp=NULL, int fd=-1)=0; + virtual void printSQLForeignString()=0; + virtual DbRetVal compact()=0; //optimizer virtual DbRetVal optimize()=0; virtual ScanType getScanType()=0; @@ -217,7 +218,7 @@ class Table virtual void printPlan(int space)=0; virtual void addPredicate(char *fname, ComparisionOp op, void *buf) { return; } - + virtual bool isFKTable()=0; virtual void resetNullinfo()=0; virtual int getFldPos(char *name)=0; virtual ~Table() { } diff --git a/include/TableConfig.h b/include/TableConfig.h index 04cf7445..37b5c312 100644 --- a/include/TableConfig.h +++ b/include/TableConfig.h @@ -18,12 +18,22 @@ #include #include +#define SIMPLE_CACHE 0x01 +#define CONDNL_CACHE 0x02 +#define FLDLVL_CACHE 0x04 +#define DIRECT_CACHE 0x08 + + class TableConfig { char tableName[IDENTIFIER_LENGTH]; char fieldName[IDENTIFIER_LENGTH]; char userName[IDENTIFIER_LENGTH]; char password[IDENTIFIER_LENGTH]; + char dsnName[IDENTIFIER_LENGTH]; + // char dsnId[IDENTIFIER_LENGTH]; + // char dsnPwd[IDENTIFIER_LENGTH]; + char conditionVal[IDENTIFIER_LENGTH]; //added newly char fieldlistVal[IDENTIFIER_LENGTH]; bool shouldForce; @@ -34,31 +44,62 @@ class TableConfig strcpy(conditionVal,""); strcpy(fieldName,""); strcpy(fieldlistVal,""); - shouldForce = false; + strcpy(dsnName,""); + //strcpy(dsnId,""); + //strcpy(dsnPwd,""); + shouldForce = false; + } + void init() + { + strcpy(tableName,""); + strcpy(conditionVal,""); + strcpy(fieldName,""); + strcpy(fieldlistVal,""); + strcpy(dsnName,""); + shouldForce =false; } void setForceFlag(bool flag){ shouldForce = flag;} void setConnParam(char *user, char *pass){ strcpy(userName, user); strcpy(password, pass); } void setTable(char *tablename) { strcpy(tableName,tablename); } + void setDsnName(char *dsnname) { strcpy(dsnName,dsnname);} + //void setDsnId(char *dsnid) { strcpy(dsnId,dsnid); } + //void setDsnPwd(char *dsnpwd){ strcpy(dsnPwd,dsnpwd);} + void setCondition(char *condition){strcpy(conditionVal,condition);} //new one void setFieldName(char *fldname){ strcpy(fieldName,fldname);} DbRetVal addToCacheTableFile(bool isDirect); - static int getTableMode(char *tabname); + unsigned int getTableMode(char *tabname); void setFieldListVal(char *field) {strcpy(fieldlistVal,field);} - + DbRetVal addToCacheTableFile(); DbRetVal removeFromCacheTableFile(); + DbRetVal updateIntoCacheTableFile(bool upgrade, bool isDirect=false); // DbRetVal load(bool tabDef=true); // DbRetVal reload(); // DbRetVal unload(bool tabDefinition = true); // DbRetVal refresh(); // DbRetVal recoverAllCachedTables(); // DbRetVal load(DatabaseManager *dbMgr, bool tabDef); - static DbRetVal isTableCached(char *tablename); + + DbRetVal isTableCached(char *tablename); + inline bool isTableCached(unsigned int mode) + { + return (mode & SIMPLE_CACHE || mode & CONDNL_CACHE || + mode & FLDLVL_CACHE || mode & DIRECT_CACHE); + } + inline void unsetCacheMode(unsigned int *mode) + { + *mode &= ~(SIMPLE_CACHE | CONDNL_CACHE | FLDLVL_CACHE | DIRECT_CACHE); + return; + } + DbRetVal isTablePresent();// new one by :Jitendra bool isFieldExist(char *fieldname); DbRetVal CacheInfo(bool isTabPresent); char *getRealConditionFromFile(char *condition); char *getConditionVal(char *condition); + static DbRetVal getDsnAndTdb(char *dsn,char *newdsn, char *tdb); + DbRetVal getDsnForTable(char *tabname, char *dsn); }; class TableConf @@ -67,29 +108,3 @@ class TableConf static TableConfig config; }; -/* -class BindBuffer -{ - public: - void *csql; - void *targetdb; - DataType type; -}; - -class CacheTableInfo -{ - public: - char tableName[IDENTIFIER_LENGTH]; - char fieldName[IDENTIFIER_LENGTH]; - char projFieldlist[IDENTIFIER_LENGTH]; - char condition[IDENTIFIER_LENGTH]; - - void setTableName(char *tblName){strcpy(tableName,tblName);} - void setFieldName(char *fldName){strcpy(fieldName,fldName);} - void setProjFieldList(char *fieldlist){ strcpy(projFieldlist,fieldlist);} - void setCondition(char *cond){ strcpy(condition,cond);} - char *getTableName(){return tableName;} - char *getFieldName(){return fieldName;} - char *getCondition(){ return condition;} - char *getProjFieldList(){return projFieldlist;} -};*/ diff --git a/include/TableImpl.h b/include/TableImpl.h index 4270931e..7a758fcc 100644 --- a/include/TableImpl.h +++ b/include/TableImpl.h @@ -52,25 +52,36 @@ class TupleIterator BucketIter *bIter; TreeIter *tIter; IndexInfo *info; + char *keyBuffer; + char *keyPtr; + ComparisionOp op; void *chunkPtr_; int procSlot; bool isBetween; bool isPointLook; - + bool shouldNullCheck; + bool isClosed; TupleIterator() { } public: - TupleIterator(Predicate *p, ScanType t, IndexInfo *i, void *cptr, int pslot,bool between , bool isPtLook) - { bIter = NULL; cIter = NULL; tIter = NULL; + TupleIterator(Predicate *p, ScanType t, IndexInfo *i, void *cptr, int pslot,bool between , bool isPtLook,bool nullflag) + { bIter = new BucketIter(); + cIter = new ChunkIterator();; + tIter = new TreeIter(); + keyBuffer = NULL; pred_ = p ; scanType_ = t; info = i; chunkPtr_ = cptr; - procSlot =pslot; isBetween=between; isPointLook=isPtLook; + isClosed =true; + procSlot =pslot; isBetween=between; isPointLook=isPtLook; shouldNullCheck=nullflag; } + DbRetVal setPlan(); ~TupleIterator() { if (bIter) { delete bIter; bIter = NULL; } if (cIter) { delete cIter; cIter = NULL; } if (tIter) { delete tIter; tIter = NULL; } + if (keyBuffer) { ::free(keyBuffer); keyBuffer = NULL; } } + bool isIterClosed() { return isClosed; } bool isBetInvolved(){ return isBetween;} void setBetInvolved(bool between){ isBetween=between;} bool isPointLookInvolved(){return isPointLook;} @@ -79,13 +90,10 @@ class TupleIterator void* prev();//used only for tree iter during deleteTuple void reset(); DbRetVal close(); - }; class TableImpl:public Table { private: - - LockManager *lMgr_; Transaction **trans; //This is pointer to the pointer stored in the @@ -101,6 +109,7 @@ class TableImpl:public Table void *curTuple_; //holds the current tuple ptr. moved during fetch() calls Predicate *pred_; + List predList; ScanType scanType_; //ChunkIterator *iter; //BucketIter *bIter; @@ -108,6 +117,7 @@ class TableImpl:public Table TupleIterator *iter; bool loadFlag; + char aliasName[IDENTIFIER_LENGTH]; public: FieldList fldList_; @@ -115,6 +125,7 @@ class TableImpl:public Table void **bindListArray_; int numBindFlds_; int numIndexes_; + int numFkRelation_; char** indexPtr_; // array of index ptrs to the catalog table for the indexes of this table. IndexInfo **idxInfo; int useIndex_;//offet in the above array indexPtr_ for scan @@ -131,7 +142,12 @@ class TableImpl:public Table char *cNullInfo; int iNotNullInfo; char *cNotNullInfo; - + //Table *fkTbl; + List tblList; + List tblFkList; + bool isFkTbl; + bool isPkTbl; + bool shouldNullSearch; private: //copy Values from binded buffer to tuple pointed by arg @@ -139,15 +155,18 @@ class TableImpl:public Table DbRetVal copyValuesToBindBuffer(void *tuple); void setNullBit(int fldpos); void clearNullBit(int fldpos); - DbRetVal insertIndexNode(Transaction *trans, void *indexPtr, IndexInfo *info, void *tuple, bool loadFlag=0); + DbRetVal insertIndexNode(Transaction *trans, void *indexPtr, IndexInfo *info, void *tuple); DbRetVal updateIndexNode(Transaction *trans, void *indexPtr, IndexInfo *info, void *tuple); DbRetVal deleteIndexNode(Transaction *trans, void *indexPtr, IndexInfo *info, void *tuple); - + bool isFKTable(){return isFkTbl;}; DbRetVal createPlan(); Chunk* getSystemTableChunk(CatalogTableID id) { return sysDB_->getSystemDatabaseChunk(id); } + DbRetVal trySharedLock(void *curTuple, Transaction **trans); + DbRetVal tryExclusiveLock(void *curTuple, Transaction **trans); + public: TableImpl() { db_ = NULL; chunkPtr_ = NULL; iter = NULL; @@ -155,7 +174,7 @@ class TableImpl:public Table pred_ = NULL; useIndex_ = -1; numFlds_ = 0; bindListArray_ = NULL; iNullInfo = 0; cNullInfo = NULL; isIntUsedForNULL = true; iNotNullInfo = 0; cNotNullInfo = NULL; curTuple_ = NULL; - isPlanCreated = false; loadFlag = false; ptrToAuto=NULL;} + isPlanCreated = false; loadFlag = false;isFkTbl=false;isPkTbl=false;numFkRelation_=0; shouldNullSearch = false;} ~TableImpl(); void setDB(Database *db) { db_ = db; } @@ -170,6 +189,9 @@ class TableImpl:public Table { return fldList_.getFieldOffset(name); } size_t getFieldLength(const char *name) { return fldList_.getFieldLength(name); } + int getNumFields() { return numFlds_; } + void fillFieldInfo(int pos, void* val) + { return fldList_.fillFieldInfo(pos,val); } DbRetVal getFieldInfo(const char *fieldName, FieldInfo *&info) { @@ -177,7 +199,8 @@ class TableImpl:public Table char fldName[IDENTIFIER_LENGTH]; getTableNameAlone((char*)fieldName, tblName); getFieldNameAlone((char*)fieldName, fldName); - if (0 == strcmp(tblName, "") || 0 ==strcmp(tblName, getName())) + if (0 == strcmp(tblName, "") || 0 ==strcmp(tblName, getName()) || + 0 == strcmp(tblName, getAliasName())) return fldList_.getFieldInfo(fldName, info); else return ErrNotExists; @@ -186,8 +209,8 @@ class TableImpl:public Table List getFieldNameList(); // search predicate - void setCondition(Condition *p) - { isPlanCreated = false; if (p) pred_ = p->getPredicate(); else pred_ = NULL;} + void setCondition(Condition *p); + //{ isPlanCreated = false; if (p) pred_ = p->getPredicate(); else pred_ = NULL;} //binding DbRetVal bindFld(const char *name, void *val); @@ -209,12 +232,13 @@ class TableImpl:public Table int truncate(); DbRetVal execute(); - + bool isPkTableHasRecord(char *name,TableImpl *fkTbl,bool isInsert); + bool isFkTableHasRecord(char *name,TableImpl *fkTbl); void* fetch(); void* fetch(DbRetVal &rv); void* fetchNoBind(); void* fetchNoBind(DbRetVal &rv); - DbRetVal fetchAgg(const char *fldName, AggType aType, void *buf); + DbRetVal fetchAgg(const char *fldName, AggType aType, void *buf, bool &noRec); DbRetVal close(); DbRetVal closeScan(); @@ -229,10 +253,10 @@ class TableImpl:public Table DbRetVal lock(bool shared); DbRetVal unlock(); - DbRetVal setUndoLogging(bool flag) { loadFlag = flag; } - - void printSQLIndexString(); + DbRetVal setUndoLogging(bool flag) { loadFlag = flag; return OK;} + void printSQLIndexString(FILE *fp, int fd); + void printSQLForeignString(); DbRetVal optimize(); bool isTableInvolved(char *tblName); bool pushPredicate(Predicate *pred); @@ -241,8 +265,11 @@ class TableImpl:public Table bool hasIndex(char *fldName); IndexType getIndexType(char *fldName, int* pos); void addPredicate(char *fName, ComparisionOp op, void *buf); - + DbRetVal compact(); + DbRetVal compactIndexNode( void *indexPtr); char* getName() { return tblName_; } + char* getAliasName() { return aliasName; } + void setAliasName(char *name); void setTableInfo(char *name, int tblid, size_t length, int numFld, int numIdx, void *chunk); void setLoading(bool flag) { loadFlag = flag; } diff --git a/include/Transaction.h b/include/Transaction.h index f68048d0..82417214 100644 --- a/include/Transaction.h +++ b/include/Transaction.h @@ -26,7 +26,8 @@ enum TransStatus TransCommitting = 1, TransAborting = 2, TransRunning = 3, - TransUnknown = 4 + TransUnknown = 4, + TransReserved = 5 }; class TransHasNode; class LockManager; @@ -39,7 +40,10 @@ enum OperationType UpdateOperation = 2, InsertHashIndexOperation = 3, UpdateHashIndexOperation = 4, - DeleteHashIndexOperation = 5 + DeleteHashIndexOperation = 5, + InsertTreeIndexOperation = 6, + UpdateTreeIndexOperation = 7, + DeleteTreeIndexOperation = 8 }; class UndoLogInfo { @@ -70,6 +74,17 @@ class HashUndoLogInfo { metaData_ = tuple_ = keyPtr_ = hChunk_ = bucket_ = NULL; } }; +class TreeUndoLogInfo +{ + public: + void *metaData_; + void *tuple_; + //void *keyPtr_; + void *cIndex_;//CINDEX ptr + TreeUndoLogInfo() + { metaData_ = tuple_ = cIndex_ = NULL; } +}; + class Transaction { public: @@ -94,6 +109,7 @@ class Transaction DbRetVal appendUndoLog(Database *sysdb, OperationType type, void *data, size_t size); DbRetVal appendLogicalUndoLog(Database *sysdb, OperationType type, void *data, size_t size, void *indexPtr); DbRetVal appendLogicalHashUndoLog(Database *sysdb, OperationType type, void *data, size_t size); + DbRetVal appendLogicalTreeUndoLog(Database *sysdb, OperationType type, void *data, size_t size); UndoLogInfo* createUndoLog(Database *sysdb, OperationType type, void *data, size_t size, DbRetVal *rv); void addAtBegin(UndoLogInfo* logInfo); @@ -113,7 +129,9 @@ class TransactionManager //Transaction *trans; Transaction *firstTrans; - + IsolationLevel getIsoLevel() { + if(firstTrans) return firstTrans->isoLevel_; + else return READ_COMMITTED;} void setFirstTrans(Transaction *trans); void printUsageStatistics(); void printDebugInfo(Database *sysdb); diff --git a/include/UserManager.h b/include/UserManager.h index 9e9cdb1f..e7189054 100644 --- a/include/UserManager.h +++ b/include/UserManager.h @@ -15,6 +15,7 @@ ***************************************************************************/ #ifndef USER_MANAGER_H #define USER_MANAGER_H +#include /** * @class UserManager * @@ -63,6 +64,8 @@ class UserManager * @return int return code */ virtual int changePassword(const char *userName, const char* newPasswd)=0; + + virtual List getAllUserNames(int *rv=0)=0; virtual ~UserManager(){}; }; #endif diff --git a/include/UserManagerImpl.h b/include/UserManagerImpl.h index 95e25877..60c87912 100644 --- a/include/UserManagerImpl.h +++ b/include/UserManagerImpl.h @@ -17,7 +17,6 @@ #define USER_MANAGER_IMPL_H #include #include - class Database; class UserManagerImpl: public UserManager { @@ -41,6 +40,7 @@ class UserManagerImpl: public UserManager int changePassword(const char* newPasswd); int changePassword(const char *userName, const char* newPasswd); + List getAllUserNames(int *rv=NULL); }; diff --git a/include/Util.h b/include/Util.h index 47119e92..72a9d4c9 100644 --- a/include/Util.h +++ b/include/Util.h @@ -1,22 +1,9 @@ /*************************************************************************** - * Copyright (C) 2007 by Prabakaran Thirumalai * - * praba_tuty@yahoo.com * * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * + * Copyright (C) Lakshya Solutions Ltd. All rights reserved. * * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU General Public License for more details. * - * * - * You should have received a copy of the GNU General Public License * - * along with this program; if not, write to the * - * Free Software Foundation, Inc., * - * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ + #ifndef UTIL_H #define UTIL_H #include @@ -25,6 +12,83 @@ enum UniqueIDType { STMT_ID=0, TXN_ID }; +class Util +{ + public: + static unsigned int hashBinary(char *strVal, int length); + static void trimEnd(char *name) + { + while(*name!='\0') + { + if(*name == ' ') { *name='\0'; break;} + name++; + } + } + static void trimRight(char *name) + { + int len = strlen(name); + while(name[len-1] == ' ' && len != 0 ) + { + len--; + } + name[len]='\0'; + } + static void str_tolower(char *s) + { + while(*s) + { + *s=tolower(*s); + s++; + } + } + static void str_toupper(char *s) + { + while(*s) + { + *s=toupper(*s); + s++; + } + } + static bool isIdentifier(char *name) + { + char *p = name; + if (!isalpha(*p)) return false; + while (*p != '\0') { + if (*p == '_') { p++; continue; } + if (!isalnum(*p)) return false; + p++; + } + return true; + } + inline static void changeWildcardChar(char *src) + { + char *c = (char *)src; + while (*c != '\0') { + if (*c == '_') *c = '?'; + else if(*c == '%') *c = '*'; + c++; + } + return; + } + inline static void itoa(int n, char s[]) + { + int i, sign, j, k ; + if ((sign = n) < 0) n = -n; + i = 0; + do { + s[i++] = n % 10 + '0'; + } while ((n /= 10) > 0); + if (sign < 0) + s[i++] = '-'; + s[i] = '\0'; + char c; + for (k = 0, j = i-1; knext; return node->element; } + void* nextElementInQueue() + { + ListNode *node = iter; + if(iter->next) { + iter = iter ->next; + return node->element; + } else return NULL; + } + void *getCurrentListNode(){ return iter; } //index start with one, such that 1->first element in list void* getElement(int index) { @@ -85,7 +158,7 @@ class List int totalElements; public: List() { head = NULL; totalElements = 0;} - + List(ListNode *hd) { head = hd; } //Use only for free in metadata DbRetVal append(void *elem) { ListNode *newNode = new ListNode(); @@ -115,7 +188,12 @@ class List { if (elem == iter->element) { - if (iter == head) { head = iter->next; delete iter; return OK;} + if (iter == head) { + head = iter->next; + delete iter; + totalElements--; + return OK; + } prev->next = iter->next; delete iter; totalElements--; @@ -177,6 +255,26 @@ class List totalElements = 0; return; } + void init() { head = NULL; totalElements=0;} + + DbRetVal addAtMiddle(void *elem, void *prevIter) + { + ListNode *newNode = new ListNode(); + newNode->element = elem; + totalElements++; + newNode->next =((ListNode *)prevIter)->next; + ((ListNode *)prevIter)->next = newNode; + return OK; + } + DbRetVal addAtBegin(void *elem) + { + ListNode *newNode = new ListNode(); + newNode->element = elem; + totalElements++; + newNode->next = head; + head = newNode; + return OK; + } int size() { return totalElements; @@ -191,7 +289,7 @@ class GlobalUniqueID GlobalUniqueID() { ptr = NULL; } DbRetVal create(); DbRetVal open(); - DbRetVal close() { os::shm_detach(ptr); return OK; } + DbRetVal close() { os::shm_detach(ptr); ptr = NULL; return OK; } DbRetVal destroy(); int getID(UniqueIDType type); }; diff --git a/include/os.h b/include/os.h index cefc53dd..3a343a94 100644 --- a/include/os.h +++ b/include/os.h @@ -95,6 +95,8 @@ enum MapMode #define SYSTEMDB "SYSTEMDB" #define DBAUSER "root" #define DBAPASS "manager" +#define I_USER "i@1r4D_f$_a" +#define I_PASS "a_$f_D4r1@i" #define DEFAULT_CONFIG_FILE "/etc/csql/csql.conf" #define LOCK_BUCKET_SIZE 2048 #define STMT_BUCKET_SIZE 1023 @@ -116,6 +118,11 @@ enum MapMode typedef key_t shared_memory_key; typedef int shared_memory_id; +#if defined(__sparcv9) + typedef long InUse; +#else + typedef int InUse; +#endif #endif diff --git a/include/sql.h b/include/sql.h index a5a98303..9341b941 100644 --- a/include/sql.h +++ b/include/sql.h @@ -167,6 +167,7 @@ extern "C" { #define SQL_SMALLINT 5 #define SQL_FLOAT 6 #define SQL_REAL 7 +//#define SQL_BIGINT -5 #define SQL_DOUBLE 8 #if (ODBCVER >= 0x0300) #define SQL_DATETIME 9 -- 2.11.4.GIT