Skip to content

Commit 794a3e0

Browse files
committed
Work around Issue #2206
Possibly not the best fix, but for some reason MySqlRow.column_names is not being populated. If a string index is requested and column_names is empty, fall back to iterating over columns to try to find the column index.
1 parent e8384f2 commit 794a3e0

File tree

2 files changed

+45
-4
lines changed

2 files changed

+45
-4
lines changed

sqlx-mysql/src/row.rs

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,21 @@ impl Row for MySqlRow {
4242

4343
impl ColumnIndex<MySqlRow> for &'_ str {
4444
fn index(&self, row: &MySqlRow) -> Result<usize, Error> {
45-
row.column_names
46-
.get(*self)
47-
.ok_or_else(|| Error::ColumnNotFound((*self).into()))
48-
.copied()
45+
// Work around Issue #2206, <https://github.com/launchbadge/sqlx/issues/2206>
46+
//
47+
// column_names is empty so will always fail, but user expects this to work.
48+
// Check the individual columns.
49+
if row.column_names.is_empty() {
50+
row.columns
51+
.iter()
52+
.find_map(|c| (*c.name == **self).then_some(c.ordinal))
53+
.ok_or_else(|| Error::ColumnNotFound((*self).into()))
54+
} else {
55+
row.column_names
56+
.get(*self)
57+
.ok_or_else(|| Error::ColumnNotFound((*self).into()))
58+
.copied()
59+
}
4960
}
5061
}
5162

tests/mysql/mysql.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -636,3 +636,33 @@ async fn issue_3200() -> anyhow::Result<()> {
636636

637637
Ok(())
638638
}
639+
640+
#[sqlx_macros::test]
641+
async fn it_can_name_columns_issue_2206() -> anyhow::Result<()> {
642+
let mut conn = new::<MySql>().await?;
643+
644+
sqlx::raw_sql(
645+
"\
646+
CREATE TABLE IF NOT EXISTS issue_2206
647+
(
648+
`id` BIGINT AUTO_INCREMENT,
649+
`name` VARCHAR(128) NOT NULL,
650+
PRIMARY KEY (id)
651+
);
652+
",
653+
)
654+
.execute(&mut conn)
655+
.await?;
656+
657+
let row = sqlx::query("INSERT INTO issue_2206 (name) VALUES (?) RETURNING *")
658+
.bind("Alice")
659+
.fetch_one(&mut conn)
660+
.await?;
661+
662+
let _id: i64 = row.get("id");
663+
let name: String = row.get("name");
664+
665+
assert_eq!(&name, "Alice");
666+
667+
Ok(())
668+
}

0 commit comments

Comments
 (0)