简体   繁体   中英

Why don't sql databases allow creating functions for all queries vs constructing the sql strings in the calling program?

I'm new to sql and rdbms, and just curious why sql database drivers (eg postgreSQL, mySQL, etc) for languages like python, node, c#, etc, require you to programmatically construct the query strings in the language rather than calling a database function for all queries? Wouldn't it be a better level of abstraction to write all the queries in the database and call those functions from the code?

Why do this (pseudo code):

var query = "select * from " + table_name + ";"

When you could just do something like this:

var rows = dbInstance.getAll(table_name, max_rows, start);

Wouldn't it be less clunky and higher performance if the queries were constructed in the database itself?

There are many libraries that give you a more object-oriented usage of database queries. For example:

These are usually called ORM libraries. ORM means Object-Relational Mapping, because relational databases are not object databases, and these libraries have to fetch rows of data and map them onto collections of objects in your app. And then vice-versa, when you save objects, it maps them into rows of data.

These ORM libaries make your code look nicer, and for certain tasks you may be able to write code more productively, but ORMs don't make queries run any faster in the database. On the contrary, complex ORMs like Hibernate are notorious for translating your code into inefficient SQL, and making the queries have much worse performance.

The queries still run in the database server regardless of how you invoke them. The majority of time is spent in the database, not in your app.

And yet ORM packages fail to support the power of SQL. SQL is a language itself, and it can do things that are very awkward to represent in code like you show, that only uses objects and functions. The example you show of getting all columns for all rows from a single table is fine for an ORM. ORM's generally do well for simple CRUD (create, read, update, delete) code that works with individual rows of a single table, mapping them into collections of objects in your app.

ORM packages that try to simulate a greater variety of SQL queries end up being incredibly difficult to learn and to use. The code for Hibernate is 800,000 lines of Java.

You might also like to read https://hackerfall.com/story/what-orms-have-taught-me-just-learn-sql

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM