This commit is contained in:
Lukas Eder 2014-11-12 11:41:58 +01:00
commit 64a60d0bb8
29 changed files with 598 additions and 221 deletions

View File

@ -41,6 +41,8 @@
package org.jooq.util;
import java.io.File;
import java.util.Collections;
import java.util.Set;
/**
@ -261,20 +263,28 @@ abstract class AbstractGenerator implements Generator {
/**
* If file is a directory, recursively empty its children.
* If file is a file, delete it
* If file is a file, delete it.
*/
protected void empty(File file, String suffix) {
empty(file, suffix, Collections.<File>emptySet());
}
/**
* If file is a directory, recursively empty its children.
* If file is a file, delete it, except if it is in the list of files to keep.
*/
protected void empty(File file, String suffix, Set<File> keep) {
if (file != null) {
if (file.isDirectory()) {
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
empty(child, suffix);
empty(child, suffix, keep);
}
}
} else {
if (file.getName().endsWith(suffix)) {
if (file.getName().endsWith(suffix) && !keep.contains(file)) {
file.delete();
}
}

View File

@ -45,6 +45,7 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@ -78,7 +79,6 @@ public abstract class GeneratorWriter<W extends GeneratorWriter<W>> {
private final File file;
private final PrintWriter writer;
private final StringBuilder sb;
private int indentTabs;
private boolean newline = true;
@ -87,12 +87,6 @@ public abstract class GeneratorWriter<W extends GeneratorWriter<W>> {
file.getParentFile().mkdirs();
this.file = file;
try {
this.writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
}
catch (IOException e) {
throw new GeneratorException("Error writing " + file.getAbsolutePath());
}
this.sb = new StringBuilder();
}
@ -235,11 +229,37 @@ public abstract class GeneratorWriter<W extends GeneratorWriter<W>> {
}
public final void close() {
String string = beforeClose(sb.toString());
String newContent = beforeClose(sb.toString());
writer.append(string);
writer.flush();
writer.close();
try {
// [#3756] Regenerate files only if there is a difference
String oldContent = null;
if (file.exists()) {
RandomAccessFile old = null;
try {
old = new RandomAccessFile(file, "r");
byte[] oldBytes = new byte[(int) old.length()];
old.readFully(oldBytes);
oldContent = new String(oldBytes, "UTF-8");
}
finally {
if (old != null)
old.close();
}
}
if (oldContent == null || !oldContent.equals(newContent)) {
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
writer.append(newContent);
writer.flush();
writer.close();
}
}
catch (IOException e) {
throw new GeneratorException("Error writing " + file.getAbsolutePath());
}
}
protected String beforeClose(String string) {

View File

@ -57,6 +57,7 @@ import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@ -158,6 +159,11 @@ public class JavaGenerator extends AbstractGenerator {
*/
private Map<SchemaDefinition, String> schemaVersions;
/**
* All files modified by this generator
*/
private Set<File> files = new LinkedHashSet<File>();
@Override
public final void generate(Database db) {
this.isoDate = DatatypeConverter.printDateTime(Calendar.getInstance(TimeZone.getTimeZone("UTC")));
@ -273,9 +279,6 @@ public class JavaGenerator extends AbstractGenerator {
// ----------------------------------------------------------------------
// XXX Initialising
// ----------------------------------------------------------------------
log.info("Emptying", targetPackage.getAbsolutePath());
empty(getStrategy().getFile(schema).getParentFile(), ".java");
generateSchema(schema);
if (generateGlobalObjectReferences() && database.getSequences(schema).size() > 0) {
@ -356,8 +359,12 @@ public class JavaGenerator extends AbstractGenerator {
x
xx [/pro] */
log.info("Removing excess files");
empty(getStrategy().getFile(schema).getParentFile(), ".java", files);
files.clear();
// XXX [#651] Refactoring-cursor
watch.splitInfo("GENERATION FINISHED!");
watch.splitInfo("GENERATION FINISHED: " + schema.getQualifiedName());
}
private class AvoidAmbiguousClassesFilter implements Database.Filter {
@ -399,7 +406,7 @@ public class JavaGenerator extends AbstractGenerator {
xxxxxxxxxxxxxxxxxxxx xxxxxxxxx
xxxxxxxxxxxxxx xxxxxxxxxxxxxx x xxxxxxxxxxxxxxxx xxxxxxxxx
xxxxxxxxxx xxx x xxx xxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxx
xxxxxxxxxx xxx x xxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxx xxxxxxxx
xxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxx xxxxxx xx xxx xxxxxx xx x x xxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxx
@ -438,7 +445,7 @@ public class JavaGenerator extends AbstractGenerator {
protected void generateRelations(SchemaDefinition schema) {
log.info("Generating Keys");
JavaWriter out = new JavaWriter(new File(getStrategy().getFile(schema).getParentFile(), "Keys.java"));
JavaWriter out = newJavaWriter(new File(getStrategy().getFile(schema).getParentFile(), "Keys.java"));
printPackage(out, schema);
printClassJavadoc(out,
"A class modelling foreign key relationships between tables of the <code>" + schema.getOutputName() + "</code> schema");
@ -664,7 +671,7 @@ public class JavaGenerator extends AbstractGenerator {
final List<String> interfaces = getStrategy().getJavaClassImplements(tableOrUdt, Mode.RECORD);
final List<? extends TypedElementDefinition<?>> columns = getTypedElements(tableOrUdt);
JavaWriter out = new JavaWriter(getStrategy().getFile(tableOrUdt, Mode.RECORD));
JavaWriter out = newJavaWriter(getStrategy().getFile(tableOrUdt, Mode.RECORD));
printPackage(out, tableOrUdt, Mode.RECORD);
if (tableOrUdt instanceof TableDefinition)
@ -957,7 +964,7 @@ public class JavaGenerator extends AbstractGenerator {
final String className = getStrategy().getJavaClassName(tableOrUDT, Mode.INTERFACE);
final List<String> interfaces = getStrategy().getJavaClassImplements(tableOrUDT, Mode.INTERFACE);
JavaWriter out = new JavaWriter(getStrategy().getFile(tableOrUDT, Mode.INTERFACE));
JavaWriter out = newJavaWriter(getStrategy().getFile(tableOrUDT, Mode.INTERFACE));
printPackage(out, tableOrUDT, Mode.INTERFACE);
if (tableOrUDT instanceof TableDefinition)
generateInterfaceClassJavadoc((TableDefinition) tableOrUDT, out);
@ -1053,7 +1060,7 @@ public class JavaGenerator extends AbstractGenerator {
final String schemaId = getStrategy().getFullJavaIdentifier(schema);
final String udtId = getStrategy().getJavaIdentifier(udt);
JavaWriter out = new JavaWriter(getStrategy().getFile(udt));
JavaWriter out = newJavaWriter(getStrategy().getFile(udt));
printPackage(out, udt);
generateUDTClassJavadoc(udt, out);
printClassAnnotations(out, schema);
@ -1258,7 +1265,7 @@ public class JavaGenerator extends AbstractGenerator {
protected void generateUDTReferences(SchemaDefinition schema) {
log.info("Generating UDT references");
JavaWriter out = new JavaWriter(new File(getStrategy().getFile(schema).getParentFile(), "UDTs.java"));
JavaWriter out = newJavaWriter(new File(getStrategy().getFile(schema).getParentFile(), "UDTs.java"));
printPackage(out, schema);
printClassJavadoc(out, "Convenience access to all UDTs in " + schema.getOutputName());
printClassAnnotations(out, schema);
@ -1305,7 +1312,7 @@ public class JavaGenerator extends AbstractGenerator {
xxxxx xxxxxx xxxxxxxx x xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxx xxxxxx xxxxxxxxxxxxxxxxxxxx x xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxx xxx x xxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxx
xxxxxxxxxx xxx x xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxx xxxxxx xxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxx
@ -1401,7 +1408,7 @@ public class JavaGenerator extends AbstractGenerator {
final String className = getStrategy().getJavaClassName(e, Mode.ENUM);
final List<String> interfaces = getStrategy().getJavaClassImplements(e, Mode.ENUM);
JavaWriter out = new JavaWriter(getStrategy().getFile(e, Mode.ENUM));
JavaWriter out = newJavaWriter(getStrategy().getFile(e, Mode.ENUM));
printPackage(out, e);
generateEnumClassJavadoc(e, out);
printClassAnnotations(out, e.getSchema());
@ -1473,7 +1480,7 @@ public class JavaGenerator extends AbstractGenerator {
protected void generateRoutines(SchemaDefinition schema) {
log.info("Generating routines and table-valued functions");
JavaWriter out = new JavaWriter(new File(getStrategy().getFile(schema).getParentFile(), "Routines.java"));
JavaWriter out = newJavaWriter(new File(getStrategy().getFile(schema).getParentFile(), "Routines.java"));
printPackage(out, schema);
printClassJavadoc(out, "Convenience access to all stored procedures and functions in " + schema.getOutputName());
printClassAnnotations(out, schema);
@ -1548,7 +1555,7 @@ public class JavaGenerator extends AbstractGenerator {
final List<String> interfaces = getStrategy().getJavaClassImplements(pkg, Mode.DEFAULT);
// Static convenience methods
JavaWriter out = new JavaWriter(getStrategy().getFile(pkg));
JavaWriter out = newJavaWriter(getStrategy().getFile(pkg));
printPackage(out, pkg);
generatePackageClassJavadoc(pkg, out);
printClassAnnotations(out, schema);
@ -1596,7 +1603,7 @@ public class JavaGenerator extends AbstractGenerator {
protected void generateTableReferences(SchemaDefinition schema) {
log.info("Generating table references");
JavaWriter out = new JavaWriter(new File(getStrategy().getFile(schema).getParentFile(), "Tables.java"));
JavaWriter out = newJavaWriter(new File(getStrategy().getFile(schema).getParentFile(), "Tables.java"));
printPackage(out, schema);
printClassJavadoc(out, "Convenience access to all tables in " + schema.getOutputName());
printClassAnnotations(out, schema);
@ -1672,7 +1679,7 @@ public class JavaGenerator extends AbstractGenerator {
log.info("Generating DAO", getStrategy().getFileName(table, Mode.DAO));
JavaWriter out = new JavaWriter(getStrategy().getFile(table, Mode.DAO));
JavaWriter out = newJavaWriter(getStrategy().getFile(table, Mode.DAO));
printPackage(out, table, Mode.DAO);
generateDaoClassJavadoc(table, out);
printClassAnnotations(out, table.getSchema());
@ -1795,7 +1802,7 @@ public class JavaGenerator extends AbstractGenerator {
interfaces.add(getStrategy().getFullJavaClassName(tableOrUDT, Mode.INTERFACE));
}
JavaWriter out = new JavaWriter(getStrategy().getFile(tableOrUDT, Mode.POJO));
JavaWriter out = newJavaWriter(getStrategy().getFile(tableOrUDT, Mode.POJO));
printPackage(out, tableOrUDT, Mode.POJO);
if (tableOrUDT instanceof TableDefinition)
@ -2048,7 +2055,7 @@ public class JavaGenerator extends AbstractGenerator {
", pk=" + (primaryKey != null ? primaryKey.getName() : "N/A") +
"]");
JavaWriter out = new JavaWriter(getStrategy().getFile(table));
JavaWriter out = newJavaWriter(getStrategy().getFile(table));
printPackage(out, table);
generateTableClassJavadoc(table, out);
printClassAnnotations(out, schema);
@ -2302,7 +2309,7 @@ public class JavaGenerator extends AbstractGenerator {
protected void generateSequences(SchemaDefinition schema) {
log.info("Generating sequences");
JavaWriter out = new JavaWriter(new File(getStrategy().getFile(schema).getParentFile(), "Sequences.java"));
JavaWriter out = newJavaWriter(new File(getStrategy().getFile(schema).getParentFile(), "Sequences.java"));
printPackage(out, schema);
printClassJavadoc(out, "Convenience access to all sequences in " + schema.getOutputName());
printClassAnnotations(out, schema);
@ -2334,7 +2341,7 @@ public class JavaGenerator extends AbstractGenerator {
final String className = getStrategy().getJavaClassName(schema);
final List<String> interfaces = getStrategy().getJavaClassImplements(schema, Mode.DEFAULT);
JavaWriter out = new JavaWriter(getStrategy().getFile(schema));
JavaWriter out = newJavaWriter(getStrategy().getFile(schema));
printPackage(out, schema);
generateSchemaClassJavadoc(schema, out);
printClassAnnotations(out, schema);
@ -2571,7 +2578,7 @@ public class JavaGenerator extends AbstractGenerator {
final String schemaId = getStrategy().getFullJavaIdentifier(schema);
final List<String> packageId = getStrategy().getFullJavaIdentifiers(routine.getPackage());
JavaWriter out = new JavaWriter(getStrategy().getFile(routine));
JavaWriter out = newJavaWriter(getStrategy().getFile(routine));
printPackage(out, routine);
generateRoutineClassJavadoc(routine, out);
printClassAnnotations(out, schema);
@ -3379,4 +3386,9 @@ public class JavaGenerator extends AbstractGenerator {
return result;
}
private final JavaWriter newJavaWriter(File file) {
files.add(file);
return new JavaWriter(file);
}
}

View File

@ -141,6 +141,8 @@ public abstract class AbstractDatabase implements Database {
private transient Map<SchemaDefinition, List<RoutineDefinition>> routinesBySchema;
private transient Map<SchemaDefinition, List<PackageDefinition>> packagesBySchema;
private static Map<String, Pattern> patterns;
// Other caches
private final Map<Table<?>, Boolean> exists;
@ -196,6 +198,19 @@ public abstract class AbstractDatabase implements Database {
return result;
}
final static Pattern pattern(String regex) {
if (patterns == null)
patterns = new HashMap<String, Pattern>();
Pattern pattern = patterns.get(regex);
if (pattern == null) {
pattern = Pattern.compile(regex, Pattern.COMMENTS);
patterns.put(regex, pattern);
}
return pattern;
}
@Override
public final List<SchemaDefinition> getSchemata() {
if (schemata == null) {
@ -679,14 +694,27 @@ public abstract class AbstractDatabase implements Database {
String types = forcedType.getTypes();
if (expression != null
&& !definition.getName().matches(expression)
&& !definition.getQualifiedName().matches(expression)) {
continue forcedTypeLoop;
if (expression != null) {
Pattern p = pattern(expression);
if ( !p.matcher(definition.getName()).matches()
&& !p.matcher(definition.getQualifiedName()).matches()) {
continue forcedTypeLoop;
}
}
if (types != null && definedType != null && !definedType.getType().matches(types)) {
continue forcedTypeLoop;
if (types != null && definedType != null) {
Pattern p = pattern(types);
if ( ( !p.matcher(definedType.getType()).matches() )
&& ( definedType.getLength() == 0
|| !p.matcher(definedType.getType() + "(" + definedType.getLength() + ")").matches())
&& ( definedType.getScale() != 0
|| !p.matcher(definedType.getType() + "(" + definedType.getPrecision() + ")").matches())
&& ( !p.matcher(definedType.getType() + "(" + definedType.getPrecision() + "," + definedType.getScale() + ")").matches() )
&& ( !p.matcher(definedType.getType() + "(" + definedType.getPrecision() + ", " + definedType.getScale() + ")").matches() )) {
continue forcedTypeLoop;
}
}
return forcedType;
@ -883,7 +911,7 @@ public abstract class AbstractDatabase implements Database {
definitionsLoop: for (T definition : definitions) {
if (excludes != null) {
for (String exclude : excludes) {
Pattern p = Pattern.compile(exclude, Pattern.COMMENTS);
Pattern p = pattern(exclude);
if (exclude != null &&
(p.matcher(definition.getName()).matches() ||
@ -899,7 +927,7 @@ public abstract class AbstractDatabase implements Database {
if (includes != null) {
for (String include : includes) {
Pattern p = Pattern.compile(include, Pattern.COMMENTS);
Pattern p = pattern(include);
if (include != null &&
(p.matcher(definition.getName()).matches() ||

View File

@ -12,15 +12,13 @@
The JDBC configuration element contains information about how
to set up the database connection used for source code generation
-->
<element name="jdbc" type="tns:Jdbc" minOccurs="1"
maxOccurs="1" />
<element name="jdbc" type="tns:Jdbc" minOccurs="0" maxOccurs="1" />
<!--
The GENERATOR configuration element contains information about
source code generation itself
-->
<element name="generator" type="tns:Generator" minOccurs="1"
maxOccurs="1" />
<element name="generator" type="tns:Generator" minOccurs="1" maxOccurs="1" />
</all>
</complexType>
</element>

View File

@ -814,6 +814,17 @@ public enum Clause {
*/
CREATE_TABLE_AS,
/**
* A column list within a {@link #CREATE_TABLE} statement.
* <p>
* This clause surrounds
* <ul>
* <li>The parentheses</li>
* <li>The column list</li>
* </ul>
*/
CREATE_TABLE_COLUMNS,
/**
* A complete <code>CREATE VIEW</code> statement.
*/

View File

@ -68,4 +68,16 @@ public interface CreateTableAsStep<R extends Record> {
*/
@Support({ CUBRID, DERBY, FIREBIRD, H2, HSQLDB, MARIADB, MYSQL, POSTGRES, SQLITE })
CreateTableFinalStep as(Select<? extends R> select);
/**
* Add a column to the column list of the <code>CREATE TABLE</code> statement.
*/
@Support
<T> CreateTableColumnStep column(Field<T> field, DataType<T> type);
/**
* Add a column to the column list of the <code>CREATE TABLE</code> statement.
*/
@Support
CreateTableColumnStep column(String field, DataType<?> type);
}

View File

@ -0,0 +1,61 @@
/**
* Copyright (c) 2009-2014, Data Geekery GmbH (http://www.datageekery.com)
* All rights reserved.
*
* This work is dual-licensed
* - under the Apache Software License 2.0 (the "ASL")
* - under the jOOQ License and Maintenance Agreement (the "jOOQ License")
* =============================================================================
* You may choose which license applies to you:
*
* - If you're using this work with Open Source databases, you may choose
* either ASL or jOOQ License.
* - If you're using this work with at least one commercial database, you must
* choose jOOQ License
*
* For more information, please visit http://www.jooq.org/licenses
*
* Apache Software License 2.0:
* -----------------------------------------------------------------------------
* 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.
*
* jOOQ License and Maintenance Agreement:
* -----------------------------------------------------------------------------
* Data Geekery grants the Customer the non-exclusive, timely limited and
* non-transferable license to install and use the Software under the terms of
* the jOOQ License and Maintenance Agreement.
*
* This library is distributed with a LIMITED WARRANTY. See the jOOQ License
* and Maintenance Agreement for more details: http://www.jooq.org/licensing
*/
package org.jooq;
/**
* A {@link Query} that can create tables.
*
* @author Lukas Eder
*/
public interface CreateTableColumnStep extends CreateTableFinalStep {
/**
* Add a column to the column list of the <code>CREATE TABLE</code> statement.
*/
@Support
<T> CreateTableColumnStep column(Field<T> field, DataType<T> type);
/**
* Add a column to the column list of the <code>CREATE TABLE</code> statement.
*/
@Support
CreateTableColumnStep column(String field, DataType<?> type);
}

View File

@ -5863,6 +5863,49 @@ public interface DSLContext extends Scope {
*/
int fetchCount(Table<?> table, Condition condition) throws DataAccessException;
/**
* Check if a {@link Select} would return any records, if it were executed.
* <p>
* This wraps a pre-existing <code>SELECT</code> query in another one to
* check for result existence, without modifying the original
* <code>SELECT</code>. An example: <code><pre>
* -- Original query:
* SELECT id, title FROM book WHERE title LIKE '%a%'
*
* -- Wrapped query:
* SELECT EXISTS (
* SELECT id, title FROM book WHERE title LIKE '%a%'
* )
* </pre></code>
*
* @param query The wrapped query
* @return The <code>EXISTS(...)</code> result
* @throws DataAccessException if something went wrong executing the query
*/
boolean fetchExists(Select<?> query) throws DataAccessException;
/**
* Check if a table has any records.
* <p>
* This executes <code><pre>SELECT EXISTS(SELECT * FROM table)</pre></code>
*
* @param table The table whose records to count
* @return The number or records in the table
* @throws DataAccessException if something went wrong executing the query
*/
boolean fetchExists(Table<?> table) throws DataAccessException;
/**
* Check if a table has any records that satisfy a condition.
* <p>
* This executes <code><pre>SELECT EXISTS(SELECT * FROM table WHERE condition)</pre></code>
*
* @param table The table whose records to count
* @return The number or records in the table
* @throws DataAccessException if something went wrong executing the query
*/
boolean fetchExists(Table<?> table, Condition condition) throws DataAccessException;
/**
* Execute a {@link Query} in the context of this <code>DSLContext</code>.
*

View File

@ -236,6 +236,15 @@ import org.jooq.tools.StopWatchListener;
* <td>Yes, 1x</td>
* </tr>
* <tr>
* <td> {@link #warning(ExecuteContext)}</td>
* <td>Maybe, 1x</td>
* <td>Maybe, 1x</td>
* <td>Maybe, 1x</td>
* <td>Maybe, 1x</td>
* <td>Maybe, 1x</td>
* <td>Maybe, 1x</td>
* </tr>
* <tr>
* <td> {@link #exception(ExecuteContext)}</td>
* <td>Maybe, 1x</td>
* <td>Maybe, 1x</td>

View File

@ -46,6 +46,7 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLData;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
@ -683,6 +684,21 @@ public interface Record extends Attachable, Comparable<Record> {
*/
Object[] intoArray();
/**
* Convert this record into a list.
* <p>
* The resulting list has the same number of elements as this record has
* fields. The resulting array contains data as such:
* <p>
* <code><pre>
* // For arbitrary values of i
* record.getValue(i) == record.intoList().get(i)
* </pre></code>
* <p>
* This is the same as calling <code>Arrays.asList(intoArray())</code>
*/
List<Object> intoList();
/**
* Return this record as a name/value map.
* <p>

View File

@ -134,6 +134,11 @@ public interface Routine<T> extends QueryPart {
*/
T getReturnValue();
/**
* @return The routine's results (if available)
*/
List<Result<Record>> getResults();
/**
* @return A list of parameters passed to the stored object as argument
*/

View File

@ -106,6 +106,13 @@ public interface Table<R extends Record> extends TableLike<R> {
*/
Class<? extends R> getRecordType();
/**
* Create a new {@link Record} of this table's type.
*
* @see DSLContext#newRecord(Table)
*/
R newRecord();
/**
* Retrieve the table's <code>IDENTITY</code> information, if available.
* <p>

View File

@ -98,6 +98,13 @@ public interface UDT<R extends UDTRecord<R>> extends QueryPart {
*/
Class<R> getRecordType();
/**
* Create a new {@link Record} of this UDT's type.
*
* @see DSLContext#newRecord(UDT)
*/
R newRecord();
/**
* The UDT's data type as known to the database
*/

View File

@ -52,7 +52,6 @@ import static org.jooq.impl.DSL.using;
import static org.jooq.impl.Utils.DATA_COUNT_BIND_VALUES;
import static org.jooq.impl.Utils.DATA_FORCE_STATIC_STATEMENT;
import static org.jooq.impl.Utils.consumeExceptions;
import static org.jooq.impl.Utils.consumeWarnings;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@ -413,10 +412,6 @@ abstract class AbstractQuery extends AbstractQueryPart implements Query, Attacha
consumeExceptions(ctx.configuration(), stmt, e);
throw e;
}
finally {
consumeWarnings(ctx, listener);
}
}
/**

View File

@ -55,6 +55,7 @@ import static org.jooq.impl.Utils.settings;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.LinkedHashMap;
@ -523,6 +524,11 @@ abstract class AbstractRecord extends AbstractStore implements Record {
return into(Object[].class);
}
@Override
public final List<Object> intoList() {
return Arrays.asList(intoArray());
}
@Override
public final Map<String, Object> intoMap() {
Map<String, Object> map = new LinkedHashMap<String, Object>();

View File

@ -48,12 +48,11 @@ import static java.util.concurrent.Executors.newSingleThreadExecutor;
import static org.jooq.SQLDialect.CUBRID;
// ...
import static org.jooq.impl.Utils.DATA_LOCK_ROWS_FOR_UPDATE;
import static org.jooq.impl.Utils.consumeWarnings;
import static org.jooq.impl.Utils.consumeResultSets;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@ -104,9 +103,7 @@ abstract class AbstractResultQuery<R extends Record> extends AbstractQuery imple
private List<Result<Record>> results;
// Some temp variables for String interning
private int[] internIndexes;
private Field<?>[] internFields;
private String[] internNames;
private final Intern intern = new Intern();
AbstractResultQuery(Configuration configuration) {
super(configuration);
@ -173,36 +170,22 @@ abstract class AbstractResultQuery<R extends Record> extends AbstractQuery imple
@Override
public final ResultQuery<R> intern(Field<?>... fields) {
this.internFields = fields;
intern.internFields = fields;
return this;
}
@Override
public final ResultQuery<R> intern(int... fieldIndexes) {
this.internIndexes = fieldIndexes;
intern.internIndexes = fieldIndexes;
return this;
}
@Override
public final ResultQuery<R> intern(String... fieldNames) {
this.internNames = fieldNames;
intern.internNames = fieldNames;
return this;
}
private final int[] internIndexes(Field<?>[] fields) {
if (internIndexes != null) {
return internIndexes;
}
else if (internFields != null) {
return new Fields<Record>(fields).indexesOf(internFields);
}
else if (internNames != null) {
return new Fields<Record>(fields).indexesOf(internNames);
}
return null;
}
@Override
protected final void prepare(ExecuteContext ctx) throws SQLException {
@ -250,33 +233,28 @@ abstract class AbstractResultQuery<R extends Record> extends AbstractQuery imple
@Override
protected final int execute(ExecuteContext ctx, ExecuteListener listener) throws SQLException {
try {
listener.executeStart(ctx);
listener.executeStart(ctx);
/* [pro] xx
xx xxxx xxxxxxx xxxx xx xxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxx
xx xxxxxxxxxx xx xxxxx xxx xxx xxxxxxx
xx xxxxxxxxxxxxx xx xxxx x
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
x
/* [pro] xx
xx xxxx xxxxxxx xxxx xx xxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxx
xx xxxxxxxxxx xx xxxxx xxx xxx xxxxxxx
xx xxxxxxxxxxxxx xx xxxx x
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
x
xx xxxxxxx xxxxx xxxxxxxxxxxxxx xx xxxxx xx xxxxxx xxxxxxx xxxx xxx
xx xxx xxxxxx x xxxxxxxxxx xxxx xxxxxxxx xxxxxx xxxxxxxxxxxxxxxxxxxxxxx
xxxx xx [/pro] */if (ctx.statement().execute()) {
ctx.resultSet(ctx.statement().getResultSet());
}
listener.executeEnd(ctx);
}
finally {
consumeWarnings(ctx, listener);
xx xxxxxxx xxxxx xxxxxxxxxxxxxx xx xxxxx xx xxxxxx xxxxxxx xxxx xxx
xx xxx xxxxxx x xxxxxxxxxx xxxx xxxxxxxx xxxxxx xxxxxxxxxxxxxxxxxxxxxxx
xxxx xx [/pro] */if (ctx.statement().execute()) {
ctx.resultSet(ctx.statement().getResultSet());
}
listener.executeEnd(ctx);
// Fetch a single result set
if (!many) {
if (ctx.resultSet() != null) {
Field<?>[] fields = getFields(ctx.resultSet().getMetaData());
cursor = new CursorImpl<R>(ctx, listener, fields, internIndexes(fields), keepStatement(), keepResultSet(), getRecordType());
cursor = new CursorImpl<R>(ctx, listener, fields, intern.internIndexes(fields), keepStatement(), keepResultSet(), getRecordType());
if (!lazy) {
result = cursor.fetch();
@ -291,28 +269,7 @@ abstract class AbstractResultQuery<R extends Record> extends AbstractQuery imple
// Fetch several result sets
else {
results = new ArrayList<Result<Record>>();
boolean anyResults = false;
while (ctx.resultSet() != null) {
anyResults = true;
Field<?>[] fields = new MetaDataFieldProvider(ctx.configuration(), ctx.resultSet().getMetaData()).getFields();
Cursor<Record> c = new CursorImpl<Record>(ctx, listener, fields, internIndexes(fields), true, false);
results.add(c.fetch());
if (ctx.statement().getMoreResults()) {
ctx.resultSet(ctx.statement().getResultSet());
}
else {
ctx.resultSet(null);
}
}
// Call this only when there was at least one ResultSet.
// Otherwise, this call is not supported by ojdbc...
if (anyResults) {
ctx.statement().getMoreResults(Statement.CLOSE_ALL_RESULTS);
}
consumeResultSets(ctx, listener, results, intern);
}
return result != null ? result.size() : 0;

View File

@ -51,7 +51,6 @@ import static org.jooq.impl.DSL.table;
import static org.jooq.impl.DSL.using;
import static org.jooq.impl.DSL.val;
import static org.jooq.impl.Utils.consumeExceptions;
import static org.jooq.impl.Utils.consumeWarnings;
import static org.jooq.impl.Utils.settings;
import java.sql.CallableStatement;
@ -79,6 +78,7 @@ import org.jooq.ExecuteListener;
import org.jooq.Field;
import org.jooq.Package;
import org.jooq.Parameter;
import org.jooq.Record;
import org.jooq.RenderContext;
import org.jooq.Result;
import org.jooq.Routine;
@ -114,6 +114,7 @@ public abstract class AbstractRoutine<T> extends AbstractQueryPart implements Ro
private final List<Parameter<?>> outParameters;
private final DataType<T> type;
private Parameter<T> returnParameter;
private List<Result<Record>> results;
private boolean overloaded;
private boolean hasDefaultedParameters;
@ -127,7 +128,7 @@ public abstract class AbstractRoutine<T> extends AbstractQueryPart implements Ro
private transient Field<T> function;
private Configuration configuration;
private final Map<Parameter<?>, Object> results;
private final Map<Parameter<?>, Object> outValues;
private final Map<Parameter<?>, Integer> parameterIndexes;
// ------------------------------------------------------------------------
@ -164,10 +165,11 @@ public abstract class AbstractRoutine<T> extends AbstractQueryPart implements Ro
this.allParameters = new ArrayList<Parameter<?>>();
this.inParameters = new ArrayList<Parameter<?>>();
this.outParameters = new ArrayList<Parameter<?>>();
this.results = new ArrayList<Result<Record>>();
this.inValues = new HashMap<Parameter<?>, Field<?>>();
this.inValuesDefaulted = new HashSet<Parameter<?>>();
this.inValuesNonDefaulted = new HashSet<Parameter<?>>();
this.results = new HashMap<Parameter<?>, Object>();
this.outValues = new HashMap<Parameter<?>, Object>();
this.type = converter == null
? (DataType<T>) type
: type.asConvertedDataType((Converter) converter);
@ -241,6 +243,9 @@ public abstract class AbstractRoutine<T> extends AbstractQueryPart implements Ro
@Override
public final int execute() {
results.clear();
outValues.clear();
// Procedures (no return value) are always executed as CallableStatement
if (type == null) {
return executeCallableStatement();
@ -283,13 +288,13 @@ public abstract class AbstractRoutine<T> extends AbstractQueryPart implements Ro
private final int executeSelectFrom() {
DSLContext create = create(configuration);
Result<?> result = create.selectFrom(table(asField())).fetch();
results.put(returnParameter, result);
outValues.put(returnParameter, result);
return 0;
}
private final int executeSelect() {
final Field<T> field = asField();
results.put(returnParameter, create(configuration).select(field).fetchOne(field));
outValues.put(returnParameter, create(configuration).select(field).fetchOne(field));
return 0;
}
@ -317,6 +322,11 @@ public abstract class AbstractRoutine<T> extends AbstractQueryPart implements Ro
execute0(ctx, listener);
/* [pro] xx
xx xxxxxxx xxx xxxxx xx xxxxxxxxx xxxxxx xxxx xxx xxxx xxxxxxxxx
xx xxx xxxxxxxxxx xx xxxxxxxx xx xxx xxxxxx
xx [/pro] */
Utils.consumeResultSets(ctx, listener, results, null);
fetchOutParameters(ctx);
return 0;
}
@ -343,7 +353,10 @@ public abstract class AbstractRoutine<T> extends AbstractQueryPart implements Ro
private final void execute0(ExecuteContext ctx, ExecuteListener listener) throws SQLException {
try {
listener.executeStart(ctx);
ctx.statement().execute();
if (ctx.statement().execute())
ctx.resultSet(ctx.statement().getResultSet());
listener.executeEnd(ctx);
}
@ -352,10 +365,6 @@ public abstract class AbstractRoutine<T> extends AbstractQueryPart implements Ro
consumeExceptions(ctx.configuration(), ctx.statement(), e);
throw e;
}
finally {
consumeWarnings(ctx, listener);
}
}
@Override
@ -569,7 +578,7 @@ public abstract class AbstractRoutine<T> extends AbstractQueryPart implements Ro
);
parameter.getBinding().get(out);
results.put(parameter, out.value());
outValues.put(parameter, out.value());
}
private final void registerOutParameters(Configuration c, CallableStatement statement) throws SQLException {
@ -602,9 +611,14 @@ public abstract class AbstractRoutine<T> extends AbstractQueryPart implements Ro
return null;
}
@Override
public final List<Result<Record>> getResults() {
return results;
}
@SuppressWarnings("unchecked")
protected final <Z> Z getValue(Parameter<Z> parameter) {
return (Z) results.get(parameter);
return (Z) outValues.get(parameter);
}
protected final Map<Parameter<?>, Field<?>> getInValues() {

View File

@ -45,7 +45,6 @@ import static org.jooq.conf.RenderNameStyle.LOWER;
import static org.jooq.conf.RenderNameStyle.UPPER;
import static org.jooq.impl.DSL.select;
// ...
import static org.jooq.impl.Utils.consumeWarnings;
import static org.jooq.impl.Utils.fieldArray;
import static org.jooq.impl.Utils.unqualify;
import static org.jooq.util.sqlite.SQLiteDSL.rowid;
@ -327,15 +326,10 @@ abstract class AbstractStoreQuery<R extends Record> extends AbstractQuery implem
// SQLite can select _rowid_ after the insert
case SQLITE: {
try {
listener.executeStart(ctx);
result = ctx.statement().executeUpdate();
ctx.rows(result);
listener.executeEnd(ctx);
}
finally {
consumeWarnings(ctx, listener);
}
listener.executeStart(ctx);
result = ctx.statement().executeUpdate();
ctx.rows(result);
listener.executeEnd(ctx);
DSLContext create = DSL.using(ctx.configuration());
returned =
@ -358,15 +352,10 @@ abstract class AbstractStoreQuery<R extends Record> extends AbstractQuery implem
xx [/pro] */
case CUBRID: {
try {
listener.executeStart(ctx);
result = ctx.statement().executeUpdate();
ctx.rows(result);
listener.executeEnd(ctx);
}
finally {
consumeWarnings(ctx, listener);
}
listener.executeStart(ctx);
result = ctx.statement().executeUpdate();
ctx.rows(result);
listener.executeEnd(ctx);
selectReturning(ctx.configuration(), create(ctx.configuration()).lastID());
return result;
@ -385,15 +374,10 @@ abstract class AbstractStoreQuery<R extends Record> extends AbstractQuery implem
case H2:
case MARIADB:
case MYSQL: {
try {
listener.executeStart(ctx);
result = ctx.statement().executeUpdate();
ctx.rows(result);
listener.executeEnd(ctx);
}
finally {
consumeWarnings(ctx, listener);
}
listener.executeStart(ctx);
result = ctx.statement().executeUpdate();
ctx.rows(result);
listener.executeEnd(ctx);
rs = ctx.statement().getGeneratedKeys();
@ -426,15 +410,9 @@ abstract class AbstractStoreQuery<R extends Record> extends AbstractQuery implem
// in the Postgres JDBC driver
case FIREBIRD:
case POSTGRES: {
try {
listener.executeStart(ctx);
rs = ctx.statement().executeQuery();
listener.executeEnd(ctx);
}
finally {
consumeWarnings(ctx, listener);
}
listener.executeStart(ctx);
rs = ctx.statement().executeQuery();
listener.executeEnd(ctx);
break;
}
@ -444,15 +422,10 @@ abstract class AbstractStoreQuery<R extends Record> extends AbstractQuery implem
xx [/pro] */
case HSQLDB:
default: {
try {
listener.executeStart(ctx);
result = ctx.statement().executeUpdate();
ctx.rows(result);
listener.executeEnd(ctx);
}
finally {
consumeWarnings(ctx, listener);
}
listener.executeStart(ctx);
result = ctx.statement().executeUpdate();
ctx.rows(result);
listener.executeEnd(ctx);
rs = ctx.statement().getGeneratedKeys();
break;

View File

@ -143,6 +143,11 @@ abstract class AbstractTable<R extends Record> extends AbstractQueryPart impleme
return fields0();
}
@Override
public final R newRecord() {
return DSL.using(new DefaultConfiguration()).newRecord(this);
}
@SuppressWarnings({ "rawtypes" })
@Override
public final Row fieldsRow() {

View File

@ -40,8 +40,6 @@
*/
package org.jooq.impl;
import static org.jooq.impl.Utils.consumeWarnings;
import java.sql.Connection;
import java.sql.SQLException;
@ -99,20 +97,15 @@ class BatchMultiple implements Batch {
ctx.sql(null);
}
try {
listener.executeStart(ctx);
listener.executeStart(ctx);
int[] result = ctx.statement().executeBatch();
int[] batchRows = ctx.batchRows();
for (int i = 0; i < batchRows.length && i < result.length; i++)
batchRows[i] = result[i];
int[] result = ctx.statement().executeBatch();
int[] batchRows = ctx.batchRows();
for (int i = 0; i < batchRows.length && i < result.length; i++)
batchRows[i] = result[i];
listener.executeEnd(ctx);
return result;
}
finally {
consumeWarnings(ctx, listener);
}
listener.executeEnd(ctx);
return result;
}
// [#3427] ControlFlowSignals must not be passed on to ExecuteListners

View File

@ -42,7 +42,6 @@ package org.jooq.impl;
import static org.jooq.conf.ParamType.INLINED;
import static org.jooq.conf.SettingsTools.executeStaticStatements;
import static org.jooq.impl.Utils.consumeWarnings;
import static org.jooq.impl.Utils.dataTypes;
import static org.jooq.impl.Utils.fields;
import static org.jooq.impl.Utils.visitAll;
@ -152,20 +151,15 @@ class BatchSingle implements BatchBindStep {
ctx.statement().addBatch();
}
try {
listener.executeStart(ctx);
int[] result = ctx.statement().executeBatch();
listener.executeStart(ctx);
int[] result = ctx.statement().executeBatch();
int[] batchRows = ctx.batchRows();
for (int i = 0; i < batchRows.length && i < result.length; i++)
batchRows[i] = result[i];
int[] batchRows = ctx.batchRows();
for (int i = 0; i < batchRows.length && i < result.length; i++)
batchRows[i] = result[i];
listener.executeEnd(ctx);
return result;
}
finally {
consumeWarnings(ctx, listener);
}
listener.executeEnd(ctx);
return result;
}
// [#3427] ControlFlowSignals must not be passed on to ExecuteListners

View File

@ -43,17 +43,25 @@ package org.jooq.impl;
import static java.util.Arrays.asList;
import static org.jooq.Clause.CREATE_TABLE;
import static org.jooq.Clause.CREATE_TABLE_AS;
import static org.jooq.Clause.CREATE_TABLE_COLUMNS;
import static org.jooq.Clause.CREATE_TABLE_NAME;
// ...
// ...
// ...
import static org.jooq.impl.DSL.fieldByName;
import static org.jooq.impl.Utils.DATA_SELECT_INTO_TABLE;
import java.util.ArrayList;
import java.util.List;
import org.jooq.Clause;
import org.jooq.Configuration;
import org.jooq.Context;
import org.jooq.CreateTableAsStep;
import org.jooq.CreateTableColumnStep;
import org.jooq.CreateTableFinalStep;
import org.jooq.DataType;
import org.jooq.Field;
import org.jooq.Record;
import org.jooq.Select;
import org.jooq.Table;
@ -65,20 +73,24 @@ class CreateTableImpl<R extends Record> extends AbstractQuery implements
// Cascading interface implementations for CREATE TABLE behaviour
CreateTableAsStep<R>,
CreateTableFinalStep {
CreateTableColumnStep {
/**
* Generated UID
*/
private static final long serialVersionUID = 8904572826501186329L;
private static final long serialVersionUID = 8904572826501186329L;
private final Table<?> table;
private Select<?> select;
private final Table<?> table;
private Select<?> select;
private final List<Field<?>> columnFields;
private final List<DataType<?>> columnTypes;
CreateTableImpl(Configuration configuration, Table<?> table) {
super(configuration);
this.table = table;
this.columnFields = new ArrayList<Field<?>>();
this.columnTypes = new ArrayList<DataType<?>>();
}
// ------------------------------------------------------------------------
@ -91,24 +103,69 @@ class CreateTableImpl<R extends Record> extends AbstractQuery implements
return this;
}
@Override
public final <T> CreateTableColumnStep column(Field<T> field, DataType<T> type) {
columnFields.add(field);
columnTypes.add(type);
return this;
}
@Override
public final CreateTableColumnStep column(String field, DataType<?> type) {
columnFields.add(fieldByName(type, field));
columnTypes.add(type);
return this;
}
// ------------------------------------------------------------------------
// XXX: QueryPart API
// ------------------------------------------------------------------------
@Override
public final void accept(Context<?> ctx) {
/* [pro] xx
xx xxxxxxxxxxxxxxx xxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx x
xxxxxxxxxxxxxxxxxxxxxx
x
xxxx
xx [/pro] */
{
acceptNative(ctx);
if (select != null) {
/* [pro] xx
xx xxxxxxxxxxxxxxx xxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx x
xxxxxxxxxxxxxxxxxxxxxx
x
xxxx
xx [/pro] */
{
acceptCreateTableAsSelect(ctx);
}
}
else {
ctx.start(CREATE_TABLE)
.start(CREATE_TABLE_NAME)
.keyword("create table")
.sql(" ")
.visit(table)
.end(CREATE_TABLE_NAME)
.start(CREATE_TABLE_COLUMNS)
.sql("(")
.formatIndentStart()
.formatNewLine();
for (int i = 0; i < columnFields.size(); i++) {
ctx.visit(columnFields.get(i))
.sql(" ")
.sql(columnTypes.get(i).getCastTypeName(ctx.configuration()));
if (i < columnFields.size() - 1)
ctx.sql(",").formatSeparator();
}
ctx.formatIndentEnd()
.formatNewLine()
.sql(")")
.end(CREATE_TABLE_COLUMNS)
.end(CREATE_TABLE);
}
}
private final void acceptNative(Context<?> ctx) {
private final void acceptCreateTableAsSelect(Context<?> ctx) {
ctx.start(CREATE_TABLE)
.start(CREATE_TABLE_NAME)
.keyword("create table")

View File

@ -2241,6 +2241,21 @@ public class DefaultDSLContext extends AbstractScope implements DSLContext, Seri
return selectCount().from(table).where(condition).fetchOne(0, int.class);
}
@Override
public boolean fetchExists(Select<?> query) throws DataAccessException {
return selectOne().whereExists(query).fetchOne() != null;
}
@Override
public boolean fetchExists(Table<?> table) throws DataAccessException {
return fetchExists(table, trueCondition());
}
@Override
public boolean fetchExists(Table<?> table, Condition condition) throws DataAccessException {
return fetchExists(selectOne().from(table).where(condition));
}
@Override
public int execute(Query query) {
final Configuration previous = Utils.getConfiguration(query);

View File

@ -672,10 +672,10 @@ class DefaultRenderContext extends AbstractContext<RenderContext> implements Ren
JooqLogger l = JooqLogger.getLogger(Constants.class);
String message;
message = "Thank you for using jOOQ";
message = "Thank you for using jOOQ " + Constants.FULL_VERSION;
/* [pro] xx
xxxxxxx x xxxxxx xxx xxx xxxxx xxx xx xxx xxxx xxxx xxxxx xxxxxxxxx
xxxxxxx x xxxxxx xxx xxx xxxxx xxx xx xxx xxxx xxxx x x xxxxxxxxxxxxxxxxxxxxxx x x xxxxx xxxxxxxxx
xx [/pro] */

View File

@ -0,0 +1,76 @@
/**
* Copyright (c) 2009-2014, Data Geekery GmbH (http://www.datageekery.com)
* All rights reserved.
*
* This work is dual-licensed
* - under the Apache Software License 2.0 (the "ASL")
* - under the jOOQ License and Maintenance Agreement (the "jOOQ License")
* =============================================================================
* You may choose which license applies to you:
*
* - If you're using this work with Open Source databases, you may choose
* either ASL or jOOQ License.
* - If you're using this work with at least one commercial database, you must
* choose jOOQ License
*
* For more information, please visit http://www.jooq.org/licenses
*
* Apache Software License 2.0:
* -----------------------------------------------------------------------------
* 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.
*
* jOOQ License and Maintenance Agreement:
* -----------------------------------------------------------------------------
* Data Geekery grants the Customer the non-exclusive, timely limited and
* non-transferable license to install and use the Software under the terms of
* the jOOQ License and Maintenance Agreement.
*
* This library is distributed with a LIMITED WARRANTY. See the jOOQ License
* and Maintenance Agreement for more details: http://www.jooq.org/licensing
*/
package org.jooq.impl;
import java.io.Serializable;
import org.jooq.Field;
import org.jooq.Record;
/**
* @author Lukas Eder
*/
class Intern implements Serializable {
/**
* Generated UID
*/
private static final long serialVersionUID = 6455756912567274014L;
// Some temp variables for String interning
int[] internIndexes;
Field<?>[] internFields;
String[] internNames;
final int[] internIndexes(Field<?>[] fields) {
if (internIndexes != null) {
return internIndexes;
}
else if (internFields != null) {
return new Fields<Record>(fields).indexesOf(internFields);
}
else if (internNames != null) {
return new Fields<Record>(fields).indexesOf(internNames);
}
return null;
}
}

View File

@ -123,6 +123,11 @@ public class UDTImpl<R extends UDTRecord<R>> extends AbstractQueryPart implement
throw new UnsupportedOperationException();
}
@Override
public final R newRecord() {
return DSL.using(new DefaultConfiguration()).newRecord(this);
}
@Override
public final DataType<R> getDataType() {
if (type == null) {

View File

@ -75,6 +75,7 @@ import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
@ -1569,10 +1570,13 @@ final class Utils {
JDBCUtils.safeClose(ctx.resultSet());
ctx.resultSet(null);
PreparedStatement statement = ctx.statement();
if (statement != null) {
consumeWarnings(ctx, listener);
}
// [#385] Close statements only if not requested to keep open
if (!keepStatement) {
PreparedStatement statement = ctx.statement();
if (statement != null) {
JDBCUtils.safeClose(statement);
ctx.statement(null);
@ -2266,17 +2270,54 @@ final class Utils {
/**
* [#3076] Consume warnings from a {@link Statement} and notify listeners.
*/
static final void consumeWarnings(ExecuteContext ctx, ExecuteListener listener) throws SQLException {
static final void consumeWarnings(ExecuteContext ctx, ExecuteListener listener) {
// [#3558] In some databases (e.g. MySQL), the call to PreparedStatement.getWarnings() issues
// a separate SHOW WARNINGS query. Users may want to avoid this query, explicitly
if (!Boolean.FALSE.equals(ctx.settings().isFetchWarnings()))
ctx.sqlWarning(ctx.statement().getWarnings());
if (!Boolean.FALSE.equals(ctx.settings().isFetchWarnings())) {
try {
ctx.sqlWarning(ctx.statement().getWarnings());
}
// [#3741] In MySQL, calling SHOW WARNINGS on open streaming result sets can cause issues.
// while this has been resolved, we should expect the above call to cause other issues, too
catch (SQLException e) {
ctx.sqlWarning(new SQLWarning("Could not fetch SQLWarning", e));
}
}
if (ctx.sqlWarning() != null)
listener.warning(ctx);
}
/**
* [#3681] Consume all {@link ResultSet}s from a JDBC {@link Statement}.
*/
static void consumeResultSets(ExecuteContext ctx, ExecuteListener listener, List<Result<Record>> results, Intern intern) throws SQLException {
boolean anyResults = false;
while (ctx.resultSet() != null) {
anyResults = true;
Field<?>[] fields = new MetaDataFieldProvider(ctx.configuration(), ctx.resultSet().getMetaData()).getFields();
Cursor<Record> c = new CursorImpl<Record>(ctx, listener, fields, intern != null ? intern.internIndexes(fields) : null, true, false);
results.add(c.fetch());
if (ctx.statement().getMoreResults()) {
ctx.resultSet(ctx.statement().getResultSet());
}
else {
ctx.resultSet(null);
}
}
// Call this only when there was at least one ResultSet.
// Otherwise, this call is not supported by ojdbc...
if (anyResults) {
ctx.statement().getMoreResults(Statement.CLOSE_ALL_RESULTS);
}
}
static List<String[]> parseTXT(String string, String nullLiteral) {
String[] strings = string.split("[\\r\\n]+");

View File

@ -305,7 +305,8 @@ public final class Convert {
* <ul>
* <li><code>null</code> is always converted to <code>null</code>,
* regardless of the target type.</li>
* <li>Identity conversion is always possible</li>
* <li>Identity conversion (converting a value to its own type) is always
* possible.</li>
* <li>All types can be converted to <code>String</code></li>
* <li>All types can be converted to <code>Object</code></li>
* <li>All <code>Number</code> types can be converted to other
@ -315,6 +316,7 @@ public final class Convert {
* <code>true</code>:
* <ul>
* <li><code>1</code></li>
* <li><code>1.0</code></li>
* <li><code>y</code></li>
* <li><code>yes</code></li>
* <li><code>true</code></li>
@ -325,6 +327,7 @@ public final class Convert {
* Possible (case-insensitive) values for <code>false</code>:
* <ul>
* <li><code>0</code></li>
* <li><code>0.0</code></li>
* <li><code>n</code></li>
* <li><code>no</code></li>
* <li><code>false</code></li>
@ -336,6 +339,10 @@ public final class Convert {
* <li>All <code>Date</code> types can be converted into each other</li>
* <li>All <code>String</code> types can be converted into {@link URI},
* {@link URL} and {@link File}</li>
* <li>Primitive target types behave like their wrapper types, except that
* <code>null</code> is converted into the initialisation value (e.g.
* <code>0</code> for <code>int</code>, <code>false</code> for
* <code>boolean</code>)</li>
* <li><code>byte[]</code> can be converted into <code>String</code>, using
* the platform's default charset</li>
* <li><code>Object[]</code> can be converted into any other array type, if