示例#1
0
        public override void ExplicitVisit(CreateProcedureStatement node)
        {
            var visitor = new ReturnStatementPresentVisitor();

            node.Accept(visitor);
            this.ReturnStatements = visitor.ReturnStatements;
        }
示例#2
0
 public void ProcessCreateProcedure(CreateProcedureStatement prcStmt)
 {
     foreach (var stmt in prcStmt.StatementList.Statements)
     {
         ProcessTsqlFragment(stmt);
     }
 }
示例#3
0
        private static string ChangeCreateToAlter(CreateProcedureStatement procedure, string wholeScript)
        {
            //get part of script we are interested in...
            var subScript = wholeScript.Substring(procedure.StartOffset, procedure.FragmentLength);

            IList <ParseError> errors;
            var fragment = new TSql130Parser(false).Parse(new StringReader(subScript), out errors);

            bool haveCreate = false;
            var  output     = new StringBuilder();

            foreach (var token in fragment.ScriptTokenStream)
            {
                if (!haveCreate && token.TokenType == TSqlTokenType.Create)
                {
                    var alterToken = new TSqlParserToken(TSqlTokenType.Alter, "alter");
                    output.Append(alterToken.Text);
                    haveCreate = true;
                    continue;
                }

                output.Append(token.Text);
            }

            return(output.ToString());
        }
示例#4
0
        public override void Visit(CreateProcedureStatement node)
        {
            base.Visit(node);

            CheckFirstStatementInBatch(node, "CREATE PROCEDURE");
            CheckLastStatementInBatch(node, "CREATE PROCEDURE");
        }
示例#5
0
        private static string BuildIfNotExistsStatements(CreateProcedureStatement procedure)
        {
            var generateIfExists =
                string.Format("if object_id('{0}') is null\r\nbegin\r\n execute sp_executeSql N' create procedure {0} as select 1;';\r\nend",
                              procedure.ProcedureReference.Name.ToQuotedString());

            return(generateIfExists);
        }
示例#6
0
        private static string BuildIfNotExistsStatements(CreateProcedureStatement procedure)
        {
            var generateIfExists =
                string.Format("if object_id('{0}') is null\r\nbegin\r\n execute sp_executeSql N' create procedure {0} as select 1;';\r\nend",
                    procedure.ProcedureReference.Name.ToQuotedString());

            return generateIfExists;
        }
 public override void ExplicitVisit(CreateProcedureStatement proc)
 {
     if (IsSupportedForCurrentType(proc.GetType()) &&
         proc.ProcedureReference != null)
     {
         Name = proc.ProcedureReference.Name;
     }
 }
        private void AnalyzeCreateProcedureStatement(CreateProcedureStatement createProcedureStatement, ParserResults results)
        {
            //((BeginEndBlockStatement)((CreateProcedureStatement)statement).StatementList.Statements[0]).StatementList.Statements
            if (createProcedureStatement.StatementList.Statements.Count == 0)
            {
                return;
            }

            AnalyzeTsqlStatementList(createProcedureStatement.StatementList, results);
        }
        public override void ExplicitVisit(CreateProcedureStatement node)
        {
            var visitor = new DdlVisitor();

            node.Accept(visitor);

            this.AlterTableStatements  = visitor.AlterTableStatements;
            this.DropTableStatements   = visitor.DropTableStatements;
            this.CreateTableStatements = visitor.CreateTableStatements;
        }
        /// <summary>
        /// Creates a PopulateCommand method taking a SqlCommand and parameters for each sproc parameter.
        /// </summary>
        /// <param name="node">The CREATE STORED PROCEDURE statement</param>
        /// <param name="schemaQualifiedProcedureName">The full name of the stored procedure</param>
        /// <returns>The method declaration</returns>
        private MethodDeclarationSyntax AddPopulateCommandMethod(CreateProcedureStatement node, string schemaQualifiedProcedureName)
        {
            return(MethodDeclaration(
                       typeof(void).ToTypeSyntax(),
                       Identifier(PopulateCommandMethodName))
                   .AddModifiers(Token(SyntaxKind.PublicKeyword))

                   // first parameter is the SqlCommand
                   .AddParameterListParameters(Parameter(Identifier(CommandParameterName)).WithType(ParseTypeName("SqlCommandWrapper")))

                   // Add a parameter for each stored procedure parameter
                   .AddParameterListParameters(node.Parameters.Select(selector: p =>
                                                                      Parameter(Identifier(ParameterNameForParameter(p)))
                                                                      .WithType(DataTypeReferenceToClrType(p.DataType, p.Value != null))).ToArray())

                   // start the body with:
                   // command.CommandType = CommandType.StoredProcedure
                   // command.CommandText = "dbo.MySproc"
                   .AddBodyStatements(
                       ExpressionStatement(
                           AssignmentExpression(
                               SyntaxKind.SimpleAssignmentExpression,
                               MemberAccessExpression(
                                   SyntaxKind.SimpleMemberAccessExpression,
                                   IdentifierName(CommandParameterName),
                                   IdentifierName("CommandType")),
                               MemberAccessExpression(
                                   SyntaxKind.SimpleMemberAccessExpression,
                                   typeof(CommandType).ToTypeSyntax(useGlobalAlias: true),
                                   IdentifierName("StoredProcedure")))),
                       ExpressionStatement(
                           AssignmentExpression(
                               SyntaxKind.SimpleAssignmentExpression,
                               MemberAccessExpression(
                                   SyntaxKind.SimpleMemberAccessExpression,
                                   IdentifierName(CommandParameterName),
                                   IdentifierName("CommandText")),
                               LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(schemaQualifiedProcedureName)))))

                   // now for each parameter generate:
                   // _fieldForParameter.AddParameter(command, parameterValue)
                   .AddBodyStatements(node.Parameters.Select(p => (StatementSyntax)ExpressionStatement(
                                                                 InvocationExpression(
                                                                     MemberAccessExpression(
                                                                         SyntaxKind.SimpleMemberAccessExpression,
                                                                         IdentifierName(FieldNameForParameter(p)),
                                                                         IdentifierName("AddParameter")))
                                                                 .AddArgumentListArguments(
                                                                     Argument(MemberAccessExpression(
                                                                                  SyntaxKind.SimpleMemberAccessExpression,
                                                                                  IdentifierName(CommandParameterName),
                                                                                  IdentifierName("Parameters"))),
                                                                     Argument(IdentifierName(ParameterNameForParameter(p)))))).ToArray()));
        }
        public override void Visit(CreateProcedureStatement node)
        {
            var    rawProcedureName             = node.ProcedureReference.Name.BaseIdentifier.Value;
            string procedureName                = GetMemberNameWithoutVersionSuffix(node.ProcedureReference.Name);
            string schemaQualifiedProcedureName = $"{node.ProcedureReference.Name.SchemaIdentifier.Value}.{rawProcedureName}";
            string className = $"{procedureName}Procedure";

            ClassDeclarationSyntax classDeclarationSyntax =
                ClassDeclaration(className)
                .WithModifiers(TokenList(Token(SyntaxKind.InternalKeyword)))

                // derive from StoredProcedure
                .WithBaseList(
                    BaseList(
                        SingletonSeparatedList <BaseTypeSyntax>(
                            SimpleBaseType(
                                IdentifierName("StoredProcedure")))))

                // call base("dbo.StoredProcedure")
                .AddMembers(
                    ConstructorDeclaration(
                        Identifier(className))
                    .WithModifiers(
                        TokenList(
                            Token(SyntaxKind.InternalKeyword)))
                    .WithInitializer(
                        ConstructorInitializer(
                            SyntaxKind.BaseConstructorInitializer,
                            ArgumentList(
                                SingletonSeparatedList(
                                    Argument(
                                        LiteralExpression(
                                            SyntaxKind.StringLiteralExpression,
                                            Literal(schemaQualifiedProcedureName)))))))
                    .WithBody(Block()))

                // add fields for each parameter
                .AddMembers(node.Parameters.Select(CreateFieldForParameter).ToArray())

                // add the PopulateCommand method
                .AddMembers(AddPopulateCommandMethod(node, schemaQualifiedProcedureName), AddPopulateCommandMethodForTableValuedParameters(node, procedureName));

            FieldDeclarationSyntax fieldDeclarationSyntax = CreateStaticFieldForClass(className, procedureName);

            var(tvpGeneratorClass, tvpHolderStruct) = CreateTvpGeneratorTypes(node, procedureName);

            MembersToAdd.Add(classDeclarationSyntax.AddSortingKey(this, procedureName));
            MembersToAdd.Add(fieldDeclarationSyntax.AddSortingKey(this, procedureName));
            MembersToAdd.Add(tvpGeneratorClass.AddSortingKey(this, procedureName));
            MembersToAdd.Add(tvpHolderStruct.AddSortingKey(this, procedureName));

            base.Visit(node);
        }
示例#12
0
        public void ScanReturnValues(StoredProcedureReport spReport,
                                     CreateProcedureStatement sp)
        {
            var returnValueVisitor = new SelectElementVisitor();
            var spText             = ParseSpText(sp);

            sp.Accept(returnValueVisitor);

            foreach (var returnValue in returnValueVisitor.ReturnValues)
            {
                ParseSelectElement(returnValue, spText, spReport);
            }
        }
            public override void ExplicitVisit(CreateProcedureStatement node)
            {
                if (ProcedureName != null)
                {
                    throw new FormatException("Only one procedure definition is allowed per a script");
                }

                ProcedureName = new ProcedureNameInfo(
                    node.ProcedureReference.Name.BaseIdentifier.Value,
                    node.ProcedureReference.Name.SchemaIdentifier?.Value
                    );
                base.ExplicitVisit(node);
            }
示例#14
0
        public override void Visit(CreateProcedureStatement proc)
        {
            var name = new SqlObjectName();
            var son  = proc.ProcedureReference.Name;

            name.Schema = son.SchemaIdentifier?.Value.UnQuote();
            name.Object = son.BaseIdentifier?.Value.UnQuote();

            if (name.Object.ToLowerInvariant().StartsWith("test"))
            {
                Procedures.Add(new SqlProcedure(name, _path, _offset + proc.StartOffset, proc.FragmentLength, _lineOffset + proc.StartLine));
            }

            base.Visit(proc);
        }
示例#15
0
        public override void ExplicitVisit(CreateProcedureStatement node)
        {
            var setOptionsVisitor = new BalancedNumberSetOptionsNoCountVisitor();

            node.Accept(setOptionsVisitor);

            var selectStatementVisitor = new SelectStatmentVisitor();

            node.Accept(selectStatementVisitor);
            if (selectStatementVisitor.SelectStatements.Any())
            {
                this.ShouldRunBalancedCheck = true;
            }

            var deleteStatementVisitor = new DeleteStatementVisitor();

            node.Accept(deleteStatementVisitor);
            if (deleteStatementVisitor.DeleteStatements.Any())
            {
                this.ShouldRunBalancedCheck = true;
            }

            var updateStatementVisitor = new UpdateStatementVisitor();

            node.Accept(updateStatementVisitor);
            if (updateStatementVisitor.UpdateStatements.Any())
            {
                this.ShouldRunBalancedCheck = true;
            }

            var insertStatmentVisitor = new InsertStatementVisitor();

            node.Accept(insertStatmentVisitor);
            if (insertStatmentVisitor.InsertStatements.Any())
            {
                this.ShouldRunBalancedCheck = true;
            }

            var mergeStatementVisitor = new MergeStatmentVisitor();

            node.Accept(mergeStatementVisitor);
            if (mergeStatementVisitor.MergeStatements.Any())
            {
                this.ShouldRunBalancedCheck = true;
            }

            this.SetStatements = setOptionsVisitor.SetStatements;
        }
        /// <summary>
        /// Wraps input statements into block statement. Create create procedure statement if required by config.
        /// </summary>
        /// <param name="inputStatements">List of input statements</param>
        /// <param name="mod">Modifier</param>
        /// <returns></returns>
        private BlockStatement WrapInputStatements(IList <Statement> inputStatements, Modifier mod)
        {
            BlockStatement retStatement;

            // inputStatements[0] is always StartSQLStatement
            if (Config.CreateProcedure && !(inputStatements[1] is CreateProcedureStatement))
            {
                CreateProcedureStatement procedure = new CreateProcedureStatement(new DbObject(new Identifier(IdentifierType.Plain, mod.ProcPool.GetNewProcedureName())), -1,
                                                                                  new List <ProcedureParameter> {
                }, null, false, inputStatements as List <Statement>);
                procedure.Declarations = new BlockStatement();
                retStatement           = new BlockStatement(procedure);
            }
            else
            {
                retStatement = new BlockStatement(inputStatements);
            }

            return(retStatement);
        }
示例#17
0
        public void ScanSpParameters(StoredProcedureReport spReport,
                                     CreateProcedureStatement sp)
        {
            if (sp.Parameters.Count == 0)
            {
                return;
            }

            foreach (var p in sp.Parameters)
            {
                var isDefaulted = p.Value != null;
                var length      = ParseLength(p);

                var entry =
                    new ParamSqlReportEntry(p.VariableName.Value,
                                            p.DataType.Name.BaseIdentifier.Value,
                                            length,
                                            isDefaulted);

                spReport.Parameters.Add(entry);
            }
        }
 public override void ExplicitVisit(CreateProcedureStatement node)
 {
     IsProcedure = true;
 }
示例#19
0
 public override void Visit(CreateProcedureStatement node)
 {
     CreatedProcedures.Add(node);
     base.Visit(node);
 }
示例#20
0
 protected override void VisitCreateProcedureStatement(CreateProcedureStatement statement)
 {
     throw new NotImplementedException();
 }
示例#21
0
        public void ProcessTsqlFragment(TSqlFragment fragment)
        {
            String stmtType = GetFragmentType(fragment);

            //Console.WriteLine(StmtType);
            switch (stmtType)
            {
            case "CreateTableStatement":
                CreateTableStatement tblStmt = (CreateTableStatement)fragment;
                CurrentType   = "Table";
                CurrentObject = (tblStmt.SchemaObjectName.DatabaseIdentifier == null ? this.databaseName : tblStmt.SchemaObjectName.DatabaseIdentifier.Value) + "." +
                                (tblStmt.SchemaObjectName.SchemaIdentifier == null ? this.schemaName : tblStmt.SchemaObjectName.SchemaIdentifier.Value) + "." +
                                (tblStmt.SchemaObjectName.BaseIdentifier == null ? "" : tblStmt.SchemaObjectName.BaseIdentifier.Value);
                addNode(CurrentObject, "Table");
                CurrentType = "";
                break;

            case "CreateViewStatement":

                CreateViewStatement vw = (CreateViewStatement)fragment;
                CurrentType   = "View";
                CurrentObject = (vw.SchemaObjectName.DatabaseIdentifier == null ? this.databaseName : vw.SchemaObjectName.DatabaseIdentifier.Value) + "." +
                                (vw.SchemaObjectName.SchemaIdentifier == null ? this.schemaName : vw.SchemaObjectName.SchemaIdentifier.Value) + "." +
                                (vw.SchemaObjectName.BaseIdentifier == null ? "" : vw.SchemaObjectName.BaseIdentifier.Value);
                addNode(CurrentObject, "View");


                ProcessSelectStatement(vw.SelectStatement);
                CurrentType = "";


                break;

            case "CreateProcedureStatement":
                CreateProcedureStatement prc = (CreateProcedureStatement)fragment;
                CurrentType = "Proc";

                CurrentObject = (prc.ProcedureReference.Name.DatabaseIdentifier == null ? this.databaseName : prc.ProcedureReference.Name.DatabaseIdentifier.Value) + "." +
                                (prc.ProcedureReference.Name.SchemaIdentifier == null ? this.schemaName : prc.ProcedureReference.Name.SchemaIdentifier.Value) + "." +
                                (prc.ProcedureReference.Name.BaseIdentifier == null ? "" : prc.ProcedureReference.Name.BaseIdentifier.Value);
                addNode(CurrentObject, "Proc");

                ProcessCreateProcedure(prc);
                CurrentType = "";

                break;

            case "SelectStatement":
                ProcessSelectStatement((SelectStatement)fragment);
                break;

            case "BeginEndBlockStatement":
                ProcessBeginEndBlockStatement((BeginEndBlockStatement)fragment);
                break;

            case "TryCatchStatement":
                ProcessTryCatchStatement((TryCatchStatement)fragment);
                break;

            case "UpdateStatement":
                ProcessUpdateStatement((UpdateStatement)fragment);
                break;

            case "InsertStatement":
                ProcessInsertStatement((InsertStatement)fragment);
                break;

            case "IfStatement":
                ProcessIfStatement((IfStatement)fragment);
                break;

            case "BeginTransactionStatement":
                break;

            default:
                break;
            }
        }
示例#22
0
 public override void ExplicitVisit(CreateProcedureStatement node)
 {
     ProcedureName = node.ProcedureReference.Name.BaseIdentifier.Value;
     ParseParameters(node.Parameters);
     base.ExplicitVisit(node);
 }
示例#23
0
 public override void ExplicitVisit(CreateProcedureStatement node)
 {
     VisitHelper(node);
 }
示例#24
0
 public override void ExplicitVisit(CreateProcedureStatement node)
 {
     VisitHelper(node);
 }
 public override void ExplicitVisit(CreateProcedureStatement fragment)
 {
     _fragments.Add(fragment);
 }
示例#26
0
 public override void Visit(CreateProcedureStatement node)
 {
     base.Visit(node);
     stmts.Add(node);
 }
示例#27
0
 public override void ExplicitVisit(CreateProcedureStatement proc)
 {
     if (IsSupportedForCurrentType(proc.GetType())
         && proc.ProcedureReference != null)
     {
         Name = proc.ProcedureReference.Name;
     }
 }
示例#28
0
 public override void Visit(CreateProcedureStatement createProcedureStatement)
 {
     ExtractSchemaAndProcedureNameIdentifiers(createProcedureStatement.ProcedureReference);
 }
示例#29
0
 protected abstract void VisitCreateProcedureStatement(CreateProcedureStatement statement);
示例#30
0
        public CreateProcedureStatement Convert(CStoredProcedure storedProcedure)
        {
            //build body

            string[] parts = { storedProcedure.Schema.SchemaName, storedProcedure.StoredProcedureName };

            var createStoredProcedure = new CreateProcedureStatement();

            ///set schema and table name
            ///
            var schemaObjectName = new SchemaObjectName();

            schemaObjectName.Identifiers.Add(new Identifier {
                Value = storedProcedure.Schema.SchemaName
            });
            schemaObjectName.Identifiers.Add(new Identifier {
                Value = storedProcedure.StoredProcedureName
            });

            createStoredProcedure.ProcedureReference      = new ProcedureReference();
            createStoredProcedure.ProcedureReference.Name = schemaObjectName;

            //add parameters


            foreach (var param in storedProcedure.Parameter)
            {
                if (param.ParameterTypeIsUserDefined)
                {
                    var dataType = new UserDataTypeReference();
                    dataType.Name = new SchemaObjectName();
                    dataType.Name.Identifiers.Add(new Identifier {
                        Value = param.ParameterTypeRaw
                    });
                    if (param.ParameterLength > 0)
                    {
                        dataType.Parameters.Add(new IntegerLiteral {
                            Value = param.ParameterLength.ToString()
                        });
                    }

                    createStoredProcedure.Parameters.Add(new ProcedureParameter
                    {
                        VariableName = new Identifier {
                            Value = $"@{param.ParameterName}"
                        },
                        DataType = dataType,
                        Value    = param.DefaultToNull ? new NullLiteral() : null,
                        Modifier = param.ParameterTypeRaw.ToLower() == "sysname" ? ParameterModifier.None: ParameterModifier.ReadOnly //todo
                    });
                }
                else
                {
                    var dataType      = new SqlDataTypeReference();
                    var parameterName = param.ParameterName;
                    if (param.IsCollection)
                    {
                        parameterName += "_Collection";// temp solution for comma separate collection parameters
                    }
                    if (param.ParameterTypeRaw == "enum")
                    {
                        dataType.SqlDataTypeOption = SqlDataTypeOption.Int; //todo: review this
                    }
                    else
                    {
                        dataType.SqlDataTypeOption = SqlMapper.SqlTypeToSqlDataTypeOption(param.ParameterTypeRaw);
                    }

                    if (param.ParameterLength > 0)
                    {
                        dataType.Parameters.Add(new IntegerLiteral {
                            Value = param.ParameterLength.ToString()
                        });
                    }

                    createStoredProcedure.Parameters.Add(new ProcedureParameter
                    {
                        VariableName = new Identifier {
                            Value = $"@{parameterName}"
                        },
                        DataType = dataType,
                        Value    = param.DefaultToNull ? new NullLiteral() : null
                    });
                }
            }

            var parser = new TSql120Parser(false);

            createStoredProcedure.StatementList = new StatementList();
            if (!string.IsNullOrEmpty(storedProcedure.StoredProcedureBody))
            {
                IList <ParseError> errors;
                var script2 =
                    parser.Parse(new StringReader(storedProcedure.StoredProcedureBody), out errors) as TSqlScript;
                if (errors.Count > 0)
                {
                    RaiseSqlErrorsException(errors, storedProcedure.StoredProcedureBody);
                }
                foreach (var batch2 in script2.Batches)
                {
                    foreach (var statement in batch2.Statements)
                    {
                        createStoredProcedure.StatementList.Statements.Add(statement);
                    }
                }
            }

            return(createStoredProcedure);
        }
示例#31
0
        private static string ChangeCreateToAlter(CreateProcedureStatement procedure, string wholeScript)
        {
            //get part of script we are interested in...
            var subScript = wholeScript.Substring(procedure.StartOffset, procedure.FragmentLength);

            IList<ParseError> errors;
            var fragment = new TSql130Parser(false).Parse(new StringReader(subScript), out errors);

            bool haveCreate = false;
            var output = new StringBuilder();

            foreach (var token in fragment.ScriptTokenStream)
            {
                if (!haveCreate && token.TokenType == TSqlTokenType.Create)
                {
                    var alterToken = new TSqlParserToken(TSqlTokenType.Alter, "alter");
                    output.Append(alterToken.Text);
                    haveCreate = true;
                    continue;
                }

                output.Append(token.Text);
            }

            return output.ToString();
        }
示例#32
0
 public void ProcessCreateProcedure(CreateProcedureStatement prcStmt)
 {
     foreach (var stmt in prcStmt.StatementList.Statements)
     {
         ProcessTsqlFragment(stmt);
     }
 }
示例#33
0
 public override void Visit(CreateProcedureStatement node)
 {
     Statements.Add(node);
 }
        private MemberDeclarationSyntax AddPopulateCommandMethodForTableValuedParameters(CreateProcedureStatement node, string procedureName)
        {
            var nonTableParameters = new List <ProcedureParameter>();
            var tableParameters    = new List <ProcedureParameter>();

            foreach (var procedureParameter in node.Parameters)
            {
                if (TryGetSqlDbTypeForParameter(procedureParameter, out _))
                {
                    nonTableParameters.Add(procedureParameter);
                }
                else
                {
                    tableParameters.Add(procedureParameter);
                }
            }

            if (tableParameters.Count == 0)
            {
                return(IncompleteMember());
            }

            string tableValuedParametersParameterName = "tableValuedParameters";

            return(MethodDeclaration(
                       typeof(void).ToTypeSyntax(),
                       Identifier(PopulateCommandMethodName))
                   .AddModifiers(Token(SyntaxKind.PublicKeyword))

                   // first parameter is the SqlCommand
                   .AddParameterListParameters(Parameter(Identifier(CommandParameterName)).WithType(ParseTypeName("SqlCommandWrapper")))

                   // Add a parameter for each non-TVP
                   .AddParameterListParameters(nonTableParameters.Select(selector: p =>
                                                                         Parameter(Identifier(ParameterNameForParameter(p)))
                                                                         .WithType(DataTypeReferenceToClrType(p.DataType, p.Value != null))).ToArray())

                   // Add a parameter for the TVP set
                   .AddParameterListParameters(
                       Parameter(Identifier(tableValuedParametersParameterName)).WithType(IdentifierName(TableValuedParametersStructName(procedureName))))

                   // Call the overload
                   .AddBodyStatements(
                       ExpressionStatement(
                           InvocationExpression(
                               IdentifierName(PopulateCommandMethodName))
                           .AddArgumentListArguments(Argument(IdentifierName(CommandParameterName)))
                           .AddArgumentListArguments(
                               nonTableParameters.Select(p =>
                                                         Argument(IdentifierName(ParameterNameForParameter(p)))
                                                         .WithNameColon(NameColon(ParameterNameForParameter(p)))).ToArray())
                           .AddArgumentListArguments(
                               tableParameters.Select(p =>
                                                      Argument(MemberAccessExpression(
                                                                   SyntaxKind.SimpleMemberAccessExpression,
                                                                   IdentifierName(tableValuedParametersParameterName),
                                                                   IdentifierName(PropertyNameForParameter(p))))
                                                      .WithNameColon(NameColon(ParameterNameForParameter(p)))).ToArray()))));
        }
            public override void ExplicitVisit(CreateProcedureStatement node)
            {
                if (ProcedureName != null)
                {
                    throw new FormatException("Only one procedure definition is allowed per a script");
                }

                ProcedureName = new ProcedureNameInfo(
                    node.ProcedureReference.Name.BaseIdentifier.Value,
                    node.ProcedureReference.Name.SchemaIdentifier?.Value
                );
                base.ExplicitVisit(node);
            }
示例#36
0
 public override void Visit(CreateProcedureStatement node)
 {
     Statements.Add(node);
 }
        private (MemberDeclarationSyntax tvpGeneratorClass, MemberDeclarationSyntax tvpHolderStruct) CreateTvpGeneratorTypes(CreateProcedureStatement node, string procedureName)
        {
            List <(string parameterName, string rowStructName)> rowTypes = node.Parameters
                                                                           .Where(p => !TryGetSqlDbTypeForParameter(p, out _))
                                                                           .Select(p => (parameterName: PropertyNameForParameter(p), rowStructName: GetRowStructNameForTableType(p.DataType.Name)))
                                                                           .ToList();

            if (rowTypes.Count == 0)
            {
                // no table-valued parameters on this procedure
                return(IncompleteMember(), IncompleteMember());
            }

            var holderStructName = TableValuedParametersStructName(procedureName);

            // create a struct with properties for each table-valued parameter

            var structDeclaration = StructDeclaration(holderStructName)
                                    .AddModifiers(Token(SyntaxKind.InternalKeyword))

                                    // Add a constructor with parameters for each column, setting the associated property for each column.
                                    .AddMembers(
                ConstructorDeclaration(
                    Identifier(holderStructName))
                .WithModifiers(
                    TokenList(
                        Token(SyntaxKind.InternalKeyword)))
                .AddParameterListParameters(
                    rowTypes.Select(p =>
                                    Parameter(Identifier(p.parameterName))
                                    .WithType(TypeExtensions.CreateGenericTypeFromGenericTypeDefinition(
                                                  typeof(IEnumerable <>).ToTypeSyntax(true),
                                                  IdentifierName(p.rowStructName)))).ToArray())
                .WithBody(
                    Block(rowTypes.Select(p =>
                                          ExpressionStatement(
                                              AssignmentExpression(
                                                  SyntaxKind.SimpleAssignmentExpression,
                                                  left: MemberAccessExpression(
                                                      SyntaxKind.SimpleMemberAccessExpression,
                                                      ThisExpression(),
                                                      IdentifierName(p.parameterName)),
                                                  right: IdentifierName(p.parameterName)))))))

                                    // Add a property for each column
                                    .AddMembers(rowTypes.Select(p =>
                                                                (MemberDeclarationSyntax)PropertyDeclaration(
                                                                    TypeExtensions.CreateGenericTypeFromGenericTypeDefinition(
                                                                        typeof(IEnumerable <>).ToTypeSyntax(true),
                                                                        IdentifierName(p.rowStructName)),
                                                                    Identifier(p.parameterName))
                                                                .AddModifiers(Token(SyntaxKind.InternalKeyword))
                                                                .AddAccessorListAccessors(AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                                                                                          .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)))).ToArray());

            string className = $"{procedureName}TvpGenerator";

            List <string> distinctTvpTypeNames = rowTypes.Select(r => r.rowStructName).Distinct().ToList();

            var classDeclaration = ClassDeclaration(className)
                                   .AddTypeParameterListParameters(TypeParameter(TvpGeneratorGenericTypeName))
                                   .AddBaseListTypes(
                SimpleBaseType(
                    GenericName("IStoredProcedureTableValuedParametersGenerator")
                    .AddTypeArgumentListArguments(
                        IdentifierName(TvpGeneratorGenericTypeName),
                        IdentifierName(holderStructName))))
                                   .AddModifiers(Token(SyntaxKind.InternalKeyword))
                                   .AddMembers(
                ConstructorDeclaration(Identifier(className))
                .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword)))
                .AddParameterListParameters(distinctTvpTypeNames
                                            .Select(t =>
                                                    Parameter(Identifier(GeneratorFieldName(t)))
                                                    .WithType(GeneratorType(t))).ToArray())
                .WithBody(
                    Block(distinctTvpTypeNames
                          .Select(t =>
                                  ExpressionStatement(
                                      AssignmentExpression(
                                          SyntaxKind.SimpleAssignmentExpression,
                                          left: MemberAccessExpression(
                                              SyntaxKind.SimpleMemberAccessExpression,
                                              ThisExpression(),
                                              IdentifierName(GeneratorFieldName(t))),
                                          right: IdentifierName(GeneratorFieldName(t))))))))
                                   .AddMembers(
                distinctTvpTypeNames
                .Select(t => (MemberDeclarationSyntax)FieldDeclaration(
                            VariableDeclaration(GeneratorType(t))
                            .AddVariables(VariableDeclarator(GeneratorFieldName(t))))
                        .AddModifiers(Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.ReadOnlyKeyword))).ToArray())
                                   .AddMembers(
                MethodDeclaration(IdentifierName(holderStructName), Identifier("Generate"))
                .AddModifiers(Token(SyntaxKind.PublicKeyword))
                .AddParameterListParameters(Parameter(Identifier("input")).WithType(IdentifierName(TvpGeneratorGenericTypeName)))
                .AddBodyStatements(
                    ReturnStatement(
                        ObjectCreationExpression(IdentifierName(holderStructName))
                        .AddArgumentListArguments(
                            rowTypes.Select(p => Argument(
                                                InvocationExpression(
                                                    MemberAccessExpression(
                                                        SyntaxKind.SimpleMemberAccessExpression,
                                                        IdentifierName(GeneratorFieldName(p.rowStructName)),
                                                        IdentifierName("GenerateRows")))
                                                .AddArgumentListArguments(Argument(IdentifierName("input"))))).ToArray()))));

            return(classDeclaration, structDeclaration);
        }
 protected override void VisitCreateProcedureStatement(CreateProcedureStatement statement)
 {
     VisitProcedureAndBodyParameters(statement, true, statement.CheckIfNotExists);
 }
示例#39
0
 public override void Visit(CreateProcedureStatement node) { this.action(node); }
示例#40
0
 public override void Visit(CreateProcedureStatement node)
 {
     base.Visit(node);
     stmts.Add(node);
 }