Skip to content

Commit

Permalink
Fixing get_latest_migration_version to handle error when initial tabl…
Browse files Browse the repository at this point in the history
…e doesnt exist
  • Loading branch information
mjovanc committed Mar 24, 2024
1 parent 62d6e8e commit 18a1b95
Show file tree
Hide file tree
Showing 12 changed files with 25 additions and 52 deletions.
29 changes: 17 additions & 12 deletions njord_cli/src/migration.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{fs, path::Path};

use njord::sqlite;
use rusqlite::Connection;
use rusqlite::{Connection, Error, ErrorCode};

use crate::util::{
create_migration_files, get_migrations_directory_path, get_next_migration_version, read_config,
Expand Down Expand Up @@ -63,13 +63,8 @@ pub fn generate(name: Option<&String>, env: Option<&String>, dry_run: Option<&St
/// run(Some("production"), Some("debug"));
/// ```
pub fn run(env: Option<&String>, log_level: Option<&String>) {
//TODO: this doesnt load since it looks in the wrong directory
// need to update the open() function to look for either ../target or ./target dir
// it should not be hardcoded here as well, we need a more elegant solution
let conn = sqlite::open("sqlite.db");

println!("{}", conn.is_ok());

match conn {
Ok(conn) => {
println!("Database connection established successfully.");
Expand Down Expand Up @@ -165,14 +160,24 @@ pub fn rollback(env: Option<&String>, to: Option<&String>, log_level: Option<&St
/// # Note
///
/// This function queries the "migration_history" table to obtain the latest version.
fn get_latest_migration_version(conn: &Connection) -> Result<String, rusqlite::Error> {
fn get_latest_migration_version(conn: &Connection) -> Result<String, Error> {
let query = "SELECT version FROM migration_history ORDER BY version DESC LIMIT 1;";
let result: Result<String, rusqlite::Error> = conn.query_row(query, [], |row| row.get(0));
let result: Result<String, Error> = conn.query_row(query, [], |row| row.get(0));

result.map_err(|err| {
eprintln!("Error getting latest migration version: {}", err);
err
})
match result {
Ok(version) => Ok(version),
Err(err) => {
match err {
Error::SqliteFailure(error, _) if error.code == ErrorCode::Unknown => {
Ok("00000000000000_njord_initial_setup".to_string())
}
_ => {
eprintln!("Error getting latest migration version: {}", err);
Err(err)
}
}
}
}
}

/// Executes SQL content from a file on the provided database connection.
Expand Down
4 changes: 2 additions & 2 deletions njord_examples/sqlite/generate.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@
# Author: Marcus Cvjeticanin
# Date: December 15, 2023
# -----------------------------------------------------------------------------
cargo run --manifest-path=../../njord_cli/Cargo.toml -- migration generate -- --name=update_users -- --env=development --dry-run
cargo run --manifest-path=../../njord_cli/Cargo.toml -- migration generate -- --name=update_users -- --env=development
# cargo run --manifest-path=../../njord_cli/Cargo.toml -- migration generate -- --name=init_tables -- --env=development --dry-run // TODO: --dry-run doesnt work!
cargo run --manifest-path=../../njord_cli/Cargo.toml -- migration generate -- --name=init_tables -- --env=development
Original file line number Diff line number Diff line change
@@ -1,6 +1 @@
-- Drop tables in reverse order to handle foreign key constraints

DROP TABLE IF EXISTS order_products;
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS products;
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS migration_history;
Original file line number Diff line number Diff line change
@@ -1,32 +1,5 @@
-- users table
CREATE TABLE users (
user_id INTEGER PRIMARY KEY,
username TEXT NOT NULL,
email TEXT NOT NULL,
address TEXT NOT NULL
);

-- products table
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
description TEXT NOT NULL,
price REAL NOT NULL,
stock_quantity INTEGER NOT NULL,
category TEXT NOT NULL
);

-- orders table
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
user_id INTEGER REFERENCES users(user_id),
total_cost REAL NOT NULL,
order_date TEXT NOT NULL
);

-- order_products table
CREATE TABLE order_products (
order_id INTEGER REFERENCES orders(order_id),
product_id INTEGER REFERENCES products(product_id),
PRIMARY KEY (order_id, product_id)
);
CREATE TABLE IF NOT EXISTS migration_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
version TEXT NOT NULL,
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.

0 comments on commit 18a1b95

Please sign in to comment.