Rustでデータベースを設計しよう4

カラム名の衝突や順番依存の設計リスクを解消する
L columnsにcolumのorderを値として持つようにする

#[derive(Debug)]
struct ColumnSchema {
    order: usize,
    column_type: ColumnType,
}

#[derive(Debug)]
struct Columns {
    schema: HashMap<String, ColumnSchema>,
    order: Vec<String>,
}

利用側

fn main() {
    let mut schema = HashMap::new();
    let mut order = vec![];

    let columns = vec![
        ("id", ColumnType::Integer),
        ("name", ColumnType::Text),
        ("age", ColumnType::Integer),
    ];

    for (i, (name, col_type)) in columns.into_iter().enumerate() {
        schema.insert(name.to_string(), ColumnSchema {
            order: i,
            column_type: col_type,
        });
        order.push(name.to_string());
    }
    let columns = Columns { schema, order };

    let mut table = Table {
        name: "users".to_string(),
        columns: columns,
        rows: vec![],
    };

    let result = table.insert_row(vec![
        Value::Integer(1),
        Value::Text("Alice".to_string()),
        Value::Integer(30),
    ]);

    let result = table.insert_row(vec![
        Value::Integer(2),
        Value::Text("Bob".to_string()),
        Value::Integer(25),
    ]);

    println!("{:?}", table);

    let _ = table.update_value_by_column_condition(
        "id",
        &Value::Integer(2),
        "name",
        Value::Text("Carol".to_string()),
    );

    // let matching_rows = table.find_rows_by_column_value("id", &Value::Integer(2));

    // for row in matching_rows {
    //     println!("Matched row: {:?}", row);
    // }

    // let matching_rows = table.find_rows_by_column_value("id", &Value::Integer(2));

    // for row in matching_rows {
    //     println!("Matched row: {:?}", row);
    // }

    let _ = table.delete_rows_by_column_value("id", &Value::Integer(2));
    println!("{:?}", table);
}

Table { name: “users”, columns: Columns { schema: {“age”: ColumnSchema { order: 2, column_type: Integer }, “name”: ColumnSchema { order: 1, column_type: Text }, “id”: ColumnSchema { order: 0, column_type: Integer }}, order: [“id”, “name”, “age”] }, rows: [[Integer(1), Text(“Alice”), Integer(30)], [Integer(2), Text(“Bob”), Integer(25)]] }
Table { name: “users”, columns: Columns { schema: {“age”: ColumnSchema { order: 2, column_type: Integer }, “name”: ColumnSchema { order: 1, column_type: Text }, “id”: ColumnSchema { order: 0, column_type: Integer }}, order: [“id”, “name”, “age”] }, rows: [[Integer(1), Text(“Alice”), Integer(30)]] }

なるほど、ある程度期待通りになっています。