[#3381] Add support for CREATE TABLE AS statements

This commit is contained in:
Lukas Eder 2014-07-22 15:12:08 +02:00
parent c4cf343e09
commit 5b20df44ad
12 changed files with 414 additions and 28 deletions

View File

@ -1048,4 +1048,13 @@ public abstract class BaseTest<
if (fail)
Assert.fail("No exception was thrown");
}
public static void ignoreThrows(ThrowableRunnable runnable) {
try {
runnable.run();
}
catch (Throwable t) {
t.printStackTrace();
}
}
}

View File

@ -137,7 +137,7 @@ extends BaseTest<A, AP, B, S, B2S, BS, L, X, DATE, BOOL, D, T, U, UU, I, IPK, T7
catch (DataAccessException expected) {}
}
finally {
create().dropTable("t").execute();
ignoreThrows(() -> create().dropTable("t").execute());
}
}
@ -151,7 +151,7 @@ extends BaseTest<A, AP, B, S, B2S, BS, L, X, DATE, BOOL, D, T, U, UU, I, IPK, T7
create().createIndex("idx2").on("t", "b").execute();
}
finally {
create().dropTable("t").execute();
ignoreThrows(() -> create().dropTable("t").execute());
}
}
@ -163,7 +163,7 @@ extends BaseTest<A, AP, B, S, B2S, BS, L, X, DATE, BOOL, D, T, U, UU, I, IPK, T7
assertEquals(BigInteger.ONE, create().nextval("s"));
}
finally {
create().dropSequence("s").execute();
ignoreThrows(() -> create().dropSequence("s").execute());
}
}
@ -245,7 +245,7 @@ extends BaseTest<A, AP, B, S, B2S, BS, L, X, DATE, BOOL, D, T, U, UU, I, IPK, T7
assertEquals(asList("1", null, null, null, null, null, null), asList(create().fetchOne(tableByName("t")).intoArray()));
}
finally {
create().dropTable("t").execute();
ignoreThrows(() -> create().dropTable("t").execute());
}
}
@ -260,7 +260,7 @@ extends BaseTest<A, AP, B, S, B2S, BS, L, X, DATE, BOOL, D, T, U, UU, I, IPK, T7
assertEquals("1", create().fetchOne("select * from {0}", name("t")).getValue(0));
}
finally {
create().dropTable("t").execute();
ignoreThrows(() -> create().dropTable("t").execute());
}
}
@ -274,7 +274,7 @@ extends BaseTest<A, AP, B, S, B2S, BS, L, X, DATE, BOOL, D, T, U, UU, I, IPK, T7
assertEquals("empty", create().fetchValue("select {0} from {1}", name("b"), name("t")));
}
finally {
create().dropTable("t").execute();
ignoreThrows(() -> create().dropTable("t").execute());
}
}
@ -292,7 +292,7 @@ extends BaseTest<A, AP, B, S, B2S, BS, L, X, DATE, BOOL, D, T, U, UU, I, IPK, T7
assertEquals(asList("1"), asList(create().fetchOne(tableByName("t")).intoArray()));
}
finally {
create().dropTable("t").execute();
ignoreThrows(() -> create().dropTable("t").execute());
}
}
@ -315,18 +315,35 @@ extends BaseTest<A, AP, B, S, B2S, BS, L, X, DATE, BOOL, D, T, U, UU, I, IPK, T7
return SQLDataType.VARCHAR.length(10).getCastTypeName(create().configuration());
}
public void testSelectInto() throws Exception {
public void testCreateTableAsSelect() throws Exception {
try {
create().select(val("value").as("value")).into(tableByName("value")).execute();
Result<Record> r2 = create().selectFrom(tableByName("value")).fetch();
create().createTable("t").as(
select(val("value").as("value"))
).execute();
Result<Record> r1 = create().selectFrom(tableByName("t")).fetch();
assertEquals(1, r2.size());
assertEquals(1, r2.fields().length);
assertEquals("value", r2.field(0).getName());
assertEquals("value", r2.get(0).getValue(0));
assertEquals(1, r1.size());
assertEquals(1, r1.fields().length);
assertEquals("value", r1.field(0).getName());
assertEquals("value", r1.get(0).getValue(0));
}
finally {
create().dropTable("value").execute();
ignoreThrows(() -> create().dropTable("t").execute());
}
}
public void testSelectInto() throws Exception {
try {
create().select(val("value").as("value")).into(tableByName("t")).execute();
Result<Record> result = create().selectFrom(tableByName("t")).fetch();
assertEquals(1, result.size());
assertEquals(1, result.fields().length);
assertEquals("value", result.field(0).getName());
assertEquals("value", result.get(0).getValue(0));
}
finally {
ignoreThrows(() -> create().dropTable("t").execute());
}
}
}

View File

@ -1344,6 +1344,11 @@ public abstract class jOOQAbstractTest<
new DDLTests(this).testDropTable();
}
@Test
public void testCreateTableAsSelect() throws Exception {
new DDLTests(this).testCreateTableAsSelect();
}
@Test
public void testSelectInto() throws Exception {
new DDLTests(this).testSelectInto();

View File

@ -787,6 +787,33 @@ public enum Clause {
// Clauses that are used in an ALTER statement
// -------------------------------------------------------------------------
/**
* A complete <code>CREATE TABLE</code> statement.
*/
CREATE_TABLE,
/**
* A view name clause within a {@link #CREATE_TABLE} statement.
* <p>
* This clause surrounds
* <ul>
* <li>The table name</li>
* <li>The (optional) column names</li>
* </ul>
*/
CREATE_TABLE_NAME,
/**
* An <code>AS</code> clause within a {@link #CREATE_TABLE} statement.
* <p>
* This clause surrounds
* <ul>
* <li>The <code>AS</code> keyword</li>
* <li>The select code</li>
* </ul>
*/
CREATE_TABLE_AS,
/**
* A complete <code>CREATE VIEW</code> statement.
*/
@ -804,7 +831,7 @@ public enum Clause {
CREATE_VIEW_NAME,
/**
* An as clause within a {@link #CREATE_VIEW} statement.
* An <code>AS</code> clause within a {@link #CREATE_VIEW} statement.
* <p>
* This clause surrounds
* <ul>

View File

@ -0,0 +1,71 @@
/**
* 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;
// ...
// ...
import static org.jooq.SQLDialect.CUBRID;
// ...
import static org.jooq.SQLDialect.DERBY;
import static org.jooq.SQLDialect.H2;
import static org.jooq.SQLDialect.HSQLDB;
// ...
import static org.jooq.SQLDialect.MARIADB;
import static org.jooq.SQLDialect.MYSQL;
// ...
import static org.jooq.SQLDialect.POSTGRES;
import static org.jooq.SQLDialect.SQLITE;
// ...
// ...
/**
* A {@link Query} that can create tables.
*
* @author Lukas Eder
*/
public interface CreateTableAsStep<R extends Record> {
/**
* Add an <code>AS</code> clause to the <code>CREATE TABLE</code> statement.
*/
@Support({ CUBRID, DERBY, H2, HSQLDB, MARIADB, MYSQL, POSTGRES, SQLITE })
CreateTableFinalStep as(Select<? extends R> select);
}

View File

@ -0,0 +1,50 @@
/**
* 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 CreateTableFinalStep extends Query {
}

View File

@ -40,6 +40,7 @@
*/
package org.jooq;
// ...
// ...
import static org.jooq.SQLDialect.CUBRID;
// ...
@ -4788,6 +4789,22 @@ public interface DSLContext {
// XXX DDL Statements
// -------------------------------------------------------------------------
/**
* Create a new DSL <code>CREATE TABLE</code> statement.
*
* @see DSL#createTable(String)
*/
@Support({ CUBRID, DERBY, H2, HSQLDB, MARIADB, MYSQL, POSTGRES, SQLITE })
CreateTableAsStep<Record> createTable(String tableName);
/**
* Create a new DSL <code>CREATE TABLE</code> statement.
*
* @see DSL#createTable(Table)
*/
@Support({ CUBRID, DERBY, H2, HSQLDB, MARIADB, MYSQL, POSTGRES, SQLITE })
CreateTableAsStep<Record> createTable(Table<?> table);
/**
* Create a new DSL <code>CREATE VIEW</code> statement.
*

View File

@ -0,0 +1,138 @@
/**
* 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 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_NAME;
// ...
// ...
// ...
// ...
import static org.jooq.impl.Utils.DATA_SELECT_INTO_TABLE;
import org.jooq.Clause;
import org.jooq.Configuration;
import org.jooq.Context;
import org.jooq.CreateTableAsStep;
import org.jooq.CreateTableFinalStep;
import org.jooq.Record;
import org.jooq.Select;
import org.jooq.Table;
/**
* @author Lukas Eder
*/
class CreateTableImpl<R extends Record> extends AbstractQuery implements
// Cascading interface implementations for CREATE TABLE behaviour
CreateTableAsStep<R>,
CreateTableFinalStep {
/**
* Generated UID
*/
private static final long serialVersionUID = 8904572826501186329L;
private final Table<?> table;
private Select<?> select;
CreateTableImpl(Configuration configuration, Table<?> table) {
super(configuration);
this.table = table;
}
// ------------------------------------------------------------------------
// XXX: DSL API
// ------------------------------------------------------------------------
@Override
public final CreateTableFinalStep as(Select<? extends R> s) {
this.select = s;
return this;
}
// ------------------------------------------------------------------------
// XXX: QueryPart API
// ------------------------------------------------------------------------
@Override
public final void accept(Context<?> ctx) {
/* [pro] xx
xx xxxxxxxxxxxxxxx xxxx xxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx x
xxxxxxxxxxxxxxxxxxxxxx
x
xxxx
xx [/pro] */
{
acceptNative(ctx);
}
}
private final void acceptNative(Context<?> ctx) {
ctx.start(CREATE_TABLE)
.start(CREATE_TABLE_NAME)
.keyword("create table")
.sql(" ")
.visit(table)
.end(CREATE_TABLE_NAME)
.formatSeparator()
.keyword("as")
.formatSeparator()
.start(CREATE_TABLE_AS)
.visit(select)
.end(CREATE_TABLE_AS)
.end(CREATE_TABLE);
}
private final void acceptSelectInto(Context<?> ctx) {
ctx.data(DATA_SELECT_INTO_TABLE, table);
ctx.visit(select);
ctx.data().remove(DATA_SELECT_INTO_TABLE);
}
@Override
public final Clause[] clauses(Context<?> ctx) {
return null;
}
}

View File

@ -91,6 +91,7 @@ import org.jooq.Configuration;
import org.jooq.ConnectionProvider;
import org.jooq.CreateIndexStep;
import org.jooq.CreateSequenceFinalStep;
import org.jooq.CreateTableAsStep;
import org.jooq.CreateViewAsStep;
import org.jooq.DSLContext;
import org.jooq.DataType;
@ -4207,6 +4208,26 @@ public class DSL {
// XXX DDL Statements
// -------------------------------------------------------------------------
/**
* Create a new DSL <code>CREATE TABLE</code> statement.
*
* @see DSLContext#createTable(String)
*/
@Support({ CUBRID, DERBY, H2, HSQLDB, MARIADB, MYSQL, POSTGRES, SQLITE })
public static CreateTableAsStep<Record> createTable(String tableName) {
return createTable(tableByName(tableName));
}
/**
* Create a new DSL <code>CREATE TABLE</code> statement.
*
* @see DSLContext#createTable(Table)
*/
@Support({ CUBRID, DERBY, H2, HSQLDB, MARIADB, MYSQL, POSTGRES, SQLITE })
public static CreateTableAsStep<Record> createTable(Table<?> table) {
return using(new DefaultConfiguration()).createTable(table);
}
/**
* Create a new DSL <code>CREATE VIEW</code> statement.
*

View File

@ -84,6 +84,7 @@ import org.jooq.Configuration;
import org.jooq.ConnectionProvider;
import org.jooq.CreateIndexStep;
import org.jooq.CreateSequenceFinalStep;
import org.jooq.CreateTableAsStep;
import org.jooq.CreateViewAsStep;
import org.jooq.Cursor;
import org.jooq.DSLContext;
@ -1613,8 +1614,18 @@ public class DefaultDSLContext implements DSLContext, Serializable {
// -------------------------------------------------------------------------
@Override
public CreateViewAsStep<Record> createView(String viewName, String... columnNames) {
return new CreateViewImpl<Record>(configuration, viewName, columnNames);
public CreateViewAsStep<Record> createView(String viewName, String... fieldNames) {
return new CreateViewImpl<Record>(configuration, viewName, fieldNames);
}
@Override
public CreateTableAsStep<Record> createTable(String tableName) {
return createTable(tableByName(tableName));
}
@Override
public CreateTableAsStep<Record> createTable(Table<?> table) {
return new CreateTableImpl<Record>(configuration, table);
}
@Override

View File

@ -81,8 +81,10 @@ import static org.jooq.impl.DSL.orderBy;
import static org.jooq.impl.DSL.row;
import static org.jooq.impl.Dual.DUAL_ACCESS;
import static org.jooq.impl.Utils.DATA_LOCALLY_SCOPED_DATA_MAP;
import static org.jooq.impl.Utils.DATA_OMIT_INTO_CLAUSE;
import static org.jooq.impl.Utils.DATA_RENDERING_DB2_FINAL_TABLE_CLAUSE;
import static org.jooq.impl.Utils.DATA_ROW_VALUE_EXPRESSION_PREDICATE_SUBQUERY;
import static org.jooq.impl.Utils.DATA_SELECT_INTO_TABLE;
import static org.jooq.impl.Utils.DATA_WINDOW_DEFINITIONS;
import static org.jooq.impl.Utils.DATA_WRAP_DERIVED_TABLES_IN_PARENTHESES;
@ -200,15 +202,16 @@ class SelectQueryImpl<R extends Record> extends AbstractSelect<R> implements Sel
@Override
public final void accept(Context<?> context) {
if (into != null
&& context.data(DATA_OMIT_INTO_CLAUSE) == null
&& asList(CUBRID, DERBY, FIREBIRD, H2, MARIADB, MYSQL, POSTGRES, SQLITE).contains(context.configuration().dialect().family())) {
// [#3381] TODO: Delegate to a jOOQ CREATE TABLE AS statement
if (into != null && asList(CUBRID, DERBY, FIREBIRD, H2, MARIADB, MYSQL, POSTGRES, SQLITE).contains(context.configuration().dialect().family()))
context.keyword("create table")
.sql(" ")
.visit(into)
.formatSeparator()
.keyword("as")
.formatSeparator();
context.data(DATA_OMIT_INTO_CLAUSE, true);
context.visit(DSL.createTable(into).as(this));
context.data().remove(DATA_OMIT_INTO_CLAUSE);
return;
}
if (with != null)
context.visit(with).formatSeparator();
@ -649,11 +652,18 @@ class SelectQueryImpl<R extends Record> extends AbstractSelect<R> implements Sel
// ------------
context.start(SELECT_INTO);
if (into != null && asList(HSQLDB, POSTGRES).contains(dialect.family())) {
Table<?> actualInto = (Table<?>) context.data(DATA_SELECT_INTO_TABLE);
if (actualInto == null)
actualInto = into;
if (actualInto != null
&& context.data(DATA_OMIT_INTO_CLAUSE) == null
&& asList(HSQLDB, POSTGRES).contains(dialect.family())) {
context.formatSeparator()
.keyword("into")
.sql(" ")
.visit(into);
.visit(actualInto);
}
context.end(SELECT_INTO);

View File

@ -273,6 +273,16 @@ final class Utils {
*/
static final String DATA_DEFAULT_TRANSACTION_PROVIDER_CONNECTION = "org.jooq.configuration.default-transaction-provider-connection-provider";
/**
* [#3381] The table to be used for the {@link Clause#SELECT_INTO} clause.
*/
static final String DATA_SELECT_INTO_TABLE = "org.jooq.configuration.select-into-table";
/**
* [#3381] Omit the {@link Clause#SELECT_INTO}, as it is being emulated.
*/
static final String DATA_OMIT_INTO_CLAUSE = "org.jooq.configuration.omit-into-clause";
/**
* [#2965] These are {@link ConcurrentHashMap}s containing caches for
* reflection information.