KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > continuent > sequoia > controller > requests > InsertRequest


1 /**
2  * Sequoia: Database clustering technology.
3  * Copyright (C) 2002-2004 French National Institute For Research In Computer
4  * Science And Control (INRIA).
5  * Copyright (C) 2005 AmicoSoft, Inc. dba Emic Networks
6  * Copyright (C) 2005-2006 Continuent, Inc.
7  * Contact: sequoia@continuent.org
8  *
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  * http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Initial developer(s): Emmanuel Cecchet.
22  * Contributor(s): Mathieu Peltier, Sara Bouchenak, Stephane Giron.
23  */

24
25 package org.continuent.sequoia.controller.requests;
26
27 import java.io.Serializable JavaDoc;
28 import java.sql.SQLException JavaDoc;
29 import java.util.ArrayList JavaDoc;
30 import java.util.StringTokenizer JavaDoc;
31 import java.util.TreeSet JavaDoc;
32 import java.util.regex.Matcher JavaDoc;
33 import java.util.regex.Pattern JavaDoc;
34
35 import org.continuent.sequoia.controller.semantic.SemanticBehavior;
36 import org.continuent.sequoia.controller.sql.schema.DatabaseColumn;
37 import org.continuent.sequoia.controller.sql.schema.DatabaseSchema;
38 import org.continuent.sequoia.controller.sql.schema.DatabaseTable;
39 import org.continuent.sequoia.controller.sql.schema.TableColumn;
40
41 /**
42  * An <code>InsertRequest</code> is an SQL request of the following syntax:
43  *
44  * <pre>
45  * INSERT INTO table-name [(column-name[,column-name]*)] {VALUES (constant|null[,constant|null]*)}|{SELECT query}
46  * </pre>
47  * <code>VALUES<code> are ignored.
48  * *
49  * @author <a HREF="mailto:Emmanuel.Cecchet@inria.fr">Emmanuel Cecchet</a>
50  * @version 1.0
51  */

52 public class InsertRequest extends AbstractWriteRequest implements Serializable JavaDoc
53 {
54   private static final long serialVersionUID = -7395745061633156437L;
55
56   private static final String JavaDoc INSERT_REQUEST_PATTERN_STRING = "^insert\\s+(into\\s+)?(only\\s+)?([^(\\s|\\()]+)(\\s*\\(.*\\)\\s*|\\s+)(values|select)(.*)";
57
58   private static final Pattern JavaDoc INSERT_REQUEST_PATTERN = Pattern
59                                                                  .compile(
60                                                                      INSERT_REQUEST_PATTERN_STRING,
61                                                                      Pattern.CASE_INSENSITIVE
62                                                                          | Pattern.DOTALL);
63
64   // These TABLENAME_POS and COLUMNS_POS respectively represent the position of
65
// the table name and the list of columns in the previous regular expression.
66
// Check that it did change when updating the regular expression
67
// INSERT_REQUEST_PATTERN_STRING.
68
private static final int TABLENAME_POS = 3;
69   private static final int COLUMNS_POS = 4;
70
71   /**
72    * Creates a new <code>InsertRequest</code> instance. The caller must give
73    * an SQL request, without any leading or trailing spaces and beginning with
74    * 'create table ' (it will not be checked).
75    * <p>
76    * The request is not parsed but it can be done later by a call to
77    * {@link #parse(DatabaseSchema, int, boolean)}.
78    *
79    * @param sqlQuery the SQL request
80    * @param escapeProcessing should the driver to escape processing before
81    * sending to the database ?
82    * @param timeout an <code>int</code> value
83    * @param lineSeparator the line separator used in the query
84    * @see #parse(DatabaseSchema, int, boolean)
85    */

86   public InsertRequest(String JavaDoc sqlQuery, boolean escapeProcessing, int timeout,
87       String JavaDoc lineSeparator)
88   {
89     super(sqlQuery, escapeProcessing, timeout, lineSeparator,
90         RequestType.INSERT);
91   }
92
93   /**
94    * @see org.continuent.sequoia.controller.requests.AbstractRequest#altersAggregateList()
95    */

96   public boolean altersAggregateList()
97   {
98     return false;
99   }
100
101   /**
102    * @see org.continuent.sequoia.controller.requests.AbstractRequest#altersDatabaseCatalog()
103    */

104   public boolean altersDatabaseCatalog()
105   {
106     return false;
107   }
108
109   /**
110    * @see org.continuent.sequoia.controller.requests.AbstractRequest#altersDatabaseSchema()
111    */

112   public boolean altersDatabaseSchema()
113   {
114     return false;
115   }
116
117   /**
118    * @see org.continuent.sequoia.controller.requests.AbstractRequest#altersMetadataCache()
119    */

120   public boolean altersMetadataCache()
121   {
122     return false;
123   }
124
125   /**
126    * @see org.continuent.sequoia.controller.requests.AbstractRequest#altersQueryResultCache()
127    */

128   public boolean altersQueryResultCache()
129   {
130     return true;
131   }
132
133   /**
134    * @see org.continuent.sequoia.controller.requests.AbstractRequest#altersSomething()
135    */

136   public boolean altersSomething()
137   {
138     return true;
139   }
140
141   /**
142    * @see org.continuent.sequoia.controller.requests.AbstractRequest#altersStoredProcedureList()
143    */

144   public boolean altersStoredProcedureList()
145   {
146     return false;
147   }
148
149   /**
150    * @see org.continuent.sequoia.controller.requests.AbstractRequest#altersUserDefinedTypes()
151    */

152   public boolean altersUserDefinedTypes()
153   {
154     return false;
155   }
156
157   /**
158    * @see org.continuent.sequoia.controller.requests.AbstractRequest#altersUsers()
159    */

160   public boolean altersUsers()
161   {
162     return false;
163   }
164
165   /**
166    * @see AbstractRequest#cloneParsing(AbstractRequest)
167    */

168   public void cloneParsing(AbstractRequest request)
169   {
170     if (!request.isParsed())
171       return;
172     cloneParsingCommons(request);
173     cloneTableNameAndColumns((AbstractWriteRequest) request);
174     isParsed = true;
175   }
176
177   /**
178    * @see org.continuent.sequoia.controller.requests.AbstractRequest#needsMacroProcessing()
179    */

180   public boolean needsMacroProcessing()
181   {
182     return true;
183   }
184
185   /**
186    * Parse the query to know which table is affected. Also checks for the
187    * columns if the parsing granularity requires it.
188    *
189    * @see org.continuent.sequoia.controller.requests.AbstractRequest#parse(org.continuent.sequoia.controller.sql.schema.DatabaseSchema,
190    * int, boolean)
191    */

192   public void parse(DatabaseSchema schema, int granularity,
193       boolean isCaseSensitive) throws SQLException JavaDoc
194   {
195
196     if (granularity == ParsingGranularities.NO_PARSING)
197     {
198       isParsed = true;
199       return;
200     }
201
202     try
203     {
204       Matcher JavaDoc matcher;
205       String JavaDoc insertTable = "";
206       String JavaDoc strColumns = null;
207
208       String JavaDoc originalSQL = this.trimCarriageReturnAndTabs();
209
210       matcher = INSERT_REQUEST_PATTERN.matcher(originalSQL);
211       if (matcher.matches())
212       {
213         insertTable = matcher.group(TABLENAME_POS);
214         strColumns = matcher.group(COLUMNS_POS).trim();
215       }
216
217       if (!isCaseSensitive)
218         insertTable = insertTable.toLowerCase();
219
220       if (schema == null)
221       {
222         // Lock this table in write
223
writeLockedTables = new TreeSet JavaDoc();
224         writeLockedTables.add(insertTable);
225         isParsed = true;
226         // and stop parsing
227
return;
228       }
229
230       DatabaseTable t = schema.getTable(insertTable, isCaseSensitive);
231       if (t == null)
232         throw new SQLException JavaDoc("Unknown table '" + insertTable
233             + "' in this INSERT statement: '" + sqlQueryOrTemplate + "'");
234       else
235         tableName = t.getName();
236
237       // Lock this table in write
238
writeLockedTables = new TreeSet JavaDoc();
239       writeLockedTables.add(tableName);
240       addDependingTables(schema, writeLockedTables);
241
242       if ((granularity == ParsingGranularities.COLUMN)
243           || (granularity == ParsingGranularities.COLUMN_UNIQUE))
244       {
245         if (strColumns.length() > 0)
246         {
247           // Removes '(' and ')' surrounding column names
248
strColumns = strColumns.substring(1, strColumns.length() - 1);
249
250           // get all column names
251
StringTokenizer JavaDoc columnTokens = new StringTokenizer JavaDoc(strColumns, ",");
252
253           this.columns = new ArrayList JavaDoc();
254           DatabaseColumn col = null;
255           while (columnTokens.hasMoreTokens())
256           {
257             String JavaDoc token = columnTokens.nextToken().trim();
258             if ((col = t.getColumn(token)) == null)
259             {
260               tableName = null;
261               this.columns = null;
262               throw new SQLException JavaDoc("Unknown column name '" + token
263                   + "' in this INSERT statement: '" + sqlQueryOrTemplate + "'");
264             }
265             else
266             {
267               this.columns.add(new TableColumn(tableName, col.getName()));
268             }
269           }
270         }
271         else
272         {
273           // All columns are affected
274
this.columns = new ArrayList JavaDoc();
275           ArrayList JavaDoc cols = t.getColumns();
276           int size = cols.size();
277           for (int j = 0; j < size; j++)
278           {
279             this.columns.add(new TableColumn(tableName, ((DatabaseColumn) cols
280                 .get(j)).getName()));
281           }
282         }
283       }
284
285       isParsed = true;
286     }
287     finally
288     {
289       if (isParsed)
290       {
291         setSemantic(new SemanticBehavior(null, writeLockedTables, null,
292             altersDatabaseSchema(), altersMetadataCache(),
293             altersQueryResultCache(), altersUsers(), isReadOnly,
294             needsMacroProcessing(), SemanticBehavior.SERIALIZABLE_ORDER,
295             requiresConnectionPoolFlush
296                 ? SemanticBehavior.FLUSH_ALL_USERS
297                 : SemanticBehavior.FLUSH_NONE));
298       }
299     }
300   }
301
302   /**
303    * Displays some debugging information about this request.
304    */

305   public void debug()
306   {
307     super.debug();
308     if (tableName != null)
309       System.out.println("Inserted table: " + tableName);
310     else
311       System.out.println("No information about inserted table");
312
313     if (columns != null)
314     {
315       System.out.println("Inserted columns:");
316       for (int i = 0; i < columns.size(); i++)
317         System.out.println(" "
318             + ((TableColumn) columns.get(i)).getColumnName());
319     }
320     else
321       System.out.println("No information about inserted columns");
322
323     System.out.println("");
324   }
325
326 }
Popular Tags