Domanda

I suppose this isn't a particularly "good fit for our Q&A format" but no idea where else to ask it.

Why is SQL-querying text based? Is there a historical motivation, or just laziness?

mysqli_query("SELECT * FROM users WHERE Name=$name");

It opens up an incredible number of stupid mistakes like above, encouraging SQL injection. It's basically exec for SQL, and exec'ing code, especially dynamically generated, is widely discouraged. Plus, to be honest, prepared statements seem like just a verbose workaround.

Why don't we have a more object-oriented, noninjectable way of doing it, like having a directly-accessible database object with certain methods:

$DB->setDB("mysite");
$table='users';
$col='username';
$DB->selectWhereEquals($table,$col,$name);

Which the database itself natively implements, completely eliminating all resemblance to exec and nullifying the entire basis of SQL injection.

Culminating in the real question, is there any database framework that does anything like this?

È stato utile?

Soluzione

Why are programming languages text-based? Quite simply: because text can be used to represent powerful human-readable/editable DSLs (Domain-specific language), such as SQL.

The better (?) question is: Why do programmers refuse to use placeholders?

Modern database providers (e.g. ADO.NET, PDO) support placeholders and an appropriate range of database adapters1. Programmers who fail to take advantage of this support only have themselves to blame.

Besides ubiquitous support for placeholders in direct database providers, there are also many different APIs available including:

  • "Fluent database libraries"; these generally map an AST, such as LINQ, onto a dynamically generated SQL query and take care of the details such as correctly using placeholders.
  • A wide variety of ORMs; may or may not include a fluent API.
  • Primitive CRUD wrappers as found in the Android SQLite API, which looks suspiciously similar to the proposal.

I love the power of SQL and almost none of the queries I write can be expressed in such a trivial API. Even LINQ, which is a powerful provider, can sometimes get in my way (although the prudent use of Views helps).


1 Even though SQL is text-based (and such is used to pass the shape of the query to the back-end), bound data need not be included in-line, which is where the issue of SQL Injection (being able to change the shape of the query) comes in. The database adapter can, and does if it is smart enough, use the API exposed by the target database. In the case of SQL Server this amounts to sending the data separately [via RPC] and for SQLite this means creating and binding separate prepared-statement objects.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top