/*
FILE:     CifSchemaMap.h
*/
/*
VERSION:  2.201
*/
/*
DATE:     8/30/2004
*/
/*
  Comments and Questions to: sw-help@rcsb.rutgers.edu
*/
/*
COPYRIGHT 1999-2004 Rutgers - The State University of New Jersey

This software is provided WITHOUT WARRANTY OF MERCHANTABILITY OR
FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR
IMPLIED.  RUTGERS MAKE NO REPRESENTATION OR WARRANTY THAT THE
SOFTWARE WILL NOT INFRINGE ANY PATENT, COPYRIGHT OR OTHER
PROPRIETARY RIGHT.

The user of this software shall indemnify, hold harmless and defend
Rutgers, its governors, trustees, officers, employees, students,
agents and the authors against any and all claims, suits,
losses, liabilities, damages, costs, fees, and expenses including
reasonable attorneys' fees resulting from or arising out of the
use of this software.  This indemnification shall include, but is
not limited to, any and all claims alleging products liability.
*/
/*
               PDB SOFTWARE LICENSE AGREEMENT

BY CLICKING THE ACCEPTANCE BUTTON OR INSTALLING OR USING 
THIS "SOFTWARE, THE INDIVIDUAL OR ENTITY LICENSING THE  
SOFTWARE ("LICENSEE") IS CONSENTING TO BE BOUND BY AND IS 
BECOMING A PARTY TO THIS AGREEMENT.  IF LICENSEE DOES NOT 
AGREE TO ALL OF THE TERMS OF THIS AGREEMENT
THE LICENSEE MUST NOT INSTALL OR USE THE SOFTWARE.

1. LICENSE AGREEMENT

This is a license between you ("Licensee") and the Protein Data Bank (PDB) 
at Rutgers, The State University of New Jersey (hereafter referred to 
as "RUTGERS").   The software is owned by RUTGERS and protected by 
copyright laws, and some elements are protected by laws governing 
trademarks, trade dress and trade secrets, and may be protected by 
patent laws. 

2. LICENSE GRANT

RUTGERS grants you, and you hereby accept, non-exclusive, royalty-free 
perpetual license to install, use, modify, prepare derivative works, 
incorporate into other computer software, and distribute in binary 
and source code format, or any derivative work thereof, together with 
any associated media, printed materials, and on-line or electronic 
documentation (if any) provided by RUTGERS (collectively, the "SOFTWARE"), 
subject to the following terms and conditions: (i) any distribution 
of the SOFTWARE shall bind the receiver to the terms and conditions 
of this Agreement; (ii) any distribution of the SOFTWARE in modified 
form shall clearly state that the SOFTWARE has been modified from 
the version originally obtained from RUTGERS.  

2. COPYRIGHT; RETENTION OF RIGHTS.  

The above license grant is conditioned on the following: (i) you must 
reproduce all copyright notices and other proprietary notices on any 
copies of the SOFTWARE and you must not remove such notices; (ii) in 
the event you compile the SOFTWARE, you will include the copyright 
notice with the binary in such a manner as to allow it to be easily 
viewable; (iii) if you incorporate the SOFTWARE into other code, you 
must provide notice that the code contains the SOFTWARE and include 
a copy of the copyright notices and other proprietary notices.  All 
copies of the SOFTWARE shall be subject to the terms of this Agreement.  

3. NO MAINTENANCE OR SUPPORT; TREATMENT OF ENHANCEMENTS 

RUTGERS is under no obligation whatsoever to: (i) provide maintenance 
or support for the SOFTWARE; or (ii) to notify you of bug fixes, patches, 
or upgrades to the features, functionality or performance of the 
SOFTWARE ("Enhancements") (if any), whether developed by RUTGERS 
or third parties.  If, in its sole discretion, RUTGERS makes an 
Enhancement available to you and RUTGERS does not separately enter 
into a written license agreement with you relating to such bug fix, 
patch or upgrade, then it shall be deemed incorporated into the SOFTWARE 
and subject to this Agreement. You are under no obligation whatsoever 
to provide any Enhancements to RUTGERS or the public that you may 
develop over time; however, if you choose to provide your Enhancements 
to RUTGERS, or if you choose to otherwise publish or distribute your 
Enhancements, in source code form without contemporaneously requiring 
end users or RUTGERS to enter into a separate written license agreement 
for such Enhancements, then you hereby grant RUTGERS a non-exclusive,
royalty-free perpetual license to install, use, modify, prepare
derivative works, incorporate into the SOFTWARE or other computer
software, distribute, and sublicense your Enhancements or derivative
works thereof, in binary and source code form.

4. FEES.  There is no license fee for the SOFTWARE.  If Licensee
wishes to receive the SOFTWARE on media, there may be a small charge
for the media and for shipping and handling.  Licensee is
responsible for any and all taxes.

5. TERMINATION.  Without prejudice to any other rights, Licensor
may terminate this Agreement if Licensee breaches any of its terms
and conditions.  Upon termination, Licensee shall destroy all
copies of the SOFTWARE.

6. PROPRIETARY RIGHTS.  Title, ownership rights, and intellectual
property rights in the Product shall remain with RUTGERS.  Licensee 
acknowledges such ownership and intellectual property rights and will 
not take any action to jeopardize, limit or interfere in any manner 
with RUTGERS' ownership of or rights with respect to the SOFTWARE.  
The SOFTWARE is protected by copyright and other intellectual 
property laws and by international treaties.  Title and related 
rights in the content accessed through the SOFTWARE is the property 
of the applicable content owner and is protected by applicable law.  
The license granted under this Agreement gives Licensee no rights to such
content.

7. DISCLAIMER OF WARRANTY.  THE SOFTWARE IS PROVIDED FREE OF 
CHARGE, AND, THEREFORE, ON AN "AS IS" BASIS, WITHOUT WARRANTY OF 
ANY KIND, INCLUDING WITHOUT LIMITATION THE WARRANTIES THAT IT 
IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE 
OR NON-INFRINGING.  THE ENTIRE RISK AS TO THE QUALITY AND 
PERFORMANCE OF THE SOFTWARE IS BORNE BY LICENSEE.  SHOULD THE 
SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, THE LICENSEE AND NOT 
LICENSOR ASSUMES THE ENTIRE COST OF ANY SERVICE AND REPAIR.  
THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF 
THIS AGREEMENT.  NO USE OF THE PRODUCT IS AUTHORIZED HEREUNDER 
EXCEPT UNDER THIS DISCLAIMER.

8. LIMITATION OF LIABILITY.  TO THE MAXIMUM EXTENT PERMITTED BY
APPLICABLE LAW,  IN NO EVENT WILL LICENSOR BE LIABLE FOR ANY 
INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 
OUT OF THE USE OF OR INABILITY TO USE THE SOFTWARE, INCLUDING, 
WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK 
STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL 
OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF ADVISED OF THE
POSSIBILITY THEREOF. 
*/
#ifndef CIFSCHEMAMAP_H
#define CIFSCHEMAMAP_H



#include "CifFileObj.h"


//extern "C" {
//  int strcasecmp (const char *s1, const char *s2);
//  int strncasecmp (const char *s1, const char *s2, size_t n);
//  int symlink(const char *s1, const char *s2);
//}

#define TRUE  1
#define FALSE 0
#define _MAX_NAME_LENGTH 80



typedef struct _attribInfo {
  int iIndex, iNull, iWidth, iPrecision, iMaxWidth;
  CifString dType;
  int iTypeCode;
} ATTRIBINFO;


class  CifSchemaMap {

 private:
  int  _compatibilityMode;
  int  _hashMode;

//  const static int _MAX_NAME_LENGTH;// =80;
  const static int _MAX_LINE_LENGTH;// =130;
  static int _RCSBEXTENSIONS;//  =TRUE;

  const static int _TYPE_CODE_INT        ;//= 1;
  const static int _TYPE_CODE_FLOAT      ;//= 2;
  const static int _TYPE_CODE_STRING     ;//= 3;
  const static int _TYPE_CODE_TEXT       ;//= 4;
  const static int _TYPE_CODE_DATETIME   ;//= 5;
  const static int _TYPE_CODE_BIGINT     ;//= 6;

  const static int _SERVER_TYPE_SYBASE   ;//= 1;
  const static int _SERVER_TYPE_MYSQL    ;//= 2;
  const static int _SERVER_TYPE_ORACLE   ;//= 3;
  const static int _SERVER_TYPE_DB2      ;//= 4;
  const static long _MAXFILESIZE ;//= 2000000000;
    


  char * _dbName;            // Target database name 
  char * _dbUser;            // Valid user of target database.  
  char * _dbMgr;             // Administrative user for targe database.  
                             // Used in assigning permissions when exporting schema in SQL. 


  char * _schemaFile;        // Schema definition file name (mmCIF)
  char * _schemaFileOdb;     // Schema definition file name (odb)

  char *_blockName;          // Block name of loadable data in mmCIF format

  char *_path;               // File system path for all output files.

  char *_fieldSeparator;     // Field and row separators for compact output (eg. BCP)
  char *_rowSeparator;   
  char *_cmdTerm;            //SQL command terminator.

  CifFileObj *_fobjS;        // File object for schema definitions

  ISTable *_tableSchema;
  int _cInTSTableName, _cInTSGroupName;

  ISTable *_attribSchema;
  int _cInASTableName,  _cInASAttributeName,  _cInASDataType, _cInASIndexFlag;
  int _cInASNullFlag,   _cInASWidth,          _cInASPrecision;               

  ISTable *_schemaMap;
  int _cInSMTargetTableName, _cInSMTargetAttributeName, _cInSMSourceItemName;
  int _cInSMConditionId, _cInSMFunctionId;
 
  ISTable *_mapConditions;
  int _cInMCConditionId, _cInMCAttributeName, _cInMCAttributeValue;


  ISTable *_tableAbbrev;    
  int _cInTATableName,  _cInTATableNameAbbrev;
  ISTable *_attributeAbbrev;
  int _cInAATableName, _cInAAAttributeName,  _cInAAAttributeNameAbbrev;


  int _serverType;
  int _verbose;
  ofstream _log;

  void _AssignAttribIndices(void);
  void _CreateTableSQL(ostream &io, CifString tableName);
  ISTable * _CreateColumnInfo(CifFileObj *fobj);
  ISTable * _CreateTableInfo(CifFileObj *fobj);
  void _CreateTables(CifFileObj *fobj, const char *blockName);
  void _LoadBlock(CifFileObj *fobjR, const char *rBlockName,
		  CifFileObj *fobjW, const char *wBlockName);
  int _Search(CifFileObj *fobjR, const char *rBlockName, ReVarCifArray<CifString> *cNameMap,
	      const char *sItem, const char *sCnd, const char *sFnct,
	      ReVarCifArray<CifString> **d, int *ind, int iAttr);
  
  ReVarCifArray<CifString> * _DoFunc(ReVarCifArray<CifString> *r, const char *sFnct);
  //  void _AddIndex(ISTable *t, const char *columnName);

  void _OpenLog(const char *logName);

  int _GetCategoryNameFromItemName(char categoryName[_MAX_NAME_LENGTH], const char *itemName);
  int _GetKeywordFromItemName(char keyword[_MAX_NAME_LENGTH], const char *itemName);

  int _GetMapColumnIndex(ReVarCifArray<CifString> *cNameMap, const char *vOf);
  char * _GetMapColumnValue(ReVarCifArray<CifString> **dMap,  int iCol,  int irow);
  int _GetMapColumnLength(ReVarCifArray<CifString> **dMap,   int iCol);

  ATTRIBINFO * _GetAttributeInfo(ISTable *tIn);
  ATTRIBINFO * _GetAllAttributeInfo(CifString tableName);

  void _FormatStringDataBCP(ostream &io,  CifString &cs, int maxWidth);
  void _FormatStringDataBCPdb2(ostream &io,  CifString &cs, int maxWidth);
  void _FormatStringDataSQL(ostream &io,  CifString &cs, int maxWidth);
  void _FormatStringDataXML(ostream &io,  CifString &cs, int maxWidth);

  void _FormatNumericDataBCP(ostream &io,  CifString &cs);
  void _FormatNumericDataSQL(ostream &io,  CifString &cs);
  void _FormatNumericDataXML(ostream &io,  CifString &cs);

  void _FormatDateDataBCP(ostream &io,  CifString &cs, int maxWidth);
  void _FormatDateDataSQL(ostream &io,  CifString &cs, int maxWidth);  
  void _FormatDateDataXML(ostream &io,  CifString &cs, int maxWidth);  

  void _FormatTextDataSQL(ostream &io,  CifString &cs); 
  void _FormatTextDataBCP(ostream &io,  CifString &cs);
  void _FormatTextDataBCPdb2(ostream &io,  CifString &cs);
  void _FormatTextDataXML(ostream &io,  CifString &cs);

  void _dformat_1(const char *date, char *odate);
  void _dformat_2(const char *date, char *odate);
  void _dformat_3(const char *date, char *odate, int shortFlag);
  void _dformat_4(const char *date, char *odate);
  void _dformat_5(const char *date, char *odate);
  void _ReorderName(char *string, int mode);
  void _CleanString(char *string);
  void _ToUpperString(char *string);
  void _StripString(char *string, int mode);
  int _CheckMandatoryAttributes(ReVarCifArray<CifString> * row, ATTRIBINFO *aI);
  int _CheckIndexAttributes(ReVarCifArray<CifString> * row, ATTRIBINFO *aI);
  int _CheckNullRow(ReVarCifArray<CifString> * row, ATTRIBINFO *aI);
  void _WriteScriptSchema(void);
  int  _isElementNullXML(const char *val);

  void _UpdateTableSQL(ostream &io,  ISTable *tIn);
  void _WriteTableBCP(ostream &io,   ISTable *tIn);
  void _WriteTableBCPdb2(ostream &io,   ISTable *tIn);
  void _WriteTableXML(ostream &io,   ISTable *tIn);
  void _DeleteRowsSQL(ostream &io,   ISTable *tIn);
  void _DeleteTableSQL(ostream &io, ISTable *tIn);
  void _InsertTableSQL(ostream &io, ISTable *tIn);
  void _UpdateBCP(CifFileObj *fobj, int flagAppend);
  void _UpdateSQL(CifFileObj *fobj, int flagAppend);
  void _UpdateXML(CifFileObj *fobj, int flagAppend);
  void _QualifyNameXML(ostream &io,  const char *name); 
  void _QualifyNameWithNSXML(ostream &io,  const char *name);
  void _GetDefaultNamespaceXML(ostream &io); 
  void _SetNamespaceDefaultXML(const char *name); 
  void _WriteScriptBCP(void);
  void _WriteScriptSQL(void);
  void _WriteOracleControlFiles(int iAppend);
  void _WriteDB2ControlFiles(void);
  void _WriteMysqlLoadFile(int flagAppend);
  void _UpdateIndicesSQL(void);
  void _GetAttributeNameAbbrev(CifString &abbrev, CifString targetTable, CifString targetAttribute);
  void _GetTableNameAbbrev(CifString &abbrev, CifString target);
  void _GetAttributeNameAbbrevXML(CifString &abbrev, CifString targetTable, CifString targetAttribute);
  void _GetTableNameAbbrevXML(CifString &abbrev, CifString target);
  long long pdbIdHash(const char *id);
  void _CreateComplexTypeXML(ostream &io, CifString tableName);

 public:

  const static int MODE_SQL;//=1;
  const static int MODE_BCP;//=2;
  const static int MODE_XML;//=3;

  const static int _SCRIPT_ONLY      ;//= 2;
  const static int _DATA_ONLY        ;//= 0;
  const static int _DATA_PLUS_SCRIPT ;//= 1;

  virtual ~CifSchemaMap() {
    Reset();
    if (_verbose) _log.close();
  }
  CifSchemaMap(const char * schemaFile, const char * schemaFileOdb, 
	       const char * path, int verbose);
  CifSchemaMap(const char * schemaFile, const char * schemaFileOdb, int verbose=0);
  CifSchemaMap(const char * schemaFileOdb, int verbose=0, const char *path="");

  void Clear();
  void Reset();
  void SetDatabaseName(const char *dbName);
  void SetDatabaseUser(const char *dbUser);
  void SetDatabaseMgr(const char *dbMgr);
  void SetServerType(const char *server);
  void SetRowSeparator(const char *rowSeparator);
  void SetFieldSeparator(const char *fieldSeparator);

  void SetPath(const char *path);
  char *GetCommandPath();

  void SetCompatibilityMode(int mode);
  void SetHashMode(int mode);

  void WriteSchemaSQL(int updateMode=1);

  void LoadFile(const char *inpFile, int mode, int opFlag); 
  void LoadFileObj(char *inpFileObj, int mode);
  void LoadFileObj(CifFileObj *fobjR, int mode);

  void WriteSchemaXML();
  void _CreateTableXML(ostream &io, CifString tableName);
  //
};



#endif
