db-derby-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From rhille...@apache.org
Subject svn commit: r905289 - in /db/derby/code/trunk/java: engine/org/apache/derby/catalog/types/ engine/org/apache/derby/iapi/types/ engine/org/apache/derby/impl/load/ engine/org/apache/derby/impl/sql/compile/ testing/org/apache/derbyTesting/functionTests/te...
Date Mon, 01 Feb 2010 14:38:13 GMT
Author: rhillegas
Date: Mon Feb  1 14:38:12 2010
New Revision: 905289

URL: http://svn.apache.org/viewvc?rev=905289&view=rev
Log:
DERBY-4484: Add export/import of UDT columns to/from the same file which holds the other columns.

Modified:
    db/derby/code/trunk/java/engine/org/apache/derby/catalog/types/BaseTypeIdImpl.java
    db/derby/code/trunk/java/engine/org/apache/derby/catalog/types/UserDefinedTypeIdImpl.java
    db/derby/code/trunk/java/engine/org/apache/derby/iapi/types/DataTypeDescriptor.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/load/ColumnInfo.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/load/ExportAbstract.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/load/Import.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/load/ImportAbstract.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/load/ImportResultSetMetaData.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/CreateTableNode.java
    db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/ValueNode.java
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/lang/UDTTest.java
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/tools/ImportExportTest.java

Modified: db/derby/code/trunk/java/engine/org/apache/derby/catalog/types/BaseTypeIdImpl.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/catalog/types/BaseTypeIdImpl.java?rev=905289&r1=905288&r2=905289&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/catalog/types/BaseTypeIdImpl.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/catalog/types/BaseTypeIdImpl.java Mon
Feb  1 14:38:12 2010
@@ -74,7 +74,7 @@
     private int   formatId;
 
     // schema where the type lives. only for UDTs
-    private String schemaName;
+    protected String schemaName;
 
     // unqualified type name
     String unqualifiedName;

Modified: db/derby/code/trunk/java/engine/org/apache/derby/catalog/types/UserDefinedTypeIdImpl.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/catalog/types/UserDefinedTypeIdImpl.java?rev=905289&r1=905288&r2=905289&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/catalog/types/UserDefinedTypeIdImpl.java
(original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/catalog/types/UserDefinedTypeIdImpl.java
Mon Feb  1 14:38:12 2010
@@ -22,6 +22,8 @@
 package org.apache.derby.catalog.types;
 
 import org.apache.derby.iapi.services.io.StoredFormatIds;
+import org.apache.derby.iapi.util.IdUtil;
+import org.apache.derby.iapi.error.StandardException;
 
 import java.sql.Types;
 import java.io.ObjectOutput;
@@ -81,9 +83,28 @@
 
 	public UserDefinedTypeIdImpl(String className)
 	{
-		super(className);
-		this.className = className;
-		JDBCTypeId = java.sql.Types.JAVA_OBJECT;
+        try {
+            //
+            // If the name begins with a quote, then it is the schema-qualified name
+            // of a UDT. Parse the name.
+            //
+            if ( className.charAt( 0 ) == '"' )
+            {
+                String[] nameParts = IdUtil.parseMultiPartSQLIdentifier( className );
+                
+                schemaName = nameParts[ 0 ];
+                unqualifiedName = nameParts[ 1 ];
+                className = null;
+            }
+            else
+            {
+                schemaName = null;
+                unqualifiedName = className;
+                this.className = className;
+            }
+            
+            JDBCTypeId = java.sql.Types.JAVA_OBJECT;
+        } catch (Exception e) { throw new IllegalArgumentException( e.getMessage() ); }
 	}
 
 	/**

Modified: db/derby/code/trunk/java/engine/org/apache/derby/iapi/types/DataTypeDescriptor.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/iapi/types/DataTypeDescriptor.java?rev=905289&r1=905288&r2=905289&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/iapi/types/DataTypeDescriptor.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/iapi/types/DataTypeDescriptor.java Mon
Feb  1 14:38:12 2010
@@ -1806,8 +1806,9 @@
         switch (typeId.getJDBCTypeId())
         {
             case Types.BOOLEAN:
+                return false;
             case Types.JAVA_OBJECT:
-            	return false;
+            	return getTypeId().getBaseTypeId().isAnsiUDT();
             case Types.DECIMAL:
                 return
                 (getPrecision() <= typeId.getMaximumPrecision()) &&

Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/load/ColumnInfo.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/load/ColumnInfo.java?rev=905289&r1=905288&r2=905289&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/load/ColumnInfo.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/load/ColumnInfo.java Mon Feb  1
14:38:12 2010
@@ -21,6 +21,7 @@
 
 package org.apache.derby.impl.load;
 
+import org.apache.derby.iapi.util.IdUtil;
 import org.apache.derby.iapi.reference.JDBC40Translation;
 import org.apache.derby.iapi.services.io.StoredFormatIds;
 
@@ -60,6 +61,7 @@
 	private Connection conn;
 	private String tableName;
 	private String schemaName;
+    private HashMap udtClassNames;
 
 	/**
 	 * Initialize the column type and name  information
@@ -84,6 +86,7 @@
 		insertColumnNames = new ArrayList(1);
 		columnTypes = new ArrayList(1);
         jdbcColumnTypes = new ArrayList(1);
+        udtClassNames = new HashMap();
 		noOfColumns = 0;
 		this.conn = conn;
 
@@ -198,6 +201,11 @@
 				columnTypes.add(sqlType);
                 jdbcColumnTypes.add(new Integer(dataType));
 				noOfColumns++;
+
+                if ( dataType == java.sql.Types.JAVA_OBJECT )
+                {
+                    udtClassNames.put( "COLUMN" +  noOfColumns, getUDTClassName( dmd, typeName
) );
+                }
 			}else
 			{
 				rs.close();
@@ -211,14 +219,43 @@
 		return foundTheColumn;
 	}
 
+    // look up the class name of a UDT
+    private String getUDTClassName( DatabaseMetaData dmd, String sqlTypeName )
+        throws SQLException
+    {
+        String className = null;
+        
+        try {
+            // special case for system defined types
+            if ( sqlTypeName.charAt( 0 ) != '"' ) { return sqlTypeName; }
+
+            String[] nameParts = IdUtil.parseMultiPartSQLIdentifier( sqlTypeName );
+
+            String schemaName = nameParts[ 0 ];
+            String unqualifiedName = nameParts[ 1 ];
+
+            ResultSet rs = dmd.getUDTs( null, schemaName, unqualifiedName, new int[] { java.sql.Types.JAVA_OBJECT
} );
+
+            if ( rs.next() )
+            {
+                className = rs.getString( 4 );
+            }
+            rs.close();
+        }
+        catch (Exception e) { throw new SQLException( e.getMessage() ); }
+
+        if ( className == null ) { className = "???"; }
+        
+        return className;
+    }
+
 
 	//return true if the given type is supported by import/export
 	public  static final boolean importExportSupportedType(int type){
 
 		return !(type == java.sql.Types.BIT ||
-				 type == java.sql.Types.JAVA_OBJECT ||
 				 type == java.sql.Types.OTHER ||
-				 type == JDBC40Translation.SQLXML); 
+				 type == JDBC40Translation.SQLXML ); 
 	}
 
 
@@ -257,6 +294,25 @@
 			return "";
 	}
 
+    /**
+     * Get the column type names.
+     */
+    public String getColumnTypeNames()
+        throws Exception
+    {
+        // we use the object serializer logic
+        return ExportAbstract.stringifyObject( columnTypes );
+    }
+
+    /**
+     * Get the class names of udt columns as a string.
+     */
+    public String getUDTClassNames()
+        throws Exception
+    {
+        // we use the object serializer logic
+        return ExportAbstract.stringifyObject( udtClassNames );
+    }
 
 	/*
 	 * Returns a  string of columns with proper casting/conversion
@@ -404,7 +460,7 @@
 
     /*
      * Get the expected vti data column types. This information was 
-     * passed earlies as string to the vti. This rourine extract the 
+     * earlier passed as a string to the vti. This routine extracts the 
      * information from the string.
      * @param columnTypesStr  import data column type information , 
      *                        encoded as string. 
@@ -415,7 +471,6 @@
     public static int[] getExpectedVtiColumnTypes(String columnTypesStr, 
                                                   int noOfColumns) 
     {
-
         // extract the table column types. Break the comma seperated 
         // column types into java.sql.Types int values from the columnTypes 
         // string that got passed to the import VTI.
@@ -435,6 +490,7 @@
             vtiColumnTypes[i] = java.sql.Types.VARCHAR;
 
         StringTokenizer st = new StringTokenizer(columnTypesStr , ",");
+
         while (st.hasMoreTokens()) 
         {
             String colTypeInfo = (st.nextToken()).trim();
@@ -454,8 +510,79 @@
                 vtiColumnTypes[colIndex-1] = colType;
             
         }
+        
         return vtiColumnTypes;
     }
+
+
+    /*
+     * Get the expected vti column type names. This information was 
+     * passed earlier as a string to the vti. This routine extracts the 
+     * information from the string.
+     * @param columnTypeNamesString  import data column type information, encoded as string.

+     * @param noOfColumns     number of columns in the import file.
+     * 
+     * @see getColumnTypeNames()
+     */
+    public static String[] getExpectedColumnTypeNames
+        ( String columnTypeNamesString, int noOfColumns )
+        throws Exception
+    {
+        ArrayList list = (ArrayList) ImportAbstract.destringifyObject( columnTypeNamesString
);
+
+        String[] retval = new String[ list.size() ];
+
+        list.toArray( retval );
+        
+        return retval;
+    }
+
+    /*
+     * Get the expected classes bound to UDT columns. This information was 
+     * passed earlier as a string to the vti. This routine extracts the 
+     * information from the string.
+     * @param stringVersion The result of calling toString() on the original HashMap<String><String>.
+     * @return a HashMap<String><Class> mapping column names to their udt classes
+     * 
+     * @see initializeColumnInfo()
+     */
+    public static HashMap getExpectedUDTClasses( String stringVersion )
+        throws Exception
+    {
+        // deserialize the original HashMap<String><String>
+        HashMap stringMap = deserializeHashMap( stringVersion );
+
+        if ( stringMap == null ) { return null; }
+        
+        HashMap retval = new HashMap();
+        Iterator keys = stringMap.keySet().iterator();
+
+        while ( keys.hasNext() )
+        {
+            String columnName = (String) keys.next();
+            String className = (String) stringMap.get( columnName );
+
+            Class classValue = Class.forName( className );
+
+            retval.put( columnName, classValue );
+        }
+
+        return retval;
+    }
+    
+    /*
+     * Deserialize a HashMap produced by ExportAbstract.stringifyObject()
+     */
+    public static HashMap deserializeHashMap( String stringVersion )
+        throws Exception
+    {
+        if ( stringVersion == null ) { return null; }
+
+        HashMap retval = (HashMap) ImportAbstract.destringifyObject( stringVersion );
+
+        return retval;
+    }
+    
 }
 
 

Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/load/ExportAbstract.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/load/ExportAbstract.java?rev=905289&r1=905288&r2=905289&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/load/ExportAbstract.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/load/ExportAbstract.java Mon Feb
 1 14:38:12 2010
@@ -27,8 +27,12 @@
 import java.sql.Types;
 import java.util.Date;
 import java.io.InputStream;
+import java.io.ObjectOutputStream;
 import java.io.Reader;
 
+import org.apache.derby.iapi.services.io.DynamicByteArrayOutputStream;
+import org.apache.derby.iapi.util.StringUtil;
+
 /**
  * 
  * <P>
@@ -110,7 +114,14 @@
                // TODO : handling of Nulls. 
            }
 		   else {
-			   rowObjects[colNum]=rs.getString(colNum + 1);
+               String columnValue;
+               int jdbcColumnNumber = colNum + 1;
+               
+               if ( rsm.getColumnType( jdbcColumnNumber ) == java.sql.Types.JAVA_OBJECT )
+               { columnValue = stringifyObject( rs.getObject( jdbcColumnNumber ) ); }
+               else { columnValue = rs.getString( jdbcColumnNumber ); }
+               
+			   rowObjects[colNum] = columnValue;
            }
        }
        return rowObjects;
@@ -120,6 +131,20 @@
     return null;
   }
 
+    // write a Serializable as a string
+    public static String stringifyObject( Object udt ) throws Exception
+    {
+        DynamicByteArrayOutputStream dbaos = new DynamicByteArrayOutputStream();
+        ObjectOutputStream oos = new ObjectOutputStream( dbaos );
+        
+        oos.writeObject( udt );
+        
+        byte[] buffer = dbaos.getByteArray();
+        int length = dbaos.getUsed();
+        
+        return StringUtil.toHexString( buffer, 0, length );
+    }
+
   //returns the control file reader corresponding to the control file passed
   protected ControlInfo getControlFileReader(){
 	  return controlFileReader; 

Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/load/Import.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/load/Import.java?rev=905289&r1=905288&r2=905289&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/load/Import.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/load/Import.java Mon Feb  1 14:38:12
2010
@@ -64,13 +64,15 @@
                   String characterDelimiter,  String codeset, 
                   int noOfColumnsExpected,  String columnTypes, 
                   boolean lobsInExtFile,
-                  int importCounter ) throws SQLException 
+                  int importCounter,
+                  String columnTypeNames, String udtClassNamesString ) throws SQLException

 	{
-
 		try{
 			this.inputFileName = inputFileName;
             this.noOfColumnsExpected = noOfColumnsExpected;
             this.tableColumnTypesStr = columnTypes;
+            this.columnTypeNamesString = columnTypeNames;
+            this.udtClassNamesString = udtClassNamesString;
 			controlFileReader = new ControlInfo();
 			controlFileReader.setControlProperties(characterDelimiter,
 												   columnDelimiter, codeset);
@@ -205,6 +207,17 @@
                                                    tableName, insertColumnList, 
                                                    columnIndexes, COLUMNNAMEPREFIX);
 
+            String columnTypeNames = null;
+            String udtClassNames = null;
+            try {
+                columnTypeNames = columnInfo.getColumnTypeNames();
+                udtClassNames = columnInfo.getUDTClassNames();
+            }
+            catch (Throwable t)
+            {
+                throw formatImportError( (Import) _importers.get( importCounter ), inputFileName,
t );
+            }
+
             StringBuffer sb = new StringBuffer("new ");
             sb.append("org.apache.derby.impl.load.Import");
             sb.append("(") ;
@@ -224,6 +237,10 @@
             sb.append(lobsInExtFile);
             sb.append(", ");
             sb.append( importCounter.intValue() );
+            sb.append(", ");
+            sb.append(quoteStringArgument( columnTypeNames ) );
+            sb.append(", ");
+            sb.append(quoteStringArgument( udtClassNames ) );
             sb.append(" )") ;
             
             String importvti = sb.toString();

Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/load/ImportAbstract.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/load/ImportAbstract.java?rev=905289&r1=905288&r2=905289&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/load/ImportAbstract.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/load/ImportAbstract.java Mon Feb
 1 14:38:12 2010
@@ -21,12 +21,14 @@
 
 package org.apache.derby.impl.load;
 
-import java.io.IOException;
+import java.io.ByteArrayInputStream;
+import java.io.ObjectInputStream;
 import java.sql.SQLException;
 import java.sql.SQLWarning;
 import java.sql.ResultSetMetaData;
 import org.apache.derby.vti.VTITemplate;
 import java.util.ArrayList;
+import java.util.HashMap;
 import org.apache.derby.iapi.util.StringUtil;
 import org.apache.derby.iapi.error.PublicAPI;
 import org.apache.derby.iapi.reference.SQLState;
@@ -49,13 +51,17 @@
   int lineNumber = 0;
   String[] nextRow;
 
-  ResultSetMetaData importResultSetMetaData;
+  ImportResultSetMetaData importResultSetMetaData;
   int noOfColumnsExpected;
 
   protected boolean lobsInExtFile = false;
 
   String tableColumnTypesStr;
   int[] tableColumnTypes;
+  String columnTypeNamesString;
+  String[] columnTypeNames;
+  String  udtClassNamesString;
+  HashMap udtClasses;
   private boolean wasNull;
 
 	static final String COLUMNNAMEPREFIX = "COLUMN";
@@ -84,10 +90,12 @@
     nextRow = new String[numberOfColumns];
     tableColumnTypes = ColumnInfo.getExpectedVtiColumnTypes(tableColumnTypesStr,
                                                             numberOfColumns);
+    columnTypeNames =  ColumnInfo.getExpectedColumnTypeNames( columnTypeNamesString, numberOfColumns
);
+    udtClasses = ColumnInfo.getExpectedUDTClasses( udtClassNamesString );
 	// get the ResultSetMetaData now as we know it's needed
 	importResultSetMetaData =
 		new ImportResultSetMetaData(numberOfColumns, columnNames, columnWidths,
-                                    tableColumnTypes);
+                                    tableColumnTypes, columnTypeNames, udtClasses );
 
 
     //FIXME don't go through the resultset here. just for testing
@@ -170,7 +178,7 @@
 
     /**
      * Returns <code> java.sql.Clob </code> type object that 
-     * contains the columnn data from the import file. 
+     * contains the column data from the import file. 
      * @param columnIndex number of the column. starts at 1.
      * @exception SQLException if any occurs during create of the clob object.
      */
@@ -197,7 +205,7 @@
 	
     /**
      * Returns <code> java.sql.Blob </code> type object that 
-     * contains the columnn data from the import file. 
+     * contains the column data from the import file. 
      * @param columnIndex number of the column. starts at 1.
      * @exception SQLException if any occurs during create of the blob object.
      */
@@ -246,11 +254,57 @@
         return blob;
 	}
 
+    /**
+     * Returns Object that contains the column data 
+     * from the import file. 
+     * @param columnIndex number of the column. starts at 1.
+     * @exception SQLException if any error occurs.
+     */
+	public Object getObject(int columnIndex) throws SQLException
+    {
+        byte[] bytes = getBytes( columnIndex );
+
+        try {
+            Class udtClass = importResultSetMetaData.getUDTClass( columnIndex );
+            
+            Object obj = readObject( bytes );
+            
+            //
+            // We need to make sure that the user is not trying to import some
+            // other object into the target column. This could happen if, for instance,
+            // you try to import the exported contents of a table which has the same
+            // shape as the target table except that its udt columns are of different type.
+            //
+            if ( (obj !=null) && (!udtClass.isInstance( obj )) )
+            {
+                throw new ClassCastException( obj.getClass().getName() + " -> " + udtClass.getName()
);
+            }
+            
+            return obj;
+        }
+        catch (Exception e) { throw importError( e ); }
+    }
+
+    /** Read a serializable from a set of bytes. */
+    public static Object readObject( byte[] bytes ) throws Exception
+    {
+        ByteArrayInputStream bais = new ByteArrayInputStream( bytes );
+        ObjectInputStream ois = new ObjectInputStream( bais );
+
+        return ois.readObject();
+    }
+
+    /** Read an object which was serialized to a string using StringUtil */
+    public static Object destringifyObject( String raw ) throws Exception
+    {
+        byte[] bytes = StringUtil.fromHexString( raw, 0, raw.length());
 
+        return readObject( bytes );
+    }
 
 
     /**
-     * Returns byte array that contains the columnn data 
+     * Returns byte array that contains the column data 
      * from the import file. 
      * @param columnIndex number of the column. starts at 1.
      * @exception SQLException if any error occurs.

Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/load/ImportResultSetMetaData.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/load/ImportResultSetMetaData.java?rev=905289&r1=905288&r2=905289&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/load/ImportResultSetMetaData.java
(original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/load/ImportResultSetMetaData.java
Mon Feb  1 14:38:12 2010
@@ -22,6 +22,7 @@
 package org.apache.derby.impl.load;
 
 import java.sql.SQLException;
+import java.util.HashMap;
 import org.apache.derby.vti.VTIMetaDataTemplate;
 
 import org.apache.derby.iapi.reference.Limits;
@@ -32,16 +33,22 @@
   private final String[] columnNames;
   private final int[] columnWidths;
   // types of the table columns that the data is imported. 
-  private final int[] tableColumnTypes ; 
+  private final int[] tableColumnTypes ;
+  private final String[] columnTypeNames;
+  private final HashMap udtClasses;
 
   public ImportResultSetMetaData(int numberOfColumns, 
                                  String[] columnNames,
                                  int[] columnWidths, 
-                                 int[] tableColumnTypes) {
+                                 int[] tableColumnTypes,
+                                 String[] columnTypeNames,
+                                 HashMap udtClasses ) {
     this.numberOfColumns = numberOfColumns;
     this.columnNames = columnNames;
     this.columnWidths = columnWidths;
     this.tableColumnTypes = tableColumnTypes;
+    this.columnTypeNames = columnTypeNames;
+    this.udtClasses = udtClasses;
   }
 
 	public int getColumnCount() {
@@ -99,6 +106,10 @@
             // CHAR FOR BIT DATA 
             colType = java.sql.Types.BINARY;
             break;
+        case java.sql.Types.JAVA_OBJECT: 
+            // User-defined type
+            colType = java.sql.Types.JAVA_OBJECT;
+            break;
         default: 
             // all other data in the import file is 
             // assumed to be in varchar format.
@@ -118,4 +129,19 @@
        return columnWidths[column-1];
   }
 
+	public  String getColumnTypeName(int column) throws SQLException
+    {
+		return columnTypeNames[ column - 1 ];
+	}
+
+    /**
+     * Get the class bound to a UDT column.
+     */
+    public Class getUDTClass( int column ) throws SQLException
+    {
+        String columnName = getColumnName( column );
+        
+        return (Class) udtClasses.get( getColumnName( column ) );
+    }
+    
 }

Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/CreateTableNode.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/CreateTableNode.java?rev=905289&r1=905288&r2=905289&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/CreateTableNode.java
(original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/CreateTableNode.java
Mon Feb  1 14:38:12 2010
@@ -367,8 +367,8 @@
 							schemaCollationName);
 				}
 
-				ColumnDefinitionNode column = new ColumnDefinitionNode();
-				column.init(rc.getName(), null, rc.getType(), null);
+				ColumnDefinitionNode column = (ColumnDefinitionNode) getNodeFactory().getNode
+                    ( C_NodeTypes.COLUMN_DEFINITION_NODE, rc.getName(), null, rc.getType(),
null, getContextManager() );
 				tableElementList.addTableElement(column);
 			}
 		} else {

Modified: db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/ValueNode.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/ValueNode.java?rev=905289&r1=905288&r2=905289&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/ValueNode.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/ValueNode.java Mon Feb
 1 14:38:12 2010
@@ -286,8 +286,14 @@
 
 	public void setType(DataTypeDescriptor dataTypeServices) throws StandardException
 	{
-		this.dataTypeServices = dataTypeServices;
+        // bind the type in case it is a user defined type. this will create a dependency
on the udt.
+        if ( dataTypeServices != null )
+        {
+            dataTypeServices = bindUserType( dataTypeServices );
+        }
 
+		this.dataTypeServices = dataTypeServices;
+        
         // create a dependency on this type if it is an ANSI UDT
         if ( dataTypeServices != null ) { createTypeDependency( dataTypeServices ); }
 	}

Modified: db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/lang/UDTTest.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/lang/UDTTest.java?rev=905289&r1=905288&r2=905289&view=diff
==============================================================================
--- db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/lang/UDTTest.java
(original)
+++ db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/lang/UDTTest.java
Mon Feb  1 14:38:12 2010
@@ -28,6 +28,7 @@
 import java.sql.ResultSet;
 import java.sql.ResultSetMetaData;
 import java.sql.Timestamp;
+import java.util.HashMap;
 
 import junit.framework.Test;
 import junit.framework.TestSuite;
@@ -727,7 +728,7 @@
 
     ///////////////////////////////////////////////////////////////////////////////////
     //
-    // PROCEDURES
+    // PROCEDURES AND FUNCTIONS
     //
     ///////////////////////////////////////////////////////////////////////////////////
 
@@ -742,6 +743,17 @@
         price[ 0 ] = newPrice;
     }
 
+    public static HashMap makeHashMap() { return new HashMap(); }
+
+    public static HashMap putValue( HashMap map, String key, String value )
+    {
+        map.put( key, value );
+
+        return map;
+    }
+
+    
+
     ///////////////////////////////////////////////////////////////////////////////////
     //
     // MINIONS

Modified: db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/tools/ImportExportTest.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/tools/ImportExportTest.java?rev=905289&r1=905288&r2=905289&view=diff
==============================================================================
--- db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/tools/ImportExportTest.java
(original)
+++ db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/tools/ImportExportTest.java
Mon Feb  1 14:38:12 2010
@@ -66,22 +66,36 @@
 		return new CleanDatabaseTestSetup(test) {
             protected void decorateSQL(Statement s) throws SQLException {
 
+                s.execute( "create type Price external name 'org.apache.derbyTesting.functionTests.tests.lang.Price'
language java" );
+                s.execute( "create type hashmap external name 'java.util.HashMap' language
java" );
+
+                s.execute( "create function makePrice( ) returns price " +
+                           "language java parameter style java no sql " +
+                           "external name 'org.apache.derbyTesting.functionTests.tests.lang.Price.makePrice'"
);
+
+                s.execute( "create function makeHashMap( ) returns hashmap " +
+                           "language java parameter style java no sql " +
+                           "external name 'org.apache.derbyTesting.functionTests.tests.lang.UDTTest.makeHashMap'"
);
+
                 s.execute("CREATE TABLE T1 (COLUMN1 VARCHAR(5) , COLUMN2 VARCHAR(8) , " +
 						   "COLUMN3 SMALLINT , COLUMN4 CHAR(11) , COLUMN5 DATE , COLUMN6 DECIMAL(5,1) , " +
 						   "COLUMN7 DOUBLE PRECISION , COLUMN8 INT , COLUMN9 BIGINT , COLUMN10 NUMERIC , "
+
 						   "COLUMN11 REAL , COLUMN12 SMALLINT , COLUMN13 TIME , COLUMN14 TIMESTAMP , "+
-						   "COLUMN15 SMALLINT , COLUMN16 VARCHAR(1))");
+						   "COLUMN15 SMALLINT , COLUMN16 VARCHAR(1), COLUMN17 PRICE)");
                 s.execute("CREATE TABLE T2 (COLUMN1 VARCHAR(5) , COLUMN2 VARCHAR(8) , " +
 						   "COLUMN3 SMALLINT, COLUMN4 CHAR(11) , COLUMN5 DATE , COLUMN6 DECIMAL(5,1) , " +
 						   "COLUMN7 DOUBLE PRECISION , COLUMN8 INT , COLUMN9 BIGINT , COLUMN10 NUMERIC , "
+
 						   "COLUMN11 REAL , COLUMN12 SMALLINT , COLUMN13 TIME , COLUMN14 TIMESTAMP , "+
-						   "COLUMN15 SMALLINT , COLUMN16 VARCHAR(1))");
+						   "COLUMN15 SMALLINT , COLUMN16 VARCHAR(1), COLUMN17 PRICE)");
                 s.execute("create table T4 (   Account int,    Name   char(30), Jobdesc char(40),
" +
                            "Company varchar(35), Address1 varchar(40), Address2 varchar(40),
" +
                            "City    varchar(20), State   char(5), Zip char(10), Country char(10),
" +
                            "Phone1  char(20), Phone2  char(20), email   char(30), web   
 char(30), " +
                            "Fname   char(30), Lname   char(30), Comment char(30), AccDate
char(30), " +
                            "Payment decimal(8,2), Balance decimal(8,2))");
+
+                s.execute( "create table t5( a int, b price )" );
+                s.execute( "create table t6( a int, b hashmap )" );
                 }
         };
 	}
@@ -224,9 +238,28 @@
         JDBC.assertSingleValueResultSet(
                 s.executeQuery("select count(*) from " + escapedName),
                 Integer.toString(rowsInTable));
-        JDBC.assertEmpty(s.executeQuery(
-                "select * from " + escapedName +
-                " except all select * from T1"));
+    }
+
+    /**
+     * Test that you can't import the wrong type of object into a UDT column.
+     */
+    public void testCastingProblem() throws Exception
+    {
+        resetTables();
+
+        final String fileName = SupportFilesSetup.
+                getReadWrite("castCheck.dat").getPath();
+
+        // export table which has a HashMap column
+        doExportToFile( fileName, null, "T6", null, null, null );
+
+        // try to import the HashMap into a Price column
+        try {
+            doImportFromFile( fileName, null, "T5", null, null, null, 0 );
+            fail();
+		} catch (SQLException e) {
+			assertSQLState("XJ001", e);
+		}
     }
 
     private void doImport(String fromTable, String toSchema, String toTable,
@@ -345,14 +378,17 @@
 	private void resetTables() throws Exception {
 		runSQLCommands("delete from t1");
 		runSQLCommands("delete from t2");
+		runSQLCommands("delete from t5");
+		runSQLCommands("delete from t6");
 		runSQLCommands("INSERT INTO T1 VALUES (null,'aa',1,'a',DATE('1998-06-30'),"+
-		               "1,1,1,1,1,1,1,TIME('12:00:00'),TIMESTAMP('1998-06-30 12:00:00.0'),1,'a')");
+		               "1,1,1,1,1,1,1,TIME('12:00:00'),TIMESTAMP('1998-06-30 12:00:00.0'),1,'a',
makePrice() )");
         runSQLCommands("INSERT INTO T1 VALUES (null,'bb',1,'b',DATE('1998-06-30'),"+
-					   "2,2,2,2,2,2,2,TIME('12:00:00'),TIMESTAMP('1998-06-30 12:00:00.0'),2,'b')");
+					   "2,2,2,2,2,2,2,TIME('12:00:00'),TIMESTAMP('1998-06-30 12:00:00.0'),2,'b', makePrice()
)");
         runSQLCommands("INSERT INTO T1 VALUES (null,'cc',1,'c',DATE('1998-06-30'),"+
-					   "3,3,3,3,3,3,3,TIME('12:00:00'),TIMESTAMP('1998-06-30 12:00:00.0'),3,'c')");
+					   "3,3,3,3,3,3,3,TIME('12:00:00'),TIMESTAMP('1998-06-30 12:00:00.0'),3,'c', makePrice())");
         runSQLCommands("INSERT INTO T1 VALUES (null,'dd',1,'d',DATE('1998-06-30'),"+
-					   "4,4,4,4,4,4,4,TIME('12:00:00'),TIMESTAMP('1998-06-30 12:00:00.0'),4,'d')");
+					   "4,4,4,4,4,4,4,TIME('12:00:00'),TIMESTAMP('1998-06-30 12:00:00.0'),4,'d', makePrice())");
+        runSQLCommands( "insert into t6 values( 1, makeHashMap() )" );
 	}
 
 }



Mime
View raw message