private void BuildEqualsSameLiteral(BooleanExpression search, ScalarExpression firstParam, Literal literal)
        {
            var newExpression = new BooleanParenthesisExpression();
            var expression    = new BooleanBinaryExpression();

            newExpression.Expression = expression;

            expression.BinaryExpressionType = BooleanBinaryExpressionType.Or;
            var isnull = new BooleanIsNullExpression();

            isnull.Expression          = firstParam;
            expression.FirstExpression = isnull;

            var second = new BooleanComparisonExpression();

            second.FirstExpression      = firstParam;
            second.SecondExpression     = literal;
            expression.SecondExpression = second;

            var sql = ScriptDom.GenerateTSql(newExpression);

            _replacementsToMake.Add(new Replacements
            {
                Original         = _script.Substring(search.StartOffset, search.FragmentLength),
                OriginalLength   = search.FragmentLength,
                OriginalOffset   = search.StartOffset,
                Replacement      = sql,
                OriginalFragment = _currentFragment
            });
        }
Beispiel #2
0
        public string ExtractIntoFunction()
        {
            var browser = new SolutionBrowserForm("");

            browser.ShowDialog();

            var destination = browser.DestinationItem;

            if (destination == null)
            {
                return(null);
            }

            var name = browser.GetObjectName();

            var function     = new CreateFunctionStatement();
            var returnSelect = (function.ReturnType = new SelectFunctionReturnType()) as SelectFunctionReturnType;

            returnSelect.SelectStatement = GetSelectStatementForQuery();
            function.Name = name.ToSchemaObjectName();

            var classFolder = destination.ProjectItems.AddFromTemplate("Procedure", name.UnQuote() + ".sql");
            var filePath    = classFolder.GetStringProperty("FullPath");

            File.WriteAllText(filePath, ScriptDom.GenerateTSql(function));

            classFolder.Open().Visible = true;

            return(GetCallingCode(function));
        }
Beispiel #3
0
        private void RewriteNonSargableIsNull(object sender, EventArgs e)
        {
            try
            {
                var oldDoc = GetCurrentDocumentText();
                var newDoc = oldDoc;

                var rewriter = new NonSargableRewrites(oldDoc);
                var queries  = ScriptDom.GetQuerySpecifications(oldDoc);
                foreach (var rep in rewriter.GetReplacements(queries))
                {
                    newDoc = newDoc.Replace(rep.Original, rep.Replacement);
                    OutputPane.WriteMessage("Non-Sargable IsNull re-written from \r\n\"{0}\" \r\nto\r\n\"{1}\"\r\n", rep.Original, rep.Replacement);
                }

                if (oldDoc != newDoc)
                {
                    SetCurrentDocumentText(newDoc);
                }
            }
            catch (Exception ex)
            {
                OutputPane.WriteMessage("Error re-writing non sargable isnulls {0}", ex.Message);
            }
        }
Beispiel #4
0
        public static string KeywordsToLower(string script)
        {
            var fragment = ScriptDom.GetFragment(script);

            var builder = new StringBuilder();

            foreach (var t in fragment.ScriptTokenStream)
            {
                if (string.IsNullOrEmpty(t.Text))
                {
                    continue;
                }

                if (IsKeyword(t))
                {
                    builder.Append(t.Text.ToLowerInvariant());
                }
                else
                {
                    builder.Append(t.Text);
                }
            }

            return(builder.ToString());
        }
Beispiel #5
0
        /// <summary>
        /// 开始编译
        /// </summary>
        public void BeginCompile()
        {
            foreach (FileInfo src in opt.Sources)
            {
                OnCompileSource?.Invoke(src.Name);
                FileStream srcStream = src.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
                TextReader r         = new StreamReader(srcStream, Encoding.UTF8, false);
                using Parser p = new(r);

                if (p.Parse())
                {
                    errors.AddRange(p.Errors);
                    OnErrorsAdded?.Invoke(p.Errors);

                    ScriptDom dom = p.Dom;
                    try
                    {
                        BackendRecord backendFactory;

                        if (opt.BackendName == null)
                        {
                            backendFactory = select_factory(opt.TargetEngine ?? dom.Metadata.TargetEngine,
                                                            opt.TargetLanguage, opt.BackendVersion);
                        }
                        else
                        {
                            backendFactory = backends.Find((b) => b.Name == opt.BackendName) ??
                                             select_factory(opt.TargetEngine ?? dom.Metadata.TargetEngine,
                                                            opt.TargetLanguage, opt.BackendVersion);
                        }

                        Backend.IBackend backend = backendFactory.Factory.CreateBackend(
                            OutputDirectory, opt.TargetLanguage);
                        backend.Compile(dom);

                        if (backend.HasCriticialError)
                        {
                            errors.AddRange(backend.Errors);
                            OnErrorsAdded?.Invoke(backend.Errors);
                            continue;
                        }
                    }
                    catch (BackendNotFoundException e)
                    {
                        errors.Add(new CompilerDriverError(9013, ErrorServiety.CritialError,
                                                           e.ToString(), new string[] { e.Engine, e.Version }));
                        OnErrorsAdded?.Invoke(errors.GetRange(errors.Count - 1, 1));
                    }
                }
                else
                {
                    var errs = p.Errors;
                    errors.AddRange(errs);
                    OnErrorsAdded?.Invoke(errs);
                    continue;
                }
            }
            OnComplete?.Invoke();
        }
        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);
        }
Beispiel #7
0
        public void DoWork()
        {
            _stop   = false;
            Stopped = false;

            while (!_stop)
            {
                while (!_queuedRequests.IsEmpty)
                {
                    string text;
                    _queuedRequests.TryPop(out text);

                    if (string.IsNullOrEmpty(text))
                    {
                        continue;
                    }

                    if (_definitions.ContainsKey(text))
                    {
                        continue; //already done it....
                    }
                    try
                    {
                        IList <ParseError> errors;
                        var statements = ScriptDom.GetStatements(text, out errors);
                        if (statements.Count > 0)
                        {
                            var glyphDefinitions = GetGlyphDefinitions(statements, text);

                            _definitions[text] = glyphDefinitions;
                        }
                    }
                    catch (Exception e)
                    {
                        //hmmmmm
                    }
                    var rePop    = new string[5];
                    var clearPop = new string[100];

                    if (_queuedRequests.Count > 10)
                    {
                        var count = _queuedRequests.TryPopRange(rePop);

                        while (_queuedRequests.Count > 10)
                        {
                            _queuedRequests.TryPopRange(clearPop);
                        }

                        _queuedRequests.PushRange(rePop, 0, count - 1);
                    }
                }

                _event.WaitOne();
            }

            Stopped = true;
        }
Beispiel #8
0
        private static double AddChildItems(string name, CodeStatement <TSqlStatement> sqlModule, CodeCoverageStore store, double parentStatements, string file, TreeViewItem child, ref double parentCoveredStatements, ref double childStatements, ref double childCoveredStatements)
        {
            if (string.IsNullOrEmpty(name))
            {
                return(parentStatements);
            }

            //need to enumerate the statement tree to find statements (flatten tree - have probably already done it?? maybe can just use a visitor - see count lines of code surely?)
            var script = File.ReadAllText(sqlModule.FileName);

            if (script.Length < sqlModule.Length)
            {
                //bad tings....
                return(parentStatements);
            }

            IList <ParseError> errors;
            var statementNodes = ScriptDom.GetStatements(script.Substring(sqlModule.StartLocation, sqlModule.Length), out errors);

            if (errors != null && errors.Count > 1)
            {
                //more bad tings
                return(parentStatements);
            }

            var coveredStatements = store.GetCoveredStatements(name, sqlModule.FileName);

            var beginEndBlocks = statementNodes.Count(p => p.GetType() == typeof(BeginEndBlockStatement));

            var statementCount = statementNodes.Count - 1 - beginEndBlocks;



            parentStatements        += statementCount;
            parentCoveredStatements += coveredStatements?.Count ?? 0;

            childStatements        += statementCount;
            childCoveredStatements += coveredStatements?.Count ?? 0;
            //if the file has changed we can't get anything useful from it...
            if (coveredStatements != null && coveredStatements.Count > 0 && !coveredStatements.Any(p => p.TimeStamp < File.GetLastWriteTimeUtc(file)))
            {
                var coveragePercent = ((double)coveredStatements.Count / (double)statementCount) * 100;

                var label = new LabelWithProgressIndicator(string.Format("{0} - {1}% ({2} / {3})", name, coveragePercent, coveredStatements.Count, statementCount), coveragePercent, file);
                label.Configure();

                child.Items.Add(label);
            }
            else
            {
                var label = new LabelWithProgressIndicator(name + " - 0 %", 0, file);
                label.Configure();
                child.Items.Add(label);
            }
            return(parentStatements);
        }
Beispiel #9
0
        public static void DeployFile(string newCode)
        {
            if (String.IsNullOrEmpty(ConnectionString))
            {
                var connectDialog = new ConnectDialog();
                connectDialog.ShowDialog();
                ConnectionString = connectDialog.ConnectionString;

                if (String.IsNullOrEmpty(ConnectionString))
                {
                    return;
                }
            }

            var procedures    = ScriptDom.GetProcedures(newCode);
            var deployScripts = new List <string>();

            foreach (var procedure in procedures)
            {
                OutputPane.WriteMessage("Deploying {0}", procedure.ProcedureReference.Name.ToQuotedString());
                Deploy(BuildIfNotExistsStatements(procedure));
                Deploy(ChangeCreateToAlter(procedure, newCode));
                OutputPane.WriteMessage("Deploying {0}...Done", procedure.ProcedureReference.Name.ToQuotedString());
            }

            var functions = ScriptDom.GetFunctions(newCode);

            foreach (var function in functions)
            {
                OutputPane.WriteMessage("Deploying {0}", function.Name.ToQuotedString());
                if (function.ReturnType is SelectFunctionReturnType)
                {
                    Deploy(BuildIfNotExistsStatementsInlineFunction(function));
                }
                else
                {
                    Deploy(BuildIfNotExistsStatements(function));
                }

                Deploy(ChangeCreateToAlter(function, newCode));
                OutputPane.WriteMessage("Deploying {0}...Done", function.Name.ToQuotedString());
            }

            foreach (var statement in deployScripts)
            {
                Deploy(statement);
            }
            //Deploy();
        }
Beispiel #10
0
        private string GetCallingCode(CreateFunctionStatement function)
        {
            var callingSelect = new SelectStatement();
            var spec          = (callingSelect.QueryExpression = new QuerySpecification()) as QuerySpecification;

            spec.FromClause = new FromClause();
            spec.FromClause.TableReferences.Add(new SchemaObjectFunctionTableReference()
            {
                SchemaObject = function.Name
            });

            spec.SelectElements.Add(new SelectStarExpression());

            return(ScriptDom.GenerateTSql(spec));
        }
Beispiel #11
0
        private List <GlyphDefinition> GetGlyphDefinitions(List <TSqlStatement> statements, string script)
        {
            var definitions = new List <GlyphDefinition>();

            foreach (var statement in statements)
            {
                var definition = new GlyphDefinition();
                definition.Line            = statement.StartLine;
                definition.StatementOffset = statement.StartOffset;
                definition.Type            = GlyphDefinitonType.Normal;
                definition.LineCount       = statement.ScriptTokenStream.LastOrDefault().Line - definition.Line;
                definition.StatementLength = statement.FragmentLength;

                var fragment           = script.Substring(statement.StartOffset, statement.FragmentLength);
                var queriesInStatement = ScriptDom.GetQuerySpecifications(fragment);
                var deletes            = ScriptDom.GetDeleteStatements(fragment);

                foreach (var operation in _operations)
                {
                    try
                    {
                        definition = operation.GetDefintions(fragment, statement, definition, queriesInStatement);
                        definition = operation.GetDefintions(fragment, statement, definition, deletes);

                        definition = operation.GetDefinitions(fragment, statement, definition, new List <TSqlStatement>()
                        {
                            statement
                        });
                    }
                    catch (Exception e)
                    {
                    }
                }


                definitions.Add(definition);
            }

            return(definitions);
        }
        public void ShowDuplicateIndexes()
        {
            var statements = new StatementEnumerator().GetIndexes();

            var indexes = new Dictionary <string, List <CodeStatement <CreateIndexStatement> > >();

            foreach (var statement in statements)
            {
                var key = BuildKey(statement.Statement);

                if (indexes.ContainsKey(key))
                {
                    indexes[key].Add(statement);
                }
                else
                {
                    indexes[key] = new List <CodeStatement <CreateIndexStatement> > {
                        statement
                    };
                }
            }

            var dups = indexes.Where(p => p.Value.Count > 1);

            foreach (var d in dups)
            {
                OutputPane.WriteMessage("Duplicate Indexes Found: ");

                foreach (var statement in d.Value)
                {
                    OutputPane.WriteMessageWithLink(statement.FileName, statement.Line, "{0}",
                                                    ScriptDom.GenerateTSql(statement.Statement));
                }
            }

            if (dups == null || !dups.Any())
            {
                OutputPane.WriteMessage("No Duplicate Indexes Found.");
            }
        }
Beispiel #13
0
        public static string GetDeployScript(string newCode)
        {
            var procedures    = ScriptDom.GetProcedures(newCode);
            var deployScripts = new List <string>();

            foreach (var procedure in procedures)
            {
                OutputPane.WriteMessage("Generating Deploy Script for {0}", procedure.ProcedureReference.Name.ToQuotedString());
                deployScripts.Add(BuildIfNotExistsStatements(procedure));
                deployScripts.Add(ChangeCreateToAlter(procedure, newCode));
            }

            var functions = ScriptDom.GetFunctions(newCode);

            foreach (var function in functions)
            {
                OutputPane.WriteMessage("Generating script for {0}", function.Name.ToQuotedString());
                if (function.ReturnType is SelectFunctionReturnType)
                {
                    deployScripts.Add(BuildIfNotExistsStatementsInlineFunction(function));
                }
                else
                {
                    deployScripts.Add(BuildIfNotExistsStatements(function));
                }

                deployScripts.Add(ChangeCreateToAlter(function, newCode));
            }

            StringBuilder script = new StringBuilder();

            foreach (var statement in deployScripts)
            {
                script.AppendFormat("{0}\r\nGO\r\n", statement);
            }

            return(script.ToString());
        }
Beispiel #14
0
 public void Compile(ScriptDom dom)
 {
 }
Beispiel #15
0
 private SelectStatement GetSelectStatementForQuery()
 {
     return(ScriptDom.GetSelects(_code).FirstOrDefault());
 }
Beispiel #16
0
        protected override void UpdateWordAdornments()
        {
            try
            {
                var dte = (DTE)VsServiceProvider.Get(typeof(DTE));

                if (dte.ActiveDocument == null)
                {
                    return;
                }

                if (RequestedPoint.Snapshot.ContentType.TypeName != "SQL Server Tools" || !RequestedPoint.Snapshot.ContentType.BaseTypes.Any(p => p.IsOfType("code")))
                {
                    return;
                }



                try
                {
                    var store = CodeCoverageStore.Get;

                    var path = dte.ActiveDocument.FullName;

                    if (store.ObjectsInFile(path) == null)
                    {
                        return;
                    }

                    var yellowWordSpans = new List <SnapshotSpan>();
                    var redWordSpans    = new List <SnapshotSpan>();

                    if (null != store && CodeCoverageTaggerSettings.Enabled)
                    {
                        var documentKey = string.Format("{0}:{1}", RequestedPoint.Snapshot.Length, RequestedPoint.Snapshot.Version.VersionNumber);

                        var script = GetCurrentDocumentText(dte);

                        foreach (var proc in ScriptDom.GetProcedures(script))
                        {
                            var name = proc?.ProcedureReference.Name.ToNameString();

                            if (string.IsNullOrEmpty(name))
                            {
                                continue;
                            }

                            var statements = store.GetCoveredStatements(name, path);

                            if (statements == null)
                            {
                                continue;
                            }

                            if (statements.Any(p => p.TimeStamp < File.GetLastWriteTimeUtc(path)))
                            {
                                continue;
                            }

                            foreach (var statement in statements)
                            {
                                var offset = proc.StartOffset + (int)statement.Offset;
                                if (offset + statement.Length > script.Length)
                                {
                                    continue; //bad things!
                                }
                                if (statement.Length > -1)
                                {
                                    var span = new SnapshotSpan(new SnapshotPoint(RequestedPoint.Snapshot, offset), (int)statement.Length + 1);
                                    yellowWordSpans.Add(span);
                                }
                                else
                                {
                                    var span = new SnapshotSpan(new SnapshotPoint(RequestedPoint.Snapshot, offset), (proc.FragmentLength - offset));
                                    yellowWordSpans.Add(span);
                                }
                            }
                        }

                        foreach (var proc in ScriptDom.GetFunctions(script))
                        {
                            var name = proc?.Name.ToNameString();

                            if (string.IsNullOrEmpty(name))
                            {
                                continue;
                            }

                            var statements = store.GetCoveredStatements(name, path);

                            if (statements == null)
                            {
                                continue;
                            }

                            foreach (var statement in statements)
                            {
                                var offset = proc.StartOffset + (int)statement.Offset;
                                if (offset + statement.Length > script.Length)
                                {
                                    continue; //bad things!
                                }
                                if (statement.Length > -1)
                                {
                                    var span = new SnapshotSpan(new SnapshotPoint(RequestedPoint.Snapshot, offset), (int)statement.Length + 1);
                                    yellowWordSpans.Add(span);
                                }
                                else
                                {
                                    var span = new SnapshotSpan(new SnapshotPoint(RequestedPoint.Snapshot, offset), (proc.FragmentLength - offset) + 1);
                                    yellowWordSpans.Add(span);
                                }
                            }
                        }

                        if (documentKey != string.Format("{0}:{1}", RequestedPoint.Snapshot.Length, RequestedPoint.Snapshot.Version.VersionNumber))
                        {
                            return;
                        }
                    }



                    var currentRequest = RequestedPoint;
                    var word           = TextStructureNavigator.GetExtentOfWord(currentRequest);
                    var currentWord    = word.Span;

                    //If another change hasn't happened, do a real update
                    if (currentRequest == RequestedPoint)
                    {
                        SynchronousUpdate(currentRequest, new NormalizedSnapshotSpanCollection(yellowWordSpans), new NormalizedSnapshotSpanCollection(redWordSpans), currentWord);
                    }
                }

                catch (Exception)
                {
                    // MessageBox.Show("2 - e : " + e.Message + " \r\n " + e.StackTrace);
                }
            }
            catch (Exception)
            {
                // MessageBox.Show("2 - e : " + e.Message + " \r\n " + e.StackTrace);
            }
        }
        private string buildChunkedDelete(DeleteSpecification delete)
        {
            var counter         = new DeclareVariableStatement();
            var counterVariable = new DeclareVariableElement();

            counterVariable.DataType = new SqlDataTypeReference()
            {
                SqlDataTypeOption = SqlDataTypeOption.Int
            };
            counterVariable.VariableName = new Identifier()
            {
                Value = "@rowcount"
            };
            counterVariable.Value = new IntegerLiteral()
            {
                Value = "10000"
            };
            counter.Declarations.Add(counterVariable);

            delete.TopRowFilter            = new TopRowFilter();
            delete.TopRowFilter.Expression = new ParenthesisExpression()
            {
                Expression = new IntegerLiteral()
                {
                    Value = "10000"
                }
            };

            var setCounter = new SetVariableStatement();

            setCounter.Variable = new VariableReference()
            {
                Name = "@rowcount"
            };
            setCounter.Expression = new GlobalVariableExpression()
            {
                Name = "@@rowcount"
            };
            setCounter.AssignmentKind = AssignmentKind.Equals;

            var deleteStatement = new DeleteStatement();

            deleteStatement.DeleteSpecification = delete;

            var beginEnd = new BeginEndBlockStatement();

            beginEnd.StatementList = new StatementList();
            beginEnd.StatementList.Statements.Add(deleteStatement);
            beginEnd.StatementList.Statements.Add(setCounter);

            var whilePredicate = new BooleanComparisonExpression();

            whilePredicate.ComparisonType  = BooleanComparisonType.GreaterThan;
            whilePredicate.FirstExpression = new VariableReference()
            {
                Name = "@rowcount"
            };
            whilePredicate.SecondExpression = new IntegerLiteral()
            {
                Value = "0"
            };

            var whileStatement = new WhileStatement();

            whileStatement.Predicate = whilePredicate;
            whileStatement.Statement = beginEnd;

            var text = ScriptDom.GenerateTSql(counter) + "\r\n" + ScriptDom.GenerateTSql(whileStatement);

            return(text);
        }
        public void CorrectCaseAllTableNames()
        {
            var statements = new StatementEnumerator().GetStatements();

            var dacTables = new List <TableDescriptor>();

            foreach (var project in new ProjectEnumerator().Get(ProjectType.SSDT))
            {
                try
                {
                    var path = DacpacPath.Get(project);
                    dacTables.AddRange(new TableRepository(path).Get());
                }
                catch (Exception ex)
                {
                    OutputPane.WriteMessage("Error getting list of tables in project: {0}, error: {1}", project.Name, ex.Message);
                }
            }

            var alreadyChanged = new Dictionary <string, object>();


            foreach (var statement in statements.OrderByDescending(p => p.Statement.StartOffset))
            {
                var scriptTables = ScriptDom.GetTableList(statement.Statement).Where(p => p is NamedTableReference).Cast <NamedTableReference>().ToList();

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


                var approvedReplacements = new List <Replacements>();

                foreach (var replacement in replacements)
                {
                    var key = string.Format("{0}:{1}:{2}", statement.FileName, replacement.OriginalOffset, replacement.OriginalLength);

                    if (alreadyChanged.ContainsKey(key))
                    {
                        continue;
                    }

                    approvedReplacements.Add(replacement);
                    alreadyChanged[key] = null;
                }

                if (approvedReplacements.Count > 0)
                {
                    var script = File.ReadAllText(statement.FileName);
                    OutputPane.WriteMessage("File: {0}", statement.FileName);
                    foreach (var replacement in approvedReplacements.OrderByDescending(p => p.OriginalOffset))
                    {
                        var from = script.Substring(replacement.OriginalOffset, replacement.OriginalLength);

                        var to = replacement.Replacement;
                        OutputPane.WriteMessageWithLink(statement.FileName, statement.Line, "\tChanging case of {0} to {1}", from, to);
                        script = script.Substring(0, replacement.OriginalOffset) + to + script.Substring(replacement.OriginalOffset + replacement.OriginalLength);
                    }

                    File.WriteAllText(statement.FileName, script);
                }
            }
        }