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

com.viaoa.ds.jdbc.delegate.UpdateDelegate Maven / Gradle / Ivy

There is a newer version: 3.7.10
Show newest version
/*  Copyright 1999 Vince Via [email protected]
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/
package com.viaoa.ds.jdbc.delegate;

import java.util.*;
import java.util.logging.Logger;
import java.io.*;
import java.sql.*;

import com.viaoa.ds.jdbc.*;
import com.viaoa.ds.jdbc.db.*;
import com.viaoa.object.*;
import com.viaoa.util.OANotExist;
import com.viaoa.util.OANullObject;
import com.viaoa.util.OAString;

/**
 * Manages updates for JDBC datasource.
 * @author vvia
 */
public class UpdateDelegate {
    private static Logger LOG = Logger.getLogger(UpdateDelegate.class.getName());

    public static void removeReference(OADataSourceJDBC ds, OAObject oaObj, String propertyName) {
        if (oaObj == null) return;
        update(ds, oaObj, oaObj.getClass(), new String[] {propertyName}, null);
    }
    
    public static void update(OADataSourceJDBC ds, OAObject oaObj) {
        if (oaObj == null) return;
        update(ds, oaObj, oaObj.getClass(), null, null);
    }

    public static void update(OADataSourceJDBC ds, OAObject oaObj, String[] includeProperties, String[] excludeProperties) {
        if (oaObj == null) return;
        update(ds, oaObj, oaObj.getClass(), includeProperties, excludeProperties);
    }
    
    
    protected static void update(OADataSourceJDBC ds, OAObject oaObj, Class clazz, String[] includeProperties, String[] excludeProperties) {
        Class cx = clazz.getSuperclass();
        if (cx != null && !cx.equals(OAObject.class)) update(ds, oaObj, cx, includeProperties, excludeProperties);
        
        Object[] objs = null;
        try {
            objs = getUpdateSQL(ds, oaObj, clazz, includeProperties, excludeProperties);
            if (objs == null) return; // could be subclass with only an Id property
            Object[] params = null;
            Vector v = (Vector) objs[1];
            if (v != null) {
                int x = v.size();
                params = new Object[x];
                for (int i=0; i 0) {
                boolean b = false;
                for (int j=0; !b && j 0) {
                boolean b = false;
                for (int j=0; !b && j 512);
    
            // 20100514
            boolean byteArray = (obj instanceof byte[]);
            if (byteArray) {
                if (vecParam == null) vecParam = new Vector(3,3);
                vecParam.addElement(obj);
                value = "?";
            }
            else {
                value = ConverterDelegate.convertToString(dbmd, obj, !bOver512, Delegate.getMaxLength(column), column.decimalPlaces, column);
                String origValue = value;
                
                if (value != null && bOver512) {
                    if (vecParam == null) vecParam = new Vector(3,3);
                    vecParam.addElement(value);
                    value = "?";
                }
            }
            value = dbmd.leftBracket + column.columnName.toUpperCase() + dbmd.rightBracket + " = " + value;
            if (column.primaryKey) {
                if (sbWhere.length() > 0) sbWhere.append(" AND ");
                sbWhere.append(value);
            }
            else {
                if (sbSet.length() > 0) sbSet.append(", ");
                sbSet.append(value);
            }

            /**
            // check for case sensitive column
        	if (dbmd.caseSensitive) {
            	String colName = column.columnLowerName;
            	if (colName != null && colName.trim().length() > 0 && !colName.equalsIgnoreCase(column.columnName)) {
                    value = origValue;
            		if (!bNull) value = value.toLowerCase();
            		if (bOver512) {
            			vecParam.addElement(value);
                        value = "?";
                    }
            		sbSet.append(", ");
                    sbSet.append(dbmd.leftBracket + column.columnLowerName.toUpperCase() + dbmd.rightBracket + " = " + value);
            	}            
        	}
        	**/
        }
        
        Link[] links = table.getLinks();
        for (int i=0; links != null && i < links.length; i++) {
            if (links[i].fkeys == null || (links[i].fkeys.length == 0)) continue;
            if (links[i].fkeys[0].primaryKey) continue;    // one2many, or one2one (where Key is the fkey)

            if (includeProperties != null && includeProperties.length > 0) {
                boolean b = false;
                if (links[i].propertyName == null) continue;
                for (int j=0; !b && j 0) {
                boolean b = false;
                if (links[i].propertyName == null) b = true;
                else {
                    for (int j=0; !b && j= ids.length)) ? null : ids[j];
            	value = ConverterDelegate.convert(dbmd, fkeys[j], objProperty);
                if (sbSet.length() > 0) sbSet.append(", ");
                sbSet.append(dbmd.leftBracket + links[i].fkeys[j].columnName.toUpperCase() + dbmd.rightBracket + " = " + value);
            }
        }
        
        if (sbSet.length() == 0) return null;

        s = ("UPDATE " + dbmd.leftBracket + table.name.toUpperCase() + dbmd.rightBracket + " SET " + sbSet + " WHERE " + sbWhere);
        return new Object[] { s, vecParam };
    }

    private static void performUpdate(OADataSourceJDBC ds, String sqlUpdate, Object[] sqlParams) throws Exception {
        Statement statement = null;

        // DBLogDelegate.logUpdate(sqlUpdate, sqlParams);
        
        PreparedStatement preparedStatement = null;
        try {
            int x;
            if (sqlParams != null && sqlParams.length > 0) {
                preparedStatement = ds.getPreparedStatement(sqlUpdate);
                for (int i=0; i 0) {
                    str.append(", ");
                    values.append(", ");
                }
                str.append(dbmd.leftBracket + column.columnName.toUpperCase() + dbmd.rightBracket );
                values.append( value );
            }
            for (int i=0; i < linkTableToFKeys.length; i++) {
                Column column = linkTableToFKeys[i];
                value = ConverterDelegate.convert(ds.getDBMetaData(), column, toPKeyValues[i]);

                if (str.length() > 0) {
                    str.append(", ");
                    values.append(", ");
                }
                str.append(dbmd.leftBracket + column.columnName.toUpperCase() + dbmd.rightBracket);
                values.append(value);
            }

            str = new StringBuffer("INSERT INTO " + dbmd.leftBracket + linkTable.name.toUpperCase() + dbmd.rightBracket + " (" + str + ") VALUES (" + values + ")");

            Statement statement = null;
            try {
                String sql = str.toString();
                LOG.fine("masterClass="+masterObject.getClass().getName()+", propFromMaster="+propFromMaster+", sql="+sql);            
                statement = ds.getStatement(sql);
                statement.executeUpdate(sql);
            }
            catch (Exception e) {
              //System.out.println("UpdateDelegate.updateMany2ManyLinks(..) failed, exception: "+e);                
                // if (!connectionPool.isDatabaseAvailable()) throw new RuntimeException("Database Connection is not Available.  Error:"+e);
                // could be a duplicate record ... just ignore
                // throw new OADataSourceException(this, "OADataSourceJDBC.saveLinks() - "+e.getMessage());
            }
            finally {
                if (statement != null) ds.releaseStatement(statement);
            }
        }

        // get properties for each removed detailObject and delete linkObject
        for (int j=0; removes != null && j 0) str.append(" AND ");
                str.append( dbmd.leftBracket + column.columnName.toUpperCase() + dbmd.rightBracket + " " + op + " " + value  );
            }
            for (int i=0; i < linkTableToFKeys.length; i++) {
                Column column = linkTableToFKeys[i];
                String op = "=";
                if (toPKeyValues[i] == null) op = "IS";
                value = ConverterDelegate.convert(ds.getDBMetaData(), column, toPKeyValues[i]);
                if (str.length() > 0) str.append(" AND ");
                str.append( dbmd.leftBracket + column.columnName.toUpperCase() + dbmd.rightBracket + " " + op + " " + value  );
            }
            String whereClause = new String(str);

            str = new StringBuffer("DELETE FROM " + dbmd.leftBracket + linkTable.name.toUpperCase() + dbmd.rightBracket + " WHERE " + whereClause);
            Statement statement = null;
            try {
                String sql = str.toString();
                LOG.fine("masterClass="+masterObject.getClass().getName()+", propFromMaster="+propFromMaster+", sql="+sql);            
                statement = ds.getStatement(sql);
                statement.executeUpdate(sql);
            }
            catch (Exception e) {
//System.out.println("UpdateDelegate.updateMany2ManyLinks(..) failed, exception: "+e);                
                // if (!connectionPool.isDatabaseAvailable()) throw new OAException("Database Connection is not Available.  Error:"+e);
                // could be a duplicate ... just ignore
                // throw new OADataSourceException(this, "OADataSourceJDBC.saveLinks() - "+e.getMessage());
            }
            finally {
                if (statement != null) {
                	ds.releaseStatement(statement);
                	statement = null;
                }
            }
        }
	}

}







© 2015 - 2025 Weber Informatics LLC | Privacy Policy