291 points · by steveklabnik · 10y ago · 162 comments
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.
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.
A "proper" solution to this problem requires language changes (as Microsoft did with C# 3.0).
For example, ActiveRecord doesn't have support for window functions, but its underlying AST (a library called ARel) allows you to extend it, which at one point I did, allowing me to write something like this:
things = Arel::Table.new('things')
things.project(Arel::Nodes::NamedFunction.new(:sum, [things.count]).over('my_window')).
window('my_window').
order(things[:name]).
range(Arel::Nodes::Preceding.new)
which generates something like: select sum(count(*)) over my_window
from things
window my_window as (order by name rows unbounded preceding)
(It's been a while since I looked at this particular code, which is no longer in production use, so it might not be correct.)In other words, I could continue to express whatever I wanted of SQL, at the language level — no type mismatches.
The SQL builder code isn't pretty, to be sure, but it's something you typically encapsulate into a lower-level module rather than writing in application code. And as it's highly analogous to the SQL code it generates, it's not like it's that much more complicated. (ARel isn't a shining example of how to do it right, either. I expect Diesel implements the AST aspect more cleanly.)
Edit: I see what you're saying about typed record types. I was thinking more about the grammar, not the shape of the data.
The main reasons I like this approach are:
* it makes way easier (and safer) to reuse query parts compared to string composition/interpolation
* the ORM takes care of differences between the backends, so it is easier if I have to port the application to another RDBMS.
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.
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.
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. ;)
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.
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.)
Diesel 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?Long version: 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
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.
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
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.
Example:
var posts = connection.Query<Post>("select * from posts where user_id = @UserId", param: new { UserId = 1 });Are you sure? Why do you say that?
[1]: http://www.meetup.com/Rust-Bay-Area/events/219697075/
[2]: https://air.mozilla.org/bay-area-rust-meetup-february-2016/
It makes heavy usage of Rust's type system features, particularly zero-sized types, to provide a large degree of safety with no overhead. Sean has mentioned several times that he even believes that he is faster than literal SQL strings, due to pre-compiling them in some way, but that's a bit out of my league.
He also wants to have features like "type-check all of your queries at compile time and then query the database to make sure that the schemas all line up" and other such compile-time safety shenanigans.
Wouldn't waiting on the network eat up any possible performance gain you could expect from Rust vs something like the JVM or Go runtime? Before modern day JavaScript JITs, relational database systems were the epitome of dynamic runtime systems. There's so much performance variability in the query planner, network, disk caching, etc, to make garbage collection a rounding error. Zero-cost abstractions are just not a particularly useful thing in this context from what I can tell.
Even if you do have genuinely CPU-bound tasks, why wouldn't you use Rust for those modules + call it via FFI from whatever is doing most of the boring business logic? If it's just about static-type-check-all-the-things! I just can't get excited about it vs something like Go.
Long version: http://bikeshed.fm/49
So if Rust is not substantially easier or harder than Go, when Rust catches up to Go in the library ecosystem, I can see why people might want to use Rust. Also, it's nice to have better language support for functional strategies.
I didn't pick up Rust as quickly as Go. However, that's not really surprising, because Go is approximately the lowest common dominator of modern statically typed languages minus generics. (In a good and bad way.)
At any rate, I started learning Rust ~2 weeks ago and I am already writing small libraries, programs, etc. for my daily work.
Although that took a bit more time than Go, it's also a much more pleasing language to write in (the lack or sum types or generics in Go is very annoying) and you get more safety guarantees.
https://crates.io/crates/postgres/
https://crates.io/crates/mysql/
This is an experimental approach. It might or might not be useful, but you don't have to use it.
It seems like the intersection of good use case for Rust and need to use SQL, will also intersect with "minimal SQL needs", hence preference for simpler libraries.
Think about JavaScript and Node.js. Who would have predicted that?
In fact, that's behind: strong memory safety, Option/no-null (probably lumps in with "strong memory safety") and of course generics and the type system at large.
The speed is honestly a nice benefit. (I'm not being sassy, I don't have speed intensive applications and still reach for Rust).
It's also a pain in the ass to register because you have to have a Serbian tax ID
There is an Italian clothing company "Diesel S.p.A." that tries to protect their brand by suing almost anyone using "Diesel".
For example a German video game called "DieselStormers": due to a successful trademark lawsuit by Diesel S.p.A., who owns the trademark "Diesel" in relation to video games, Black Forest Games had been required to drop the title DieselStormers. http://www.eurogamer.net/articles/2015-09-30-dieselstormers-...
Such greedy companies act very similar to patent trolls. Well, there are sadly several other common words that are tainted by such "brands".
Edit: In 2015/2016 the Volkswagen (VW) Diesel scandal tainted the "Diesel" name too: http://autoweek.com/car-news/vw-diesel-scandal
// application.css:529
body {
-webkit-font-feature-settings: "kern", "liga", "pnum";
-ms-font-feature-settings: "kern", "liga", "pnum";
font-feature-settings: "kern", "liga", "pnum";
// ...
}I'd rather use template string generated promises in node, tbh, than any ORM.
This is one of the shortcomings of ActiveRecord. The SQL building used to be extremely ad-hoc, and though ARel was eventually written to fix this problem, the integration between ARel and ActiveRecord is not very fluid (and ARel itself has some design issues; if I remember correctly from the last time I worked with it, it's not immutable, which can be very confusing when chaining expressions).
Also random fun story about Arel not being immutable. We had a bug in 4.1 where basically PG bind params are ordered, but Relation can't actually know the order ahead of time (e.g. because a Relation can be used in a from clause). Turned out actually fixing it was somewhat hard (the "real" fix was eventually https://github.com/rails/arel/commit/590c784a30b13153667f8db...). But as a hack, basically someone took advantage of the fact that `Arel::Nodes::BindParam < SqlLiteral` and `SqlLiteral < String`, and Strings are mutable. So they just ignored the lack of a proper map function, and fiddled with the strings. >_>
Anyway, yeah our AST is fun because Rust's compiler lets us set it up so that we can walk it as many times as we need basically for free (because it gets monomorphised and the walking ultimately gets inlined and optimized away)
I couldn't figure out from cursory reading how "PgConnection" works or how it would be compatible with other IO-related code.
I'm thinking of question such as :
-embedded http server vs using apache or nginx ( eg : node and go seem to favor not using third party servers at least for simple cases)
- prefered concurrency model ? ( async vs thread based vs coroutines vs...)
- deployment issues ? ( single binary with everything inside, vs parts that need to be predeployed on the server beforehand)
- third-party connectivity ? ( diesel seems like a really fantastic way to query a db, but what about other storage such as s3, mongo, redis, queue systems, etc)
- current frameworks status ?
I know it sounds like a lot, but as ORMs is usually the major pain point for me when looking at a new techno ( it's one of the main reason i'm not using go, for example) and now that diesel seems to answer all my needs, i'm REALLY looking forward to start using Rust. I just need those questions to be answered, and i think i'm not the only one.
It would be really cool if this had an easy integration with postgis that uses simple syntax to query location
When I'm using a node framework and using postgres I have to use a nosql db for playing with coordinates as postgis syntax is not something i am very fond of
If you're interested in adding postgis support, ping me in our Gitter room. I'd be happy to help.
Generally we're designed for the idea that you'll have a separate struct for read, create, and update. We also try and design for the latter two mapping roughly to web forms, as this is how most large applications end up wanting to be structured from my experience.
The main thing I'm trying to avoid is lumping all your logic in a single place, and ending up in many of the same rabbit holes that Active Record has led us to (which is at least partially my fault)
Also, what about upsert?
Correct. Sorry, I should have been clearer in my last comment. The reason you'd want a separate type for insert is because wrapping your id in an `Option` would be painful for anything except insert.
> but my first thought is of how much boiler plate will result.
Yeah, if you're coming from Active Record (which is the other project I maintain), we'll probably seem a little bit verbose. My goal here is to be 80% as nice to get started with, but nudge users towards significantly more maintainable code as their product grows.
> I would guess most record types will be very similar between create, update, and retrieve.
Early on, yes. 2 years in, not so much.
> Also, what about upsert?
This is something I'd like to add support for in the future. This comment made me realize I didn't have a tracking issue, so here it is: https://github.com/sgrif/diesel/issues/196
Edit: let's paraphrase - how excessive safety nets for construction workers makes buildings more safe?
A strong-typed language without implicit coersions is not more "unsafe".
Baning heterogeneous containers and conditionals, maybe-wrapping of everything to be able to check some constraints at compile time and catch simple errors (which also would be caught in a strong-typed language at run time) does not quality for this "safe" meme.