Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix test suite #1341

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions sqlx-core/src/postgres/connection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use crate::postgres::message::{
};
use crate::postgres::statement::PgStatementMetadata;
use crate::postgres::{PgConnectOptions, PgTypeInfo, Postgres};
use crate::row::Row;
use crate::transaction::Transaction;

pub(crate) mod describe;
Expand Down Expand Up @@ -100,6 +101,21 @@ impl PgConnection {

Ok(())
}

pub async fn server_version(&mut self) -> Result<String, Error> {
let result = self.fetch_one("SHOW server_version;").await?;
let server_version: String = result.get("server_version");

Ok(server_version)
}

pub async fn server_major_version(&mut self) -> Result<i32, Error> {
let server_version = self.server_version().await?;
let first = server_version.split(".").next().unwrap();
let major_version = first.parse::<i32>().unwrap();

Ok(major_version)
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should actually be receiving this information already when establishing the connection, so we could just save this info in the connection when we receive it and then this can be a simple getter.

It'll be in ParameterStatus messages which the server sends unprompted on startup, and which we currently ignore: https://github.com/launchbadge/sqlx/blob/master/sqlx-core/src/postgres/connection/stream.rs#L107

https://www.postgresql.org/docs/13/protocol-flow.html#PROTOCOL-ASYNC

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice. It looks like this is the approach taken by @AtkinsChang in #1346. Do you want me to backport that into this PR, or wait for @AtkinsChang to clean this approach up in his rebased branch?

Copy link
Collaborator

@abonander abonander Jul 27, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had them rebase on yours already so merging that should merge both.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great. I'll consider this resolved by #1346. Also happy to open another PR after #1346 if we need more cleanup to make sure there is only one (more efficient) way to do things.

}

impl Debug for PgConnection {
Expand Down
18 changes: 18 additions & 0 deletions tests/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@


### Running Tests
SQLx uses docker to run many compatible database systems for integration testing. You'll need to [install docker](https://docs.docker.com/engine/) to run the full suite. You can validate your docker installation with:

$ docker run hello-world

Start the databases with `docker-compose` before running tests:

$ docker-compose up

Run all tests against all supported databases using:

$ ./x.py

If you see test failures, or want to run a more specific set of tests against a specific database, you can specify both the features to be tests and the DATABASE_URL. e.g.

$ DATABASE_URL=mysql://root:password@127.0.0.1:49183/sqlx cargo test --no-default-features --features macros,offline,any,all-types,mysql,runtime-async-std-native-tls
1 change: 1 addition & 0 deletions tests/docker.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import subprocess
import sys
import time
from os import path

Expand Down
21 changes: 16 additions & 5 deletions tests/mysql/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,12 +190,19 @@ async fn with_test_row<'a>(
conn: &'a mut MySqlConnection,
) -> anyhow::Result<Transaction<'a, MySql>> {
let mut transaction = conn.begin().await?;
sqlx::query!("INSERT INTO tweet(id, text, owner_id) VALUES (1, '#sqlx is pretty cool!', 1)")
sqlx::query!("INSERT INTO tweet(text, owner_id) VALUES ('#sqlx is pretty cool!', 1)")
.execute(&mut transaction)
.await?;
Ok(transaction)
}

async fn last_insert_id(conn: &mut MySqlConnection) -> anyhow::Result<MyInt> {
let result = sqlx::query!("SELECT last_insert_id() AS last_insert_id")
.fetch_one(conn)
.await?;
Ok(MyInt(result.last_insert_id as i64))
}

#[derive(PartialEq, Eq, Debug, sqlx::Type)]
#[sqlx(transparent)]
struct MyInt(i64);
Expand All @@ -212,12 +219,13 @@ struct OptionalRecord {
async fn test_column_override_wildcard() -> anyhow::Result<()> {
let mut conn = new::<MySql>().await?;
let mut conn = with_test_row(&mut conn).await?;
let id = last_insert_id(&mut conn).await?;

let record = sqlx::query_as!(Record, "select id as `id: _` from tweet")
.fetch_one(&mut conn)
.await?;

assert_eq!(record.id, MyInt(1));
assert_eq!(record.id, id);

// this syntax is also useful for expressions
let record = sqlx::query_as!(Record, "select * from (select 1 as `id: _`) records")
Expand Down Expand Up @@ -253,12 +261,13 @@ async fn test_column_override_wildcard_not_null() -> anyhow::Result<()> {
async fn test_column_override_wildcard_nullable() -> anyhow::Result<()> {
let mut conn = new::<MySql>().await?;
let mut conn = with_test_row(&mut conn).await?;
let id = last_insert_id(&mut conn).await?;

let record = sqlx::query_as!(OptionalRecord, "select id as `id?: _` from tweet")
.fetch_one(&mut conn)
.await?;

assert_eq!(record.id, Some(MyInt(1)));
assert_eq!(record.id, Some(id));

Ok(())
}
Expand All @@ -267,12 +276,13 @@ async fn test_column_override_wildcard_nullable() -> anyhow::Result<()> {
async fn test_column_override_exact() -> anyhow::Result<()> {
let mut conn = new::<MySql>().await?;
let mut conn = with_test_row(&mut conn).await?;
let id = last_insert_id(&mut conn).await?;

let record = sqlx::query!("select id as `id: MyInt` from tweet")
.fetch_one(&mut conn)
.await?;

assert_eq!(record.id, MyInt(1));
assert_eq!(record.id, id);

// we can also support this syntax for expressions
let record = sqlx::query!("select * from (select 1 as `id: MyInt`) records")
Expand Down Expand Up @@ -308,12 +318,13 @@ async fn test_column_override_exact_not_null() -> anyhow::Result<()> {
async fn test_column_override_exact_nullable() -> anyhow::Result<()> {
let mut conn = new::<MySql>().await?;
let mut conn = with_test_row(&mut conn).await?;
let id = last_insert_id(&mut conn).await?;

let record = sqlx::query!("select id as `id?: MyInt` from tweet")
.fetch_one(&mut conn)
.await?;

assert_eq!(record.id, Some(MyInt(1)));
assert_eq!(record.id, Some(id));

Ok(())
}
Expand Down
44 changes: 16 additions & 28 deletions tests/postgres/postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -968,6 +968,12 @@ async fn test_listener_cleanup() -> anyhow::Result<()> {

#[sqlx_macros::test]
async fn it_supports_domain_types_in_composite_domain_types() -> anyhow::Result<()> {
// Only supported in Postgres 11+
let mut conn = new::<Postgres>().await?;
if !(conn.server_major_version().await? >= 11) {
return Ok(());
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct MonthId(i16);

Expand Down Expand Up @@ -1040,40 +1046,22 @@ async fn it_supports_domain_types_in_composite_domain_types() -> anyhow::Result<
}
}

let mut conn = new::<Postgres>().await?;

{
let result = sqlx::query("DELETE FROM heating_bills;")
.execute(&mut conn)
.await;

let result = result.unwrap();
assert_eq!(result.rows_affected(), 1);
}

{
let result = sqlx::query(
"INSERT INTO heating_bills(month, cost) VALUES($1::winter_year_month, 100);",
)
.bind(WinterYearMonth {
year: 2021,
month: MonthId(1),
})
// Ensure the table is empty to begin to avoid CPK violations from repeat runs
sqlx::query("DELETE FROM heating_bills;")
.execute(&mut conn)
.await;

let result = result.unwrap();
assert_eq!(result.rows_affected(), 1);
}

{
let result = sqlx::query("DELETE FROM heating_bills;")
let result =
sqlx::query("INSERT INTO heating_bills(month, cost) VALUES($1::winter_year_month, 100);")
.bind(WinterYearMonth {
year: 2021,
month: MonthId(1),
})
.execute(&mut conn)
.await;

let result = result.unwrap();
assert_eq!(result.rows_affected(), 1);
}
let result = result.unwrap();
assert_eq!(result.rows_affected(), 1);

Ok(())
}
2 changes: 1 addition & 1 deletion tests/postgres/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ test_type!(ipnetwork_vec<Vec<sqlx::types::ipnetwork::IpNetwork>>(Postgres,

#[cfg(feature = "mac_address")]
test_type!(mac_address_vec<Vec<sqlx::types::mac_address::MacAddress>>(Postgres,
"'{01:02:03:04:05:06,FF:FF:FF:FF:FF:FF}'::inet[]"
"'{01:02:03:04:05:06,FF:FF:FF:FF:FF:FF}'::macaddr[]"
== vec![
"01:02:03:04:05:06".parse::<sqlx::types::mac_address::MacAddress>().unwrap(),
"FF:FF:FF:FF:FF:FF".parse::<sqlx::types::mac_address::MacAddress>().unwrap()
Expand Down
Binary file modified tests/sqlite/sqlite.db
Binary file not shown.
12 changes: 8 additions & 4 deletions tests/x.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,6 @@ def run(command, comment=None, env=None, service=None, tag=None, args=None, data
# check
#

run("cargo c", comment="check with a default set of features", tag="check")

run(
"cargo c --no-default-features --features runtime-async-std-native-tls,all-databases,all-types,offline,macros",
comment="check with async-std",
Expand All @@ -113,9 +111,9 @@ def run(command, comment=None, env=None, service=None, tag=None, args=None, data
#

run(
"cargo test --manifest-path sqlx-core/Cargo.toml --features all-databases,all-types",
"cargo test --no-default-features --manifest-path sqlx-core/Cargo.toml --features all-databases,all-types,runtime-async-std-native-tls",
comment="unit test core",
tag="unit"
tag="unit_async_std"
)

run(
Expand All @@ -124,6 +122,12 @@ def run(command, comment=None, env=None, service=None, tag=None, args=None, data
tag="unit_tokio"
)

run(
"cargo test --no-default-features --manifest-path sqlx-core/Cargo.toml --features all-databases,all-types,runtime-actix-native-tls",
comment="unit test core",
tag="unit_actix"
)

#
# integration tests
#
Expand Down