Skip to content

Commit 079414d

Browse files
Merge pull request #30 from theseus-rs/refactor-status-check
refactor!: refactor status to check on demand instead of attempting to track the state dynamically
2 parents 7e8cdc7 + dad2dea commit 079414d

File tree

5 files changed

+33
-65
lines changed

5 files changed

+33
-65
lines changed

Cargo.lock

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

deny.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
targets = [
55
{ triple = "aarch64-unknown-linux-gnu" },
6+
{ triple = "aarch64-unknown-linux-musl" },
67
{ triple = "aarch64-apple-darwin" },
78
{ triple = "x86_64-apple-darwin" },
89
{ triple = "x86_64-pc-windows-msvc" },
@@ -35,4 +36,4 @@ name = "ring"
3536
expression = "MIT AND ISC AND OpenSSL"
3637
license-files = [
3738
{ path = "LICENSE", hash = 0xbd0eed23 }
38-
]
39+
]

examples/sqlx_embedded/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,5 @@ version.workspace = true
88
[dependencies]
99
anyhow = { workspace = true }
1010
postgresql_embedded = { path = "../../postgresql_embedded" }
11-
sqlx = { version = "0.7", no-default-features = true, features = ["postgres", "runtime-tokio-rustls"] }
11+
sqlx = { version = "0.7", default-features = true, features = ["postgres", "runtime-tokio-rustls"] }
1212
tokio = { workspace = true }

postgresql_embedded/src/blocking/mod.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,28 +55,28 @@ impl PostgreSQL {
5555
}
5656

5757
/// Stop the database gracefully (smart mode) and wait for the shutdown to complete.
58-
pub fn stop(&mut self) -> Result<()> {
58+
pub fn stop(&self) -> Result<()> {
5959
RUNTIME
6060
.handle()
6161
.block_on(async move { self.inner.stop().await })
6262
}
6363

6464
/// Create a new database with the given name.
65-
pub fn create_database<S: AsRef<str>>(&mut self, database_name: S) -> Result<()> {
65+
pub fn create_database<S: AsRef<str>>(&self, database_name: S) -> Result<()> {
6666
RUNTIME
6767
.handle()
6868
.block_on(async move { self.inner.create_database(database_name).await })
6969
}
7070

7171
/// Check if a database with the given name exists.
72-
pub fn database_exists<S: AsRef<str>>(&mut self, database_name: S) -> Result<bool> {
72+
pub fn database_exists<S: AsRef<str>>(&self, database_name: S) -> Result<bool> {
7373
RUNTIME
7474
.handle()
7575
.block_on(async move { self.inner.database_exists(database_name).await })
7676
}
7777

7878
/// Drop a database with the given name.
79-
pub fn drop_database<S: AsRef<str>>(&mut self, database_name: S) -> Result<()> {
79+
pub fn drop_database<S: AsRef<str>>(&self, database_name: S) -> Result<()> {
8080
RUNTIME
8181
.handle()
8282
.block_on(async move { self.inner.drop_database(database_name).await })

postgresql_embedded/src/postgresql.rs

Lines changed: 24 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -39,26 +39,17 @@ pub(crate) const ARCHIVE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/post
3939
pub enum Status {
4040
/// Archive not installed
4141
NotInstalled,
42-
/// Installing software from archive
43-
Installing,
4442
/// Installation complete; not initialized
4543
Installed,
46-
/// Initialization running
47-
Initializing,
48-
/// Server starting
49-
Starting,
5044
/// Server started
5145
Started,
52-
/// Server stopping
53-
Stopping,
5446
/// Server initialized and stopped
5547
Stopped,
5648
}
5749

5850
/// PostgreSQL server
5951
#[derive(Clone, Debug)]
6052
pub struct PostgreSQL {
61-
status: Status,
6253
version: Version,
6354
settings: Settings,
6455
}
@@ -67,11 +58,7 @@ pub struct PostgreSQL {
6758
impl PostgreSQL {
6859
/// Create a new [`PostgreSQL`] instance
6960
pub fn new(version: Version, settings: Settings) -> Self {
70-
let mut postgresql = PostgreSQL {
71-
status: Status::NotInstalled,
72-
version,
73-
settings,
74-
};
61+
let mut postgresql = PostgreSQL { version, settings };
7562

7663
// If the minor and release version are set, append the version to the installation directory
7764
// to avoid conflicts with other versions. This will also facilitate setting the status
@@ -85,8 +72,6 @@ impl PostgreSQL {
8572
postgresql.settings.installation_dir =
8673
postgresql.settings.installation_dir.join(version_string);
8774
}
88-
89-
postgresql.update_status();
9075
}
9176

9277
postgresql
@@ -101,23 +86,17 @@ impl PostgreSQL {
10186
}
10287
}
10388

104-
/// Determine the status of the PostgreSQL server based on the settings
105-
fn update_status(&mut self) {
106-
let is_installed = self.is_installed();
107-
let is_initialized = self.is_initialized();
108-
109-
if is_installed && is_initialized {
110-
self.status = Status::Stopped
111-
} else if is_installed {
112-
self.status = Status::Installed
113-
} else {
114-
self.status = Status::NotInstalled
115-
}
116-
}
117-
11889
/// Get the [status](Status) of the PostgreSQL server
11990
pub fn status(&self) -> Status {
120-
self.status
91+
if self.is_running() {
92+
Status::Started
93+
} else if self.is_initialized() {
94+
Status::Stopped
95+
} else if self.is_installed() {
96+
Status::Installed
97+
} else {
98+
Status::NotInstalled
99+
}
121100
}
122101

123102
/// Get the [version](Version) of the PostgreSQL server
@@ -145,6 +124,12 @@ impl PostgreSQL {
145124
self.settings.data_dir.join("postgresql.conf").exists()
146125
}
147126

127+
/// Check if the PostgreSQL server is running
128+
fn is_running(&self) -> bool {
129+
let pid_file = self.settings.data_dir.join("postmaster.pid");
130+
pid_file.exists()
131+
}
132+
148133
/// Set up the database by extracting the archive and initializing the database.
149134
/// If the installation directory already exists, the archive will not be extracted.
150135
/// If the data directory already exists, the database will not be initialized.
@@ -182,7 +167,6 @@ impl PostgreSQL {
182167

183168
if self.settings.installation_dir.exists() {
184169
debug!("Installation directory already exists");
185-
self.update_status();
186170
return Ok(());
187171
}
188172

@@ -201,10 +185,8 @@ impl PostgreSQL {
201185
let (version, bytes) = { get_archive(&self.version).await? };
202186

203187
self.version = version;
204-
self.status = Status::Installing;
205188
create_dir_all(&self.settings.installation_dir)?;
206189
extract(&bytes, &self.settings.installation_dir).await?;
207-
self.status = Status::Installed;
208190

209191
debug!(
210192
"Installed PostgreSQL version {} to {}",
@@ -236,20 +218,15 @@ impl PostgreSQL {
236218
.username(&self.settings.username)
237219
.encoding("UTF8");
238220

239-
self.status = Status::Initializing;
240221
match self.execute_command(initdb).await {
241222
Ok((_stdout, _stderr)) => {
242-
self.status = Status::Stopped;
243223
debug!(
244224
"Initialized database {}",
245225
self.settings.data_dir.to_string_lossy()
246226
);
247227
Ok(())
248228
}
249-
Err(error) => {
250-
self.update_status();
251-
Err(DatabaseInitializationError(error.into()))
252-
}
229+
Err(error) => Err(DatabaseInitializationError(error.into())),
253230
}
254231
}
255232

@@ -276,26 +253,21 @@ impl PostgreSQL {
276253
.options(options)
277254
.wait();
278255

279-
self.status = Status::Starting;
280256
match self.execute_command(pg_ctl).await {
281257
Ok((_stdout, _stderr)) => {
282-
self.status = Status::Started;
283258
debug!(
284259
"Started database {} on port {}",
285260
self.settings.data_dir.to_string_lossy(),
286261
self.settings.port
287262
);
288263
Ok(())
289264
}
290-
Err(error) => {
291-
self.update_status();
292-
Err(DatabaseStartError(error.into()))
293-
}
265+
Err(error) => Err(DatabaseStartError(error.into())),
294266
}
295267
}
296268

297269
/// Stop the database gracefully (smart mode) and wait for the shutdown to complete.
298-
pub async fn stop(&mut self) -> Result<()> {
270+
pub async fn stop(&self) -> Result<()> {
299271
debug!(
300272
"Stopping database {}",
301273
self.settings.data_dir.to_string_lossy()
@@ -307,25 +279,20 @@ impl PostgreSQL {
307279
.shutdown_mode(Fast)
308280
.wait();
309281

310-
self.status = Status::Stopping;
311282
match self.execute_command(pg_ctl).await {
312283
Ok((_stdout, _stderr)) => {
313-
self.status = Status::Stopped;
314284
debug!(
315285
"Stopped database {}",
316286
self.settings.data_dir.to_string_lossy()
317287
);
318288
Ok(())
319289
}
320-
Err(error) => {
321-
self.update_status();
322-
Err(DatabaseStopError(error.into()))
323-
}
290+
Err(error) => Err(DatabaseStopError(error.into())),
324291
}
325292
}
326293

327294
/// Create a new database with the given name.
328-
pub async fn create_database<S: AsRef<str>>(&mut self, database_name: S) -> Result<()> {
295+
pub async fn create_database<S: AsRef<str>>(&self, database_name: S) -> Result<()> {
329296
debug!(
330297
"Creating database {} for {}:{}",
331298
database_name.as_ref(),
@@ -358,7 +325,7 @@ impl PostgreSQL {
358325
}
359326

360327
/// Check if a database with the given name exists.
361-
pub async fn database_exists<S: AsRef<str>>(&mut self, database_name: S) -> Result<bool> {
328+
pub async fn database_exists<S: AsRef<str>>(&self, database_name: S) -> Result<bool> {
362329
debug!(
363330
"Checking if database {} exists for {}:{}",
364331
database_name.as_ref(),
@@ -389,7 +356,7 @@ impl PostgreSQL {
389356
}
390357

391358
/// Drop a database with the given name.
392-
pub async fn drop_database<S: AsRef<str>>(&mut self, database_name: S) -> Result<()> {
359+
pub async fn drop_database<S: AsRef<str>>(&self, database_name: S) -> Result<()> {
393360
debug!(
394361
"Dropping database {} for {}:{}",
395362
database_name.as_ref(),
@@ -457,7 +424,7 @@ impl Default for PostgreSQL {
457424
/// Stop the PostgreSQL server and remove the data directory if it is marked as temporary.
458425
impl Drop for PostgreSQL {
459426
fn drop(&mut self) {
460-
if self.status == Status::Starting || self.status == Status::Started {
427+
if self.status() == Status::Started {
461428
let mut pg_ctl = PgCtlBuilder::new()
462429
.program_dir(self.settings.binary_dir())
463430
.mode(Stop)

0 commit comments

Comments
 (0)