use of org.pentaho.commons.connection.IPentahoMetaData in project pentaho-platform by pentaho.
the class SqlMetadataQueryExec method executeQuery.
public IPentahoResultSet executeQuery(Query queryObject) {
// need to get the correct DatabaseMeta
SqlPhysicalModel sqlModel = (SqlPhysicalModel) queryObject.getLogicalModel().getPhysicalModel();
DatabaseMeta databaseMeta = ThinModelConverter.convertToLegacy(sqlModel.getId(), sqlModel.getDatasource());
// this connection needs closed
boolean closeConnection = true;
DatabaseMeta activeDatabaseMeta = getActiveDatabaseMeta(databaseMeta);
SQLConnection sqlConnection = getConnection(activeDatabaseMeta);
String sql = null;
try {
if ((sqlConnection == null) || !sqlConnection.initialized()) {
// $NON-NLS-1$
logger.error(Messages.getInstance().getErrorString("SQLBaseComponent.ERROR_0007_NO_CONNECTION"));
// TODO: throw an exception up the stack.
return null;
}
// Fix for PDB-1753
for (Parameter param : queryObject.getParameters()) {
String pName = param.getName();
if (parameters.containsKey(pName) && parameters.get(pName) != null && !parameters.get(pName).getClass().isArray()) {
parameters.put(pName, this.convertParameterValue(param, parameters.get(pName)));
}
}
MappedQuery mappedQuery = null;
try {
SqlGenerator sqlGenerator = createSqlGenerator();
mappedQuery = sqlGenerator.generateSql(queryObject, LocaleHelper.getLocale().toString(), getMetadataDomainRepository(), activeDatabaseMeta, parameters, true);
} catch (Exception e) {
throw new RuntimeException(e.getLocalizedMessage(), e);
}
Integer timeout = getTimeout();
if (timeout != null && timeout >= 0) {
sqlConnection.setQueryTimeout(timeout);
}
Integer maxRows = getMaxRows();
if (maxRows != null && maxRows >= 0) {
sqlConnection.setMaxRows(maxRows);
}
Boolean readOnly = isReadOnly();
if (readOnly != null && readOnly.booleanValue()) {
sqlConnection.setReadOnly(true);
}
IPentahoResultSet localResultSet = null;
sql = mappedQuery.getQuery();
if (logger.isDebugEnabled()) {
// $NON-NLS-1$
logger.debug("SQL: " + sql);
}
if (getDoQueryLog()) {
// $NON-NLS-1$
logger.info("SQL: " + sql);
}
// populate prepared sql params
List<Object> sqlParams = null;
if (mappedQuery.getParamList() != null) {
sqlParams = new ArrayList<Object>();
for (String param : mappedQuery.getParamList()) {
Object sqlParam = parameters.get(param);
// lets see if the parameter is a multi valued param
if (sqlParam instanceof Object[]) {
Object[] multivaluedParamValues = (Object[]) sqlParam;
for (Object p : multivaluedParamValues) {
sqlParams.add(p);
}
if (multivaluedParamValues.length == 0) {
sqlParams.add("");
}
} else {
sqlParams.add(sqlParam);
}
}
}
try {
if (!isForwardOnly()) {
if (sqlParams != null) {
localResultSet = sqlConnection.prepareAndExecuteQuery(sql, sqlParams);
} else {
localResultSet = sqlConnection.executeQuery(sql);
}
} else {
if (sqlParams != null) {
localResultSet = sqlConnection.prepareAndExecuteQuery(sql, sqlParams, SQLConnection.RESULTSET_FORWARDONLY, SQLConnection.CONCUR_READONLY);
} else {
localResultSet = sqlConnection.executeQuery(sql, SQLConnection.RESULTSET_FORWARDONLY, SQLConnection.CONCUR_READONLY);
}
}
IPentahoMetaData metadata = mappedQuery.generateMetadata(localResultSet.getMetaData());
((SQLResultSet) localResultSet).setMetaData(metadata);
closeConnection = false;
} catch (Exception e) {
logger.error(Messages.getInstance().getErrorString("SqlMetadataQueryExec.ERROR_0002_ERROR_EXECUTING_QUERY", e.getLocalizedMessage(), // $NON-NLS-1$
sql));
// $NON-NLS-1$
logger.debug("error", e);
return null;
}
return localResultSet;
} finally {
if (closeConnection && sqlConnection != null) {
sqlConnection.close();
}
}
}
use of org.pentaho.commons.connection.IPentahoMetaData in project pentaho-platform by pentaho.
the class SelectionMapper method create.
/**
* Creates a SelectionMapper based on an IPentahoResultSet. The index of the column to use for the values and
* display names are passed in. The index is 1 based so the first (left most) column is 1.
*
* @param resultSet
* The result set to get the data from
* @param valueColName
* The index of the column to use for the values.
* @param dispColName
* The index of the column to use for the display names. If 0 then the valueColumn will be used.
* @param displayName
* The name used to describe the choice for this selection. Usually used as a header
* @return SelectionMapper if successful or null
*/
public static SelectionMapper create(final IPentahoResultSet resultSet, int valueColIndex, int dispColIndex, final String displayName, final String displayStyle) {
--valueColIndex;
--dispColIndex;
if ((resultSet == null) || (valueColIndex < 0)) {
return (null);
}
IPentahoMetaData metaData = resultSet.getMetaData();
if ((metaData == null) || (metaData.getColumnCount() < valueColIndex) || (metaData.getColumnCount() < dispColIndex)) {
return (null);
}
ArrayList<Object> values = new ArrayList<Object>();
HashMap<Object, Object> displayNames = (dispColIndex < 0) ? null : new HashMap<Object, Object>();
Object[] row = resultSet.next();
Object value, name;
while (row != null) {
value = row[valueColIndex];
if (value != null) {
value = value.toString();
values.add(value);
if (displayNames != null) {
name = row[dispColIndex];
displayNames.put(value, (name != null) ? name.toString() : value);
}
}
row = resultSet.next();
}
// close the result set so we can loop through it again later if we need to
resultSet.close();
return (new SelectionMapper(values, displayNames, displayName, displayStyle));
}
use of org.pentaho.commons.connection.IPentahoMetaData in project pentaho-platform by pentaho.
the class TemplateUtilTest method testKeyedTableTemplate.
public void testKeyedTableTemplate() {
IRuntimeContext mockRuntimeContext = mock(IRuntimeContext.class);
IPentahoSession mockSession = mock(IPentahoSession.class);
IParameterManager mockParameterManager = mock(IParameterManager.class);
IPentahoResultSet mockPentahoResultSet = createMockResultSet();
IPentahoMetaData mockPentahoMetaData = mock(IPentahoMetaData.class);
final Set inputNames = new HashSet<Object>(Arrays.asList(new String[] { "param1" }));
when(mockParameterManager.getCurrentInputNames()).thenReturn(inputNames);
when(mockRuntimeContext.getSession()).thenReturn(mockSession);
when(mockRuntimeContext.getParameterManager()).thenReturn(mockParameterManager);
when(mockRuntimeContext.getInputParameterValue("param1")).thenReturn(mockPentahoResultSet);
when(mockRuntimeContext.getInputNames()).thenReturn(inputNames);
// "key_value" is parsed as "key value"
String template = "{param1:keycol:key_Value:valcol:defaultValue}";
assertEquals("field Value", TemplateUtil.applyTemplate(template, mockRuntimeContext));
}
use of org.pentaho.commons.connection.IPentahoMetaData in project pentaho-platform by pentaho.
the class DataGrid method populateRowStyle.
protected void populateRowStyle(final IPentahoResultSet results) {
gridDocument = DocumentHelper.createDocument();
gridDocument.setXMLEncoding(LocaleHelper.getSystemEncoding());
// $NON-NLS-1$
Element root = gridDocument.addElement("datagrid");
// add metadata about the headers
// $NON-NLS-1$
Element metadataNode = root.addElement("metadata");
HashMap<String, String> headerMap = new HashMap<String, String>();
IPentahoMetaData metadata = results.getMetaData();
// first process the column headers
Object[][] headers = metadata.getColumnHeaders();
addHeaderMetadata(headers, metadataNode, headerMap);
// now process the rows in the data set
// $NON-NLS-1$
Element rowsNode = root.addElement("data");
Object[] row = results.next();
while (row != null) {
// create a new node tree for every row
// $NON-NLS-1$
Element rowNode = rowsNode.addElement("row");
Element currentNode = rowNode;
String headerId;
for (int columnNo = 0; columnNo < row.length; columnNo++) {
// TODO make sure the nodes are encoded well
Object columnHeader;
for (int headerNo = 0; headerNo < headers.length; headerNo++) {
columnHeader = headers[headerNo][columnNo];
headerId = headerMap.get(columnHeader);
currentNode = currentNode.addElement(headerId);
if (headerNo < row.length) {
// $NON-NLS-1$
currentNode.addElement("value").setText(row[headerNo].toString());
}
// TODO support formatters
// currentNode.addElement( "formatted" ).setText( row[
// headerNo ].toString() );
}
}
row = results.next();
}
// System .out.println(gridDocument.asXML());
}
use of org.pentaho.commons.connection.IPentahoMetaData in project pentaho-platform by pentaho.
the class SQLDdlComponent method doQuery.
@Override
public IPentahoResultSet doQuery(final SQLConnection sqlConnection, final String query, boolean forwardOnlyResultset) throws Exception {
MemoryResultSet resultSet = null;
int n = ((SQLConnection) connection).execute(query);
Object[][] columnHeaders = new Object[1][1];
// $NON-NLS-1$
columnHeaders[0][0] = "result";
IPentahoMetaData metadata = new MemoryMetaData(columnHeaders, null);
resultSet = new MemoryResultSet(metadata);
Object[] rowObjects = new Object[1];
rowObjects[0] = new Integer(n);
resultSet.addRow(rowObjects);
return resultSet;
}
Aggregations