public async Task HandleActor(StatementBase statement, IStatementBaseEntity newStatement, CancellationToken cancellationToken) { var actor = (AgentEntity)await _mediator.Send(UpsertActorCommand.Create(statement.Actor), cancellationToken); newStatement.ActorId = actor.AgentId; newStatement.Actor = null; }
public void NextTokenShouldNotReturnWhiteSpaceToken() { TokenBase identifier = TokenCreator.Create <IdentifierToken>("test"); TokenBase space = TokenCreator.Create <SpaceToken>(); StatementBase classStatement = StatementCreator.CreateClassStatement(); StatementBase memberStatement = StatementCreator.CreateMemberStatement("test"); IList <TokenBase> totalList = new List <TokenBase>(); foreach (TokenBase aToken in classStatement.Tokens) { totalList.Add(aToken); } foreach (TokenBase aToken in memberStatement.Tokens) { totalList.Add(aToken); } totalList.Add(space); totalList.Add(identifier); IList <TokenBase> identifierList = new List <TokenBase>(); identifierList.Add(space); identifierList.Add(identifier); _manager.Encountered(new[] { classStatement }, classStatement.Tokens.Count(), totalList); Assert.AreEqual(identifier, _manager.GetContext(memberStatement.Tokens).NextTokenFromCurrentStatement); }
public async Task HandleContext(StatementBase statement, IStatementBaseEntity newStatement, CancellationToken cancellationToken) { if (statement.Context != null) { newStatement.Context = _mapper.Map <ContextEntity>(statement.Context); ContextEntity context = newStatement.Context; if (context.Instructor != null) { var instructor = (AgentEntity)await _mediator.Send(UpsertActorCommand.Create(statement.Context.Instructor), cancellationToken); context.InstructorId = instructor.AgentId; context.Instructor = null; } if (context.Team != null) { var team = (AgentEntity)await _mediator.Send(UpsertActorCommand.Create(statement.Context.Team), cancellationToken); context.TeamId = team.AgentId; context.Team = null; } if (context.ContextActivities != null) { foreach (var contextActivity in context.ContextActivities) { Iri id = new Iri(contextActivity.Activity.Id); var activity = await _mediator.Send(UpsertActivityCommand.Create(id), cancellationToken); contextActivity.Activity = null; contextActivity.ActivityId = activity.ActivityId; } } } }
private StatementBase AddNewStatement(Type type, Token InputToken, YangAddingOption opt = YangAddingOption.None) { StatementBase instantiatedobj; try { instantiatedobj = (StatementBase)Activator.CreateInstance(type, InputToken.TokenArgument); } catch (Exception e) { if (e.InnerException != null) { throw e.InnerException; } else { throw e; } } instantiatedobj = TracerCurrentNode.AddStatement(instantiatedobj); if (opt == YangAddingOption.None && !typeof(ChildlessStatement).IsAssignableFrom(instantiatedobj.GetType())) { TracerCurrentNode = instantiatedobj; NewInterpreterStatus(InputToken.TokenAsType); } else if (opt == YangAddingOption.ChildIncapable) { NewInterpreterStatus(InputToken.TokenAsType); } return(instantiatedobj); }
public async Task HandleObject(StatementBase statement, IStatementBaseEntity newStatement, CancellationToken cancellationToken) { var objType = statement.Object.ObjectType; if (objType == ObjectType.Activity) { var activity = await _mediator.Send(UpsertActivityCommand.Create((Activity)statement.Object), cancellationToken); newStatement.ObjectType = EntityObjectType.Activity; newStatement.ObjectId = activity.ActivityId; } else if (objType == ObjectType.Agent || objType == ObjectType.Group) { AgentEntity agent = await _mediator.Send(UpsertActorCommand.Create((Agent)statement.Object), cancellationToken);; newStatement.ObjectType = EntityObjectType.Agent; newStatement.ObjectId = agent.AgentId; } else if (objType == ObjectType.SubStatement) { SubStatementEntity subStatement = await _mediator.Send(CreateSubStatementCommand.Create((SubStatement)statement.Object), cancellationToken); newStatement.ObjectType = EntityObjectType.SubStatement; newStatement.ObjectId = subStatement.SubStatementId; } else if (objType == ObjectType.StatementRef) { StatementRef statementRef = (StatementRef)statement.Object; newStatement.ObjectType = EntityObjectType.StatementRef; newStatement.ObjectId = statementRef.Id; } }
public void TestWhere() { StatementBase sql = SqlBuilder.Database(Dialect.SqlServer2005). Select.All.Form("table1").As("t1").Where("t1.id>10").And("t1.id<100").Or("1=2"); Assert.AreEqual(sql.ToString(), "select * form table1 as t1 where t1.id>10 and t1.id<100 or 1=2"); }
public void Dispose() { if (!_disposed) { _disposed = true; try { Release(); } catch (IscException ex) { throw FbException.Create(ex); } _multiError = false; //_commandTimeout = 0; //_fetchSize = 0; _implicitTransaction = false; _commandText = null; _connection = null; _transaction = null; _batchParameters = null; _statement = null; //_activeReader = null; _namedParameters = null; } }
public override StatementBase AddStatement(StatementBase Node) { if (Root == null) { Root = this; } if (Node.GetType() == typeof(YangVersionStatement)) { var version = Descendants("yang-version")?.Single(); if (version != null) { return(version); } } else if (Node.GetType() == typeof(PrefixStatement)) { Prefix = Node.Argument; } else if (Node.GetType() == typeof(NamespaceStatement)) { Namespace = Node.Argument; } base.AddStatement(Node); return(Node); }
protected override void Dispose(bool disposing) { if (disposing) { if (!_disposed) { _disposed = true; Release(); _commandTimeout = 0; _fetchSize = 0; _implicitTransaction = false; _commandText = null; _connection = null; _transaction = null; _parameters = null; _statement = null; _activeReader = null; if (_namedParameters != null) { _namedParameters.Clear(); _namedParameters = null; } } } base.Dispose(disposing); }
public async ValueTask DisposeAsync() { if (!_disposed) { _disposed = true; try { await ReleaseAsync(CancellationToken.None).ConfigureAwait(false); } catch (IscException ex) { throw FbException.Create(ex); } _multiError = false; //_commandTimeout = 0; //_fetchSize = 0; _implicitTransaction = false; _commandText = null; _connection = null; _transaction = null; _batchParameters = null; _statement = null; //_activeReader = null; _namedParameters = null; } }
public int Prepare(string sql, short paramCount) { try { if (this.statement != null) { this.Release(); } this.transactionId = this.connection.GetTransactionId(); if (this.transactionId < 0) { this.connection.BeginTransaction(this.transactionId, (int)(IsolationLevel.ReadCommitted)); } ITransaction transaction = (ITransaction)this.connection.Transactions[this.transactionId]; this.statement = this.connection.Database.CreateStatement(transaction); this.statement.Prepare(sql); this.statement.Describe(); this.statement.DescribeParameters(); } catch (IscException e) { this.lastError = e; this.RollbackImplicitTransaction(); } return(this.GetErrorCode()); }
public static bool TryGetPlSqlUnitName(StatementBase statement, out OracleObjectIdentifier objectIdentifier) { objectIdentifier = OracleObjectIdentifier.Empty; switch (statement.RootNode.Id) { case NonTerminals.CreatePlSqlStatement: var createPlSqlObjectClause = statement.RootNode[NonTerminals.CreatePlSqlObjectClause]; if (createPlSqlObjectClause != null && createPlSqlObjectClause.ChildNodes.Count == 1) { var createFunctionNode = createPlSqlObjectClause[NonTerminals.CreateFunction, NonTerminals.PlSqlFunctionSource]; createPlSqlObjectClause = createFunctionNode ?? createPlSqlObjectClause.ChildNodes[0]; objectIdentifier = GetObjectIdentifierFromNode(createPlSqlObjectClause[NonTerminals.SchemaObject]); } break; case NonTerminals.StandaloneStatement: var alterObjectClause = statement.RootNode[NonTerminals.Statement, NonTerminals.AlterStatement, NonTerminals.AlterObjectClause]; if (alterObjectClause != null && alterObjectClause.ChildNodes.Count == 1 && alterObjectClause.ChildNodes[0].Id.In(NonTerminals.AlterProcedure, NonTerminals.AlterFunction, NonTerminals.AlterPackage)) { objectIdentifier = GetObjectIdentifierFromNode(alterObjectClause.ChildNodes[0][NonTerminals.SchemaObject]); } break; } return(!String.IsNullOrEmpty(objectIdentifier.Name)); }
public async Task HandleVerb(StatementBase statement, IStatementBaseEntity newStatement, CancellationToken cancellationToken) { var verb = (VerbEntity)await _mediator.Send(UpsertVerbCommand.Create(statement.Verb), cancellationToken); newStatement.VerbId = verb.VerbId; newStatement.Verb = null; }
public static StatementBase Validate(this StatementBase statement) { if (statement.RootNode == null || statement.RootNode.TerminalCount <= 1) { return(statement); } var sortedTerminals = statement.AllTerminals.OrderBy(t => t.SourcePosition.IndexStart).ToArray(); var terminal = sortedTerminals[0]; var allTerminals = statement.AllTerminals.ToArray(); for (var i = 1; i < sortedTerminals.Length; i++) { var followingTerminal = sortedTerminals[i]; if (terminal.SourcePosition.IndexEnd >= followingTerminal.SourcePosition.IndexStart) { throw new InvalidOperationException($"Terminals '{terminal.Id}' and '{followingTerminal.Id}' within the statement are overlapping. "); } if (followingTerminal != allTerminals[i]) { throw new InvalidOperationException($"Terminals within the statement are in invalid order (index {i}). "); } terminal = followingTerminal; } return(statement); }
/// <summary> /// Checks if the rule is valid for the statement /// </summary> /// <param name="statement">The statement</param> /// <returns>True if valid, otherwise false</returns> public override bool IsValidFor(StatementBase statement) { MemberStatement memberStatement = (MemberStatement)statement; bool matchesExpression = _expression.IsMatch(memberStatement.MemberNameToken.Content); //either true or must be public static to be true return(matchesExpression || (memberStatement.AccessModifierToken is PublicModifierToken && memberStatement.StaticToken != null)); }
public void TestForm() { StatementBase sql = SqlBuilder.Database(Dialect.SqlServer2005).Select.All.Form("table1").As("t1"); Assert.AreEqual(sql.ToString(), "select * form table1 as t1"); sql = SqlBuilder.Database(Dialect.SqlServer2005).Select.All.Form("table1").As("t1").Form("table2 as t2"); Assert.AreEqual(sql.ToString(), "select * form table1 as t1,table2 as t2"); }
public override StatementBase AddStatement(StatementBase StatementToAdd) { if (TypeStatement.CountTypes(Elements()) >= 1 && typeof(TypeStatement).IsAssignableFrom(StatementToAdd.GetType())) { throw new ArgumentOutOfRangeException(StatementToAdd.GetType().ToString(), "Cannot add more " + StatementToAdd.GetType().ToString() + " into " + GetType().ToString() + ", maximum amount reached: 1"); } return(base.AddStatement(StatementToAdd)); }
public Task HandleResult(StatementBase statement, IStatementBaseEntity newStatement, CancellationToken cancellationToken) { if (statement.Result != null) { newStatement.Result = _mapper.Map <ResultEntity>(statement.Result); } return(Task.CompletedTask); }
private void VisitNext(StatementBase stm) { var st = NextStms(stm); if (st != null) { Visit((dynamic)st); } }
public async Task HandleStatementBase(StatementBase statement, IStatementBaseEntity newStatement, CancellationToken cancellationToken) { newStatement.Timestamp = statement.Timestamp ?? DateTimeOffset.UtcNow; await HandleVerb(statement, newStatement, cancellationToken); await HandleActor(statement, newStatement, cancellationToken); await HandleObject(statement, newStatement, cancellationToken); await HandleContext(statement, newStatement, cancellationToken); await HandleResult(statement, newStatement, cancellationToken); }
internal UnionStatement(SqlBuilder context, StatementBase statmen) : base(context) { if (this.Context.Statements.First() == this) { this.StatementBock = string.Format(" {0}", statmen.ToString()); } else { this.StatementBock = string.Format("\n{0}\n {1}", Symbol, statmen.ToString()); } }
/// <summary> /// 子查询 /// </summary> /// <param name="context">当前context</param> /// <param name="statment">子查询</param> internal FormStatment(SqlBuilder context, StatementBase statment) : base(context) { if (this.Context.Statements.First(item => item.GetType() == typeof(FormStatment)) == this) { this.StatementBock = string.Format("{0} {1}", this.Symbol, statment); } else { this.StatementBock = string.Format(", ({1})", this.Symbol, statment); } }
/// <summary> /// Builds the output string from the given error, token and status stack. /// </summary> /// <param name="StatementWithParseError"></param> /// <param name="StatusStack"></param> /// <param name="ParsedToken"></param> /// <returns></returns> private string BuildOutputString(StatementBase StatementWithParseError, Stack <Type> StatusStack, Token ParsedToken) { string strBuilder = string.Empty; strBuilder += "Error at row: " + RowNumber + Environment.NewLine; strBuilder += "Row content:-->" + Row + "<--" + Environment.NewLine; strBuilder += "The interpreter parsed the previously mentioned line as:-->" + ParsedToken.TokenType + "<--" + Environment.NewLine; strBuilder += "The last yang statement was parsed as: " + Environment.NewLine; strBuilder += StatementWithParseError.StatementAsYangString() + Environment.NewLine; strBuilder += "Stack trace: " + MakeStatusStackIntoString(StatusStack); return(strBuilder); }
/// <summary> /// Builds the output string from the given error and status stack if the token creation wasnt successful. /// </summary> /// <param name="StatementWithParseError"></param> /// <param name="StatusStack"></param> /// <returns></returns> private string BuildOutputString(StatementBase StatementWithParseError, Stack <Type> StatusStack) { string strBuilder = string.Empty; strBuilder += "Error at row: " + RowNumber + Environment.NewLine; strBuilder += "Row content: " + Row + Environment.NewLine; strBuilder += "The interpreter could not parse the mentioned row." + Environment.NewLine; strBuilder += "The last yang statement was parsed as: " + Environment.NewLine; strBuilder += StatementWithParseError.StatementAsYangString() + Environment.NewLine; strBuilder += "Stack trace: " + MakeStatusStackIntoString(StatusStack); return(strBuilder); }
/// <summary> /// Creates log in the desired location. Returns false if failed. /// </summary> /// <param name="StatementWithParseError"></param> /// <param name="StatusStack"></param> /// <returns></returns> public bool CreateLog(StatementBase StatementWithParseError, Stack <Type> StatusStack) { try { string LogText = BuildOutputString(StatementWithParseError, StatusStack); return(LogOnExpectedOutput(LogText)); } catch (Exception) { return(false); } }
public void StatementParentsShouldBeEqual() { StatementBase alphaStatement = StatementCreator.CreateMemberStatement("test"); StatementBase alphaDelimiter = StatementCreator.CreateOpenBlockStatement(); TokenCreator.Reset(); StatementBase bravoStatement = StatementCreator.CreateMemberStatement("test"); StatementBase bravoDelimiter = StatementCreator.CreateOpenBlockStatement(); StatementParent alpha = new StatementParent(new[] { alphaStatement }, alphaDelimiter); StatementParent bravo = new StatementParent(new[] { bravoStatement }, bravoDelimiter); Assert.AreEqual(alpha, bravo); }
public void Split(StatementBase stm) { var left = new CodeBlock { Namespace = Namespace, Node = Node, Statements = Statements.TakeWhile(x => x != stm).ToList() }; var right = new CodeBlock { Namespace = Namespace, Node = Node, Statements = Statements.ToArray().Reverse().TakeWhile(x => x != stm).Reverse().ToList() }; Statements = new List <StatementBase> { left, right }; Children.AddRange(new[] { left, right }); }
internal void Release() { this.RollbackImplicitTransaction(); if (this.connection != null && this.connection.State == ConnectionState.Open) { this.connection.InnerConnection.RemovePreparedCommand(this); } if (this.statement != null) { this.statement.Dispose(); this.statement = null; } }
private string GetIndentation(StatementBase statement) { if (ExecutionContext.SelectionStart < statement.RootNode.SourcePosition.IndexStart) { return(String.Empty); } var formattedTextStart = _formatSelectionOnly ? statement.GetNearestTerminalToPosition(ExecutionContext.SelectionStart).SourcePosition.IndexStart : statement.RootNode.SourcePosition.IndexStart; var lineStart = ExecutionContext.StatementText.LastIndexOfAny(new [] { '\n', '\r' }, formattedTextStart) + 1; var indentation = ExecutionContext.StatementText.Substring(lineStart, formattedTextStart - lineStart); return(TextHelper.ReplaceAllNonBlankCharactersWithSpace(indentation)); }
internal void Release() { RollbackImplicitTransaction(); //DisposeReader(); if (_connection != null && _connection.State == ConnectionState.Open) { _connection.InnerConnection.RemovePreparedCommand(this); } if (_statement != null) { _statement.Dispose2(); _statement = null; } }
public StatementGrammarNode(NodeType type, StatementBase statement, IToken token) : base(statement, token) { Type = type; if (type != NodeType.Terminal) { return; } if (token == null) { throw new ArgumentNullException(nameof(token)); } IsGrammarValid = true; FirstTerminalNode = this; LastTerminalNode = this; _terminalCount = 1; }
private async Task<IReadOnlyList<CompilationError>> RetrieveCompilationErrors(StatementBase statement, CancellationToken cancellationToken) { var compilationErrorUpdater = new CompilationErrorDataProvider(statement, _currentSchema); await _databaseModel.UpdateModelAsync(true, cancellationToken, compilationErrorUpdater); return compilationErrorUpdater.Errors; }
private void Normalize(StatementBase statement) { foreach (var terminal in statement.AllTerminals) { var segment = new TextSegment { IndextStart = terminal.SourcePosition.IndexStart, Length = terminal.SourcePosition.Length, Text = FormatTerminal(terminal) }; ExecutionContext.SegmentsToReplace.Add(segment); } }
public static bool TryGetPlSqlUnitName(StatementBase statement, out OracleObjectIdentifier objectIdentifier) { objectIdentifier = OracleObjectIdentifier.Empty; switch (statement.RootNode.Id) { case NonTerminals.CreatePlSqlStatement: var createPlSqlObjectClause = statement.RootNode[NonTerminals.CreatePlSqlObjectClause]; if (createPlSqlObjectClause != null && createPlSqlObjectClause.ChildNodes.Count == 1) { var createFunctionNode = createPlSqlObjectClause[NonTerminals.CreateFunction, NonTerminals.PlSqlFunctionSource]; createPlSqlObjectClause = createFunctionNode ?? createPlSqlObjectClause.ChildNodes[0]; objectIdentifier = GetObjectIdentifierFromNode(createPlSqlObjectClause[NonTerminals.SchemaObject]); } break; case NonTerminals.StandaloneStatement: var alterObjectClause = statement.RootNode[NonTerminals.Statement, NonTerminals.AlterStatement, NonTerminals.AlterObjectClause]; if (alterObjectClause != null && alterObjectClause.ChildNodes.Count == 1 && alterObjectClause.ChildNodes[0].Id.In(NonTerminals.AlterProcedure, NonTerminals.AlterFunction, NonTerminals.AlterPackage)) { objectIdentifier = GetObjectIdentifierFromNode(alterObjectClause.ChildNodes[0][NonTerminals.SchemaObject]); } break; } return !String.IsNullOrEmpty(objectIdentifier.Name); }
private void FormatStatementAsSingleLine(StatementBase statement) { var builder = new StringBuilder(); IEnumerable<StatementNode> terminals = ((IEnumerable<StatementNode>)statement.AllTerminals).Concat(statement.Comments).OrderBy(t => t.Token.Index); if (ExecutionContext.SelectionLength > 0) { terminals = terminals.Where(t => t.SourcePosition.IndexStart <= ExecutionContext.SelectionEnd && t.SourcePosition.IndexEnd + 1 >= ExecutionContext.SelectionStart); } StatementNode precedingNode = null; var textSegment = new TextSegment(); foreach (var terminal in terminals) { var precedingGrammarTerminal = precedingNode as StatementGrammarNode; var grammarTerminal = terminal as StatementGrammarNode; if (precedingNode != null && precedingGrammarTerminal != null && !SingleLineNoSpaceAfterTerminals.Contains(precedingGrammarTerminal.Id) && grammarTerminal != null && !SingleLineNoSpaceBeforeTerminals.Contains(grammarTerminal.Id)) { builder.Append(' '); } builder.Append(FormatTerminal(terminal)); if (precedingNode == null) { textSegment.IndextStart = terminal.SourcePosition.IndexStart; } precedingNode = terminal; } if (precedingNode == null) { return; } textSegment.Length = precedingNode.SourcePosition.IndexEnd - textSegment.IndextStart + 1; textSegment.Text = builder.ToString(); ExecutionContext.SegmentsToReplace.Add(textSegment); }
private string GetIndentation(StatementBase statement) { if (ExecutionContext.SelectionStart < statement.RootNode.SourcePosition.IndexStart) { return String.Empty; } var formattedTextStart = _formatSelectionOnly ? statement.GetNearestTerminalToPosition(ExecutionContext.SelectionStart).SourcePosition.IndexStart : statement.RootNode.SourcePosition.IndexStart; var lineStart = ExecutionContext.StatementText.LastIndexOfAny(new [] { '\n', '\r' }, formattedTextStart) + 1; var indentation = ExecutionContext.StatementText.Substring(lineStart, formattedTextStart - lineStart); return TextHelper.ReplaceAllNonBlankCharactersWithSpace(indentation); }