01: /*
02: * User: Michael Rettig
03: * Date: Aug 10, 2002
04: * Time: 2:17:13 PM
05: */
06: package net.sourceforge.jaxor.example.tests;
07:
08: import net.sourceforge.jaxor.MetaField;
09: import net.sourceforge.jaxor.MetaRow;
10: import net.sourceforge.jaxor.api.Mapper;
11: import net.sourceforge.jaxor.example.db.JaxorContextTestingFactory;
12: import net.sourceforge.jaxor.util.SystemException;
13:
14: import java.sql.Connection;
15: import java.sql.SQLException;
16: import java.sql.Statement;
17: import java.util.List;
18: import java.util.Iterator;
19:
20: public class TableMaker {
21:
22: public static void createTable(MetaRow metaRow, Connection conn,
23: JaxorContextTestingFactory fact) {
24: String sql = createSql(metaRow, fact);
25: execute(conn, sql);
26: }
27:
28: public static void dropTable(String table, Connection conn) {
29: execute(conn, "drop table " + table);
30: }
31:
32: private static void execute(Connection conn, String sql) {
33: Statement stmt = null;
34: try {
35: stmt = conn.createStatement();
36: stmt.execute(sql);
37: } catch (SQLException e) {
38: throw new SystemException(sql, e);
39: } finally {
40: if (stmt != null) {
41: try {
42: stmt.close();
43: } catch (SQLException e) {
44: e.printStackTrace();
45: }
46: }
47: }
48: }
49:
50: public static String createSql(MetaRow metaRow,
51: JaxorContextTestingFactory fact) {
52: StringBuffer buf = new StringBuffer("create table "
53: + metaRow.getTableName());
54: buf.append("(");
55:
56: List pkColumns = metaRow.getPrimaryKey();
57: for (Iterator iterator = pkColumns.iterator(); iterator
58: .hasNext();) {
59: MetaField metaField = (MetaField) iterator.next();
60: appendColumn(metaField, buf, fact);
61: if (pkColumns.size() == 1)
62: buf.append(" PRIMARY KEY ");
63: if (iterator.hasNext())
64: buf.append(",");
65: }
66: List columns = metaRow.getNonPrimaryKeyColumns();
67: for (int i = 0; i < columns.size(); i++) {
68: if (i > 0 || pkColumns.size() > 0)
69: buf.append(",");
70: appendColumn((MetaField) columns.get(i), buf, fact);
71: }
72: buf.append(")");
73: return buf.toString();
74: }
75:
76: private static void appendColumn(MetaField field, StringBuffer buf,
77: JaxorContextTestingFactory fact) {
78: Mapper mapper = field.getMapperInstance();
79: buf.append(field.getColumn());
80: buf.append(" ");
81: buf.append(fact.getCreateTable(mapper));
82: if (!field.isPrimaryKey() && !field.isAutoAssign()) {
83: if (field.canBeNull())
84: buf.append(" null ");
85: else
86: buf.append(" not null ");
87: }
88: if (field.isAutoAssign() && fact.hasAutoIncrementColumns())
89: buf.append(" " + fact.getAutoIncrementKeyword() + " ");
90: }
91:
92: }
|