Ejemplo n.º 1
0
        private void NodeAction(TSqlFragment node)
        {
            List<ISkimmer<SqlFileContext>> skimmersList;

            if (node == null) { return; }

            if (this.typeToSkimmersMap.TryGetValue(node.GetType(), out skimmersList))
            {
                foreach (ISqlSkimmer skimmer in skimmersList)
                {
                    this.context.Fragment = node;
                    try
                    {
                        skimmer.Analyze(this.context);
                    }
                    catch (Exception ex)
                    {
                        RuntimeErrors |= AnalyzeCommand.LogUnhandledRuleExceptionAnalyzingTarget(
                            this.disabledSkimmers,
                            this.context,
                            skimmer,
                            ex);
                    }
                }
            }
        }
        private TableNameDeclareCheckVisitor visitTSql(string tsql)
        {
            TSqlParser parser = new TSql100Parser(false);

            IList <ParseError> errors;
            TextReader         reader = new StringReader(tsql);

            TSqlFragment parsed = parser.Parse(reader, out errors);

            if (errors.Count != 0)
            {
                string errorMessage = "";
                foreach (ParseError error in errors)
                {
                    errorMessage = errorMessage + "\n" + error.Line + " : " + error.Message;
                }
                throw new Exception("パース失敗\n" + errorMessage);
            }

            TableNameDeclareCheckVisitor visitor = new TableNameDeclareCheckVisitor();

            parsed.Accept(visitor);

            return(visitor);
        }
        private void ParseDelete(string query)
        {
            TSqlFragment tree = InitiateTSql110Parser(query);

            if (SyntaxError)
            {
                return;
            }

            if (tree is TSqlScript)
            {
                TSqlScript tSqlScript = tree as TSqlScript;
                foreach (TSqlBatch sqlBatch in tSqlScript.Batches)
                {
                    foreach (TSqlStatement sqlStatement in sqlBatch.Statements)
                    {
                        ParseSqlDeleteStatement(sqlStatement);
                    }
                }
            }
            RbacTSqlFragmentVisitor rbacTSqlFragmentVisitor = new RbacTSqlFragmentVisitor();

            tree.Accept(rbacTSqlFragmentVisitor);
            this.Warnings.AddRange(rbacTSqlFragmentVisitor.Warnings);

            TablesReferred = new List <RbacTable>(TablesReferred.DistinctBy(t => t.Name));
            IsParsed       = true;
        }
Ejemplo n.º 4
0
        private WSqlFragment ConvertFragment(TSqlFragment fragment)
        {

            var tscript = fragment as TSqlScript;

            var wscript = new WSqlScript
            {
                FirstTokenIndex = tscript.FirstTokenIndex,
                LastTokenIndex = tscript.LastTokenIndex,
                Batches = tscript.Batches == null ? null : new List<WSqlBatch>(tscript.Batches.Count),
            };

            foreach (var tbatch in tscript.Batches)
            {
                var wbatch = new WSqlBatch
                {
                    FirstTokenIndex = tbatch.FirstTokenIndex,
                    LastTokenIndex = tbatch.LastTokenIndex,
                    Statements = new List<WSqlStatement>(tbatch.Statements.Count),
                };

                foreach (var wstat in tbatch.Statements.Select(ParseStatement))
                {
                    wbatch.Statements.Add(wstat);
                }

                wscript.Batches.Add(wbatch);
            }

            return wscript;
        }
Ejemplo n.º 5
0
 public static void Accept(this TSqlFragment fragment, params TSqlFragmentVisitor[] visitors)
 {
     foreach (var visitor in visitors)
     {
         fragment.Accept(visitor);
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Scripts the fragment to a string
        /// </summary>
        /// <param name="fragment"></param>
        /// <returns></returns>
        public static string GetScript(this TSqlFragment fragment)
        {
            var generator = new Sql140ScriptGenerator();

            generator.GenerateScript(fragment, out string sql);
            return(sql);
        }
        public static int GetNodeColumnPosition(TSqlFragment node)
        {
            var line          = string.Empty;
            var nodeStartLine = node.StartLine;
            var nodeLastLine  = node.ScriptTokenStream[node.LastTokenIndex].Line;

            for (var tokenIndex = 0; tokenIndex <= node.LastTokenIndex; tokenIndex++)
            {
                var token = node.ScriptTokenStream[tokenIndex];
                if (token.Line >= nodeStartLine && token.Line <= nodeLastLine)
                {
                    line += token.Text;
                }
            }

            var positionOfNodeOnLine = line.LastIndexOf(node.ScriptTokenStream[node.FirstTokenIndex].Text, StringComparison.Ordinal);
            var charactersBeforeNode = line.Substring(0, positionOfNodeOnLine);

            var offSet = 0;

            if (charactersBeforeNode.IndexOf(" ", StringComparison.Ordinal) != -1)
            {
                offSet = 1;
            }

            var tabCount       = CountTabs(charactersBeforeNode);
            var totalTabLentgh = tabCount * Constants.TabWidth;

            var nodePosition = totalTabLentgh + (charactersBeforeNode.Length - tabCount) + offSet;

            return(nodePosition);
        }
Ejemplo n.º 8
0
        private void NodeAction(TSqlFragment node)
        {
            List <ISkimmer <SqlFileContext> > skimmersList;

            if (node == null)
            {
                return;
            }

            if (this.typeToSkimmersMap.TryGetValue(node.GetType(), out skimmersList))
            {
                foreach (ISqlSkimmer skimmer in skimmersList)
                {
                    this.context.Fragment = node;
                    try
                    {
                        skimmer.Analyze(this.context);
                    }
                    catch (Exception ex)
                    {
                        RuntimeErrors |= AnalyzeCommand.LogUnhandledRuleExceptionAnalyzingTarget(
                            this.disabledSkimmers,
                            this.context,
                            skimmer,
                            ex);
                    }
                }
            }
        }
Ejemplo n.º 9
0
 protected string GenerateScript(TSqlFragment fragment)
 {
     string script;
     var generator = new Sql120ScriptGenerator(SavedSettings.Get().GeneratorOptions);
     generator.GenerateScript(fragment, out script);
     return script;
 }
        private void AnalyzeQueries(IList <SqlRuleProblem> problems, TSqlFragment fragment,
                                    SqlRuleExecutionContext ruleExecutionContext)
        {
            // Find all queries in current checking fragment.
            var visitor = new GetQuerySpecificationsVisitor();

            fragment.Accept(visitor);
            foreach (var querySpecification in visitor.Queries)
            {
                // Get the specified tables in the query.
                var unspecifiedPartitions = CollectFromClause(ruleExecutionContext, querySpecification);

                // If the query isn't querying a partition table, we don't need to check it.
                if (unspecifiedPartitions.Count > 0)
                {
                    // Get all constraints in the query.
                    if (querySpecification.WhereClause != null)
                    {
                        SearchConstraints(querySpecification.WhereClause, unspecifiedPartitions);
                    }
                }

                // If there are any unspecified partitions left, these are considered problems.
                foreach (var unspecifiedPartition in unspecifiedPartitions)
                {
                    SqlRuleProblem problem = CreateProblem(ruleExecutionContext, unspecifiedPartition);
                    problems.Add(problem);
                }

                AnalyzeJoins(problems, ruleExecutionContext, querySpecification);
            }
        }
        public static CodeExpression BuildFromCheckConstraintDefinition(string schemaName, DataTable table, string check_name, string check_definition, out bool hasError, out string errorText)
        {
            string       select_statement = "SELECT colx = IIF((" + check_definition + "), 1, 0) FROM " + schemaName + ".[" + table.TableName + "] WHERE " + check_definition;
            TSqlFragment sqlF             = ScriptDomFacade.Parse(select_statement);
            IIFVisitor   iif_visitor      = new IIFVisitor();

            sqlF.Accept(iif_visitor);
            if (iif_visitor.result == null)
            {
                throw new NotSupportedException("Expression 'IIF' could not be found:" + sqlF.AsText());
            }

            BooleanExpression iif_predicate = iif_visitor.result.Predicate;

            //if (iif_visitor != null)
            //{
            //    //return null; // comment out if it needed
            //}

            //Console.WriteLine("");
            //Console.WriteLine("==== " + check_name + " ============");
            //Console.WriteLine(ScriptDomFacade.GenerateScript(iif_predicate));
            //Console.WriteLine("-------------------------------------------");
            //Console.WriteLine("");

            var databaseMetadata = new DatabaseMetadataOnTable(table);

            hasError  = false;
            errorText = null;
            return(BooleanExpressionGeneratorVisitor.TryBuildFromFragment(databaseMetadata, iif_predicate, ref hasError, ref errorText));
        }
Ejemplo n.º 12
0
 private void ProcessSelectSetFragment(TSqlFragment Expression, string VarName)
 {
     string ElemType = FragmentTypeParser.GetFragmentType(Expression);
     switch (ElemType)
     {
         case "BinaryExpression":
             var BinaryExpression = (BinaryExpression) Expression;
             ProcessSelectSetFragment(BinaryExpression.FirstExpression, VarName);
             ProcessSelectSetFragment(BinaryExpression.SecondExpression, VarName);
             break;
         case "VariableReference":
             ProcessVariableReference((VariableReference) Expression, VarName);
             break;
         case "FunctionCall":
             var Func = (FunctionCall) Expression;
             foreach (TSqlFragment Parameter in Func.Parameters)
             {
                 ProcessSelectSetFragment(Parameter, VarName);
             }
             break;
         case "CastCall":
             var Cast = (CastCall) Expression;
             if (FragmentTypeParser.GetFragmentType(Cast.Parameter) == "VariableReference")
             {
                 ProcessVariableReference((VariableReference) Cast.Parameter, VarName);
             }
             break;
         case "StringLiteral":
             break;
     }
 }
Ejemplo n.º 13
0
        public IList<ParseError> TryGetTSqlFragment(out TSqlFragment fragment)
        {
            IList<ParseError> errors;

            if (this.tsqlFragment != null)
            {
                fragment = this.tsqlFragment;
                return null;
            }

            errors = null;
            fragment = null;

            lock (this.lockObject)
            {
                if (this.tsqlFragment == null)
                {
                    var parser = new TSql120Parser(initialQuotedIdentifiers: false);

                    using (StringReader reader = new StringReader(File.ReadAllText(TargetUri.LocalPath)))
                    {
                        this.tsqlFragment = parser.Parse(reader, out errors);
                    }
                }
            }

            fragment = this.tsqlFragment;
            return errors;
        }
Ejemplo n.º 14
0
        protected override IList <SqlRuleProblem> ElicitProblems(TSqlFragment fragment, RuleDescriptor ruleDescriptor, string elementName, TSqlObject modelElement)
        {
            var visitor = new AvoidUsingGlobalVariableForIdentityVisitor();

            fragment.Accept(visitor);
            return(this.CreateProblemsAsError(ruleDescriptor, elementName, modelElement, visitor.InvalidVariables));
        }
            public static IList <SelectStatement> VisitSelectStatements(TSqlFragment fragment)
            {
                TSqlSelectVisitor visitor = new TSqlSelectVisitor();

                fragment.Accept(visitor);
                return(visitor.SelectStatements);
            }
Ejemplo n.º 16
0
        public ISyntaxNode Visit(TSqlFragment node, TSqlFragment parent, string sourceProperty, ISyntaxNode result)
        {
            UpdateSpecification update = node as UpdateSpecification;

            if (update == null)
            {
                return(result);
            }

            StatementNode statement = new StatementNode()
            {
                Parent         = result,
                Fragment       = node,
                ParentFragment = parent,
                TargetProperty = sourceProperty
            };

            if (result is ScriptNode script)
            {
                if (parent is UpdateStatement)
                {
                    script.Statements.Add(statement);
                    return(statement);
                }
            }
            return(result);
        }
 public override void ExplicitVisit(CreateTableStatement table)
 {
     if (IsSupportedForCurrentType(table.GetType()))
     {
         Name = table.SchemaObjectName;
     }
 }
 public override void ExplicitVisit(CreateFunctionStatement func)
 {
     if (IsSupportedForCurrentType(func.GetType()))
     {
         Name = func.Name;
     }
 }
 public override void ExplicitVisit(AlterViewStatement view)
 {
     if (IsSupportedForCurrentType(view.GetType()))
     {
         Name = view.SchemaObjectName;
     }
 }
 public override void ExplicitVisit(AlterIndexStatement index)
 {
     if (IsSupportedForCurrentType(index.GetType()))
     {
         Name = index.Name;
     }
 }
        protected override IList <SqlRuleProblem> ElicitProblems(TSqlFragment fragment, RuleDescriptor ruleDescriptor, string elementName, TSqlObject modelElement)
        {
            var visitor = new HintsVisitor();

            fragment.Accept(visitor);
            return(this.CreateProblemsAsError(ruleDescriptor, elementName, modelElement, visitor.Hints));
        }
Ejemplo n.º 22
0
        private static string ScriptFragment(SqlScriptGenerator sg, TSqlFragment fragment)
        {
            string resultString;

            sg.GenerateScript(fragment, out resultString);
            return(resultString);
        }
Ejemplo n.º 23
0
        //Script formater only for parsing the query
        public string SQLScriptFormater(string sqlScript, bool onlyParse)
        {
            try
            {
                string strFormattedSQL = string.Empty;
                using (TextReader rdr = new StringReader(sqlScript))
                {
                    TSql130Parser      parser = new TSql130Parser(true);
                    IList <ParseError> errors = null;
                    TSqlFragment       tree   = parser.Parse(rdr, out errors);

                    if (errors.Count > 0)
                    {
                        foreach (ParseError err in errors)
                        {
                            strFormattedSQL = strFormattedSQL + err.Message + "\r\n";
                        }
                        return(strFormattedSQL);
                    }
                    else
                    {
                        return("true");
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        private void ChangeNewDatabaseLocation(DeploymentPlanContributorContext context, string databasePath,
                                               string logPath)
        {
            DeploymentStep nextStep = context.PlanHandle.Head;

            // Loop through all steps in the deployment plan
            bool finished = false;

            while (nextStep != null && !finished)
            {
                // Increment the step pointer, saving both the current and next steps
                DeploymentStep currentStep = nextStep;

                // Only interrogate up to BeginPreDeploymentScriptStep - setvars must be done before that
                if (currentStep is BeginPreDeploymentScriptStep)
                {
                    finished = true;
                    break;
                }

                SqlCreateDatabaseStep createDbStep = currentStep as SqlCreateDatabaseStep;
                if (createDbStep != null)
                {
                    TSqlFragment fragment = createDbStep.Script;

                    CreateDatabaseStatementVisitor visitor = new CreateDatabaseStatementVisitor(databasePath, logPath);
                    fragment.Accept(visitor);

                    finished = true;
                }

                nextStep = currentStep.Next;
            }
        }
Ejemplo n.º 25
0
        public static void ParseSQL()
        {
            var sql = @"select AreaId = A.mcw_areaId,  SurrogateKey = A.AreaKey,  Code = S.statecode, Name = S.statename From CRM.dim_Area as A inner join CRM.dim_AreaState as S ON A.statecode = S.statecode  ; DELET  blogs SET url = 'aaa' where url='dasfds'";


            //@"select p.firstname, p.lastname, p.custid FROM persons as p ;
            //SELECT id, name FROM companies;
            //select s.test from (select 'hello' as test) as s; ";

            TSqlParser         parser = new TSql120Parser(true);
            IList <ParseError> parseErrors;
            var          tReader     = new StringReader(sql);
            TSqlFragment sqlFragment = parser.Parse(tReader, out parseErrors);
            var          queryTokens = parser.GetTokenStream(tReader, out parseErrors);

            if (parseErrors.Count > 0)
            {
                Console.WriteLine("Errors:");
            }
            parseErrors.Select(e => e.Message.Indent(2)).ToList().ForEach(Console.WriteLine);

            OwnVisitor visitor = new OwnVisitor();

            sqlFragment.Accept(visitor);
            // sqlFragment.AcceptChildren(visitor);

            Console.WriteLine("Done.");
            Console.ReadKey();
        }
            public static IList <CreateTableStatement> VisitCreateTableStatements(TSqlFragment fragment)
            {
                TSqlSelectVisitor visitor = new TSqlSelectVisitor();

                fragment.Accept(visitor);
                return(visitor.CreateTableStatements);
            }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            TextReader txtRdr = new StringReader(@"select AreaId = A.mcw_areaId,  SurrogateKey = A.AreaKey,  Code = S.statecode, Name = S.statename From CRM.dim_Area as A inner join CRM.dim_AreaState as S ON A.statecode = S.statecode  ; DELET FROM blogs  where url='dasfds'");

            //TextReader txtRdr = new StreamReader("myscriptfile.sql");

            TSql120Parser parser = new TSql120Parser(true);

            IList <ParseError> errors;

            TSqlFragment sqlFragment = parser.Parse(txtRdr, out errors);

            foreach (var err in errors)
            {
                Console.WriteLine(err.Message);
            }

            SQLVisitor myVisitor = new SQLVisitor();

            sqlFragment.Accept(myVisitor);

            myVisitor.DumpStatistics();

            ParseSQL();

            Console.ReadKey();
        }
            public static IList <ProcedureParameter> VisitProcedureParameters(TSqlFragment fragment)
            {
                TSqlSelectVisitor visitor = new TSqlSelectVisitor();

                fragment.Accept(visitor);
                return(visitor.ProcedureParameters);
            }
Ejemplo n.º 29
0
        /// <summary>
        /// Checks if an object is:
        /// - Named
        /// - Starts with a letter or digit. This filters our parameters starting with '@', but may filter out other
        ///   objects you wish to test for. This is where you would extend the logic for more advanced cases
        /// - The first letter is not uppercase.
        /// </summary>
        private void CheckIfCapitalized(TSqlObject tSqlObject, List <SqlRuleProblem> problems)
        {
            ObjectIdentifier name = tSqlObject.Name;

            if (name != null &&
                name.HasName &&
                name.Parts.Count > 0)       // This check is equivalent to name.HasHame, including in case you don't trust the framework and want to verify yourself
            {
                string actualName = name.Parts[name.Parts.Count - 1];
                if (!string.IsNullOrEmpty(actualName) &&
                    Char.IsLetterOrDigit(actualName[0]) &&
                    !Char.IsUpper(actualName[0]))
                {
                    string description = string.Format(CultureInfo.CurrentCulture,
                                                       RuleResources.CapitalizedNames_ProblemDescription,
                                                       _model.DisplayServices.GetElementName(tSqlObject, ElementNameStyle.EscapedFullyQualifiedName));

                    // Name fragment would have more precise location information than the overall object.
                    // This can be null, in which case the object's position will be used.
                    // note that the current implementation does not work for non-top level types as it
                    // relies on the TSqlModelUtils.TryGetFragmentForAnalysis() method which doesn't support these.
                    TSqlFragment nameFragment = TsqlScriptDomUtils.LookupSchemaObjectName(tSqlObject);

                    problems.Add(new SqlRuleProblem(description, tSqlObject, nameFragment));
                }
            }
        }
Ejemplo n.º 30
0
 public static string GenerateTSql(TSqlFragment script)
 {
     var generator = new Sql130ScriptGenerator(Settings.SavedSettings.Get().GeneratorOptions);
     var builder = new StringBuilder();
     generator.GenerateScript(script, new StringWriter(builder));
     return builder.ToString();
 }
Ejemplo n.º 31
0
 public static string GetFragmentType(TSqlFragment Statement)
 {
     String Type = Statement.ToString();
     String[] TypeSplit = Type.Split('.');
     String StmtType = TypeSplit[TypeSplit.Length - 1];
     return (StmtType);
 }
Ejemplo n.º 32
0
        protected override IList <SqlRuleProblem> ElicitProblems(TSqlFragment fragment, RuleDescriptor ruleDescriptor, string elementName, TSqlObject modelElement)
        {
            var sb = new StringBuilder();

            foreach (var scriptTokenStreamFragment in fragment.ScriptTokenStream)
            {
                sb.Append(scriptTokenStreamFragment.Text);
            }

            var fullScript      = sb.ToString();
            var isHeaderPresent = true;

            foreach (var knownHeaderItem in this.KnownHeaderItems)
            {
                if (fullScript.IndexOf(knownHeaderItem, StringComparison.OrdinalIgnoreCase) == -1)
                {
                    isHeaderPresent = false;
                }
            }

            if (!isHeaderPresent)
            {
                return(this.CreateProblemsAsError(ruleDescriptor, elementName, modelElement, new List <TSqlFragment> {
                    fragment
                }));
            }
            return(null);
        }
Ejemplo n.º 33
0
        public string PrepareScript(string script, out IList <ParseError> errors)
        {
            if (MetadataService.CurrentDatabase == null)
            {
                throw new InvalidOperationException("Current database is not defined!");
            }

            TSqlFragment fragment = Parser.Parse(new StringReader(script), out errors);

            if (errors.Count > 0)
            {
                return(script);
            }

            ScriptNode result = new ScriptNode()
            {
                InfoBase = MetadataService.CurrentDatabase
            };
            SyntaxTreeVisitor visitor = new SyntaxTreeVisitor(MetadataService);

            visitor.Visit(fragment, result);

            Generator.GenerateScript(fragment, out string sql);
            return(sql);
        }
Ejemplo n.º 34
0
        private void SaveScriptSourceCode()
        {
            IScriptingService scripting  = Services.GetService <IScriptingService>();
            TSqlFragment      syntaxTree = scripting.ParseScript(ScriptCode, out IList <ParseError> errors);

            if (errors.Count > 0)
            {
                ShowParseErrors(errors);
                throw new InvalidOperationException("Saving script failed: incorrect syntax.");
            }

            ScriptingController controller = Services.GetService <ScriptingController>();
            string catalogName             = controller.GetScriptsCatalogName(MyServer, MyDatabase, ScriptType);

            if (controller.ScriptFileExists(catalogName, Name))
            {
                controller.SaveScriptFile(catalogName, Name, ScriptCode);
            }
            else
            {
                if (controller.GetScriptTreeNodeByName(MyServer, MyDatabase, ScriptType, Name) != null)
                {
                    throw new InvalidOperationException($"Script node \"{Name}\" already exists!");
                }
                controller.SaveScriptFile(catalogName, Name, ScriptCode);
            }

            MainWindowViewModel mainWindow = Services.GetService <MainWindowViewModel>();
            TreeNodeViewModel   treeNode   = mainWindow.GetTreeNodeByPayload(mainWindow.MainTreeRegion.TreeNodes, this);

            if (treeNode == null)
            {
                controller.CreateScriptTreeNode(this);
            }
        }
Ejemplo n.º 35
0
 public SubroutineDataType(string name, TSqlFragment sqlFragment, IEnumerable <Parameter> parameters)
 {
     _name                    = name;
     _sqlFragment             = sqlFragment;
     _parameters              = parameters;
     _parameterDictionaryLazy = new Lazy <Dictionary <string, Parameter> >(() => _parameters.ToDictionary(it => it.Name.ToLower()));
 }
Ejemplo n.º 36
0
        public IList <ParseError> TryGetTSqlFragment(out TSqlFragment fragment)
        {
            IList <ParseError> errors;

            if (this.tsqlFragment != null)
            {
                fragment = this.tsqlFragment;
                return(null);
            }

            errors   = null;
            fragment = null;

            lock (this.lockObject)
            {
                if (this.tsqlFragment == null)
                {
                    var parser = new TSql120Parser(initialQuotedIdentifiers: false);

                    using (StringReader reader = new StringReader(File.ReadAllText(TargetUri.LocalPath)))
                    {
                        this.tsqlFragment = parser.Parse(reader, out errors);
                    }
                }
            }

            fragment = this.tsqlFragment;
            return(errors);
        }
        private IEnumerable <PartitionedColumn> CollectFromTableReference(SqlRuleExecutionContext ruleExecutionContext,
                                                                          TSqlFragment fragment, TableReference tableReference)
        {
            if (!(tableReference is NamedTableReference namedTableReference))
            {
                return(new List <PartitionedColumn>());
            }

            // Resolve the table from its name.
            var table =
                ResolveTable(ruleExecutionContext.SchemaModel, namedTableReference.SchemaObject);

            if (table == null)
            {
                return(new List <PartitionedColumn>());
            }
            // In the tabe object, find all columns that are a partition column, and save them.
            var partitionColumns = table.GetReferenced(Table.PartitionColumn, DacQueryScopes.All);

            var allowedTableNames = new HashSet <string>();

            allowedTableNames.Add(namedTableReference.SchemaObject.BaseIdentifier.Value);
            if (namedTableReference.Alias != null)
            {
                allowedTableNames.Add(namedTableReference.Alias.Value);
            }

            return(partitionColumns
                   .Select(x => new PartitionedColumn(
                               allowedTableNames,
                               x.Name.Parts.Last(), fragment)));
        }
        protected override void DisplayScript(TSqlFragment rootFragment)
        {
            TreeNode rootTreeNode = CreateNewTreeNodeForFragment(rootFragment);

            tvwFragmentTree.Nodes.Add(rootTreeNode);
            AddTreeNodeChildren(rootTreeNode);
            ExpandTreeNode(rootTreeNode);
        }
        public List<TSqlFragment> GetFragmentChildren(TSqlFragment parentFragment)
        {
            oVisitorAll visitor = new oVisitorAll();

            parentFragment.AcceptChildren(visitor);

            return visitor.Fragments;
        }
        private TreeNode CreateNewTreeNodeForFragment(TSqlFragment fragment)
        {
            TreeNode tn = new TreeNode();

            tn.Text = ScriptParser.GetFragmentTypeName(fragment);
            tn.Tag = fragment;

            return tn;
        }
        protected override void DisplayScript(TSqlFragment rootFragment)
        {
            List<oIssue> issuesFound = new List<oIssue>();
            oSQLStandardsChecker sqlStandardsChecker = new oSQLStandardsChecker(ScriptParser, rootFragment);

            issuesFound.AddRange(sqlStandardsChecker.CheckProcedureName());
            issuesFound.AddRange(sqlStandardsChecker.CheckProcedureSchemaPrefixes());
            issuesFound.AddRange(sqlStandardsChecker.CheckTableVariableCharacterColumnCollations());
            issuesFound.AddRange(sqlStandardsChecker.CheckTemporaryTableCharacterColumnCollations());

            DisplayIssues(issuesFound);
        }
        public string GetFragmentSQL(TSqlFragment fragment)
        {
            StringBuilder sql = new StringBuilder();

            if (fragment.FirstTokenIndex != -1)
            {
                for (int counter = fragment.FirstTokenIndex; counter <= fragment.LastTokenIndex; counter++)
                {
                    sql.Append(fragment.ScriptTokenStream[counter].Text);
                    //sql.Append(" ");
                }
            }

            return sql.ToString().Trim();
        }
Ejemplo n.º 43
0
        public List<Replacements> GetReplacements(List<QuerySpecification> queries)
        {
            foreach (var select in queries)
            {
                _currentFragment = select;

                if (select.WhereClause != null)
                {
                    Search(select.WhereClause.SearchCondition);
                }

                if (select.FromClause != null)
                {
                    foreach (var reference in select.FromClause.TableReferences)
                    {
                        if (reference is QualifiedJoin)
                        {
                            var join = reference as QualifiedJoin;
                            Search(join.SearchCondition);
                        }
                    }
                }

            }

            var distinctor = new Dictionary<string, Replacements>();

            foreach (var p in _replacementsToMake)
            {
                distinctor[p.Original + ":" + p.OriginalLength + ":" + p.OriginalOffset] = p;
            }
            //remove duplicates
            _replacementsToMake = distinctor.Values.ToList();

            for (var i = 0; i < _replacementsToMake.Count; i++)
            {
                var rep = _replacementsToMake[i];

                if (!rep.Original.Contains("\r\n") && rep.Replacement.Contains("\r\n"))
                {
                    rep.Replacement = rep.Replacement.Replace("\r\n", "");
                    _replacementsToMake[i] = rep;
                }
            }

            return _replacementsToMake;
        }
        public List<TSqlFragment> GetFragmentChildren(TSqlFragment parentFragment, oVisitorBase visitor, bool recurseChildren = false)
        {
            parentFragment.AcceptChildren(visitor);

            List<TSqlFragment> children = visitor.Fragments;
            List<TSqlFragment> grandChildren;

            if (recurseChildren)
            {
                foreach (TSqlFragment f in children)
                {
                    grandChildren = GetFragmentChildren(f, visitor, recurseChildren);

                    if ((grandChildren != null) && (grandChildren.Count > 0))
                        children.AddRange(grandChildren);
                }
            }

            return children;
        }
Ejemplo n.º 45
0
 public override void ExplicitVisit(CreateTableStatement table)
 {
     if (IsSupportedForCurrentType(table.GetType()))
     {
         Name = table.SchemaObjectName;
     }
 }
Ejemplo n.º 46
0
 public override void ExplicitVisit(AlterProcedureStatement proc)
 {
     if (IsSupportedForCurrentType(proc.GetType())
         && proc.ProcedureReference != null)
     {
         Name = proc.ProcedureReference.Name;
     }
 }
Ejemplo n.º 47
0
 public override void ExplicitVisit(CreateFunctionStatement func)
 {
     if (IsSupportedForCurrentType(func.GetType()))
     {
         Name = func.Name;
     }
 }
Ejemplo n.º 48
0
 /// <summary>
 /// Checks if a fragment represents the body of a subroutine, a view, 
 /// or a trigger. These have similar characteristics, for instance the ability to
 /// include select statements against tables. 
 /// </summary>
 /// <param name="fragment">
 /// <see cref="TSqlFragment"/> representing part of a TSQL object definition
 /// </param>
 /// <returns>true if this is a subroutine, a view or a trigger body</returns>
 public static bool IsSubroutineViewOrTrigger(TSqlFragment fragment)
 {
     return fragment is ProcedureStatementBodyBase ||
         fragment is ViewStatementBody ||
         fragment is TriggerStatementBody;
 }
Ejemplo n.º 49
0
        public void SendFeedBack(int errorNum, TSqlFragment errorFrg)
        {
            if (errorNum != _iRule) return;


            ResourceManager rm = Resources.ResourceManager;

            string lookup = "TSQLSmell_RuleName" + errorNum.ToString("D2");
            string Out = rm.GetString(lookup);

            _problems.Add(new SqlRuleProblem(Out, _modelElement, errorFrg));
        }
Ejemplo n.º 50
0
        //void ProcessSelectElements(


        public void ProcessTsqlFragment(TSqlFragment fragment)
        {
           String stmtType = FragmentTypeParser.GetFragmentType(fragment);
            //Console.WriteLine(StmtType);
            switch (stmtType)
            {
                case "DeclareCursorStatement":
                    _cursorProcessor.ProcessCursorStatement((DeclareCursorStatement) fragment);
                    break;
                case "BeginEndBlockStatement":
                    _beginEndBlockProcessor.ProcessBeginEndBlockStatement((BeginEndBlockStatement) fragment);
                    break;
                case "CreateFunctionStatement":
                case "AlterFunctionStatement":
                    _functionStatementBodyProcessor.ProcessFunctionStatementBody((FunctionStatementBody) fragment);
                    break;
                case "SelectFunctionReturnType":
                    _selectFunctionReturnTypeProcessor.ProcessSelectFunctionReturnType((SelectFunctionReturnType) fragment);
                    return;
                case "ScalarFunctionReturnType":
                    _scalarFunctionReturnTypeProcessor.ProcessScalarFunctionReturnType((ScalarFunctionReturnType) fragment);
                    break;
                case "SetTransactionIsolationLevelStatement":
                    _setTransactionIsolationLevelProcessor.ProcessSetTransactionIolationLevelStatement((SetTransactionIsolationLevelStatement) fragment);
                    break;
                case "WhileStatement":
                    _whileProcessor.ProcessWhileStatement((WhileStatement) fragment);
                    break;
                case "InsertStatement":
                    InsertProcessor.Process((InsertStatement) fragment);
                    break;
                case "SelectStatement":
                    _selectStatementProcessor.Process((SelectStatement) fragment, "RG", true);
                    break;
                case "SetRowCountStatement":
                    SendFeedBack(42, fragment);
                    break;
                case "IfStatement":
                    _ifStatementProcessor.ProcessIfStatement((IfStatement) fragment);
                    break;
                case "PredicateSetStatement":
                    _predicateSetProcessor.ProcessPredicateSetStatement((PredicateSetStatement) fragment);
                    break;
                case "ExecuteStatement":
                    ExecutableEntityProcessor.ProcessExecuteStatement((ExecuteStatement) fragment);
                    break;
                case "SetIdentityInsertStatement":
                    SendFeedBack(22, fragment);
                    break;
                case "SetCommandStatement":
                    _setProcessor.ProcessSetStatement((SetCommandStatement) fragment);
                    break;

                case "CreateTableStatement":
                    _createTableProcessor.ProcessCreateTable((CreateTableStatement) fragment);
                    break;

                case "CreateProcedureStatement":
                case "AlterProcedureStatement":
                    ProcedureStatementBodyProcessor.ProcessProcedureStatementBody((ProcedureStatementBody) fragment);
                    _assignmentList.Clear();
                    break;
                case "CreateViewStatement":
                case "AlterViewStatement":
                    _viewStatementProcessor.ProcessViewStatementBody((ViewStatementBody) fragment);
                    break;
                case "TSqlBatch":
                    var batch = (TSqlBatch) fragment;
                    foreach (TSqlStatement innerFragment in batch.Statements)
                    {
                        ProcessTsqlFragment(innerFragment);
                    }
                    break;
                case "TSqlScript":
                    var script = (TSqlScript) fragment;
                    foreach (TSqlBatch innerBatch in script.Batches)
                    {
                        ProcessTsqlFragment(innerBatch);
                    }
                    break;
                case "BooleanParenthesisExpression":
                    var expression = (BooleanParenthesisExpression) fragment;
                    ProcessTsqlFragment(expression.Expression);
                    break;
                case "BooleanComparisonExpression":
                    var bcExpression = (BooleanComparisonExpression) fragment;
                    ProcessTsqlFragment(bcExpression.FirstExpression);
                    ProcessTsqlFragment(bcExpression.SecondExpression);
                    break;
                case "ScalarSubquery":
                    var scalarSubquery = (ScalarSubquery) fragment;
                    ProcessQueryExpression(scalarSubquery.QueryExpression, "RG");
                    break;
                case "ReturnStatement":
                    _returnStatementProcessor.ProcessReturnStatement((ReturnStatement) fragment);
                    break;
                case "IntegerLiteral":
                    break;
                case "DeclareVariableStatement":
                    _declareVariableProcessor.ProcessDeclareVariableStatement((DeclareVariableStatement) fragment);
                    break;
                case "DeclareVariableElement":
                    _declareVariableProcessor.ProcessDeclareVariableElement((DeclareVariableElement) fragment);
                    break;
                case "PrintStatement":
                    break;
                case "SqlDataTypeReference":
                    _sqlDataTypeProcessor.ProcessSqlDataTypeReference((SqlDataTypeReference) fragment);
                    break;
                case "DeclareTableVariableStatement":
                    _tableVariableProcessor.ProcessTableVariableStatement((DeclareTableVariableStatement) fragment);
                    break;
                case "TableValuedFunctionReturnType":
                    _tableVariableProcessor.ProcessTableValuedFunctionReturnType((TableValuedFunctionReturnType) fragment);
                    break;
                case "DeclareTableVariableBody":
                    _tableVariableProcessor.ProcessTableVariableBody((DeclareTableVariableBody) fragment);
                    break;
                case "VariableReference":
                    //ProcessVariableReference((VariableReference)Fragment);
                    break;
                case "ExistsPredicate":
                    _tableVariableProcessor.ProcessExistsPredicate((ExistsPredicate) fragment);
                    break;

                case "ColumnDefinition":
                    _columnDefinitionProcessor.ProcessColumnDefinition((ColumnDefinition)fragment);
                    break;
            }
        }
Ejemplo n.º 51
0
        public WSqlUnknownStatement(TSqlFragment statement)
        {
            TokenStream = new List<TSqlParserToken>(statement.LastTokenIndex - statement.FirstTokenIndex + 1);

            for (var pos = statement.FirstTokenIndex; pos <= statement.LastTokenIndex; pos++)
            {
                TokenStream.Add(statement.ScriptTokenStream[pos]);
            }
        }
Ejemplo n.º 52
0
        private static List<TableReference> FindTableReferences(TSqlFragment statement)
        {
            var nodeType = statement.ToString().Split(' ')[0];
            var t = ScriptDomCode.GetType(nodeType, false, true);

            var tables = new List<TableReference>();

            foreach (var p in t.GetProperties())
            {
                var value = TryGetValue(p, statement);
                if(value == null)
                    continue;
                
                if (value is List<TableReference>)
                {
                    tables.AddRange(value as List<TableReference>);
                    continue;
                }

                if (value is TableReference)
                {
                    tables.Add(value as TableReference);
                    continue;
                }
                
                //don't move this before is List<TableReference> as they are also TSqlFragments which causes hilarity
                if (value is IEnumerable<TSqlFragment>)
                {
                    foreach (var fragment in value as IEnumerable<TSqlFragment>)
                    {
                        tables.AddRange(FindTableReferences(fragment));
                    }

                    continue;
                }

                if (value is TSqlFragment)
                {
                    tables.AddRange(FindTableReferences(value as TSqlFragment));
                    continue;
                }
            }

            return tables;
        }
Ejemplo n.º 53
0
 internal void UpdateTokenInfo(TSqlFragment fragment)
 {
     if (fragment == null)
         return;
     UpdateTokenInfo(fragment.FirstTokenIndex, fragment.LastTokenIndex);
 }
Ejemplo n.º 54
0
        private static IEnumerable<QuerySpecification> SearchChildren(TSqlFragment fragment)
        {
            if (fragment is InsertStatement)
            {
                return SearchChildren((fragment as InsertStatement).InsertSpecification.InsertSource);
            }

            if (fragment is SelectInsertSource)
            {
                return SearchChildren((fragment as SelectInsertSource).Select);
            }

            var children = new List<QuerySpecification>();
          
            if (fragment is BinaryQueryExpression)
            {
                var expression = fragment as BinaryQueryExpression;
                children.AddRange(SearchChildren(expression.FirstQueryExpression));
                children.AddRange(SearchChildren(expression.SecondQueryExpression));
            }

            if (fragment is QueryParenthesisExpression)
            {
                var expression = fragment as QueryParenthesisExpression;
                children.AddRange(SearchChildren(expression.QueryExpression));
            }

            if (fragment is BooleanBinaryExpression)
            {
                var expression = fragment as BooleanBinaryExpression;
                children.AddRange(SearchChildren(expression.FirstExpression));
                children.AddRange(SearchChildren(expression.SecondExpression));
            }

            if (fragment is BooleanComparisonExpression)
            {
                var expression = fragment as BooleanComparisonExpression;
                children.AddRange(SearchChildren(expression.FirstExpression));
                children.AddRange(SearchChildren(expression.SecondExpression));
            }

            if (fragment is ScalarSubquery)
            {
                var query = fragment as ScalarSubquery;
                children.AddRange(SearchChildren(query.QueryExpression));
            }

            if (fragment is QuerySpecification)
            {
                var spec = fragment as QuerySpecification;
                
                children.Add(spec);
                
                foreach (var select in spec.SelectElements)
                {
                    children.AddRange(SearchChildren(select));
                }

                if (spec.WhereClause != null)
                {
                    children.AddRange(SearchChildren(spec.WhereClause.SearchCondition));
                }

                if (spec.FromClause != null)
                {
                    foreach (var table in spec.FromClause.TableReferences)
                    {
                        children.AddRange(SearchChildren(table));
                    }
                }
                
            }

            if (fragment is SelectStatement)
            {
                if ((fragment as SelectStatement).QueryExpression != null)
                {
                    if ((fragment as SelectStatement).QueryExpression is BinaryQueryExpression)
                    {
                        var expression = (fragment as SelectStatement).QueryExpression as BinaryQueryExpression;
                        
                             children.AddRange(SearchChildren(expression.FirstQueryExpression));
                             children.AddRange(SearchChildren(expression.SecondQueryExpression));
                        
                    }
                }

                if ((fragment as SelectStatement).QueryExpression != null)
                {
                    if ((fragment as SelectStatement).QueryExpression is QuerySpecification)
                    {
                        var expression = (fragment as SelectStatement).QueryExpression as QuerySpecification;
                        
                        children.Add(expression);
                    }
                    
                }
            }

            return children;
        }
 public string GetFragmentTypeName(TSqlFragment fragment)
 {
     return fragment.GetType().Name;
 }
 private TSqlFragment GetTag(TSqlFragment sqlFragment)
 {
     return sqlFragment;
 }
Ejemplo n.º 57
0
 public override void ExplicitVisit(AlterIndexStatement index)
 {
     if (IsSupportedForCurrentType(index.GetType()))
     {
         Name = index.Name;
     }
 }
Ejemplo n.º 58
0
 protected IList<TSqlParserToken> GetTokens(TSqlFragment fragment)
 {
     return _generator.GenerateTokens(fragment);
 }
Ejemplo n.º 59
0
 protected string GenerateScript(TSqlFragment fragment)
 {
     string script;
     _generator.GenerateScript(fragment, out script);
     return script;
 }
Ejemplo n.º 60
0
 protected IList<TSqlParserToken> GetTokens(TSqlFragment fragment)
 {
     var generator = new Sql120ScriptGenerator(SavedSettings.Get().GeneratorOptions);
     return generator.GenerateTokens(fragment);
 }