1   /*
2    * org.riverock.dbrevision - Database revision engine
3    * For more information about DbRevision, please visit project site
4    * http://www.riverock.org
5    *
6    * Copyright (C) 2006-2006, Riverock Software, All Rights Reserved.
7    *
8    * Riverock - The Open-source Java Development Community
9    * http://www.riverock.org
10   *
11   *
12   * This library is free software; you can redistribute it and/or
13   * modify it under the terms of the GNU Lesser General Public
14   * License as published by the Free Software Foundation; either
15   * version 2.1 of the License, or (at your option) any later version.
16   *
17   * This library is distributed in the hope that it will be useful,
18   * but WITHOUT ANY WARRANTY; without even the implied warranty of
19   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20   * Lesser General Public License for more details.
21   *
22   * You should have received a copy of the GNU Lesser General Public
23   * License along with this library; if not, write to the Free Software
24   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25   */
26  package org.riverock.dbrevision.system;
27  
28  import java.io.FileInputStream;
29  
30  import org.apache.commons.lang.StringUtils;
31  
32  import org.riverock.dbrevision.annotation.schema.db.DbField;
33  import org.riverock.dbrevision.annotation.schema.db.DbForeignKey;
34  import org.riverock.dbrevision.annotation.schema.db.DbSchema;
35  import org.riverock.dbrevision.annotation.schema.db.DbTable;
36  import org.riverock.dbrevision.annotation.schema.db.DbView;
37  import org.riverock.dbrevision.db.Database;
38  import org.riverock.dbrevision.db.DatabaseManager;
39  import org.riverock.dbrevision.db.DatabaseStructureManager;
40  import org.riverock.dbrevision.utils.Utils;
41  
42  /**
43   * Author: mill
44   * Date: Nov 28, 2002
45   * Time: 3:10:19 PM
46   * <p/>
47   * $Id: ValidateStructure.java 1141 2006-12-14 14:43:29Z serg_main $
48   */
49  public class ValidateStructure {
50  
51      public ValidateStructure() {
52      }
53  
54      private static void processAllView(Database db_, DbSchema millSchema) throws Exception {
55          for (DbView view : millSchema.getViews()) {
56              DatabaseManager.createWithReplaceAllView(db_, millSchema);
57              try {
58                  System.out.println("create view " + view.getName());
59                  db_.createView(view);
60              }
61              catch (Exception e) {
62                  if (db_.testExceptionViewExists(e)) {
63                      System.out.println("view " + view.getName() + " already exists");
64                      System.out.println("drop view " + view.getName());
65                      DatabaseStructureManager.dropView(db_, view);
66                      System.out.println("create view " + view.getName());
67                      try {
68                          db_.createView(view);
69                      }
70                      catch (Exception e1) {
71                          System.out.println("Error create view - " + e1.toString());
72                      }
73                  }
74                  else {
75                      System.out.println("Error create view - " + e.toString());
76                  }
77              }
78          }
79          DatabaseManager.createWithReplaceAllView(db_, millSchema);
80      }
81  
82      private static void processForeignKeys(Database adapter, DbSchema millSchema) throws Exception {
83          for (DbTable table : millSchema.getTables()) {
84              if (!DatabaseManager.isSkipTable(table.getName())) {
85                  System.out.println("Create foreign key for table " + table.getName());
86  
87                  int p = 0;
88                  for (DbForeignKey foreignKey : table.getForeignKeys()) {
89                      if (StringUtils.isBlank(foreignKey.getFkName())) {
90                          foreignKey.setFkName(foreignKey.getFkTableName() + p + "_fk");
91                      }
92                      DatabaseStructureManager.createForeignKey(adapter, foreignKey);
93                  }
94              }
95              else {
96                  System.out.println("skip table " + table.getName());
97              }
98          }
99      }
100 
101     private static DbSchema validateStructure(Database adapter, DbSchema millSchema) throws Exception {
102         DbSchema schema = DatabaseManager.getDbStructure(adapter);
103 
104         String nameFile = "test-schema.xml";
105         System.out.println("Marshal data to file " + nameFile);
106 
107         Utils.writeToFile(schema, nameFile);
108 
109         for (DbTable table : millSchema.getTables()) {
110             if (!DatabaseManager.isSkipTable(table.getName())) {
111                 DbTable originTable = DatabaseManager.getTableFromStructure(schema, table.getName());
112                 if (!DatabaseManager.isTableExists(schema, table)) {
113                     System.out.println("Create new table " + table.getName());
114                     adapter.createTable(table);
115                 }
116                 else {
117                     // check valid structure of fields
118                     for (DbField field : table.getFields()) {
119                         if (!DatabaseManager.isFieldExists(schema, table, field)) {
120                             System.out.println("Add field '" + field.getName() + "' to table '" + table.getName() + "'");
121                             adapter.addColumn(table, field);
122                         }
123 
124                         DbField originField =
125                             DatabaseManager.getFieldFromStructure(schema, table.getName(), field.getName());
126 
127                         if (originField != null && (originField.getDefaultValue() == null && field.getDefaultValue() != null)) {
128                             System.out.println("Default value of field " + table.getName() + '.' + originField.getName() +
129                                 " not set to " + field.getDefaultValue());
130                             if (DatabaseManager.checkDefaultTimestamp(field.getDefaultValue())) {
131                                 System.out.println("Field recognized as default date field");
132                                 DatabaseStructureManager.setDefaultValueTimestamp(adapter, originTable, field );
133                             }
134                             else
135                                 System.out.println("Unknown default type of field");
136                         }
137                     }
138 
139                 }
140             }
141             else
142                 System.out.println("skip table " + table.getName());
143         }
144 
145 /*
146         // get new instance of schema
147         schema = DbService.getDbStructure(db_, "MILLENNIUM");
148         try
149         {
150             // check for correct PK
151             DbTable tableForCheckPk =
152                 DbService.getTableFromStructure(schema, table.getName());
153 
154 //                    System.out.println("orig table '"+table.getName()+"', table for check'"+tableForCheckPk.getName()+"'");
155 //                    System.out.println("orig table PK "+table.getPrimaryKey()+", table for check PK "+tableForCheckPk.getPrimaryKey()+"");
156 
157             if (table.getPrimaryKey()!=null &&
158                 table.getPrimaryKey().getColumnsCount()>0 &&
159                 (tableForCheckPk.getPrimaryKey()==null || tableForCheckPk.getPrimaryKey().getColumnsCount()==0))
160             {
161                 System.out.println("Add PK to table '"+tableForCheckPk.getName()+"'");
162                 DbService.addPrimaryKey(db_, tableForCheckPk, table.getPrimaryKey());
163             }
164         }
165         catch(Exception e)
166         {
167             System.out.println("Error add PK "+e.toString());
168         }
169 */
170 
171         processAllView(adapter, millSchema);
172         processForeignKeys(adapter, millSchema);
173 
174         return DatabaseManager.getDbStructure(adapter);
175     }
176 
177     public static void main(String args[]) throws Exception {
178         long mills = System.currentTimeMillis();
179 
180 
181         System.out.println("Unmarshal data from file");
182         FileInputStream stream = new FileInputStream("webmill-schema.xml");
183         DbSchema millSchema = Utils.getObjectFromXml(DbSchema.class, stream);
184 
185         Database adapter=null;
186 //        validateStructure(millSchema, "ORACLE_MILL_TEST");
187         validateStructure(adapter, millSchema);
188 //        validateStructure(millSchema, "MYSQL");
189         validateStructure(adapter, millSchema);
190 
191 //        validateStructure(millSchema, "IBM-DB2");
192 
193         System.out.println("Done validate structure in " + (System.currentTimeMillis() - mills) + " milliseconds");
194 
195     }
196 }