KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectstyle > cayenne > access > jdbc > SQLTemplateAction


1 /* ====================================================================
2  *
3  * The ObjectStyle Group Software License, version 1.1
4  * ObjectStyle Group - http://objectstyle.org/
5  *
6  * Copyright (c) 2002-2005, Andrei (Andrus) Adamchik and individual authors
7  * of the software. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution, if any,
22  * must include the following acknowlegement:
23  * "This product includes software developed by independent contributors
24  * and hosted on ObjectStyle Group web site (http://objectstyle.org/)."
25  * Alternately, this acknowlegement may appear in the software itself,
26  * if and wherever such third-party acknowlegements normally appear.
27  *
28  * 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse
29  * or promote products derived from this software without prior written
30  * permission. For written permission, email
31  * "andrus at objectstyle dot org".
32  *
33  * 5. Products derived from this software may not be called "ObjectStyle"
34  * or "Cayenne", nor may "ObjectStyle" or "Cayenne" appear in their
35  * names without prior written permission.
36  *
37  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
38  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
39  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
40  * DISCLAIMED. IN NO EVENT SHALL THE OBJECTSTYLE GROUP OR
41  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
43  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
44  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
46  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
47  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
48  * SUCH DAMAGE.
49  * ====================================================================
50  *
51  * This software consists of voluntary contributions made by many
52  * individuals and hosted on ObjectStyle Group web site. For more
53  * information on the ObjectStyle Group, please see
54  * <http://objectstyle.org/>.
55  */

56
57 package org.objectstyle.cayenne.access.jdbc;
58
59 import java.sql.Connection JavaDoc;
60 import java.sql.PreparedStatement JavaDoc;
61 import java.sql.SQLException JavaDoc;
62 import java.util.Arrays JavaDoc;
63 import java.util.Collections JavaDoc;
64 import java.util.Iterator JavaDoc;
65 import java.util.Map JavaDoc;
66
67 import org.apache.commons.collections.IteratorUtils;
68 import org.objectstyle.cayenne.CayenneException;
69 import org.objectstyle.cayenne.access.OperationObserver;
70 import org.objectstyle.cayenne.access.QueryLogger;
71 import org.objectstyle.cayenne.dba.DbAdapter;
72 import org.objectstyle.cayenne.query.SQLAction;
73 import org.objectstyle.cayenne.query.SQLTemplate;
74 import org.objectstyle.cayenne.util.Util;
75
76 /**
77  * Implements a strategy for execution of updating SQLTemplates.
78  *
79  * @author Andrei Adamchik
80  * @since 1.2 replaces SQLTemplateExecutionPlan
81  */

82 public class SQLTemplateAction implements SQLAction {
83
84     protected DbAdapter adapter;
85     protected boolean removingLineBreaks;
86     protected SQLTemplate query;
87
88     public SQLTemplateAction(SQLTemplate query, DbAdapter adapter) {
89         this.query = query;
90         this.adapter = adapter;
91     }
92
93     /**
94      * Returns DbAdapter associated with this execution plan object.
95      */

96     public DbAdapter getAdapter() {
97         return adapter;
98     }
99
100     /**
101      * Runs a SQLTemplate query as an update.
102      */

103     public void performAction(Connection JavaDoc connection, OperationObserver observer)
104             throws SQLException JavaDoc, Exception JavaDoc {
105
106         String JavaDoc template = extractTemplateString();
107
108         // sanity check - misconfigured templates
109
if (template == null) {
110             throw new CayenneException("No template string configured for adapter "
111                     + getAdapter().getClass().getName());
112         }
113
114         boolean loggable = QueryLogger.isLoggable(query.getLoggingLevel());
115         int size = query.parametersSize();
116
117         SQLTemplateProcessor templateProcessor = new SQLTemplateProcessor();
118
119         // zero size indicates a one-shot query with no parameters
120
// so fake a single entry batch...
121
int[] counts = new int[size > 0 ? size : 1];
122         Iterator JavaDoc it = (size > 0) ? query.parametersIterator() : IteratorUtils
123                 .singletonIterator(Collections.EMPTY_MAP);
124         for (int i = 0; i < counts.length; i++) {
125             Map JavaDoc nextParameters = (Map JavaDoc) it.next();
126
127             SQLStatement compiled = templateProcessor.processTemplate(template,
128                     nextParameters);
129
130             if (loggable) {
131                 QueryLogger.logQuery(query.getLoggingLevel(), compiled.getSql(), Arrays
132                         .asList(compiled.getBindings()));
133             }
134
135             // TODO: we may cache prep statements for this loop, using merged string as a
136
// key since it is very likely that it will be the same for multiple parameter
137
// sets...
138
PreparedStatement JavaDoc statement = connection.prepareStatement(compiled.getSql());
139             try {
140                 bind(statement, compiled.getBindings());
141                 counts[i] = statement.executeUpdate();
142                 QueryLogger.logUpdateCount(query.getLoggingLevel(), counts[i]);
143             }
144             finally {
145                 statement.close();
146             }
147         }
148
149         observer.nextBatchCount(query, counts);
150     }
151
152     /**
153      * Extracts a template string from a SQLTemplate query. Exists mainly for the benefit
154      * of subclasses that can customize returned template.
155      *
156      * @since 1.2
157      */

158     protected String JavaDoc extractTemplateString() {
159         String JavaDoc sql = query.getTemplate(getAdapter().getClass().getName());
160         return isRemovingLineBreaks() ? Util.stripLineBreaks(sql, " ") : sql;
161     }
162
163     /**
164      * Binds parameters to the PreparedStatement.
165      */

166     protected void bind(PreparedStatement JavaDoc preparedStatement, ParameterBinding[] bindings)
167             throws SQLException JavaDoc, Exception JavaDoc {
168         // bind parameters
169
if (bindings.length > 0) {
170             int len = bindings.length;
171             for (int i = 0; i < len; i++) {
172                 adapter.bindParameter(preparedStatement,
173                         bindings[i].getValue(),
174                         i + 1,
175                         bindings[i].getJdbcType(),
176                         bindings[i].getPrecision());
177             }
178         }
179     }
180
181     /**
182      * Returns whether line breaks are removed when the query is executed. Some databases
183      * (like DB2) can't handle multiline queries.
184      */

185     public boolean isRemovingLineBreaks() {
186         return removingLineBreaks;
187     }
188
189     public void setRemovingLineBreaks(boolean removingLineBreaks) {
190         this.removingLineBreaks = removingLineBreaks;
191     }
192
193     /**
194      * Returns a SQLTemplate for this action.
195      */

196     public SQLTemplate getQuery() {
197         return query;
198     }
199 }
Popular Tags