public boolean tableExists(Connection connection, TableName tableName) throws PersistenceException { if (tableName == null) { throw new NullPointerException("table name is mandatory"); } ResultSet rs = null; try { // we need to make sure, that (even if the user has extended permissions) only the tables in // current schema are checked // explicit set of the schema to the current user one to make sure only tables of the current // users are requested DatabaseMetaData metaData = connection.getMetaData(); String schemaPattern = tableName.getSchema(); if (schemaPattern == null) { switch (getDialect()) { case ORACLE: schemaPattern = metaData.getUserName(); break; default: } } rs = metaData.getTables(null, schemaPattern, tableName.getName(), new String[] {"TABLE"}); return rs.next(); } catch (SQLException e) { if (trace) log.tracef(e, "SQLException occurs while checking the table %s", tableName); return false; } finally { JdbcUtil.safeClose(rs); } }
/** * Prints metadata, such as database username and connection URL, for an open JDBC connection. * This is a utility method for use during debugging. * * @param conn an open JDBC Connection * @throws SQLException */ private static void printConnectionMetaData(Connection conn) throws SQLException { if (conn != null) { DatabaseMetaData metadata = conn.getMetaData(); // FIXME: Outputs via System.out, rather than Logger, for // cases where this may be called during server startup. System.out.println("username="******"database url=" + metadata.getURL()); } }
public String getUserName() throws SQLException { { try { return _meta.getUserName(); } catch (SQLException e) { handleException(e); throw new AssertionError(); } } }
/** Returns a table's primary key columns as a Set of strings. */ public static Set<String> getPrimaryKey(DatabaseMetaData metadata, String tableName) throws Exception { Set<String> columns = new HashSet<String>(); ResultSet keys = metadata.getPrimaryKeys( metadata.getConnection().getCatalog(), metadata.getUserName(), tableName); while (keys.next()) { columns.add(keys.getString(PRIMARY_PK_COL_NAME)); } keys.close(); return columns; }
@Test public void testMatchInParametersAndSqlTypeInfoWrapping() throws Exception { final String TABLE = "customers"; final String USER = "******"; ResultSet metaDataResultSet = mock(ResultSet.class); given(metaDataResultSet.next()).willReturn(true, false); given(metaDataResultSet.getString("TABLE_SCHEM")).willReturn(USER); given(metaDataResultSet.getString("TABLE_NAME")).willReturn(TABLE); given(metaDataResultSet.getString("TABLE_TYPE")).willReturn("TABLE"); ResultSet columnsResultSet = mock(ResultSet.class); given(columnsResultSet.next()).willReturn(true, true, true, true, false); given(columnsResultSet.getString("COLUMN_NAME")) .willReturn("id", "name", "customersince", "version"); given(columnsResultSet.getInt("DATA_TYPE")) .willReturn(Types.INTEGER, Types.VARCHAR, Types.DATE, Types.NUMERIC); given(columnsResultSet.getBoolean("NULLABLE")).willReturn(false, true, true, false); given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB"); given(databaseMetaData.getDatabaseProductName()).willReturn("1.0"); given(databaseMetaData.getUserName()).willReturn(USER); given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true); given(databaseMetaData.getTables(null, null, TABLE, null)).willReturn(metaDataResultSet); given(databaseMetaData.getColumns(null, USER, TABLE, null)).willReturn(columnsResultSet); MapSqlParameterSource map = new MapSqlParameterSource(); map.addValue("id", 1); map.addValue("name", "Sven"); map.addValue("customersince", new Date()); map.addValue("version", 0); map.registerSqlType("customersince", Types.DATE); map.registerSqlType("version", Types.NUMERIC); context.setTableName(TABLE); context.processMetaData(dataSource, new ArrayList<>(), new String[] {}); List<Object> values = context.matchInParameterValuesWithInsertColumns(map); assertEquals("wrong number of parameters: ", 4, values.size()); assertTrue("id not wrapped with type info", values.get(0) instanceof Number); assertTrue("name not wrapped with type info", values.get(1) instanceof String); assertTrue("date wrapped with type info", values.get(2) instanceof SqlParameterValue); assertTrue("version wrapped with type info", values.get(3) instanceof SqlParameterValue); verify(metaDataResultSet, atLeastOnce()).next(); verify(columnsResultSet, atLeastOnce()).next(); verify(metaDataResultSet).close(); verify(columnsResultSet).close(); }
public static String getDBServerURL() { Connection conn = null; try { conn = DAOFactory.getInstance().getConnection(); if (conn != null) { DatabaseMetaData meta = conn.getMetaData(); return (meta.getURL() + ":" + meta.getUserName()).toUpperCase(); } } catch (SQLException e) { e.printStackTrace(); } finally { DBHelper.closeConnection(conn); } return ""; }
private static void print(Connection connection) { if (LOGGER.isDebugEnabled()) { try { DatabaseMetaData metadata = connection.getMetaData(); LOGGER.debug( "Returning Connection [" + metadata.getURL() + "] From user [" + metadata.getUserName() + "]"); } catch (Exception ex) { LOGGER.error("Error logging connection details: " + ex.getMessage(), ex); } } }
public CompositeMap getPrimaryKeys() throws SQLException { CompositeMap primaryKeyArray = new CommentCompositeMap(BMUtil.BMPrefix, AuroraConstant.BMUri, "primary-key"); String tableName = getTableName(); if (tableName == null) return primaryKeyArray; DatabaseMetaData dbMetaData = getDBMetaData(); ResultSet tableRet = dbMetaData.getPrimaryKeys(null, dbMetaData.getUserName(), tableName); while (tableRet.next()) { CompositeMap field = new CommentCompositeMap(BMUtil.BMPrefix, AuroraConstant.BMUri, "pk-field"); field.put("name", tableRet.getString("COLUMN_NAME").toLowerCase()); primaryKeyArray.addChild(field); } return primaryKeyArray; }
@Signature public Memory getMetaData() throws SQLException { ArrayMemory r = new ArrayMemory(); r.refOfIndex("userName").assign(metaData.getUserName()); r.refOfIndex("driverName").assign(metaData.getDriverName()); r.refOfIndex("driverVersion").assign(metaData.getDriverVersion()); r.refOfIndex("databaseName").assign(metaData.getDatabaseProductName()); r.refOfIndex("databaseVersion").assign(metaData.getDatabaseProductVersion()); r.refOfIndex("catalogSeparator").assign(metaData.getCatalogSeparator()); r.refOfIndex("catalogTerm").assign(metaData.getCatalogTerm()); r.refOfIndex("schemaTerm").assign(metaData.getSchemaTerm()); r.refOfIndex("procedureTerm").assign(metaData.getProcedureTerm()); r.refOfIndex("searchStringEscape").assign(metaData.getSearchStringEscape()); r.refOfIndex("numericFunctions").assign(metaData.getNumericFunctions()); r.refOfIndex("stringFunctions").assign(metaData.getStringFunctions()); r.refOfIndex("timeDateFunctions").assign(metaData.getTimeDateFunctions()); r.refOfIndex("systemFunctions").assign(metaData.getSystemFunctions()); r.refOfIndex("defaultTransactionIsolation").assign(metaData.getDefaultTransactionIsolation()); r.refOfIndex("identifierQuoteString").assign(metaData.getIdentifierQuoteString()); r.refOfIndex("maxBinaryLiteralLength").assign(metaData.getMaxBinaryLiteralLength()); r.refOfIndex("maxCatalogNameLength").assign(metaData.getMaxCatalogNameLength()); r.refOfIndex("maxCharLiteralLength").assign(metaData.getMaxCharLiteralLength()); r.refOfIndex("maxConnections").assign(metaData.getMaxConnections()); r.refOfIndex("maxColumnNameLength").assign(metaData.getMaxColumnNameLength()); r.refOfIndex("maxColumnsInGroupBy").assign(metaData.getMaxColumnsInGroupBy()); r.refOfIndex("maxColumnsInIndex").assign(metaData.getMaxColumnsInIndex()); r.refOfIndex("maxColumnsInOrderBy").assign(metaData.getMaxColumnsInOrderBy()); r.refOfIndex("maxColumnsInSelect").assign(metaData.getMaxColumnsInSelect()); r.refOfIndex("maxColumnsInTable").assign(metaData.getMaxColumnsInTable()); r.refOfIndex("maxCursorNameLength").assign(metaData.getMaxCursorNameLength()); r.refOfIndex("maxIndexLength").assign(metaData.getMaxIndexLength()); r.refOfIndex("maxProcedureNameLength").assign(metaData.getMaxProcedureNameLength()); r.refOfIndex("maxRowSize").assign(metaData.getMaxRowSize()); r.refOfIndex("maxSchemaNameLength").assign(metaData.getMaxSchemaNameLength()); r.refOfIndex("maxStatementLength").assign(metaData.getMaxStatementLength()); r.refOfIndex("maxTableNameLength").assign(metaData.getMaxTableNameLength()); r.refOfIndex("maxTablesInSelect").assign(metaData.getMaxTablesInSelect()); return r.toConstant(); }
@Override public IDatabaseConnection createConnection( final Connection con, final DatabaseMetaData databaseMetaData) throws SQLException, DatabaseUnitException { logger.warn( String.format( ">>>>> %s invoked to create a connection!\n", this.getClass().getSimpleName())); IDatabaseConnection connection = null; // FIXME not nice I found not a fast possibility to generate inside H2 // the tables inside a // schema as oracle do. final String driverName = databaseMetaData.getDriverName(); if (driverName.toLowerCase().contains("oracle")) { // oracle schema name is the user name connection = new DatabaseConnection(con, databaseMetaData.getUserName().toUpperCase()); } else { if (driverName.contains("H2")) { // H2 connection = new DatabaseConnection(con); } else if (driverName.contains("postgresql")) { // postgresql connection = new DatabaseConnection(con, "public"); } else { // all other connection = new DatabaseConnection(con); } } logger.warn( String.format( "<<<<< %s returns connection %s!\n", this.getClass().getSimpleName(), connection)); // final DatabaseConfig config = connection.getConfig(); // // oracle 10g // // FIXME at the moment we have a hard coded oracle notation // config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new // Oracle10DataTypeFactory()); return connection; }
@RequestMapping(method = RequestMethod.GET) public String showInformations(Model model) { List<Informations> info = new ArrayList<>(); info.add(new Informations("Versão", repInfo.getProperty("repository.version"))); info.add(new Informations("Número de documentos", Long.toString(docService.count()))); info.add( new Informations( "Domínio", config.getProperty("Repositorio.hostname"), "Este dominio será utilizado para criar a localização dos documentos. Editar no arquivo: 'config.properties'.")); info.add( new Informations( "Raiz do projeto", config.getProperty("Repositorio.rootPath", "/repositorio"))); info.add( new Informations( "Porta", config.getProperty("Repositorio.port", "8080"), "Porta informada no arquivo '/WEB-INF/classes/config.properties'")); info.add( new Informations( "URL dos objetos", Config.getUrl(config) + "{id}", "URL que será utilizada para criar o location dos objetos. Pode ser editada em: '/WEB-INF/classes/config.properties'")); try { DatabaseMetaData databaseInfo = dataSource.getConnection().getMetaData(); info.add(new Informations("Base de dados utilizada", databaseInfo.getDatabaseProductName())); info.add( new Informations("Versão da base de dados", databaseInfo.getDatabaseProductVersion())); info.add(new Informations("JDBC driver", databaseInfo.getDriverName())); info.add(new Informations("Versão do JDBC driver", databaseInfo.getDriverVersion())); info.add(new Informations("URL da base de dados", databaseInfo.getURL())); info.add(new Informations("Usuário da base de dados", databaseInfo.getUserName())); } catch (SQLException s) { log.error("Error getting information about database.", s); info.add(new Informations("Erro", "Não foi possível carregar os dados da base de dados")); } model.addAttribute("info", info); return "panel/show"; }
/** * Returns a table's foreign keys and their columns as a Map from the key name to the ForeignKey * object. * * <p>A foreign key may not have a name. On such a database, 2 foreign keys must reference 2 * different tables. Otherwise there's no way to tell them apart and the foreign key information * reported by DatabaseMetaData becomes ill-formed. */ public static Map<String, ForeignKey> getForeignKeys(DatabaseMetaData metadata, String tableName) throws Exception { ResultSet keys = metadata.getImportedKeys( metadata.getConnection().getCatalog(), metadata.getUserName(), tableName); Map<String, ForeignKey> map = new HashMap<String, ForeignKey>(); while (keys.next()) { String table = keys.getString(IMPORTED_PK_TAB_NAME); String name = keys.getString(IMPORTED_FK_KEY_NAME); if (name == null || name.length() == 0) name = "UNNAMED_FK_" + table; ForeignKey key = map.get(name); if (key == null) { map.put(name, key = new ForeignKey(table)); } key.add(keys.getString(IMPORTED_FK_COL_NAME)); } keys.close(); return map; }
@Test public void testTableWithSingleColumnGeneratedKey() throws Exception { final String TABLE = "customers"; final String USER = "******"; ResultSet metaDataResultSet = mock(ResultSet.class); given(metaDataResultSet.next()).willReturn(true, false); given(metaDataResultSet.getString("TABLE_SCHEM")).willReturn(USER); given(metaDataResultSet.getString("TABLE_NAME")).willReturn(TABLE); given(metaDataResultSet.getString("TABLE_TYPE")).willReturn("TABLE"); ResultSet columnsResultSet = mock(ResultSet.class); given(columnsResultSet.next()).willReturn(true, false); given(columnsResultSet.getString("COLUMN_NAME")).willReturn("id"); given(columnsResultSet.getInt("DATA_TYPE")).willReturn(Types.INTEGER); given(columnsResultSet.getBoolean("NULLABLE")).willReturn(false); given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB"); given(databaseMetaData.getDatabaseProductName()).willReturn("1.0"); given(databaseMetaData.getUserName()).willReturn(USER); given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true); given(databaseMetaData.getTables(null, null, TABLE, null)).willReturn(metaDataResultSet); given(databaseMetaData.getColumns(null, USER, TABLE, null)).willReturn(columnsResultSet); MapSqlParameterSource map = new MapSqlParameterSource(); String[] keyCols = new String[] {"id"}; context.setTableName(TABLE); context.processMetaData(dataSource, new ArrayList<>(), keyCols); List<Object> values = context.matchInParameterValuesWithInsertColumns(map); String insertString = context.createInsertString(keyCols); assertEquals("wrong number of parameters: ", 0, values.size()); assertEquals( "empty insert not generated correctly", "INSERT INTO customers () VALUES()", insertString); verify(metaDataResultSet, atLeastOnce()).next(); verify(columnsResultSet, atLeastOnce()).next(); verify(metaDataResultSet).close(); verify(columnsResultSet).close(); }
/* Clear all existing nodes from the tree model and rebuild from scratch. */ protected void refreshTree() { DefaultMutableTreeNode propertiesNode; DefaultMutableTreeNode leaf; // First clear the existing tree by simply enumerating // over the root node's children and removing them one by one. while (treeModel.getChildCount(rootNode) > 0) { DefaultMutableTreeNode child = (DefaultMutableTreeNode) treeModel.getChild(rootNode, 0); treeModel.removeNodeFromParent(child); child.removeAllChildren(); child.removeFromParent(); } treeModel.nodeStructureChanged(rootNode); treeModel.reload(); tScrollPane.repaint(); // Now rebuild the tree below its root try { // Start by naming the root node from its URL: rootNode.setUserObject(dMeta.getURL()); // get metadata about user tables by building a vector of table names String usertables[] = {"TABLE", "GLOBAL TEMPORARY", "VIEW"}; ResultSet result = dMeta.getTables(null, null, null, usertables); Vector tables = new Vector(); // sqlbob@users Added remarks. Vector remarks = new Vector(); while (result.next()) { tables.addElement(result.getString(3)); remarks.addElement(result.getString(5)); } result.close(); // For each table, build a tree node with interesting info for (int i = 0; i < tables.size(); i++) { String name = (String) tables.elementAt(i); DefaultMutableTreeNode tableNode = makeNode(name, rootNode); ResultSet col = dMeta.getColumns(null, null, name, null); // sqlbob@users Added remarks. String remark = (String) remarks.elementAt(i); if ((remark != null) && !remark.trim().equals("")) { makeNode(remark, tableNode); } // With a child for each column containing pertinent attributes while (col.next()) { String c = col.getString(4); DefaultMutableTreeNode columnNode = makeNode(c, tableNode); String type = col.getString(6); makeNode("Type: " + type, columnNode); boolean nullable = col.getInt(11) != DatabaseMetaData.columnNoNulls; makeNode("Nullable: " + nullable, columnNode); } col.close(); DefaultMutableTreeNode indexesNode = makeNode("Indices", tableNode); ResultSet ind = dMeta.getIndexInfo(null, null, name, false, false); String oldiname = null; // A child node to contain each index - and its attributes while (ind.next()) { DefaultMutableTreeNode indexNode = null; boolean nonunique = ind.getBoolean(4); String iname = ind.getString(6); if ((oldiname == null || !oldiname.equals(iname))) { indexNode = makeNode(iname, indexesNode); makeNode("Unique: " + !nonunique, indexNode); oldiname = iname; } // And the ordered column list for index components makeNode(ind.getString(9), indexNode); } ind.close(); } // Finally - a little additional metadata on this connection propertiesNode = makeNode("Properties", rootNode); makeNode("User: "******"ReadOnly: " + cConn.isReadOnly(), propertiesNode); makeNode("AutoCommit: " + cConn.getAutoCommit(), propertiesNode); makeNode("Driver: " + dMeta.getDriverName(), propertiesNode); makeNode("Product: " + dMeta.getDatabaseProductName(), propertiesNode); makeNode("Version: " + dMeta.getDatabaseProductVersion(), propertiesNode); } catch (SQLException se) { propertiesNode = makeNode("Error getting metadata:", rootNode); makeNode(se.getMessage(), propertiesNode); makeNode(se.getSQLState(), propertiesNode); } treeModel.nodeStructureChanged(rootNode); treeModel.reload(); tScrollPane.repaint(); }
/** Method declaration */ private void refreshTree() { tTree.removeAll(); try { int color_table = Color.yellow.getRGB(); int color_column = Color.orange.getRGB(); int color_index = Color.red.getRGB(); tTree.addRow("", dMeta.getURL(), "-", 0); String usertables[] = {"TABLE"}; ResultSet result = dMeta.getTables(null, null, null, usertables); Vector tables = new Vector(); // sqlbob@users Added remarks. Vector remarks = new Vector(); while (result.next()) { tables.addElement(result.getString(3)); remarks.addElement(result.getString(5)); } result.close(); for (int i = 0; i < tables.size(); i++) { String name = (String) tables.elementAt(i); String key = "tab-" + name + "-"; tTree.addRow(key, name, "+", color_table); // sqlbob@users Added remarks. String remark = (String) remarks.elementAt(i); if ((remark != null) && !remark.trim().equals("")) { tTree.addRow(key + "r", " " + remark); } ResultSet col = dMeta.getColumns(null, null, name, null); while (col.next()) { String c = col.getString(4); String k1 = key + "col-" + c + "-"; tTree.addRow(k1, c, "+", color_column); String type = col.getString(6); tTree.addRow(k1 + "t", "Type: " + type); boolean nullable = col.getInt(11) != DatabaseMetaData.columnNoNulls; tTree.addRow(k1 + "n", "Nullable: " + nullable); } col.close(); tTree.addRow(key + "ind", "Indices", "+", 0); ResultSet ind = dMeta.getIndexInfo(null, null, name, false, false); String oldiname = null; while (ind.next()) { boolean nonunique = ind.getBoolean(4); String iname = ind.getString(6); String k2 = key + "ind-" + iname + "-"; if ((oldiname == null || !oldiname.equals(iname))) { tTree.addRow(k2, iname, "+", color_index); tTree.addRow(k2 + "u", "Unique: " + !nonunique); oldiname = iname; } String c = ind.getString(9); tTree.addRow(k2 + "c-" + c + "-", c); } ind.close(); } tTree.addRow("p", "Properties", "+", 0); tTree.addRow("pu", "User: "******"pr", "ReadOnly: " + cConn.isReadOnly()); tTree.addRow("pa", "AutoCommit: " + cConn.getAutoCommit()); tTree.addRow("pd", "Driver: " + dMeta.getDriverName()); tTree.addRow("pp", "Product: " + dMeta.getDatabaseProductName()); tTree.addRow("pv", "Version: " + dMeta.getDatabaseProductVersion()); } catch (SQLException e) { tTree.addRow("", "Error getting metadata:", "-", 0); tTree.addRow("-", e.getMessage()); tTree.addRow("-", e.getSQLState()); } tTree.update(); }
public void init() throws ServletException { super.init(); ARE.getLog() .info( "**********************************InitDataServlet Start*********************************"); try { ARE.getLog() .info( "**============System Property Begin==============================================**"); Properties ps = System.getProperties(); Iterator ir = ps.keySet().iterator(); for (int i = 1; ir.hasNext(); i++) { String sKey = (String) ir.next(); ARE.getLog().info("(" + i + ")" + sKey + " = [" + ps.getProperty(sKey) + "]"); } ARE.getLog() .info( "**============System Property End=================================================**"); Transaction Sqlca = null; try { String sConfigFile = getInitParameter("ConfigFile"); if ((sConfigFile != null) && (!"".equals(sConfigFile))) { ASConfigure.setXMLFile(sConfigFile); ARE.getLog().info("ConfigFile = [" + sConfigFile + "]"); } ASConfigure asc = ASConfigure.getASConfigure(getServletContext()); Sqlca = getSqlca(asc); ARE.getLog() .info( "**============DataBase And JDBC Property Begin=====================================**"); DatabaseMetaData dbmd = Sqlca.conn.getMetaData(); ARE.getLog() .info( "DatabaseName[" + dbmd.getDatabaseProductName() + "] Version[" + dbmd.getDatabaseProductVersion() + "]"); ARE.getLog() .info( "Driver Name[" + dbmd.getDriverName() + "] Version[" + dbmd.getDriverVersion() + "]"); ARE.getLog() .info( "JDBC MajorVersion[" + dbmd.getJDBCMajorVersion() + "] MinorVersion[" + dbmd.getJDBCMinorVersion() + "]"); ARE.getLog().info("URL[" + dbmd.getURL() + "] UserName[" + dbmd.getUserName() + "]"); ARE.getLog() .info( "DatabaseState IsAutoCommit[" + Sqlca.conn.getAutoCommit() + "] TransactionIsolation[" + Sqlca.conn.getTransactionIsolation() + "]"); ARE.getLog() .info( "**============DataBase And JDBC Property End=======================================**"); ARE.getLog() .info("Init Cache Data[ALL] .......... Starting" + StringFunction.getNow()); ASConfigure.getSysConfig("ASCodeSet", Sqlca); ARE.getLog() .info("Init Cache Data[SYSCONFIG_CODE] .......... Success!" + StringFunction.getNow()); ASConfigure.getSysConfig("ASCompSet", Sqlca); ARE.getLog() .info("Init Cache Data[SYSCONFIG_COMP] .......... Success!" + StringFunction.getNow()); ASConfigure.getSysConfig("ASFuncSet", Sqlca); ARE.getLog() .info("Init Cache Data[SYSCONFIG_FUNC] .......... Success!" + StringFunction.getNow()); ASConfigure.getSysConfig("ASRoleSet", Sqlca); ARE.getLog() .info("Init Cache Data[SYSCONFIG_ROLE] .......... Success!" + StringFunction.getNow()); ARE.getLog() .info("Init Cache Data[ALL] .......... Success!" + StringFunction.getNow()); } catch (Exception e) { ARE.getLog().info("InitDataServerlet :error", e); e.printStackTrace(); throw new RuntimeException("构造系统配置时出错:" + e); } finally { try { if (Sqlca != null) { Sqlca.conn.commit(); Sqlca.disConnect(); Sqlca = null; } } catch (Exception e1) { } } } catch (Exception e) { ARE.getLog().info("InitDataServerlet :error", e); e.printStackTrace(); } ARE.getLog() .info( "**********************************InitDataServlet Success*********************************"); ARE.getLog().info(""); }
public void testMetaData() { String ddl0 = "DROP TABLE ADDRESSBOOK IF EXISTS; DROP TABLE ADDRESSBOOK_CATEGORY IF EXISTS; DROP TABLE USER IF EXISTS;"; String ddl1 = "CREATE TABLE USER(USER_ID INTEGER NOT NULL PRIMARY KEY,LOGIN_ID VARCHAR(128) NOT NULL,USER_NAME VARCHAR(254) DEFAULT ' ' NOT NULL,CREATE_DATE TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,UPDATE_DATE TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,LAST_ACCESS_DATE TIMESTAMP,CONSTRAINT IXUQ_LOGIN_ID0 UNIQUE(LOGIN_ID))"; String ddl2 = "CREATE TABLE ADDRESSBOOK_CATEGORY(USER_ID INTEGER NOT NULL,CATEGORY_ID INTEGER DEFAULT 0 NOT NULL,CATEGORY_NAME VARCHAR(60) DEFAULT '' NOT NULL,CONSTRAINT SYS_PK_ADDRESSBOOK_CATEGORY PRIMARY KEY(USER_ID,CATEGORY_ID),CONSTRAINT FK_ADRBKCAT1 FOREIGN KEY(USER_ID) REFERENCES USER(USER_ID) ON DELETE CASCADE)"; String ddl3 = "CREATE TABLE ADDRESSBOOK(USER_ID INTEGER NOT NULL,ADDRESSBOOK_ID INTEGER NOT NULL,CATEGORY_ID INTEGER DEFAULT 0 NOT NULL,FIRST VARCHAR(64) DEFAULT '' NOT NULL,LAST VARCHAR(64) DEFAULT '' NOT NULL,NOTE VARCHAR(128) DEFAULT '' NOT NULL,CONSTRAINT SYS_PK_ADDRESSBOOK PRIMARY KEY(USER_ID,ADDRESSBOOK_ID),CONSTRAINT FK_ADRBOOK1 FOREIGN KEY(USER_ID,CATEGORY_ID) REFERENCES ADDRESSBOOK_CATEGORY(USER_ID,CATEGORY_ID) ON DELETE CASCADE)"; String result1 = "1"; String result2 = "2"; String result3 = "3"; String result4 = "4"; String result5 = "5"; try { stmnt.execute(ddl0); stmnt.execute(ddl1); stmnt.execute(ddl2); stmnt.execute(ddl3); DatabaseMetaData md = connection.getMetaData(); { System.out.println("Testing DatabaseMetaData methods"); System.out.println(md.getDatabaseMajorVersion()); System.out.println(md.getDatabaseMinorVersion()); System.out.println(md.getDatabaseProductName()); System.out.println(md.getDatabaseProductVersion()); System.out.println(md.getDefaultTransactionIsolation()); System.out.println(md.getDriverMajorVersion()); System.out.println(md.getDriverMinorVersion()); System.out.println(md.getDriverName()); System.out.println(md.getDriverVersion()); System.out.println(md.getExtraNameCharacters()); System.out.println(md.getIdentifierQuoteString()); System.out.println(md.getJDBCMajorVersion()); System.out.println(md.getJDBCMinorVersion()); System.out.println(md.getMaxBinaryLiteralLength()); System.out.println(md.getMaxCatalogNameLength()); System.out.println(md.getMaxColumnsInGroupBy()); System.out.println(md.getMaxColumnsInIndex()); System.out.println(md.getMaxColumnsInOrderBy()); System.out.println(md.getMaxColumnsInSelect()); System.out.println(md.getMaxColumnsInTable()); System.out.println(md.getMaxConnections()); System.out.println(md.getMaxCursorNameLength()); System.out.println(md.getMaxIndexLength()); System.out.println(md.getMaxProcedureNameLength()); System.out.println(md.getMaxRowSize()); System.out.println(md.getMaxSchemaNameLength()); System.out.println(md.getMaxStatementLength()); System.out.println(md.getMaxStatements()); System.out.println(md.getMaxTableNameLength()); System.out.println(md.getMaxUserNameLength()); System.out.println(md.getNumericFunctions()); System.out.println(md.getProcedureTerm()); System.out.println(md.getResultSetHoldability()); System.out.println(md.getSchemaTerm()); System.out.println(md.getSearchStringEscape()); System.out.println("Testing DatabaseMetaData.getSQLKeywords()"); System.out.println(md.getSQLKeywords()); System.out.println(md.getSQLStateType()); System.out.println("Testing DatabaseMetaData.getStringFunctions()"); System.out.println(md.getStringFunctions()); System.out.println("Testing DatabaseMetaData.getSystemFunctions()"); System.out.println(md.getSystemFunctions()); System.out.println("Testing DatabaseMetaData.getTimeDateFunctions()"); System.out.println(md.getTimeDateFunctions()); System.out.println(md.getURL()); System.out.println(md.getUserName()); System.out.println(DatabaseMetaData.importedKeyCascade); System.out.println(md.isCatalogAtStart()); System.out.println(md.isReadOnly()); ResultSet rs; rs = md.getPrimaryKeys(null, null, "USER"); ResultSetMetaData rsmd = rs.getMetaData(); String result0 = ""; for (; rs.next(); ) { for (int i = 0; i < rsmd.getColumnCount(); i++) { result0 += rs.getString(i + 1) + ":"; } result0 += "\n"; } rs.close(); System.out.println(result0); } { ResultSet rs; rs = md.getBestRowIdentifier(null, null, "USER", 0, true); ResultSetMetaData rsmd = rs.getMetaData(); String result0 = ""; for (; rs.next(); ) { for (int i = 0; i < rsmd.getColumnCount(); i++) { result0 += rs.getString(i + 1) + ":"; } result0 += "\n"; } rs.close(); System.out.println(result0); } { ResultSet rs = md.getImportedKeys(null, null, "ADDRESSBOOK"); ResultSetMetaData rsmd = rs.getMetaData(); result1 = ""; for (; rs.next(); ) { for (int i = 0; i < rsmd.getColumnCount(); i++) { result1 += rs.getString(i + 1) + ":"; } result1 += "\n"; } rs.close(); System.out.println(result1); } { ResultSet rs = md.getCrossReference(null, null, "ADDRESSBOOK_CATEGORY", null, null, "ADDRESSBOOK"); ResultSetMetaData rsmd = rs.getMetaData(); result2 = ""; for (; rs.next(); ) { for (int i = 0; i < rsmd.getColumnCount(); i++) { result2 += rs.getString(i + 1) + ":"; } result2 += "\n"; } rs.close(); System.out.println(result2); } { ResultSet rs = md.getExportedKeys(null, null, "USER"); ResultSetMetaData rsmd = rs.getMetaData(); result3 = ""; for (; rs.next(); ) { for (int i = 0; i < rsmd.getColumnCount(); i++) { result3 += rs.getString(i + 1) + ":"; } result3 += "\n"; } rs.close(); System.out.println(result3); } { ResultSet rs = md.getCrossReference(null, null, "USER", null, null, "ADDRESSBOOK_CATEGORY"); ResultSetMetaData rsmd = rs.getMetaData(); result4 = ""; for (; rs.next(); ) { for (int i = 0; i < rsmd.getColumnCount(); i++) { result4 += rs.getString(i + 1) + ":"; } result4 += "\n"; } rs.close(); System.out.println(result4); } { stmnt.execute("DROP TABLE T IF EXISTS;"); stmnt.execute("CREATE TABLE T (I IDENTITY, A CHAR(20), B CHAR(20));"); stmnt.execute("INSERT INTO T VALUES (NULL, 'get_column_name', '" + getColumnName + "');"); ResultSet rs = stmnt.executeQuery("SELECT I, A, B, A \"aliasA\", B \"aliasB\", 1 FROM T;"); ResultSetMetaData rsmd = rs.getMetaData(); result5 = ""; for (; rs.next(); ) { for (int i = 0; i < rsmd.getColumnCount(); i++) { result5 += rsmd.getColumnName(i + 1) + ":" + rs.getString(i + 1) + ":"; } result5 += "\n"; } rs.close(); rs = stmnt.executeQuery("SELECT I, A, B, A \"aliasA\", B \"aliasB\", 1 FROM T;"); rsmd = rs.getMetaData(); for (; rs.next(); ) { for (int i = 0; i < rsmd.getColumnCount(); i++) { result5 += rsmd.getColumnLabel(i + 1) + ":" + rs.getString(i + 1) + ":"; } result5 += "\n"; } System.out.println(result5); System.out.println("first column identity: " + rsmd.isAutoIncrement(1)); rsmd.isCaseSensitive(1); rsmd.isCurrency(1); rsmd.isDefinitelyWritable(1); rsmd.isNullable(1); rsmd.isReadOnly(1); rsmd.isSearchable(1); rsmd.isSigned(1); rsmd.isWritable(1); rs.close(); // test identity with PreparedStatement pstmnt = connection.prepareStatement("INSERT INTO T VALUES (?,?,?)"); pstmnt.setString(1, null); pstmnt.setString(2, "test"); pstmnt.setString(3, "test2"); pstmnt.executeUpdate(); pstmnt = connection.prepareStatement("call identity()"); ResultSet rsi = pstmnt.executeQuery(); rsi.next(); int identity = rsi.getInt(1); System.out.println("call identity(): " + identity); rsi.close(); } } catch (SQLException e) { fail(e.getMessage()); } System.out.println("testMetaData complete"); // assert equality of exported and imported with xref assertEquals(result1, result2); assertEquals(result3, result4); }
public String getUserName() throws SQLException { return throwExceptionDelegate.getUserName(); }