Sqlbolt has been good so far, just started myself
I'm slowly starting Rust for Rustaceans, and it's already poking holes in my understanding of Rust. Here's a couple initial questions I have:
> A shared reference, &T is , as the name implies, a pointer that may be shared. Any number of references may exist to the same value, and each shared reference is Copy, so you can trivially make more of them
I don't understand why a shared reference has to implement copy. In fact, isn't this not true just by the fact that references work for Strings and Strings size can't be known at compile time?
- I'm having trouble with the idea of assigning a new value to a mutable reference.
let mut x = Box::new(42); *x = 84;
Why in this example, is the assignment dereferenced. Why not just do x=84? is it dereferenced specifically because is Boxed on the heap?
Indeed it does haha, thanks
I'm new to multithreaded programming. How would some other thread create it? Like what's the real-world scenario?
I think I had that in a few attempts, I can't remember why I removed it. Thanks for pointing this out.
I managed to get this working, but there has to be a better way. How else could I write this?
pub async fn insert_or_return_user(
db: &DbConn,
partial_user: Auth0UserPart,
) -> Result {
let user = users::ActiveModel {
email: Set(partial_user.email.to_owned()),
email_verified: Set(partial_user.email_verified.to_owned()),
auth0_sub: Set(partial_user.sub.to_owned()),
..Default::default()
};
let result = user.clone().insert(db).await;
match result {
Ok(u) => {
println!("{u:#?}");
Ok(u.try_into_model().unwrap() as UsersModel)
}
Err(error) => {
let user = Users::find()
.filter(users::Column::Auth0Sub.eq(&partial_user.sub))
.one(db)
.await?;
Ok(user.unwrap() as UsersModel)
}
}
}
in sequelize (javascript) it's pretty straightforward to either find a record, or create it if it doesn't exist. I don't see anything similar with sea-orm. There's a 'save' method that seems to insert or update, but I need to know details about the record ahead of time :/
Any ideas?
https://sequelize.org/docs/v6/core-concepts/model-querying-finders/
🤣
We're a pretty darn good minor league baseball team if you ask me
It should be wrapped in an array, not an object. Then it's valid. The problem was that I was trying to use an enum.
The first post had a couple errors that made things confusing. I have an accurately formatted JSON response, but I still can't seem to deserialize it. ---------
I keep getting an error where the response isn’t matching up as expected: Error("data did not match any variant of untagged enum NationResponse"
I have a JSON response that looks like this:
{ { "id": 1, "country": "usa" }, [ { "id": 1, "age": 37, "name": "John" }, { "id": 2, "age": 21, "name": "Nick" }, ] }
And I’m trying to deserialize it, but I can’t seem to get it right. Isn’t this accurate?
``` #[derive(Deserialize, Debug)] #[serde(untagged)] enum NationResponse { Nation(Nation), People(Vec), }
struct Person { id : i32, age : i32, name : String }
struct Nation { id : i32, country : String } ```
Edit:
The problem I was actually experiencing was trying to use an enum as the response. Yes the formatting for my example was wrong (it should have been an array). But the structure besides that was accurate.
What I needed was Vec>
Yes, that's what I meant, but no I can't edit it :/
I got the response wrong, here's what I'm using that isn't working:
enum NationResponse {
Nation(Nation),
People(Vec),
}
Why the heck can't I edit the original post after a comment is made?
Oh man, I didn't know debug_handler existed. Sure enough I had a missing derived attribute... not sure how but Serde serialize and deserialize were missing, so when I was trying to return Ok(Json(army)) it was failing. Thanks so much!
Thanks for the reply! I don't know what you mean by extensions, but the state is literally just the DB connection:
struct AppState { conn: DatabaseConnection, }
Not sure what happened exactly... it was working fine and I didn't change anything in this file. It has to be related to something I did recently:
- Ran a migration adding a unique constraint on a table
- Generated two new entities of a couple very basic tables.
The handler I'm using isn't even using the new tables, so I don't know why this randomly broke. Anyone have any ideas? Or even some guidance on how to decipher that obscure error would be helpful.
Async I have a handle on, but I'll take a look at the others for sure.
Nice, thanks... looking into these now.
🤔 I thought lazy_static was deprecated in favor of one_cell
One for now, theoretically many later.
Nice I've never used Rc. Maybe now's my chance to look into it.
I've been trying to use OneCell, but I keep having errors trying to set it up to handle a mutable vector that I can push to.
I know there's going to be some answers telling me maybe not to use a singleton, but the alternative of passing a vector all around throughout my code is not ergonmic at all.
I've tried lots of things, but this is where I'm at right now. Specifically I'm just having trouble initializing it.
`/**
- LOG_CELL
- Stores a vec of Strings that is added to throughout the algorithm with information to report
- To the end user and developer */ pub static LOG_CELL: OnceLock<&mut Vec> = OnceLock::new();
pub fn set_log() { LOG_CELL.set(Vec::new()); }
pub fn push_log(message: String) { if let Some(vec_of_messages) = LOG_CELL.get() { let something = *vec_of_messages; something.push(message); } } `
Also, move out special types to types.rs, error types to errors.rs to keep the area with the actual algorithms more clear.
Ok this is totally something my code base needs. Very actionable feedback.
And yeah that's one of the things I love about rust; it will tell me everywhere things are out of wack. It's such a different experience from back when I had large JavaScript code bases. Make changes and pray lol.
This is really good to hear, I don't think I'm as far off base as I thought; maybe I've been over thinking it a bit. And thanks for that refactoring resource. I'm very big into making my TS code clean and maintainable. I'm just thrown off a bit with the new paradigm.
I've mostly been putting functions, structs enums and tests in the same file and it's starting to feel like a mess... I am constantly losing track of which function is where and I'm never quite sure if I have code in the right place. I know this is kind of vague, but that's been my general feeling while working in my largest personal project so far. It's essentially a large Algorithm that has many smaller steps that needs to run in a sequence.
I think I might just have too many loose functions and maybe I should use more impl methods and traits? I'm also thinking I should try the builder pattern in a few spots.
Anyone have any guidance on code organization in rust?
I know there's mockall which seems to be geared towards implementation methods and traits, but I'm wondering about just structs with non-function properties.
In my tests, I want to define initialized structs with values. It works fine to just do it like I normally would in code, but I'm wondering if there's more to it than that. Like if I have a cat struct:
struct Cat { name : String }
`
#[cfg(test)] pub mod test { use super::Cat; fn test_create_cat() -> Cat { Cat { name. : String::from("Fred") }; }
That's fine, but should I be doing it differently? What about mockall, is it not meant for structs with properties?
for example, I have a file structure that looks like this:
``` action/ attack.rs attack.test.rs mod.rs
```
But this doesn't work in the mod file:
pub mod attack.test;
and neither does:
pub mod "attack.test";
My program is small enough that in TS/JS I'd normally just store the data in some global variable to be access from whatever elsewhere in the app. But with Rust from what I can tell this doesn't seem to be a common practice. How should i handle this?
More specifically, I need to:
- program start, fetch data from my db (DONE)
- store this data somehow somewhere
- access said data (for read only in this use case)
Thanks for any insights here!
Eh , its probably just temporary. People just had apps they've used for 10 years yanked away and it's jaring how it all went down. Of course people are going to want to talk about it.
Have you thought about wiping your comments? I had 1300 (more than I thought I would) and have no regrets.
It's basically the same premise. Link aggregator with a forum attached, where upvoted content rises to the top. She doesn't need to know how instances work in order to use it in the same way that she doesn't need to be a mechanic in order to drive her car.