001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Florent Guillaume
011 */
012
013package org.nuxeo.ecm.core.storage.sql.jdbc.db;
014
015import java.io.Serializable;
016import java.util.Collection;
017import java.util.HashSet;
018import java.util.Iterator;
019import java.util.LinkedHashMap;
020import java.util.Map;
021import java.util.Set;
022
023import org.nuxeo.ecm.core.storage.sql.jdbc.dialect.Dialect;
024
025/**
026 * A collection of {@link Table}s.
027 *
028 * @author Florent Guillaume
029 */
030public class Database implements Serializable {
031
032    private static final long serialVersionUID = 1L;
033
034    protected final Dialect dialect;
035
036    protected final Map<String, Table> tables;
037
038    protected final Set<String> physicalTables;
039
040    public Database(Dialect dialect) {
041        this.dialect = dialect;
042        tables = new LinkedHashMap<String, Table>();
043        physicalTables = new HashSet<String>();
044    }
045
046    public Table addTable(String name) throws IllegalArgumentException {
047        String physicalName = dialect.getTableName(name);
048        if (!physicalTables.add(physicalName)) {
049            throw new IllegalArgumentException("Duplicate table name: " + physicalName);
050        }
051        Table table = new TableImpl(dialect, physicalName, name);
052        tables.put(name, table);
053        return table;
054    }
055
056    public Table getTable(String name) {
057        return tables.get(name);
058    }
059
060    public Collection<Table> getTables() {
061        return tables.values();
062    }
063
064    @Override
065    public String toString() {
066        StringBuilder buf = new StringBuilder();
067        buf.append(getClass().getSimpleName());
068        buf.append('(');
069        for (Iterator<Table> iter = tables.values().iterator(); iter.hasNext();) {
070            Table table = iter.next();
071            buf.append(table.getPhysicalName());
072            if (iter.hasNext()) {
073                buf.append(',');
074            }
075        }
076        buf.append(')');
077        return buf.toString();
078    }
079
080}