Skip to content

Commit dac12cd

Browse files
committed
use application version instead of db
1 parent 108a212 commit dac12cd

File tree

3 files changed

+68
-51
lines changed

3 files changed

+68
-51
lines changed

mithril-aggregator/src/command_args.rs

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use clap::{Parser, Subcommand};
22
use config::{builder::DefaultState, ConfigBuilder, Map, Source, Value, ValueKind};
33
use semver::{Version, VersionReq};
44
use slog::Level;
5-
use slog_scope::debug;
5+
use slog_scope::{debug, warn};
66
use sqlite::Connection;
77
use std::error::Error;
88
use std::fs;
@@ -15,7 +15,7 @@ use mithril_common::certificate_chain::MithrilCertificateVerifier;
1515
use mithril_common::chain_observer::{CardanoCliRunner, ChainObserver};
1616
use mithril_common::crypto_helper::ProtocolGenesisVerifier;
1717
use mithril_common::database::{
18-
ApplicationNodeType, DatabaseVersion, VersionProvider, VersionUpdatedProvider,
18+
ApplicationNodeType, ApplicationVersion, VersionProvider, VersionUpdaterProvider,
1919
};
2020
use mithril_common::digesters::{CardanoImmutableDigester, ImmutableFileSystemObserver};
2121
use mithril_common::entities::{Epoch, HexEncodedGenesisSecretKey};
@@ -35,26 +35,26 @@ use crate::{
3535
use crate::{
3636
CertificateStore, DefaultConfiguration, GzipSnapshotter, MultiSignerImpl,
3737
ProtocolParametersStorer, SingleSignatureStore, VerificationKeyStore,
38-
DATABASE_SCHEMATIC_VERSION,
3938
};
4039

4140
fn check_database_version(connection: &Connection) -> Result<bool, Box<dyn Error>> {
4241
let provider = VersionProvider::new(connection);
4342
provider.create_table_if_not_exists()?;
44-
let maybe_option = provider.get_database_version()?;
43+
let application_type = ApplicationNodeType::new("aggregator")?;
44+
let maybe_option = provider.get_database_version(&application_type)?;
4545

4646
let version = match maybe_option {
4747
None => {
48-
let provider = VersionUpdatedProvider::new(connection);
49-
let version = DatabaseVersion {
50-
database_version: Version::parse(DATABASE_SCHEMATIC_VERSION)?,
51-
application_type: ApplicationNodeType::new("aggregator")?,
48+
let provider = VersionUpdaterProvider::new(connection);
49+
let version = ApplicationVersion {
50+
database_version: Version::parse(env!("CARGO_PKG_VERSION"))?,
51+
application_type,
5252
};
5353
provider.save(version)?
5454
}
5555
Some(version) => version,
5656
};
57-
let req = VersionReq::parse("~0.1").unwrap();
57+
let req = VersionReq::parse(env!("CARGO_PKG_VERSION")).unwrap();
5858

5959
Ok(req.matches(&version.database_version))
6060
}
@@ -69,7 +69,12 @@ fn setup_genesis_dependencies(
6969
None => Connection::open(":memory:")?,
7070
};
7171
if !check_database_version(&connection)? {
72-
return Err("The database is out of date, cannot start.".into());
72+
warn!("❌ The database is out of date, application may fail.");
73+
} else {
74+
debug!(
75+
"Database schematic for application version {} has been checked OK!",
76+
env!("CARGO_PKG_VERSION")
77+
);
7378
}
7479

7580
let chain_observer = Arc::new(
@@ -342,7 +347,12 @@ impl ServeCommand {
342347
};
343348

344349
if !check_database_version(&connection)? {
345-
return Err("The database is out of date, cannot start.".into());
350+
warn!("❌ The database is out of date, application may fail.");
351+
} else {
352+
debug!(
353+
"Database schematic for application version {} has been checked OK!",
354+
env!("CARGO_PKG_VERSION")
355+
);
346356
}
347357

348358
let certificate_pending_store = Arc::new(CertificatePendingStore::new(Box::new(

mithril-aggregator/src/lib.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,6 @@ mod snapshotter;
2323
mod store;
2424
mod tools;
2525

26-
const DATABASE_SCHEMATIC_VERSION: &str = "0.1.0";
27-
2826
pub use crate::configuration::{
2927
Configuration, DefaultConfiguration, GenesisConfiguration, SnapshotStoreType,
3028
SnapshotUploaderType,

mithril-common/src/database/db_version.rs

Lines changed: 47 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -35,17 +35,17 @@ impl Display for ApplicationNodeType {
3535
}
3636
}
3737

38-
/// Entity related to the `db_version` database table.
38+
/// Entity related to the `app_version` database table.
3939
#[derive(Debug, PartialEq, Eq)]
40-
pub struct DatabaseVersion {
40+
pub struct ApplicationVersion {
4141
/// Semver of the database structure.
4242
pub database_version: Version,
4343

4444
/// Name of the application.
4545
pub application_type: ApplicationNodeType,
4646
}
4747

48-
impl SqLiteEntity for DatabaseVersion {
48+
impl SqLiteEntity for ApplicationVersion {
4949
fn hydrate(row: Row) -> Result<Self, HydrationError> {
5050
Ok(Self {
5151
database_version: Version::parse(&row.get::<String, _>(0))
@@ -56,12 +56,12 @@ impl SqLiteEntity for DatabaseVersion {
5656
}
5757
}
5858

59-
/// Projection dedicated to [DatabaseVersion] entities.
60-
struct DbVersionProjection {
59+
/// Projection dedicated to [ApplicationVersion] entities.
60+
struct ApplicationVersionProjection {
6161
fields: Vec<ProjectionField>,
6262
}
6363

64-
impl Projection for DbVersionProjection {
64+
impl Projection for ApplicationVersionProjection {
6565
fn set_field(&mut self, field: ProjectionField) {
6666
self.fields.push(field);
6767
}
@@ -70,36 +70,40 @@ impl Projection for DbVersionProjection {
7070
&self.fields
7171
}
7272
}
73-
impl DbVersionProjection {
73+
impl ApplicationVersionProjection {
7474
pub fn new() -> Self {
7575
let mut projection = Self { fields: Vec::new() };
76-
projection.add_field("db_version", "{:version:}.version", "text");
77-
projection.add_field("application_type", "{:version:}.application_type", "text");
76+
projection.add_field("version", "{:app_version:}.version", "text");
77+
projection.add_field(
78+
"application_type",
79+
"{:app_version:}.application_type",
80+
"text",
81+
);
7882

7983
projection
8084
}
8185
}
8286

83-
/// Provider for the [DatabaseVersion] entities using the [DbVersionProjection].
87+
/// Provider for the [ApplicationVersion] entities using the `ApplicationVersionProjection`.
8488
pub struct VersionProvider<'conn> {
8589
connection: &'conn Connection,
86-
projection: DbVersionProjection,
90+
projection: ApplicationVersionProjection,
8791
}
8892

8993
impl<'conn> VersionProvider<'conn> {
9094
/// [VersionProvider] constructor.
9195
pub fn new(connection: &'conn Connection) -> Self {
9296
Self {
9397
connection,
94-
projection: DbVersionProjection::new(),
98+
projection: ApplicationVersionProjection::new(),
9599
}
96100
}
97101

98102
/// Method to create the table at the beginning of the migration procedure.
99103
/// This code is temporary and should not last.
100104
pub fn create_table_if_not_exists(&self) -> Result<(), Box<dyn Error>> {
101105
let connection = self.get_connection();
102-
let sql = "select exists(select name from sqlite_master where type='table' and name='db_version') as table_exists";
106+
let sql = "select exists(select name from sqlite_master where type='table' and name='app_version') as table_exists";
103107
let table_exists = connection
104108
.prepare(sql)?
105109
.into_cursor()
@@ -111,7 +115,7 @@ impl<'conn> VersionProvider<'conn> {
111115

112116
if !table_exists {
113117
let sql = r#"
114-
create table db_version (application_type text not null primary key, version text not null)
118+
create table app_version (application_type text not null primary key, version text not null)
115119
"#;
116120
connection.execute(sql)?;
117121
}
@@ -120,15 +124,20 @@ create table db_version (application_type text not null primary key, version tex
120124
}
121125

122126
/// Read the database version from the database.
123-
pub fn get_database_version(&self) -> Result<Option<DatabaseVersion>, Box<dyn Error>> {
124-
let result = self.find(None, &[])?.next();
127+
pub fn get_database_version(
128+
&self,
129+
application_type: &ApplicationNodeType,
130+
) -> Result<Option<ApplicationVersion>, Box<dyn Error>> {
131+
let condition = "application_type = ?";
132+
let params = [Value::String(format!("{}", application_type))];
133+
let result = self.find(Some(condition), &params)?.next();
125134

126135
Ok(result)
127136
}
128137
}
129138

130139
impl<'conn> Provider<'conn> for VersionProvider<'conn> {
131-
type Entity = DatabaseVersion;
140+
type Entity = ApplicationVersion;
132141

133142
fn get_projection(&self) -> &dyn Projection {
134143
&self.projection
@@ -141,37 +150,37 @@ impl<'conn> Provider<'conn> for VersionProvider<'conn> {
141150
fn get_definition(&self, condition: Option<&str>) -> String {
142151
let where_clause = condition.unwrap_or("true");
143152
let mut aliases = HashMap::new();
144-
let _ = aliases.insert("{:version:}".to_string(), "db_version".to_string());
153+
let _ = aliases.insert("{:app_version:}".to_string(), "app_version".to_string());
145154
let projection = self.get_projection().expand(aliases);
146155

147156
format!(
148157
r#"
149158
select {projection}
150-
from db_version
159+
from app_version
151160
where {where_clause}
152161
"#
153162
)
154163
}
155164
}
156165

157-
/// Write [Provider] for the [DatabaseVersion] entities.
166+
/// Write [Provider] for the [ApplicationVersion] entities.
158167
/// This will perform an UPSERT and return the updated entity.
159-
pub struct VersionUpdatedProvider<'conn> {
168+
pub struct VersionUpdaterProvider<'conn> {
160169
connection: &'conn Connection,
161-
projection: DbVersionProjection,
170+
projection: ApplicationVersionProjection,
162171
}
163172

164-
impl<'conn> VersionUpdatedProvider<'conn> {
165-
/// [VersionUpdateprovider] constructor.
173+
impl<'conn> VersionUpdaterProvider<'conn> {
174+
/// [VersionUpdaterProvider] constructor.
166175
pub fn new(connection: &'conn Connection) -> Self {
167176
Self {
168177
connection,
169-
projection: DbVersionProjection::new(),
178+
projection: ApplicationVersionProjection::new(),
170179
}
171180
}
172181

173182
/// Persist the given entity and return the projection of the saved entity.
174-
pub fn save(&self, version: DatabaseVersion) -> Result<DatabaseVersion, Box<dyn Error>> {
183+
pub fn save(&self, version: ApplicationVersion) -> Result<ApplicationVersion, Box<dyn Error>> {
175184
let params = [
176185
Value::String(format!("{}", version.application_type)),
177186
Value::String(version.database_version.to_string()),
@@ -185,8 +194,8 @@ impl<'conn> VersionUpdatedProvider<'conn> {
185194
}
186195
}
187196

188-
impl<'conn> Provider<'conn> for VersionUpdatedProvider<'conn> {
189-
type Entity = DatabaseVersion;
197+
impl<'conn> Provider<'conn> for VersionUpdaterProvider<'conn> {
198+
type Entity = ApplicationVersion;
190199

191200
fn get_projection(&self) -> &dyn Projection {
192201
&self.projection
@@ -199,12 +208,12 @@ impl<'conn> Provider<'conn> for VersionUpdatedProvider<'conn> {
199208
fn get_definition(&self, condition: Option<&str>) -> String {
200209
let _where_clause = condition.unwrap_or("true");
201210
let mut aliases = HashMap::new();
202-
let _ = aliases.insert("{:version:}".to_string(), "db_version".to_string());
211+
let _ = aliases.insert("{:app_version:}".to_string(), "app_version".to_string());
203212
let projection = self.get_projection().expand(aliases);
204213

205214
format!(
206215
r#"
207-
insert into db_version (application_type, version) values (?, ?)
216+
insert into app_version (application_type, version) values (?, ?)
208217
on conflict (application_type) do update set version = excluded.version
209218
returning {projection}
210219
"#
@@ -218,12 +227,12 @@ mod tests {
218227

219228
#[test]
220229
fn test_projection() {
221-
let projection = DbVersionProjection::new();
230+
let projection = ApplicationVersionProjection::new();
222231
let mut aliases: HashMap<String, String> = HashMap::new();
223-
let _ = aliases.insert("{:version:}".to_string(), "whatever".to_string());
232+
let _ = aliases.insert("{:app_version:}".to_string(), "whatever".to_string());
224233

225234
assert_eq!(
226-
"whatever.version as db_version, whatever.application_type as application_type"
235+
"whatever.version as version, whatever.application_type as application_type"
227236
.to_string(),
228237
projection.expand(aliases)
229238
);
@@ -236,8 +245,8 @@ mod tests {
236245

237246
assert_eq!(
238247
r#"
239-
select db_version.version as db_version, db_version.application_type as application_type
240-
from db_version
248+
select app_version.version as version, app_version.application_type as application_type
249+
from app_version
241250
where true
242251
"#,
243252
provider.get_definition(None)
@@ -247,13 +256,13 @@ where true
247256
#[test]
248257
fn test_updated_entity() {
249258
let connection = Connection::open(":memory:").unwrap();
250-
let provider = VersionUpdatedProvider::new(&connection);
259+
let provider = VersionUpdaterProvider::new(&connection);
251260

252261
assert_eq!(
253262
r#"
254-
insert into db_version (application_type, version) values (?, ?)
263+
insert into app_version (application_type, version) values (?, ?)
255264
on conflict (application_type) do update set version = excluded.version
256-
returning db_version.version as db_version, db_version.application_type as application_type
265+
returning app_version.version as version, app_version.application_type as application_type
257266
"#,
258267
provider.get_definition(None)
259268
)

0 commit comments

Comments
 (0)