Example #1
0
        public override GlyphDefinition GetDefintions(string fragment, TSqlStatement statement, GlyphDefinition definition, List<QuerySpecification> queries)
        {
            var documentCoster = DocumentScriptCosters.GetInstance();
            if (documentCoster == null)
                return definition;

            var coster = documentCoster.GetCoster();
            if (null == coster)
                return definition;

            var statements = coster.GetCosts();

            if (statements == null || statements.Count == 0)
                return definition;

            var thisStatement = fragment;

            var costedStatement =
                statements.FirstOrDefault(p => p.Text.IndexOf(thisStatement, StringComparison.OrdinalIgnoreCase) > 0);

            if (costedStatement == null)
                return definition;

            definition.Menu.Add(new MenuDefinition
            {
                Action = null,
                Caption = "Query Cost: " + costedStatement.Cost,
                Type = MenuItemType.Header
            });

            return definition;
        }
        public override void Visit(TSqlStatement node)
        {
            base.Visit(node);

            if(!Nodes.Any(p=>p.StartOffset <= node.StartOffset && p.StartOffset + p.FragmentLength >= node.StartOffset + node.FragmentLength))
                Nodes.Add(node);
        }
        public override GlyphDefinition GetDefinitions(string fragment, TSqlStatement statement, GlyphDefinition definition, List<TSqlStatement> queries)
        {
            var scriptTables = ScriptDom.GetTableList(statement).Where(p => p is NamedTableReference).Cast<NamedTableReference>().ToList();
            
            var dacTables = GetDacTables();

            var rewriter = new TableReferenceRewriter(fragment, scriptTables);
            var replacements = rewriter.GetReplacements(dacTables);

            if (replacements.Count > 0)
            {
                definition.Menu.Add(new MenuDefinition()
                {
                    Caption = "Correct Case Table Identifiers",
                    Action = () => { },
                    Type = MenuItemType.Header
                    ,
                    Glyph = definition
                });

                var offsettedReplacments = new List<Replacements>();
                foreach (var replacement in replacements)
                {
                    var replacement1 = replacement;
                    
                    replacement1.Original = fragment.Substring(replacement1.OriginalOffset-statement.StartOffset, replacement1.OriginalLength);
                  
                    offsettedReplacments.Add(replacement1);
                }

                if (replacements.Count > 1)
                {
                    var menu = new MenuDefinition();
                    menu.Operation = new ClippyReplacementOperations(offsettedReplacments);
                    menu.Action = () => PerformAction(menu.Operation, menu.Glyph);

                    menu.Glyph = definition;
                    menu.Caption = GetCaptionForAll(statement);
                    menu.Type = MenuItemType.MenuItem;
                    definition.Menu.Add(menu);
                }


                foreach (var replacement in offsettedReplacments)
                {
                    var menu = new MenuDefinition();
                    menu.Action = () => PerformAction(menu.Operation, menu.Glyph);
                    menu.Glyph = definition;
                    menu.Caption = string.Format("\t\"{0}\" into \"{1}\"", replacement.Original, replacement.Replacement);
                    menu.Type = MenuItemType.MenuItem;
                    menu.Operation = new ClippyReplacementOperation(replacement);
                    definition.Menu.Add(menu);
                }

            }

            return definition;
        }
        public override void Visit(TSqlStatement node)
        {
            if ((node as SelectStatement) == null)
            {
                containsOnlySelects = false;
            }

            base.Visit(node);
        }
        protected string GetCaptionForAll(TSqlStatement statement)
        {
            if (statement is SelectStatement)
                return "All on Statement";

            if (statement.GetType().Name.StartsWith("Create"))
                return "All in Module";

            return "All";
        }
        public override GlyphDefinition GetDefintions(string fragment, TSqlStatement statement, GlyphDefinition definition, List<QuerySpecification> queries)
        {
            var rewriter = new OrderByOrdinalRewrites();
            var replacements = rewriter.GetReplacements(queries);

            if (replacements == null)
                return definition;

            if (replacements.Count > 0)
            {
                definition.Menu.Add(new MenuDefinition()
                {
                    Caption = "Replace Ordinals in Order By",
                    Action = () => { },
                    Type = MenuItemType.Header
                    ,
                    Glyph = definition
                });

                var offsettedReplacments = new List<Replacements>();
                foreach (var replacement in replacements)
                {
                    var replacement1 = replacement;
                    replacement1.OriginalOffset += statement.StartOffset;
                    offsettedReplacments.Add(replacement1);
                }

                if (replacements.Count > 1)
                {
                    var menu = new MenuDefinition();
                    menu.Operation = new ClippyReplacementOperations(offsettedReplacments);
                    menu.Action = () => PerformAction(menu.Operation, menu.Glyph);

                    menu.Glyph = definition;
                    menu.Caption = GetCaptionForAll(statement);
                    menu.Type = MenuItemType.MenuItem;
                    definition.Menu.Add(menu);
                }


                foreach (var replacement in offsettedReplacments)
                {
                    var menu = new MenuDefinition();
                    menu.Action = () => PerformAction(menu.Operation, menu.Glyph);
                    menu.Glyph = definition;
                    menu.Caption = string.Format("\t\"{0}\" into \"{1}\"", replacement.Original, replacement.Replacement);
                    menu.Type = MenuItemType.MenuItem;
                    menu.Operation = new ClippyReplacementOperation(replacement);
                    definition.Menu.Add(menu);
                }

                definition.GenerateKey();
            }
            return definition;
        }
        public override GlyphDefinition GetDefintions(string fragment, TSqlStatement statement, GlyphDefinition definition, List<DeleteSpecification> queries)
        {
            var nonSargableRewriter = new ChunkDeletesRewriter(fragment);
            var replacements = nonSargableRewriter.GetReplacements(queries);

            if (replacements.Count > 0)
            {
                definition.Menu.Add(new MenuDefinition()
                {
                    Caption = "Run Delete Statement in Batches",
                    Action = () => { },
                    Type = MenuItemType.Header
                    ,
                    Glyph = definition
                });

                var offsettedReplacments = new List<Replacements>();
                foreach (var replacement in replacements)
                {
                    var replacement1 = replacement;
                    replacement1.OriginalOffset += statement.StartOffset;
                    offsettedReplacments.Add(replacement1);
                }

                if (replacements.Count > 1)
                {
                    var menu = new MenuDefinition();
                    menu.Operation = new ClippyReplacementOperations(offsettedReplacments);
                    menu.Action = () => PerformAction(menu.Operation, menu.Glyph);

                    menu.Glyph = definition;
                    menu.Caption = GetCaptionForAll(statement);
                    menu.Type = MenuItemType.MenuItem;
                    definition.Menu.Add(menu);
                }


                foreach (var replacement in offsettedReplacments)
                {
                    var menu = new MenuDefinition();
                    menu.Action = () => PerformAction(menu.Operation, menu.Glyph);
                    menu.Glyph = definition;
                    menu.Caption = string.Format("\t\"{0}\" into Chunked Delete", replacement.Original);
                    menu.Type = MenuItemType.MenuItem;
                    menu.Operation = new ClippyReplacementOperation(replacement);
                    definition.Menu.Add(menu);
                }

                definition.GenerateKey();
            }

            return definition;

        }
        public static void PrintTSqlStatementBlockToDebugConsole(this TSqlStatement statement)
        {
            StringBuilder sb            = new StringBuilder();
            int           skipFragments = statement.FirstTokenIndex - 1;

            skipFragments = skipFragments > 0 ? skipFragments : 0;
            int takeFragments = (statement.LastTokenIndex - statement.FirstTokenIndex) + 2;

            takeFragments = skipFragments + takeFragments > statement.ScriptTokenStream.Count ? statement.ScriptTokenStream.Count - skipFragments : takeFragments;
            statement.ScriptTokenStream
            .Skip(skipFragments)
            .Take(takeFragments).ToList().ForEach(x => sb.Append(x.Text));

            Debug.WriteLine($"============= {statement.GetType().FullName} =============");
            Debug.WriteLine(sb.ToString());
        }
        public static void PrintTablesToDebugConsole(this TSqlStatement statement, List <TableParsingResult> items)
        {
            StringBuilder sb = new StringBuilder();

            Debug.WriteLine($"============= tables added in {statement.GetType().FullName} section =============");
            if (items.Count > 0)
            {
                items.ForEach(x => sb.AppendLine($"Name: {x.TableName} Operation: {x.OperationType} Alias:{x.Alias}"));
            }
            else
            {
                sb.AppendLine("no tables parsed in this section");
            }
            Debug.WriteLine(sb.ToString());
            //Debug.WriteLine($"============= {statement.GetType().FullName} =============");
        }
Example #10
0
        public override void Visit(TSqlStatement statement)
        {
            if (_stopEnumerating)
            {
                return;
            }

            if (ShouldNotEnumerateChildren(statement))
            {
                Statements.Add(new Statement {
                    Text = _script.Substring(statement.StartOffset, statement.FragmentLength), Offset = statement.StartOffset, Length = statement.FragmentLength, IsCoverable = false
                });
                _stopEnumerating = true;       //maybe ExplicitVisit would be simpler??
                return;
            }

            base.Visit(statement);

            if (!IsIgnoredType(statement))
            {
                Statements.Add(new Statement {
                    Text = _script.Substring(statement.StartOffset, statement.FragmentLength), Offset = statement.StartOffset, Length = statement.FragmentLength, IsCoverable = CanBeCovered(statement)
                });
            }

            if (statement is IfStatement)
            {
                var ifStatement = (IfStatement)statement;

                var offset = statement.StartOffset;
                var length = ifStatement.Predicate.StartOffset + ifStatement.Predicate.FragmentLength - statement.StartOffset;
                Statements.Add(new Statement {
                    Text = _script.Substring(offset, length), Offset = offset, Length = length, IsCoverable = CanBeCovered(statement)
                });
            }

            if (statement is WhileStatement)
            {
                var whileStatement = (WhileStatement)statement;

                var offset = statement.StartOffset;
                var length = whileStatement.Predicate.StartOffset + whileStatement.Predicate.FragmentLength - statement.StartOffset;
                Statements.Add(new Statement {
                    Text = _script.Substring(offset, length), Offset = offset, Length = length, IsCoverable = CanBeCovered(statement)
                });
            }
        }
Example #11
0
        public static List <TableReference> GetTableList(TSqlStatement script)
        {
            var tables = new List <TableReference>();

            var parser = new TSql130Parser(false);

            var visitor = new EnumeratorVisitor();

            script.Accept(visitor);

            foreach (var statement in visitor.Nodes)
            {
                tables.AddRange(FindTableReferences(statement));
            }

            return(tables);
        }
Example #12
0
        private void ParseSqlInsertStatement(TSqlStatement sqlStatement)
        {
            if (sqlStatement.GetType() == typeof(InsertStatement))
            {
                InsertStatement aInsertStatement = (InsertStatement)sqlStatement;

                if (aInsertStatement.InsertSpecification.Target is NamedTableReference)
                {
                    //tables
                    NamedTableReferenceVisitor ntVisitor = new NamedTableReferenceVisitor(Context);
                    aInsertStatement.InsertSpecification.Accept(ntVisitor);
                    TablesReferred = ntVisitor.Tables;
                }

                if ((TablesReferred.Count == 1) &&
                    (aInsertStatement.InsertSpecification.Columns.Count == 0))
                {
                    //insert query does not specific columns
                    int howManyColumnValues = ((ValuesInsertSource)aInsertStatement.InsertSpecification.InsertSource).RowValues[0].ColumnValues.Count;
                    //add table column sequentially
                    for (int i = 0; i < howManyColumnValues; i++)
                    {
                        AddSelectColumn(TablesReferred[0].Name, TablesReferred[0].Columns[i].Name);
                    }
                }
                else if ((TablesReferred.Count == 1) &&
                         (aInsertStatement.InsertSpecification.Columns.Count > 0))
                {
                    //insert query has specific columns
                    foreach (ColumnReferenceExpression columnExp in aInsertStatement.InsertSpecification.Columns)
                    {
                        var columnName = columnExp.MultiPartIdentifier.Identifiers[0].Value;
                        AddSelectColumn(TablesReferred[0].Name, columnName);
                    }
                }
                else
                {
                    throw new NotImplementedException("This kind of insert statement not supported yet!");
                }
            }
            else
            {
                Errors.Add("Not a update statement!");
            }
        }
Example #13
0
        private bool IsCaretInsideStatement(TSqlStatement statement, VirtualPoint caret)
        {
            var ft = statement.ScriptTokenStream[statement.FirstTokenIndex];
            var lt = statement.ScriptTokenStream[statement.LastTokenIndex];

            if (caret.Line >= ft.Line && caret.Line <= lt.Line)
            {
                var isBeforeFirstToken = caret.Line == ft.Line && caret.LineCharOffset < ft.Column;
                var isAfterLastToken   = caret.Line == lt.Line && caret.LineCharOffset > lt.Column + lt.Text.Length;

                if (!(isBeforeFirstToken || isAfterLastToken))
                {
                    return(true);
                }
            }

            return(false);
        }
Example #14
0
        private static bool CreateObject(
            SqlConnection connection,
            TSqlObjectIdentifier identifier,
            TSqlStatement statement)
        {
            if (connection.ObjectExists(identifier))
            {
                // TODO: logging
                return(false);
            }

            if (identifier is TSqlSchemaObjectIdentifier schemaIdentifier)
            {
                connection.CreateSchemaIfNotExists(schemaIdentifier.SchemaName);
            }

            connection.ExecuteNonQuery(statement.ToString());
            return(true);
        }
        public override void Visit(TSqlStatement node)
        {
            if (typesToSkip.Contains(node.GetType()) ||
                EndsWithSemicolon(node) ||
                waitForStatements.Contains(node))
            {
                return;
            }

            var dynamicSqlColumnOffset = node.StartLine == DynamicSqlStartLine
                ? DynamicSqlStartColumn
                : 0;

            var lastToken  = node.ScriptTokenStream[node.LastTokenIndex];
            var tabsOnLine = ColumnNumberCalculator.CountTabsBeforeToken(lastToken.Line, node.LastTokenIndex, node.ScriptTokenStream);
            var column     = ColumnNumberCalculator.GetColumnNumberAfterToken(tabsOnLine, lastToken);

            errorCallback(RULE_NAME, RULE_TEXT, lastToken.Line, column + dynamicSqlColumnOffset);
        }
        public override GlyphDefinition GetDefintions(string fragment, TSqlStatement statement, GlyphDefinition definition, List <QuerySpecification> queries)
        {
            var documentCoster = DocumentScriptCosters.GetInstance();

            if (documentCoster == null)
            {
                return(definition);
            }

            var coster = documentCoster.GetCoster();

            if (null == coster)
            {
                return(definition);
            }

            var statements = coster.GetCosts();

            if (statements == null || statements.Count == 0)
            {
                return(definition);
            }

            var thisStatement = fragment;

            var costedStatement =
                statements.FirstOrDefault(p => p.Text.IndexOf(thisStatement, StringComparison.OrdinalIgnoreCase) > 0);

            if (costedStatement == null)
            {
                return(definition);
            }

            definition.Menu.Add(new MenuDefinition
            {
                Action  = null,
                Caption = "Query Cost: " + costedStatement.Cost,
                Type    = MenuItemType.Header
            });

            return(definition);
        }
Example #17
0
        private TextBlock GetTextBlockFromStatement(TSqlStatement statement)
        {
            var ft = statement.ScriptTokenStream[statement.FirstTokenIndex];
            var lt = statement.ScriptTokenStream[statement.LastTokenIndex];

            return(new TextBlock()
            {
                StartPoint = new VirtualPoint
                {
                    Line = ft.Line,
                    LineCharOffset = ft.Column
                },

                EndPoint = new VirtualPoint
                {
                    Line = lt.Line,
                    LineCharOffset = lt.Column + lt.Text.Length
                }
            });
        }
Example #18
0
        public void logger(DeploymentStep ds, int i)
        {
            string msg = "";

            if (ds is CreateElementStep || ds is DropElementStep)
            {
                DeploymentScriptDomStep domStep = ds as DeploymentScriptDomStep;

                TSqlScript    script = domStep.Script as TSqlScript;
                TSqlStatement t      = script.Batches[0].Statements[0];

                msg = $"{DateTime.Now.ToLongTimeString()}, {i:000} - {ds.GetType().Name}: {t.GetType().Name}";
            }
            else
            {
                msg = $"{DateTime.Now.ToLongTimeString()}, {i:000} - {ds.GetType().Name}: - ";
            }

            using (StreamWriter w = File.AppendText(logfilepath)) { w.WriteLine(msg); }
        }
Example #19
0
        public override void Visit(TSqlStatement node)
        {
            if (TypesToSkip.Contains(node.GetType()))
            {
                return;
            }

            var lastToken = node.ScriptTokenStream[node.LastTokenIndex];

            if (lastToken.TokenType == TSqlTokenType.Semicolon)
            {
                return;
            }

            // get a count of all tabs on the line that occur prior to the last token in this node
            var tabsOnLine = ColumnNumberCounter.CountTabsOnLine(lastToken.Line, node.LastTokenIndex, node.ScriptTokenStream);
            var column     = ColumnNumberCounter.GetColumnNumberAfterToken(tabsOnLine, lastToken);

            ErrorCallback(RULE_NAME, RULE_TEXT, lastToken.Line, column);
        }
Example #20
0
        public override void Visit(TSqlStatement node)
        {
            if (node.GetType().Name.StartsWith("Create") || node.GetType().Name.StartsWith("AlterTabl") ||
                node.GetType().Name.StartsWith("AlterProc") || node.GetType().Name.StartsWith("AlterFunc"))
            {
                if (!_topLevelObjects.Any(p => p.Start < node.StartOffset && p.Length > node.FragmentLength))
                {
                    //string script;
                    //_generator.GenerateScript(node, out script);

                    var script = _currentBatch.Substring(node.StartOffset, node.FragmentLength);

                    _topLevelObjects.Add(new fragment_position {
                        Start = node.StartOffset, Length = node.FragmentLength
                    });
                    Statements.Add(script);

                    Console.WriteLine(node);
                }
            }
        }
Example #21
0
        private bool IsIgnoredType(TSqlStatement statement)
        {
            if (statement is BeginEndBlockStatement)
            {
                return(true);
            }

            if (statement is WhileStatement)
            {
                return(true);
            }

            if (statement is IfStatement)
            {
                return(true);
            }

            //next todo - in extended events i think if are handled differently - do we need to search for the predicate and have that a s asepararte thinggy???

            return(!CanBeCovered(statement)); //TODO: This all needs tidying up, don't think i need two things to do the same thing???
        }
Example #22
0
        private bool CanBeCovered(TSqlStatement statement)
        {
            if (statement is BeginEndBlockStatement)
            {
                return(false);
            }

            if (statement is TryCatchStatement)
            {
                return(false);
            }

            if (statement is CreateProcedureStatement)
            {
                return(false);
            }

            if (statement is CreateFunctionStatement)
            {
                return(false);
            }

            if (statement is CreateTriggerStatement)
            {
                return(false);
            }

            if (statement is DeclareVariableStatement)
            {
                return(false);
            }

            if (statement is DeclareTableVariableStatement)
            {
                return(false);
            }

            return(true);
        }
Example #23
0
        public void ParseSQL(string sql)
        {
            TSql130Parser sqlParser = new TSql130Parser(false);

            IList <ParseError> parseErrors;
            TSqlFragment       result = sqlParser.Parse(new StringReader(sql), out parseErrors);

            if (parseErrors.Count > 0)
            {
                throw new ArgumentException(string.Join(Environment.NewLine, parseErrors.Select(p => p.Message)));
            }

            TSqlScript SqlScript = result as TSqlScript;

            if (SqlScript.Batches.Count > 1)
            {
                throw new NotSupportedException("Batches.Count > 1 not supported");
            }

            var batch = SqlScript.Batches.First();

            if (batch.Statements.Count > 1)
            {
                throw new NotSupportedException("Statements.Count > 1 not supported");
            }

            TSqlStatement statement = batch.Statements.First();

            if (statement is SelectStatement)
            {
                ParseSelectStatement(statement as SelectStatement);
            }
            else
            {
                throw new NotImplementedException($"Query statement of type {statement.GetType().Name} not supported");
            }
        }
Example #24
0
 public override void Visit(TSqlStatement node)
 {
     Statements.Add(node);
 }
Example #25
0
        public static List<QuerySpecification> FlattenTreeGetQuerySpecifications(TSqlStatement statement)
        {
            var specifications = new List<QuerySpecification>();

            if (statement is SelectStatement)
            {
                specifications.Add( (statement as SelectStatement).QueryExpression as QuerySpecification );
            }

            specifications.AddRange(SearchChildren(statement));

            return specifications;
        }
Example #26
0
 public override GlyphDefinition GetDefintions(string fragment, TSqlStatement statement, GlyphDefinition definition, List<DeleteSpecification> queries)
 {
     return definition;
 }
        public IEnumerable <IColumnRelationship> ParseViewTableColumnToBaseTableColumnRelationships(TSqlStatement tsqlStatement, string contextualServerName, string contextualDatabaseName, RelationshipOrigin relationshipOrigin)
        {
            var viewStatementBody = tsqlStatement as ViewStatementBody;

            if (viewStatementBody == null)
            {
                yield break;
            }

            if (!TryParseTable(contextualServerName, contextualDatabaseName, viewStatementBody.SchemaObjectName, out ITable viewTable))
            {
                yield break;
            }

            var selectStatement    = viewStatementBody.SelectStatement;
            var queryExpression    = selectStatement.QueryExpression;
            var querySpecification = queryExpression as QuerySpecification;

            if (!(queryExpression is QuerySpecification))
            {
                yield break;
            }

            var selectElements = querySpecification.SelectElements;

            if (viewTable.Columns.Count != selectElements.Count)
            {
                yield break;
            }

            var viewStatementFromClause = querySpecification.FromClause;

            if (!TryParseTableByAliasIdentifier(viewStatementFromClause, contextualServerName, contextualDatabaseName, out IDictionary <string, ITable> viewTableByAliasIdentifier))
            {
                yield break;
            }

            for (var index = 0; index < selectElements.Count; index++)
            {
                var selectElement             = selectElements[index];
                var selectScalarExpression    = (SelectScalarExpression)selectElement;
                var scalarExpression          = selectScalarExpression.Expression;
                var columnReferenceExpression = scalarExpression as ColumnReferenceExpression;

                if (!(scalarExpression is ColumnReferenceExpression))
                {
                    continue;
                }

                var viewColumns     = viewTable.Columns.AsList();
                var viewTableColumn = viewColumns[index];

                if (!TryParseColumn(columnReferenceExpression, viewTableByAliasIdentifier, out IColumn baseTableColumn))
                {
                    continue;
                }

                var columnRelationship = new ColumnRelationship(viewTableColumn, baseTableColumn, relationshipOrigin);

                yield return(columnRelationship);
            }
        }
Example #28
0
 public override void ExplicitVisit(TSqlStatement node) { this.action(node); }
Example #29
0
        private WSqlStatement ParseStatement(TSqlStatement tsqlStat)
        {
            WSqlStatement wstat;

            switch (tsqlStat.GetType().Name)
            {
                case "SelectStatement":
                    {
                        var sel = tsqlStat as SelectStatement;
                        wstat = ParseSelectQueryStatement(sel.QueryExpression);

                        break;
                    }
                case "CreateFunctionStatement":
                    {
                        var creat = tsqlStat as CreateFunctionStatement;
                        var wcreat = new WCreateFunctionStatement
                        {
                            Parameters = creat.Parameters,
                            ReturnType = creat.ReturnType,
                            StatementList = new List<WSqlStatement>(creat.StatementList.Statements.Count),
                            FirstTokenIndex = creat.FirstTokenIndex,
                            LastTokenIndex = creat.LastTokenIndex,
                            Name = ParseSchemaObjectName(creat.Name)
                        };

                        foreach (var stat in creat.StatementList.Statements)
                        {
                            wcreat.StatementList.Add(ParseStatement(stat));
                        }

                        wstat = wcreat;
                        break;
                    }
                case "BeginEndBlockStatement":
                    {
                        var bestat = tsqlStat as BeginEndBlockStatement;
                        var wbestat = new WBeginEndBlockStatement
                        {
                            StatementList = new List<WSqlStatement>(bestat.StatementList.Statements.Count),
                            FirstTokenIndex = bestat.FirstTokenIndex,
                            LastTokenIndex = bestat.LastTokenIndex
                        };

                        foreach (var pstat in bestat.StatementList.Statements.Select(ParseStatement))
                        {
                            wbestat.StatementList.Add(pstat);
                        }

                        wstat = wbestat;
                        break;
                    }
                case "UpdateStatement":
                    {
                        var upd = tsqlStat as UpdateStatement;
                        wstat = ParseUpdateStatement(upd.UpdateSpecification);
                        break;
                    }
                case "DeleteStatement":
                    {
                        var del = tsqlStat as DeleteStatement;
                        wstat = ParseDeleteStatement(del.DeleteSpecification);
                        break;
                    }
                case "InsertStatement":
                    {
                        var ins = tsqlStat as InsertStatement;
                        wstat = ParseInsertStatement(ins.InsertSpecification);
                        break;
                    }
                case "CreateTableStatement":
                    {
                        var cts = tsqlStat as CreateTableStatement;
                        var wcstat = new WCreateTableStatement
                        {
                            FirstTokenIndex = cts.FirstTokenIndex,
                            LastTokenIndex = cts.LastTokenIndex,
                            Definition = ParseTableDefinition(cts.Definition),
                            SchemaObjectName = ParseSchemaObjectName(cts.SchemaObjectName),
                        };
                        wstat = wcstat;
                        break;
                    }
                case "DropTableStatement":
                    {
                        var dts = tsqlStat as DropTableStatement;
                        var wdstat = new WDropTableStatement
                        {
                            FirstTokenIndex = dts.FirstTokenIndex,
                            LastTokenIndex = dts.LastTokenIndex,
                        };
                        if (dts.Objects != null)
                        {
                            wdstat.Objects = new List<WSchemaObjectName>();
                            foreach (var obj in dts.Objects)
                            {
                                wdstat.Objects.Add(ParseSchemaObjectName(obj));
                            }
                        }
                        wstat = wdstat;
                        break;
                    }
                case "CreateViewStatement":
                {
                    var cvs = tsqlStat as CreateViewStatement;
                    var wcvs = new WCreateViewStatement
                    {
                        Columns = cvs.Columns,
                        FirstTokenIndex = cvs.FirstTokenIndex,
                        LastTokenIndex = cvs.LastTokenIndex,
                        SchemaObjectName = ParseSchemaObjectName(cvs.SchemaObjectName),
                        SelectStatement = ParseSelectQueryStatement(cvs.SelectStatement.QueryExpression),
                        ViewOptions = cvs.ViewOptions,
                        WithCheckOption = cvs.WithCheckOption
                    };
                    wstat = wcvs;
                    break;
                }
                case "BeginTransactionStatement":
                    {
                        var beginTranStat = tsqlStat as BeginTransactionStatement;
                        wstat = new WBeginTransactionStatement
                        {
                            Name = ParseIdentifierOrValueExpression(beginTranStat.Name),
                            Distributed = beginTranStat.Distributed,
                            FirstTokenIndex = beginTranStat.FirstTokenIndex,
                            LastTokenIndex = beginTranStat.LastTokenIndex
                        };
                        break;
                    }
                case "CommitTransactionStatement":
                    {

                        var commitTranStat = tsqlStat as CommitTransactionStatement;
                        wstat = new WCommitTransactionStatement
                        {
                            Name = ParseIdentifierOrValueExpression(commitTranStat.Name),
                            FirstTokenIndex = commitTranStat.FirstTokenIndex,
                            LastTokenIndex = commitTranStat.LastTokenIndex
                        };
                        break;
                    }
                case "RollbackTransactionStatement":
                    {

                        var rollbackTranStat = tsqlStat as RollbackTransactionStatement;
                        wstat = new WRollbackTransactionStatement
                        {
                            Name = ParseIdentifierOrValueExpression(rollbackTranStat.Name),
                            FirstTokenIndex = rollbackTranStat.FirstTokenIndex,
                            LastTokenIndex = rollbackTranStat.LastTokenIndex
                        };
                        break;
                    }
                case "SaveTransactionStatement":
                    {

                        var saveTranStat = tsqlStat as SaveTransactionStatement;
                        wstat = new WSaveTransactionStatement
                        {
                            Name = ParseIdentifierOrValueExpression(saveTranStat.Name),
                            FirstTokenIndex = saveTranStat.FirstTokenIndex,
                            LastTokenIndex = saveTranStat.LastTokenIndex
                        };
                        break;
                    }
                case "CreateProcedureStatement":
                    {
                        var creat = tsqlStat as CreateProcedureStatement;
                        var wcreat = new WCreateProcedureStatement
                        {
                            IsForReplication = creat.IsForReplication,
                            Parameters = creat.Parameters,
                            StatementList = new List<WSqlStatement>(creat.StatementList.Statements.Count),
                            FirstTokenIndex = creat.FirstTokenIndex,
                            LastTokenIndex = creat.LastTokenIndex,
                            ProcedureReference = new WProcedureReference
                            {
                                Name = ParseSchemaObjectName(creat.ProcedureReference.Name),
                                Number = creat.ProcedureReference.Number
                            }
                        };

                        foreach (var stat in creat.StatementList.Statements)
                        {
                            wcreat.StatementList.Add(ParseStatement(stat));
                        }

                        wstat = wcreat;
                        break;
                    }
                case "DropProcedureStatement":
                    {
                        var dts = tsqlStat as DropProcedureStatement;
                        var wdstat = new WDropProcedureStatement
                        {
                            FirstTokenIndex = dts.FirstTokenIndex,
                            LastTokenIndex = dts.LastTokenIndex,
                        };
                        if (dts.Objects != null)
                        {
                            wdstat.Objects = new List<WSchemaObjectName>();
                            foreach (var obj in dts.Objects)
                            {
                                wdstat.Objects.Add(ParseSchemaObjectName(obj));
                            }
                        }
                        wstat = wdstat;
                        break;
                    }
                case "WhileStatement":
                    {
                        var bestat = tsqlStat as WhileStatement;
                        var wbestat = new WWhileStatement()
                        {
                            Predicate = ParseBooleanExpression(bestat.Predicate),
                            Statement = ParseStatement(bestat.Statement),
                            FirstTokenIndex = bestat.FirstTokenIndex,
                            LastTokenIndex = bestat.LastTokenIndex
                        };


                        wstat = wbestat;
                        break;
                    }
                case "DeclareVariableStatement":
                {
                    var dvstat = tsqlStat as DeclareVariableStatement;
                    wstat = new WDeclareVariableStatement
                    {
                        Statement = dvstat
                    };
                    break;
                }
                default:
                    {
                        wstat = new WSqlUnknownStatement(tsqlStat)
                        {
                            FirstTokenIndex = tsqlStat.FirstTokenIndex,
                            LastTokenIndex = tsqlStat.LastTokenIndex
                        };

                        break;
                    }
            }

            return wstat;
        }
 public override GlyphDefinition GetDefintions(string fragment, TSqlStatement statement, GlyphDefinition definition, List <DeleteSpecification> queries)
 {
     return(definition);
 }
        private void ParseSqlUpdateStatement(TSqlStatement sqlStatement)
        {
            if (sqlStatement.GetType() == typeof(UpdateStatement))
            {
                UpdateStatement aUpdateStatement = (UpdateStatement)sqlStatement;

                #region Handle Target Table


                #endregion Handle Target Table

                RbacTable targetTable = new RbacTable();

                #region Handle From Clause - When Update with Join
                if (aUpdateStatement.UpdateSpecification.FromClause != null)
                {
                    //mostly update with join case
                    NamedTableReferenceVisitor fromClauseNtVisitor = new NamedTableReferenceVisitor(Context);
                    aUpdateStatement.UpdateSpecification.FromClause.AcceptChildren(fromClauseNtVisitor);
                    this.TablesReferred = fromClauseNtVisitor.Tables;
                    if (TablesReferred.Count > 0)
                    {
                        targetTable = TablesReferred[0];
                        //if alias is being updated, we need to fix table name
                        RbacTable tryTable = Context.User.Role.CrudPermissions.Find(targetTable.Name);
                        if (tryTable == null)
                        {
                            //alias is being updated, lets get the actual table name
                            var tt = fromClauseNtVisitor.Tables.Where(t => t.Alias == targetTable.Name).ToList()[0];
                            if (tt != null)
                            {
                                targetTable.Name = tt.Name;
                            }
                        }
                    }
                    else
                    {
                        RbacException.Raise("No target table found in the update query!");
                    }
                }
                else
                {
                    NamedTableReferenceVisitor ntVisitor = new NamedTableReferenceVisitor(Context);
                    aUpdateStatement.UpdateSpecification.Target.Accept(ntVisitor);

                    if (ntVisitor.Tables.Count == 0)
                    {
                        RbacException.Raise("No target table found in the update query!");
                    }
                    else if (ntVisitor.Tables.Count == 1)
                    {
                        targetTable = ntVisitor.Tables[0];
                    }
                    else
                    {
                        RbacException.Raise("More than 1 target tables found in the update query! Currently not supported.");
                    }

                    TablesReferred.Add(targetTable);
                }
                #endregion Handle From Clause - When Update with Join

                #region Handle Columns

                SetClauseVisitor scVisitor = new SetClauseVisitor(targetTable.Name);
                aUpdateStatement.UpdateSpecification.AcceptChildren(scVisitor);
                Columns = scVisitor.Columns;
                UpdateReferredTables(Columns);

                #endregion Handle Columns
            }
            else
            {
                Errors.Add("Not a update statement!");
            }
        }
        protected override void OnExecute(DeploymentPlanContributorContext context)
        {
            DeploymentStep nextStep = context.PlanHandle.Head;

            while (nextStep != null)
            {
                DeploymentStep currentStep = nextStep;
                nextStep = currentStep.Next;

                //Debug.WriteLine($"{currentStep.GetType()}");

                if (currentStep is DeploymentScriptStep)
                {
                    DeploymentScriptStep d = currentStep as DeploymentScriptStep;

                    Regex rx = new Regex(@"\[sandbox\]");   //[\n\r]*is being dropped.  Deployment will halt if the table contains data.");
                    if (rx.IsMatch(d.GenerateTSQL()[0]))
                    {
                        base.Remove(context.PlanHandle, currentStep);
                        continue;
                    }
                }

                if (currentStep is CreateElementStep)
                {
                    DeploymentScriptDomStep domStep = currentStep as DeploymentScriptDomStep;

                    TSqlScript    script = domStep.Script as TSqlScript;
                    TSqlStatement t      = script.Batches[0].Statements[0];

                    if (t is CreateTableStatement o)
                    {
                        SchemaObjectName ol  = o.SchemaObjectName;
                        string           ol1 = ol.SchemaIdentifier.Value;

                        if (ol1 == "sandbox" || ol1 == "unittests")
                        {
                            base.Remove(context.PlanHandle, currentStep);
                            continue;
                        }
                    }

                    //  Sql140ScriptGenerator s = new Sql140ScriptGenerator();
                    //  s.GenerateScript(t, out string ts);
                    //  Debug.WriteLine($"{t.GetType()}: {ts}");
                    //  DropChildObjectsStatement
                    //  DropStatisticsStatement
                }

                if (currentStep is DropElementStep)
                {
                    DeploymentScriptDomStep domStep = currentStep as DeploymentScriptDomStep;
                    TSqlScript    script            = domStep.Script as TSqlScript;
                    TSqlStatement t = script.Batches[0].Statements[0];

                    //Debug.WriteLine($"{currentStep.GetType()}: {t.GetType()}");

                    if (t is DropStatisticsStatement)
                    {
                        base.Remove(context.PlanHandle, currentStep);
                        continue;
                    }

                    if (t is DropObjectsStatement)
                    {
                        DropObjectsStatement     o  = (DropObjectsStatement)t;
                        IList <SchemaObjectName> ol = o.Objects;
                        string ol1 = ol[0].SchemaIdentifier.Value;

                        if (ol1 == "sandbox" || ol1 == "unittests")
                        {
                            base.Remove(context.PlanHandle, currentStep);
                            continue;
                        }
                    }

                    //  Sql140ScriptGenerator s = new Sql140ScriptGenerator();
                    //  s.GenerateScript(t, out string ts);
                    //  Debug.WriteLine($"{t.GetType()}: {ts}");
                    //  DropChildObjectsStatement
                    //  DropStatisticsStatement
                }

                //if (currentStep is AlterElementStep)
                //{
                //    DeploymentScriptDomStep domStep = currentStep as DeploymentScriptDomStep;
                //    TSqlScript script = domStep.Script as TSqlScript;
                //    TSqlStatement t = script.Batches[0].Statements[0];

                //    if (t is AlterProcedureStatement)
                //    {
                //        AlterProcedureStatement o = (AlterProcedureStatement)t;
                //        SchemaObjectName ol = o.Options.sch
                //        string ol1 = ol.SchemaIdentifier.Value;

                //        if (ol1 == "sandbox" || ol1 == "unittests")
                //        {
                //            base.Remove(context.PlanHandle, currentStep);
                //            continue;
                //        }
                //    }
                //}
            }
        }
 public override void ExplicitVisit(TSqlStatement fragment)
 {
     _fragments.Add(fragment);
 }
Example #34
0
 public override void Visit(TSqlStatement node)
 {
     StatementCount++;
 }
Example #35
0
        protected override void OnExecute(DeploymentPlanContributorContext context)
        {
            // Obtain the first step in the Plan from the provided context
            int            batchId  = 0;
            DeploymentStep nextStep = context.PlanHandle.Head;
            BeginPreDeploymentScriptStep beforePreDeploy = null;

            while (nextStep != null)
            {
                DeploymentStep currentStep = nextStep;
                nextStep = currentStep.Next;

                if (currentStep is BeginPreDeploymentScriptStep)
                {
                    beforePreDeploy = (BeginPreDeploymentScriptStep)currentStep;
                    continue;
                }
                if (currentStep is SqlPrintStep)
                {
                    continue;
                }
                if (currentStep is BeginPostDeploymentScriptStep)
                {
                    break;
                }
                if (beforePreDeploy == null)
                {
                    continue;
                }

                DeploymentScriptDomStep domStep = currentStep as DeploymentScriptDomStep;
                if (domStep == null)
                {
                    continue;
                }

                TSqlScript script = domStep.Script as TSqlScript;
                if (script == null)
                {
                    continue;
                }

                // Loop through all the batches in the script for this step.  All the statements
                // in the batch will be enclosed in an if statement that will check the
                // table to ensure that the batch has not already been executed
                TSqlObject sqlObject;
                string     stepDescription;
                GetStepInfo(domStep, out stepDescription, out sqlObject);
                int batchCount = script.Batches.Count;

                for (int batchIndex = 0; batchIndex < batchCount; batchIndex++)
                {
                    // Create the if statement that will contain the batch's contents
                    IfStatement            ifBatchNotExecutedStatement = CreateIfNotExecutedStatement(batchId);
                    BeginEndBlockStatement statementBlock = new BeginEndBlockStatement();
                    ifBatchNotExecutedStatement.ThenStatement = statementBlock;
                    statementBlock.StatementList = new StatementList();

                    TSqlBatch batch          = script.Batches[batchIndex];
                    int       statementCount = batch.Statements.Count;

                    // Loop through all statements in the batch, embedding those in an sp_execsql
                    // statement that must be handled this way (schemas, stored procedures,
                    // views, functions, and triggers).
                    for (int statementIndex = 0; statementIndex < statementCount; statementIndex++)
                    {
                        TSqlStatement smnt = batch.Statements[statementIndex];

                        if (IsStatementEscaped(sqlObject))
                        {
                            // "escape" this statement by embedding it in a sp_executesql statement
                            string statementScript;
                            domStep.ScriptGenerator.GenerateScript(smnt, out statementScript);
                            ExecuteStatement spExecuteSql = CreateExecuteSql(statementScript);
                            smnt = spExecuteSql;
                        }

                        statementBlock.StatementList.Statements.Add(smnt);
                    }

                    // Add an insert statement to track that all the statements in this
                    // batch were executed.  Turn on nocount to improve performance by
                    // avoiding row inserted messages from the server
                    string batchDescription = string.Format(CultureInfo.InvariantCulture,
                                                            "{0} batch {1}", stepDescription, batchIndex);

                    PredicateSetStatement noCountOff = new PredicateSetStatement();
                    noCountOff.IsOn    = false;
                    noCountOff.Options = SetOptions.NoCount;

                    PredicateSetStatement noCountOn = new PredicateSetStatement();
                    noCountOn.IsOn    = true;
                    noCountOn.Options = SetOptions.NoCount;
                    InsertStatement batchCompleteInsert = CreateBatchCompleteInsert(batchId, batchDescription);
                    statementBlock.StatementList.Statements.Add(noCountOn);
                    statementBlock.StatementList.Statements.Add(batchCompleteInsert);
                    statementBlock.StatementList.Statements.Add(noCountOff);

                    // Remove all the statements from the batch (they are now in the if block) and add the if statement
                    // as the sole statement in the batch
                    batch.Statements.Clear();
                    batch.Statements.Add(ifBatchNotExecutedStatement);

                    // Next batch
                    batchId++;
                }
            }

            // if we found steps that required processing, set up a temporary table to track the work that you are doing
            if (beforePreDeploy != null)
            {
                // Declare a SqlCmd variables.
                //
                // CompletedBatches variable - defines the name of the table in tempdb that will track
                // all the completed batches.  The temporary table's name has the target database name and
                // a guid embedded in it so that:
                // * Multiple deployment scripts targeting different DBs on the same server
                // * Failed deployments with old tables do not conflict with more recent deployments
                //
                // TotalBatchCount variable - the total number of batches surrounded by if statements.  Using this
                // variable pre/post deployment scripts can also use the CompletedBatches table to make their
                // script rerunnable if there is an error during execution
                StringBuilder sqlcmdVars = new StringBuilder();
                sqlcmdVars.AppendFormat(CultureInfo.InvariantCulture, CompletedBatchesSqlCmd,
                                        context.Options.TargetDatabaseName, Guid.NewGuid().ToString("D"));
                sqlcmdVars.AppendLine();
                sqlcmdVars.AppendFormat(CultureInfo.InvariantCulture, TotalBatchCountSqlCmd, batchId);

                DeploymentScriptStep completedBatchesSetVarStep = new DeploymentScriptStep(sqlcmdVars.ToString());
                base.AddBefore(context.PlanHandle, beforePreDeploy, completedBatchesSetVarStep);

                // Create the temporary table we will use to track the work that we are doing
                DeploymentScriptStep createStatusTableStep = new DeploymentScriptStep(CreateCompletedBatchesTable);
                base.AddBefore(context.PlanHandle, beforePreDeploy, createStatusTableStep);
            }

            //   Cleanup and drop the table
            //   DeploymentScriptStep dropStep = new DeploymentScriptStep(DropCompletedBatchesTable);
            //   base.AddAfter(context.PlanHandle, context.PlanHandle.Tail, dropStep);
        }
        private TSqlStatement WrapInBeginEnd(TSqlStatement fragment)
        {
            var beginEnd = new BeginEndBlockStatement();
            beginEnd.StatementList = new StatementList();

            beginEnd.StatementList.Statements.Add(fragment);
            return beginEnd;
        }
 public abstract GlyphDefinition GetDefintions(string fragment, TSqlStatement statement, GlyphDefinition definition, List<DeleteSpecification> queries);
 public abstract GlyphDefinition GetDefinitions(string fragment, TSqlStatement statement, GlyphDefinition definition, List <TSqlStatement> queries);
Example #39
0
        public override void Visit(TSqlStatement node)
        {
            if (node.GetType().Name.StartsWith("Create") || node.GetType().Name.StartsWith("AlterTabl") ||
                node.GetType().Name.StartsWith("AlterProc") || node.GetType().Name.StartsWith("AlterFunc"))
            {
                if (!_topLevelObjects.Any(p => p.Start < node.StartOffset && p.Length > node.FragmentLength))
                {
                    //string script;
                    //_generator.GenerateScript(node, out script);

                    var script = _currentBatch.Substring(node.StartOffset, node.FragmentLength);

                    _topLevelObjects.Add(new fragment_position {Start = node.StartOffset, Length = node.FragmentLength});
                    Statements.Add(script);

                    Console.WriteLine(node);
                }
            }
        }
Example #40
0
 // Generic statement
 public override void Visit(TSqlStatement node)
 {
     DoSomething(node);
     base.Visit(node);
 }
        public override GlyphDefinition GetDefintions(string fragment, TSqlStatement statement, GlyphDefinition definition, List<QuerySpecification> queries)
        {
            var rewriter = new InEqualityRewriter(fragment);
            var replacements = rewriter.GetReplacements(queries);

            if (replacements == null)
                return definition;

            if (replacements.Count > 0)
            {
                definition.Menu.Add(new MenuDefinition()
                {
                    Caption = "Replace != with <>",
                    Action = () => { },
                    Type = MenuItemType.Header
                    ,
                    Glyph = definition
                });

                var offsettedReplacments = new List<Replacements>();

                //span.Snapshot.CreateTrackingSpan(glyph.Tag.ParentTag.Span.Start+offset, _replacement.OriginalLength, SpanTrackingMode.EdgeNegative);
                foreach (var replacement in replacements)
                {
                    var replacement1 = replacement;
                    replacement1.OriginalOffset += statement.StartOffset;
                    offsettedReplacments.Add(replacement1);
                }

                if (replacements.Count > 1)
                {
                    var menu = new MenuDefinition();
                    menu.Operation = new ClippyReplacementOperations(offsettedReplacments);
                    menu.Action = () => PerformAction(menu.Operation, menu.Glyph);

                    menu.Glyph = definition;
                    menu.Caption = GetCaptionForAll(statement);
                    menu.Type = MenuItemType.MenuItem;
                    definition.Menu.Add(menu);
                }


                foreach (var replacement in offsettedReplacments)
                {
                    var menu = new MenuDefinition();
                    menu.Action = () => PerformAction(menu.Operation, menu.Glyph);
                    menu.Glyph = definition;
                    menu.Caption = string.Format("\t\"{0}\" into \"{1}\"", replacement.Original, replacement.Replacement);
                    menu.Type = MenuItemType.MenuItem;
                    Debug.WriteLine("\tLine {2} \"{0}\" into \"{1}\"", replacement.Original, replacement.Replacement, replacement.OriginalFragment.StartLine);
                    menu.Operation = new ClippyReplacementOperation(replacement);
                    
                    definition.Menu.Add(menu);

                }

                definition.GenerateKey();
            }
            return definition;


        }
Example #42
0
        private void ProcessViewStatementBody(TSqlStatement sqlStatement)
        {
            ViewStatementBody aViewStatementBody = (ViewStatementBody)sqlStatement;

            AddLogText("Columns:");
            foreach (Identifier aColumnIdentifier in aViewStatementBody.Columns)
            {
                AddLogText(string.Format("Column:{0}", aColumnIdentifier.Value));
                aColumnInfoList.ColumnList.Add(new ColumnInfo {
                    Alias = aColumnIdentifier.Value
                });
            }

            AddLogText("");
            AddLogText("QueryExpression SelectElements:");
            SelectStatement aSelectStatement = aViewStatementBody.SelectStatement;
            QueryExpression aQueryExpression = aSelectStatement.QueryExpression;

            if (aQueryExpression.GetType() == typeof(QuerySpecification))
            {
                QuerySpecification aQuerySpecification = (QuerySpecification)aQueryExpression;
                int aSelectElementID = 0;
                foreach (SelectElement aSelectElement in aQuerySpecification.SelectElements)
                {
                    if (aSelectElement.GetType() == typeof(SelectScalarExpression))
                    {
                        SelectScalarExpression aSelectScalarExpression = (SelectScalarExpression)aSelectElement;

                        string identStr = string.Empty;
                        IdentifierOrValueExpression aIdentifierOrValueExpression =
                            aSelectScalarExpression.ColumnName;
                        if (aIdentifierOrValueExpression != null)
                        {
                            if (aIdentifierOrValueExpression.ValueExpression == null)
                            {
                                AddLogText(string.Format("Identifier={0}",
                                                         aIdentifierOrValueExpression.Identifier.Value));
                                identStr = aIdentifierOrValueExpression.Identifier.Value;
                            }
                            else
                            {
                                AddLogText("Expression");
                            }
                        }
                        aColumnInfoList.AddIfNeeded(aSelectElementID, identStr);

                        ScalarExpression aScalarExpression = aSelectScalarExpression.Expression;
                        PrintSelectScalarExperssionRecurse(aSelectElementID, aScalarExpression);
                    }
                    else
                    {
                        aColumnInfoList.AddIfNeeded(aSelectElementID,
                                                    "Error, something else than SelectScalarExpression found");
                        AddLogText("We only support SelectScalarExpression.");
                    }
                    aSelectElementID = aSelectElementID + 1;
                    AddLogText("");
                }
                AddLogText("");
                AddLogText("Table References:");
                FromClause aFromClause = aQuerySpecification.FromClause;
                foreach (TableReference aTableReference in aFromClause.TableReferences)
                {
                    PrintTableReferenceRecurse(aTableReference);
                }
            }
            aColumnInfoList.FillEmptyAlias();
        }//function
Example #43
0
 public override GlyphDefinition GetDefinitions(string fragment, TSqlStatement statement, GlyphDefinition definition, List<TSqlStatement> queries)
 {
     return definition;
 }
 public abstract GlyphDefinition GetDefinitions(string fragment, TSqlStatement statement, GlyphDefinition definition, List<TSqlStatement> queries);
Example #45
0
        public static List<TableReference> GetTableList(TSqlStatement script)
        {
            var tables = new List<TableReference>();
            
            var parser = new TSql130Parser(false);
            
            var visitor = new EnumeratorVisitor();
            script.Accept(visitor);

            foreach (var statement in visitor.Nodes)
            {
                tables.AddRange(FindTableReferences(statement));
            }

            return tables;
        }
Example #46
0
 public override void Visit(TSqlStatement node)
 {
     Statements.Add(node);
 }
Example #47
0
        public override GlyphDefinition GetDefintions(string fragment, TSqlStatement statement, GlyphDefinition definition, List <QuerySpecification> queries)
        {
            var rewriter     = new InEqualityRewriter(fragment);
            var replacements = rewriter.GetReplacements(queries);

            if (replacements == null)
            {
                return(definition);
            }

            if (replacements.Count > 0)
            {
                definition.Menu.Add(new MenuDefinition()
                {
                    Caption = "Replace != with <>",
                    Action  = () => { },
                    Type    = MenuItemType.Header
                    ,
                    Glyph = definition
                });

                var offsettedReplacments = new List <Replacements>();

                //span.Snapshot.CreateTrackingSpan(glyph.Tag.ParentTag.Span.Start+offset, _replacement.OriginalLength, SpanTrackingMode.EdgeNegative);
                foreach (var replacement in replacements)
                {
                    var replacement1 = replacement;
                    replacement1.OriginalOffset += statement.StartOffset;
                    offsettedReplacments.Add(replacement1);
                }

                if (replacements.Count > 1)
                {
                    var menu = new MenuDefinition();
                    menu.Operation = new ClippyReplacementOperations(offsettedReplacments);
                    menu.Action    = () => PerformAction(menu.Operation, menu.Glyph);

                    menu.Glyph   = definition;
                    menu.Caption = GetCaptionForAll(statement);
                    menu.Type    = MenuItemType.MenuItem;
                    definition.Menu.Add(menu);
                }


                foreach (var replacement in offsettedReplacments)
                {
                    var menu = new MenuDefinition();
                    menu.Action  = () => PerformAction(menu.Operation, menu.Glyph);
                    menu.Glyph   = definition;
                    menu.Caption = string.Format("\t\"{0}\" into \"{1}\"", replacement.Original, replacement.Replacement);
                    menu.Type    = MenuItemType.MenuItem;
                    Debug.WriteLine("\tLine {2} \"{0}\" into \"{1}\"", replacement.Original, replacement.Replacement, replacement.OriginalFragment.StartLine);
                    menu.Operation = new ClippyReplacementOperation(replacement);

                    definition.Menu.Add(menu);
                }

                definition.GenerateKey();
            }
            return(definition);
        }
 public abstract GlyphDefinition GetDefintions(string fragment, TSqlStatement statement, GlyphDefinition definition, List <DeleteSpecification> queries);
 public override GlyphDefinition GetDefinitions(string fragment, TSqlStatement statement, GlyphDefinition definition, List <TSqlStatement> queries)
 {
     return(definition);
 }
Example #50
0
 public override void Visit(TSqlStatement node)
 {
     StatementCount++;
 }
Example #51
0
        public static IEnumerable <SchemaObject> CollectLocalSchema(this TSqlStatement statement, ILogger logger, SchemaFile file)
        {
            switch (statement)
            {
            case BeginEndBlockStatement beginEndBlockStatement:
                return(beginEndBlockStatement
                       .StatementList
                       .Statements
                       .CollectLocalSchema(logger, file)
                       .ToList());

            case DeclareVariableStatement declareVariableStatement:
            {
                foreach (var declaration in declareVariableStatement.Declarations)
                {
                    var name       = declaration.VariableName.Value;
                    var isNullable = false;         // TODO : how to determine this?
                    var variable   = declaration.DataType.GetField(name, isNullable, logger, file);
                    variable.Origin = OriginType.Variable;

                    file.FileContext.Variables.Peek().Add(variable);
                }

                // TODO : what should I return here?
                break;
            }

            case DeclareTableVariableStatement declareTableVariableStatement:
            {
                var columns = declareTableVariableStatement
                              .Body
                              .Definition
                              .ColumnDefinitions
                              .GetFields(logger, file)
                              .ToList();

                var tableReference = new Table()
                {
                    Columns    = columns,
                    File       = file,
                    Database   = SchemaObject.TempDb,
                    Schema     = SchemaObject.DefaultSchema,
                    Identifier = declareTableVariableStatement.Body.VariableName.Value,
                };

                var field = new TableReferenceField()
                {
                    Name       = declareTableVariableStatement.Body.VariableName.Value,
                    Type       = FieldType.Table,
                    Origin     = OriginType.Variable,
                    IsNullable = false,
                    Reference  = tableReference,
                };

                file.FileContext.Variables.Peek().Add(field);

                // TODO : what should I return here?
                break;
            }

            // TODO : this could be an actual create table statement and not just a temp table
            case CreateTableStatement createTableStatement:
            {
                if (!createTableStatement.SchemaObjectName.BaseIdentifier.Value.StartsWith("#"))
                {
                    break;         // not a temp table
                }

                var columns = createTableStatement
                              .Definition
                              .ColumnDefinitions
                              .GetFields(logger, file)
                              .ToList();

                columns.ForEach(c => c.Origin = OriginType.Table);

                var tempTable = new TemporaryTable()
                {
                    Database   = createTableStatement.SchemaObjectName.DatabaseIdentifier?.Value ?? SchemaObject.TempDb,
                    Schema     = createTableStatement.SchemaObjectName.SchemaIdentifier?.Value ?? SchemaObject.DefaultSchema,
                    Identifier = createTableStatement.SchemaObjectName.BaseIdentifier.Value,
                    File       = file,
                    Columns    = columns,
                };

                file
                .LocalSchema
                .Add(new KeyValuePair <string, SchemaObject>(tempTable.GetQualifiedIdentfier(), tempTable));

                break;
            }

            case IfStatement ifStatement:
            {
                // TODO : conditional output? which data set to return? we don't know till runtime
                var thenReferences = ifStatement.ThenStatement.CollectLocalSchema(logger, file).ToList();

                if (ifStatement.ElseStatement != null)
                {
                    var elseReferences = ifStatement.ElseStatement.CollectLocalSchema(logger, file).ToList();
                    return(thenReferences.Concat(elseReferences));
                }

                return(thenReferences);
            }

            case SelectStatement selectStatement:
            {
                var columns = selectStatement.GetFields(logger, file);

                if (!columns.Any())
                {
                    // if there are no columns there's no data set to return..
                    // this happens for SELECT statement that assigns values to variables
                    break;
                }

                if (selectStatement.Into != null &&
                    selectStatement.Into.BaseIdentifier.Value.StartsWith("#") &&
                    !file.LocalSchema.ContainsKey(selectStatement.Into.GetTemporaryQualifiedIdentfier()))
                {
                    var tempTableColumns = selectStatement.GetFields(logger, file);;
                    var tempTable        = new TemporaryTable()
                    {
                        Columns    = tempTableColumns,
                        File       = file,
                        Database   = SchemaObject.TempDb,
                        Schema     = SchemaObject.DefaultSchema,
                        Identifier = selectStatement.Into.BaseIdentifier.Value,
                    };

                    file
                    .LocalSchema
                    .Add(new KeyValuePair <string, SchemaObject>(tempTable.GetQualifiedIdentfier(), tempTable));
                }

                var dataSet = new DerivedTable()
                {
                    Columns    = columns,
                    File       = file,
                    Identifier = selectStatement.GetTokenText(),
                };

                return(new List <SchemaObject>()
                    {
                        dataSet
                    });
            }

            case WhileStatement whileStatement:
                return(whileStatement.Statement.CollectLocalSchema(logger, file));

            case TryCatchStatement tryCatchStatement:
            {
                var tryReferences   = tryCatchStatement.TryStatements.Statements.CollectLocalSchema(logger, file);
                var catchReferences = tryCatchStatement.CatchStatements.Statements.CollectLocalSchema(logger, file);
                return(tryReferences.Concat(catchReferences).ToList());
            }

            case ReturnStatement x:
            {
                // TODO : check this statement, do I want to stop collecting data sets now?
                // what if it is conditinal return statement?
                break;
            }

            case MergeStatement mergeStatement:
                break;     // TODO : what to do with this one?

            // NOTE : I don't care about these statements yet
            case PredicateSetStatement x: break;

            case SetVariableStatement x: break;

            case SetCommandStatement x: break;

            case SetRowCountStatement x: break;

            case UseStatement x: break;

            case DenyStatement x: break;

            case RevokeStatement x: break;

            case SetIdentityInsertStatement x: break;

            case SetTransactionIsolationLevelStatement x: break;

            case BeginTransactionStatement x: break;

            case RollbackTransactionStatement x: break;

            case CommitTransactionStatement x: break;

            case RaiseErrorStatement x: break;

            case ThrowStatement x: break;

            case BreakStatement x: break;

            case ContinueStatement x: break;

            case SaveTransactionStatement x: break;

            case UpdateStatisticsStatement x: break;

            case InsertStatement x: break;

            case UpdateStatement x: break;

            case DeleteStatement x: break;

            case ExecuteStatement x: break;

            case GrantStatement x: break;

            case CreateIndexStatement x: break;

            case GoToStatement x: break;

            case LabelStatement x: break;

            case PrintStatement x: break;

            case DeclareCursorStatement x: break;

            case OpenCursorStatement x: break;

            case FetchCursorStatement x: break;

            case CloseCursorStatement x: break;

            case DeallocateCursorStatement x: break;

            case WaitForStatement x: break;

            case BeginDialogStatement x: break;

            case SendStatement x: break;

            case EndConversationStatement x: break;

            // TODO : statements to generate schema.. might be useful for sql in the test project
            case TruncateTableStatement x: break;

            case DropTableStatement x: break;

            case DropViewStatement x: break;

            case CreateFunctionStatement x: break;

            case AlterFunctionStatement x: break;

            case CreateOrAlterFunctionStatement x: break;

            case DropFunctionStatement x: break;

            case AlterTableAddTableElementStatement x: break;

            case AlterTableConstraintModificationStatement x: break;

            case CreateTypeTableStatement x: break;

            case CreateViewStatement x: break;

            case AlterViewStatement x: break;

            case DropProcedureStatement x: break;

            case CreateProcedureStatement x: break;

            case CreateOrAlterProcedureStatement x: break;

            case CreateOrAlterViewStatement x: break;

            case AlterTableSetStatement x: break;

            case AlterProcedureStatement x: break;

            case CreateTypeUddtStatement x: break;

            default:
            {
                logger.Log(LogLevel.Warning,
                           LogType.NotSupportedYet,
                           file.Path,
                           $"\"{statement.GetType()}\" Tsql statement is not supported yet. " +
                           $"Fragment: \"{statement.GetTokenText()}\"");
                break;
            }
            }

            return(new List <SchemaObject>());
        }
Example #52
0
 public override void Visit(TSqlStatement node)
 {
     base.Visit(node);
 }