Search in sources :

Example 56 with ExecutionContext

use of org.teiid.translator.ExecutionContext in project teiid by teiid.

the class TestODataIntegration method testErrorCodes.

@Test
public void testErrorCodes() throws Exception {
    HardCodedExecutionFactory hc = new HardCodedExecutionFactory() {

        @Override
        public ResultSetExecution createResultSetExecution(final QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connection) throws TranslatorException {
            List<? extends List<?>> list = getData(command);
            if (list == null) {
                throw new RuntimeException(command.toString());
            }
            final Iterator<? extends List<?>> result = list.iterator();
            return new ResultSetExecution() {

                @Override
                public void execute() throws TranslatorException {
                    throw new TranslatorException(ODataPlugin.Event.TEIID16001, "execution failed");
                }

                @Override
                public void close() {
                }

                @Override
                public void cancel() throws TranslatorException {
                }

                @Override
                public List<?> next() throws TranslatorException, DataNotAvailableException {
                    if (result.hasNext()) {
                        return result.next();
                    }
                    return null;
                }
            };
        }
    };
    hc.addData("SELECT x.a, x.b FROM x", Arrays.asList(Arrays.asList("a", 1)));
    teiid.addTranslator("x1", hc);
    try {
        ModelMetaData mmd = new ModelMetaData();
        mmd.setName("m");
        mmd.addSourceMetadata("ddl", "create foreign table x (a string, b integer, primary key (a));");
        mmd.addSourceMapping("x1", "x1", null);
        teiid.deployVDB("northwind", mmd);
        localClient = getClient(teiid.getDriver(), "northwind", new Properties());
        ContentResponse response = http.newRequest(baseURL + "/northwind/m/x").method("GET").send();
        assertEquals(400, response.getStatus());
        assertEquals("{\"error\":{\"code\":\"TEIID30504\"," + "\"message\":\"TEIID30504 x1: TEIID16001 execution failed\"}}", response.getContentAsString());
        response = http.newRequest(baseURL + "/northwind/m/x?$format=xml").method("GET").send();
        assertEquals(400, response.getStatus());
        assertEquals("<?xml version='1.0' encoding='UTF-8'?>" + "<error xmlns=\"http://docs.oasis-open.org/odata/ns/metadata\">" + "<code>TEIID30504</code>" + "<message>TEIID30504 x1: TEIID16001 execution failed</message>" + "</error>", response.getContentAsString());
    } finally {
        localClient = null;
        teiid.undeployVDB("northwind");
    }
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) RuntimeMetadata(org.teiid.metadata.RuntimeMetadata) Properties(java.util.Properties) ModelMetaData(org.teiid.adminapi.impl.ModelMetaData) ResultSetExecution(org.teiid.translator.ResultSetExecution) ExecutionContext(org.teiid.translator.ExecutionContext) TeiidRuntimeException(org.teiid.core.TeiidRuntimeException) HardCodedExecutionFactory(org.teiid.runtime.HardCodedExecutionFactory) TranslatorException(org.teiid.translator.TranslatorException) QueryExpression(org.teiid.language.QueryExpression) Test(org.junit.Test)

Example 57 with ExecutionContext

use of org.teiid.translator.ExecutionContext in project teiid by teiid.

the class TestEmbeddedServer method testQueryTimeout.

@Test
public void testQueryTimeout() throws Exception {
    es.start(new EmbeddedConfiguration());
    es.addTranslator("foo", new ExecutionFactory() {

        @Override
        public boolean isSourceRequired() {
            return false;
        }

        @Override
        public ResultSetExecution createResultSetExecution(QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connection) throws TranslatorException {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
            }
            return super.createResultSetExecution(command, executionContext, metadata, connection);
        }
    });
    es.deployVDB(new ByteArrayInputStream("<vdb name=\"test\" version=\"1\"><model name=\"test\"><source name=\"foo\" translator-name=\"foo\"/><metadata type=\"DDL\"><![CDATA[CREATE foreign table x (y xml);]]> </metadata></model></vdb>".getBytes()));
    Connection c = es.getDriver().connect("jdbc:teiid:test", null);
    Statement s = c.createStatement();
    s.setQueryTimeout(1);
    try {
        s.execute("select * from x");
        fail();
    } catch (SQLException e) {
        assertEquals(SQLStates.QUERY_CANCELED, e.getSQLState());
    }
}
Also used : TeiidSQLException(org.teiid.jdbc.TeiidSQLException) ExecutionFactory(org.teiid.translator.ExecutionFactory) RuntimeMetadata(org.teiid.metadata.RuntimeMetadata) ResultSetExecution(org.teiid.translator.ResultSetExecution) ExecutionContext(org.teiid.translator.ExecutionContext) ByteArrayInputStream(java.io.ByteArrayInputStream) TranslatorException(org.teiid.translator.TranslatorException) QueryExpression(org.teiid.language.QueryExpression) Test(org.junit.Test)

Example 58 with ExecutionContext

use of org.teiid.translator.ExecutionContext in project teiid by teiid.

the class TestEmbeddedServer method testSourceLobUnderTxn.

@Test
public void testSourceLobUnderTxn() throws Exception {
    EmbeddedConfiguration ec = new EmbeddedConfiguration();
    ec.setMaxResultSetCacheStaleness(0);
    MockTransactionManager tm = new MockTransactionManager();
    ec.setTransactionManager(tm);
    ec.setUseDisk(false);
    es.start(ec);
    final AtomicBoolean closed = new AtomicBoolean();
    es.addTranslator("foo", new ExecutionFactory() {

        @Override
        public boolean isSourceRequired() {
            return false;
        }

        @Override
        public ResultSetExecution createResultSetExecution(QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connection) throws TranslatorException {
            return new ResultSetExecution() {

                private boolean returned;

                @Override
                public void execute() throws TranslatorException {
                }

                @Override
                public void close() {
                    closed.set(true);
                }

                @Override
                public void cancel() throws TranslatorException {
                }

                @Override
                public List<?> next() throws TranslatorException, DataNotAvailableException {
                    if (returned) {
                        return null;
                    }
                    returned = true;
                    ArrayList<Object> result = new ArrayList<Object>(1);
                    result.add(new SQLXMLImpl(new InputStreamFactory() {

                        @Override
                        public InputStream getInputStream() throws IOException {
                            // need to make it of a sufficient size to not be inlined
                            return new ByteArrayInputStream(new byte[DataTypeManager.MAX_LOB_MEMORY_BYTES + 1]);
                        }
                    }));
                    return result;
                }
            };
        }
    });
    es.deployVDB(new ByteArrayInputStream("<vdb name=\"test\" version=\"1\"><model name=\"test\"><source name=\"foo\" translator-name=\"foo\"/><metadata type=\"DDL\"><![CDATA[CREATE foreign table x (y xml);]]> </metadata></model></vdb>".getBytes()));
    Connection c = es.getDriver().connect("jdbc:teiid:test", null);
    c.setAutoCommit(false);
    Statement s = c.createStatement();
    ResultSet rs = s.executeQuery("select * from x");
    rs.next();
    assertFalse(closed.get());
    s.close();
    assertTrue(closed.get());
}
Also used : SQLXMLImpl(org.teiid.core.types.SQLXMLImpl) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) ExecutionFactory(org.teiid.translator.ExecutionFactory) IOException(java.io.IOException) RuntimeMetadata(org.teiid.metadata.RuntimeMetadata) InputStreamFactory(org.teiid.core.types.InputStreamFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ResultSetExecution(org.teiid.translator.ResultSetExecution) ExecutionContext(org.teiid.translator.ExecutionContext) ByteArrayInputStream(java.io.ByteArrayInputStream) TranslatorException(org.teiid.translator.TranslatorException) List(java.util.List) ArrayList(java.util.ArrayList) DataNotAvailableException(org.teiid.translator.DataNotAvailableException) QueryExpression(org.teiid.language.QueryExpression) Test(org.junit.Test)

Example 59 with ExecutionContext

use of org.teiid.translator.ExecutionContext in project teiid by teiid.

the class TestEmbeddedServer method testDynamicUpdate.

@Test
public void testDynamicUpdate() throws Exception {
    EmbeddedConfiguration ec = new EmbeddedConfiguration();
    MockTransactionManager tm = new MockTransactionManager();
    ec.setTransactionManager(tm);
    ec.setUseDisk(false);
    es.start(ec);
    es.addTranslator("t", new ExecutionFactory<Void, Void>() {

        @Override
        public boolean supportsCompareCriteriaEquals() {
            return true;
        }

        @Override
        public boolean isSourceRequired() {
            return false;
        }

        @Override
        public UpdateExecution createUpdateExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata, Void connection) throws TranslatorException {
            Collection<Literal> values = CollectorVisitor.collectObjects(Literal.class, command);
            assertEquals(2, values.size());
            for (Literal literal : values) {
                assertFalse(literal.getValue() instanceof Reference);
            }
            return new UpdateExecution() {

                @Override
                public void execute() throws TranslatorException {
                }

                @Override
                public void close() {
                }

                @Override
                public void cancel() throws TranslatorException {
                }

                @Override
                public int[] getUpdateCounts() throws DataNotAvailableException, TranslatorException {
                    return new int[] { 1 };
                }
            };
        }
    });
    ModelMetaData mmd1 = new ModelMetaData();
    mmd1.setName("accounts");
    mmd1.setSchemaSourceType("ddl");
    mmd1.setSchemaText(ObjectConverterUtil.convertFileToString(UnitTestUtil.getTestDataFile("dynamic_update.sql")));
    mmd1.addSourceMapping("y", "t", null);
    es.deployVDB("vdb", mmd1);
    Connection c = es.getDriver().connect("jdbc:teiid:vdb", null);
    PreparedStatement ps = c.prepareStatement("update hello1 set SchemaName=? where Name=?");
    ps.setString(1, "test1223");
    ps.setString(2, "Columns");
    assertEquals(1, ps.executeUpdate());
}
Also used : Reference(org.teiid.query.sql.symbol.Reference) UpdateExecution(org.teiid.translator.UpdateExecution) RuntimeMetadata(org.teiid.metadata.RuntimeMetadata) ModelMetaData(org.teiid.adminapi.impl.ModelMetaData) ExecutionContext(org.teiid.translator.ExecutionContext) Command(org.teiid.language.Command) Literal(org.teiid.language.Literal) Collection(java.util.Collection) TranslatorException(org.teiid.translator.TranslatorException) DataNotAvailableException(org.teiid.translator.DataNotAvailableException) Test(org.junit.Test)

Example 60 with ExecutionContext

use of org.teiid.translator.ExecutionContext in project teiid by teiid.

the class TestEmbeddedServer method testExternalMaterializationManagement.

@Test
public void testExternalMaterializationManagement() throws Exception {
    EmbeddedConfiguration ec = new EmbeddedConfiguration();
    ec.setUseDisk(false);
    ec.setTransactionManager(SimpleMock.createSimpleMock(TransactionManager.class));
    es.transactionService.setXaTerminator(SimpleMock.createSimpleMock(XATerminator.class));
    es.transactionService.setWorkManager(new FakeWorkManager());
    es.start(ec);
    es.transactionService.setDetectTransactions(false);
    final AtomicBoolean loaded = new AtomicBoolean();
    final AtomicBoolean valid = new AtomicBoolean();
    final AtomicInteger matTableCount = new AtomicInteger();
    final AtomicInteger tableCount = new AtomicInteger();
    final AtomicBoolean hasStatus = new AtomicBoolean();
    es.addTranslator("y", new ExecutionFactory<AtomicInteger, Object>() {

        public boolean supportsCompareCriteriaEquals() {
            return true;
        }

        @Override
        public Object getConnection(AtomicInteger factory) throws TranslatorException {
            return factory.incrementAndGet();
        }

        @Override
        public void closeConnection(Object connection, AtomicInteger factory) {
        }

        @Override
        public void getMetadata(MetadataFactory metadataFactory, Object conn) throws TranslatorException {
            assertEquals(conn, Integer.valueOf(1));
            Table t = metadataFactory.addTable("my_table");
            t.setSupportsUpdate(true);
            Column c = metadataFactory.addColumn("my_column", TypeFacility.RUNTIME_NAMES.STRING, t);
            c.setUpdatable(true);
            // mat table
            t = metadataFactory.addTable("mat_table");
            t.setSupportsUpdate(true);
            c = metadataFactory.addColumn("my_column", TypeFacility.RUNTIME_NAMES.STRING, t);
            c.setUpdatable(true);
            // status table
            t = metadataFactory.addTable("status");
            t.setSupportsUpdate(true);
            c = metadataFactory.addColumn("VDBName", TypeFacility.RUNTIME_NAMES.STRING, t);
            c.setUpdatable(true);
            c = metadataFactory.addColumn("VDBVersion", TypeFacility.RUNTIME_NAMES.STRING, t);
            c.setUpdatable(true);
            c = metadataFactory.addColumn("SchemaName", TypeFacility.RUNTIME_NAMES.STRING, t);
            c.setUpdatable(true);
            c = metadataFactory.addColumn("Name", TypeFacility.RUNTIME_NAMES.STRING, t);
            c.setUpdatable(true);
            c = metadataFactory.addColumn("TargetSchemaName", TypeFacility.RUNTIME_NAMES.STRING, t);
            c.setUpdatable(true);
            c = metadataFactory.addColumn("TargetName", TypeFacility.RUNTIME_NAMES.STRING, t);
            c.setUpdatable(true);
            c = metadataFactory.addColumn("Valid", TypeFacility.RUNTIME_NAMES.BOOLEAN, t);
            c.setUpdatable(true);
            c = metadataFactory.addColumn("LoadState", TypeFacility.RUNTIME_NAMES.STRING, t);
            c.setUpdatable(true);
            c = metadataFactory.addColumn("Cardinality", TypeFacility.RUNTIME_NAMES.LONG, t);
            c.setUpdatable(true);
            c = metadataFactory.addColumn("Updated", TypeFacility.RUNTIME_NAMES.TIMESTAMP, t);
            c.setUpdatable(true);
            c = metadataFactory.addColumn("LoadNumber", TypeFacility.RUNTIME_NAMES.LONG, t);
            c.setUpdatable(true);
            c = metadataFactory.addColumn("NodeName", TypeFacility.RUNTIME_NAMES.STRING, t);
            c.setUpdatable(true);
            c = metadataFactory.addColumn("StaleCount", TypeFacility.RUNTIME_NAMES.LONG, t);
            c.setUpdatable(true);
            metadataFactory.addPrimaryKey("PK", Arrays.asList("VDBName", "VDBVersion", "SchemaName", "Name"), t);
        }

        @Override
        public ResultSetExecution createResultSetExecution(final QueryExpression command, final ExecutionContext executionContext, final RuntimeMetadata metadata, final Object connection) throws TranslatorException {
            return new ResultSetExecution() {

                Iterator<? extends List<? extends Object>> results;

                @Override
                public void execute() throws TranslatorException {
                }

                @Override
                public void close() {
                }

                @Override
                public void cancel() throws TranslatorException {
                }

                @Override
                public List<?> next() throws TranslatorException, DataNotAvailableException {
                    String status = "SELECT status.TargetSchemaName, status.TargetName, status.Valid, " + "status.LoadState, status.Updated, status.Cardinality, status.LoadNumber " + "FROM status WHERE status.VDBName = 'test' AND status.VDBVersion = '1.0.0' " + "AND status.SchemaName = 'virt' AND status.Name = 'my_view'";
                    if (results == null) {
                        String commandString = command.toString();
                        if (hasStatus.get() && commandString.equals(status)) {
                            results = Arrays.asList(Arrays.asList(null, "mat_table", valid.get(), loaded.get() ? "LOADED" : "LOADING", new Timestamp(System.currentTimeMillis()), -1, new Integer(1))).iterator();
                        } else if (hasStatus.get() && commandString.startsWith("SELECT status.Valid, status.LoadState FROM status")) {
                            results = Arrays.asList(Arrays.asList(valid.get(), loaded.get() ? "LOADED" : "LOADING")).iterator();
                        } else if (loaded.get() && commandString.equals("SELECT mat_table.my_column FROM mat_table")) {
                            matTableCount.getAndIncrement();
                            results = Arrays.asList(Arrays.asList("mat_column0"), Arrays.asList("mat_column1")).iterator();
                        } else if (commandString.equals("SELECT my_table.my_column FROM my_table")) {
                            tableCount.getAndIncrement();
                            results = Arrays.asList(Arrays.asList("regular_column")).iterator();
                        }
                    }
                    if (results != null && results.hasNext()) {
                        return results.next();
                    }
                    return null;
                }
            };
        }

        @Override
        public UpdateExecution createUpdateExecution(final Command command, final ExecutionContext executionContext, final RuntimeMetadata metadata, final Object connection) throws TranslatorException {
            UpdateExecution ue = new UpdateExecution() {

                @Override
                public void execute() throws TranslatorException {
                    String commandString = command.toString();
                    if (commandString.startsWith("INSERT INTO status")) {
                        hasStatus.set(true);
                    }
                    if (commandString.startsWith("INSERT INTO status") || commandString.startsWith("UPDATE status SET")) {
                        if (commandString.contains("LoadState")) {
                            synchronized (loaded) {
                                loaded.set(commandString.indexOf("LOADED") != -1);
                                loaded.notifyAll();
                            }
                        }
                        if (commandString.contains("Valid")) {
                            valid.set(commandString.indexOf("TRUE") != -1);
                        }
                    }
                }

                @Override
                public void close() {
                }

                @Override
                public void cancel() throws TranslatorException {
                }

                @Override
                public int[] getUpdateCounts() throws DataNotAvailableException, TranslatorException {
                    return new int[] { 1 };
                }
            };
            return ue;
        }
    });
    final AtomicInteger counter = new AtomicInteger();
    ConnectionFactoryProvider<AtomicInteger> cfp = new EmbeddedServer.SimpleConnectionFactoryProvider<AtomicInteger>(counter);
    es.addConnectionFactoryProvider("z", cfp);
    ModelMetaData mmd = new ModelMetaData();
    mmd.setName("my_schema");
    mmd.addSourceMapping("x", "y", "z");
    ModelMetaData mmd1 = new ModelMetaData();
    mmd1.setName("virt");
    mmd1.setModelType(Type.VIRTUAL);
    mmd1.setSchemaSourceType("ddl");
    mmd1.setSchemaText("	create view my_view OPTIONS (" + "UPDATABLE 'true',MATERIALIZED 'TRUE',\n" + "MATERIALIZED_TABLE 'my_schema.mat_table', \n" + "\"teiid_rel:MATERIALIZED_STAGE_TABLE\" 'my_schema.mat_table',\n" + "\"teiid_rel:ALLOW_MATVIEW_MANAGEMENT\" 'true', \n" + "\"teiid_rel:MATVIEW_STATUS_TABLE\" 'my_schema.status', \n" + "\"teiid_rel:MATVIEW_AFTER_LOAD_SCRIPT\" 'select 1; select 1, ''a''', \n" + "\"teiid_rel:MATVIEW_SHARE_SCOPE\" 'NONE',\n" + "\"teiid_rel:MATVIEW_ONERROR_ACTION\" 'THROW_EXCEPTION',\n" + "\"teiid_rel:MATVIEW_TTL\" 100000)" + "as select * from \"my_table\";" + " create view mat_table as select 'I conflict';");
    es.deployVDB("test", mmd, mmd1);
    synchronized (loaded) {
        while (!loaded.get()) {
            loaded.wait();
        }
    }
    // need to ensure that the mat view is built
    Thread.sleep(2000);
    final TeiidDriver td = es.getDriver();
    Connection c = td.connect("jdbc:teiid:test", null);
    Statement s = c.createStatement();
    ResultSet rs = s.executeQuery("select * from my_view");
    assertTrue(rs.next());
    assertEquals("mat_column0", rs.getString(1));
    s.execute("update my_schema.status set valid=false");
    try {
        rs = s.executeQuery("select * from my_view");
        fail("expected throw exception to work");
    } catch (SQLException e) {
    }
    assertEquals(1, tableCount.get());
    // make sure a similar name doesn't cause an issue
    rs = s.executeQuery("select * from (call sysadmin.updateMatView('virt', 'my_view', 'true')) as x");
    rs.next();
    assertEquals(2, rs.getInt(1));
    assertEquals(2, tableCount.get());
    s.execute("call setProperty((SELECT UID FROM Sys.Tables WHERE SchemaName = 'virt' AND Name = 'my_view'), 'teiid_rel:MATVIEW_ONERROR_ACTION', 'WAIT')");
    // this thread should hang, until the status changes
    final AtomicBoolean success = new AtomicBoolean();
    Thread t = new Thread() {

        public void run() {
            try {
                Connection c1 = td.connect("jdbc:teiid:test", null);
                Statement s1 = c1.createStatement();
                s1.executeQuery("select * from my_view");
                success.set(true);
            } catch (SQLException e) {
            }
        }
    };
    t.start();
    // wait to ensure that the thread is blocked
    Thread.sleep(5000);
    // update the status and make sure the thread finished
    s.execute("update my_schema.status set valid=true");
    t.join(10000);
    assertTrue(success.get());
}
Also used : XATerminator(javax.resource.spi.XATerminator) TeiidSQLException(org.teiid.jdbc.TeiidSQLException) UpdateExecution(org.teiid.translator.UpdateExecution) RuntimeMetadata(org.teiid.metadata.RuntimeMetadata) Column(org.teiid.metadata.Column) List(java.util.List) ArrayList(java.util.ArrayList) DataNotAvailableException(org.teiid.translator.DataNotAvailableException) QueryExpression(org.teiid.language.QueryExpression) Table(org.teiid.metadata.Table) FakeWorkManager(org.teiid.common.queue.FakeWorkManager) ModelMetaData(org.teiid.adminapi.impl.ModelMetaData) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ResultSetExecution(org.teiid.translator.ResultSetExecution) ExecutionContext(org.teiid.translator.ExecutionContext) MetadataFactory(org.teiid.metadata.MetadataFactory) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Command(org.teiid.language.Command) DummyTransactionManager(org.infinispan.transaction.tm.DummyTransactionManager) TranslatorException(org.teiid.translator.TranslatorException) TeiidDriver(org.teiid.jdbc.TeiidDriver) Test(org.junit.Test)

Aggregations

ExecutionContext (org.teiid.translator.ExecutionContext)65 Test (org.junit.Test)50 Command (org.teiid.language.Command)49 RuntimeMetadata (org.teiid.metadata.RuntimeMetadata)48 TranslationUtility (org.teiid.cdk.api.TranslationUtility)32 ResultSetExecution (org.teiid.translator.ResultSetExecution)23 List (java.util.List)17 UpdateExecution (org.teiid.translator.UpdateExecution)14 TranslatorException (org.teiid.translator.TranslatorException)11 ArrayList (java.util.ArrayList)10 QueryExpression (org.teiid.language.QueryExpression)10 ByteArrayInputStream (java.io.ByteArrayInputStream)9 LdapContext (javax.naming.ldap.LdapContext)9 ExecutionFactory (org.teiid.translator.ExecutionFactory)9 SalesforceConnection (org.teiid.translator.salesforce.SalesforceConnection)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 HashMap (java.util.HashMap)6 DataSource (javax.activation.DataSource)6 ModelMetaData (org.teiid.adminapi.impl.ModelMetaData)6 WSConnection (org.teiid.translator.WSConnection)6