KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > xquark > mapper > dbms > SQLTableBuilder


1 /*
2  * This file belongs to the XQuark distribution.
3  * Copyright (C) 2003 Universite de Versailles Saint-Quentin.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307.
18  * You can also get it at http://www.gnu.org/licenses/lgpl.html
19  *
20  * For more information on this software, see http://www.xquark.org.
21  */

22
23 /*
24  * SQLTableBuilder.java
25  *
26  * Created on 5 décembre 2000, 17:22
27  */

28
29 package org.xquark.mapper.dbms;
30
31 import java.io.*;
32 import java.sql.SQLException JavaDoc;
33
34 import javax.xml.parsers.SAXParserFactory JavaDoc;
35
36 import org.xml.sax.InputSource JavaDoc;
37 import org.xml.sax.SAXException JavaDoc;
38 import org.xquark.mapper.RepositoryException;
39 import org.xquark.mapper.mapping.*;
40 import org.xquark.mapper.metadata.RepositoryConstants;
41
42 /** This utility allows to generate table in the relational database basing on
43  * a mapping file and its associated schemas.
44  * <p>It is able to directly generate tables through JDBC or generate an SQL script file.</p>
45  * <p>This tool must be used after the referenced schemas repository storage with the
46  * {@link org.xquark.mapper.Repository#saveSchema saveSchema} method and
47  * before mapping storage with {@link org.xquark.mapper.Repository#saveMapping saveMapping}
48  * that will refuse execution until relational table exist.
49  * @see org.xquark.mapper.Repository#saveSchema
50  * @see org.xquark.mapper.Repository#saveMapping
51  */

52 public class SQLTableBuilder implements RepositoryConstants
53 {
54 private static final String JavaDoc RCSRevision = "$Revision: 1.1 $";
55 private static final String JavaDoc RCSName = "$Name: $";
56     static StringBuffer JavaDoc pkConstraintStmt = new StringBuffer JavaDoc();
57     static StringBuffer JavaDoc fkConstraintStmt1 = new StringBuffer JavaDoc();
58     static StringBuffer JavaDoc fkConstraintStmt2 = new StringBuffer JavaDoc();
59
60     public static void generateScripts(_RepositoryConnection repConn, String JavaDoc mappingURL, File wPath)
61     throws Exception JavaDoc
62     {
63         final String JavaDoc SQLCreateFile = "CreateTables.sql";
64         final String JavaDoc SQLDropFile = "DropTables.sql";
65         
66         RepositoryMapping mapping = null;
67         
68         ///////////////////// Loading Schema(s) and Mapping //////////////////////
69

70         System.out.println("Loading Schema and Mapping...");
71         try {
72             MappingFactory factory = new MappingFactory(
73                 repConn.getSchemaManager(),
74                 repConn
75                 );
76             mapping = (RepositoryMapping)factory.createTree();
77             SAXParserFactory JavaDoc parserFactory = SAXParserFactory.newInstance();
78             parserFactory.setNamespaceAware(true);
79             Loader loader = new Loader(parserFactory.newSAXParser().getXMLReader(),
80                                         repConn.getConnection(), repConn.getSchemaManager(), true);
81             InputSource JavaDoc source = new InputSource JavaDoc(mappingURL);
82             mapping = loader.load(source, factory, false);
83         }
84         catch(SAXException JavaDoc e) {
85             throw new RepositoryException(RepositoryException.SAX_OUTPUT_ERROR, e.getMessage(), e.getException());
86         }
87         catch(SQLException JavaDoc e) {
88             throw new RepositoryException(RepositoryException.DB_ERROR, "JDBC error while loading mapping", e);
89         }
90
91         ///////////////////// Processing table generation //////////////////////
92

93         /* Create output files */
94         PrintStream createFile = null;
95         PrintStream dropFile = null;
96         try {
97             createFile = new PrintStream(new FileOutputStream(new File(wPath, SQLCreateFile)), true);
98             dropFile = new PrintStream(new FileOutputStream(new File(wPath, SQLDropFile)), true);
99         }
100         catch(FileNotFoundException e) {
101             throw new RepositoryException(RepositoryException.SYSTEM_ERROR, "Could not open files to generate", e);
102         }
103             
104         /* Generate output file */
105         System.out.println("Generating SQL script...");
106         generateSQL(repConn, createFile, dropFile, mapping);
107         createFile.close();
108         dropFile.close();
109     }
110             
111     private static void generateSQL(_RepositoryConnection repConn,
112             PrintStream outPrinter,
113             PrintStream dropPrinter,
114             RepositoryMapping mapping)
115     throws RepositoryException
116     {
117         MappingSetIterator itt = mapping.getSortedTableMappingSetIterator(false);
118         TableMapping tableMapping;
119         
120         /* Table loop for creation statements */
121         while (itt.hasNext())
122         {
123             pkConstraintStmt.setLength(0);
124             fkConstraintStmt1.setLength(0);
125             fkConstraintStmt2.setLength(0);
126             boolean firstColumn = true;
127             tableMapping = itt.next().getTableMapping();
128
129             /* Create statement */
130             outPrinter.print("CREATE TABLE ");
131             outPrinter.print(tableMapping.getTableName());
132             outPrinter.println("(");
133             
134             /* Columns loop */
135             ColumnMapping[] columns = tableMapping.getColumnMappings();
136             for(int i = 0; i < columns.length; i++)
137             {
138                 if (firstColumn)
139                     firstColumn = false;
140                 else
141                     outPrinter.println(","); // REGLER LE PB DE LA VIRGULE
142
generateSQLforColumn(repConn, outPrinter, columns[i], mapping);
143             }
144             /* Writing pk constraint */
145             if (pkConstraintStmt.length() > 0)
146             {
147                 pkConstraintStmt.setLength(pkConstraintStmt.length() - 1);
148                 outPrinter.println(",");
149                 outPrinter.print("PRIMARY KEY(" + pkConstraintStmt + ")");
150             }
151             /* Writing fk constraint */
152             if (fkConstraintStmt1.length() > 0)
153             {
154                 fkConstraintStmt1.setLength(fkConstraintStmt1.length() - 1);
155                 fkConstraintStmt2.setLength(fkConstraintStmt2.length() - 1);
156                 outPrinter.println(",");
157                 outPrinter.print("FOREIGN KEY(" + fkConstraintStmt1 + ")");
158                 outPrinter.print(" REFERENCES " + fkConstraintStmt2 + ")");
159             }
160             /* Ending Create statement */
161             outPrinter.println();
162             outPrinter.println(");");
163             outPrinter.println();
164         }
165         
166         itt = mapping.getSortedTableMappingSetIterator(true);
167         
168         /* Table loop for drop statements */
169         while (itt.hasNext())
170         {
171             tableMapping = itt.next().getTableMapping();
172             /* Create statement */
173             dropPrinter.print("DROP TABLE ");
174             dropPrinter.println(tableMapping.getTableName() + ";");
175         }
176     }
177     
178     private static void generateSQLforColumn(_RepositoryConnection repConn,
179                                             PrintStream outPrinter,
180                                             ColumnMapping mapping,
181                                             RepositoryMapping repMapping)
182     throws RepositoryException
183     {
184         TableMapping refTableMapping = null;
185         ColumnMapping refColumnMapping = null;
186         StringBuffer JavaDoc columnStmt = new StringBuffer JavaDoc();
187         
188         /* writing column definition */
189         columnStmt.append(mapping.getColumnName());
190         
191         /* Column type */
192         columnStmt.append(" ");
193         columnStmt.append(mapping.getTypeInfo().getTypeCreationString(repConn.getConnection()));
194         
195         /* Primary key (if not, nullable for simplification) */
196         if (mapping.getKeyColumnIndex() != -1)
197         {
198             pkConstraintStmt.append(mapping.getColumnName());
199             pkConstraintStmt.append(",");
200             columnStmt.append(" NOT NULL");
201         }
202         outPrinter.print(columnStmt);
203         
204         /* Foreign key */
205         if (mapping.getTableRefIndex() != -1)
206         {
207             refTableMapping = repMapping.getTableMapping(mapping.getTableRefIndex());
208             refColumnMapping = ((ColumnRefGenerator)mapping.getGenerator()).getColumnRef();
209             fkConstraintStmt1.append(mapping.getColumnName());
210             fkConstraintStmt1.append(",");
211             
212             if (fkConstraintStmt2.length() == 0)
213             {
214                 fkConstraintStmt2.append(refTableMapping.getTableName());
215                 fkConstraintStmt2.append("(");
216             }
217             fkConstraintStmt2.append(refColumnMapping.getColumnName());
218             fkConstraintStmt2.append(",");
219         }
220     }
221 }
222
Popular Tags