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

connect_with_connection_string borrows Environment preventing you from moving instances to a higher scope #77

Open
ZerothLaw opened this issue Jun 28, 2018 · 2 comments
Labels

Comments

@ZerothLaw
Copy link

ZerothLaw commented Jun 28, 2018

Consider this code:

pub fn create_connection<'env>(config: &UpgradeConfig) ->Result<(Connection<'env>, Environment<Version3>)> {
    let conn_str = build_connection_string(&config);
    let env = create_environment_v3().map_err(|e| e.unwrap()).unwrap();
    let conn = env.connect_with_connection_string(&conn_str);
    (conn, env)
}

Because Connection is created within the scope of the method from a borrowed self, the original env reference is no longer valid, at least until conn is dropped. This means you can't move Connection out of that scope and can only go into inner scopes. This isn't necessarily ideal, as you can't even assign env/conn to struct fields.

I would suggest instead doing Connection::from_connection_string(&conn_str, &env). Env would only be borrowed for that scope of the method unless you borrow a field from Env for Conn.

@ZerothLaw ZerothLaw changed the title connection_with_connection_string borrows Environment preventing you from moving instances to a higher scope connect_with_connection_string borrows Environment preventing you from moving instances to a higher scope Jun 28, 2018
@ZerothLaw
Copy link
Author

Looking closer at the source code, I notice that inside Environment/mod.rs the as_safe call creates a borrowed reference to an inner field of Environment.

Link here: https://github.com/Koka/odbc-rs/blob/master/src/environment/mod.rs#L60

Is there any way as_safe can be improved to prevent permanent borrowing of Environment?

@Koka
Copy link
Owner

Koka commented Jun 29, 2018

@ZerothLaw Thanks for your question. I'm not sure if I understand it correctly, but just to be on the same wave I need to mention that you supposed to have only one Env instance per your whole application (perhaps inside lazy_static or something). According to ODBC spec you shouldn't allocate more than one environment handle (which exactly what create_environment_v3() does). So it's better not to call this method on every connection creation.

You can see a very simple example of multiple connections handling in r2d2-odbc crate - maybe it's source code will somehow help you with yours implementation.

@Koka Koka added the question label Jun 29, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants