JdbcMetaData.java.txt 11.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
/*
 * Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
 *
 * This file is part of Resin(R) Open Source
 *
 * Each copy or derived work must preserve the copyright notice and this
 * notice unmodified.
 *
 * Resin Open Source is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Resin Open Source is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
 * of NON-INFRINGEMENT.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Resin Open Source; if not, write to the
 *
 *   Free Software Foundation, Inc.
 *   59 Temple Place, Suite 330
 *   Boston, MA 02111-1307  USA
 *
 * @author Scott Ferguson
 */

package com.caucho.jdbc;

import com.caucho.util.L10N;
import com.caucho.util.Log;

import javax.sql.DataSource;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Abstract way of grabbing data from the JDBC connection.
 */
public class JdbcMetaData {
  private static final L10N L = new L10N(JdbcMetaData.class);
  private static final Logger log = Log.open(JdbcMetaData.class);

  private DataSource _ds;

  /**
   * Create a new JDBC backing store.
   */
  protected JdbcMetaData(DataSource ds)
  {
    _ds = ds;
  }

  /**
   * Create based on the connection.
   */
  public static JdbcMetaData create(DataSource ds)
  {
    Connection conn = null;

    try {
      conn = ds.getConnection();

      DatabaseMetaData md = conn.getMetaData();

      String name = md.getDatabaseProductName();

      log.fine(L.l("Database '{0}' metadata.", name));

      if ("H2".equalsIgnoreCase(name))
    return new H2MetaData(ds);
      else if ("oracle".equalsIgnoreCase(name))
    return new OracleMetaData(ds);
      else if ("resin".equalsIgnoreCase(name))
    return new ResinMetaData(ds);
      else if ("postgres".equalsIgnoreCase(name) ||
           "PostgreSQL".equalsIgnoreCase(name))
    return new PostgresMetaData(ds);
      else if ("mysql".equalsIgnoreCase(name))
    return new MysqlMetaData(ds);
      else if ("Microsoft SQL Server".equalsIgnoreCase(name))
    return new SqlServerMetaData(ds);
      else {
    log.fine(name + " is an unknown database type");
    return new JdbcMetaData(ds);
      }
    } catch (SQLException e) {
      log.log(Level.FINE, e.toString(), e);
      return new JdbcMetaData(ds);
    } finally {
      try {
    if (conn != null) conn.close();
      } catch (SQLException e) {
      }
    }
  }

  /**
   * Returns the database name.
   */
  public String getDatabaseName()
  {
    Connection conn = null;

    try {
      conn = getConnection();

      DatabaseMetaData md = conn.getMetaData();

      return md.getDatabaseProductName();
    } catch (SQLException e) {
      log.log(Level.WARNING, e.toString(), e);
      return "unknown";
    } finally {
      try {
    if (conn != null) conn.close();
      } catch (SQLException e) {
      }
    }
  }

  /**
   * Returns the blob type.
   */
  public String getBlobType()
  {
    Connection conn = null;

    try {
      conn = getConnection();

      DatabaseMetaData md = conn.getMetaData();
      ResultSet rs;

      rs = md.getTypeInfo();
      try {
    while (rs.next()) {
      if (rs.getShort("DATA_TYPE") == Types.BLOB) {
        return rs.getString("TYPE_NAME");
      }
    }
      } finally {
    rs.close();
      }

      rs = md.getTypeInfo();
      try {
        while (rs.next()) {
          int dataType = rs.getShort("DATA_TYPE");

          if (rs.getShort("DATA_TYPE") == Types.LONGVARBINARY) {
            return rs.getString("TYPE_NAME");
          }
        }
      } finally {
        rs.close();
      }

      rs = md.getTypeInfo();
      try {
        while (rs.next()) {
          if (rs.getShort("DATA_TYPE") == Types.BINARY) {
            return rs.getString("TYPE_NAME");
          }
        }
      } finally {
        rs.close();
      }

      rs = md.getTypeInfo();
      try {
    while (rs.next()) {
      if (rs.getShort("DATA_TYPE") == Types.VARBINARY) {
        return rs.getString("TYPE_NAME");
      }
    }
      } finally {
    rs.close();
      }
    } catch (SQLException e) {
      log.log(Level.FINE, e.toString(), e);
    } finally {
      try {
    if (conn != null)
      conn.close();
      } catch (Exception e) {
      }
    }

    return null;
  }

  /**
   * Returns the long type.
   */
  public String getLongType()
  {
    Connection conn = null;

    try {
      conn = getConnection();

      DatabaseMetaData md = conn.getMetaData();
      ResultSet rs;

      rs = md.getTypeInfo();
      try {
    while (rs.next()) {
      if (rs.getShort("DATA_TYPE") == Types.BIGINT) {
        return rs.getString("TYPE_NAME");
      }
    }
      } finally {
    rs.close();
      }
    } catch (SQLException e) {
      log.log(Level.FINE, e.toString(), e);
    } finally {
      try {
    if (conn != null) conn.close();
      } catch (SQLException e) {
      }
    }

    return null;
  }

  /**
   * Returns true if identity is supported.
   */
  public boolean supportsIdentity()
  {
    return false;
  }

  /**
   * Returns the identity property
   */
  public String createIdentitySQL(String sqlType)
  {
    throw new UnsupportedOperationException(getClass().getName());
  }

  /**
   * Returns true if sequences are supported.
   */
  public boolean supportsSequences()
  {
    return false;
  }

  /**
   * Returns a sequence select expression.
   */
  public String createSequenceSQL(String name, int size)
  {
    throw new UnsupportedOperationException(getClass().getName());
  }

  /**
   * Returns a sequence select expression.
   */
  public String selectSequenceSQL(String name)
  {
    throw new UnsupportedOperationException(getClass().getName());
  }

  /**
   * Returns a sequence select expression.
   */
  public String testSequenceSQL(String name)
  {
    return selectSequenceSQL(name) + " WHERE 1=0";
  }

  /**
   * Returns the code to test for a boolean value for a term.
   */
  public String generateBoolean(String term)
  {
    return term;
  }

  /**
   * Returns a limit.
   */
  public String limit(String sql, int max)
  {
    return sql;
  }
  /**
   * New version to Return SQL for the table with the given
   * SQL type.  Takes, length, precision and scale.
   */
  public String getCreateColumnSQL(int sqlType, int length, int precision, int scale)
  {
    String type = null;

    switch (sqlType) {
    case Types.BOOLEAN:
      type = getCreateColumnSQLImpl(sqlType, length, precision, scale);
      if (type == null)
        type = getCreateColumnSQLImpl(Types.BIT, length, precision, scale);
      break;

    case Types.DATE:
      type = getCreateColumnSQLImpl(sqlType, length, precision, scale);
      if (type == null)
    type = getCreateColumnSQLImpl(Types.TIMESTAMP, length, precision, scale);
      break;

    case Types.TIME:
      type = getCreateColumnSQLImpl(sqlType, length, precision, scale);
      if (type == null)
    type = getCreateColumnSQLImpl(Types.TIMESTAMP, length, precision, scale);
      break;

    case Types.DOUBLE:
      type = getCreateColumnSQLImpl(Types.DOUBLE, length, precision, scale);
      break;

    case Types.NUMERIC:
        type = getCreateColumnSQLImpl(Types.NUMERIC, length, precision, scale);
        break;

    default:
      type = getCreateColumnSQLImpl(sqlType, length, precision, scale);
      break;
    }

    if (type == null)
      type = getDefaultCreateTableSQL(sqlType, length, precision, scale);

    return type;
  }

  /**
   * Returns the SQL for the table with the given SQL type.
   */
  protected String getCreateColumnSQLImpl(int sqlType, int length, int precision, int scale)
  {
    Connection conn = null;

    try {
      conn = getConnection();

      DatabaseMetaData md = conn.getMetaData();
      ResultSet rs;

      rs = md.getTypeInfo();

      try {
    while (rs.next()) {
      if (rs.getShort("DATA_TYPE") == sqlType) {
        String typeName = rs.getString("TYPE_NAME");
        String params = rs.getString("CREATE_PARAMS");

        if (params == null || params.equals(""))
          return typeName;
        else if (params.startsWith("(M)")) {
          if (length > 0)
        return typeName + "(" + length + ")";
          else
        return typeName;
        }
        else if (params.startsWith("(M,D)") || params.equals("precision,scale")) {
              if (precision > 0) {
                typeName += "(" + precision;
                if (scale > 0) {
                  typeName += "," + scale;
                }
                typeName += ")";
              }
          return typeName;
        }
        else if (params.startsWith("(")) {
          int tail = params.indexOf(')');

          if (tail > 0) {
        String value = params.substring(1, tail);
        boolean isConstant = true;

        for (int i = 0; i < value.length(); i++) {
          if (value.charAt(i) >= 'a' && value.charAt(i) <= 'z')
            isConstant = false;
          else if (value.charAt(i) >= 'A' && value.charAt(i) <= 'Z')
            isConstant = false;
        }

        if (isConstant)
          return typeName + "(" + value + ")";
          }

          return typeName;
        }
        else {
          return typeName;
        }
      }
    }
      } finally {
    rs.close();
      }
    } catch (Throwable e) {
      log.log(Level.FINE, e.toString(), e);
    } finally {
      try {
    if (conn != null)
      conn.close();
      } catch (Exception e) {
      }
    }

    return null;
  }

  protected String getDefaultCreateTableSQL(int sqlType, int length, int precision, int scale)
  {
    switch (sqlType) {
    case java.sql.Types.BOOLEAN:
      return "CHAR";
    case java.sql.Types.BIT:
    case java.sql.Types.TINYINT:
    case java.sql.Types.SMALLINT:
    case java.sql.Types.INTEGER:
    case java.sql.Types.BIGINT:
      return "INTEGER";
    case java.sql.Types.NUMERIC:
    case java.sql.Types.DECIMAL:
      String typeString = "NUMERIC";
      if (precision > 0) {
        typeString += "(" + precision;
        if (scale > 0) {
          typeString += "," + scale;
        }
        typeString += ")";
      }
      return typeString;
    case java.sql.Types.DOUBLE:
    case java.sql.Types.FLOAT:
      return "DOUBLE";
    case java.sql.Types.CHAR:
      return "CHAR";
    case java.sql.Types.DATE:
    case java.sql.Types.TIME:
    case java.sql.Types.TIMESTAMP:
        return "TIMESTAMP";
    default:
      return "VARCHAR(" + length + ")";
    }
  }

  /**
   * Returns a connection.
   */
  protected Connection getConnection()
    throws SQLException
  {
    return _ds.getConnection();
  }
}