} // createTempFile() public static string getTempDir() { string result = ""; FileStream fs = null; // String tmpDirPath = System.getProperty("java.io.tmpdir"); string tmp_file_path = Path.GetTempPath(); if (tmp_file_path != null && !"".Equals(tmp_file_path)) { fs = File.Open(tmp_file_path, FileMode.Create); } else { logger.debug("Could not determine tmpdir by using environment variable."); try { // https://www.tutorialspoint.com/java/io/file_createtempfile_directory.htm //File.createTempFile("foo", "bar"); tmp_file_path = ".foo.bar"; fs = File.Open(tmp_file_path, FileMode.Create); DirectoryInfo di = Directory.GetParent(tmp_file_path); string tmp_file_full_path = di.FullName + "\\" + tmp_file_path; result = tmp_file_full_path; try { File.Delete(tmp_file_full_path); } catch (Exception e) { logger.warn("Could not delete temp file '{}'", tmp_file_full_path); } } catch (IOException e) { logger.error("Could not create tempFile in order to find temporary dir", e); try { DirectoryInfo di = Directory.CreateDirectory("metamodel.tmp.dir"); } catch (Exception e2) { throw new InvalidOperationException("Could not create directory for temporary files: " + e2.Message); } //result.deleteOnExit(); fs.Dispose(); } } if (logger.isInfoEnabled()) { logger.info("Using '{0}' as tmpdir.", result); } return(result); } // getTempDir()
// @SuppressWarnings("unchecked") public int compare(object o1, object o2) { logger.debug("compare({},{})", o1, o2); if (o1 == null && o2 == null) { return(0); } if (o1 == null) { return(-1); } if (o2 == null) { return(1); } if (o1 is NNumber && o1 is NNumber) { return(NumberComparator.getComparator().Compare(o1, o2)); } if (TimeComparator.isTimeBased(o1) && TimeComparator.isTimeBased(o2)) { return(TimeComparator.getComparator().Compare(o1, o2)); } if (BooleanComparator.isBoolean(o1) && BooleanComparator.isBoolean(o2)) { return(BooleanComparator.getComparator().Compare(o1, o2)); } if (o1 is IComparable && o2 is IComparable) { //@SuppressWarnings("rawtypes") IComparable c1 = (IComparable)o1; //@SuppressWarnings("rawtypes") IComparable c2 = (IComparable)o2; // We can only count on using the comparable interface if o1 and o2 // are within of the same class or if one is a subclass of the other if (c1.GetType().IsAssignableFrom(c2.GetType())) { return(c1.CompareTo(o2)); } if (o2.GetType().IsAssignableFrom(c1.GetType())) { return(-1 * c2.CompareTo(o1)); } } logger.debug("Using ToStringComparator because no apparent better comparison method could be found"); return(ToStringComparator.getComparator().Compare(o1, o2)); } // compare()
} // materializeMainSchemaTable() private DocumentSource createDocumentSource() { Debug.WriteLine("JsonDataContext.createDocumentSource()"); NInputStream input_stream = _resource.read(); try { // MappingJsonFactory jsonFactory = new MappingJsonFactory(); NJsonParser parser = new NJsonParser(input_stream); // jsonFactory.createParser(inputStream); logger.debug("Created JSON parser for resource: {0}", _resource); return(new JsonDocumentSource(parser, _resource.getName())); } catch (Exception e) { Debug.WriteLine("Unexpected error while creating JSON parser \n " + e.Message); try { Debug.WriteLine("Trying to close input_stream"); FileHelper.safeClose(input_stream); } catch (Exception e1) { throw new MetaModelException("Tried to close input_stream\n " + e1.Message); } throw new MetaModelException("... Unexpected error while creating JSON parser \n " + e.Message); } } // createDocumentSource()
/** * {@inheritDoc} */ public int hashCode() { logger.debug("{}.hashCode()", this); int hash_code = -1; NList<object> list = new NList<object>(); decorateIdentity(list); if (NEnumerableUtils.IsEmpty<object>(list)) { list.Add(ToString()); } hash_code -= list.Count; foreach (object obj in list) { hash_code += hashCode(obj); } return hash_code; }
public EqualsBuilder append(bool b) { logger.debug("append({})", b); if (_equals) { _equals = b; } return(this); }
/** * Factory method to create relations between two tables by specifying which * columns from the tables that enforce the relationship. * * @param primaryColumns * the columns from the primary key table * @param foreignColumns * the columns from the foreign key table * @return the relation created */ public static Relationship createRelationship(List <Column> primaryColumns, List <Column> foreignColumns) { Table primaryTable = checkSameTable(primaryColumns); Table foreignTable = checkSameTable(foreignColumns); MutableRelationship relation = new MutableRelationship(primaryColumns, foreignColumns); if (primaryTable is MutableTable) { try { ((MutableTable)primaryTable).addRelationship(relation); } catch (NUnsupportedOperationException e) { // this is an allowed behaviour - not all tables need to support // this method. logger.debug( "primary table ({}) threw exception when adding relationship", primaryTable); } // Ticket #144: Some tables have relations with them selves and then // the // relationship should only be added once. if (foreignTable != primaryTable && foreignTable is MutableTable) { try { ((MutableTable)foreignTable).addRelationship(relation); } catch (NUnsupportedOperationException e) { // this is an allowed behaviour - not all tables need to // support this method. logger.debug( "foreign table ({}) threw exception when adding relationship", foreignTable); } } } return(relation); }
/** * @return the name that this SelectItem can be referenced with, if * referenced from a super-query. This will usually be the alias, * but if there is no alias, then the column name will be used. * * @param includeQuotes * indicates whether or not the output should include quotes, if * the select item's column has quotes associated (typically * true, but false if used for presentation) */ public string getSuperQueryAlias(bool includeQuotes) { if (_alias != null) { return(_alias); } else if (_column != null) { StringBuilder sb = new StringBuilder(); if (_function != null) { if (_functionApproximationAllowed) { sb.Append(FUNCTION_APPROXIMATION_PREFIX); } sb.Append(_function.getFunctionName()); sb.Append('('); } if (includeQuotes) { sb.Append(_column.getQuotedName()); } else { sb.Append(_column.getName()); } if (_function != null) { sb.Append(')'); } return(sb.ToString()); } else { logger.debug("Could not resolve a reasonable super-query alias for SelectItem: {0}", toSql()); return(toStringNoAlias().ToString()); } } // getSuperQueryAlias()
} // getTableCount() // @Override public virtual Table getTableByName(String tableName) { if (tableName == null) { return(null); } List <string> found_table_names = new List <string>(1); List <Table> foundTables = new List <Table>(1); // Search for table matches, case insensitive. foreach (Table table in getTables(false)) { if (tableName.Equals(table.getName(), StringComparison.CurrentCultureIgnoreCase)) { foundTables.Add(table); found_table_names.Add(table.getName()); } } int numTables = foundTables.Count; if (logger.isDebugEnabled()) { logger.debug("Found {0} tables(s) matching '{1}': {2}", numTables, tableName, found_table_names); } if (numTables == 0) { return(null); } else if (numTables == 1) { return(foundTables[0]); } // If more matches are found, search case sensitive foreach (Table table in foundTables) { if (tableName.Equals(table.getName())) { return(table); } } // if none matches case sensitive, pick the first one. return(foundTables[0]); } // getTableByName()
} // constructor // @Override public void parse(String delim, String itemToken) { FromItem fromItem; int parenthesisStart = itemToken.IndexOf('('); if (parenthesisStart != -1) { if (parenthesisStart != 0) { throw new QueryParserException("Not capable of parsing FROM token: " + itemToken + ". Expected parenthesis to start at first character."); } int parenthesisEnd = itemToken.IndexOf(')', parenthesisStart); if (parenthesisEnd == -1) { throw new QueryParserException("Not capable of parsing FROM token: " + itemToken + ". Expected end parenthesis."); } String subQueryString = itemToken.Substring(parenthesisStart + 1, parenthesisEnd); logger.debug("Parsing sub-query: {0}", subQueryString); Query subQuery = new QueryParser(_dataContext, subQueryString).parse(); fromItem = new FromItem(subQuery); string alias = itemToken.Substring(parenthesisEnd + 1).Trim(); if (!alias.IsEmpty()) { fromItem.setAlias(alias); } } else if (itemToken.ToUpper().IndexOf(" JOIN ") != -1) { fromItem = parseAllJoinItems(itemToken); } else { fromItem = parseTableItem(itemToken); } _query.from(fromItem); } // parse()
} // next() // @Override public override Row getRow() { Row sourceRow = _dataSet.getRow(); Object[] values = new Object[_converters.Length]; for (int i = 0; i < values.Length; i++) { Object value = sourceRow.getValue(i); // @SuppressWarnings("unchecked") TypeConverter <object, object> converter = (TypeConverter <object, object>)_converters[i]; if (converter != null) { Object virtualValue = converter.toVirtualValue(value); logger.debug("Converted physical value {} to {}", value, virtualValue); value = virtualValue; } values[i] = value; } return(new DefaultRow(getHeader(), values)); } // getRow()
} // constructor public DataSet executeQuery(Query query) { List <SelectItem> selectItems = query.getSelectClause().getItems(); List <FromItem> fromItems = query.getFromClause().getItems(); List <FilterItem> whereItems = query.getWhereClause().getItems(); List <SelectItem> whereSelectItems = query.getWhereClause().getEvaluatedSelectItems(); List <GroupByItem> groupByItems = query.getGroupByClause().getItems(); List <SelectItem> groupBySelectItems = query.getGroupByClause().getEvaluatedSelectItems(); List <SelectItem> havingSelectItems = query.getHavingClause().getEvaluatedSelectItems(); List <SelectItem> orderBySelectItems = query.getOrderByClause().getEvaluatedSelectItems(); List <FilterItem> havingItems = query.getHavingClause().getItems(); List <OrderByItem> orderByItems = query.getOrderByClause().getItems(); int firstRow = (query.getFirstRow() == null ? 1 : query.getFirstRow()); int maxRows = (query.getMaxRows() == null ? -1 : query.getMaxRows()); if (maxRows == 0) { // no rows requested - no reason to do anything return(new EmptyDataSet(selectItems)); } // check certain common query types that can often be optimized by // subclasses bool singleFromItem = fromItems.Count == 1; bool noGrouping = groupByItems.IsEmpty() && havingItems.IsEmpty(); if (singleFromItem && noGrouping) { FromItem fromItem = query.getFromClause().getItem(0); Table table = fromItem.getTable(); if (table != null) { // check for SELECT COUNT(*) queries if (selectItems.Count == 1) { SelectItem selectItem = query.getSelectClause().getItem(0); if (SelectItem.isCountAllItem(selectItem)) { bool functionApproximationAllowed = selectItem.isFunctionApproximationAllowed(); if (isMainSchemaTable(table)) { logger.debug("Query is a COUNT query with {} where items. Trying executeCountQuery(...)", whereItems.Count); NNumber count = executeCountQuery(table, whereItems, functionApproximationAllowed); if (count == null) { logger.debug( "DataContext did not return any count query results. Proceeding with manual counting."); } else { List <Row> data = new List <Row>(1); DataSetHeader header = new SimpleDataSetHeader(new SelectItem[] { selectItem }); data.Add(new DefaultRow(header, new Object[] { count })); return(new InMemoryDataSet(header, data)); } } } } bool is_simple_select = isSimpleSelect(query.getSelectClause()); if (is_simple_select) { // check for lookup query by primary key if (whereItems.Count == 1) { FilterItem whereItem = whereItems[0]; SelectItem selectItem = whereItem.getSelectItem(); if (!whereItem.isCompoundFilter() && selectItem != null && selectItem.getColumn() != null) { Column column = selectItem.getColumn(); if (column.isPrimaryKey() && OperatorType.EQUALS_TO.Equals(whereItem.getOperator())) { logger.debug( "Query is a primary key lookup query. Trying executePrimaryKeyLookupQuery(...)"); if (table != null) { if (isMainSchemaTable(table)) { Object operand = whereItem.getOperand(); Row row = executePrimaryKeyLookupQuery(table, selectItems, column, operand); if (row == null) { logger.debug( "DataContext did not return any GET query results. Proceeding with manual lookup."); } else { DataSetHeader header = new SimpleDataSetHeader(selectItems); return(new InMemoryDataSet(header, row)); } } } } } } // check for simple queries with or without simple criteria if (orderByItems.IsEmpty()) { DataSet ds = null; // no WHERE criteria set if (whereItems.IsEmpty()) { ds = materializeTable(table, selectItems, firstRow, maxRows); return(ds); } ds = materializeTable(table, selectItems, whereItems, firstRow, maxRows); return(ds); } } } } // Creates a list for all select items that are needed to execute query // (some may only be used as part of a filter, but not shown in result) List <SelectItem> workSelectItems = CollectionUtils.concat(true, selectItems, whereSelectItems, groupBySelectItems, havingSelectItems, orderBySelectItems); // Materialize the tables in the from clause DataSet[] fromDataSets = new DataSet[fromItems.Count]; for (int i = 0; i < fromDataSets.Length; i++) { FromItem fromItem = fromItems[i]; fromDataSets[i] = materializeFromItem(fromItem, workSelectItems); } // Execute the query using the raw data DataSet dataSet = null; // MetaModelHelper.getCarthesianProduct(fromDataSets, whereItems); // we can now exclude the select items imposed by the WHERE clause (and // should, to make the aggregation process faster) workSelectItems = CollectionUtils.concat(true, selectItems, groupBySelectItems, havingSelectItems, orderBySelectItems); if (groupByItems.Count > 0) { dataSet = MetaModelHelper.getGrouped(workSelectItems, dataSet, groupByItems); } else { dataSet = MetaModelHelper.getAggregated(workSelectItems, dataSet); } dataSet = MetaModelHelper.getFiltered(dataSet, havingItems); if (query.getSelectClause().isDistinct()) { dataSet = MetaModelHelper.getSelection(selectItems, dataSet); dataSet = MetaModelHelper.getDistinct(dataSet); dataSet = MetaModelHelper.getOrdered(dataSet, orderByItems); } else { dataSet = MetaModelHelper.getOrdered(dataSet, orderByItems); dataSet = MetaModelHelper.getSelection(selectItems, dataSet); } dataSet = MetaModelHelper.getPaged(dataSet, firstRow, maxRows); return(dataSet); } // executeQuery()
} // getColumnNames() // @Override public bool equals(object obj) { if (obj == null) { return(false); } if (obj == this) { return(true); } if (obj is Table) { Table other = (Table)obj; if (!getQualifiedLabel().Equals(other.getQualifiedLabel())) { return(false); } if (GetType() != other.GetType()) { return(false); } Schema sch1 = getSchema(); Schema sch2 = other.getSchema(); if (sch1 != null) { if (!sch1.Equals(sch2)) { return(false); } } else { if (sch2 != null) { return(false); } } try { String[] columnNames1 = getColumnNames(); String[] columnNames2 = other.getColumnNames(); if (columnNames1 != null && columnNames1.Length != 0) { if (columnNames2 != null && columnNames2.Length != 0) { if (!columnNames1.Equals(columnNames2)) { return(false); } } } } catch (Exception e) { // going "down stream" may throw exceptions, e.g. due to // de-serialization issues. We will be tolerant to such // exceptions logger.debug("Caught (and ignoring) exception while comparing column names of tables", e); } return(true); } return(false); } // equals()
// @Override public Column findColumn(String columnName) // throws IllegalArgumentException { if (columnName == null) { throw new ArgumentException("columnName cannot be null"); } List <FromItem> fromItems = _query.getFromClause().getItems(); List <SelectItem> selectItems = _query.getSelectClause().getItems(); Column column = null; int dotIndex = columnName.IndexOf('.'); if (dotIndex != -1) { // check aliases of from items String aliasPart = columnName.Substring(0, dotIndex); String columnPart = columnName.Substring(dotIndex + 1); foreach (FromItem fromItem in fromItems) { column = null; column = findColumnInAliasedTable(column, fromItem, aliasPart, columnPart); if (column != null) { return(column); } } } // check columns already in select clause foreach (SelectItem item in selectItems) { column = item.getColumn(); if (column != null) { if (columnName.Equals(column.getName())) { return(column); } } } foreach (FromItem fromItem in fromItems) { Table table = fromItem.getTable(); if (table != null) { column = table.getColumnByName(columnName); if (column != null) { return(column); } } } column = _dataContext.getColumnByQualifiedLabel(columnName); if (column != null) { return(column); } ArgumentException exception = new ArgumentException("Could not find column: " + columnName); if (logger.isDebugEnabled()) { logger.debug("findColumn('" + columnName + "') could not resolve a column", exception); foreach (FromItem fromItem in fromItems) { Table table = fromItem.getTable(); if (table != null) { logger.debug("Table available in FROM item: {}. Column names: {}", table, NArrays.ArrayAsString(table.getColumnNames())); } } } throw exception; }