Search in sources :

Example 46 with DatabasePlatform

use of org.eclipse.persistence.internal.databaseaccess.DatabasePlatform in project eclipselink by eclipse-ee4j.

the class AbstractTransformationMapping method initializeFieldToTransformers.

/**
 * INTERNAL:
 * Convert the field names and their corresponding method names to
 * DatabaseFields and Methods.
 */
protected void initializeFieldToTransformers(AbstractSession session) throws DescriptorException {
    for (Object[] pair : this.fieldToTransformers) {
        pair[0] = getDescriptor().buildField(((DatabaseField) pair[0]));
        ((FieldTransformer) pair[1]).initialize(this);
    }
    for (FieldTransformation transformation : getFieldTransformations()) {
        DatabaseField field = getDescriptor().buildField(transformation.getField());
        String transformerClassName = "MethodBasedFieldTransformer";
        FieldTransformer transformer = null;
        try {
            transformer = transformation.buildTransformer();
        } catch (ConversionException ex) {
            if (transformation instanceof TransformerBasedFieldTransformation) {
                transformerClassName = ((TransformerBasedFieldTransformation) transformation).getTransformerClassName();
            }
            throw DescriptorException.fieldTransformerClassNotFound(transformerClassName, this, ex);
        } catch (Exception ex) {
            if (transformation instanceof TransformerBasedFieldTransformation) {
                transformerClassName = ((TransformerBasedFieldTransformation) transformation).getTransformerClassName();
            }
            throw DescriptorException.fieldTransformerClassInvalid(transformerClassName, this, ex);
        }
        transformer.initialize(this);
        // Attempt to ensure a type is set on the field.
        if (field.getType() == null) {
            if (transformer instanceof MethodBasedFieldTransformer) {
                field.setType(((MethodBasedFieldTransformer) transformer).getFieldType());
            } else if (field.getColumnDefinition() != null) {
                // Search for the type for this field definition.
                if (session.getDatasourcePlatform() instanceof DatabasePlatform) {
                    Iterator<Map.Entry<Class<?>, FieldTypeDefinition>> iterator = session.getPlatform().getFieldTypes().entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<Class<?>, FieldTypeDefinition> entry = iterator.next();
                        if (entry.getValue().getName().equals(field.getColumnDefinition())) {
                            field.setType(entry.getKey());
                            break;
                        }
                    }
                }
            }
        }
        Object[] fieldToTransformer = new Object[2];
        fieldToTransformer[0] = field;
        fieldToTransformer[1] = transformer;
        this.fieldToTransformers.add(fieldToTransformer);
    }
}
Also used : ConversionException(org.eclipse.persistence.exceptions.ConversionException) TransformerBasedFieldTransformation(org.eclipse.persistence.internal.descriptors.TransformerBasedFieldTransformation) DatabasePlatform(org.eclipse.persistence.internal.databaseaccess.DatabasePlatform) DatabaseException(org.eclipse.persistence.exceptions.DatabaseException) DescriptorException(org.eclipse.persistence.exceptions.DescriptorException) ValidationException(org.eclipse.persistence.exceptions.ValidationException) ConversionException(org.eclipse.persistence.exceptions.ConversionException) PrivilegedActionException(java.security.PrivilegedActionException) MethodBasedFieldTransformer(org.eclipse.persistence.mappings.transformers.MethodBasedFieldTransformer) FieldTypeDefinition(org.eclipse.persistence.internal.databaseaccess.FieldTypeDefinition) MethodBasedFieldTransformer(org.eclipse.persistence.mappings.transformers.MethodBasedFieldTransformer) FieldTransformer(org.eclipse.persistence.mappings.transformers.FieldTransformer) DatabaseField(org.eclipse.persistence.internal.helper.DatabaseField) Iterator(java.util.Iterator) DescriptorIterator(org.eclipse.persistence.internal.descriptors.DescriptorIterator) PrivilegedNewInstanceFromClass(org.eclipse.persistence.internal.security.PrivilegedNewInstanceFromClass) Map(java.util.Map) TransformerBasedFieldTransformation(org.eclipse.persistence.internal.descriptors.TransformerBasedFieldTransformation) FieldTransformation(org.eclipse.persistence.internal.descriptors.FieldTransformation) MethodBasedFieldTransformation(org.eclipse.persistence.internal.descriptors.MethodBasedFieldTransformation)

Example 47 with DatabasePlatform

use of org.eclipse.persistence.internal.databaseaccess.DatabasePlatform in project eclipselink by eclipse-ee4j.

the class ObjectBuilder method buildObjectsFromResultSetInto.

/**
 * Version of buildObjectsInto method that takes call instead of rows.
 * Return a container which contains the instances of the receivers javaClass.
 * Set the fields of the instance to the values stored in the result set.
 */
public Object buildObjectsFromResultSetInto(ReadAllQuery query, ResultSet resultSet, Vector fields, DatabaseField[] fieldsArray, Object domainObjects) throws SQLException {
    AbstractSession session = query.getSession();
    session.startOperationProfile(SessionProfiler.ObjectBuilding, query, SessionProfiler.ALL);
    try {
        boolean hasNext = resultSet.next();
        if (hasNext) {
            InheritancePolicy inheritancePolicy = null;
            if (this.descriptor.hasInheritance()) {
                inheritancePolicy = this.descriptor.getInheritancePolicy();
            }
            boolean isUnitOfWork = session.isUnitOfWork();
            boolean shouldCacheQueryResults = query.shouldCacheQueryResults();
            boolean shouldUseWrapperPolicy = query.shouldUseWrapperPolicy();
            // PERF: Avoid lazy init of join manager if no joining.
            JoinedAttributeManager joinManager = null;
            if (query.hasJoining()) {
                joinManager = query.getJoinedAttributeManager();
            }
            ContainerPolicy policy = query.getContainerPolicy();
            // !cp.shouldAddAll() - query with SortedListContainerPolicy - currently does not use this method
            boolean quickAdd = (domainObjects instanceof Collection) && !this.hasWrapperPolicy;
            ResultSetMetaData metaData = resultSet.getMetaData();
            ResultSetRecord row = null;
            AbstractSession executionSession = query.getExecutionSession();
            DatabaseAccessor dbAccessor = (DatabaseAccessor) query.getAccessor();
            DatabasePlatform platform = dbAccessor.getPlatform();
            boolean optimizeData = platform.shouldOptimizeDataConversion();
            if (this.isSimple) {
                // None of the fields are relational - the row could be reused, just clear all the values.
                row = new SimpleResultSetRecord(fields, fieldsArray, resultSet, metaData, dbAccessor, executionSession, platform, optimizeData);
                if (this.descriptor.isDescriptorTypeAggregate()) {
                    // Aggregate Collection may have an unmapped primary key referencing the owner, the corresponding field will not be used when the object is populated and therefore may not be cleared.
                    ((SimpleResultSetRecord) row).setShouldKeepValues(true);
                }
            }
            while (hasNext) {
                if (!this.isSimple) {
                    row = new ResultSetRecord(fields, fieldsArray, resultSet, metaData, dbAccessor, executionSession, platform, optimizeData);
                }
                Object domainObject = buildObject(query, row, joinManager, session, this.descriptor, inheritancePolicy, isUnitOfWork, shouldCacheQueryResults, shouldUseWrapperPolicy);
                if (quickAdd) {
                    ((Collection) domainObjects).add(domainObject);
                } else {
                    // query with MappedKeyMapPolicy currently does not use this method
                    policy.addInto(domainObject, domainObjects, session);
                }
                if (this.isSimple) {
                    ((SimpleResultSetRecord) row).reset();
                } else {
                    if (this.shouldKeepRow) {
                        if (row.hasResultSet()) {
                            // ResultSet has not been fully triggered - that means the cached object was used.
                            // Yet the row still may be cached in a value holder (see loadBatchReadAttributes and loadJoinedAttributes methods).
                            // Remove ResultSet to avoid attempt to trigger it (already closed) when pk or fk values (already extracted) accessed when the value holder is instantiated.
                            row.removeResultSet();
                        } else {
                            row.removeNonIndirectionValues();
                        }
                    }
                }
                hasNext = resultSet.next();
            }
        }
    } finally {
        session.endOperationProfile(SessionProfiler.ObjectBuilding, query, SessionProfiler.ALL);
    }
    return domainObjects;
}
Also used : ResultSetMetaData(java.sql.ResultSetMetaData) ContainerPolicy(org.eclipse.persistence.internal.queries.ContainerPolicy) InheritancePolicy(org.eclipse.persistence.descriptors.InheritancePolicy) JoinedAttributeManager(org.eclipse.persistence.internal.queries.JoinedAttributeManager) Collection(java.util.Collection) SimpleResultSetRecord(org.eclipse.persistence.internal.sessions.SimpleResultSetRecord) ResultSetRecord(org.eclipse.persistence.internal.sessions.ResultSetRecord) DatabaseAccessor(org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor) InvalidObject(org.eclipse.persistence.internal.helper.InvalidObject) DatabasePlatform(org.eclipse.persistence.internal.databaseaccess.DatabasePlatform) SimpleResultSetRecord(org.eclipse.persistence.internal.sessions.SimpleResultSetRecord) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession)

Example 48 with DatabasePlatform

use of org.eclipse.persistence.internal.databaseaccess.DatabasePlatform in project eclipselink by eclipse-ee4j.

the class StoredProcedureDefinition method buildCreationWriter.

/**
 * INTERNAL: Return the create table statement.
 */
@Override
public Writer buildCreationWriter(AbstractSession session, Writer writer) throws ValidationException {
    try {
        DatabasePlatform platform = session.getPlatform();
        writer.write(getCreationHeader() + getFullName());
        if (getArguments().size() > getFirstArgumentIndex() || platform.requiresProcedureBrackets()) {
            writer.write(" (");
        }
        writer.write("\n");
        for (int i = getFirstArgumentIndex(); i < getArguments().size(); i++) {
            writer.write("\t");
            FieldDefinition argument = getArguments().get(i);
            Integer argumentType = getArgumentTypes().get(i);
            if (argumentType == IN) {
                printArgument(argument, writer, session);
            } else if (argumentType == OUT) {
                printOutputArgument(argument, writer, session);
            } else if (argumentType == INOUT) {
                printInOutputArgument(argument, writer, session);
            }
            if (i < (getArguments().size() - 1)) {
                writer.write(",\n");
            }
        }
        if (getArguments().size() > getFirstArgumentIndex() || platform.requiresProcedureBrackets()) {
            writer.write(")");
        }
        printReturn(writer, session);
        writer.write(platform.getProcedureAsString());
        writer.write("\n");
        writer.write(platform.getProcedureOptionList());
        writer.write("\n");
        if (platform.shouldPrintStoredProcedureVariablesAfterBeginString()) {
            writer.write(platform.getProcedureBeginString());
            writer.write("\n");
        }
        if (!getVariables().isEmpty()) {
            writer.write("DECLARE\n");
        }
        for (FieldDefinition field : getVariables()) {
            writer.write("\t");
            writer.write(field.getName());
            writer.write(" ");
            writer.write(field.getTypeName());
            writer.write(platform.getBatchDelimiterString());
            writer.write("\n");
        }
        if (!platform.shouldPrintStoredProcedureVariablesAfterBeginString()) {
            writer.write(platform.getProcedureBeginString());
            writer.write("\n");
        }
        for (String statement : getStatements()) {
            writer.write(statement);
            writer.write(platform.getBatchDelimiterString());
            writer.write("\n");
        }
        writer.write(platform.getProcedureEndString());
    } catch (IOException ioException) {
        throw ValidationException.fileError(ioException);
    }
    return writer;
}
Also used : DatabasePlatform(org.eclipse.persistence.internal.databaseaccess.DatabasePlatform) IOException(java.io.IOException)

Example 49 with DatabasePlatform

use of org.eclipse.persistence.internal.databaseaccess.DatabasePlatform in project eclipselink by eclipse-ee4j.

the class FieldDefinition method appendDBString.

/**
 * INTERNAL:
 * Append the database field definition string to the table creation statement.
 * @param writer  Target writer where to write field definition string.
 * @param session Current session context.
 * @param table   Database table being processed.
 * @throws ValidationException When invalid or inconsistent data were found.
 */
public void appendDBString(final Writer writer, final AbstractSession session, final TableDefinition table) throws ValidationException {
    try {
        writer.write(name);
        writer.write(" ");
        if (getTypeDefinition() != null) {
            // apply user-defined complete type definition
            writer.write(typeDefinition);
        } else {
            final DatabasePlatform platform = session.getPlatform();
            // compose type definition - type name, size, unique, identity, constraints...
            final FieldTypeDefinition fieldType = DatabaseObjectDefinition.getFieldTypeDefinition(platform, type, typeName);
            String qualifiedName = table.getFullName() + '.' + name;
            boolean shouldPrintFieldIdentityClause = isIdentity && platform.shouldPrintFieldIdentityClause(session, qualifiedName);
            platform.printFieldTypeSize(writer, this, fieldType, shouldPrintFieldIdentityClause);
            if (shouldPrintFieldIdentityClause) {
                platform.printFieldIdentityClause(writer);
            }
            if (shouldAllowNull && fieldType.shouldAllowNull()) {
                platform.printFieldNullClause(writer);
            } else {
                platform.printFieldNotNullClause(writer);
            }
            if (isUnique) {
                if (platform.supportsUniqueColumns()) {
                    // #282751: do not add UNIQUE if the field is also simple primary key
                    if (!isPrimaryKey || table.getPrimaryKeyFieldNames().size() > 1) {
                        platform.printFieldUnique(writer, shouldPrintFieldIdentityClause);
                    } else {
                        setUnique(false);
                        session.log(SessionLog.WARNING, SessionLog.DDL, "removing_unique_constraint", qualifiedName);
                    }
                } else {
                    // Need to move the unique column to be a constraint.
                    setUnique(false);
                    String constraintName = table.buildUniqueKeyConstraintName(table.getName(), table.getFields().indexOf(this), platform.getMaxUniqueKeyNameSize());
                    table.addUniqueKeyConstraint(constraintName, name);
                }
            }
            if (constraint != null) {
                writer.write(" " + constraint);
            }
            if (additional != null) {
                writer.write(" " + additional);
            }
        }
    } catch (IOException ioException) {
        throw ValidationException.fileError(ioException);
    }
}
Also used : FieldTypeDefinition(org.eclipse.persistence.internal.databaseaccess.FieldTypeDefinition) DatabasePlatform(org.eclipse.persistence.internal.databaseaccess.DatabasePlatform) IOException(java.io.IOException)

Example 50 with DatabasePlatform

use of org.eclipse.persistence.internal.databaseaccess.DatabasePlatform in project eclipselink by eclipse-ee4j.

the class EmployeePopulator method persistExample.

public void persistExample(Session session) {
    Vector allObjects = new Vector();
    UnitOfWork unitOfWork = session.acquireUnitOfWork();
    PopulationManager.getDefaultManager().addAllObjectsForClass(Employee.class, allObjects);
    PopulationManager.getDefaultManager().addAllObjectsForClass(SmallProject.class, allObjects);
    PopulationManager.getDefaultManager().addAllObjectsForClass(LargeProject.class, allObjects);
    unitOfWork.registerAllObjects(allObjects);
    unitOfWork.commit();
    DatabasePlatform platform = session.getLogin().getPlatform();
    if (TestCase.supportsStoredProcedures(session)) {
        boolean orig_FAST_TABLE_CREATOR = SchemaManager.FAST_TABLE_CREATOR;
        // of an instance of this class (drops & re-)creates the tables.
        if (useFastTableCreatorAfterInitialCreate && !isFirstCreation) {
            SchemaManager.FAST_TABLE_CREATOR = true;
        }
        try {
            SchemaManager schema = new SchemaManager((DatabaseSession) session);
            schema.replaceObject(buildStoredProcedureReadFromAddress(platform));
            schema.replaceObject(buildStoredProcedureReadFromAddressMappedNamed(platform));
            schema.replaceObject(buildStoredProcedureReadFromAddressMappedNumbered(platform));
            schema.replaceObject(buildStoredProcedureReadAllAddresses());
            if (platform.isOracle()) {
                schema.replaceObject(buildOraclePackage());
                schema.replaceObject(buildStoredProcedureReadUsingNamedRefCursor());
                schema.replaceObject(buildStoredProcedureReadUsingUnNamedRefCursor());
            }
            if (platform.isMySQL()) {
                schema.replaceObject(buildMySQLResultSetProcedure());
            }
        } finally {
            if (useFastTableCreatorAfterInitialCreate && !isFirstCreation) {
                SchemaManager.FAST_TABLE_CREATOR = orig_FAST_TABLE_CREATOR;
            }
        }
        // next time it deletes the rows instead.
        isFirstCreation = false;
    }
    // Force uppercase for Postgres.
    if (platform.isPostgreSQL()) {
        session.getLogin().setShouldForceFieldNamesToUpperCase(true);
    }
}
Also used : UnitOfWork(org.eclipse.persistence.sessions.UnitOfWork) DatabasePlatform(org.eclipse.persistence.internal.databaseaccess.DatabasePlatform) SchemaManager(org.eclipse.persistence.tools.schemaframework.SchemaManager) Vector(java.util.Vector)

Aggregations

DatabasePlatform (org.eclipse.persistence.internal.databaseaccess.DatabasePlatform)52 EntityManager (jakarta.persistence.EntityManager)12 DatabaseCall (org.eclipse.persistence.internal.databaseaccess.DatabaseCall)11 DatabaseException (org.eclipse.persistence.exceptions.DatabaseException)9 EntityManagerFactoryImpl (org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl)9 Test (org.junit.Test)9 GenericEntity (org.eclipse.persistence.jpa.test.property.model.GenericEntity)8 PersistenceException (jakarta.persistence.PersistenceException)6 Platform (org.eclipse.persistence.internal.databaseaccess.Platform)6 AbstractSession (org.eclipse.persistence.internal.sessions.AbstractSession)6 ResultSetMetaData (java.sql.ResultSetMetaData)5 DatabaseAccessor (org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor)5 FieldTypeDefinition (org.eclipse.persistence.internal.databaseaccess.FieldTypeDefinition)5 UnitOfWork (org.eclipse.persistence.sessions.UnitOfWork)5 IOException (java.io.IOException)4 ResultSet (java.sql.ResultSet)4 SQLException (java.sql.SQLException)4 ArrayList (java.util.ArrayList)4 List (java.util.List)4 Vector (java.util.Vector)4