public async Task ShouldThrowExceptionIfNullResult() { IStatementResultCursor result = null; var exception = await Record.ExceptionAsync(() => result.SingleAsync()); exception.Should().BeOfType <ArgumentNullException>(); }
public async Task <int> DropIndexAsync(string label, string propertyname) { string query = $"DROP INDEX ON :{label}({propertyname})"; int count = 0; using (ISession session = this._driver.Session()) { try { await session.ReadTransactionAsync(async (tx) => { IStatementResultCursor reader = await tx.RunAsync(query); await reader.ConsumeAsync(); IResultSummary summary = await reader.SummaryAsync(); count = summary.Counters.IndexesRemoved; }); } catch (Exception e) { this._logger.LogError(e, $"Error dropping index for label {label} on property {propertyname}"); } finally { await session.CloseAsync(); } } return(count); }
private async Task <ExerciseSession> GetExerciseSessionComplete(IStatementResultCursor reader) { var exerciseSession = new ExerciseSession(); while (await reader.FetchAsync()) { var exerciseSessionId = Guid.Parse(reader.Current[0].ToString()); if (exerciseSession.Id != exerciseSessionId) { exerciseSession = new ExerciseSession() { Id = exerciseSessionId, Note = reader.Current[1]?.ToString(), ExerciseName = reader.Current[2].ToString(), Records = new List <ExerciseRecord>() }; } exerciseSession.Records.Add(new ExerciseRecord() { Id = Guid.Parse(reader.Current[3].ToString()), EpochTimestamp = double.Parse(reader.Current[4].ToString()), Set = reader.Current[5].ToString(), Reps = (Int64)reader.Current[6], Value = double.Parse(reader.Current[7].ToString()), Unit = reader.Current[8]?.ToString(), DropSet = (bool)reader.Current[9], Note = reader.Current[10]?.ToString() }); } return(exerciseSession); }
public async Task <int> CreateIndexAsync(NewIndex newIndex) { string query = $"CREATE INDEX ON :{newIndex.Label}({newIndex.Property})"; int count = 0; using (ISession session = this._driver.Session()) { try { await session.ReadTransactionAsync(async (tx) => { IStatementResultCursor reader = await tx.RunAsync(query); await reader.ConsumeAsync(); IResultSummary summary = await reader.SummaryAsync(); count = summary.Counters.IndexesAdded; }); } catch (Exception e) { this._logger.LogError(e, $"Error creating index for label {newIndex.Label} on property {newIndex.Property}"); } finally { await session.CloseAsync(); } } return(count); }
public async Task <ResultSet> GetResultSetFromQueryAsync(string query, object props) { ResultSet returnedresults = new ResultSet(); using (ISession session = this._driver.Session()) { try { await session.ReadTransactionAsync(async (tx) => { IStatementResultCursor reader = await tx.RunAsync(query, props); while (await reader.FetchAsync()) { // Each current read in buffer can be reached via Current returnedresults.Append(ParseRecord(reader.Current)); } }); } catch (Exception e) { this._logger.LogError("Error running query from {0}: {1}", e.StackTrace, e.Message); this._logger.LogError("Query {0}", query); } finally { await session.CloseAsync(); } } return(returnedresults); }
public async Task <ResultSet> AdvancedSearch(AdvancedSearch.Search search) { string query = search.ToTokenizedSearchString(); ResultSet returnedresults = new ResultSet(); //validate the types/labels using (ISession session = this._driver.Session()) { try { await session.ReadTransactionAsync(async (tx) => { IStatementResultCursor reader = await tx.RunAsync(query, search.Tokens.Properties); while (await reader.FetchAsync()) { returnedresults.Append(ParseRecord(reader.Current)); } }); } catch (Exception e) { this._logger.LogError("Error running advanced search: " + e.Message); } finally { await session.CloseAsync(); } } return(returnedresults); }
public static IEnumerable <T> MapTo <T>(this IStatementResultCursor record) { while (record.FetchAsync().Result) { yield return(record.Current.MapTo <T>()); } }
/// <summary> /// Return the only record in the result stream. /// </summary> /// <param name="result">The result stream</param> /// <typeparam name="TResult">The type of the returning value.</typeparam> /// <returns>The single element of the input sequence, or default(<paramref name="TResult">TResult</paramref> if the sequence contains no elements.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="result">result</paramref> is null.</exception> /// <exception cref="T:System.ArgumentNullException"><paramref name="operation">operation</paramref> is null.</exception> /// <exception cref="T:System.InvalidOperationException">The input sequence contains more than one element.</exception> public static async Task <TResult> SingleOrDefaultAsync <TResult>(this IStatementResultCursor result, Func <IRecord, TResult> operation) { if (result == null) { throw new ArgumentNullException(nameof(result)); } if (operation == null) { throw new ArgumentNullException(nameof(operation)); } if (!await result.FetchAsync().ConfigureAwait(false)) { return(default(TResult)); } var record = result.Current; if (!await result.FetchAsync().ConfigureAwait(false)) { return(operation(record)); } throw new InvalidOperationException("The result contains more than one element."); }
public async Task <int> AddEmployeesAsync(string companyName) { var session = Driver.Session(); try { var persons = await session.ReadTransactionAsync(async tx => { IStatementResultCursor result = await tx.RunAsync("MATCH (a:Person) RETURN a.name AS name"); return(await result.ToListAsync()); }); return(persons.Sum(person => session.WriteTransactionAsync(async tx => { await tx.RunAsync("MATCH (emp:Person {name: $person_name}) " + "MERGE (com:Company {name: $company_name}) " + "MERGE (emp)-[:WORKS_FOR]->(com)", new { person_name = person["name"].As <string>(), company_name = companyName }); return 1; }).Result)); } finally { await session.CloseAsync(); } }
public async Task ProcessDelegatePerRecordFromQueryAsync(string query, object props, ProcessIRecord processor) { using (ISession session = this._driver.Session()) { try { await session.ReadTransactionAsync(async (tx) => { IStatementResultCursor reader = await tx.RunAsync(query, props); while (await reader.FetchAsync()) { // Each current read in buffer can be reached via Current processor(reader.Current); } }); } catch (Exception e) { this._logger.LogError("Error running query from {0}: {1}", e.StackTrace, e.Message); this._logger.LogError("Query {0}", query); } finally { await session.CloseAsync(); } } }
public InternalStatementResult(IStatementResultCursor cursor, BlockingExecutor executor) { _cursor = cursor ?? throw new ArgumentNullException(nameof(cursor)); _executor = executor ?? throw new ArgumentNullException(nameof(executor)); _cursor = cursor; _recordSet = new RecordSet(cursor, executor); _executor = executor; }
public static async Task <List <T> > MapToList <T>(this IStatementResultCursor record) { var result = new List <T>(); while (await record.FetchAsync()) { result.Add(record.Current.MapTo <T>()); } return(result); }
/// <summary> /// Read each record in the result stream and apply the operation on each record. /// </summary> /// <param name="result">The result stream.</param> /// <param name="operation">The operation is carried out on each record.</param> /// <returns>The result summary after all records have been processed.</returns> public static async Task <IResultSummary> ForEachAsync(this IStatementResultCursor result, Action <IRecord> operation) { Throw.ArgumentNullException.IfNull(result, nameof(result)); while (await result.FetchAsync().ConfigureAwait(false)) { var record = result.Current; operation(record); } return(await result.SummaryAsync().ConfigureAwait(false)); }
/// <summary> /// Pull all records in the result stream into memory and return in a list. /// </summary> /// <param name="result"> The result stream.</param> /// <returns>A list with all records in the result stream.</returns> public static async Task <List <IRecord> > ToListAsync(this IStatementResultCursor result) { Throw.ArgumentNullException.IfNull(result, nameof(result)); List <IRecord> list = new List <IRecord>(); while (await result.FetchAsync().ConfigureAwait(false)) { list.Add(result.Current); } return(list); }
/// <summary> /// Apply the operation on each record in the result stream and return the operation results in a list. /// </summary> /// <typeparam name="T">The return type of the list</typeparam> /// <param name="result">The result stream.</param> /// <param name="operation">The operation to carry out on each record.</param> /// <returns>A list of collected operation result.</returns> public static async Task <List <T> > ToListAsync <T>(this IStatementResultCursor result, Func <IRecord, T> operation) { Throw.ArgumentNullException.IfNull(result, nameof(result)); var list = new List <T>(); while (await result.FetchAsync().ConfigureAwait(false)) { var record = result.Current; list.Add(operation(record)); } return(list); }
public async Task <IEnumerable <string> > SearchEdgePropertyValuesAsync(string type, string property, string searchterm) { if (string.IsNullOrWhiteSpace(type)) { throw new ArgumentException("Type is required"); } if (string.IsNullOrWhiteSpace(property)) { throw new ArgumentException("Property is required"); } if (this._pluginmanager.EdgeDataTypes.Keys.Contains(type) == false) { throw new ArgumentException("Type not valid: " + type); } if (string.IsNullOrEmpty(type) || string.IsNullOrEmpty(property) || string.IsNullOrEmpty(searchterm)) { return(new List <string>()); } string regexterm = "(?i).*" + searchterm + ".*"; List <string> results = new List <string>(); using (ISession session = this._driver.Session()) { try { string query = "MATCH ()-[r:" + type + "]->() WHERE r[{prop}] =~ $regex RETURN DISTINCT r[{prop}] ORDER BY r[{prop}] LIMIT 20"; await session.ReadTransactionAsync(async (tx) => { IStatementResultCursor reader = await tx.RunAsync(query, new { prop = property, regex = regexterm }); while (await reader.FetchAsync()) { results.AddRange(ParseStringListRecord(reader.Current)); } }); } catch (Exception e) { this._logger.LogError("Error querying SearchNodePropertyValues: " + e.Message); } finally { await session.CloseAsync(); } } return(results); }
private async Task <Exercise> GetExercise(IStatementResultCursor reader) { Exercise item = null; while (await reader.FetchAsync()) { item = new Exercise() { Id = Guid.Parse(reader.Current[0].ToString()), Name = reader.Current[1].ToString(), Note = reader.Current[2]?.ToString() }; } return(item); }
private async Task <User> GetUser(IStatementResultCursor reader) { User item = null; while (await reader.FetchAsync()) { item = new User() { Id = Guid.Parse(reader.Current[0].ToString()), Email = reader.Current[1].ToString(), Blocked = (bool?)reader.Current[2] ?? false }; } return(item); }
private async Task <Category> GetCategory(IStatementResultCursor reader) { Category item = null; while (await reader.FetchAsync()) { item = new Category() { Id = Guid.Parse(reader.Current[0].ToString()), Name = reader.Current[1].ToString(), Note = reader.Current[2]?.ToString() }; } return(item); }
internal async Task <List <Person> > Find() { IDriver driver = GraphDatabase.Driver("bolt://127.0.0.1:7687", AuthTokens.None); List <Person> nodes = new List <Person>(); using (ISession session = driver.Session(AccessMode.Read)) { IStatementResultCursor result = await session.RunAsync("MATCH (n:Person) return n"); await result.ForEachAsync(r => { nodes.Add(r[r.Keys[0]].Map <Person>()); }); } return(nodes); }
private async Task <WorkoutSession> GetWorkoutSession(IStatementResultCursor reader) { WorkoutSession item = null; while (await reader.FetchAsync()) { item = new WorkoutSession() { Id = Guid.Parse(reader.Current[0].ToString()), Note = reader.Current[1]?.ToString(), StartEpochTimestamp = double.Parse(reader.Current[2].ToString()), EndEpochTimestamp = (reader.Current[3] != null) ? double.Parse(reader.Current[3].ToString()) : 0 }; } return(item); }
public async Task <IEnumerable <string> > SearchNodePropertyValuesAsync(string type, string property, string searchterm) { if (string.IsNullOrEmpty(property) || string.IsNullOrEmpty(searchterm)) { return(new List <string>()); } //replace the slashes so it picks up fs paths string regexterm = "(?i).*" + Regex.Escape(searchterm) + ".*"; string typequery = string.Empty; if (string.IsNullOrWhiteSpace(type) == false) { typequery = "$type IN labels(n) AND "; } List <string> results = new List <string>(); using (ISession session = this._driver.Session()) { try { string query = "MATCH (n) WHERE " + typequery + "n[{prop}] =~ $regex RETURN DISTINCT n[{prop}] ORDER BY n[{prop}] LIMIT 20"; await session.ReadTransactionAsync(async (tx) => { IStatementResultCursor reader = await tx.RunAsync(query, new { type, prop = property, regex = regexterm }); while (await reader.FetchAsync()) { results.AddRange(ParseStringListRecord(reader.Current)); } }); } catch (Exception e) { this._logger.LogError("Error querying SearchNodePropertyValues: " + e.Message); } finally { await session.CloseAsync(); } } return(results); }
protected async Task <int> CountPersonAsync(string name) { var session = Driver.Session(); try { return(await session.ReadTransactionAsync(async tx => { IStatementResultCursor result = await tx.RunAsync("MATCH (a:Person {name: $name}) RETURN count(a)", new { name }); return (await result.SingleAsync())[0].As <int>(); })); } finally { await session.CloseAsync(); } }
public async Task <string> Read() { string result = string.Empty; using (ISession session = GlobalDatabaseContext.Driver.Session()) { string query = "match (user:User {name:\"User\"}) return user.name as Name"; await session.ReadTransactionAsync(async x => { IStatementResultCursor cursor = await x.RunAsync(query); var tmp = await cursor.ToListAsync(c => { return(c.To <string>("Name")); }); result = tmp.FirstOrDefault(); query = string.Empty; }); return(result); } }
private async Task DiscardUnconsumedAsync() { if (_result != null) { IStatementResultCursor cursor = null; try { cursor = await _result.ConfigureAwait(false); } catch (Exception) { // ignored if the cursor failed to create } if (cursor != null) { await cursor.SummaryAsync().ConfigureAwait(false); } } }
/// <summary> /// Return the only record in the result stream. /// </summary> /// <param name="result">The result stream</param> /// <returns>The only record in the result stream.</returns> /// <remarks>Throws <exception cref="InvalidOperationException"></exception> /// if the result contains more than one record or the result is empty.</remarks> public static async Task <IRecord> SingleAsync(this IStatementResultCursor result) { Throw.ArgumentNullException.IfNull(result, nameof(result)); if (await result.FetchAsync().ConfigureAwait(false)) { var record = result.Current; if (!await result.FetchAsync().ConfigureAwait(false)) { return(record); } else { throw new InvalidOperationException("The result contains more than one element."); } } else { throw new InvalidOperationException("The result is empty."); } }
private async Task DiscardUnconsumed() { foreach (var result in _results) { IStatementResultCursor cursor = null; try { cursor = await result.ConfigureAwait(false); } catch (Exception) { // ignore if cursor failed to create } if (cursor != null) { await cursor.SummaryAsync().ConfigureAwait(false); } } }
private async Task <ExerciseRecord> GetExerciseRecord(IStatementResultCursor reader) { ExerciseRecord item = null; while (await reader.FetchAsync()) { item = new ExerciseRecord() { Id = Guid.Parse(reader.Current[0].ToString()), EpochTimestamp = double.Parse(reader.Current[1].ToString()), Set = reader.Current[2].ToString(), Reps = (Int64)reader.Current[3], Value = double.Parse(reader.Current[4].ToString()), Unit = reader.Current[5]?.ToString(), DropSet = (bool)reader.Current[6], Note = reader.Current[7]?.ToString() }; } return(item); }
private static Task AssertGetExpectResults(IStatementResultCursor cursor, int numberExpected, List <object> exspectedRecordsValues = null) { int count = 0; var t = Task.Factory.StartNew(async() => { // ReSharper disable once LoopCanBeConvertedToQuery while (await cursor.FetchAsync()) { if (exspectedRecordsValues != null) { cursor.Current.Values.First().Value.Should().Be(exspectedRecordsValues[count]); } count++; } count.Should().Be(numberExpected); }); return(t); }
public async Task TestDriverLifecycleExample() { // Given var driver = new DriverLifecycleExample(Uri, User, Password).Driver; var session = driver.Session(); try { // When & Then IStatementResultCursor result = await session.RunAsync("RETURN 1"); bool read = await result.FetchAsync(); read.Should().BeTrue(); result.Current[0].As <int>().Should().Be(1); } finally { await session.CloseAsync(); } }