Skip to content

Commit

Permalink
Use the pg_isready command to asses wether a PostgreSQL is ready or not
Browse files Browse the repository at this point in the history
  • Loading branch information
0xced committed Jan 22, 2024
1 parent c69afa3 commit 48f1934
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 10 deletions.
12 changes: 2 additions & 10 deletions src/Testcontainers.PostgreSql/PostgreSqlBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,18 +123,10 @@ protected override PostgreSqlBuilder Merge(PostgreSqlConfiguration oldValue, Pos
/// <inheritdoc cref="IWaitUntil" />
private sealed class WaitUntil : IWaitUntil
{
private static readonly string[] LineEndings = { "\r\n", "\n" };

/// <inheritdoc />
public async Task<bool> UntilAsync(IContainer container)
public Task<bool> UntilAsync(IContainer container)
{
var (stdout, stderr) = await container.GetLogsAsync(timestampsEnabled: false)
.ConfigureAwait(false);

return 2.Equals(Array.Empty<string>()
.Concat(stdout.Split(LineEndings, StringSplitOptions.RemoveEmptyEntries))
.Concat(stderr.Split(LineEndings, StringSplitOptions.RemoveEmptyEntries))
.Count(line => line.Contains("database system is ready to accept connections")));
return ((PostgreSqlContainer)container).IsReadyAsync();
}
}
}
15 changes: 15 additions & 0 deletions src/Testcontainers.PostgreSql/PostgreSqlContainer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,19 @@ await CopyAsync(Encoding.Default.GetBytes(scriptContent), scriptFilePath, Unix.F
return await ExecAsync(new[] { "psql", "--username", _configuration.Username, "--dbname", _configuration.Database, "--file", scriptFilePath }, ct)
.ConfigureAwait(false);
}

/// <summary>
/// Test whether the database is ready to accept connections or not with the <c>pg_isready</c> command.
/// </summary>
/// <returns><see langword="true"/> if the database is ready to accept connections; <see langword="false"/> if the database is not yet ready.</returns>
internal async Task<bool> IsReadyAsync()
{
var command = new[] {
"pg_isready",
"--dbname", _configuration.Database,
"--username", _configuration.Username,
};
var result = await ExecAsync(command);
return result.ExitCode == 0;
}
}

0 comments on commit 48f1934

Please sign in to comment.