6 ms·
Why is Post::belonging_to(user).load(&connection) an improvement over SELECT * FROM posts WHERE user_id = 1; ? If you use this, it nails the databa
by Animats 11y ago
Why is
Post::belonging_to(user).load(&connection)
an improvement over
SELECT * FROM posts WHERE user_id = 1;
?
If you use this, it nails the database schema into your Rust code, because this needs to know the table formats. If someone adds a new field to a row, you have to rebuild all your Rust programs that use the database. Now your deployment process just got much more complicated.
It's a neat hack, but seems an overly complex way to do something that's not that complicated. Unless this has some huge performance gain over rust-postgres[1],
it's probably too much.
If rust-postgres is too slow, it would be worth having an optional generic for rust-postgres to help with unmarshalling returned rows. Rust-postgres returns row objects from which fields can be extracted. Converting that to a Rust struct is the only operation which needs to go fast.
[1] https://github.com/sfackler/rust-postgres https://github.com/sfackler/rust-postgres
- rabidferret 11y agoIn that very specific example, you are right -- the benefits are pretty minimal (mostly just the deserialization). However, you're actually able to represent the relationship between those two models however you want, but still deal with relationships between types, and not what the exact join clause is. Additionally, SQL is extremely hard to compose. In my applications, I very rarely have some specific one off query that I want to run, I have multiple predicates that I want to be able to mix and match easily. String munging is fragile, while this actually lets me build reasonable domain abstractions. To your final point "Unless this has some huge performance gain over rust-postgres" Diesel performs 33% faster than rust-postgres, and will be competitive with if not faster than ideomatic C.
- BinaryIdiot 11y ago> Additionally, SQL is extremely hard to compose. I've seen almost everyone who doesn't use SQL directly say this but I always feel it's the exact opposite. SQL is easy to write once you do it enough. I've gotten to the point where I compose zero SQL in any application's code and, instead, do it all inside of stored procedures (of which they do not generate dynamic SQL). Then my code just calls stored procedures, my database users for the web application never have more access than executing a specific subset of stored procedures, and if there is a bug found in a stored procedure I can deploy them separately from the web application. I'm guessing it's just different philosophies but almost every time I've used something that abstracts an existing interface to another, completely different interface, I always end up running into major issues.
- DannoHung 11y agoSQL is hard to programatically compose. At the very least, you have to use a Lang/SQL.
- rabidferret 11y agoStored procedures are no more composeable than SQL strings are. Now it's certainly easy to say that I haven't used SQL directly. But I did spend years working that way (though of course this statement shouldn't give you much confidence by itself). Ultimately an ORM can help you to build more maintainable and resilient (to changing market conditions) software than direct SQL. Diesel in particular can catch mistakes that SQL strings cannot. I do understand why a lot of people have reservations about ORMs. I share a lot of them. I've maintained Active Record for about 2 years now, and learned a lot from doing so (note: This does not mean that I like AR or want this to be anything like it). TL;DR: Your points aren't wrong. Diesel is different. Maybe give it a shot. ;)
- BinaryIdiot 11y ago> Stored procedures are no more composeable than SQL strings are[...]Ultimately an ORM can help you to build more maintainable and resilient (to changing market conditions) software than direct SQL. I couldn't disagree more. Creating the separation between SQL DB and web application allows you to maintain, deploy, fix and upgrade things independently and it's easy (maybe not quite as easy as an ORM would make it but not really harder either; you're going to have to know how SQL works anyway if you want to effectively optimize and secure your data). Not only that but you can provide far better security controls because you can limit certain users access to certain procedures, never direct access to tables and various other things and if you don't do any dynamic SQL in the procedures itself you not only never have to worry about SQL injection but unless there is a critical vulnerability in the SQL system itself it's going to be impossible to conduct an injection attack. Yeah you can separate your code to make it easier to deploy separately to get a similar benefit and yeah your code can prevent SQL injections too but it's so much more work, more possible points of failure and the differences between databases can really bite you in the ass when you do everything generically. SQL is fun :) > TL;DR: Your points aren't wrong. Diesel is different. Maybe give it a shot. ;) Yeah I'm not saying NEVER use ORMs; they're great for creating things quickly that don't need to scale. But after my experience with them I'm highly skeptical using them outside of that type of use case. Of course you can scale ORMs but I've never seen it done well.
- Ygg2 11y agoDiesel performs 33% faster than rust-postgres, and will be competitive with if not faster than ideomatic C. Interesting. What makes it faster than rust-postgress?
- rabidferret 11y agoShort version: Our compile time guarantees allow us to omit a lot of runtime checks that you would otherwise have. Long version: http://bikeshed.fm/49 http://bikeshed.fm/49 Longer version: Planning on doing a really in depth write up for the website soon. I'll also be going into more detail during my talk at the SF rust meetup, which there's a link to the live stream towards the bottom of the thread
- Ygg2 11y agoI'm interested if some of those guarantees can be used upstream in rust-postgres? As far as I saw, Diesel is essentially shipping with its own PostgreSQL driver.
- rabidferret 11y agoIt's possible. I tried to build on rust-postgres originally, but its design basically makes it impossible to abstract over. We also have fundamentally different views on how `ToSql` should work.
- Ygg2 11y agoI'd love to find out what made it impossible to abstract over? Please include in your larger talk!
- rabidferret 11y agoThe short version is its refusal to box things means that you have to have the connection, the statement, and the cursor all as local variables in the same lexical scope (you almost always want to abstract away the statement and cursor), and it's use of trait objects for serialization and deserialization. I might go into it briefly in my talk, but I don't like to rag on other people's work so I probably won't say much on it. (Sorry for the double post, I think I replied to my own comment and not yours!)
- gleb 11y agoI think somebody needs to actually justify the need for composable SQL. With examples. It's far from obvious. In my experience outside of extension code the need for composable SQL is very limited. Most uses cases can be satisfied by Rails 2 scopes. Now, if composability was free - sure it's great. But it's not free. So, on one hand: * it would be nice to have infinitely composable SQL On the other hand: * it would be nice to just have the actual SQL with all the features, well understood syntax and semantics that cost decades and billions of dollars to develop * and no wrapper-on-top-of-SQL limitations and translation bugs, and need for training With these language-on-top-of-SQL you don't get both. In fact you get severe compromises in the second group.
- rabidferret 11y agoRails 2 scopes are literally the case for composeability...
- gleb 11y agoYes, but a very limited one. I'd love to see a solution with tradeoffs made the other way: * syntax and semantics 99% like underlying SQL * support for 99% of underlying DB functionality * traditional areas where ORMs add value: * deserialization into convenient data structures * casting, quoting and escaping on the way in and out * using stored association metadata for concise joins in the query
- rabidferret 11y agoEvery single one of those bullet points is a primary design goal of Diesel (caveat: Our semantics generally map to PG, because they apply well to other backends and are the least nonsensical)
- barrkel 11y agoUser-generated data in a user-defined schema, where the user wants an Excel-autofilter-like sorting and filtering experience over rowsets that range from 10 thousand to 3 million rows, and 2 columns to 150 columns. Columns may be sorted and filtered individually or in combination. Filters may be based on value set membership or range criteria, comparisons with fields in the data or via a join to other tables, or based on the presence of an entry in a join table (think: tags or labels, and you want to filter by presence or absence of tag). (This is what I spent the past couple of months implementing. The simplest way of composing SQL is via union / except / intersect, but it's also the worst performing; doesn't work great past a few hundred thousand rows. And you still need to compose together the filter conditions into a where clause.)
- foota 11y agoFor one thing, I believe SELECT * is generally considered harmful (I certainly view it as such), and without wildcard you would need to update the query regardless of the method you use to construct it.
- rabidferret 11y agoYeah, I've been wondering if I should note somewhere in the examples that we don't actually execute `SELECT *`, we do something more reliable. I felt like listing every column would bury the lede though.
- foota 11y agoSorry, I wasn't at all criticizing the example, I was replying to the parent poster. Your library looks awesome :)
- rabidferret 11y agoOh I know, I didn't think you were. Just stating a random thought I've had about the examples on the site. XD
- pbreit 11y agoI generally agree. Are there frameworks or db access libraries that just offer some helpers around plain ole SQL? Seems like very framework/ORM invents it's own query DSL.
- bluejekyll 11y agoIn Java I really liked MyBatis for this, and I think fits what you are asking.
- mking1024 11y agoIn the .NET world we have Dapper (https://github.com/StackExchange/dapper-dot-net https://github.com/StackExchange/dapper-dot-net), which lets us write queries in plain old SQL. It's a very useful little library. I believe StackOverflow use it for their data access. Example: var posts = connection.Query<Post>("select * from posts where user_id = @UserId", param: new { UserId = 1 });
- arethuza 11y agoI really like Dapper - allows you to write "raw" SQL but does the tedious bit of mapping to/from objects in a nice way.
- lobster_johnson 11y agoOn its own, the code representation is not an improvement. Where it shines is when you want to compose result sets. For example, in ActiveRecord (the Ruby library that this looks very much influenced by), given: posts = Post.where(user_id: 1) ...you can now do things like: recent_posts = posts.order(created_at: :desc).limit(100) or tagged = recent_posts.where('tag in ?', ['hacker', 'news']) and then you can extract data: tagged.group_by('tag') or do mutate it: tagged.update_attributes({author_id: 2}) or tagged.destroy_all ...And so on. By encapsulating a result set as something that can be augmented with new query clauses (where, limit, select) and so on, you can incrementally build queries, pass them to other functions, store them as member variables so that they be reused as "scopes" across multiple calls, and so on. If the query were just a string, this sort of thing becomes awkward, verbose, brittle, and generally not type-safe.
- u320 11y agoThe problem with this approach is that you are forced to work in a subset of SQL due to the type system mismatch of SQL and the host language. A "proper" solution to this problem requires language changes (as Microsoft did with C# 3.0).
- rabidferret 11y agoYou should take a closer look at what Diesel is doing with it's query builder. We actually do attempt to support the full power of every supported backend (of course there's still holes which need to be filled), with proper type guarantees which map to the semantics of Postgres. The main difference being that Diesel can check your queries for correctness at compile time.
- u320 11y agoThe problem is that joins and projections give rise to new record types. The only way to support this in a type safe and natural way is if you have anonymous records in the host language, which Rust doesn't. On top of this there is some other metaprogramming stuff that is necessary in order to facilitate the DSL embedding. Look at what Microsoft did with LINQ. You can't pull that off in Rust no matter how much you want to.
- sixbrx 11y agoWell for one thing the "SELECT *" query will typically yield for results a runtime-typed flat list of fields/values as accessed via a generic database access api. Whereas as an applications programmer I'd rather deal with structures that make sense in my domain of interest, and let the marshalling code from SQL results be handled for me, and with compile-time checking for correctness. When that's coupled with a database schema reverse engineering tool (not sure if this project provides one), that way whenever the database changes, compile errors will result, which errors allow me to quickly hunt down places in my code that are affected and need changing.
- Pxtl 11y agoIf you change your schema without changing your client code, your program is broken - you just haven't found out about it yet. The fact that changing schema becomes a compile-time error with an ORM is a feature, not a bug.
- jeffdavis 11y ago"If someone adds a new field to a row, you have to rebuild all your Rust programs that use the database." Are you sure? Why do you say that?
- Animats 11y agoRead the Diesel build process, especially the section on "migrations".[1] [1] http://diesel.rs/guides/getting-started/ http://diesel.rs/guides/getting-started/
- rabidferret 11y agoThis isn't true at all. You can add as many fields as you want. You'll need to recompile to use them, of course.
- daniel-levin 11y ago>> it nails the database schema into your Rust code On the contrary, the purpose of an ORM is to let your code be a schema for your database. This is my personal use case for an ORM; I want persistence but am not overly concerned with the database. There are plenty of use cases [1] where a schema update from outside is unlikely or impossible. In these cases, there is a very low cost for (by way of an ORM) tightly coupling your code to your schema. Also, an ORM lets somebody else worry about sanitisation, and database specific-code. It can abstract away the choice of database, another very valuable feature. I think that the example you quote is actually a poor demonstration of the value of an ORM. The other ones on the linked page are far better :) [1] A program running on only one machine, like an Android app or a music player on Linux desktops etc
- vpkaihla 11y agoPerhaps the question should be rather: Why is Post::belonging_to(usre).load(&connection) an improvement over SELECT * FROM posts WHERE usre_id = 1; ? ... to which the answer is probably more obvious.
- rabidferret 11y agoHah I love this answer. ^_^