public string BuildCleanUpQuery(SchemaNode generatorNode, NodeConfiguration nodeConfiguration)
        {
            var table  = (Table)generatorNode;
            var delete = SqlDml.Delete(SqlDml.TableRef(table));

            return(Compile(delete, nodeConfiguration).GetCommandText());
        }
Exemple #2
0
    public IEnumerable <ITreeNode> GetChildren(bool refresh)
    {
        ITreeNode[] treeNodes;

        try
        {
            var restrictions = new object[] { Name };
            var dataTable    = Connection.GetOleDbSchemaTable(OleDbSchemaGuid.Schemata, restrictions);
            var count        = dataTable.Rows.Count;
            var nameColumn   = dataTable.Columns["SCHEMA_NAME"];
            treeNodes = new ITreeNode[count];

            for (var i = 0; i < count; i++)
            {
                var schemaName = (string)dataTable.Rows[i][nameColumn];
                treeNodes[i] = new SchemaNode(this, schemaName);
            }
        }
        catch
        {
            treeNodes    = new ITreeNode[1];
            treeNodes[0] = new SchemaNode(this, null);
        }

        return(treeNodes);
    }
Exemple #3
0
        private void ComputeColumnMetadata(IDataReader dataReader, IEnumerable <SelectNode> selectNodes, Dictionary <int, SelectNode> tempMap)
        {
            SchemaNode currentEntity = null;

            for (int i = 0; i < dataReader.FieldCount; i++)
            {
                var(_alias, _name) = splitColumnName(dataReader.GetName(i));
                var m = selectNodes.FirstOrDefault(x => x.EntityField.CodeName == _name && x.Alias == _alias);

                if (m.OwnerEntity != currentEntity)
                {
                    if (!(currentEntity is null))
                    {
                        this.ObjectRanges[currentEntity].End = i - 1;
                    }
                    this.ObjectRanges.Add(m.OwnerEntity, new IndexRange()
                    {
                        Start = i
                    });
                    currentEntity = m.OwnerEntity;
                }
                else if (i == dataReader.FieldCount - 1)
                {
                    this.ObjectRanges[currentEntity].End = i;
                }

                if (m.EntityField.IsPrimary)
                {
                    this.IdentityIndexes.Add(m.FullPath.OwnerEntityPath, m.FullPath);
                }

                ColumnMap.Add(m.FullPath, i);
                tempMap.Add(i, m);
            }
        }
        public SequenceQuery BuildNextValueQuery(SchemaNode generatorNode, NodeConfiguration nodeConfiguration, long increment, bool forcedSameSessionExecution)
        {
            var actualCompartment = forcedSameSessionExecution
        ? SequenceQueryCompartment.SameSession
        : compartment;

            var sqlNext = hasSequences
        ? GetSequenceBasedNextImplementation(generatorNode, increment)
        : GetTableBasedNextImplementation(generatorNode);

            var requiresSeparateSession = !hasSequences;
            var batch = sqlNext as SqlBatch;

            if (batch == null || hasBatches)
            {
                // There are batches or there is single statement, so we can run this as a single request
                return(new SequenceQuery(Compile(sqlNext, nodeConfiguration).GetCommandText(), actualCompartment));
            }

            // No batches, so we must execute this manually
            if (!storesAutoIncrementSettingsInMemory)
            {
                return(new SequenceQuery(
                           Compile((ISqlCompileUnit)batch[0], nodeConfiguration).GetCommandText(),
                           Compile((ISqlCompileUnit)batch[1], nodeConfiguration).GetCommandText(),
                           actualCompartment));
            }
            return(new SequenceQuery(
                       Compile((ISqlCompileUnit)batch[0], nodeConfiguration).GetCommandText(),
                       Compile((ISqlCompileUnit)batch[1], nodeConfiguration).GetCommandText(),
                       Compile((ISqlCompileUnit)batch[2], nodeConfiguration).GetCommandText(),
                       actualCompartment));
        }
        private ISqlCompileUnit GetTableBasedNextImplementation(SchemaNode generatorNode)
        {
            var table = (Table)generatorNode;

            var idColumn = GetColumn(table, WellKnown.GeneratorColumnName);

            var tableRef = SqlDml.TableRef(table);
            var insert   = SqlDml.Insert(tableRef);
            var delete   = SqlDml.Delete(tableRef);

            if (!hasInsertDefaultValues)
            {
                var fakeColumn = GetColumn(table, WellKnown.GeneratorFakeColumnName);
                insert.Values[tableRef[fakeColumn.Name]] = SqlDml.Null;
            }

            var result = SqlDml.Batch();

            if (storesAutoIncrementSettingsInMemory)
            {
                result.Add(delete);
            }
            result.Add(insert);
            result.Add(SqlDml.Select(SqlDml.LastAutoGeneratedId()));
            return(result);
        }
        private static void DoUpdate(Table table, TypedDataSource source, SchemaNode tableSchema, RowLimitClause rowLimitClause)
        {
            table.Partitions[0].Name  = tableSchema.Name;
            table.Partitions[0].Query = tableSchema.GetSql(true, source.UseThreePartName);
            table.Partitions[0].SetAnnotation("TabularEditor_TableSchema", tableSchema.ToJson());

            var schemaTable    = source.GetSchemaTable(tableSchema);
            var updatedColumns = new HashSet <TOMWrapper.DataColumn>();

            foreach (DataRow row in schemaTable.Rows)
            {
                var sourceColumn = row["ColumnName"].ToString();
                var dataTypeName =
                    schemaTable.Columns.Contains("DataTypeName") ?
                    row["DataTypeName"].ToString() :
                    (row["DataType"] as Type).Name;
                var column = table.DataColumns.FirstOrDefault(c => c.SourceColumn.EqualsI(sourceColumn));
                if (column == null)
                {
                    column = table.AddDataColumn(sourceColumn, sourceColumn);
                }
                column.DataType           = TableMetadata.DataTypeMap(dataTypeName);
                column.SourceProviderType = dataTypeName;

                updatedColumns.Add(column);
            }
            foreach (var col in table.DataColumns.Except(updatedColumns).ToList())
            {
                col.Delete();
            }
        }
Exemple #7
0
 protected VisitResult VisitLiteral(LiteralOperation operation)
 {
     return(new VisitResult
     {
         ResultSchema = SchemaNode.GetSchemaNodeForValue(operation.Value),
         Expression = Expression.Constant(operation.Value),
     });
 }
Exemple #8
0
 public TableNode(
     SchemaNode schema,
     string name,
     bool showFullName)
 {
     _schema       = schema;
     _name         = name;
     _showFullName = showFullName;
 }
Exemple #9
0
        protected VisitResult VisitUnary(Func <Expression, Expression> factoryMethod, UnaryOperation operation)
        {
            var operand = Visit(operation.Operand);

            return(new VisitResult
            {
                ResultSchema = SchemaNode.GetSchemaNodeForUnaryOperation(operation, operand.ResultSchema),
                Expression = factoryMethod(operand.Expression),
            });
        }
Exemple #10
0
        protected VisitResult VisitBinary(Func <Expression, Expression, Expression> factoryMethod, BinaryOperation operation)
        {
            var leftOperand  = Visit(operation.LeftOperand);
            var rightOperand = Visit(operation.RightOperand);

            return(new VisitResult
            {
                ResultSchema = SchemaNode.GetSchemaNodeForBinaryOperation(operation, leftOperand.ResultSchema, rightOperand.ResultSchema),
                Expression = factoryMethod(leftOperand.Expression, rightOperand.Expression),
            });
        }
Exemple #11
0
 private void SetDepth(SchemaNode node, SchemaNode parent)
 {
     if (parent == null)
     {
         node.Depth = 0;
     }
     else
     {
         node.Depth = parent.Depth + 1;
     }
 }
 public override string Translate(SqlCompilerContext context, SchemaNode node)
 {
     //temporary tables need no schema qualifier
     if (!(node is TemporaryTable) && node.Schema != null)
     {
         return(context == null
   ? QuoteIdentifier(new[] { node.Schema.Name, node.Name })
   : QuoteIdentifier(new[] { context.SqlNodeActualizer.Actualize(node.Schema), node.Name }));
     }
     return(QuoteIdentifier(new[] { node.Name }));
 }
Exemple #13
0
 //Set Numbering
 private void SetNumbering(SchemaNode mRootNode)
 {
     for (var i = 0; i < ((ComplexNode)mRootNode).mChildList.Count; i++)
     {
         var targetNode = ((ComplexNode)mRootNode)[i];
         targetNode.Numbering = (mRootNode.Numbering + "." + (i + 1)).TrimStart('.');
         if (targetNode is ComplexNode)
         {
             SetNumbering(((ComplexNode)mRootNode)[i]);
         }
     }
 }
Exemple #14
0
        private void RenderHtml(SchemaNode XsdModel)
        {
            // Tag;

            webBrowserHtml.Navigate("about:blank");
            webBrowserHtml.Document.OpenNew(false);
            var path     = Path.Combine(Directory.GetCurrentDirectory(), "Template.cshtml");
            var template = File.ReadAllText(path);

            var result = Engine.Razor.RunCompile(template, Guid.NewGuid().ToString(), typeof(SchemaNode), XsdModel);

            webBrowserHtml.Document.Write(result);
            webBrowserHtml.Refresh();
        }
Exemple #15
0
        protected VisitResult VisitElementLiteral(ElementLiteralOperation operation)
        {
            var  fields     = operation.Fields.Select(field => Visit(field.Value).ResultSchema).ToList();
            var  schema     = SchemaNode.GetSchemaNodeForElementLiteralOperation(operation, fields);
            Type objectType = _objectService.GetTypeForElement(schema, out var mappings);

            _schemaTypeMappings[schema] = mappings;
            return(new VisitResult
            {
                ResultSchema = schema,
                Expression = Expression.MemberInit(
                    Expression.New(objectType.GetConstructor(new Type[0])),
                    operation.Fields.Select(field => Expression.Bind(objectType.GetProperty(mappings.Get(field.Name)), Visit(field.Value).Expression))),
            });
        }
        public override string Translate(SqlCompilerContext context, SchemaNode node)
        {
            TemporaryTable tmp = node as TemporaryTable;

            //temporary tables need no schema qualifier
            if (tmp == null && node.Schema != null)
            {
                if (context == null)// extractor for some reason uses this method without context
                {
                    return(QuoteIdentifier(new[] { node.Schema.Name, node.Name }));
                }
                return(QuoteIdentifier(new[] { context.SqlNodeActualizer.Actualize(node.Schema), node.Name }));
            }
            return(QuoteIdentifier(new[] { node.Name }));
        }
    public IEnumerable <ITreeNode> GetChildren(bool refresh)
    {
        var commandText = "select username from all_users order by username";
        var executor    = _connection.CreateCommandExecutor();
        var dataTable   = executor.ExecuteDataTable(new ExecuteReaderRequest(commandText));
        var count       = dataTable.Rows.Count;
        var treeNodes   = new ITreeNode[count];

        for (var i = 0; i < count; i++)
        {
            var name = (string)dataTable.Rows[i][0];
            treeNodes[i] = new SchemaNode(this, name);
        }

        return(treeNodes);
    }
        protected string TranslateExecSpRename(SqlCompilerContext context, SchemaNode affectedNode, string objectName, string newName, string type)
        {
            var result = new StringBuilder();

            result.Append("EXEC ");
            if (context.HasOptions(SqlCompilerNamingOptions.DatabaseQualifiedObjects))
            {
                result.AppendFormat("{0}..", QuoteIdentifier(affectedNode.Schema.Catalog.DbName));
            }
            result.AppendFormat("sp_rename '{0}', '{1}'", objectName, newName);
            if (type != null)
            {
                result.AppendFormat(", '{0}'", type);
            }
            return(result.ToString());
        }
    IEnumerable <ITreeNode> ITreeNode.GetChildren(bool refresh)
    {
        var commandText =
            $@"
select	s.TABLE_OWNER,
	s.TABLE_NAME
from	SYS.ALL_SYNONYMS s
where	s.OWNER			= '{_schema.Name}'
	and s.SYNONYM_NAME	= '{_name}'"        ;
        var executor   = _schema.SchemasNode.Connection.CreateCommandExecutor();
        var dataTable  = executor.ExecuteDataTable(new ExecuteReaderRequest(commandText));
        var dataRow    = dataTable.Rows[0];
        var schemaName = (string)dataRow["TABLE_OWNER"];
        var schemaNode = new SchemaNode(_schema.SchemasNode, schemaName);
        var tableNode  = new TableNode(schemaNode, (string)dataRow["TABLE_NAME"], true);

        return(new ITreeNode[] { tableNode });
    }
Exemple #20
0
        private void BuildSchema(Hashtable nsPrefixTable, XmlSchemaElement elem, string JsonDoc)
        {
            try
            {
                if (elem == null)
                {
                    IEnumerator e = mSchema.Items.GetEnumerator();
                    while (e.MoveNext())
                    {
                        if (e.Current is XmlSchemaElement)
                        {
                            elem = (XmlSchemaElement)e.Current;
                            break;
                        }
                    }
                }

                if (elem != null)
                {
                    mSchema   = (XmlSchema)elem.Parent;
                    mRootNode = (ComplexNode)ParseElement(null, elem);

                    var jsonString = JsonConvert.SerializeObject(mRootNode);
                    var errors     = new StringCollection();
                    textBoxOutput.Text = jsonString;

                    var XSDJsonObj = JObject.Parse(jsonString);
                    // cleanJson(XSDJsonObj);

                    SetNumbering(mRootNode);
                    if (!string.IsNullOrWhiteSpace(JsonDoc))
                    {
                    }
                    RenderHtml(mRootNode);
                }
            }

#pragma warning suppress 6500
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                textBoxOutput.Text = e.Message;
            }
        }
Exemple #21
0
        internal StormResult(StormRow datarow, SchemaNode node)
        {
            this.datarow = datarow;
            _node        = node;
            String getField(string x)
            {
                var i = x.LastIndexOf('.');

                return(x.Substring(i + 1));
            };

            foreach (var item in this.datarow.Keys)
            {
                var _fieldName = getField(item);
                if (_node.entityFields.Any(x => x.CodeName.ToLowerInvariant() == _fieldName.ToLowerInvariant()))
                {
                    _propertyMap.Add(_fieldName, item);
                }
            }
        }
Exemple #22
0
        private SchemaNode ParseComplexType(SchemaNode parent,
                                            XmlSchemaComplexType ct)
        {
            SchemaNode node = null;

            if (ct.ContentModel == null && ct.Particle != null)
            {
                if ((ct.Particle is XmlSchemaChoice))
                {
                    parent.XSDType = "Choice";
                    var schemaBase = (XmlSchemaGroupBase)ct.Particle;
                    if (schemaBase.Items != null)
                    {
                        for (var i = 0; i < schemaBase.Items.Count; i++)
                        {
                            var particle = (XmlSchemaParticle)schemaBase.Items[i];
                            node = ParseParticle(parent, particle);
                        }
                    }
                }
                else if (ct.Particle is XmlSchemaSequence)
                {
                    /*
                     * Parse each particle inside the ComplexType
                     */
                    var schemaBase = (XmlSchemaGroupBase)ct.Particle;
                    if (schemaBase.Items != null)
                    {
                        for (var i = 0; i < schemaBase.Items.Count; i++)
                        {
                            var particle = (XmlSchemaParticle)schemaBase.Items[i];
                            node = ParseParticle(parent, particle);
                        }
                    }
                }
            }

            return(node);
        }
        public static DialogResult ShowWizard(Table table)
        {
            if (!(table.Partitions[0].DataSource is ProviderDataSource))
            {
                MessageBox.Show("This feature currently only supports tables using Legacy Data Sources.", "Unsupported Data Source", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return(DialogResult.Cancel);
            }

            var dialog = new ImportTablesWizard();

            dialog.Model                  = table.Model;
            dialog._currentPage           = 2;
            dialog.btnBack.Visible        = false;
            dialog.btnNext.Visible        = false;
            dialog.btnCancel.Left         = 654;
            dialog.page2.lblHeader.Text   = "Choose the table/view you want to use as a source for " + table.DaxObjectFullName + ":";
            dialog.btnImport.Text         = "OK";
            dialog.page2.SingleSelection  = true;
            dialog.page2.InitialSelection = SchemaNode.FromJson(table.Partitions[0].GetAnnotation("TabularEditor_TableSchema"));
            if (int.TryParse(table.Partitions[0].DataSource.GetAnnotation("TabularEditor_RowLimitClause"), out int rlc))
            {
                dialog.page2.RowLimitClause = (RowLimitClause)rlc;
            }
            dialog.page2.Init(TypedDataSource.GetFromTabularDs(table.Partitions[0].DataSource as ProviderDataSource));
            dialog.page2.Visible = true;

            // TODO:

            var res = dialog.ShowDialog();

            if (res == DialogResult.OK)
            {
                DoUpdate(table, dialog.page2.Source, dialog.page2.SelectedSchemas.First(), dialog.page2.RowLimitClause);
            }
            return(res);
        }
Exemple #24
0
 public FunctionScopeVariable(string name, SchemaNode schema, Expression expression)
 {
     Name       = name;
     Schema     = schema;
     Expression = expression;
 }
Exemple #25
0
        protected VisitResult VisitMethodCall(QueryOperation callee, string methodName, QueryOperation[] arguments, SchemaNodeKind sourceType, SchemaNodeKind[] argumentTypes, SchemaNode resultSchema)
        {
            var visitedCallee = Visit(callee);

            if (visitedCallee.ResultSchema.Kind != sourceType)
            {
                throw new InvalidOperationException();
            }
            var visitedArguments = arguments.Select(arg => Visit(arg)).ToArray();

            if (!visitedArguments.Zip(argumentTypes, (arg, type) => arg.ResultSchema.Kind == type).All(e => e))
            {
                throw new InvalidOperationException();
            }
            return(new VisitResult
            {
                ResultSchema = resultSchema,
                Expression = Expression.Call(
                    visitedCallee.Expression,
                    visitedCallee.Expression.Type.GetMethod(methodName, visitedArguments.Select(arg => arg.Expression.Type).ToArray()),
                    visitedArguments.Select(arg => arg.Expression).ToArray()),
            });
        }
Exemple #26
0
 /// <inheritdoc/>
 public override string Translate(SqlCompilerContext context, SchemaNode node)
 {
     return(QuoteIdentifier(node.DbName));
 }
Exemple #27
0
 public PackageNode(SchemaNode schema, string name)
 {
     _schemaNode = schema;
     _name       = name;
 }
Exemple #28
0
 public QueryableDataSourceProvider(ObjectElementService objectService, IQueryable queryable, SchemaNode schema)
 {
     _objectService = objectService;
     _queryable     = queryable;
     _schema        = schema;
 }
 public PackageCollectionNode(SchemaNode schema) => _schema = schema;
 public ViewCollectionNode(SchemaNode schemaNode)
 {
     _schemaNode = schemaNode;
 }