Support for reading sections from db
This commit is contained in:
parent
6bbb559356
commit
27b0edf896
28
src/main.rs
28
src/main.rs
@ -1,27 +1,39 @@
|
||||
use rusqlite::NO_PARAMS;
|
||||
use rusqlite::Connection as DbConnection;
|
||||
use color_eyre::eyre::Result;
|
||||
use rusqlite::Connection as DbConnection;
|
||||
use rusqlite::NO_PARAMS;
|
||||
|
||||
mod section_interface;
|
||||
mod model;
|
||||
mod db;
|
||||
mod migrations;
|
||||
mod model;
|
||||
mod section_interface;
|
||||
|
||||
fn setup_db() -> Result<()> {
|
||||
use model::Section;
|
||||
|
||||
fn setup_db() -> Result<DbConnection> {
|
||||
// let conn = DbConnection::open_in_memory()?;
|
||||
let mut conn = DbConnection::open("test.db")?;
|
||||
|
||||
let migs = db::create_migrations();
|
||||
migs.apply(&mut conn)?;
|
||||
|
||||
Ok(())
|
||||
Ok(conn)
|
||||
}
|
||||
|
||||
fn query_sections(conn: &DbConnection) -> Result<Vec<Section>> {
|
||||
let mut statement = conn.prepare_cached("SELECT id, name, interface_id FROM sections;")?;
|
||||
let rows = statement.query_map(NO_PARAMS, Section::from_sql)?;
|
||||
Ok(rows.collect::<Result<Vec<_>, _>>()?)
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
env_logger::init();
|
||||
color_eyre::install()?;
|
||||
println!("Hello, world!");
|
||||
setup_db().unwrap();
|
||||
let conn = setup_db()?;
|
||||
|
||||
let sections = query_sections(&conn);
|
||||
for sec in sections {
|
||||
println!("section: {:?}", sec);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
@ -1 +1,3 @@
|
||||
mod section;
|
||||
|
||||
pub use section::Section;
|
||||
|
@ -1,21 +1,23 @@
|
||||
use crate::section_interface::SectionId;
|
||||
use rusqlite::Row;
|
||||
use std::convert::TryFrom;
|
||||
use rusqlite::{Row as SqlRow, Error as SqlError, ToSql};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Section {
|
||||
pub id: u32,
|
||||
pub name: String,
|
||||
pub interface_id: SectionId,
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<&Row<'a>> for Section {
|
||||
type Error = rusqlite::Error;
|
||||
fn try_from(row: &Row<'a>) -> Result<Section, Self::Error> {
|
||||
impl Section {
|
||||
pub fn from_sql<'a>(row: &SqlRow<'a>) -> Result<Section, SqlError> {
|
||||
Ok(Section {
|
||||
id: row.get(0)?,
|
||||
name: row.get(1)?,
|
||||
interface_id: row.get(2)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_sql(&self) -> Vec<&dyn ToSql> {
|
||||
vec![&self.id, &self.name, &self.interface_id]
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user