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

cdc.rdb.RdbHelper Maven / Gradle / Ivy

package cdc.rdb;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.List;

import cdc.util.strings.StringUtils;

public class RdbHelper {
    private final String catalogSeparator;
    private final String identifierQuoteString;

    public RdbHelper(DatabaseMetaData metadata) throws SQLException {
        this.catalogSeparator = metadata.getCatalogSeparator();
        this.identifierQuoteString = metadata.getIdentifierQuoteString();
    }

    public RdbHelper(Connection connection) throws SQLException {
        this(connection.getMetaData());
    }

    public String getCatalogSeparator() {
        return catalogSeparator;
    }

    public String getIdentifierQuoteString() {
        return identifierQuoteString;
    }

    public String wrapIdentifier(String s) {
        return identifierQuoteString + s + identifierQuoteString;
    }

    public String getQueryTableName(String schemaName,
                                    String tableName) {
        if (StringUtils.isNullOrEmpty(schemaName)) {
            return wrapIdentifier(tableName);
        } else {
            if (StringUtils.isNullOrEmpty(catalogSeparator)) {
                return wrapIdentifier(schemaName) + "." + wrapIdentifier(tableName);
            } else {
                // Should we do that ?
                return wrapIdentifier(schemaName) + catalogSeparator + wrapIdentifier(tableName);
            }
        }
    }

    public String getSelectClause(String schemaName,
                                  String tableName) {
        return "SELECT * FROM " + getQueryTableName(schemaName, tableName);
    }

    public String getOrderClause(List sortings) {
        if (sortings.isEmpty()) {
            return "";
        } else {
            final StringBuilder builder = new StringBuilder();
            builder.append(" ORDER BY");
            boolean first = true;
            for (final RdbColumnSorting sorting : sortings) {
                if (first) {
                    first = false;
                } else {
                    builder.append(",");
                }
                builder.append(" ");
                builder.append(identifierQuoteString);
                builder.append(sorting.getColumnName());
                builder.append(identifierQuoteString);
                builder.append(" ");
                builder.append(sorting.getOrder() == RdbColumnOrder.ASCENDING ? "ASC" : "DESC");
            }
            return builder.toString();
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy