All Downloads are FREE. Search and download functionalities are using the official Maven repository.

me.icymint.libra.jdbc.model.SqlFactory Maven / Gradle / Ivy

package me.icymint.libra.jdbc.model;

import java.sql.SQLException;
import java.util.Map;
import java.util.WeakHashMap;

/**
 * SQL工厂。
 * 
 * @author Daniel Yu
 * @since 2013-3-6
 * 
 */
public class SqlFactory extends SqlObject {
	/**
	 * 创造SQL工厂。
	 * 
	 * @param si
	 */
	public static final SqlFactory newInstance(SqlInfo si) {
		return new SqlFactory(si);
	}

	private final Database db;
	private Map map = new WeakHashMap();

	private SqlFactory(SqlInfo si) {
		this.setInfo(si);
		db = new Database(this);
		db.setInfo(si);
	}

	public Column createColumn(String name, int jdbcType, int length,
			boolean required, boolean autoIncrement, Object defaultValue)
			throws SQLException {
		String id = SqlObject.id(getInfo(), name, jdbcType, length,
				defaultValue);
		Column c = map.get(id);
		if (c == null) {
			synchronized (map) {
				c = map.get(id);
				if (c == null) {
					c = this.newInstance(Column.class, id, name);
					c.setTypes(jdbcType);
					c.setLength(length);
					c.setDefaultValue(defaultValue);
					c.setNotNull(required);
					c.setAutoIncrement(autoIncrement);
					map.put(id, c);
				}
			}
		}
		return c;
	}

	public Table createTable(String name, String[] keys, Column[] cols)
			throws SQLException {
		String id = SqlObject.id(getInfo(), name);
		Table t = this.newInstance(Table.class, id, name);
		t.setColumns(cols);
		t.setKeys(keys);
		return t;
	}

	public Database getDatabase() {
		return db;
	}

	@Override
	public String getId() {
		return this.getInfo().getId();
	}

	@Override
	public String getName() {
		return this.getInfo().getName();
	}

	private  T newInstance(Class cls, String id,
			String name) throws SQLException {
		try {
			T t = cls.newInstance();
			t.setId(id);
			t.setName(name);
			t.setInfo(this.getInfo());
			return t;
		} catch (InstantiationException e) {
			throw new SQLException(e);
		} catch (IllegalAccessException e) {
			throw new SQLException(e);
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy