Skip to content

Commit

Permalink
Infer schema properly when array columns are used
Browse files Browse the repository at this point in the history
Note: We don't ever actually use the added column, because we don't need
to. Its presence alone is enough to cause the tests to fail.

This implementation is a hack. It's awful. I need to write a more
extensible system for type lookups. But right now I don't care. This is
blocking 0.4, and I can fix it in 0.5.

Fixes #65
  • Loading branch information
sgrif committed Jan 7, 2016
1 parent db97044 commit 57f6ffd
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 3 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ for Rust libraries in [RFC #1105](https://github.com/rust-lang/rfcs/blob/master/
* `#[changeset_for]` can now be used with structs containing only a single field
other than `id`. Fixes [#66](https://github.com/sgrif/diesel/issues/66).

* `infer_schema!` properly works with array columns. Fixes
[#65](https://github.com/sgrif/diesel/issues/65).

## [0.3.0] 2015-12-04

### Changed
Expand Down
19 changes: 16 additions & 3 deletions diesel_codegen/src/schema_inference/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,11 +144,24 @@ fn table_oid(conn: &Connection, table_name: &str) -> QueryResult<u32> {

fn column_def_tokens(cx: &mut ExtCtxt, attr: &PgAttr) -> Vec<ast::TokenTree> {
let column_name = str_to_ident(&attr.column_name);
let type_name = str_to_ident(&capitalize(&attr.type_name));
let tpe = determine_column_type(cx, attr);
quote_tokens!(cx, $column_name -> $tpe,)
}

fn determine_column_type(cx: &mut ExtCtxt, attr: &PgAttr) -> P<ast::Ty> {
let tpe;
if attr.type_name.starts_with("_") {
let subtype = str_to_ident(&capitalize(&attr.type_name[1..]));
tpe = quote_ty!(cx, Array<$subtype>);
} else {
let type_name = str_to_ident(&capitalize(&attr.type_name));
tpe = quote_ty!(cx, $type_name);
}

if attr.nullable {
quote_tokens!(cx, $column_name -> Nullable<$type_name>,)
quote_ty!(cx, Nullable<$tpe>)
} else {
quote_tokens!(cx, $column_name -> $type_name,)
tpe
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TABLE posts DROP COLUMN tags;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TABLE posts ADD COLUMN tags varchar[] NOT NULL DEFAULT '{}';
2 changes: 2 additions & 0 deletions diesel_tests/tests/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ pub struct Post {
pub user_id: i32,
pub title: String,
pub body: Option<String>,
pub tags: Vec<String>,
}

impl Post {
Expand All @@ -46,6 +47,7 @@ impl Post {
user_id: user_id,
title: title.to_string(),
body: body.map(|s| s.to_string()),
tags: Vec::new(),
}
}
}
Expand Down

0 comments on commit 57f6ffd

Please sign in to comment.