Пример #1
0
        // @Override
        public TableFromBuilder from(Schema schema, String tableName)
        {
            Table table = schema.getTableByName(tableName);

            if (table == null)
            {
                throw new ArgumentException("Nu such table '" + tableName + "' found in schema: " + schema
                                            + ". Available tables are: " + NArrays.ArrayAsString(schema.getTableNames(false)));
            }
            return(from(table));
        }
        } // getRelationshipCount()

        // @Override
        public IList <Relationship> getRelationships()
        {
            Table[]             tables = getTables(false);
            List <Relationship> result = new List <Relationship>();

            foreach (Table t in tables)
            {
                Relationship[] relations = t.getRelationships();
                result.AddRange(NArrays.AsList <Relationship>(relations));
            }
            //return getTables().stream()
            //        .flatMap(tab->tab.getRelationships().stream())
            //        .collect(new HashSet<Relationship>());
            return(result);
        } // getRelationships()
Пример #3
0
 // @Override
 public bool containsColumnPair(Column pkColumn, Column fkColumn)
 {
     if (pkColumn != null && fkColumn != null)
     {
         List <Column> primaryColumns = NArrays.AsList <Column>(getPrimaryColumns());
         List <Column> foreignColumns = NArrays.AsList <Column>(getForeignColumns());
         for (int i = 0; i < primaryColumns.Count; i++)
         {
             if (pkColumn.Equals(primaryColumns[i]) &&
                 fkColumn.Equals(foreignColumns[i]))
             {
                 return(true);
             }
         }
     }
     return(false);
 }
        }     // getCarthesianProduct()

        #endregion getCarthesianProduct()

        /**
         * Executes a simple nested loop join. The innerLoopDs will be copied in an
         * in-memory dataset.
         *
         */
        public static InMemoryDataSet nestedLoopJoin(DataSet innerLoopDs, DataSet outerLoopDs, IEnumerable <FilterItem> filtersIterable)
        {
            List <FilterItem> filters = new List <FilterItem>();

            foreach (FilterItem fi in filtersIterable)
            {
                filters.Add(fi);
            }
            List <Row> innerRows = innerLoopDs.toRows();

            List <SelectItem> allItems = new List <SelectItem>(NArrays.AsList <SelectItem>(outerLoopDs.getSelectItems()));

            allItems.AddRange(NArrays.AsList(innerLoopDs.getSelectItems()));

            HashSet <FilterItem> applicable_filters = applicableFilters(filters, allItems);

            DataSetHeader jointHeader = new CachingDataSetHeader(allItems);

            List <Row> resultRows = new List <Row>();

            foreach (Row outerRow in outerLoopDs)
            {
                foreach (Row innerRow in innerRows)
                {
                    Object[] joinedRowObjects = new Object[outerRow.getValues().Length + innerRow.getValues().Length];

                    Array.Copy(outerRow.getValues(), 0, joinedRowObjects, 0, outerRow.getValues().Length);
                    Array.Copy(innerRow.getValues(), 0, joinedRowObjects, outerRow.getValues().Length,
                               innerRow.getValues().Length);

                    Row joinedRow = new DefaultRow(jointHeader, joinedRowObjects);
                    IEnumerable <FilterItem> selected_items = applicable_filters.Where(fi => isJoinedRowAccepted(fi, joinedRow));

                    if (applicable_filters.IsEmpty() || (selected_items != null && selected_items.Count <FilterItem>() != 0))
                    {
                        resultRows.Add(joinedRow);
                    }
                }
            }

            return(new InMemoryDataSet(jointHeader, resultRows));
        }     // nestedLoopJoin()
        }     // getCarthesianProduct()

        public static DataSet getCarthesianProduct(DataSet[] fromDataSets, IEnumerable <FilterItem> whereItems)
        {
            Debug.Assert(fromDataSets.Length > 0);
            // First check if carthesian product is even nescesary
            if (fromDataSets.Length == 1)
            {
                return(getFiltered(fromDataSets[0], whereItems));
            }
            // do a nested loop join, no matter what
            IEnumerator <DataSet> dsIter = NArrays.AsList(fromDataSets).GetEnumerator();

            DataSet joined = dsIter.Current;

            while (dsIter.MoveNext())
            {
                joined = nestedLoopJoin(dsIter.Current, joined, (whereItems));
            }

            return(joined);
        }     // getCarthesianProduct()
Пример #6
0
        } // testUseMapValueFunctionToGetFromNestedMap()

        public void testUseDotNotationToGetFromNestedMap() // throws Exception
        {
            Resource        resource    = new FileResource("src/test/resources/nested_fields.json");
            JsonDataContext dataContext = new JsonDataContext(resource);

            Schema schema = dataContext.getDefaultSchema();

            Debug.Assert("[nested_fields.json]".Equals(NArrays.AsString(schema.getTableNames(false))));

            DataSet ds = dataContext.query().from(schema.getTable(0)).select("name.first").execute();

            try
            {
                Debug.Assert(ds.next());
                Debug.Assert("Row[values=[John]]".Equals(ds.getRow().ToString()));
                Debug.Assert(ds.next());
                Debug.Assert("Row[values=[John]]".Equals(ds.getRow().ToString()));
                Debug.Assert(!ds.next());
            }
            finally
            {
                ds.close();
            }
        } // testUseDotNotationToGetFromNestedMap()
Пример #7
0
        } // constructor

        public SimpleDataSetHeader(SelectItem[] selectItems) : this(NArrays.AsList <SelectItem>(selectItems))
        {
        } // constructor
        } // constructor

        public AbstractDataSet(SelectItem[] selectItems) : this(NArrays.AsList <SelectItem>(selectItems))
        {
            Debug.WriteLine("new AbstractDataSet(SelectItem[])");
        } // constructor
Пример #9
0
        } // constructor

        public InMemoryDataSet(DataSetHeader header, params Row[] rows) :  base(header)
        {
            _rows = NArrays.AsList(rows);
        } // constructor
Пример #10
0
 public InMemoryDataSet(params Row[] rows) : this(NArrays.AsList(rows))
 {
 } // constructor
        }     // getDistinct()

        public static Table[] getTables(Column[] columns)
        {
            return(getTables(NArrays.AsList <Column>(columns)));
        }     // getTables()
        } // filter()

        public static List <O> map <I, SuperI, O> (I[] items, NFunc <SuperI, O> func) where I : SuperI
        {
            return(map(NArrays.AsList(items), func));
        } // map()
        }     // getSelection()

        public static DataSet getSelection(SelectItem[] selectItems, DataSet dataSet)
        {
            return(getSelection(NArrays.AsList(selectItems), dataSet));
        }
        }                                                                          // getFiltered()

        public static DataSet getFiltered(DataSet dataSet, params FilterItem[] filterItems)
        {
            return(getFiltered(dataSet, NArrays.AsList(filterItems)));
        }
        }     // executeSingleRowQuery()

        /**
         * Creates a subset array of columns, where only columns that are contained
         * within the specified table are included.
         *
         * @param table
         * @param columns
         * @return an array containing the columns that exist in the table
         */
        public static Column[] getTableColumns(Table table, Column[] columns)
        {
            return(getTableColumns(table, NArrays.AsList(columns)));
        }     // getTableColumns()
        } // executePrimaryKeyLookupQuery()

        protected DataSet materializeFromItem(FromItem fromItem, List <SelectItem> selectItems)
        {
            DataSet  dataSet;
            JoinType joinType = fromItem.getJoin();

            if (fromItem.getTable() != null)
            {
                // We need to materialize a single table
                Table             table = fromItem.getTable();
                List <SelectItem> selectItemsToMaterialize = new List <SelectItem>();

                foreach (SelectItem selectItem in selectItems)
                {
                    FromItem selectedFromItem = selectItem.getFromItem();
                    if (selectedFromItem != null)
                    {
                        if (selectedFromItem.equals(fromItem))
                        {
                            selectItemsToMaterialize.Add(selectItem.replaceFunction(null));
                        }
                    }
                    else
                    {
                        // the select item does not specify a specific
                        // from-item
                        Column selectedColumn = selectItem.getColumn();
                        if (selectedColumn != null)
                        {
                            // we assume that if the table matches, we will use the
                            // column
                            if (selectedColumn.getTable() != null && selectedColumn.getTable().Equals(table))
                            {
                                selectItemsToMaterialize.Add(selectItem.replaceFunction(null));
                            }
                        }
                    }
                }

                if (logger.isDebugEnabled())
                {
                    logger.debug("calling materializeTable(" + table.getName() + "," + selectItemsToMaterialize + ",1,-1");
                }

                // Dispatching to the concrete subclass of
                // QueryPostprocessDataContextStrategy
                dataSet = materializeTable(table, selectItemsToMaterialize, 1, -1);
            }
            else if (joinType != JoinType.None)
            {
                // We need to (recursively) materialize a joined FromItem
                if (fromItem.getLeftSide() == null || fromItem.getRightSide() == null)
                {
                    throw new ArgumentException("Joined FromItem requires both left and right side: " + fromItem);
                }
                DataSet[] fromItemDataSets = new DataSet[2];

                // materialize left side
                List <SelectItem> leftOn = NArrays.AsList(fromItem.getLeftOn());
                fromItemDataSets[0] = materializeFromItem(fromItem.getLeftSide(),
                                                          CollectionUtils.concat(true, selectItems, leftOn));

                // materialize right side
                List <SelectItem> rightOn = NArrays.AsList(fromItem.getRightOn());
                fromItemDataSets[1] = materializeFromItem(fromItem.getRightSide(),
                                                          CollectionUtils.concat(true, selectItems, rightOn));

                FilterItem[] onConditions = new FilterItem[leftOn.Count];
                for (int i = 0; i < onConditions.Length; i++)
                {
                    FilterItem whereItem = new FilterItem(leftOn[i], OperatorType.EQUALS_TO, rightOn[i]);
                    onConditions[i] = whereItem;
                }

                switch (joinType)
                {
                case JoinType.INNER:
                    dataSet = MetaModelHelper.getCarthesianProduct(fromItemDataSets, onConditions);
                    break;

                case JoinType.LEFT:
                    dataSet = MetaModelHelper.getLeftJoin(fromItemDataSets[0], fromItemDataSets[1], onConditions);
                    break;

                case JoinType.RIGHT:
                    dataSet = MetaModelHelper.getRightJoin(fromItemDataSets[0], fromItemDataSets[1], onConditions);
                    break;

                default:
                    throw new ArgumentException("FromItem type not supported: " + fromItem);
                }
            }
            else if (fromItem.getSubQuery() != null)
            {
                // We need to (recursively) materialize a subquery
                dataSet = executeQuery(fromItem.getSubQuery());
            }
            else
            {
                throw new ArgumentException("FromItem type not supported: " + fromItem);
            }
            if (dataSet == null)
            {
                throw new ArgumentException("FromItem was not succesfully materialized: " + fromItem);
            }
            return(dataSet);
        } // materializeFromItem()
Пример #17
0
        } // constructor

        public CachingDataSetHeader(SelectItem[] items) : this(NArrays.AsList(items))
        {
        } // constructor
 public static List <E> filter <E, SuperE> (E[] items, Predicate <SuperE> predicate) where E : SuperE
 {
     return(filter(NArrays.AsList(items), predicate));
 } // filter()
        // @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;
        }
        } // map()

        // https://stackoverflow.com/questions/36449343/what-is-the-c-sharp-equivalent-of-java-8-java-util-function-consumer
        public static void forEach <E> (E[] items, NConsumer <E> action)
        {
            forEach(NArrays.AsList(items), action);
        } // forEach()
Пример #21
0
        } // constructor

        /**
         * Constructs a row from an array of SelectItems and an array of
         * corresponding values
         *
         * @param items
         *            the array of SelectItems
         * @param values
         *            the array of values
         * @param styles
         *            an optional array of styles
         * @deprecated use {@link #DefaultRow(DataSetHeader, Object[])} or
         *             {@link #DefaultRow(DataSetHeader, Object[], Style[])}
         *             instead.
         */
        // @Deprecated
        public DefaultRow(SelectItem[] items, Object[] values, Style[] styles) : this(NArrays.AsList(items), values, styles)
        {
        } // constructor